-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodel.js
More file actions
2544 lines (2123 loc) · 67.1 KB
/
model.js
File metadata and controls
2544 lines (2123 loc) · 67.1 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Core data types for amounts, balances, currencies, etc.
* Inspired by Ledger (http://ledger-cli.org).
* @author jhaberman@gmail.com (Josh Haberman)
* @flow
*/
"use strict";
// $FlowIssue: how to allow this without processing all of node_modules/?
import { RBTree } from 'bintrees';
declare var indexedDB: any;
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
function toMapDate(date) {
return date.toISOString().substr(0, 10);
}
function isArray(val) {
// cf. http://stackoverflow.com/questions/4775722/check-if-object-is-array
return Object.prototype.toString.call(val) === '[object Array]';
}
function arrayFrom(iter) {
var ret = [];
while (1) {
var v = iter.next();
if (v.done) {
return ret;
}
ret.push(v.value);
}
}
function merge(obj1, obj2) {
var ret = {};
for (var attrname in obj1) { ret[attrname] = obj1[attrname]; }
for (var attrname in obj2) { ret[attrname] = obj2[attrname]; }
return ret;
}
function toposort(nodes) {
var cursor = nodes.length;
var sorted = new Array(cursor);
var visited = {};
var i = cursor;
var byGuid = {};
nodes.forEach((node) => { byGuid[node.guid] = node });
while (i--) {
if (!visited[i]) visit(nodes[i], i, [])
}
return sorted
function visit(node, i, predecessors) {
if(predecessors.indexOf(node) >= 0) {
throw new Error('Cyclic dependency: '+JSON.stringify(node))
}
if (visited[i]) return;
visited[i] = true
// outgoing edges
var outgoing = node.parent_guid ? [byGuid[node.parent_guid]] : []
if (i = outgoing.length) {
var preds = predecessors.concat(node)
do {
var child = outgoing[--i]
visit(child, nodes.indexOf(child), preds)
} while (i)
}
sorted[--cursor] = node
}
}
function rootForType(type) {
if (type == "ASSET" || type == "LIABILITY") {
return "REAL_ROOT";
} else if (type == "INCOME" || type == "EXPENSE") {
return "NOMINAL_ROOT";
} else {
throw "Unexpected account type " + type;
}
}
/**
* An ES6-compatible iterator for SortedMap.
*/
class SortedMapIterator<K, V> {
rbIter: any; // The underlying RBTree iterator.
nextFunc: string; // "next" or "prev" -- which function to call for the next item.
done: boolean; // Whether we have reached EOF.
constructor(rbIter: any, nextFunc: string) {
this.rbIter = rbIter;
this.nextFunc = nextFunc;
this.done = false;
}
// $FlowIssue: Computed property keys not supported.
[Symbol.iterator]() { return this; }
// $FlowIssue: It doesn't like what's going on here.
next() {
let item = this.rbIter.data();
if (item) {
let ret = {
value: item,
done: false
};
this.rbIter[this.nextFunc]();
return ret;
} else {
return {
done: true
}
}
}
}
/** SortedMap *****************************************************************/
/**
* Sorted K -> V map.
* Sorts using built-in "<" operator over K.
*/
class SortedMap<K, V> {
tree: RBTree;
size: number;
constructor() {
this.tree = new RBTree(SortedMap._compare);
// $FlowIssue: 'Property not found in object literal'
Object.defineProperty(this, "size", {
"get": function() { return this.tree.size; }
});
}
static _compare(e1, e2) {
var k1 = e1[0];
var k2 = e2[0];
if (k1 < k2) {
return -1;
} else if (k2 < k1) {
return 1;
} else {
return 0;
}
}
/**
* Sets the given key/value pair in the map, throwing an error if this key
* is already in the map.
*/
add(key: K, val: V) {
var ok = this.tree.insert([key, val]);
if (!ok) {
throw "Key was already present.";
}
}
/**
* Sets the given key/value pair in the map, overwriting any previous value
* for "key".
*/
set(key: K, val: V) {
this.tree.remove([key, null]);
this.tree.insert([key, val]);
}
/**
* Removes the given key from the map, if present.
* for "key".
*/
delete(key: K) {
this.tree.remove([key, null]);
}
/**
* Returns true if the given key is in the map.
*/
has(key: K): boolean {
return this.tree.find([key, null]) != null;
}
/**
* Returns the value for this key if it exists, otherwise null.
*/
get(key: K): ?V {
var val = this.tree.find([key, null]);
return val ? val[1] : null;
}
/**
* Returns an iterator over the map's entries, in key order.
* If a key is provided, iteration starts at or immediately
* after this key.
*/
iterator(key: ?K): SortedMapIterator<K, V> {
if (key) {
return new SortedMapIterator(this.tree.lowerBound([key, null]), "next");
} else {
let iter = this.tree.iterator();
iter.next(); // Advance from null iterator to one pointing at first elem.
return new SortedMapIterator(iter, "next");
}
}
/**
* Returns an iterator over the map's entries, in reverse key order.
* If a key is provided, iteration starts immediately before this key.
*/
riterator(key: ?K): SortedMapIterator<K, V> {
if (key) {
let iter = new SortedMapIterator(this.tree.iterator(), "prev");
iter.next(); // Skip element after this key.
return iter;
} else {
let iter = this.tree.iterator();
iter.prev(); // Advance from null iterator to one pointing at last elem.
return new SortedMapIterator(iter, "prev");
}
}
}
/** IntervalMap ***************************************************************/
/**
* Map of closed intervals [K, K] -> V.
* Supports intersection queries.
* Sorts keys using built-in "<" operator over K.
*
* This uses naive linear search right now, but with more work could be made
* cheaper.
*
* At the moment, values must be unique. We may want to revisit this later.
*/
class IntervalMap<K, V> {
members: Map<V, [K, K]>;
constructor() {
this.members = new Map();
// $FlowIssue: 'Property not found in object literal'
Object.defineProperty(this, "size", {
"get": function() { return this.members.size; }
});
}
/**
* Sets the given key/value pair in the map, throwing an error if this key
* is already in the map.
*/
add(low: K, high: K, val: V) {
if (this.members.has(val)) {
throw "Value was already present.";
}
this.members.set(val, [low, high]);
if (this.members.size > 1000) {
throw "Whoa, whoa";
}
}
/**
* Removes the given key from the map, if present.
* for "key".
*/
delete(val: V) {
this.members.delete(val);
}
/**
* Returns any entries that overlap this key.
*/
get(key: K): [V] {
let results = []
for (let [v, [low, high]] of this.members.entries()) {
// $FlowIssue: says "low" and "high" are of type "K." (note the dot).
if (key >= low && key <= high) {
results.push(v);
}
}
return results;
}
values(): Iterator<V> { return this.members.keys(); }
}
/** Decimal ***********************************************************/
/**
* Class for representing decimal numbers losslessly (unlike binary floating
* point). Takes inspiration from the "decimal" module from the Python standard
* library.
*
* For now we don't support mixed precision (ie. "10.1" + "10.23") because we
* assume that all amounts for a given currency will use the precision of that
* currency. We can revisit this later if required.
*/
class Decimal {
// The value is: value * 10^precision.
value: number;
precision: number;
/**
* Constructs a Decimal instance from decimal string.
*
* @param {String} value The decimal string (ie. "123.45"). The number of
* significant digits is noted, so "123.45" is different than "123.450".
*/
constructor(value: string) {
let isNegative = false;
if (value.charAt(0) == "-") {
isNegative = true;
value = value.slice(1);
}
let firstDecimal = value.indexOf(".");
if (firstDecimal != value.lastIndexOf(".")) {
throw "Value had more than one decimal point";
}
if (firstDecimal == -1) {
this.precision = 0;
} else {
this.precision = value.length - firstDecimal - 1;
}
this.value = parseInt(value.replace(/\./, ''));
if (isNegative) { this.value = -this.value; }
}
/**
* Adds the given Decimal to this one. They must have the same precision.
* @param {Decimal} other The number to add to this one.
*/
add(other) {
if (this.precision != other.precision) {
throw "Precisions must be the same."
}
this.value += other.value;
}
dup() {
let ret = new Decimal("0");
ret.value = this.value;
ret.precision = this.precision;
return ret;
}
/**
* Subtracts the given Decimal from this one.
* @param {Decimal} other The number to subtract from this one.
*/
sub(other) {
if (this.precision != other.precision) {
throw "Precisions must be the same."
}
this.value -= other.value;
}
/**
* Returns true iff the value is zero.
*/
isZero() {
return this.value == 0;
}
/**
* Returns a new value that has the value zero, but with this instance's
* precision.
*/
newZero() {
let ret = new Decimal("0");
ret.precision = this.precision;
return ret;
}
/**
* Converts the Decimal object to a string, retaining all significant digits.
* @return {String} The string representation.
*/
toString() {
return (this.value / Math.pow(10, this.precision)).toFixed(this.precision);
}
}
/** Amount ********************************************************************/
/**
* Class for representing an amount of money in one or more currencies.
* Contains a set of decimal balances and their associated commodities
* (currencies).
*
* This can be directly converted to/from the Amount type in model.proto.
*/
export class Amount {
commodities: Map<string, Decimal>;
// This is a map that parallels this.commodities, but collapses all lots
// into a single value that represents the entire currency. Created lazily
// on-demand.
collapsed: ?Map<string, Decimal>;
/**
* Constructs a new Amount.
*
* @param{Amount || null} amount The Amount (from Amount.proto) to construct
* from.
*/
constructor(amount: ?Object) {
this.commodities = new Map();
this.collapsed = undefined;
if (amount) {
for (let commodity of Object.keys(amount)) {
this.commodities.set(commodity, new Decimal(amount[commodity]));
}
}
}
dup(): Amount {
let ret = new Amount();
for (let [commodity, value] of this.commodities.entries()) {
ret.commodities.set(commodity, value.dup());
}
// TODO: copy collapsed
return ret;
}
/**
* Returns a plan JavaScript object for storing this Amount that follows the
* Amount schema in model.proto.
*/
toModel(): Object {
let ret = {}
for (let [commodity, decimal] of this.commodities) {
ret[commodity] = decimal.toString();
}
return ret;
}
_apply(other: Amount, func: Function) {
for (let [commodity, value] of other.commodities.entries()) {
if (!this.commodities.has(commodity)) {
this.commodities.set(commodity, value.newZero());
}
var amt1 = this.commodities.get(commodity);
var amt2 = other.commodities.get(commodity);
func.call(amt1, amt2);
if (amt1.isZero()) {
this.commodities.delete(commodity);
}
}
}
/**
* Adds the given amount to this one.
* @param {Amount} amount The balance to add.
*/
add(other: Amount) {
this._apply(other, Decimal.prototype.add);
}
/**
* Subtracts the given amount from this one.
* @param {Amount} amount The balance to subtract.
*/
sub(other: Amount) {
this._apply(other, Decimal.prototype.sub);
}
toString(): string {
var strs = [];
for (let [commodity, val] of this.commodities) {
let valStr = val.toString();
// Special-case commodities with common symbols.
if (commodity == "USD") {
let isNegative = false;
if (valStr.substring(0, 1) == "-") {
isNegative = true;
valStr = valStr.substring(1);
}
valStr = "$" + valStr;
if (isNegative) {
valStr = "-" + valStr;
}
strs.push(valStr);
} else {
strs.push(valStr + " " + commodity);
}
}
var ret = strs.join(", ");
if (ret == "") {
ret = "0";
}
return ret;
}
isZero(): boolean {
return this.commodities.size == 0;
}
static isValid(data) {
for (let commodity of Object.keys(data)) {
if (typeof commodity != "string" ||
typeof data[commodity] != "string") {
return false;
}
}
return true;
}
}
/** Period / SummingPeriod ****************************************************/
class Period {
name: string;
roundDown: (date: Date) => Date;
dateNext: (date: Date) => Date;
datePrev: (date: Date) => Date;
static periods: Map<string, Period>;
/**
* Adds a period to the global list of available periods.
* For use at startup time only.
*/
static add(name, roundDown, dateNext) {
let period = new Period()
period.name = name;
period.roundDown = roundDown;
period.dateNext = dateNext;
period.datePrev = function(d) {
let roundedDown = roundDown(d);
roundedDown.setMilliseconds(-1);
return roundDown(roundedDown);
}
Period.periods.set(name, period);
}
static getPeriod(name) {
return this.periods.get(name);
}
}
Period.periods = new Map();
// Periods you can use when requesting Readers.
// "FOREVER" is a special kind of period that we don't define here.
Period.add(
"YEAR",
(d) => new Date(d.getFullYear(), 0),
(d) => new Date(d.getFullYear() + 1, 0)
);
Period.add(
"QUARTER",
(d) => new Date(d.getFullYear(), Math.floor(d.getMonth() / 3) * 3),
(d) => new Date(d.getFullYear(), Math.ceil(d.getMonth() / 3) * 3)
);
Period.add(
"MONTH",
(d) => new Date(d.getFullYear(), d.getMonth()),
(d) => new Date(d.getFullYear(), d.getMonth() + 1)
);
Period.add(
"WEEK",
// Currently this always starts weeks on Sunday, could make this configurable.
(d) => new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay()),
(d) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + 7 - d.getDay())
);
Period.add(
"DAY",
(d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()),
(d) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1)
);
class SummingPeriod extends Period {
aggregateKey: string;
strLength: number;
onBoundary: Function;
// FLOW BUG: gets confused if we name this 'periods'.
static periods2: Array<SummingPeriod>;
/**
* Adds a period to the global list of available summing periods.
* For use at startup time only.
*/
static add2(name, aggregateKey: string, strLength, onBoundary) {
let period = Period.periods.get(name);
if (!period) {
throw "Must have previously been declared as a period.";
}
let new_period = new SummingPeriod();
new_period.name = period.name;
new_period.roundDown = period.roundDown;
new_period.dateNext = period.dateNext;
new_period.aggregateKey = aggregateKey + ";";
new_period.strLength = strLength;
new_period.onBoundary = onBoundary;
SummingPeriod.periods2.push(new_period);
Period.periods.set(period.name, new_period);
}
/**
* Gets a sum key for this date and period. The date should be on a boundary
* for this period.
*/
getSumKey(date) {
if (!this.onBoundary(date)) {
throw "Not on proper boundary!";
}
return this.aggregateKey + date.toISOString().substr(0, this.strLength);
}
static onDayBoundary(date) {
return date.getHours() == 0 && date.getMinutes() == 0 &&
date.getSeconds() == 0 && date.getMilliseconds() == 0;
}
static onMonthBoundary(date) {
return SummingPeriod.onDayBoundary(date) && date.getDate() == 1;
}
static onYearBoundary(date) {
return SummingPeriod.onMonthBoundary(date) && date.getMonth() == 0;
}
}
SummingPeriod.periods2 = [];
// Periods we internally aggregate by (must also be defined above).
// Order is significant: must be listed biggest to smallest.
SummingPeriod.add2("YEAR", "Y", 4, SummingPeriod.onYearBoundary);
SummingPeriod.add2("MONTH", "M", 7, SummingPeriod.onMonthBoundary);
SummingPeriod.add2("DAY", "D", 10, SummingPeriod.onDayBoundary);
// For testing purposes, remove some or all of our SummingPeriods, to make
// sure that the algorithms still work.
export function test_NoDaySums() { SummingPeriod.periods2.pop(); }
export function test_NoSums() { SummingPeriod.periods2 = []; }
/** Observable ********************************************************/
/**
* Observable interface / base class.
*
* Objects that inherit from this (Account, Transaction, and Reader) allow you
* to receive notification when the object changes.
*/
export class Observable {
// Keys are subscribed objects, values are associated callback functions.
subscribers: Map<mixed, Function>;
constructor() {
this.subscribers = new Map();
}
/**
* Registers this callback, which will be called whenever this object changes.
* Any callback previously registered for this subcriber will be replaced.
*
* Note that subscribing to an object only gives you notifications for when
* that object itself changes. It does not give you notifications when related
* information changes. For example, subscribing to a Account does
* not deliver change notifications when transactions are added to the account,
* because transactions are not directly available from the Account object.
*/
subscribe(subscriber: mixed, callback: Function) {
this.subscribers.set(subscriber, callback);
}
/**
* Unregisters any previously registered callback for this subscriber.
*/
unsubscribe(subscriber: mixed) { this.subscribers.delete(subscriber); }
/**
* Internal-only function for calling all subscribers that the object has
* changed.
*/
_notifySubscribers() {
// Important: must gather the callbacks into an array first, because
// delivering the notification can call back into unsubscribe().
var callbacks = arrayFrom(this.subscribers.values());
for (var i in callbacks) {
callbacks[i]();
}
}
/**
* Takes an array of any number of observables and calls the given function
* when all of them have loaded. In the status quo everything is kept loaded
* so the function is called immediately.
*/
static whenLoaded(observables, func) { func(); }
}
/** DB ************************************************************************/
// Maps object store name to its key field name.
const ObjectStores = {
"transactions": "guid",
"accounts": "guid",
"sums": "key"
};
/**
* The top-level "database" object that contains all accounts and transactions
* for some person or organization.
*
* Together with the Account, Transaction, and Reader types, this object
* provides a full r/w interface to all information kept in the application.
*
* All changes are immediately saved into a local indexedDB. When this object
* is constructed, it reads all data from the indexedDB to restore to the last
* saved state.
*
* This object must not be constructed directly; a database should be opened
* with DB.open below.
*/
export class DB {
idb: any;
accountsByGuid: Map<string, Account>;
transactionsByGuid: Map<string, Transaction>;
transactionsByTime: SortedMap<string, Transaction>;
sumsByKey: SortedMap<string, Sum>;
readers: Set<Reader>;
entryLists: IntervalMap<string, EntryList>;
atomicLevel: number;
dirtyMap: Map<string, Set<DbUpdater>>;
committing: number;
version: number;
static singleton: DB;
/**
* Constructor is not public: clients should obtain new DB instances with
* DB.open() below.
* @private
*/
constructor() {
this.readers = new Set();
this.entryLists = new IntervalMap();
this.accountsByGuid = new Map();
// Key is txn._byTimeKey().
this.transactionsByTime = new SortedMap();
this.transactionsByGuid = new Map();
// Key is defined by sum.key().
this.sumsByKey = new SortedMap();
this.atomicLevel = 0;
this.dirtyMap = new Map();
this.committing = 0;
this.version = 0;
// Add the two root accounts -- these are currently special-cased and
// not actually stored in the DB (should probably fix this).
new Account(this, {
"name": "Real Root Account (internal)",
"guid": "REAL_ROOT",
"type": "ASSET",
}, true);
new Account(this, {
"name": "Nominal Root Account (internal)",
"guid": "NOMINAL_ROOT",
"type": "INCOME",
}, true);
}
/**
* Opens the database and loads initial values, returning a promise that will
* provide a DB object in the success case.
*/
static open() {
let db = new DB()
let initialized = false;
if (DB.singleton) {
throw Error("Only one DB object allowed");
}
DB.singleton = db;
let openDb = function() {
return new Promise(function(resolve, reject) {
// Open Database, creating schema if necessary.
var version = 1;
var request = indexedDB.open("dblbook", version);
request.onupgradeneeded = function(e) {
var idb = request.result;
var store = idb.createObjectStore("transactions", {keyPath: "guid"});
store.createIndex("time_order", "date")
store = idb.createObjectStore("accounts", {keyPath: "guid"});
store = idb.createObjectStore("sums", {keyPath: "key"});
initialized = true;
}
request.onblocked = function(e) {
alert("Oops!");
reject(Error("DB was blocked"))
}
request.onsuccess = function() {
db.idb = request.result;
// Set up behavior for what we'll do if the database changes versions
// (or is deleted) out from under us.
request.result.onversionchange = function(e) {
if (e.newVersion === null) {
db.idb.close();
}
}
resolve();
}
request.onerror = function() {
reject(Error("error opening IndexedDB"));
}
});
}
let loadAccounts = function() {
return new Promise(function(resolve, reject) {
// Load accounts.
let txn = db.idb.transaction("accounts", "readonly");
let accounts = []
txn.objectStore("accounts").openCursor().onsuccess = function(event) {
let cursor = event.target.result;
if (cursor) {
accounts.push(cursor.value);
cursor.continue();
} else {
// End-of-stream. Need to ensure that we add parent accounts before
// children.
accounts = toposort(accounts);
accounts.reverse();
for (let account of accounts) { new Account(db, account, true); }
console.log("Loaded ", accounts.length, " accounts");
resolve(db);
}
}
});
}
let loadSums = function() {
return new Promise(function(resolve, reject) {
// Load accounts.
let txn = db.idb.transaction("sums", "readonly");
let count = 0;
txn.objectStore("sums").openCursor().onsuccess = function(event) {
let cursor = event.target.result;
if (cursor) {
let sum = cursor.value;
db.sumsByKey.set(sum.key, new Sum(db, sum.key, sum));
count++;
cursor.continue();
} else {
console.log("Loaded ", count, " sums");
resolve(db);
}
}
});
}
let loadTransactions = function() {
return new Promise(function(resolve, reject) {
// Right now we immediately and unconditionally load all transactions; we will
// want to replace this with lazy loading.
// It's confusing but there are two different kinds of transactions going on
// here: IndexedDB database transactions and the app-level financial
// transactions we are loading.
let dbTxn = db.idb.transaction("transactions", "readonly");
let count = 0;
dbTxn.objectStore("transactions").openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
new Transaction(db, cursor.value, true);
count++;
cursor.continue();
} else {
// Finished reading transactions.
console.log("Loaded ", count, " transaction");
resolve(db);
}
}
});
}
return openDb()
.then(loadAccounts)
.then(loadSums)
.then(loadTransactions);
}
/**
* Closes the DB object. After this returns, you may not call any mutating
* methods.
*/
close() {
this.idb.close();
}
/**
* Deletes the database (all data is completely lost!), returning a promise.
*/
static delete() {
return new Promise(function(resolve, reject) {
var request = indexedDB.deleteDatabase("dblbook");
request.onsuccess = function() {
resolve();
}
request.onerror = function(event) {
console.log("Error in obliterate", event);
reject(new Error("Error in obliterate", event));
}
});
}
/**
* Checks the validity of the given transaction, including that all of the
* referenced accounts exist.
*
* @param txn Data for a transaction (as in model.proto).
*/
transactionIsValid(txnData: Object): boolean {
if (!Transaction.isValid(txnData)) {
return false;
}
for (var i in txnData.entry) {
var entry = txnData.entry[i]
if (!this.accountsByGuid.has(entry.account_guid)) {
return false;
}
}
return true;
}
/**