git ssb

0+

punkmonk / double



Tree: e28105f1d92f3398e08fa1cfbf376539f6bc37ba

Files: e28105f1d92f3398e08fa1cfbf376539f6bc37ba / stores / ledger.js

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

Built with git-ssb-web