ownledger 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/AGENTS.md +28 -1
  2. package/CHANGELOG.md +48 -0
  3. package/assets/apple-touch-icon.png +0 -0
  4. package/assets/icon-192.png +0 -0
  5. package/assets/icon-512.png +0 -0
  6. package/assets/icon-maskable-512.png +0 -0
  7. package/assets/index.html +15 -18
  8. package/assets/manifest.webmanifest +1 -1
  9. package/assets/static/Account-DEBzshne.js +1 -0
  10. package/assets/static/Accounts-C1iNsQsy.js +1 -0
  11. package/assets/static/Attention-qo4v70P1.js +1 -0
  12. package/assets/static/ByCategory-33P2zSs-.js +1 -0
  13. package/assets/static/CardDetail-CvRo7JPt.js +1 -0
  14. package/assets/static/Cards-C3AdusmT.js +1 -0
  15. package/assets/static/Cards-DuqZFxkQ.js +1 -0
  16. package/assets/static/CardsValue-BM9WUQmy.js +1 -0
  17. package/assets/static/Cashback-DsWyjgRr.js +1 -0
  18. package/assets/static/CategoryIcon-E6EWIpbr.js +1 -0
  19. package/assets/static/CategoryPicker-BPeJNSuM.js +1 -0
  20. package/assets/static/ChartWidget-Bk1TAvJM.js +1 -0
  21. package/assets/static/Combobox-lRNTmjKR.js +1 -0
  22. package/assets/static/Deposits-CgEFypxb.js +1 -0
  23. package/assets/static/DrillLink-pa6s17Xu.js +1 -0
  24. package/assets/static/Field-OkPhoYM1.js +1 -0
  25. package/assets/static/HomeEditor-DdrzEPe2.js +1 -0
  26. package/assets/static/Import-DrhHmL65.js +2 -0
  27. package/assets/static/IncomeSpending-Cveqr3xt.js +1 -0
  28. package/assets/static/KV-CKGyL0p7.js +1 -0
  29. package/assets/static/Left-Bs_oKU19.js +1 -0
  30. package/assets/static/Money-DCMKf898.js +1 -0
  31. package/assets/static/NetWorth-Cjd13J56.js +1 -0
  32. package/assets/static/Pace-CBUDNxzH.js +1 -0
  33. package/assets/static/Panel-CXjnsEN0.js +1 -0
  34. package/assets/static/PinDialog-DoGuAyi4.js +1 -0
  35. package/assets/static/Plans-EWJdPCJ3.js +1 -0
  36. package/assets/static/Recent-BmJjA5dK.js +1 -0
  37. package/assets/static/Reports-DSrLn_wC.js +1 -0
  38. package/assets/static/Settings-DdiEp2Qi.js +1 -0
  39. package/assets/static/Transactions-Cy0kgcLE.js +1 -0
  40. package/assets/static/TxRow-IqjFXpya.js +1 -0
  41. package/assets/static/Unusual-D5-L9ZOy.js +1 -0
  42. package/assets/static/Upcoming-CCqPol8c.js +1 -0
  43. package/assets/static/WhichCard-Butdi7AN.js +1 -0
  44. package/assets/static/arrow-up-C8D_7x_H.js +1 -0
  45. package/assets/static/bits-BoWPOwTB.js +1 -0
  46. package/assets/static/button-Cj0k8AtB.js +1 -0
  47. package/assets/static/cards-AZlSJQ0z.js +1 -0
  48. package/assets/static/charts-Cj_hTR4h.js +65 -0
  49. package/assets/static/chevron-down-BLodeu9a.js +1 -0
  50. package/assets/static/chevron-right-BetctQ6k.js +1 -0
  51. package/assets/static/createLucideIcon-DUW9Fpzj.js +1 -0
  52. package/assets/static/dialog-BIbLA-XP.js +1 -0
  53. package/assets/static/dist-CbNfxqbd.js +1 -0
  54. package/assets/static/dist-CetESl7K.js +1 -0
  55. package/assets/static/dist-DYP_TYPy.js +1 -0
  56. package/assets/static/dist-DaSyQKU7.js +1 -0
  57. package/assets/static/drill-t1zr57xi.js +1 -0
  58. package/assets/static/es2015-BgAh-EkH.js +41 -0
  59. package/assets/static/fold-CGWYt9Iu.js +1 -0
  60. package/assets/static/index-CBsgYTMJ.css +1 -0
  61. package/assets/static/index-DYyIpxqK.js +14 -0
  62. package/assets/static/queries-C_4ufx4u.js +1 -0
  63. package/assets/static/react-dom-CI34djkT.js +1 -0
  64. package/assets/static/select-2EwEpMf_.js +1 -0
  65. package/assets/static/shared-CR-hvb-r.js +1 -0
  66. package/assets/static/triangle-exclamation-point-C6padEUM.js +1 -0
  67. package/assets/static/useMutation-BWtHiYPX.js +1 -0
  68. package/dist/cli/cards.d.ts +2 -0
  69. package/dist/cli/cards.js +86 -0
  70. package/dist/cli/import.js +12 -2
  71. package/dist/cli/index.js +3 -0
  72. package/dist/engine/actions.d.ts +5 -0
  73. package/dist/engine/actions.js +9 -5
  74. package/dist/engine/attention.d.ts +15 -0
  75. package/dist/engine/attention.js +63 -0
  76. package/dist/engine/check.js +8 -1
  77. package/dist/engine/dashboard.d.ts +72 -0
  78. package/dist/engine/dashboard.js +180 -0
  79. package/dist/engine/features.d.ts +20 -0
  80. package/dist/engine/features.js +37 -0
  81. package/dist/engine/index.d.ts +5 -0
  82. package/dist/engine/index.js +5 -0
  83. package/dist/engine/insights.d.ts +164 -0
  84. package/dist/engine/insights.js +534 -0
  85. package/dist/engine/load.js +6 -0
  86. package/dist/engine/registry.d.ts +2 -0
  87. package/dist/engine/registry.js +15 -33
  88. package/dist/engine/reports.d.ts +21 -2
  89. package/dist/engine/reports.js +51 -3
  90. package/dist/engine/schedules.d.ts +7 -84
  91. package/dist/engine/schedules.js +8 -207
  92. package/dist/engine/types.d.ts +2 -0
  93. package/dist/engine/write.d.ts +9 -0
  94. package/dist/engine/write.js +26 -5
  95. package/dist/import/mapping.js +6 -0
  96. package/dist/import/run.d.ts +7 -0
  97. package/dist/import/run.js +28 -1
  98. package/dist/modules/api.d.ts +19 -0
  99. package/dist/modules/api.js +16 -0
  100. package/dist/modules/cards/api.d.ts +3 -0
  101. package/dist/modules/cards/api.js +73 -0
  102. package/dist/modules/cards/engine.d.ts +42 -0
  103. package/dist/modules/cards/engine.js +102 -0
  104. package/dist/modules/cards/index.d.ts +26 -0
  105. package/dist/modules/cards/index.js +304 -0
  106. package/dist/modules/cards/statements.d.ts +128 -0
  107. package/dist/modules/cards/statements.js +426 -0
  108. package/dist/modules/cards/terms.d.ts +105 -0
  109. package/dist/modules/cards/terms.js +194 -0
  110. package/dist/modules/cards/tracker.d.ts +36 -0
  111. package/dist/modules/cards/tracker.js +232 -0
  112. package/dist/modules/cards/types.d.ts +2 -0
  113. package/dist/modules/cards/types.js +16 -0
  114. package/dist/modules/deposits/engine.d.ts +14 -0
  115. package/dist/modules/deposits/engine.js +32 -0
  116. package/dist/modules/deposits/index.d.ts +2 -0
  117. package/dist/modules/deposits/index.js +24 -0
  118. package/dist/modules/deposits/types.d.ts +2 -0
  119. package/dist/modules/deposits/types.js +15 -0
  120. package/dist/modules/index.d.ts +5 -0
  121. package/dist/modules/index.js +10 -0
  122. package/dist/modules/insurance/index.d.ts +3 -0
  123. package/dist/modules/insurance/index.js +8 -0
  124. package/dist/modules/insurance/types.d.ts +2 -0
  125. package/dist/modules/insurance/types.js +3 -0
  126. package/dist/modules/investments/index.d.ts +2 -0
  127. package/dist/modules/investments/index.js +24 -0
  128. package/dist/modules/investments/types.d.ts +2 -0
  129. package/dist/modules/investments/types.js +7 -0
  130. package/dist/modules/loans/engine.d.ts +30 -0
  131. package/dist/modules/loans/engine.js +77 -0
  132. package/dist/modules/loans/index.d.ts +2 -0
  133. package/dist/modules/loans/index.js +27 -0
  134. package/dist/modules/loans/types.d.ts +2 -0
  135. package/dist/modules/loans/types.js +5 -0
  136. package/dist/modules/types.d.ts +39 -0
  137. package/dist/modules/types.js +1 -0
  138. package/dist/modules/util.d.ts +8 -0
  139. package/dist/modules/util.js +8 -0
  140. package/dist/node/scaffold.js +2 -2
  141. package/dist/worker/api.d.ts +11 -1
  142. package/dist/worker/api.js +167 -13
  143. package/dist/worker/bestcard.d.ts +32 -9
  144. package/dist/worker/bestcard.js +91 -51
  145. package/dist/worker/mcp.js +209 -30
  146. package/dist/worker/openwallet.d.ts +1 -1
  147. package/dist/worker/openwallet.js +41 -11
  148. package/dist/worker/version.d.ts +1 -1
  149. package/dist/worker/version.js +1 -1
  150. package/package.json +26 -4
  151. package/presets/misa.mapping.yaml +7 -0
  152. package/assets/app.css +0 -61
  153. package/assets/app.js +0 -369
