-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.js
More file actions
1479 lines (1332 loc) · 60.2 KB
/
Copy pathstore.js
File metadata and controls
1479 lines (1332 loc) · 60.2 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
// store.js
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { DatabaseSync } = require("node:sqlite");
// Defaults to ./data; LEDGER_DATA_DIR lets tests (and anyone who wants to)
// point the database at a throwaway directory instead of the real one.
const DATA_DIR = process.env.LEDGER_DATA_DIR
? path.resolve(process.env.LEDGER_DATA_DIR)
: path.join(__dirname, "data");
const SQLITE_FILE = path.join(DATA_DIR, "ledger.sqlite3");
const BUILDING_FILE = path.join(DATA_DIR, "ledger.sqlite3.building");
const LEGACY_JSON_FILE = path.join(DATA_DIR, "db.json");
const DEFAULT_BILL_CATEGORIES = ["Housing", "Utilities", "Entertainment", "Insurance", "Subscriptions", "Food", "Transport", "Health", "Savings", "Other"];
const BILL_PRIORITIES = ["low", "medium", "high", "urgent"];
const PRIORITY_COLORS = { low: "#4fa8a0", medium: "#7c8cc9", high: "#e8a33d", urgent: "#c9605a" };
const PRIORITY_ORDER = { urgent: 3, high: 2, medium: 1, low: 0 };
const SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY NOT NULL,
username TEXT,
avatar TEXT,
timezone TEXT,
incomeEstimate REAL,
incomeCurrency TEXT,
updatedAt INTEGER,
passwordHash TEXT,
authType TEXT DEFAULT 'discord',
mustChangePassword INTEGER DEFAULT 0,
icalToken TEXT,
digestFrequency TEXT DEFAULT 'off',
lastDigestSentAt INTEGER,
lastLoginAt INTEGER,
defaultCurrency TEXT DEFAULT 'USD',
billCategories TEXT,
budgetStartMonth TEXT
);
CREATE TABLE IF NOT EXISTS characters (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
name TEXT,
color TEXT,
createdAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_characters_owner ON characters(ownerId);
CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
characterId TEXT,
title TEXT,
body TEXT,
tags TEXT,
sticky INTEGER,
spoiler INTEGER,
dueDate TEXT,
createdAt INTEGER,
updatedAt INTEGER,
deletedAt INTEGER,
prevTitle TEXT,
prevBody TEXT,
prevSavedAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_notes_owner ON notes(ownerId);
CREATE TABLE IF NOT EXISTS reminders (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
noteId TEXT,
noteTitle TEXT,
fireAt INTEGER,
repeat INTEGER,
repeatInterval INTEGER,
createdAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_reminders_owner ON reminders(ownerId);
CREATE INDEX IF NOT EXISTS idx_reminders_fireAt ON reminders(fireAt);
CREATE TABLE IF NOT EXISTS bills (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
name TEXT,
amount REAL,
currency TEXT,
dueDate TEXT,
frequency TEXT,
category TEXT,
autoPay INTEGER,
url TEXT,
color TEXT,
notes TEXT,
reminderDays INTEGER,
paid INTEGER,
paidDates TEXT,
lastReminderSent TEXT,
createdAt INTEGER,
deletedAt INTEGER,
priority TEXT DEFAULT 'medium'
);
CREATE INDEX IF NOT EXISTS idx_bills_owner ON bills(ownerId);
CREATE TABLE IF NOT EXISTS allowlist (
id TEXT PRIMARY KEY NOT NULL,
label TEXT,
addedAt INTEGER
);
CREATE TABLE IF NOT EXISTS billsAccess (
id TEXT PRIMARY KEY NOT NULL,
addedAt INTEGER
);
`;
// Tables added after the original schema shipped. SCHEMA_SQL only ever runs for
// a brand-new database, so anything introduced later has to be created here too
// and run against existing databases on every startup. Every statement is
// IF NOT EXISTS, so executing it in both paths is harmless.
const LATER_TABLES_SQL = `
CREATE TABLE IF NOT EXISTS budgetTargets (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
effectiveMonth TEXT,
category TEXT,
amount REAL,
createdAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_budgetTargets_owner ON budgetTargets(ownerId);
CREATE TABLE IF NOT EXISTS expenses (
id TEXT PRIMARY KEY NOT NULL,
ownerId TEXT,
amount REAL,
currency TEXT,
category TEXT,
spentOn TEXT,
note TEXT,
createdAt INTEGER,
deletedAt INTEGER
);
CREATE INDEX IF NOT EXISTS idx_expenses_owner ON expenses(ownerId);
`;
let db = null;
function applyPragmas(handle) {
handle.exec("PRAGMA journal_mode = WAL");
handle.exec("PRAGMA foreign_keys = OFF");
handle.exec("PRAGMA synchronous = NORMAL");
}
// Adds columns introduced after a database was first created. SCHEMA_SQL's
// CREATE TABLE IF NOT EXISTS only applies to brand-new databases, so any
// database that already exists needs its own additive, idempotent path here.
// Never drops or rewrites existing columns/rows.
function ensureColumn(handle, table, column, type) {
const cols = handle.prepare(`PRAGMA table_info(${table})`).all();
if (!cols.some((c) => c.name === column)) {
handle.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
}
}
function ensureSchemaUpToDate(handle) {
ensureColumn(handle, "notes", "spoiler", "INTEGER DEFAULT 0");
// Soft delete: rows with a deletedAt sit in the trash until purged.
ensureColumn(handle, "notes", "deletedAt", "INTEGER");
ensureColumn(handle, "bills", "deletedAt", "INTEGER");
ensureColumn(handle, "notes", "prevTitle", "TEXT");
ensureColumn(handle, "notes", "prevBody", "TEXT");
ensureColumn(handle, "notes", "prevSavedAt", "INTEGER");
// Existing bills keep whatever color they already had -- only the
// priority is backfilled (defaults every existing row to 'medium').
// Color only gets recomputed from priority the next time it's changed.
ensureColumn(handle, "bills", "priority", "TEXT DEFAULT 'medium'");
// Existing (Discord) users backfill to authType='discord', passwordHash
// stays NULL, mustChangePassword stays 0 -- none of that affects login.
ensureColumn(handle, "users", "passwordHash", "TEXT");
ensureColumn(handle, "users", "authType", "TEXT DEFAULT 'discord'");
ensureColumn(handle, "users", "mustChangePassword", "INTEGER DEFAULT 0");
ensureColumn(handle, "users", "icalToken", "TEXT");
ensureColumn(handle, "users", "digestFrequency", "TEXT DEFAULT 'off'");
ensureColumn(handle, "users", "lastDigestSentAt", "INTEGER");
ensureColumn(handle, "users", "lastLoginAt", "INTEGER");
ensureColumn(handle, "users", "defaultCurrency", "TEXT DEFAULT 'USD'");
ensureColumn(handle, "users", "billCategories", "TEXT");
ensureColumn(handle, "users", "budgetStartMonth", "TEXT");
// Creates any table introduced after the original schema. Safe to re-run.
handle.exec(LATER_TABLES_SQL);
}
// Migrates a legacy data/db.json into the (already schema-created) handle.
// Throws on any error or row-count mismatch -- callers must not treat the
// handle as valid data if this throws.
function migrateFromJson(handle, jsonPath) {
const data = JSON.parse(fs.readFileSync(jsonPath, "utf8"));
handle.exec("BEGIN");
try {
const insertUser = handle.prepare(
`INSERT INTO users (id, username, avatar, timezone, incomeEstimate, incomeCurrency, updatedAt)
VALUES (:id, :username, :avatar, :timezone, :incomeEstimate, :incomeCurrency, :updatedAt)`
);
Object.values(data.users || {}).forEach((u) => {
insertUser.run({
id: u.id,
username: u.username ?? null,
avatar: u.avatar ?? null,
timezone: u.timezone ?? null,
incomeEstimate: u.incomeEstimate != null ? Number(u.incomeEstimate) : null,
incomeCurrency: u.incomeCurrency ?? null,
updatedAt: u.updatedAt ?? null
});
});
const insertCharacter = handle.prepare(
`INSERT INTO characters (id, ownerId, name, color, createdAt)
VALUES (:id, :ownerId, :name, :color, :createdAt)`
);
Object.values(data.characters || {}).forEach((c) => {
insertCharacter.run({
id: c.id,
ownerId: c.ownerId ?? null,
name: c.name ?? null,
color: c.color ?? null,
createdAt: c.createdAt ?? null
});
});
const insertNote = handle.prepare(
`INSERT INTO notes (id, ownerId, characterId, title, body, tags, sticky, dueDate, createdAt, updatedAt)
VALUES (:id, :ownerId, :characterId, :title, :body, :tags, :sticky, :dueDate, :createdAt, :updatedAt)`
);
Object.values(data.notes || {}).forEach((n) => {
insertNote.run({
id: n.id,
ownerId: n.ownerId ?? null,
characterId: n.characterId ?? null,
title: n.title ?? "",
body: n.body ?? "",
tags: JSON.stringify(Array.isArray(n.tags) ? n.tags : []),
sticky: n.sticky ? 1 : 0,
dueDate: n.dueDate ?? null,
createdAt: n.createdAt ?? null,
updatedAt: n.updatedAt ?? null
});
});
const insertReminder = handle.prepare(
`INSERT INTO reminders (id, ownerId, noteId, noteTitle, fireAt, repeat, repeatInterval, createdAt)
VALUES (:id, :ownerId, :noteId, :noteTitle, :fireAt, :repeat, :repeatInterval, :createdAt)`
);
Object.values(data.reminders || {}).forEach((r) => {
insertReminder.run({
id: r.id,
ownerId: r.ownerId ?? null,
noteId: r.noteId ?? null,
noteTitle: r.noteTitle ?? "",
fireAt: r.fireAt ?? null,
repeat: r.repeat ? 1 : 0,
repeatInterval: r.repeatInterval ?? null,
createdAt: r.createdAt ?? null
});
});
const insertBill = handle.prepare(
`INSERT INTO bills (id, ownerId, name, amount, currency, dueDate, frequency, category, autoPay, url, color, notes, reminderDays, paid, paidDates, lastReminderSent, createdAt)
VALUES (:id, :ownerId, :name, :amount, :currency, :dueDate, :frequency, :category, :autoPay, :url, :color, :notes, :reminderDays, :paid, :paidDates, :lastReminderSent, :createdAt)`
);
Object.values(data.bills || {}).forEach((b) => {
insertBill.run({
id: b.id,
ownerId: b.ownerId ?? null,
name: b.name ?? "",
amount: b.amount != null ? Number(b.amount) : 0,
currency: b.currency ?? "USD",
dueDate: b.dueDate ?? null,
frequency: b.frequency ?? "monthly",
category: b.category ?? "Other",
autoPay: b.autoPay ? 1 : 0,
url: b.url ?? "",
color: b.color ?? "#c9605a",
notes: b.notes ?? "",
reminderDays: b.reminderDays != null ? Number(b.reminderDays) : null,
paid: b.paid ? 1 : 0,
paidDates: JSON.stringify(Array.isArray(b.paidDates) ? b.paidDates : []),
lastReminderSent: b.lastReminderSent ?? null,
createdAt: b.createdAt ?? null
});
});
const insertAllowlist = handle.prepare(
`INSERT INTO allowlist (id, label, addedAt) VALUES (:id, :label, :addedAt)`
);
Object.values(data.allowlist || {}).forEach((e) => {
insertAllowlist.run({ id: e.id, label: e.label ?? "", addedAt: e.addedAt ?? null });
});
const insertBillsAccess = handle.prepare(
`INSERT INTO billsAccess (id, addedAt) VALUES (:id, :addedAt)`
);
Object.values(data.billsAccess || {}).forEach((e) => {
insertBillsAccess.run({ id: e.id, addedAt: e.addedAt ?? null });
});
handle.exec("COMMIT");
} catch (err) {
handle.exec("ROLLBACK");
throw err;
}
// Independent verification pass beyond the transaction itself: every
// collection's row count must match the source JSON exactly, or we
// treat the whole migration as failed.
const collections = ["users", "characters", "notes", "reminders", "bills", "allowlist", "billsAccess"];
for (const table of collections) {
const expected = data[table] ? Object.keys(data[table]).length : 0;
const actual = handle.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get().n;
if (actual !== expected) {
throw new Error(`Migration verification failed for "${table}": expected ${expected} rows, found ${actual}.`);
}
}
}
function initDb() {
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (fs.existsSync(SQLITE_FILE)) {
// Already fully initialized/migrated in a previous run.
db = new DatabaseSync(SQLITE_FILE);
applyPragmas(db);
ensureSchemaUpToDate(db);
return;
}
// Clean up any incomplete attempt left behind by a crash mid-migration.
if (fs.existsSync(BUILDING_FILE)) fs.rmSync(BUILDING_FILE);
const building = new DatabaseSync(BUILDING_FILE);
applyPragmas(building);
building.exec(SCHEMA_SQL);
building.exec(LATER_TABLES_SQL);
if (fs.existsSync(LEGACY_JSON_FILE)) {
migrateFromJson(building, LEGACY_JSON_FILE); // throws on any problem
}
building.close();
// Only becomes the "real" file once schema + migration + verification
// have all fully succeeded -- this rename is the atomic success signal.
fs.renameSync(BUILDING_FILE, SQLITE_FILE);
if (fs.existsSync(LEGACY_JSON_FILE)) {
const backupPath = `${LEGACY_JSON_FILE}.migrated-${Date.now()}.bak`;
fs.renameSync(LEGACY_JSON_FILE, backupPath);
console.log(`[store] Migrated data/db.json to SQLite (data/${path.basename(SQLITE_FILE)}). Original kept as data/${path.basename(backupPath)}.`);
}
db = new DatabaseSync(SQLITE_FILE);
applyPragmas(db);
}
initDb();
function uid() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}
// ---------- row -> JS object mappers ----------
function rowToUser(row) {
if (!row) return null;
return {
id: row.id, username: row.username, avatar: row.avatar, timezone: row.timezone,
incomeEstimate: row.incomeEstimate, incomeCurrency: row.incomeCurrency, updatedAt: row.updatedAt,
authType: row.authType || "discord", mustChangePassword: !!row.mustChangePassword,
digestFrequency: row.digestFrequency || "off", lastLoginAt: row.lastLoginAt || null,
lastDigestSentAt: row.lastDigestSentAt || null, defaultCurrency: row.defaultCurrency || "USD",
billCategories: row.billCategories ? JSON.parse(row.billCategories) : DEFAULT_BILL_CATEGORIES.slice(),
budgetStartMonth: row.budgetStartMonth || null
};
}
function rowToCharacter(row) {
if (!row) return null;
return { id: row.id, ownerId: row.ownerId, name: row.name, color: row.color, createdAt: row.createdAt };
}
function rowToNote(row) {
if (!row) return null;
return {
id: row.id, ownerId: row.ownerId, characterId: row.characterId,
title: row.title, body: row.body,
tags: row.tags ? JSON.parse(row.tags) : [],
sticky: !!row.sticky, spoiler: !!row.spoiler, dueDate: row.dueDate,
createdAt: row.createdAt, updatedAt: row.updatedAt, deletedAt: row.deletedAt || null,
prevTitle: row.prevTitle, prevBody: row.prevBody, prevSavedAt: row.prevSavedAt
};
}
function rowToReminder(row) {
if (!row) return null;
return {
id: row.id, ownerId: row.ownerId, noteId: row.noteId, noteTitle: row.noteTitle,
fireAt: row.fireAt, repeat: !!row.repeat, repeatInterval: row.repeatInterval, createdAt: row.createdAt
};
}
// Payments used to be stored as bare date strings, which meant historical
// spend was always valued at the bill's *current* amount -- edit the amount and
// your past months silently changed. They're now {date, amount} pairs. Legacy
// string entries still read fine, falling back to the current amount as the
// best guess available for payments made before amounts were recorded.
function normalizePaidDates(raw, fallbackAmount) {
const list = Array.isArray(raw) ? raw : [];
return list.map((entry) => {
if (typeof entry === "string") return { date: entry, amount: Number(fallbackAmount) || 0 };
if (entry && typeof entry === "object") {
return { date: entry.date || "", amount: entry.amount != null ? Number(entry.amount) || 0 : Number(fallbackAmount) || 0 };
}
return null;
}).filter((e) => e && e.date);
}
function rowToBill(row) {
if (!row) return null;
return {
id: row.id, ownerId: row.ownerId, name: row.name, amount: row.amount, currency: row.currency,
dueDate: row.dueDate, frequency: row.frequency, category: row.category,
autoPay: !!row.autoPay, url: row.url, color: row.color, notes: row.notes,
reminderDays: row.reminderDays, paid: !!row.paid,
paidDates: normalizePaidDates(row.paidDates ? JSON.parse(row.paidDates) : [], row.amount),
lastReminderSent: row.lastReminderSent, createdAt: row.createdAt,
deletedAt: row.deletedAt || null,
priority: row.priority || "medium"
};
}
function rowToAllowlistEntry(row) {
if (!row) return null;
return { id: row.id, label: row.label, addedAt: row.addedAt };
}
function rowToBillsAccessEntry(row) {
if (!row) return null;
return { id: row.id, addedAt: row.addedAt };
}
// ---------- users ----------
async function upsertUser(discordUser) {
const existing = db.prepare("SELECT * FROM users WHERE id = :id").get({ id: discordUser.id });
const avatar = discordUser.avatar
? `https://cdn.discordapp.com/avatars/${discordUser.id}/${discordUser.avatar}.png`
: null;
const updatedAt = Date.now();
if (existing) {
db.prepare("UPDATE users SET username = :username, avatar = :avatar, updatedAt = :updatedAt WHERE id = :id")
.run({ id: discordUser.id, username: discordUser.username, avatar, updatedAt });
} else {
db.prepare(
`INSERT INTO users (id, username, avatar, timezone, incomeEstimate, incomeCurrency, updatedAt)
VALUES (:id, :username, :avatar, NULL, NULL, NULL, :updatedAt)`
).run({ id: discordUser.id, username: discordUser.username, avatar, updatedAt });
}
return rowToUser(db.prepare("SELECT * FROM users WHERE id = :id").get({ id: discordUser.id }));
}
function getUser(id) {
return rowToUser(db.prepare("SELECT * FROM users WHERE id = :id").get({ id }));
}
async function updateUserTimezone(id, timezone) {
const existing = db.prepare("SELECT * FROM users WHERE id = :id").get({ id });
if (!existing) return null;
db.prepare("UPDATE users SET timezone = :timezone WHERE id = :id").run({ id, timezone });
return rowToUser({ ...existing, timezone });
}
async function updateUserIncome(id, amount, currency) {
const existing = db.prepare("SELECT * FROM users WHERE id = :id").get({ id });
if (!existing) return null;
const incomeEstimate = amount != null ? Number(amount) : null;
const incomeCurrency = currency || existing.incomeCurrency || "USD";
db.prepare("UPDATE users SET incomeEstimate = :incomeEstimate, incomeCurrency = :incomeCurrency WHERE id = :id")
.run({ id, incomeEstimate, incomeCurrency });
return rowToUser({ ...existing, incomeEstimate, incomeCurrency });
}
const BILL_CURRENCIES = ["CAD", "USD", "EUR", "GBP", "AUD", "NZD", "CHF", "JPY", "SEK", "NOK", "DKK"];
async function updateDefaultCurrency(id, currency) {
if (!BILL_CURRENCIES.includes(currency)) throw new Error("Invalid currency.");
const existing = db.prepare("SELECT * FROM users WHERE id = :id").get({ id });
if (!existing) return null;
db.prepare("UPDATE users SET defaultCurrency = :defaultCurrency WHERE id = :id").run({ id, defaultCurrency: currency });
return rowToUser({ ...existing, defaultCurrency: currency });
}
// Relabels every bill this owner has to a new currency -- does not convert
// amounts, just changes the currency code stored alongside them. Used when
// the user opts to have their existing bills follow a new default currency.
async function updateAllBillsCurrency(ownerId, currency) {
if (!BILL_CURRENCIES.includes(currency)) throw new Error("Invalid currency.");
const result = db.prepare("UPDATE bills SET currency = :currency WHERE ownerId = :ownerId").run({ ownerId, currency });
return Number(result.changes);
}
async function updateBillCategories(id, categories) {
if (!Array.isArray(categories)) throw new Error("Categories must be a list.");
const seen = new Set();
const cleaned = [];
for (const raw of categories) {
const c = typeof raw === "string" ? raw.trim() : "";
if (!c || c.length > 30) continue;
const key = c.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
cleaned.push(c);
}
if (!cleaned.length) throw new Error("At least one category is required.");
if (cleaned.length > 40) throw new Error("Too many categories.");
const existing = db.prepare("SELECT * FROM users WHERE id = :id").get({ id });
if (!existing) return null;
const billCategories = JSON.stringify(cleaned);
db.prepare("UPDATE users SET billCategories = :billCategories WHERE id = :id").run({ id, billCategories });
return rowToUser({ ...existing, billCategories });
}
// Self-service "remove my data" -- wipes everything owned by this account
// (characters, notes, reminders, bills) and resets stored preferences.
// Does not touch the allowlist/billsAccess grant or the account row itself,
// so the user can still log back in with a clean slate.
async function deleteAllUserData(id) {
db.prepare("DELETE FROM notes WHERE ownerId = :ownerId").run({ ownerId: id });
db.prepare("DELETE FROM characters WHERE ownerId = :ownerId").run({ ownerId: id });
db.prepare("DELETE FROM reminders WHERE ownerId = :ownerId").run({ ownerId: id });
db.prepare("DELETE FROM bills WHERE ownerId = :ownerId").run({ ownerId: id });
db.prepare("UPDATE users SET timezone = NULL, incomeEstimate = NULL, incomeCurrency = NULL WHERE id = :id")
.run({ id });
}
// ---------- local (non-Discord) accounts ----------
function hashPassword(password) {
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto.scryptSync(password, salt, 64).toString("hex");
return `${salt}:${hash}`;
}
function verifyPasswordAgainstHash(password, stored) {
if (!stored) return false;
const [salt, hashHex] = stored.split(":");
if (!salt || !hashHex) return false;
const expected = Buffer.from(hashHex, "hex");
const actual = crypto.scryptSync(password, salt, 64);
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
async function createLocalAccount(username, password) {
const trimmed = String(username || "").trim();
const existing = db.prepare("SELECT id FROM users WHERE authType = 'local' AND LOWER(username) = LOWER(:username)")
.get({ username: trimmed });
if (existing) throw new Error("That username is already taken.");
const id = "local_" + uid();
const now = Date.now();
db.prepare(
`INSERT INTO users (id, username, avatar, timezone, incomeEstimate, incomeCurrency, updatedAt, passwordHash, authType, mustChangePassword)
VALUES (:id, :username, NULL, NULL, NULL, NULL, :updatedAt, :passwordHash, 'local', 1)`
).run({ id, username: trimmed, updatedAt: now, passwordHash: hashPassword(password) });
return rowToUser(db.prepare("SELECT * FROM users WHERE id = :id").get({ id }));
}
function listLocalAccounts() {
return db.prepare("SELECT * FROM users WHERE authType = 'local'").all()
.map(rowToUser)
.sort((a, b) => (a.username || "").localeCompare(b.username || ""));
}
function verifyLocalLogin(username, password) {
const row = db.prepare("SELECT * FROM users WHERE authType = 'local' AND LOWER(username) = LOWER(:username)")
.get({ username: String(username || "").trim() });
if (!row || !verifyPasswordAgainstHash(password, row.passwordHash)) return null;
return rowToUser(row);
}
async function changeOwnPassword(id, currentPassword, newPassword) {
const row = db.prepare("SELECT * FROM users WHERE id = :id AND authType = 'local'").get({ id });
if (!row) return false;
if (!verifyPasswordAgainstHash(currentPassword, row.passwordHash)) return false;
db.prepare("UPDATE users SET passwordHash = :passwordHash, mustChangePassword = 0 WHERE id = :id")
.run({ id, passwordHash: hashPassword(newPassword) });
return true;
}
async function adminResetPassword(id, newPassword) {
const row = db.prepare("SELECT * FROM users WHERE id = :id AND authType = 'local'").get({ id });
if (!row) return null;
db.prepare("UPDATE users SET passwordHash = :passwordHash, mustChangePassword = 1 WHERE id = :id")
.run({ id, passwordHash: hashPassword(newPassword) });
return rowToUser({ ...row, mustChangePassword: 1 });
}
// Fully removes a local account: unlike the self-service "remove my data"
// flow, there's no external (Discord) identity left behind to preserve, so
// this also deletes the account row itself and any Bills-access grant.
async function deleteLocalAccount(id) {
const row = db.prepare("SELECT id FROM users WHERE id = :id AND authType = 'local'").get({ id });
if (!row) return false;
await deleteAllUserData(id);
db.prepare("DELETE FROM users WHERE id = :id AND authType = 'local'").run({ id });
await revokeBillsAccess(id);
return true;
}
async function recordLogin(id) {
db.prepare("UPDATE users SET lastLoginAt = :lastLoginAt WHERE id = :id").run({ id, lastLoginAt: Date.now() });
}
// icalToken is deliberately excluded from rowToUser -- it's a bearer
// credential for the unauthenticated .ics feed route, only ever handed
// back through these dedicated functions/endpoints.
async function getOrCreateIcalToken(id) {
const row = db.prepare("SELECT icalToken FROM users WHERE id = :id").get({ id });
if (!row) return null;
if (row.icalToken) return row.icalToken;
const token = crypto.randomBytes(24).toString("hex");
db.prepare("UPDATE users SET icalToken = :icalToken WHERE id = :id").run({ id, icalToken: token });
return token;
}
async function regenerateIcalToken(id) {
const row = db.prepare("SELECT id FROM users WHERE id = :id").get({ id });
if (!row) return null;
const token = crypto.randomBytes(24).toString("hex");
db.prepare("UPDATE users SET icalToken = :icalToken WHERE id = :id").run({ id, icalToken: token });
return token;
}
function getUserByIcalToken(token) {
if (!token) return null;
return rowToUser(db.prepare("SELECT * FROM users WHERE icalToken = :token").get({ token }));
}
const DIGEST_FREQUENCIES = ["off", "daily", "weekly", "monthly"];
async function updateDigestFrequency(id, frequency) {
if (!DIGEST_FREQUENCIES.includes(frequency)) throw new Error("Invalid digest frequency.");
const row = db.prepare("SELECT * FROM users WHERE id = :id").get({ id });
if (!row) return null;
db.prepare("UPDATE users SET digestFrequency = :digestFrequency WHERE id = :id").run({ id, digestFrequency: frequency });
return rowToUser({ ...row, digestFrequency: frequency });
}
function listUsersWithDigestEnabled() {
return db.prepare("SELECT * FROM users WHERE authType = 'discord' AND digestFrequency != 'off'").all()
.map(rowToUser);
}
async function markDigestSent(id) {
db.prepare("UPDATE users SET lastDigestSentAt = :lastDigestSentAt WHERE id = :id").run({ id, lastDigestSentAt: Date.now() });
}
// ---------- characters ----------
function listCharacters(ownerId) {
return db.prepare("SELECT * FROM characters WHERE ownerId = :ownerId").all({ ownerId })
.map(rowToCharacter)
.sort((a, b) => a.createdAt - b.createdAt);
}
async function createCharacter(ownerId, partial) {
const character = {
id: uid(), ownerId, name: (partial.name || "").slice(0, 64),
color: partial.color || "#e8a33d", createdAt: Date.now()
};
db.prepare("INSERT INTO characters (id, ownerId, name, color, createdAt) VALUES (:id, :ownerId, :name, :color, :createdAt)")
.run({ id: character.id, ownerId: character.ownerId, name: character.name, color: character.color, createdAt: character.createdAt });
return character;
}
async function updateCharacter(ownerId, id, partial) {
const row = db.prepare("SELECT * FROM characters WHERE id = :id").get({ id });
if (!row || row.ownerId !== ownerId) return null;
const name = typeof partial.name === "string" ? partial.name.slice(0, 64) : row.name;
const color = typeof partial.color === "string" ? partial.color : row.color;
db.prepare("UPDATE characters SET name = :name, color = :color WHERE id = :id").run({ id, name, color });
return rowToCharacter({ ...row, name, color });
}
async function deleteCharacter(ownerId, id) {
const row = db.prepare("SELECT * FROM characters WHERE id = :id").get({ id });
if (!row || row.ownerId !== ownerId) return false;
db.prepare("DELETE FROM characters WHERE id = :id").run({ id });
// Matches original behavior: only this owner's notes for this character are
// removed -- but they go to the trash rather than vanishing outright.
db.prepare("UPDATE notes SET deletedAt = :deletedAt WHERE characterId = :characterId AND ownerId = :ownerId AND deletedAt IS NULL")
.run({ characterId: id, ownerId, deletedAt: Date.now() });
return true;
}
// ---------- notes ----------
function listNotes(ownerId, characterId) {
const requestedCharacterId = characterId || null;
return db.prepare("SELECT * FROM notes WHERE ownerId = :ownerId AND deletedAt IS NULL").all({ ownerId })
.map(rowToNote)
.filter((n) => {
if (characterId === "__all__") return true;
return n.sticky || (n.characterId || null) === requestedCharacterId;
})
.sort((a, b) => {
if (a.sticky !== b.sticky) return a.sticky ? -1 : 1;
return b.updatedAt - a.updatedAt;
});
}
function getNote(ownerId, id) {
const row = db.prepare("SELECT * FROM notes WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
return rowToNote(row);
}
async function createNote(ownerId, partial) {
const now = Date.now();
const note = {
id: uid(), ownerId,
characterId: partial.characterId || null,
title: partial.title || "",
body: partial.body || "",
tags: Array.isArray(partial.tags) ? partial.tags : [],
sticky: Boolean(partial.sticky),
spoiler: Boolean(partial.spoiler),
dueDate: partial.dueDate || null,
createdAt: now, updatedAt: now
};
db.prepare(
`INSERT INTO notes (id, ownerId, characterId, title, body, tags, sticky, spoiler, dueDate, createdAt, updatedAt)
VALUES (:id, :ownerId, :characterId, :title, :body, :tags, :sticky, :spoiler, :dueDate, :createdAt, :updatedAt)`
).run({
id: note.id, ownerId: note.ownerId, characterId: note.characterId, title: note.title, body: note.body,
tags: JSON.stringify(note.tags), sticky: note.sticky ? 1 : 0, spoiler: note.spoiler ? 1 : 0, dueDate: note.dueDate,
createdAt: note.createdAt, updatedAt: note.updatedAt
});
return note;
}
async function updateNote(ownerId, id, partial) {
const row = db.prepare("SELECT * FROM notes WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
const note = rowToNote(row);
const contentChanged =
(typeof partial.title === "string" && partial.title !== row.title) ||
(typeof partial.body === "string" && partial.body !== row.body);
if (typeof partial.title === "string") note.title = partial.title;
if (typeof partial.body === "string") note.body = partial.body;
if (Array.isArray(partial.tags)) note.tags = partial.tags;
if (typeof partial.sticky === "boolean") note.sticky = partial.sticky;
if (typeof partial.spoiler === "boolean") note.spoiler = partial.spoiler;
if ("dueDate" in partial) note.dueDate = partial.dueDate || null;
note.updatedAt = Date.now();
// Keep a single-level "previous saved version" snapshot so an accidental
// paste-over that gets autosaved isn't unrecoverable.
if (contentChanged) {
note.prevTitle = row.title;
note.prevBody = row.body;
note.prevSavedAt = note.updatedAt;
}
db.prepare(
`UPDATE notes SET title = :title, body = :body, tags = :tags, sticky = :sticky, spoiler = :spoiler, dueDate = :dueDate, updatedAt = :updatedAt,
prevTitle = :prevTitle, prevBody = :prevBody, prevSavedAt = :prevSavedAt
WHERE id = :id`
).run({
id, title: note.title, body: note.body, tags: JSON.stringify(note.tags),
sticky: note.sticky ? 1 : 0, spoiler: note.spoiler ? 1 : 0, dueDate: note.dueDate, updatedAt: note.updatedAt,
prevTitle: note.prevTitle ?? null, prevBody: note.prevBody ?? null, prevSavedAt: note.prevSavedAt ?? null
});
return note;
}
async function restorePreviousVersion(ownerId, id) {
const row = db.prepare("SELECT * FROM notes WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
if (row.prevBody == null && row.prevTitle == null) return null;
const now = Date.now();
const restored = {
title: row.prevTitle ?? "",
body: row.prevBody ?? "",
// The restore itself becomes undoable by swapping the current content in as "previous".
prevTitle: row.title,
prevBody: row.body,
prevSavedAt: now,
updatedAt: now
};
db.prepare(
`UPDATE notes SET title = :title, body = :body, updatedAt = :updatedAt,
prevTitle = :prevTitle, prevBody = :prevBody, prevSavedAt = :prevSavedAt
WHERE id = :id`
).run({ id, ...restored });
return rowToNote({ ...row, ...restored });
}
// Deletes are soft: the row gets a deletedAt and moves to the trash, where it
// stays restorable until purged. Any reminders are dropped outright -- a note
// sitting in the trash shouldn't keep pinging you, and re-adding a reminder
// after a restore is trivial.
async function deleteNote(ownerId, id) {
const row = db.prepare("SELECT * FROM notes WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return false;
db.prepare("UPDATE notes SET deletedAt = :deletedAt WHERE id = :id").run({ id, deletedAt: Date.now() });
db.prepare("DELETE FROM reminders WHERE noteId = :noteId").run({ noteId: id });
return true;
}
async function clearNotes(ownerId, characterId) {
const requestedCharacterId = characterId || null;
const rows = db.prepare("SELECT id, characterId FROM notes WHERE ownerId = :ownerId AND deletedAt IS NULL").all({ ownerId });
const idsToDelete = rows
.filter((n) => characterId === "__all__" || (n.characterId || null) === requestedCharacterId)
.map((n) => n.id);
const now = Date.now();
for (const id of idsToDelete) {
db.prepare("UPDATE notes SET deletedAt = :deletedAt WHERE id = :id").run({ id, deletedAt: now });
db.prepare("DELETE FROM reminders WHERE noteId = :noteId").run({ noteId: id });
}
}
// ---------- reminders ----------
function listReminders(ownerId) {
return db.prepare("SELECT * FROM reminders WHERE ownerId = :ownerId").all({ ownerId })
.map(rowToReminder)
.sort((a, b) => a.fireAt - b.fireAt);
}
function listRemindersForNote(ownerId, noteId) {
return db.prepare("SELECT * FROM reminders WHERE ownerId = :ownerId AND noteId = :noteId").all({ ownerId, noteId })
.map(rowToReminder)
.sort((a, b) => a.fireAt - b.fireAt);
}
function getDueReminders() {
const now = Date.now();
return db.prepare("SELECT * FROM reminders WHERE fireAt <= :now").all({ now }).map(rowToReminder);
}
async function createReminder(ownerId, partial) {
const reminder = {
id: uid(), ownerId,
noteId: partial.noteId,
noteTitle: partial.noteTitle || "",
fireAt: partial.fireAt,
repeat: partial.repeat || false,
repeatInterval: partial.repeatInterval || null,
createdAt: Date.now()
};
db.prepare(
`INSERT INTO reminders (id, ownerId, noteId, noteTitle, fireAt, repeat, repeatInterval, createdAt)
VALUES (:id, :ownerId, :noteId, :noteTitle, :fireAt, :repeat, :repeatInterval, :createdAt)`
).run({
id: reminder.id, ownerId: reminder.ownerId, noteId: reminder.noteId, noteTitle: reminder.noteTitle,
fireAt: reminder.fireAt, repeat: reminder.repeat ? 1 : 0, repeatInterval: reminder.repeatInterval,
createdAt: reminder.createdAt
});
return reminder;
}
async function rescheduleReminder(id, intervalMs) {
const row = db.prepare("SELECT * FROM reminders WHERE id = :id").get({ id });
if (!row) return null;
const fireAt = Date.now() + intervalMs;
db.prepare("UPDATE reminders SET fireAt = :fireAt WHERE id = :id").run({ id, fireAt });
const reminder = rowToReminder(row);
reminder.fireAt = fireAt;
return reminder;
}
async function deleteReminder(ownerId, id) {
const row = db.prepare("SELECT * FROM reminders WHERE id = :id").get({ id });
if (!row || row.ownerId !== ownerId) return false;
db.prepare("DELETE FROM reminders WHERE id = :id").run({ id });
return true;
}
// ---------- bills (per-user, gated by bills access) ----------
function dateToStr(d) {
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
}
// Adds calendar months while clamping to the target month's last day,
// so e.g. Jan 31 + 1 month lands on Feb 28/29, not overflowing into March.
function addMonthsClamped(d, months) {
const day = d.getDate();
d.setDate(1);
d.setMonth(d.getMonth() + months);
const daysInMonth = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
d.setDate(Math.min(day, daysInMonth));
return d;
}
function advanceDueDate(dateStr, frequency) {
const d = new Date(dateStr + "T00:00:00");
switch (frequency) {
case "weekly": d.setDate(d.getDate() + 7); break;
case "biweekly": d.setDate(d.getDate() + 14); break;
case "monthly": addMonthsClamped(d, 1); break;
case "quarterly": addMonthsClamped(d, 3); break;
case "yearly": d.setFullYear(d.getFullYear() + 1); break;
}
return dateToStr(d);
}
function listBills(ownerId) {
return db.prepare("SELECT * FROM bills WHERE ownerId = :ownerId AND deletedAt IS NULL").all({ ownerId })
.map(rowToBill)
.sort((a, b) => {
if (a.dueDate && b.dueDate) {
const cmp = a.dueDate.localeCompare(b.dueDate);
if (cmp !== 0) return cmp;
return (PRIORITY_ORDER[b.priority] ?? 1) - (PRIORITY_ORDER[a.priority] ?? 1);
}
if (a.dueDate) return -1;
if (b.dueDate) return 1;
return (a.name || "").localeCompare(b.name || "");
});
}
function getBill(ownerId, id) {
const row = db.prepare("SELECT * FROM bills WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
return rowToBill(row);
}
async function createBill(ownerId, partial) {
const priority = BILL_PRIORITIES.includes(partial.priority) ? partial.priority : "medium";
const bill = {
id: uid(), ownerId,
name: partial.name || "New bill",
amount: parseFloat(partial.amount) || 0,
currency: partial.currency || "USD",
dueDate: partial.dueDate || null,
frequency: partial.frequency || "monthly",
category: partial.category || "Other",
autoPay: Boolean(partial.autoPay),
url: partial.url || "",
color: PRIORITY_COLORS[priority],
notes: partial.notes || "",
reminderDays: partial.reminderDays != null ? Number(partial.reminderDays) : null,
paid: false,
paidDates: [],
lastReminderSent: null,
createdAt: Date.now(),
priority
};
db.prepare(
`INSERT INTO bills (id, ownerId, name, amount, currency, dueDate, frequency, category, autoPay, url, color, notes, reminderDays, paid, paidDates, lastReminderSent, createdAt, priority)
VALUES (:id, :ownerId, :name, :amount, :currency, :dueDate, :frequency, :category, :autoPay, :url, :color, :notes, :reminderDays, :paid, :paidDates, :lastReminderSent, :createdAt, :priority)`
).run({
id: bill.id, ownerId: bill.ownerId, name: bill.name, amount: bill.amount, currency: bill.currency,
dueDate: bill.dueDate, frequency: bill.frequency, category: bill.category, autoPay: bill.autoPay ? 1 : 0,
url: bill.url, color: bill.color, notes: bill.notes, reminderDays: bill.reminderDays,
paid: bill.paid ? 1 : 0, paidDates: JSON.stringify(bill.paidDates), lastReminderSent: bill.lastReminderSent,
createdAt: bill.createdAt, priority: bill.priority
});
return bill;
}
async function updateBill(ownerId, id, partial) {
const row = db.prepare("SELECT * FROM bills WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
const bill = rowToBill(row);
// "paid" is intentionally excluded -- it's only mutated via markBillPaid/markBillUnpaid,
// which also keep paidDates and dueDate advancement in sync.
const fields = ["name","amount","currency","dueDate","frequency","category","autoPay","url","notes","reminderDays"];
fields.forEach(f => { if (f in partial) bill[f] = partial[f]; });
if (typeof bill.amount === "string") bill.amount = parseFloat(bill.amount) || 0;
// Color is derived from priority, not independently settable -- picking a
// priority level recolors the bill everywhere it's shown.
if (BILL_PRIORITIES.includes(partial.priority)) {
bill.priority = partial.priority;
bill.color = PRIORITY_COLORS[bill.priority];
}
db.prepare(
`UPDATE bills SET name=:name, amount=:amount, currency=:currency, dueDate=:dueDate, frequency=:frequency,
category=:category, autoPay=:autoPay, url=:url, color=:color, notes=:notes, reminderDays=:reminderDays,
priority=:priority
WHERE id=:id`
).run({
id, name: bill.name, amount: bill.amount, currency: bill.currency, dueDate: bill.dueDate,
frequency: bill.frequency, category: bill.category, autoPay: bill.autoPay ? 1 : 0, url: bill.url,
color: bill.color, notes: bill.notes, reminderDays: bill.reminderDays, priority: bill.priority
});
return bill;
}
async function markBillPaid(ownerId, id) {
const row = db.prepare("SELECT * FROM bills WHERE id = :id AND deletedAt IS NULL").get({ id });
if (!row || row.ownerId !== ownerId) return null;
const bill = rowToBill(row);
const today = dateToStr(new Date());
if (!bill.paidDates) bill.paidDates = [];
// Record what it actually cost at the time, so later edits to the bill's
// amount don't rewrite history (the budget's rollover depends on this).
bill.paidDates.unshift({ date: today, amount: Number(bill.amount) || 0 });