Files: 8f610eca2bb7c82ab4520dcd17f0816be4901f3b / stores / ledger.js
1713 bytesRaw
1 | const Flume = require('flumedb') |
2 | const Reduce = require('flumeview-reduce') |
3 | const FlumeLog = require('flumelog-offset') |
4 | const { pull, drain } = require('pull-stream') |
5 | const codec = require('flumecodec') |
6 | |
7 | function ledger (state, emitter) { |
8 | state.accounts = {} |
9 | state.entries = [] |
10 | |
11 | const db = Flume(FlumeLog('.test.db', { codec: codec.json })) |
12 | .use('entries', Reduce(1, entriesReducer, null, null, [])) |
13 | .use('accounts', Reduce(1, accountReducer, null, null, {})) |
14 | |
15 | const onDone = () => console.log('DONE') |
16 | |
17 | pull(db.accounts.stream(), drain(acctState => { |
18 | state.accounts = acctState |
19 | emitter.emit.RENDER |
20 | }, onDone)) |
21 | |
22 | pull(db.entries.stream(), drain(entryState => { |
23 | state.entries = entryState |
24 | emitter.emit.RENDER |
25 | }, onDone)) |
26 | |
27 | function onLoad () { |
28 | emitter.on('accounts', onEvent) |
29 | emitter.on('entries', onEvent) |
30 | } |
31 | |
32 | function onEvent (data) { |
33 | db.append(data, (err, seq) => { |
34 | if (err) throw err |
35 | emitter.emit(state.events.RENDER) |
36 | }) |
37 | } |
38 | |
39 | emitter.on('DOMContentLoaded', onLoad) |
40 | |
41 | function entriesReducer (acc, item) { |
42 | if (item.type !== 'entries') return acc |
43 | acc.push(item) |
44 | |
45 | return acc |
46 | } |
47 | |
48 | function accountReducer (acc, item) { // TODO account for account creation of existing account |
49 | if (item.type === 'entries') { |
50 | const { msg } = item |
51 | acc[msg.debit].debit += msg.amount |
52 | acc[msg.credit].credit += msg.amount |
53 | |
54 | return acc |
55 | } |
56 | if (item.type !== 'accounts') return acc |
57 | const { msg } = item |
58 | |
59 | if (!acc[msg.name]) { |
60 | acc[msg.name] = msg |
61 | |
62 | return acc |
63 | } |
64 | |
65 | Object.assign(acc[msg.name], msg) |
66 | Object.assign(state.accounts[msg.name], msg) |
67 | return acc |
68 | } |
69 | } |
70 | |
71 | module.exports = ledger |
72 |
Built with git-ssb-web