@@ -0,0 +1,534 @@
1
+ import { holdingsAt } from "./balances.js";
2
+ import { flattenCategories, isSystemCategory, topOf } from "./categories.js";
3
+ import { addDays, addMonths, daysBetween, daysInMonth, isDate, monthEnd, monthStart, parts } from "./dates.js";
4
+ import { fold, monthsBetween } from "./reports.js";
5
+ /* ------------------------------------------------------------------ thresholds ("What's different") */
6
+ /** A category is "different" when it's at least this % off its usual… */
7
+ export const UNUSUAL_MIN_PCT = 30;
8
+ /** …and the difference is at least this share of your usual spending for the same days (keeps tiny categories out). */
9
+ export const UNUSUAL_MIN_SHARE = 0.03;
10
+ /** A transaction is unusually large when it's above this percentile of its category's lines in the last 12 months… */
11
+ export const LARGE_PERCENTILE = 0.99;
12
+ /** …and the category has at least this many lines to compare with. */
13
+ export const LARGE_MIN_SAMPLES = 20;
14
+ /** At most this many "What's different" cards. */
15
+ export const UNUSUAL_MAX = 5;
16
+ /** Expense categories that mean "not categorised yet" (the default `other`, or an explicit `uncategorized`). */
17
+ export const UNCATEGORISED = new Set(["other", "uncategorized", "uncategorised"]);
18
+ /** Income and spending of one transaction (transfers and system categories count 0). Optional category prefix filter. */
19
+ export function txFlow(t, cats, category) {
20
+ let income = 0;
21
+ let expense = 0;
22
+ for (const ln of t.lines) {
23
+ if (ln.category == null || isSystemCategory(ln.category))
24
+ continue;
25
+ if (category && !(ln.category === category || ln.category.startsWith(category + "/")))
26
+ continue;
27
+ const kind = cats.get(ln.category)?.kind ?? "expense";
28
+ if (kind === "income")
29
+ income += -ln.amount;
30
+ else
31
+ expense += ln.amount;
32
+ }
33
+ return { income, expense };
34
+ }
35
+ /** Income and spending per day from `from` to `to` (inclusive). */
36
+ export function flowsByDay(l, from, to, category) {
37
+ const { map: cats } = flattenCategories(l.categories);
38
+ const out = new Map();
39
+ for (const t of l.transactions) {
40
+ if (t.void || t.date < from)
41
+ continue;
42
+ if (t.date > to)
43
+ break;
44
+ const f = txFlow(t, cats, category);
45
+ if (!f.income && !f.expense)
46
+ continue;
47
+ const d = out.get(t.date) ?? { income: 0, expense: 0 };
48
+ d.income += f.income;
49
+ d.expense += f.expense;
50
+ out.set(t.date, d);
51
+ }
52
+ return out;
53
+ }
54
+ /** First date with income or spending (opening balances and transfers don't count), or null. */
55
+ export function firstActivity(l) {
56
+ for (const t of l.transactions) {
57
+ if (t.void)
58
+ continue;
59
+ if (t.lines.some((ln) => ln.category != null && !isSystemCategory(ln.category)))
60
+ return t.date;
61
+ }
62
+ return null;
63
+ }
64
+ /** Whole months of history before the month of asOf (0 when the ledger starts this month). */
65
+ export function historyMonths(l, asOf) {
66
+ const first = firstActivity(l);
67
+ if (!first || first > asOf)
68
+ return 0;
69
+ const [fy, fm] = parts(first);
70
+ const [y, m] = parts(asOf);
71
+ return Math.max(0, (y - fy) * 12 + (m - fm));
72
+ }
73
+ function cumulative(flows, month, days, key) {
74
+ const out = [];
75
+ let s = 0;
76
+ for (let d = 1; d <= days; d++) {
77
+ s += flows.get(`${month}-${String(d).padStart(2, "0")}`)?.[key] ?? 0;
78
+ out.push(s);
79
+ }
80
+ return out;
81
+ }
82
+ /** This month's spending against last month and your usual month, at the same day. */
83
+ export function pace(l, asOf, months = 6) {
84
+ const [y, m, day] = parts(asOf);
85
+ const dim = daysInMonth(y, m);
86
+ const month = asOf.slice(0, 7);
87
+ const hist = Math.min(months, historyMonths(l, asOf));
88
+ const from = addMonths(`${month}-01`, -Math.max(1, hist));
89
+ const flows = flowsByDay(l, from, monthEnd(asOf));
90
+ const thisSpend = cumulative(flows, month, dim, "expense");
91
+ const thisIncome = cumulative(flows, month, dim, "income");
92
+ const spent = thisSpend[day - 1];
93
+ const income = thisIncome[day - 1];
94
+ const daily = thisSpend.map((v, i) => (i < day ? v : null));
95
+ const at = (arr, d) => arr[Math.min(d, arr.length) - 1] ?? 0;
96
+ let lastMonth = null;
97
+ if (hist >= 1) {
98
+ const lm = addMonths(`${month}-01`, -1);
99
+ const [ly, lmo] = parts(lm);
100
+ const arr = cumulative(flows, lm.slice(0, 7), daysInMonth(ly, lmo), "expense");
101
+ lastMonth = { month: lm.slice(0, 7), toDate: at(arr, day), total: arr[arr.length - 1] ?? 0, daily: arr };
102
+ }
103
+ let usual = null;
104
+ if (hist >= 1) {
105
+ const sum = new Array(31).fill(0);
106
+ const low = new Array(31).fill(Number.POSITIVE_INFINITY);
107
+ const high = new Array(31).fill(Number.NEGATIVE_INFINITY);
108
+ let toDate = 0;
109
+ let total = 0;
110
+ let incomeTotal = 0;
111
+ for (let i = 1; i <= hist; i++) {
112
+ const pm = addMonths(`${month}-01`, -i);
113
+ const [py, pmo] = parts(pm);
114
+ const n = daysInMonth(py, pmo);
115
+ const arr = cumulative(flows, pm.slice(0, 7), n, "expense");
116
+ const inc = cumulative(flows, pm.slice(0, 7), n, "income");
117
+ for (let d = 1; d <= 31; d++) {
118
+ const v = at(arr, d);
119
+ sum[d - 1] += v;
120
+ low[d - 1] = Math.min(low[d - 1], v);
121
+ high[d - 1] = Math.max(high[d - 1], v);
122
+ }
123
+ toDate += at(arr, day);
124
+ total += arr[n - 1] ?? 0;
125
+ incomeTotal += inc[n - 1] ?? 0;
126
+ }
127
+ usual = {
128
+ months: hist,
129
+ toDate: Math.round(toDate / hist),
130
+ total: Math.round(total / hist),
131
+ incomeTotal: Math.round(incomeTotal / hist),
132
+ daily: sum.slice(0, dim).map((v) => Math.round(v / hist)),
133
+ // the band behind "usual": the lowest and highest month at each day
134
+ low: low.slice(0, dim),
135
+ high: high.slice(0, dim),
136
+ };
137
+ }
138
+ // With 2+ months of history: what's spent so far plus what you usually spend in the rest of the month.
139
+ const fromUsual = usual !== null && hist >= 2;
140
+ const estimate = fromUsual ? spent + Math.max(0, usual.total - usual.toDate) : Math.round((spent / day) * dim);
141
+ const incomeEstimate = Math.max(income, fromUsual ? usual.incomeTotal : income);
142
+ return { asOf, month, day, daysInMonth: dim, spent, income, daily, lastMonth, usual, estimate, incomeEstimate, estimateFrom: fromUsual ? "usual" : "run-rate" };
143
+ }
144
+ function aggregateBy(l, p, by, kind, cats) {
145
+ const accName = new Map(l.accounts.map((a) => [a.id, a.name]));
146
+ const rows = new Map();
147
+ let total = 0;
148
+ for (const t of l.transactions) {
149
+ if (t.void || t.date < p.from)
150
+ continue;
151
+ if (t.date > p.to)
152
+ break;
153
+ const firstAccount = t.lines.find((ln) => ln.account != null)?.account ?? "(none)";
154
+ for (const ln of t.lines) {
155
+ if (ln.category == null || isSystemCategory(ln.category))
156
+ continue;
157
+ const k = cats.get(ln.category)?.kind ?? "expense";
158
+ if (k !== kind)
159
+ continue;
160
+ const v = kind === "income" ? -ln.amount : ln.amount;
161
+ total += v;
162
+ const keys = by === "category" ? [[ln.category, cats.get(ln.category)?.name ?? ln.category]]
163
+ : by === "top" ? [[topOf(ln.category), cats.get(topOf(ln.category))?.name ?? topOf(ln.category)]]
164
+ : by === "account" ? [[firstAccount, accName.get(firstAccount) ?? firstAccount]]
165
+ : by === "who" ? [[t.who ?? "(none)", t.who ?? "(none)"]]
166
+ : by === "event" ? [[t.event ?? "(none)", t.event ?? "(none)"]]
167
+ : (t.tags?.length ? t.tags : ["(none)"]).map((g) => [g, g]);
168
+ for (const [key, name] of keys) {
169
+ const r = rows.get(key) ?? { name, value: 0 };
170
+ r.value += v;
171
+ rows.set(key, r);
172
+ }
173
+ }
174
+ }
175
+ return { total, rows };
176
+ }
177
+ /**
178
+ * The periods "your usual" is averaged over, for a period:
179
+ * - part of one month (1st … day d): days 1…d of each of the previous `months` months;
180
+ * - whole months (n of them): the previous `months` months, scaled to n months;
181
+ * - any other span of L days: the `months` months before it, scaled to L days.
182
+ * Returns the windows and the factor to multiply their sum by.
183
+ */
184
+ export function usualWindows(p, months) {
185
+ const sameMonth = p.from.slice(0, 7) === p.to.slice(0, 7);
186
+ const wholeMonths = p.from === monthStart(p.from) && p.to === monthEnd(p.to);
187
+ if (sameMonth && p.from === monthStart(p.from) && !wholeMonths) {
188
+ const d = parts(p.to)[2];
189
+ const windows = [];
190
+ for (let i = 1; i <= months; i++) {
191
+ const s = addMonths(p.from, -i);
192
+ const [y, m] = parts(s);
193
+ windows.push({ from: s, to: `${s.slice(0, 7)}-${String(Math.min(d, daysInMonth(y, m))).padStart(2, "0")}` });
194
+ }
195
+ return { windows, factor: 1 / months };
196
+ }
197
+ if (wholeMonths) {
198
+ const [fy, fm] = parts(p.from);
199
+ const [ty, tm] = parts(p.to);
200
+ const n = (ty - fy) * 12 + (tm - fm) + 1;
201
+ const from = addMonths(p.from, -months);
202
+ return { windows: [{ from, to: addDays(p.from, -1) }], factor: n / months };
203
+ }
204
+ const len = daysBetween(p.from, p.to) + 1;
205
+ const from = addMonths(p.from, -months);
206
+ const span = daysBetween(from, p.from);
207
+ return { windows: [{ from, to: addDays(p.from, -1) }], factor: len / span };
208
+ }
209
+ /** Each row this period against your usual for a period of the same length, sorted by the biggest change in money. */
210
+ export function usual(l, period, by = "top", o = {}) {
211
+ const kind = o.kind ?? "expense";
212
+ const want = o.months ?? 6;
213
+ const months = Math.min(want, historyMonths(l, period.from));
214
+ const { map: cats } = flattenCategories(l.categories);
215
+ const cur = aggregateBy(l, period, by, kind, cats);
216
+ const out = { period, kind, months, current: cur.total, usual: 0, rows: [] };
217
+ const usualRows = new Map();
218
+ if (months > 0) {
219
+ const { windows, factor } = usualWindows(period, months);
220
+ let total = 0;
221
+ for (const w of windows) {
222
+ const a = aggregateBy(l, w, by, kind, cats);
223
+ total += a.total;
224
+ for (const [k, r] of a.rows) {
225
+ const u = usualRows.get(k) ?? { name: r.name, value: 0 };
226
+ u.value += r.value;
227
+ usualRows.set(k, u);
228
+ }
229
+ }
230
+ out.usual = Math.round(total * factor);
231
+ for (const u of usualRows.values())
232
+ u.value = Math.round(u.value * factor);
233
+ }
234
+ const keys = new Set([...cur.rows.keys(), ...usualRows.keys()]);
235
+ for (const key of keys) {
236
+ const c = cur.rows.get(key)?.value ?? 0;
237
+ const u = usualRows.get(key)?.value ?? 0;
238
+ if (!c && !u)
239
+ continue;
240
+ out.rows.push({ key, name: cur.rows.get(key)?.name ?? usualRows.get(key).name, current: c, usual: u, change: c - u, changePct: u ? Math.round(((c - u) / Math.abs(u)) * 100) : null });
241
+ }
242
+ out.rows.sort((a, b) => Math.abs(b.change) - Math.abs(a.change));
243
+ return out;
244
+ }
245
+ function q(link) {
246
+ return "#/transactions?" + new URLSearchParams(link).toString();
247
+ }
248
+ /** Up to five "What's different" cards for the month of asOf (needs 2 months of history). */
249
+ export function unusual(l, asOf) {
250
+ if (historyMonths(l, asOf) < 2)
251
+ return [];
252
+ const { map: cats } = flattenCategories(l.categories);
253
+ const from = monthStart(asOf);
254
+ const scored = [];
255
+ // categories far from usual (top level, month to date vs the same days of the last 6 months)
256
+ const u = usual(l, { from, to: asOf }, "top", { months: 6 });
257
+ const minDiff = Math.max(1, u.usual * UNUSUAL_MIN_SHARE);
258
+ for (const r of u.rows) {
259
+ if (r.changePct === null || Math.abs(r.changePct) < UNUSUAL_MIN_PCT || Math.abs(r.change) < minDiff)
260
+ continue;
261
+ scored.push({
262
+ score: Math.abs(r.change),
263
+ card: { kind: r.change > 0 ? "category_up" : "category_down", category: r.key, name: r.name, current: r.current, usual: r.usual, changePct: r.changePct, link: q({ category: r.key, from, to: asOf }) },
264
+ });
265
+ }
266
+ // new categories and new people this month (never seen before this month)
267
+ const seenCat = new Set();
268
+ const seenWho = new Set();
269
+ const newCat = new Map();
270
+ const newWho = new Map();
271
+ const hist12 = addMonths(from, -12);
272
+ const linesByCat = new Map();
273
+ const large = [];
274
+ for (const t of l.transactions) {
275
+ if (t.void)
276
+ continue;
277
+ if (t.date > asOf)
278
+ break;
279
+ const before = t.date < from;
280
+ const f = txFlow(t, cats);
281
+ for (const ln of t.lines) {
282
+ if (ln.category == null || isSystemCategory(ln.category) || (cats.get(ln.category)?.kind ?? "expense") !== "expense")
283
+ continue;
284
+ if (before) {
285
+ seenCat.add(ln.category);
286
+ if (t.date >= hist12 && ln.amount > 0)
287
+ (linesByCat.get(ln.category) ?? linesByCat.set(ln.category, []).get(ln.category)).push(ln.amount);
288
+ }
289
+ else {
290
+ if (!seenCat.has(ln.category))
291
+ newCat.set(ln.category, (newCat.get(ln.category) ?? 0) + ln.amount);
292
+ if (ln.amount > 0)
293
+ large.push({ t, cat: ln.category, amount: ln.amount });
294
+ }
295
+ }
296
+ if (t.who) {
297
+ if (before)
298
+ seenWho.add(t.who);
299
+ else if (!seenWho.has(t.who) && f.expense > 0) {
300
+ const w = newWho.get(t.who) ?? { amount: 0, count: 0 };
301
+ w.amount += f.expense;
302
+ w.count++;
303
+ newWho.set(t.who, w);
304
+ }
305
+ }
306
+ }
307
+ for (const [c, amount] of newCat) {
308
+ if (amount <= 0)
309
+ continue;
310
+ scored.push({ score: amount, card: { kind: "new_category", category: c, name: cats.get(c)?.name ?? c, amount, link: q({ category: c, from, to: asOf }) } });
311
+ }
312
+ for (const [who, w] of newWho)
313
+ scored.push({ score: w.amount, card: { kind: "new_who", who, amount: w.amount, count: w.count, link: q({ text: who, from, to: asOf }) } });
314
+ for (const x of large) {
315
+ const hist = linesByCat.get(x.cat);
316
+ if (!hist || hist.length < LARGE_MIN_SAMPLES)
317
+ continue;
318
+ const sorted = [...hist].sort((a, b) => a - b);
319
+ const p = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * LARGE_PERCENTILE))];
320
+ if (x.amount <= p)
321
+ continue;
322
+ const median = sorted[Math.floor(sorted.length / 2)];
323
+ scored.push({
324
+ score: x.amount - median,
325
+ card: { kind: "large", tx: x.t.id, date: x.t.date, note: x.t.note ?? "", category: x.cat, name: cats.get(x.cat)?.name ?? x.cat, amount: x.amount, typical: median, link: q({ tx: x.t.id, from: x.t.date, to: x.t.date }) },
326
+ });
327
+ }
328
+ return scored.sort((a, b) => b.score - a.score).slice(0, UNUSUAL_MAX).map((s) => s.card);
329
+ }
330
+ export const PERIOD_PRESETS = ["this-month", "last-month", "last-3-months", "last-6-months", "this-year", "last-year", "last-12-months", "all"];
331
+ /** A preset or yyyy-mm / yyyy, resolved against asOf. */
332
+ export function resolvePeriod(spec, asOf, firstDate) {
333
+ const ms = monthStart(asOf);
334
+ switch (spec ?? "this-month") {
335
+ case "this-month": return { from: ms, to: asOf };
336
+ case "last-month": {
337
+ const f = addMonths(ms, -1);
338
+ return { from: f, to: monthEnd(f) };
339
+ }
340
+ case "last-3-months": return { from: addMonths(ms, -2), to: asOf };
341
+ case "last-6-months": return { from: addMonths(ms, -5), to: asOf };
342
+ case "last-12-months": return { from: addMonths(ms, -11), to: asOf };
343
+ case "this-year": return { from: `${asOf.slice(0, 4)}-01-01`, to: asOf };
344
+ case "last-year": {
345
+ const y = Number(asOf.slice(0, 4)) - 1;
346
+ return { from: `${y}-01-01`, to: `${y}-12-31` };
347
+ }
348
+ case "all": return { from: firstDate ?? ms, to: asOf };
349
+ }
350
+ if (/^\d{4}-\d{2}$/.test(spec))
351
+ return { from: `${spec}-01`, to: monthEnd(`${spec}-01`) };
352
+ if (/^\d{4}$/.test(spec))
353
+ return { from: `${spec}-01-01`, to: `${spec}-12-31` };
354
+ throw new Error(`bad period "${spec}" (${PERIOD_PRESETS.join(", ")}, yyyy-mm or yyyy)`);
355
+ }
356
+ /** Monday of the week of d. */
357
+ export function weekStart(d) {
358
+ const [y, m, dd] = parts(d);
359
+ const dow = (new Date(Date.UTC(y, m - 1, dd)).getUTCDay() + 6) % 7; // 0 = Monday
360
+ return addDays(d, -dow);
361
+ }
362
+ function timeKeys(p, by) {
363
+ if (by === "month")
364
+ return monthsBetween(p.from, p.to);
365
+ const out = [];
366
+ let d = by === "week" ? weekStart(p.from) : p.from;
367
+ while (d <= p.to) {
368
+ out.push(d);
369
+ d = addDays(d, by === "week" ? 7 : 1);
370
+ }
371
+ return out;
372
+ }
373
+ function matches(t, q, accounts, text) {
374
+ if (accounts && !t.lines.some((ln) => ln.account && accounts.has(ln.account)))
375
+ return false;
376
+ if (q.category && !t.lines.some((ln) => ln.category === q.category || ln.category?.startsWith(q.category + "/")))
377
+ return false;
378
+ if (q.who && t.who !== q.who)
379
+ return false;
380
+ if (q.event && t.event !== q.event)
381
+ return false;
382
+ if (q.tag && !(t.tags ?? []).includes(q.tag))
383
+ return false;
384
+ if (text) {
385
+ const hay = fold([t.note, t.who, t.event, ...(t.tags ?? []), ...t.lines.map((ln) => ln.note)].filter(Boolean).join(" "));
386
+ if (!hay.includes(text))
387
+ return false;
388
+ }
389
+ return true;
390
+ }
391
+ function seriesOnce(l, q, p, by, cats) {
392
+ const out = new Map();
393
+ const accounts = q.account ? new Set(Array.isArray(q.account) ? q.account : [q.account]) : null;
394
+ const text = q.text ? fold(q.text) : "";
395
+ const accName = new Map(l.accounts.map((a) => [a.id, a.name]));
396
+ const time = by === "day" || by === "week" || by === "month";
397
+ const keyOfDate = (d) => (by === "month" ? d.slice(0, 7) : by === "week" ? weekStart(d) : d);
398
+ const add = (key, name, v) => {
399
+ const r = out.get(key) ?? { name, value: 0 };
400
+ r.value += v;
401
+ out.set(key, r);
402
+ };
403
+ if (q.metric === "balance") {
404
+ if (!time)
405
+ throw new Error("balance needs by: day, week or month");
406
+ const ids = accounts ?? new Set(l.accounts.map((a) => a.id));
407
+ const keys = timeKeys(p, by);
408
+ const start = holdingsAt(l, addDays(p.from, -1));
409
+ let bal = [...ids].reduce((s, id) => s + (start.get(id)?.amount ?? 0), 0);
410
+ const delta = new Map();
411
+ for (const t of l.transactions) {
412
+ if (t.void || t.date < p.from)
413
+ continue;
414
+ if (t.date > p.to)
415
+ break;
416
+ for (const ln of t.lines)
417
+ if (ln.account && ids.has(ln.account))
418
+ delta.set(t.date, (delta.get(t.date) ?? 0) + ln.amount);
419
+ }
420
+ let i = 0;
421
+ const dates = [...delta.keys()].sort();
422
+ for (const k of keys) {
423
+ const end = by === "month" ? monthEnd(`${k}-01`) : by === "week" ? addDays(k, 6) : k;
424
+ while (i < dates.length && dates[i] <= end)
425
+ bal += delta.get(dates[i++]);
426
+ out.set(k, { name: k, value: bal });
427
+ }
428
+ return out;
429
+ }
430
+ if (time)
431
+ for (const k of timeKeys(p, by))
432
+ out.set(k, { name: k, value: 0 });
433
+ for (const t of l.transactions) {
434
+ if (t.void || t.date < p.from)
435
+ continue;
436
+ if (t.date > p.to)
437
+ break;
438
+ if (!matches(t, q, accounts, text))
439
+ continue;
440
+ if (q.metric === "count") {
441
+ const k = time ? keyOfDate(t.date) : "all";
442
+ add(k, k, 1);
443
+ continue;
444
+ }
445
+ for (const ln of t.lines) {
446
+ if (ln.category == null || isSystemCategory(ln.category))
447
+ continue;
448
+ if (q.category && !(ln.category === q.category || ln.category.startsWith(q.category + "/")))
449
+ continue;
450
+ const kind = cats.get(ln.category)?.kind ?? "expense";
451
+ const v = q.metric === "spending" ? (kind === "expense" ? ln.amount : 0) : q.metric === "income" ? (kind === "income" ? -ln.amount : 0) : -ln.amount;
452
+ if (!v)
453
+ continue;
454
+ if (time) {
455
+ add(keyOfDate(t.date), keyOfDate(t.date), v);
456
+ continue;
457
+ }
458
+ const firstAccount = t.lines.find((x) => x.account != null)?.account ?? "(none)";
459
+ const keys = by === "category" ? [[ln.category, cats.get(ln.category)?.name ?? ln.category]]
460
+ : by === "top" ? [[topOf(ln.category), cats.get(topOf(ln.category))?.name ?? topOf(ln.category)]]
461
+ : by === "account" ? [[firstAccount, accName.get(firstAccount) ?? firstAccount]]
462
+ : by === "who" ? [[t.who ?? "(none)", t.who ?? "(none)"]]
463
+ : by === "event" ? [[t.event ?? "(none)", t.event ?? "(none)"]]
464
+ : (t.tags?.length ? t.tags : ["(none)"]).map((g) => [g, g]);
465
+ for (const [k, n] of keys)
466
+ add(k, n, v);
467
+ }
468
+ }
469
+ return out;
470
+ }
471
+ /** The data for a chart widget. */
472
+ export function series(l, q, asOf) {
473
+ const p = q.from && q.to ? { from: q.from, to: q.to } : resolvePeriod(q.period, asOf, firstActivity(l));
474
+ if (!isDate(p.from) || !isDate(p.to) || p.from > p.to)
475
+ throw new Error("bad period");
476
+ const by = q.by ?? (q.metric === "balance" ? "month" : "top");
477
+ const time = by === "day" || by === "week" || by === "month";
478
+ const { map: cats } = flattenCategories(l.categories);
479
+ const cur = seriesOnce(l, q, p, by, cats);
480
+ let points = [...cur.entries()].map(([key, r]) => ({ key, name: r.name, value: r.value }));
481
+ if (!time)
482
+ points = points.filter((x) => x.value !== 0).sort((a, b) => Math.abs(b.value) - Math.abs(a.value)).slice(0, q.limit ?? 10);
483
+ const total = q.metric === "balance" ? (points[points.length - 1]?.value ?? 0) : [...cur.values()].reduce((s, r) => s + r.value, 0);
484
+ const out = { query: q, period: p, by, total, points };
485
+ if (q.compare && q.metric !== "balance") {
486
+ if (q.compare === "previous") {
487
+ const len = daysBetween(p.from, p.to);
488
+ const wholeMonths = p.from === monthStart(p.from) && p.to === monthEnd(p.to);
489
+ let pp;
490
+ if (wholeMonths) {
491
+ const n = monthsBetween(p.from, p.to).length;
492
+ pp = { from: addMonths(p.from, -n), to: monthEnd(addMonths(p.from, -1)) };
493
+ }
494
+ else if (p.from === monthStart(p.from) && p.from.slice(0, 7) === p.to.slice(0, 7)) {
495
+ const f = addMonths(p.from, -1);
496
+ const [y, m] = parts(f);
497
+ pp = { from: f, to: `${f.slice(0, 7)}-${String(Math.min(parts(p.to)[2], daysInMonth(y, m))).padStart(2, "0")}` };
498
+ }
499
+ else
500
+ pp = { from: addDays(p.from, -len - 1), to: addDays(p.from, -1) };
501
+ const prev = seriesOnce(l, q, pp, by, cats);
502
+ out.compareTotal = [...prev.values()].reduce((s, r) => s + r.value, 0);
503
+ if (time) {
504
+ const pv = [...prev.values()];
505
+ points.forEach((pt, i) => (pt.compare = pv[i]?.value ?? 0));
506
+ }
507
+ else
508
+ points.forEach((pt) => (pt.compare = prev.get(pt.key)?.value ?? 0));
509
+ }
510
+ else {
511
+ const hist = Math.min(6, historyMonths(l, p.from));
512
+ if (hist > 0) {
513
+ const { windows, factor } = usualWindows(p, hist);
514
+ const acc = new Map();
515
+ let tot = 0;
516
+ for (const w of windows) {
517
+ for (const [k, r] of seriesOnce(l, q, w, time ? "month" : by, cats)) {
518
+ tot += r.value;
519
+ acc.set(k, (acc.get(k) ?? 0) + r.value);
520
+ }
521
+ }
522
+ out.compareTotal = Math.round(tot * factor);
523
+ if (time) {
524
+ // spread the usual total evenly over the buckets: a flat "usual" line per bucket
525
+ const per = points.length ? Math.round(out.compareTotal / points.length) : 0;
526
+ points.forEach((pt) => (pt.compare = per));
527
+ }
528
+ else
529
+ points.forEach((pt) => (pt.compare = Math.round((acc.get(pt.key) ?? 0) * factor)));
530
+ }
531
+ }
532
+ }
533
+ return out;
534
+ }
@@ -1,4 +1,5 @@
1
1
  import { parse as parseYaml } from "yaml";
