Files: 543423934bab207e903927a812ea891b52c1f438 / stores / ledger.js
1549 bytesRaw
1 | const Flume = require('flumedb') |
2 | const Reduce = require('flumeview-reduce') |
3 | const FlumeLog = require('flumelog-memory') |
4 | const {pull, drain} = require('pull-stream') |
5 | |
6 | function 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 | |
35 | function 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 | |
44 | function entriesReducer (acc, item) { |
45 | if (item.type !== 'entries') return acc |
46 | acc.push(item) |
47 | return acc |
48 | } |
49 | |
50 | function 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 | |
63 | module.exports = ledger |
64 |
Built with git-ssb-web