ownledger 1.2.1 → 2.1.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 (166) hide show
  1. package/AGENTS.md +73 -1
  2. package/CHANGELOG.md +64 -0
  3. package/README.md +13 -0
  4. package/assets/apple-touch-icon.png +0 -0
  5. package/assets/icon-192.png +0 -0
  6. package/assets/icon-512.png +0 -0
  7. package/assets/icon-maskable-512.png +0 -0
  8. package/assets/index.html +15 -18
  9. package/assets/manifest.webmanifest +1 -1
  10. package/assets/static/Account-sw3qGLbB.js +1 -0
  11. package/assets/static/Accounts-DWyzX3qB.js +1 -0
  12. package/assets/static/Attention-DxV-4qdY.js +1 -0
  13. package/assets/static/ByCategory-B4P3ikmE.js +1 -0
  14. package/assets/static/CardDetail-CayBXBm-.js +1 -0
  15. package/assets/static/Cards-CVuOP8Bt.js +1 -0
  16. package/assets/static/Cards-XUBdWxyo.js +1 -0
  17. package/assets/static/CardsValue-EoW2jG_0.js +1 -0
  18. package/assets/static/Cashback-BibVYHf_.js +1 -0
  19. package/assets/static/CategoryIcon-HfjYhH1l.js +1 -0
  20. package/assets/static/CategoryPicker-BkmvzX2I.js +1 -0
  21. package/assets/static/ChartWidget-u09-whUU.js +1 -0
  22. package/assets/static/Combobox-xXeyjGgK.js +1 -0
  23. package/assets/static/Deposits-CLAda4dj.js +1 -0
  24. package/assets/static/DrillLink-Bvfam9FA.js +1 -0
  25. package/assets/static/Field-tKFmKDEF.js +1 -0
  26. package/assets/static/HomeEditor-4vxj5LMD.js +1 -0
  27. package/assets/static/Import-DwaaFpRJ.js +2 -0
  28. package/assets/static/IncomeSpending-RVDSxAK4.js +1 -0
  29. package/assets/static/KV-DMA1AlP-.js +1 -0
  30. package/assets/static/Left-C_4gTGSX.js +1 -0
  31. package/assets/static/Money-PfFNNDOw.js +1 -0
  32. package/assets/static/NetWorth-BSoseczC.js +1 -0
  33. package/assets/static/Pace-B8p-9174.js +1 -0
  34. package/assets/static/Panel-BnfWrw9R.js +1 -0
  35. package/assets/static/PinDialog-BqAU9Vh4.js +1 -0
  36. package/assets/static/Plans-2KuQH2_I.js +1 -0
  37. package/assets/static/Recent-Ccmb34bq.js +1 -0
  38. package/assets/static/Reports-Dd-dhclr.js +1 -0
  39. package/assets/static/Settings-BR8WBlen.js +1 -0
  40. package/assets/static/Transactions-BAuQ-6Eb.js +1 -0
  41. package/assets/static/TxRow-EKIIMQKa.js +1 -0
  42. package/assets/static/Unusual-CwFp8aA5.js +1 -0
  43. package/assets/static/Upcoming-B28roT9r.js +1 -0
  44. package/assets/static/WhichCard-B3kLc842.js +1 -0
  45. package/assets/static/arrow-up-D3gxUKLo.js +1 -0
  46. package/assets/static/bits-Dr2E0ObC.js +1 -0
  47. package/assets/static/button-rfwMVz0i.js +1 -0
  48. package/assets/static/cards-Bb5zjzRG.js +1 -0
  49. package/assets/static/charts-BqP7HKwP.js +65 -0
  50. package/assets/static/chevron-down-Co1w7ApZ.js +1 -0
  51. package/assets/static/chevron-right-Dqh3vs9Y.js +1 -0
  52. package/assets/static/createLucideIcon-flJrJK2p.js +1 -0
  53. package/assets/static/dialog-BuRqO4sc.js +1 -0
  54. package/assets/static/dist-B4_eGtNj.js +1 -0
  55. package/assets/static/dist-B7PR2b0C.js +1 -0
  56. package/assets/static/dist-BDn7ydjn.js +1 -0
  57. package/assets/static/dist-Dl-m8cc2.js +1 -0
  58. package/assets/static/drill-t1zr57xi.js +1 -0
  59. package/assets/static/es2015-DJh4h8NX.js +41 -0
  60. package/assets/static/fold-CGWYt9Iu.js +1 -0
  61. package/assets/static/index-eR1GkdC_.js +14 -0
  62. package/assets/static/index-iYMxgw-7.css +1 -0
  63. package/assets/static/queries-DZIMMe4i.js +1 -0
  64. package/assets/static/react-dom-wK_7mEjs.js +1 -0
  65. package/assets/static/select-eaSi9K-d.js +1 -0
  66. package/assets/static/shared-Box7on3B.js +1 -0
  67. package/assets/static/triangle-exclamation-point-CuL0XSJl.js +1 -0
  68. package/assets/static/useMutation-_Lw8xXWa.js +1 -0
  69. package/dist/cli/cards.d.ts +2 -0
  70. package/dist/cli/cards.js +86 -0
  71. package/dist/cli/check.js +7 -1
  72. package/dist/cli/dev.js +22 -2
  73. package/dist/cli/import.js +12 -2
  74. package/dist/cli/index.js +6 -0
  75. package/dist/cli/statements.d.ts +1 -0
  76. package/dist/cli/statements.js +231 -0
  77. package/dist/engine/actions.d.ts +5 -0
  78. package/dist/engine/actions.js +9 -5
  79. package/dist/engine/attention.d.ts +15 -0
  80. package/dist/engine/attention.js +63 -0
  81. package/dist/engine/check.js +8 -1
  82. package/dist/engine/dashboard.d.ts +72 -0
  83. package/dist/engine/dashboard.js +180 -0
  84. package/dist/engine/features.d.ts +20 -0
  85. package/dist/engine/features.js +37 -0
  86. package/dist/engine/index.d.ts +5 -0
  87. package/dist/engine/index.js +5 -0
  88. package/dist/engine/insights.d.ts +164 -0
  89. package/dist/engine/insights.js +534 -0
  90. package/dist/engine/load.js +6 -0
  91. package/dist/engine/registry.d.ts +2 -0
  92. package/dist/engine/registry.js +15 -33
  93. package/dist/engine/reports.d.ts +21 -2
  94. package/dist/engine/reports.js +51 -3
  95. package/dist/engine/schedules.d.ts +7 -84
  96. package/dist/engine/schedules.js +8 -207
  97. package/dist/engine/types.d.ts +2 -0
  98. package/dist/engine/write.d.ts +9 -0
  99. package/dist/engine/write.js +26 -5
  100. package/dist/import/mapping.js +6 -0
  101. package/dist/import/run.d.ts +7 -0
  102. package/dist/import/run.js +28 -1
  103. package/dist/modules/api.d.ts +22 -0
  104. package/dist/modules/api.js +16 -0
  105. package/dist/modules/cards/api.d.ts +3 -0
  106. package/dist/modules/cards/api.js +105 -0
  107. package/dist/modules/cards/engine.d.ts +42 -0
  108. package/dist/modules/cards/engine.js +102 -0
  109. package/dist/modules/cards/files.d.ts +11 -0
  110. package/dist/modules/cards/files.js +17 -0
  111. package/dist/modules/cards/index.d.ts +26 -0
  112. package/dist/modules/cards/index.js +304 -0
  113. package/dist/modules/cards/statements.d.ts +128 -0
  114. package/dist/modules/cards/statements.js +426 -0
  115. package/dist/modules/cards/terms.d.ts +105 -0
  116. package/dist/modules/cards/terms.js +194 -0
  117. package/dist/modules/cards/tracker.d.ts +36 -0
  118. package/dist/modules/cards/tracker.js +232 -0
  119. package/dist/modules/cards/types.d.ts +2 -0
  120. package/dist/modules/cards/types.js +16 -0
  121. package/dist/modules/deposits/engine.d.ts +14 -0
  122. package/dist/modules/deposits/engine.js +32 -0
  123. package/dist/modules/deposits/index.d.ts +2 -0
  124. package/dist/modules/deposits/index.js +24 -0
  125. package/dist/modules/deposits/types.d.ts +2 -0
  126. package/dist/modules/deposits/types.js +15 -0
  127. package/dist/modules/index.d.ts +5 -0
  128. package/dist/modules/index.js +10 -0
  129. package/dist/modules/insurance/index.d.ts +3 -0
  130. package/dist/modules/insurance/index.js +8 -0
  131. package/dist/modules/insurance/types.d.ts +2 -0
  132. package/dist/modules/insurance/types.js +3 -0
  133. package/dist/modules/investments/index.d.ts +2 -0
  134. package/dist/modules/investments/index.js +24 -0
  135. package/dist/modules/investments/types.d.ts +2 -0
  136. package/dist/modules/investments/types.js +7 -0
  137. package/dist/modules/loans/engine.d.ts +30 -0
  138. package/dist/modules/loans/engine.js +77 -0
  139. package/dist/modules/loans/index.d.ts +2 -0
  140. package/dist/modules/loans/index.js +27 -0
  141. package/dist/modules/loans/types.d.ts +2 -0
  142. package/dist/modules/loans/types.js +5 -0
  143. package/dist/modules/types.d.ts +39 -0
  144. package/dist/modules/types.js +1 -0
  145. package/dist/modules/util.d.ts +8 -0
  146. package/dist/modules/util.js +8 -0
  147. package/dist/node/scaffold.js +2 -2
  148. package/dist/node/statements.d.ts +64 -0
  149. package/dist/node/statements.js +218 -0
  150. package/dist/worker/api.d.ts +11 -1
  151. package/dist/worker/api.js +169 -13
  152. package/dist/worker/bestcard.d.ts +31 -9
  153. package/dist/worker/bestcard.js +78 -50
  154. package/dist/worker/github.d.ts +3 -1
  155. package/dist/worker/github.js +13 -2
  156. package/dist/worker/mcp.js +209 -30
  157. package/dist/worker/store.d.ts +2 -0
  158. package/dist/worker/store.js +7 -2
  159. package/dist/worker/tar.d.ts +2 -1
  160. package/dist/worker/tar.js +4 -1
  161. package/dist/worker/version.d.ts +1 -1
  162. package/dist/worker/version.js +1 -1
  163. package/package.json +28 -4
  164. package/presets/misa.mapping.yaml +7 -0
  165. package/assets/app.css +0 -61
  166. package/assets/app.js +0 -369
