git ssb

0+

punkmonk / double



Tree: 7dc6be618d7c0a5cf0b4b2c20a9b317f339d986d

Files: 7dc6be618d7c0a5cf0b4b2c20a9b317f339d986d / stores / ledger.js

1386 bytesRaw
1const Flume = require('flumedb')
2const Reduce = require('flumeview-reduce')
3const FlumeLog = require('flumelog-memory')
4
5function ledger (state, emitter) {
6 state.accounts = {}
7 state.entries = []
8
9 const db = Flume(FlumeLog())
10 .use('entries', Reduce(1, entriesReducer, null, null, state.entries))
11 .use('accounts', Reduce(1, accountReducer, null, null, state.accounts))
12 .use('balances', Reduce(1, accountBalanceReducer, null, null, state.accounts))
13
14 state.db = db
15
16 function onLoad () {
17 emitter.on('accounts', onEvent)
18 emitter.on('entries', onEvent)
19 }
20
21 function onEvent (data) {
22 db.append(data, (err, seq) => {
23 if (err) throw err
24 emitter.emit(state.events.RENDER)
25 })
26 }
27
28 emitter.on('DOMContentLoaded', onLoad)
29}
30
31function accountBalanceReducer (acc, item) {
32 if (item.type !== 'entries') return acc
33 const {msg} = item
34
35 acc[msg.debit].debit += msg.amount
36 acc[msg.credit].credit += msg.amount
37 return acc
38}
39
40function entriesReducer (acc, item) {
41 if (item.type !== 'entries') return acc
42 acc.push(item)
43 return acc
44}
45
46function accountReducer (acc, item) { // TODO account for account creation of existing account
47 if (item.type !== 'accounts') return acc
48 const { msg } = item
49
50 if (!acc[msg.name]) {
51 acc[msg.name] = msg
52 return acc
53 }
54
55 Object.assign(acc[msg.name], msg)
56 return acc
57}
58
59module.exports = ledger
60

Built with git-ssb-web