2
+ import { MODULES } from "../modules/index.js";
2
3
  export const PATHS = {
3
4
  meta: "data/meta.yaml",
4
5
  accounts: "data/accounts.yaml",
@@ -109,8 +110,13 @@ export function loadLedger(files) {
109
110
  issues.push({ level: "error", file, message: "expected a list" });
110
111
  return [];
111
112
  };
113
+ const ext = {};
114
+ for (const m of MODULES)
115
+ if (m.load)
116
+ ext[m.name] = m.load(files, issues);
112
117
  return {
113
118
  ledger: {
119
+ ext,
114
120
  meta: meta && typeof meta === "object" ? meta : { format: 0, base: "VND" },
115
121
  assets: asArray(assets, PATHS.assets),
116
122
  accounts: asArray(accounts, PATHS.accounts),
@@ -20,5 +20,7 @@ export interface TypeDef {
20
20
  note?: string;
21
21
  }>;
22
22
  }
23
+ /** Core types: everyday money. The other types belong to modules (src/modules/<name>/types.ts). */
24
+ export declare const CORE_TYPES: Record<string, TypeDef>;
23
25
  export declare const TYPES: Record<string, TypeDef>;
24
26
  export declare function typeDef(type: string): TypeDef | undefined;
@@ -1,39 +1,21 @@
1
- export const TYPES = {
1
+ import { CARD_TYPES } from "../modules/cards/types.js";
2
+ import { DEPOSIT_TYPES } from "../modules/deposits/types.js";
3
+ import { INSURANCE_TYPES } from "../modules/insurance/types.js";
4
+ import { INVESTMENT_TYPES } from "../modules/investments/types.js";
5
+ import { LOAN_TYPES } from "../modules/loans/types.js";
6
+ /** Core types: everyday money. The other types belong to modules (src/modules/<name>/types.ts). */
7
+ export const CORE_TYPES = {
2
8
  cash: { label: { en: "Cash", vi: "Tiền mặt" }, liquid: true },
3
9
  bank: { label: { en: "Bank account", vi: "Tài khoản ngân hàng" }, liquid: true, details: { bank: { kind: "string" }, number_last4: { kind: "string" } } },
4
10
  ewallet: { label: { en: "E-wallet", vi: "Ví điện tử" }, liquid: true, details: { provider: { kind: "string" } } },
5
- credit_card: {
6
- label: { en: "Credit card", vi: "Thẻ tín dụng" },
7
- liability: true,
8
- details: {
9
- statement_day: { kind: "day", note: "day of month the statement closes" },
10
- due_day: { kind: "day", note: "day of month payment is due" },
11
- limit: { kind: "int" },
12
- bank: { kind: "string" },
13
- },
14
- },
15
- bnpl: { label: { en: "Buy now pay later", vi: "Mua trước trả sau" }, liability: true, details: { provider: { kind: "string" }, limit: { kind: "int" }, due_day: { kind: "day" } } },
16
- deposit: {
17
- label: { en: "Term deposit", vi: "Tiền gửi có kỳ hạn" },
18
- details: {
19
- bank: { kind: "string" },
20
- principal: { kind: "int" },
21
- rate: { kind: "number", note: "annual %" },
22
- term_months: { kind: "int" },
23
- start: { kind: "date" },
24
- maturity: { kind: "date" },
25
- rollover: { kind: "string", note: "none | principal | principal_interest" },
26
- },
27
- },
28
- savings_goal: { label: { en: "Savings goal", vi: "Mục tiêu tiết kiệm" }, details: { target: { kind: "int" }, by: { kind: "date" } } },
29
- gold: { label: { en: "Gold", vi: "Vàng" }, holdings: true },
30
- fund: { label: { en: "Fund", vi: "Chứng chỉ quỹ" }, holdings: true, details: { broker: { kind: "string" } } },
31
- stock: { label: { en: "Stocks", vi: "Cổ phiếu" }, holdings: true, details: { broker: { kind: "string" } } },
32
- etf: { label: { en: "ETF", vi: "Quỹ ETF" }, holdings: true, details: { broker: { kind: "string" } } },
33
- crypto: { label: { en: "Crypto", vi: "Tiền mã hoá" }, holdings: true },
34
- insurance: { label: { en: "Insurance", vi: "Bảo hiểm" }, details: { insurer: { kind: "string" }, cash_value: { kind: "int" } } },
35
- loan_given: { label: { en: "Loan given", vi: "Cho vay" }, details: { borrower: { kind: "string" }, rate: { kind: "number" } } },
36
- loan_taken: { label: { en: "Loan taken", vi: "Đi vay" }, liability: true, details: { lender: { kind: "string" }, rate: { kind: "number" } } },
11
+ };
12
+ export const TYPES = {
13
+ ...CORE_TYPES,
14
+ ...CARD_TYPES,
15
+ ...LOAN_TYPES,
16
+ ...DEPOSIT_TYPES,
17
+ ...INVESTMENT_TYPES,
18
+ ...INSURANCE_TYPES,
37
19
  other: { label: { en: "Other", vi: "Khác" } },
38
20
  };
39
21
  export function typeDef(type) {
@@ -7,7 +7,7 @@ export interface Period {
7
7
  export declare function periodOf(spec: string | Period): Period;
8
8
  /** The period of the same shape just before. Whole months/years step by month/year; other spans by days. */
9
9
  export declare function previousPeriod(p: Period): Period;
10
- export type GroupBy = "category" | "top" | "account" | "who" | "event" | "tag" | "month";
10
+ export type GroupBy = "category" | "top" | "account" | "who" | "event" | "tag" | "month" | "week" | "day";
11
11
  export interface ReportRow {
12
12
  key: string;
13
13
  name: string;
@@ -46,7 +46,15 @@ export declare function report(l: Ledger, period: string | Period, o?: ReportOpt
46
46
  export interface TxQuery {
47
47
  from?: ISODate;
48
48
  to?: ISODate;
49
- account?: string;
49
+ /** One account id, or several (e.g. every account in the "My money" pool). */
50
+ account?: string | string[];
51
+ who?: string;
52
+ event?: string;
53
+ tag?: string;
54
+ /** One transaction by id. */
55
+ tx?: string;
56
+ /** Hide transfers that stay inside this set of accounts (moves within the pool). */
57
+ hideWithin?: string[];
50
58
  category?: string;
51
59
  text?: string;
52
60
  min?: number;
@@ -59,9 +67,20 @@ export interface TxQuery {
59
67
  /** Lowercase, no Vietnamese diacritics (đ → d), for search. */
60
68
  export declare function fold(s: string): string;
61
69
  export declare function txSize(t: Transaction): number;
70
+ export interface TxTotals {
71
+ income: number;
72
+ expense: number;
73
+ net: number;
74
+ count: number;
75
+ }
62
76
  export declare function queryTransactions(l: Ledger, q: TxQuery): {
63
77
  total: number;
64
78
  items: Transaction[];
79
+ totals: TxTotals;
80
+ days: Record<ISODate, {
81
+ income: number;
82
+ expense: number;
83
+ }>;
65
84
  };
66
85
  /** Month keys "yyyy-mm" from first to last inclusive. */
67
86
  export declare function monthsBetween(from: ISODate, to: ISODate): string[];