forked from halloffame/ynab-csv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_object.coffee
64 lines (56 loc) · 2 KB
/
data_object.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
ynab_cols = ['Date','Payee','Category','Memo','Outflow','Inflow']
numberfy = (val) ->
# Convert val into empty string if it is undefined or null
if !val?
val = ''
if isNaN(val)
# check for negative signs or parenthases.
is_negative = if (val.match("-") || val.match(/\(.*\)/)) then -1 else 1
# remove any commas
val = val.replace(/,/g, ".")
# return just the number and make it negative if needed.
+(val.match(/\d+.?\d*/)[0]) * is_negative
else
val
parseDate = (val) -> moment(val,"DD.MM.YY").format('MM/DD/YYYY') if val && val.length > 0
class window.DataObject
constructor: () ->
@base_json = null
parse_csv: (csv) -> @base_json = $.parse(csv)
fields: -> @base_json.results.fields
rows: -> @base_json.results.rows
converted_json: (limit, lookup) ->
return nil if @base_json == null
value = []
if @base_json.results.rows
@base_json.results.rows.forEach (row, index) ->
if !limit || index < limit
tmp_row = {}
ynab_cols.forEach (col) ->
cell = row[lookup[col]]
switch col
when 'Date' then tmp_row[col] = parseDate(cell)
when 'Outflow'
number = numberfy(cell)
if lookup['Outflow'] == lookup['Inflow']
tmp_row[col] = Math.abs(number) if number < 0
else
tmp_row[col] = number
when 'Inflow'
number = numberfy(cell)
if lookup['Outflow'] == lookup['Inflow']
tmp_row[col] = number if number > 0
else
tmp_row[col] = number
else tmp_row[col] = cell
value.push(tmp_row)
value
converted_csv: (limit, lookup) ->
return nil if @base_json == null
string = ynab_cols.join(',') + "\n"
@.converted_json(limit, lookup).forEach (row) ->
row_values = []
ynab_cols.forEach (col) ->
row_values.push row[col]
string += row_values.join(',') + "\n"
string