@@ -0,0 +1,194 @@
1
+ import { day, int, num, str } from "../util.js";
2
+ const per = (v) => (v === "month" ? "month" : "statement");
3
+ function amountPer(v) {
4
+ if (typeof v === "number" && Number.isInteger(v) && v > 0)
5
+ return { amount: v, per: "statement" };
6
+ if (v && typeof v === "object") {
7
+ const a = int(v.amount);
8
+ if (a !== undefined && a > 0)
9
+ return { amount: a, per: per(v.per) };
10
+ }
11
+ return null;
12
+ }
13
+ export function parseCashback(v) {
14
+ if (!v || typeof v !== "object" || Array.isArray(v))
15
+ return null;
16
+ const c = v;
17
+ const rules = [];
18
+ for (const r of Array.isArray(c.rules) ? c.rules : []) {
19
+ if (!r || typeof r !== "object")
20
+ continue;
21
+ const cats = r.categories;
22
+ const rate = num(r.rate) ?? null;
23
+ const list = Array.isArray(cats) ? cats.filter((x) => typeof x === "string") : typeof cats === "string" ? [cats] : [];
24
+ if (list.length)
25
+ rules.push({ categories: list, rate });
26
+ }
27
+ const paid = typeof c.paid_on === "string" ? c.paid_on : "next_statement";
28
+ const m = /^days_after:(\d+)$/.exec(paid);
29
+ return {
30
+ base: num(c.base) ?? 0,
31
+ rules,
32
+ cap: amountPer(c.cap),
33
+ min_spend: amountPer(c.min_spend),
34
+ spend_max: amountPer(c.spend_max),
35
+ paid_on: m ? { kind: "days_after", days: Number(m[1]) } : { kind: "next_statement" },
36
+ };
37
+ }
38
+ /** Terms from the card account's details, with what the card record (cards.yaml) adds for debit cards. */
39
+ export function termsOf(a, record) {
40
+ const d = { ...(record?.kind !== "credit" ? pickTerms(record) : {}), ...(a.details ?? {}) };
41
+ const fw = d.fee_waiver;
42
+ const spend = fw && typeof fw === "object" ? int(fw.spend) : undefined;
43
+ const feeMonth = int(d.fee_month);
44
+ return {
45
+ statementDay: day(d.statement_day) ?? null,
46
+ dueDay: day(d.due_day) ?? null,
47
+ limit: int(d.limit) ?? null,
48
+ bank: str(d.bank) ?? record?.bank ?? null,
49
+ last4: str(d.number_last4) ?? record?.last4 ?? null,
50
+ annualFee: int(d.annual_fee) ?? record?.annual_fee ?? null,
51
+ feeMonth: feeMonth && feeMonth >= 1 && feeMonth <= 12 ? feeMonth : null,
52
+ feeWaiver: spend && spend > 0 ? { spend, within: "year" } : null,
53
+ freeDaysMax: int(d.free_days_max) ?? null,
54
+ cashback: parseCashback(d.cashback),
55
+ };
56
+ }
57
+ function pickTerms(r) {
58
+ if (!r)
59
+ return {};
60
+ const out = {};
61
+ for (const k of ["statement_day", "cashback", "fee_month", "fee_waiver", "annual_fee"])
62
+ if (r[k] !== undefined)
63
+ out[k] = r[k];
64
+ return out;
65
+ }
66
+ /* ------------------------------------------------------------------ the cards list (data/cards.yaml) */
67
+ export const CARDS_FILE = "data/cards.yaml";
68
+ export const STATEMENTS_FILE = "data/cards/statements.yaml";
69
+ /** The cards module's data, loaded with the ledger (see ModuleDef.load). */
70
+ export function cardsData(l) {
71
+ return l.ext?.cards ?? { records: [], statements: [] };
72
+ }
73
+ export function recordFor(l, account) {
74
+ return cardsData(l).records.find((r) => r.account === account);
75
+ }
76
+ /* ------------------------------------------------------------------ codes in MISA wallet names */
77
+ /** Category emoji → category path. The owner's mapping can add its own (mapping key `card_emoji`). */
78
+ export const DEFAULT_CARD_EMOJI = {
79
+ "🛒": "shopping",
80
+ "🏋": "health/sport",
81
+ "🍿": "fun/entertainment",
82
+ "📞": "subscriptions",
83
+ "🍜": "food/eating-out",
84
+ "☕": "food/cafe",
85
+ "⛽": "transport/fuel",
86
+ "✈": "fun/trips",
87
+ };
88
+ const VS = "️?"; // optional emoji variation selector
89
+ /**
90
+ * Reads the card terms the owner writes into a wallet name: 🗓️7 statement day, 💸3 due day, category emoji
91
+ * before the first "•" (cashback categories), 🎉02/25 the card's anniversary (fee month), 1-5tr the cashback
92
+ * spend band, *4506 the last 4 digits. Anything that looks like a code but can't be read is a warning.
93
+ */
94
+ export function parseCardName(name, emoji = DEFAULT_CARD_EMOJI) {
95
+ const details = {};
96
+ const warnings = [];
97
+ const sd = new RegExp(`🗓${VS}\\s*(\\d{1,2})`, "u").exec(name);
98
+ if (sd) {
99
+ const v = Number(sd[1]);
100
+ if (v >= 1 && v <= 31)
101
+ details.statement_day = v;
102
+ else
103
+ warnings.push(`"${name}": statement day ${sd[1]} is not 1-31`);
104
+ }
105
+ else if (name.includes("🗓"))
106
+ warnings.push(`"${name}": 🗓️ without a day`);
107
+ const dd = new RegExp(`💸${VS}\\s*(\\d{1,2})`, "u").exec(name);
108
+ if (dd) {
109
+ const v = Number(dd[1]);
110
+ if (v >= 1 && v <= 31)
111
+ details.due_day = v;
112
+ else
113
+ warnings.push(`"${name}": due day ${dd[1]} is not 1-31`);
114
+ }
115
+ else if (name.includes("💸"))
116
+ warnings.push(`"${name}": 💸 without a day`);
117
+ const an = new RegExp(`🎉${VS}\\s*(\\d{1,2})/(\\d{2})`, "u").exec(name);
118
+ if (an) {
119
+ const m = Number(an[1]);
120
+ if (m >= 1 && m <= 12) {
121
+ details.fee_month = m;
122
+ details.anniversary = `20${an[2]}-${String(m).padStart(2, "0")}`;
123
+ }
124
+ else
125
+ warnings.push(`"${name}": 🎉 month ${an[1]} is not 1-12`);
126
+ }
127
+ else if (name.includes("🎉"))
128
+ warnings.push(`"${name}": 🎉 without MM/YY`);
129
+ const band = /(?:^|[\s•])(\d+(?:[.,]\d+)?)\s*-\s*(\d+(?:[.,]\d+)?)\s*tr\b/u.exec(name);
130
+ const cb = {};
131
+ if (band) {
132
+ const a = Math.round(Number(band[1].replace(",", ".")) * 1_000_000);
133
+ const b = Math.round(Number(band[2].replace(",", ".")) * 1_000_000);
134
+ if (a < b) {
135
+ cb.min_spend = { amount: a, per: "statement" };
136
+ cb.spend_max = { amount: b, per: "statement" };
137
+ }
138
+ else
139
+ warnings.push(`"${name}": spend band ${band[0].trim()} has min ≥ max`);
140
+ }
141
+ const last4 = /\*(\d{4})(?!\d)/.exec(name);
142
+ if (last4)
143
+ details.number_last4 = last4[1];
144
+ // category emoji: everything before the first "•" (or the whole name when there's no "•")
145
+ const head = name.split("•")[0];
146
+ const cats = [];
147
+ for (const ch of head.replace(/️/g, "")) {
148
+ if (!/\p{Extended_Pictographic}/u.test(ch) || ["🗓", "💸", "🎉"].includes(ch))
149
+ continue;
150
+ const path = emoji[ch];
151
+ if (path)
152
+ cats.push(path);
153
+ else
154
+ warnings.push(`"${name}": no category for ${ch} (add it to card_emoji in the mapping)`);
155
+ }
156
+ if (cats.length)
157
+ cb.rules = [{ categories: cats, rate: null }];
158
+ if (Object.keys(cb).length)
159
+ details.cashback = cb;
160
+ return { details, warnings };
161
+ }
162
+ /**
163
+ * Merges codes read from a wallet name into an account's details. `from_name` lists the keys a name gave;
164
+ * any other key already set is the owner's (through Claude or by hand) and is never overwritten by a re-import.
165
+ * Returns null when nothing changes.
166
+ */
167
+ export function mergeNameCodes(current, codes) {
168
+ const cur = current ?? {};
169
+ const fromName = new Set(Array.isArray(cur.from_name) ? cur.from_name : []);
170
+ const out = { ...cur };
171
+ let changed = false;
172
+ for (const [k, v] of Object.entries(codes)) {
173
+ if (cur[k] !== undefined && !fromName.has(k)) {
174
+ if (k !== "cashback" || typeof cur.cashback !== "object" || !cur.cashback)
175
+ continue;
176
+ // the owner's cashback terms win; a name only fills keys they haven't set
177
+ const merged = { ...v, ...cur.cashback };
178
+ if (JSON.stringify(merged) !== JSON.stringify(cur.cashback)) {
179
+ out.cashback = merged;
180
+ changed = true;
181
+ }
182
+ continue;
183
+ }
184
+ fromName.add(k);
185
+ if (JSON.stringify(cur[k]) !== JSON.stringify(v)) {
186
+ out[k] = v;
187
+ changed = true;
188
+ }
189
+ }
190
+ if (!changed)
191
+ return null;
192
+ out.from_name = [...fromName].sort();
193
+ return out;
194
+ }
@@ -0,0 +1,36 @@
1
+ import type { Ledger } from "../../engine/types.js";
2
+ import { type CardRecord } from "./terms.js";
3
+ /** The owner's answers to the mismatch list, applied on the next preview. */
4
+ export interface TrackerDecisions {
5
+ /** card id (tracker) → account id: the same card under another name. */
6
+ link?: Record<string, string>;
7
+ /** account id → closing date (yyyy-mm-dd). */
8
+ closed?: Record<string, string>;
9
+ /** card id → account id: a debit card recorded as a credit card in the ledger; the account becomes a bank account (in the pool), its card terms move to the card record. */
10
+ asDebit?: Record<string, string>;
11
+ /** account id → the full names the import source uses (from the mapping), to read card codes from. */
12
+ names?: Record<string, string[]>;
13
+ }
14
+ /**
15
+ * One-time load of a card tracker exported as CSV (a Notion "Bank cards" table: Type, Bank, Card status, Name,
16
+ * Credit balance, Số thẻ, Note, Anual fee, Close account, Benefits, Card brand, Apple Pay, Physic card,
17
+ * Issue date, Activate date, Detail link). Builds data/cards.yaml records, the credit card accounts' limits,
18
+ * and a list of what doesn't match the ledger, for the owner to confirm. Writes nothing itself.
19
+ */
20
+ export interface TrackerLoad {
21
+ records: CardRecord[];
22
+ /** Account changes the tracker implies (limits; closing cancelled cards). */
23
+ accountUpdates: {
24
+ id: string;
25
+ set: Record<string, unknown>;
26
+ why: string;
27
+ }[];
28
+ /** For the owner to confirm, one by one. */
29
+ mismatches: string[];
30
+ }
31
+ export declare function parseCsv(text: string): string[][];
32
+ /** "huỷ t12/26", "huỷ thẻ 2/27", "huỷ 05/26": the last month named after a cancel word, as yyyy-mm. */
33
+ export declare function cancelMonth(note: string): string | undefined;
34
+ /** "đã huỷ thẻ ngày 14/1/26" → 2026-01-14; "đã huỷ 05/26" → 2026-05 (day unknown). */
35
+ export declare function cancelledOn(note: string): string | undefined;
36
+ export declare function loadTracker(csv: string, l: Ledger, dec?: TrackerDecisions): TrackerLoad;
@@ -0,0 +1,232 @@
1
+ import { fold } from "../../engine/reports.js";
2
+ import { parseCardName } from "./terms.js";
3
+ export function parseCsv(text) {
4
+ const rows = [];
5
+ let row = [];
6
+ let cell = "";
7
+ let q = false;
8
+ for (let i = 0; i < text.length; i++) {
9
+ const c = text[i];
10
+ if (q) {
11
+ if (c === '"' && text[i + 1] === '"') {
12
+ cell += '"';
13
+ i++;
14
+ }
15
+ else if (c === '"')
16
+ q = false;
17
+ else
18
+ cell += c;
19
+ }
20
+ else if (c === '"')
21
+ q = true;
22
+ else if (c === ",") {
23
+ row.push(cell);
24
+ cell = "";
25
+ }
26
+ else if (c === "\n" || c === "\r") {
27
+ if (c === "\r" && text[i + 1] === "\n")
28
+ i++;
29
+ row.push(cell);
30
+ if (row.some((x) => x.trim()))
31
+ rows.push(row);
32
+ row = [];
33
+ cell = "";
34
+ }
35
+ else
36
+ cell += c;
37
+ }
38
+ row.push(cell);
39
+ if (row.some((x) => x.trim()))
40
+ rows.push(row);
41
+ return rows;
42
+ }
43
+ const money = (s) => {
44
+ const d = (s ?? "").replace(/[^\d]/g, "");
45
+ return d ? Number(d) : undefined;
46
+ };
47
+ const dmy = (s) => {
48
+ const m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec((s ?? "").trim());
49
+ return m ? `${m[3]}-${m[2].padStart(2, "0")}-${m[1].padStart(2, "0")}` : undefined;
50
+ };
51
+ const slug = (s) => fold(s).replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
52
+ /** "huỷ t12/26", "huỷ thẻ 2/27", "huỷ 05/26": the last month named after a cancel word, as yyyy-mm. */
53
+ export function cancelMonth(note) {
54
+ const re = /hu[ỷyỶ]\s*(?:th[ẻe]\s*)?(?:v[ậa]t\s*l[ýy]\s*)?(?:ng[àa]y\s*\d{1,2}\/)?t?(\d{1,2})\/(\d{2,4})/giu;
55
+ let last = null;
56
+ for (let m = re.exec(note); m; m = re.exec(note))
57
+ last = m;
58
+ if (!last)
59
+ return undefined;
60
+ const y = last[2].length === 2 ? `20${last[2]}` : last[2];
61
+ return `${y}-${last[1].padStart(2, "0")}`;
62
+ }
63
+ /** "đã huỷ thẻ ngày 14/1/26" → 2026-01-14; "đã huỷ 05/26" → 2026-05 (day unknown). */
64
+ export function cancelledOn(note) {
65
+ if (!/(đã|da)\s*hu[ỷy]/iu.test(note))
66
+ return undefined;
67
+ const d = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/.exec(note);
68
+ if (d)
69
+ return `${d[3].length === 2 ? `20${d[3]}` : d[3]}-${d[2].padStart(2, "0")}-${d[1].padStart(2, "0")}`;
70
+ return cancelMonth(note) ?? "unknown";
71
+ }
72
+ function last4Of(a) {
73
+ const d = a.details?.number_last4;
74
+ if (typeof d === "string")
75
+ return d;
76
+ return /\*(\d{4})(?!\d)/.exec(a.name)?.[1];
77
+ }
78
+ export function loadTracker(csv, l, dec = {}) {
79
+ const rows = parseCsv(csv.replace(/^/, ""));
80
+ const head = rows.shift()?.map((h) => fold(h.trim())) ?? [];
81
+ const col = (r, ...names) => {
82
+ for (const n of names) {
83
+ const i = head.indexOf(fold(n));
84
+ if (i >= 0)
85
+ return (r[i] ?? "").trim();
86
+ }
87
+ return "";
88
+ };
89
+ const out = { records: [], accountUpdates: [], mismatches: [] };
90
+ const cards = l.accounts.filter((a) => a.type === "credit_card");
91
+ const matched = new Set();
92
+ const ids = new Set();
93
+ for (const r of rows) {
94
+ if (!col(r, "Type") && !col(r, "Name"))
95
+ continue; // a totals row
96
+ const type = fold(col(r, "Type"));
97
+ const kind = type.startsWith("credit") ? "credit" : type.startsWith("debit") ? "debit" : "atm";
98
+ const bank = col(r, "Bank");
99
+ const name = col(r, "Name") || `${bank} ${kind}`;
100
+ const note = col(r, "Note");
101
+ const number = col(r, "Số thẻ", "So the", "Number");
102
+ const last4 = /(\d{4})\s*$/.exec(number)?.[1];
103
+ const statusRaw = fold(col(r, "Card status"));
104
+ let status = statusRaw.includes("lock") ? "locked" : statusRaw.includes("inactiv") ? "inactive" : "active";
105
+ const cancelled = cancelledOn(note);
106
+ if (cancelled)
107
+ status = "cancelled";
108
+ let id = slug(name) || slug(`${bank}-${kind}`);
109
+ for (let i = 2; ids.has(id); i++)
110
+ id = `${slug(name)}-${i}`;
111
+ ids.add(id);
112
+ const brand = fold(col(r, "Card brand"));
113
+ const phys = fold(col(r, "Physic card", "Physical card"));
114
+ const rec = {
115
+ id,
116
+ kind,
117
+ bank,
118
+ name,
119
+ ...(brand ? { network: brand } : {}),
120
+ ...(last4 ? { last4 } : {}),
121
+ status,
122
+ ...(dmy(col(r, "Issue date")) ? { issued: dmy(col(r, "Issue date")) } : {}),
123
+ ...(dmy(col(r, "Activate date")) ? { activated: dmy(col(r, "Activate date")) } : {}),
124
+ ...(cancelled && cancelled !== "unknown" && cancelled.length === 10 ? { cancelled } : {}),
125
+ ...(phys ? { physical: phys.includes("both") ? "both" : phys.includes("non") ? "virtual" : "physical" } : {}),
126
+ ...(col(r, "Apple Pay") ? { apple_pay: fold(col(r, "Apple Pay")) === "yes" } : {}),
127
+ ...(money(col(r, "Anual fee", "Annual fee")) !== undefined ? { annual_fee: money(col(r, "Anual fee", "Annual fee")) } : {}),
128
+ ...(money(col(r, "Close account")) !== undefined ? { close_fee: money(col(r, "Close account")) } : {}),
129
+ ...(money(col(r, "Benefits")) !== undefined ? { benefits: money(col(r, "Benefits")) } : {}),
130
+ ...(col(r, "Detail link") ? { fees_url: col(r, "Detail link") } : {}),
131
+ ...(note ? { note } : {}),
132
+ };
133
+ const plan = !cancelled ? cancelMonth(note) : undefined;
134
+ if (plan)
135
+ rec.cancel_plan = { by: plan, note };
136
+ if (/(giữ|giu)\s*h[ạa]n\s*m[ứu]c/iu.test(note))
137
+ rec.keep_for_limit = true;
138
+ const debitAcc = dec.asDebit?.[id];
139
+ if (debitAcc) {
140
+ const acc = l.accounts.find((a) => a.id === debitAcc);
141
+ if (!acc)
142
+ out.mismatches.push(`asDebit ${id}=${debitAcc}: no such account`);
143
+ else {
144
+ matched.add(acc.id);
145
+ rec.kind = "debit";
146
+ rec.account = acc.id;
147
+ const names = [...(dec.names?.[acc.id] ?? []), acc.name].sort((x, y) => [...y].length - [...x].length);
148
+ const codes = parseCardName(names[0]).details;
149
+ const d = { ...(acc.details ?? {}) };
150
+ const sd = d.statement_day ?? codes.statement_day;
151
+ if (sd !== undefined)
152
+ rec.statement_day = sd;
153
+ const cb = d.cashback ?? codes.cashback;
154
+ if (cb)
155
+ rec.cashback = cb;
156
+ if (codes.fee_month)
157
+ rec.fee_month = codes.fee_month;
158
+ for (const k of ["statement_day", "due_day", "cashback", "limit", "fee_month", "anniversary", "from_name"])
159
+ delete d[k];
160
+ out.accountUpdates.push({ id: acc.id, set: { type: "bank", details: Object.keys(d).length ? d : null }, why: `a debit card (${name}): ${acc.id} becomes a bank account in "My money"; its cycle start day and cashback terms move to the card record` });
161
+ }
162
+ }
163
+ else if (kind === "credit") {
164
+ // match: the owner's link, last 4 digits, then the name, then the only credit card of that bank
165
+ const linked = dec.link?.[id] ? cards.find((a) => a.id === dec.link[id]) : undefined;
166
+ let acc = linked ?? (last4 ? cards.find((a) => last4Of(a) === last4) : undefined);
167
+ let how = linked ? "your link" : "last 4 digits";
168
+ if (!acc) {
169
+ acc = cards.find((a) => fold(a.name).replace(/\s*\*\d{4}.*/, "").replace(/\s+/g, "") === fold(name).replace(/\s+/g, ""));
170
+ how = "name";
171
+ }
172
+ if (!acc) {
173
+ const sameBank = cards.filter((a) => !matched.has(a.id) && fold(a.name).split(/\s+/)[0] === fold(bank).split(/\s+/)[0]);
174
+ const known = sameBank.filter((a) => last4Of(a));
175
+ if (last4 && sameBank.length && known.length === sameBank.length) {
176
+ out.mismatches.push(`"${name}" (tracker, *${last4}) is not in the ledger (no ${bank} card ends in ${last4})`);
177
+ }
178
+ else if (sameBank.length === 1) {
179
+ acc = sameBank[0];
180
+ how = "bank (only one card of this bank in the ledger)";
181
+ out.mismatches.push(`"${name}" (tracker) ↔ "${acc.name}" (${acc.id}) matched by ${how}: confirm they're the same card`);
182
+ }
183
+ else if (sameBank.length > 1) {
184
+ out.mismatches.push(`"${name}" (tracker): which of ${sameBank.map((a) => `${a.name} (${a.id})`).join(", ")} is it?`);
185
+ }
186
+ }
187
+ if (acc) {
188
+ matched.add(acc.id);
189
+ rec.account = acc.id;
190
+ const limit = money(col(r, "Credit balance"));
191
+ if (limit) {
192
+ if (acc.details?.limit !== limit)
193
+ out.accountUpdates.push({ id: acc.id, set: { details: { ...(acc.details ?? {}), limit } }, why: `limit ${limit} from the tracker ("Credit balance")` });
194
+ }
195
+ else
196
+ out.mismatches.push(`${acc.name} (${acc.id}): no limit in the tracker`);
197
+ if (status === "cancelled" && !acc.closed) {
198
+ const day = dec.closed?.[acc.id] ?? (cancelled && cancelled.length === 10 ? cancelled : undefined);
199
+ if (day)
200
+ out.accountUpdates.push({ id: acc.id, set: { closed: day }, why: `cancelled on ${day} (tracker note: "${note}")` });
201
+ else
202
+ out.mismatches.push(`${acc.name} (${acc.id}) is cancelled (${cancelled === "unknown" ? "no date" : cancelled}) but still open: which day was it closed?`);
203
+ }
204
+ }
205
+ else if (!out.mismatches.some((m) => m.startsWith(`"${name}"`)))
206
+ out.mismatches.push(`"${name}" (tracker, credit) is not in the ledger`);
207
+ }
208
+ else {
209
+ const same = cards.find((a) => fold(a.name).startsWith(fold(name)) && !matched.has(a.id));
210
+ if (same)
211
+ out.mismatches.push(`"${name}" is a ${kind} card in the tracker but ${same.name} (${same.id}) is a credit card in the ledger: --as-debit ${id}=${same.id} makes it a bank account with this card's cashback`);
212
+ }
213
+ out.records.push(rec);
214
+ }
215
+ const merged = new Map();
216
+ for (const u of out.accountUpdates) {
217
+ const m = merged.get(u.id);
218
+ if (!m)
219
+ merged.set(u.id, { ...u, set: { ...u.set } });
220
+ else {
221
+ m.set = { ...m.set, ...u.set, ...(m.set.details && u.set.details ? { details: { ...m.set.details, ...u.set.details } } : {}) };
222
+ m.why += `; ${u.why}`;
223
+ }
224
+ }
225
+ out.accountUpdates = [...merged.values()];
226
+ for (const a of cards) {
227
+ if (matched.has(a.id) || a.closed || Object.values(dec.asDebit ?? {}).includes(a.id))
228
+ continue;
229
+ out.mismatches.push(`${a.name} (${a.id}) is a credit card in the ledger but not in the tracker`);
230
+ }
231
+ return out;
232
+ }
@@ -0,0 +1,2 @@
1
+ import type { TypeDef } from "../../engine/registry.js";
2
+ export declare const CARD_TYPES: Record<string, TypeDef>;
@@ -0,0 +1,16 @@
1
+ export const CARD_TYPES = {
2
+ credit_card: {
3
+ label: { en: "Credit card", vi: "Thẻ tín dụng" },
4
+ liability: true,
5
+ details: {
6
+ statement_day: { kind: "day", note: "day of month the statement closes" },
7
+ due_day: { kind: "day", note: "day of month payment is due" },
8
+ limit: { kind: "int" },
9
+ bank: { kind: "string" },
10
+ number_last4: { kind: "string" },
11
+ annual_fee: { kind: "int" },
12
+ fee_month: { kind: "int", note: "month (1-12) the annual fee is charged" },
13
+ free_days_max: { kind: "int" },
14
+ },
15
+ },
16
+ };
@@ -0,0 +1,14 @@
1
+ import type { ISODate, Ledger } from "../../engine/types.js";
2
+ export interface DepositStatus {
3
+ account: string;
4
+ name: string;
5
+ balance: number;
6
+ principal: number;
7
+ rate: number | null;
8
+ start: ISODate | null;
9
+ maturity: ISODate | null;
10
+ daysToMaturity: number | null;
11
+ interestAtMaturity: number | null;
12
+ rollover: string | null;
13
+ }
14
+ export declare function deposits(l: Ledger, asOf: ISODate): DepositStatus[];
@@ -0,0 +1,32 @@
1
+ import { holdingsAt } from "../../engine/balances.js";
2
+ import { addMonths, daysBetween } from "../../engine/dates.js";
3
+ import { date, isOpen as open, num } from "../util.js";
4
+ export function deposits(l, asOf) {
5
+ const hs = holdingsAt(l, asOf);
6
+ const out = [];
7
+ for (const a of l.accounts) {
8
+ if (a.type !== "deposit" || !open(a, asOf))
9
+ continue;
10
+ const d = a.details ?? {};
11
+ const balance = hs.get(a.id)?.amount ?? 0;
12
+ const principal = num(d.principal) ?? balance;
13
+ const rate = num(d.rate) ?? null;
14
+ const start = date(d.start) ?? date(a.opened) ?? null;
15
+ const term = num(d.term_months);
16
+ const maturity = date(d.maturity) ?? (start && term ? addMonths(start, term) : null);
17
+ const interest = rate !== null && start && maturity ? Math.round((principal * rate * daysBetween(start, maturity)) / 36500) : null;
18
+ out.push({
19
+ account: a.id,
20
+ name: a.name,
21
+ balance,
22
+ principal,
23
+ rate,
24
+ start,
25
+ maturity,
26
+ daysToMaturity: maturity ? daysBetween(asOf, maturity) : null,
27
+ interestAtMaturity: interest,
28
+ rollover: typeof d.rollover === "string" ? d.rollover : null,
29
+ });
30
+ }
31
+ return out.sort((a, b) => (a.maturity ?? "9999") < (b.maturity ?? "9999") ? -1 : 1);
32
+ }
@@ -0,0 +1,2 @@
1
+ import type { ModuleDef } from "../types.js";
2
+ export declare const depositsModule: ModuleDef;
@@ -0,0 +1,24 @@
1
+ import { isOpen } from "../util.js";
2
+ import { deposits } from "./engine.js";
3
+ import { DEPOSIT_TYPES } from "./types.js";
4
+ export const depositsModule = {
5
+ name: "deposits",
6
+ types: DEPOSIT_TYPES,
7
+ on: (l, asOf) => l.accounts.some((a) => a.type in DEPOSIT_TYPES && isOpen(a, asOf)),
8
+ attention(l, asOf) {
9
+ return deposits(l, asOf)
10
+ .filter((d) => d.daysToMaturity !== null && d.daysToMaturity <= 30 && d.maturity)
11
+ .map((d) => ({
12
+ kind: d.daysToMaturity < 0 ? "deposit_matured" : "deposit_maturing",
13
+ module: "deposits",
14
+ severity: d.daysToMaturity <= 7 ? "amber" : "info",
15
+ date: d.maturity,
16
+ title: `Deposit ${d.name} matures on ${d.maturity}`,
17
+ amount: d.balance + (d.interestAtMaturity ?? 0),
18
+ account: d.account,
19
+ name: d.name,
20
+ days: d.daysToMaturity,
21
+ link: `#/transactions?account=${encodeURIComponent(d.account)}`,
22
+ }));
23
+ },
24
+ };
@@ -0,0 +1,2 @@
1
+ import type { TypeDef } from "../../engine/registry.js";
2
+ export declare const DEPOSIT_TYPES: Record<string, TypeDef>;
@@ -0,0 +1,15 @@
1
+ export const DEPOSIT_TYPES = {
2
+ deposit: {
3
+ label: { en: "Term deposit", vi: "Tiền gửi có kỳ hạn" },
4
+ details: {
5
+ bank: { kind: "string" },
6
+ principal: { kind: "int" },
7
+ rate: { kind: "number", note: "annual %" },
8
+ term_months: { kind: "int" },
9
+ start: { kind: "date" },
10
+ maturity: { kind: "date" },
11
+ rollover: { kind: "string", note: "none | principal | principal_interest" },
12
+ },
13
+ },
14
+ savings_goal: { label: { en: "Savings goal", vi: "Mục tiêu tiết kiệm" }, details: { target: { kind: "int" }, by: { kind: "date" } } },
15
+ };
@@ -0,0 +1,5 @@
1
+ import type { ModuleDef } from "./types.js";
2
+ export type { AttentionItem, ModuleDef } from "./types.js";
3
+ /** Built-in modules, in the order their items and nav entries appear. */
4
+ export declare const MODULES: ModuleDef[];
5
+ export declare function moduleByName(name: string): ModuleDef | undefined;
@@ -0,0 +1,10 @@
1
+ import { cardsModule } from "./cards/index.js";
2
+ import { depositsModule } from "./deposits/index.js";
3
+ import { insuranceModule } from "./insurance/index.js";
4
+ import { investmentsModule } from "./investments/index.js";
5
+ import { loansModule } from "./loans/index.js";
6
+ /** Built-in modules, in the order their items and nav entries appear. */
7
+ export const MODULES = [cardsModule, loansModule, depositsModule, investmentsModule, insuranceModule];
8
+ export function moduleByName(name) {
9
+ return MODULES.find((m) => m.name === name);
10
+ }
@@ -0,0 +1,3 @@
1
+ import type { ModuleDef } from "../types.js";
2
+ /** Premiums due come through plans (kind insurance_premium) in "Needs you" via the loans module's plan items. */
3
+ export declare const insuranceModule: ModuleDef;
@@ -0,0 +1,8 @@
1
+ import { isOpen } from "../util.js";
2
+ import { INSURANCE_TYPES } from "./types.js";
3
+ /** Premiums due come through plans (kind insurance_premium) in "Needs you" via the loans module's plan items. */
4
+ export const insuranceModule = {
5
+ name: "insurance",
6
+ types: INSURANCE_TYPES,
7
+ on: (l, asOf) => l.accounts.some((a) => a.type in INSURANCE_TYPES && isOpen(a, asOf)) || l.plans.some((p) => p.kind === "insurance_premium"),
8
+ };
@@ -0,0 +1,2 @@
1
+ import type { TypeDef } from "../../engine/registry.js";
2
+ export declare const INSURANCE_TYPES: Record<string, TypeDef>;
@@ -0,0 +1,3 @@
1
+ export const INSURANCE_TYPES = {
2
+ insurance: { label: { en: "Insurance", vi: "Bảo hiểm" }, details: { insurer: { kind: "string" }, cash_value: { kind: "int" } } },
3
+ };
@@ -0,0 +1,2 @@
1
+ import type { ModuleDef } from "../types.js";
2
+ export declare const investmentsModule: ModuleDef;
@@ -0,0 +1,24 @@
1
+ import { accountValues } from "../../engine/balances.js";
2
+ import { isOpen } from "../util.js";
3
+ import { INVESTMENT_TYPES } from "./types.js";
4
+ export const investmentsModule = {
5
+ name: "investments",
6
+ types: INVESTMENT_TYPES,
7
+ on: (l, asOf) => l.accounts.some((a) => isOpen(a, asOf) && (a.type in INVESTMENT_TYPES || (a.asset && a.asset !== l.meta.base))),
8
+ attention(l, asOf) {
9
+ const unpriced = accountValues(l, asOf).filter((v) => !v.priced && (v.qty ?? 0) !== 0 && isOpen(v.account, asOf));
10
+ if (!unpriced.length)
11
+ return [];
12
+ return [{
13
+ kind: "unpriced",
14
+ module: "investments",
15
+ severity: "info",
16
+ date: asOf,
17
+ title: `${unpriced.length} holding(s) have no price: valued at cost (${unpriced.map((v) => v.account.id).join(", ")})`,
18
+ count: unpriced.length,
19
+ params: { accounts: unpriced.map((v) => v.account.name).join(", "), assets: [...new Set(unpriced.map((v) => v.asset))].join(", ") },
20
+ link: "#/accounts",
21
+ ask: true,
22
+ }];
23
+ },
24
+ };
@@ -0,0 +1,2 @@
1
+ import type { TypeDef } from "../../engine/registry.js";
2
+ export declare const INVESTMENT_TYPES: Record<string, TypeDef>;