-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathmain.ts
1566 lines (1327 loc) · 39.3 KB
/
main.ts
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
// @ts-strict-ignore
import './polyfills';
import * as injectAPI from '@actual-app/api/injected';
import * as CRDT from '@actual-app/crdt';
import { v4 as uuidv4 } from 'uuid';
import { createTestBudget } from '../mocks/budget';
import { captureException, captureBreadcrumb } from '../platform/exceptions';
import * as asyncStorage from '../platform/server/asyncStorage';
import * as connection from '../platform/server/connection';
import * as fs from '../platform/server/fs';
import { logger } from '../platform/server/log';
import * as sqlite from '../platform/server/sqlite';
import * as monthUtils from '../shared/months';
import { q } from '../shared/query';
import { type Budget } from '../types/budget';
import { Handlers } from '../types/handlers';
import { OpenIdConfig } from '../types/models/openid';
import { app as accountsApp } from './accounts/app';
import { app as adminApp } from './admin/app';
import { installAPI } from './api';
import { runQuery as aqlQuery } from './aql';
import {
getAvailableBackups,
loadBackup,
makeBackup,
startBackupService,
stopBackupService,
} from './backups';
import { app as budgetApp } from './budget/app';
import * as budget from './budget/base';
import * as cloudStorage from './cloud-storage';
import { app as dashboardApp } from './dashboard/app';
import * as db from './db';
import * as mappings from './db/mappings';
import * as encryption from './encryption';
import { APIError } from './errors';
import { app as filtersApp } from './filters/app';
import { handleBudgetImport } from './importers';
import { app } from './main-app';
import { mutator, runHandler } from './mutators';
import { app as notesApp } from './notes/app';
import { app as payeesApp } from './payees/app';
import * as Platform from './platform';
import { get, post } from './post';
import { app as preferencesApp } from './preferences/app';
import * as prefs from './prefs';
import { app as reportsApp } from './reports/app';
import { app as rulesApp } from './rules/app';
import { app as schedulesApp } from './schedules/app';
import { getServer, isValidBaseURL, setServer } from './server-config';
import * as sheet from './sheet';
import { resolveName, unresolveName } from './spreadsheet/util';
import {
initialFullSync,
fullSync,
setSyncingMode,
makeTestMessage,
clearFullSyncTimeout,
resetSync,
repairSync,
batchMessages,
} from './sync';
import * as syncMigrations from './sync/migrate';
import { app as toolsApp } from './tools/app';
import { app as transactionsApp } from './transactions/app';
import * as rules from './transactions/transaction-rules';
import { clearUndo, undo, redo, withUndo } from './undo';
import { updateVersion } from './update';
import {
uniqueBudgetName,
idFromBudgetName,
validateBudgetName,
} from './util/budget-name';
const DEMO_BUDGET_ID = '_demo-budget';
const TEST_BUDGET_ID = '_test-budget';
// util
function onSheetChange({ names }) {
const nodes = names.map(name => {
const node = sheet.get()._getNode(name);
return { name: node.name, value: node.value };
});
connection.send('cells-changed', nodes);
}
// handlers
// need to work around the type system here because the object
// is /currently/ empty but we promise to fill it in later
export let handlers = {} as unknown as Handlers;
handlers['undo'] = mutator(async function () {
return undo();
});
handlers['redo'] = mutator(function () {
return redo();
});
handlers['get-categories'] = async function () {
return {
grouped: await db.getCategoriesGrouped(),
list: await db.getCategories(),
};
};
handlers['get-budget-bounds'] = async function () {
return budget.createAllBudgets();
};
handlers['envelope-budget-month'] = async function ({ month }) {
const groups = await db.getCategoriesGrouped();
const sheetName = monthUtils.sheetForMonth(month);
function value(name) {
const v = sheet.getCellValue(sheetName, name);
return { value: v === '' ? 0 : v, name: resolveName(sheetName, name) };
}
let values = [
value('available-funds'),
value('last-month-overspent'),
value('buffered'),
value('total-budgeted'),
value('to-budget'),
value('from-last-month'),
value('total-income'),
value('total-spent'),
value('total-leftover'),
];
for (const group of groups) {
if (group.is_income) {
values.push(value('total-income'));
for (const cat of group.categories) {
values.push(value(`sum-amount-${cat.id}`));
}
} else {
values = values.concat([
value(`group-budget-${group.id}`),
value(`group-sum-amount-${group.id}`),
value(`group-leftover-${group.id}`),
]);
for (const cat of group.categories) {
values = values.concat([
value(`budget-${cat.id}`),
value(`sum-amount-${cat.id}`),
value(`leftover-${cat.id}`),
value(`carryover-${cat.id}`),
value(`goal-${cat.id}`),
value(`long-goal-${cat.id}`),
]);
}
}
}
return values;
};
handlers['tracking-budget-month'] = async function ({ month }) {
const groups = await db.getCategoriesGrouped();
const sheetName = monthUtils.sheetForMonth(month);
function value(name) {
const v = sheet.getCellValue(sheetName, name);
return { value: v === '' ? 0 : v, name: resolveName(sheetName, name) };
}
let values = [
value('total-budgeted'),
value('total-budget-income'),
value('total-saved'),
value('total-income'),
value('total-spent'),
value('real-saved'),
value('total-leftover'),
];
for (const group of groups) {
values = values.concat([
value(`group-budget-${group.id}`),
value(`group-sum-amount-${group.id}`),
value(`group-leftover-${group.id}`),
]);
for (const cat of group.categories) {
values = values.concat([
value(`budget-${cat.id}`),
value(`sum-amount-${cat.id}`),
value(`leftover-${cat.id}`),
value(`goal-${cat.id}`),
value(`long-goal-${cat.id}`),
]);
if (!group.is_income) {
values.push(value(`carryover-${cat.id}`));
}
}
}
return values;
};
handlers['category-create'] = mutator(async function ({
name,
groupId,
isIncome,
hidden,
}) {
return withUndo(async () => {
if (!groupId) {
throw APIError('Creating a category: groupId is required');
}
return db.insertCategory({
name: name.trim(),
cat_group: groupId,
is_income: isIncome ? 1 : 0,
hidden: hidden ? 1 : 0,
});
});
});
handlers['category-update'] = mutator(async function (category) {
return withUndo(async () => {
try {
await db.updateCategory({
...category,
name: category.name.trim(),
});
} catch (e) {
if (e.message.toLowerCase().includes('unique constraint')) {
return { error: { type: 'category-exists' } };
}
throw e;
}
return {};
});
});
handlers['category-move'] = mutator(async function ({ id, groupId, targetId }) {
return withUndo(async () => {
await batchMessages(async () => {
await db.moveCategory(id, groupId, targetId);
});
return 'ok';
});
});
handlers['category-delete'] = mutator(async function ({ id, transferId }) {
return withUndo(async () => {
let result = {};
await batchMessages(async () => {
const row = await db.first<Pick<db.DbCategory, 'is_income'>>(
'SELECT is_income FROM categories WHERE id = ?',
[id],
);
if (!row) {
result = { error: 'no-categories' };
return;
}
const transfer =
transferId &&
(await db.first<Pick<db.DbCategory, 'is_income'>>(
'SELECT is_income FROM categories WHERE id = ?',
[transferId],
));
if (!row || (transferId && !transfer)) {
result = { error: 'no-categories' };
return;
} else if (transferId && row.is_income !== transfer.is_income) {
result = { error: 'category-type' };
return;
}
// Update spreadsheet values if it's an expense category
// TODO: We should do this for income too if it's a reflect budget
if (row.is_income === 0) {
if (transferId) {
await budget.doTransfer([id], transferId);
}
}
await db.deleteCategory({ id }, transferId);
});
return result;
});
});
handlers['get-category-groups'] = async function () {
return await db.getCategoriesGrouped();
};
handlers['category-group-create'] = mutator(async function ({
name,
isIncome,
hidden,
}) {
return withUndo(async () => {
return db.insertCategoryGroup({
name,
is_income: isIncome ? 1 : 0,
hidden,
});
});
});
handlers['category-group-update'] = mutator(async function (group) {
return withUndo(async () => {
return db.updateCategoryGroup(group);
});
});
handlers['category-group-move'] = mutator(async function ({ id, targetId }) {
return withUndo(async () => {
await batchMessages(async () => {
await db.moveCategoryGroup(id, targetId);
});
return 'ok';
});
});
handlers['category-group-delete'] = mutator(async function ({
id,
transferId,
}) {
return withUndo(async () => {
const groupCategories = await db.all(
'SELECT id FROM categories WHERE cat_group = ? AND tombstone = 0',
[id],
);
return batchMessages(async () => {
if (transferId) {
await budget.doTransfer(
groupCategories.map(c => c.id),
transferId,
);
}
await db.deleteCategoryGroup({ id }, transferId);
});
});
});
handlers['must-category-transfer'] = async function ({ id }) {
const res = await db.runQuery<{ count: number }>(
`SELECT count(t.id) as count FROM transactions t
LEFT JOIN category_mapping cm ON cm.id = t.category
WHERE cm.transferId = ? AND t.tombstone = 0`,
[id],
true,
);
// If there are transactions with this category, return early since
// we already know it needs to be tranferred
if (res[0].count !== 0) {
return true;
}
// If there are any non-zero budget values, also force the user to
// transfer the category.
return [...sheet.get().meta().createdMonths].some(month => {
const sheetName = monthUtils.sheetForMonth(month);
const value = sheet.get().getCellValue(sheetName, 'budget-' + id);
return value != null && value !== 0;
});
};
handlers['make-filters-from-conditions'] = async function ({
conditions,
applySpecialCases,
}) {
return rules.conditionsToAQL(conditions, { applySpecialCases });
};
handlers['getCell'] = async function ({ sheetName, name }) {
const node = sheet.get()._getNode(resolveName(sheetName, name));
return { name: node.name, value: node.value };
};
handlers['getCells'] = async function ({ names }) {
return names.map(name => {
const node = sheet.get()._getNode(name);
return { name: node.name, value: node.value };
});
};
handlers['getCellNamesInSheet'] = async function ({ sheetName }) {
const names = [];
for (const name of sheet.get().getNodes().keys()) {
const { sheet: nodeSheet, name: nodeName } = unresolveName(name);
if (nodeSheet === sheetName) {
names.push(nodeName);
}
}
return names;
};
handlers['debugCell'] = async function ({ sheetName, name }) {
const node = sheet.get().getNode(resolveName(sheetName, name));
return {
...node,
_run: node._run && node._run.toString(),
};
};
handlers['create-query'] = async function ({ sheetName, name, query }) {
// Always run it regardless of cache. We don't know anything has changed
// between the cache value being saved and now
sheet.get().createQuery(sheetName, name, query);
return 'ok';
};
handlers['query'] = async function (query) {
if (query.table == null) {
throw new Error('query has no table, did you forgot to call `.serialize`?');
}
return aqlQuery(query);
};
handlers['sync-reset'] = async function () {
return await resetSync();
};
handlers['sync-repair'] = async function () {
await repairSync();
};
// A user can only enable/change their key with the file loaded. This
// will change in the future: during onboarding the user should be
// able to enable encryption. (Imagine if they are importing data from
// another source, they should be able to encrypt first)
handlers['key-make'] = async function ({ password }) {
if (!prefs.getPrefs()) {
throw new Error('user-set-key must be called with file loaded');
}
const salt = encryption.randomBytes(32).toString('base64');
const id = uuidv4();
const key = await encryption.createKey({ id, password, salt });
// Load the key
await encryption.loadKey(key);
// Make some test data to use if the key is valid or not
const testContent = await makeTestMessage(key.getId());
// Changing your key necessitates a sync reset as well. This will
// clear all existing encrypted data from the server so you won't
// have a mix of data encrypted with different keys.
return await resetSync({
key,
salt,
testContent: JSON.stringify({
...testContent,
value: testContent.value.toString('base64'),
}),
});
};
// This can be called both while a file is already loaded or not. This
// will see if a key is valid and if so save it off.
handlers['key-test'] = async function ({ fileId, password }) {
const userToken = await asyncStorage.getItem('user-token');
if (fileId == null) {
fileId = prefs.getPrefs().cloudFileId;
}
let res;
try {
res = await post(getServer().SYNC_SERVER + '/user-get-key', {
token: userToken,
fileId,
});
} catch (e) {
console.log(e);
return { error: { reason: 'network' } };
}
const { id, salt, test: originalTest } = res;
let test = originalTest;
if (test == null) {
return { error: { reason: 'old-key-style' } };
}
test = JSON.parse(test);
const key = await encryption.createKey({ id, password, salt });
encryption.loadKey(key);
try {
await encryption.decrypt(Buffer.from(test.value, 'base64'), test.meta);
} catch (e) {
console.log(e);
// Unload the key, it's invalid
encryption.unloadKey(key);
return { error: { reason: 'decrypt-failure' } };
}
// Persist key in async storage
const keys = JSON.parse((await asyncStorage.getItem(`encrypt-keys`)) || '{}');
keys[fileId] = key.serialize();
await asyncStorage.setItem('encrypt-keys', JSON.stringify(keys));
// Save the key id in prefs if the are loaded. If they aren't, we
// are testing a key to download a file and when the file is
// actually downloaded it will update the prefs with the latest key id
if (prefs.getPrefs()) {
await prefs.savePrefs({ encryptKeyId: key.getId() });
}
return {};
};
handlers['get-did-bootstrap'] = async function () {
return Boolean(await asyncStorage.getItem('did-bootstrap'));
};
handlers['subscribe-needs-bootstrap'] = async function ({
url,
}: { url? } = {}) {
if (url && !isValidBaseURL(url)) {
return { error: 'get-server-failure' };
}
try {
if (!getServer(url)) {
return { bootstrapped: true, hasServer: false };
}
} catch (err) {
return { error: 'get-server-failure' };
}
let res;
try {
res = await get(getServer(url).SIGNUP_SERVER + '/needs-bootstrap');
} catch (err) {
return { error: 'network-failure' };
}
try {
res = JSON.parse(res);
} catch (err) {
return { error: 'parse-failure' };
}
if (res.status === 'error') {
return { error: res.reason };
}
return {
bootstrapped: res.data.bootstrapped,
availableLoginMethods: res.data.availableLoginMethods || [
{ method: 'password', active: true, displayName: 'Password' },
],
multiuser: res.data.multiuser || false,
hasServer: true,
};
};
handlers['subscribe-bootstrap'] = async function (loginConfig) {
try {
await post(getServer().SIGNUP_SERVER + '/bootstrap', loginConfig);
} catch (err) {
return { error: err.reason || 'network-failure' };
}
return {};
};
handlers['subscribe-get-login-methods'] = async function () {
let res;
try {
res = await fetch(getServer().SIGNUP_SERVER + '/login-methods').then(res =>
res.json(),
);
} catch (err) {
return { error: err.reason || 'network-failure' };
}
if (res.methods) {
return { methods: res.methods };
}
return { error: 'internal' };
};
handlers['subscribe-get-user'] = async function () {
if (!getServer()) {
if (!(await asyncStorage.getItem('did-bootstrap'))) {
return null;
}
return { offline: false };
}
const userToken = await asyncStorage.getItem('user-token');
if (!userToken) {
return null;
}
try {
const res = await get(getServer().SIGNUP_SERVER + '/validate', {
headers: {
'X-ACTUAL-TOKEN': userToken,
},
});
let tokenExpired = false;
const {
status,
reason,
data: {
userName = null,
permission = '',
userId = null,
displayName = null,
loginMethod = null,
} = {},
} = JSON.parse(res) || {};
if (status === 'error') {
if (reason === 'unauthorized') {
return null;
} else if (reason === 'token-expired') {
tokenExpired = true;
} else {
return { offline: true };
}
}
return {
offline: false,
userName,
permission,
userId,
displayName,
loginMethod,
tokenExpired,
};
} catch (e) {
console.log(e);
return { offline: true };
}
};
handlers['subscribe-change-password'] = async function ({ password }) {
const userToken = await asyncStorage.getItem('user-token');
if (!userToken) {
return { error: 'not-logged-in' };
}
try {
await post(getServer().SIGNUP_SERVER + '/change-password', {
token: userToken,
password,
});
} catch (err) {
return { error: err.reason || 'network-failure' };
}
return {};
};
handlers['subscribe-sign-in'] = async function (loginInfo) {
if (
typeof loginInfo.loginMethod !== 'string' ||
loginInfo.loginMethod == null
) {
loginInfo.loginMethod = 'password';
}
let res;
try {
res = await post(getServer().SIGNUP_SERVER + '/login', loginInfo);
} catch (err) {
return { error: err.reason || 'network-failure' };
}
if (res.redirect_url) {
return { redirect_url: res.redirect_url };
}
if (!res.token) {
throw new Error('login: User token not set');
}
await asyncStorage.setItem('user-token', res.token);
return {};
};
handlers['subscribe-sign-out'] = async function () {
encryption.unloadAllKeys();
await asyncStorage.multiRemove([
'user-token',
'encrypt-keys',
'lastBudget',
'readOnly',
]);
return 'ok';
};
handlers['subscribe-set-token'] = async function ({ token }) {
await asyncStorage.setItem('user-token', token);
};
handlers['get-server-version'] = async function () {
if (!getServer()) {
return { error: 'no-server' };
}
let version;
try {
const res = await get(getServer().BASE_SERVER + '/info');
const info = JSON.parse(res);
version = info.build.version;
} catch (err) {
return { error: 'network-failure' };
}
return { version };
};
handlers['get-server-url'] = async function () {
return getServer() && getServer().BASE_SERVER;
};
handlers['set-server-url'] = async function ({ url, validate = true }) {
if (url == null) {
await asyncStorage.removeItem('user-token');
} else {
url = url.replace(/\/+$/, '');
if (validate) {
// Validate the server is running
const result = await runHandler(handlers['subscribe-needs-bootstrap'], {
url,
});
if ('error' in result) {
return { error: result.error };
}
}
}
await asyncStorage.setItem('server-url', url);
await asyncStorage.setItem('did-bootstrap', true);
setServer(url);
return {};
};
handlers['sync'] = async function () {
return fullSync();
};
handlers['validate-budget-name'] = async function ({ name }) {
return validateBudgetName(name);
};
handlers['unique-budget-name'] = async function ({ name }) {
return uniqueBudgetName(name);
};
handlers['get-budgets'] = async function () {
const paths = await fs.listDir(fs.getDocumentDir());
const budgets = (
await Promise.all(
paths.map(async name => {
const prefsPath = fs.join(fs.getDocumentDir(), name, 'metadata.json');
if (await fs.exists(prefsPath)) {
let prefs;
try {
prefs = JSON.parse(await fs.readFile(prefsPath));
} catch (e) {
console.log('Error parsing metadata:', e.stack);
return;
}
// We treat the directory name as the canonical id so that if
// the user moves it around/renames/etc, nothing breaks. The
// id is stored in prefs just for convenience (and the prefs
// will always update to the latest given id)
if (name !== DEMO_BUDGET_ID) {
return {
id: name,
...(prefs.cloudFileId ? { cloudFileId: prefs.cloudFileId } : {}),
...(prefs.encryptKeyId
? { encryptKeyId: prefs.encryptKeyId }
: {}),
...(prefs.groupId ? { groupId: prefs.groupId } : {}),
...(prefs.owner ? { owner: prefs.owner } : {}),
name: prefs.budgetName || '(no name)',
} satisfies Budget;
}
}
return null;
}),
)
).filter(x => x);
return budgets;
};
handlers['get-remote-files'] = async function () {
return cloudStorage.listRemoteFiles();
};
handlers['get-user-file-info'] = async function (fileId: string) {
return cloudStorage.getRemoteFile(fileId);
};
handlers['reset-budget-cache'] = mutator(async function () {
// Recomputing everything will update the cache
await sheet.loadUserBudgets(db);
sheet.get().recomputeAll();
await sheet.waitOnSpreadsheet();
});
handlers['upload-budget'] = async function ({ id }: { id? } = {}) {
if (id) {
if (prefs.getPrefs()) {
throw new Error('upload-budget: id given but prefs already loaded');
}
await prefs.loadPrefs(id);
}
try {
await cloudStorage.upload();
} catch (e) {
console.log(e);
if (e.type === 'FileUploadError') {
return { error: e };
}
captureException(e);
return { error: { reason: 'internal' } };
} finally {
if (id) {
prefs.unloadPrefs();
}
}
return {};
};
handlers['download-budget'] = async function ({ fileId }) {
let result;
try {
result = await cloudStorage.download(fileId);
} catch (e) {
if (e.type === 'FileDownloadError') {
if (e.reason === 'file-exists' && e.meta.id) {
await prefs.loadPrefs(e.meta.id);
const name = prefs.getPrefs().budgetName;
prefs.unloadPrefs();
e.meta = { ...e.meta, name };
}
return { error: e };
} else {
captureException(e);
return { error: { reason: 'internal' } };
}
}
const id = result.id;
await handlers['load-budget']({ id });
result = await handlers['sync-budget']();
if (result.error) {
return result;
}
return { id };
};
// open and sync, but don’t close
handlers['sync-budget'] = async function () {
setSyncingMode('enabled');
const result = await initialFullSync();
return result;
};
handlers['load-budget'] = async function ({ id }) {
const currentPrefs = prefs.getPrefs();
if (currentPrefs) {
if (currentPrefs.id === id) {
// If it's already loaded, do nothing
return {};
} else {
// Otherwise, close the currently loaded budget
await handlers['close-budget']();
}
}
const res = await loadBudget(id);
return res;
};
handlers['create-demo-budget'] = async function () {
// Make sure the read only flag isn't leftover (normally it's
// reset when signing in, but you don't have to sign in for the
// demo budget)
await asyncStorage.setItem('readOnly', '');
return handlers['create-budget']({
budgetName: 'Demo Budget',
testMode: true,
testBudgetId: DEMO_BUDGET_ID,
});
};
handlers['close-budget'] = async function () {
captureBreadcrumb({ message: 'Closing budget' });
// The spreadsheet may be running, wait for it to complete
await sheet.waitOnSpreadsheet();
sheet.unloadSpreadsheet();
clearFullSyncTimeout();
await app.stopServices();
await db.closeDatabase();
try {
await asyncStorage.setItem('lastBudget', '');
} catch (e) {
// This might fail if we are shutting down after failing to load a
// budget. We want to unload whatever has already been loaded but
// be resilient to anything failing
}
prefs.unloadPrefs();
await stopBackupService();
return 'ok';
};
handlers['delete-budget'] = async function ({ id, cloudFileId }) {
// If it's a cloud file, you can delete it from the server by
// passing its cloud id
if (cloudFileId) {
await cloudStorage.removeFile(cloudFileId).catch(() => {});
}
// If a local file exists, you can delete it by passing its local id
if (id) {
// opening and then closing the database is a hack to be able to delete
// the budget file if it hasn't been opened yet. This needs a better
// way, but works for now.
try {
await db.openDatabase(id);
await db.closeDatabase();
const budgetDir = fs.getBudgetDir(id);
await fs.removeDirRecursively(budgetDir);
} catch (e) {
return 'fail';
}
}
return 'ok';
};
handlers['duplicate-budget'] = async function ({
id,
newName,
cloudSync,
open,
}): Promise<string> {
if (!id) throw new Error('Unable to duplicate a budget that is not local.');
const { valid, message } = await validateBudgetName(newName);
if (!valid) throw new Error(message);
const budgetDir = fs.getBudgetDir(id);
const newId = await idFromBudgetName(newName);
// copy metadata from current budget
// replace id with new budget id and budgetName with new budget name
const metadataText = await fs.readFile(fs.join(budgetDir, 'metadata.json'));
const metadata = JSON.parse(metadataText);
metadata.id = newId;
metadata.budgetName = newName;