forked from kendricktan/ledger-analytics
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathledger-api.js
More file actions
78 lines (63 loc) · 2.42 KB
/
ledger-api.js
File metadata and controls
78 lines (63 loc) · 2.42 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const util = require('util')
const exec = util.promisify(require('child_process').exec)
// TODO: Make this component composable as opposed to passing in multiple args
// Since most of the arguments are redundant anyway
module.exports.getCommodities = async (file, extraArgs = ``) => {
const { stdout } = await exec('ledger commodities -f ' + file + extraArgs)
const commodities = stdout.split('\n').filter(x => x.length > 0)
return commodities
}
// Commodity can be empty
module.exports.getTimelineData = async (file, query, commodity = undefined, byMonth = false, extraArgs = ``) => {
const commodityArg = (commodity !== undefined) ? ` -X ` + commodity : ``
const periodType = byMonth ? '-M' : '-D'
const { stdout } = await exec(`ledger reg -f ` + file + ` ` + query + commodityArg + ` -j ` + periodType + extraArgs + ` --collapse --plot-total-format="%(format_date(date, "%Y-%m-%d")) %(abs(quantity(scrub(display_total))))\n"`)
// Convert datetime format from:
/*
2018-08-17 -63.26
2018-08-18 -2032.85
2018-08-20 -32.36
2018-08-21 -2050.08
to
[
{
date: [2018/08/17, 2018/08/18, 2018/08/20, 2018/08/21],
data: [-63.26 ,-2032.85 ,-32.36 ,-2050.08]
}
]
*/
const timelineData = stdout
.split('\n')
.filter(x => x.length > 0)
.reduce((obj, x) => {
const s = x.split(' ')
const date = s[0].split('-').join('/')
const data = parseFloat(s[1])
return {
date: obj.date.concat([date]),
data: obj.data.concat([data])
}
}, {date: [], data: []})
return timelineData
}
module.exports.getGrowthData = async (file, query, commodity = undefined, extraArgs = ``) => {
const commodityArg = (commodity !== undefined) ? ` -X ` + commodity : ``
const { stdout } = await exec(`ledger reg -f ` + file + ` ` + query + commodityArg + ` -j -M ` + extraArgs + ` --collapse`)
const growth = stdout
.split('\n')
.filter(x => x.length > 0)
.reduce((acc, x) => {
const xSplit = x.split(' ')
const date = xSplit[0].split('-').splice(0, 2).join('/')
const value = parseFloat(xSplit[1])
acc[date] = value
return acc
}, {})
return growth
}
module.exports.getAccounts = async (file, account, extraArgs = ``) => {
const accountArg = account || ''
const { stdout } = await exec(`ledger accounts -f ` + file + ' ' + accountArg + extraArgs)
const accounts = stdout.split('\n').filter(x => x.length > 0)
return accounts
}