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,128 @@
1
+ import type { Category, ISODate, Ledger, Transaction } from "../../engine/types.js";
2
+ import { type CardTerms } from "./terms.js";
3
+ /** The statement date in month (y, m). */
4
+ export declare const closeIn: (y: number, m: number, sd: number) => string;
5
+ /** The first statement date on or after d. */
6
+ export declare function closeOnOrAfter(d: ISODate, sd: number): ISODate;
7
+ /** The statement date just before close c. */
8
+ export declare function prevClose(c: ISODate, sd: number): ISODate;
9
+ /** The next statement date after close c. */
10
+ export declare function nextClose(c: ISODate, sd: number): ISODate;
11
+ /** The due date of the statement that closes on c (the first due day after it). */
12
+ export declare function dueAfter(c: ISODate, dd: number): ISODate;
13
+ /** Pay a purchase made on `date` by this date to pay no interest: the due date of the statement it falls into. */
14
+ export declare function interestFreeUntil(t: CardTerms, date: ISODate): ISODate | null;
15
+ export type LineKind = "purchase" | "fee" | "charge" | "payment" | "refund" | "cashback" | "adjust";
16
+ /** What one transaction does to a card account (by its card lines and the other lines). */
17
+ export declare function lineKind(t: Transaction, account: string, cats: Map<string, Category>): {
18
+ kind: LineKind;
19
+ amount: number;
20
+ } | null;
21
+ export declare function isAnnualFee(t: Transaction): boolean;
22
+ export interface Statement {
23
+ from: ISODate;
24
+ close: ISODate;
25
+ open: boolean;
26
+ opening: number;
27
+ purchases: number;
28
+ refunds: number;
29
+ cashback: number;
30
+ fees: number;
31
+ charges: number;
32
+ payments: number;
33
+ adjust: number;
34
+ closing: number;
35
+ /** Part of the closing balance that is 0% instalments not billed yet. */
36
+ deferred: number;
37
+ /** What this statement asks you to pay: the bank's amount when entered, else closing − deferred. */
38
+ amountDue: number;
39
+ bank: number | null;
40
+ bankDiff: number | null;
41
+ due: ISODate | null;
42
+ paidByDue: number;
43
+ paid: number;
44
+ toPay: number;
45
+ status: "none" | "paid" | "due" | "late" | "partly" | "unpaid" | "open";
46
+ }
47
+ /** Every statement period of a credit card from its first transaction to asOf (the last one open). */
48
+ export declare function statements(l: Ledger, account: string, asOf: ISODate): Statement[];
49
+ export interface CashbackPeriod {
50
+ from: ISODate;
51
+ close: ISODate;
52
+ open: boolean;
53
+ spend: number;
54
+ byRate: {
55
+ rate: number | null;
56
+ spend: number;
57
+ categories: string[];
58
+ }[];
59
+ expected: number;
60
+ incomplete: boolean;
61
+ minSpend: number | null;
62
+ minMet: boolean;
63
+ needForMin: number;
64
+ cap: number | null;
65
+ capLeft: number | null;
66
+ received: number;
67
+ payBy: ISODate;
68
+ }
69
+ /** Expected against received cashback, per statement (or cashback cycle), for a card with cashback terms. */
70
+ export declare function cashback(l: Ledger, account: string, asOf: ISODate): CashbackPeriod[];
71
+ export interface BestCard {
72
+ account: string;
73
+ name: string;
74
+ rate: number | null;
75
+ earn: number | null;
76
+ capLeft: number | null;
77
+ minSpendShort: number;
78
+ payBy: ISODate | null;
79
+ freeDays: number | null;
80
+ limitLeft: number | null;
81
+ reason: string;
82
+ }
83
+ export declare function bestCard(l: Ledger, q: {
84
+ category: string;
85
+ amount?: number;
86
+ date: ISODate;
87
+ }): BestCard[];
88
+ export interface FeeWaiverStatus {
89
+ account: string;
90
+ name: string;
91
+ target: number;
92
+ yearFrom: ISODate;
93
+ deadline: ISODate;
94
+ spent: number;
95
+ needed: number;
96
+ perMonth: number;
97
+ daysLeft: number;
98
+ onTrack: boolean;
99
+ met: boolean;
100
+ }
101
+ /** Card year: from the 1st of the fee month on or before asOf, for 12 months. */
102
+ export declare function cardYear(feeMonth: number, asOf: ISODate): {
103
+ from: ISODate;
104
+ to: ISODate;
105
+ };
106
+ export declare function feeWaiver(l: Ledger, account: string, asOf: ISODate): FeeWaiverStatus | null;
107
+ export interface CardValue {
108
+ card: string;
109
+ account: string | null;
110
+ name: string;
111
+ kind: "credit" | "debit" | "atm";
112
+ status: string;
113
+ benefits: number;
114
+ cashback: number;
115
+ fees: number;
116
+ feesFrom: "ledger" | "record" | "none";
117
+ closeFee: number;
118
+ net: number;
119
+ last12: {
120
+ benefits: number;
121
+ cashback: number;
122
+ fees: number;
123
+ net: number;
124
+ };
125
+ feeMonth: number | null;
126
+ }
127
+ /** benefits + cashback received − annual fees − close fee, since the card was issued and over the last 12 months. */
128
+ export declare function cardValues(l: Ledger, asOf: ISODate): CardValue[];
@@ -0,0 +1,426 @@
1
+ import { holdingsAt } from "../../engine/balances.js";
2
+ import { flattenCategories, isSystemCategory, topOf } from "../../engine/categories.js";
3
+ import { addDays, addMonths, dayIn, daysBetween, monthStart, parts } from "../../engine/dates.js";
4
+ import { dueDates } from "../loans/engine.js";
5
+ import { isOpen } from "../util.js";
6
+ import { cardsData, recordFor, termsOf } from "./terms.js";
7
+ /* ------------------------------------------------------------------ dates */
8
+ /** The statement date in month (y, m). */
9
+ export const closeIn = (y, m, sd) => dayIn(y, m, sd);
10
+ /** The first statement date on or after d. */
11
+ export function closeOnOrAfter(d, sd) {
12
+ const [y, m] = parts(d);
13
+ const c = closeIn(y, m, sd);
14
+ if (c >= d)
15
+ return c;
16
+ const [ny, nm] = parts(addMonths(monthStart(d), 1));
17
+ return closeIn(ny, nm, sd);
18
+ }
19
+ /** The statement date just before close c. */
20
+ export function prevClose(c, sd) {
21
+ const [y, m] = parts(addMonths(monthStart(c), -1));
22
+ return closeIn(y, m, sd);
23
+ }
24
+ /** The next statement date after close c. */
25
+ export function nextClose(c, sd) {
26
+ const [y, m] = parts(addMonths(monthStart(c), 1));
27
+ return closeIn(y, m, sd);
28
+ }
29
+ /** The due date of the statement that closes on c (the first due day after it). */
30
+ export function dueAfter(c, dd) {
31
+ const [y, m] = parts(c);
32
+ const d = dayIn(y, m, dd);
33
+ if (d > c)
34
+ return d;
35
+ const [ny, nm] = parts(addMonths(monthStart(c), 1));
36
+ return dayIn(ny, nm, dd);
37
+ }
38
+ /** Pay a purchase made on `date` by this date to pay no interest: the due date of the statement it falls into. */
39
+ export function interestFreeUntil(t, date) {
40
+ if (!t.statementDay || !t.dueDay)
41
+ return null;
42
+ return dueAfter(closeOnOrAfter(date, t.statementDay), t.dueDay);
43
+ }
44
+ const FEE_TOP = new Set(["bank-fees"]);
45
+ const ANNUAL_FEE_RE = /thường niên|thuong nien|phí năm|annual fee|ptn\b/i;
46
+ /** What one transaction does to a card account (by its card lines and the other lines). */
47
+ export function lineKind(t, account, cats) {
48
+ let amount = 0;
49
+ for (const ln of t.lines)
50
+ if (ln.account === account)
51
+ amount += ln.amount;
52
+ if (!amount)
53
+ return null;
54
+ const catLines = t.lines.filter((ln) => ln.category != null);
55
+ const real = catLines.filter((ln) => !isSystemCategory(ln.category));
56
+ if (catLines.length && !real.length)
57
+ return { kind: "adjust", amount };
58
+ if (amount < 0) {
59
+ if (real.some((ln) => FEE_TOP.has(topOf(ln.category))))
60
+ return { kind: "fee", amount: -amount };
61
+ if (real.length)
62
+ return { kind: "purchase", amount: -amount };
63
+ return { kind: "charge", amount: -amount }; // money moved out of the card to another account (cash advance, transfer)
64
+ }
65
+ if (real.some((ln) => topOf(ln.category) === "cashback" || (cats.get(ln.category)?.kind === "income")))
66
+ return { kind: "cashback", amount };
67
+ if (real.length)
68
+ return { kind: "refund", amount };
69
+ return { kind: "payment", amount };
70
+ }
71
+ export function isAnnualFee(t) {
72
+ return t.lines.some((ln) => ln.category && FEE_TOP.has(topOf(ln.category))) && ANNUAL_FEE_RE.test([t.note, ...t.lines.map((l) => l.note)].filter(Boolean).join(" "));
73
+ }
74
+ function instalmentsOf(l, account) {
75
+ const byId = new Map(l.transactions.map((t) => [t.id, t]));
76
+ const out = [];
77
+ for (const p of l.plans) {
78
+ if (p.kind !== "instalment" || p.account !== account || !p.count)
79
+ continue;
80
+ const src = typeof p.source === "string" ? byId.get(p.source) : undefined;
81
+ const principalPer = p.amount ?? (p.principal !== undefined ? Math.round(p.principal / p.count) : 0);
82
+ out.push({ plan: p, sourceDate: src?.date ?? p.start, principalPer, count: p.count });
83
+ }
84
+ return out;
85
+ }
86
+ /** Instalment principal included in the balance at close c but billed on later statements. */
87
+ function deferredAt(ins, c) {
88
+ let s = 0;
89
+ for (const i of ins) {
90
+ if (i.sourceDate > c)
91
+ continue;
92
+ const billed = dueDates(i.plan, c).length;
93
+ s += i.principalPer * Math.max(0, i.count - billed);
94
+ }
95
+ return s;
96
+ }
97
+ /** Every statement period of a credit card from its first transaction to asOf (the last one open). */
98
+ export function statements(l, account, asOf) {
99
+ const a = l.accounts.find((x) => x.id === account);
100
+ if (!a)
101
+ throw new Error(`no account ${account}`);
102
+ const t = termsOf(a, recordFor(l, account));
103
+ const sd = t.statementDay;
104
+ if (!sd)
105
+ return [];
106
+ const { map: cats } = flattenCategories(l.categories);
107
+ const txs = l.transactions.filter((x) => !x.void && x.date <= asOf && x.lines.some((ln) => ln.account === account));
108
+ if (!txs.length)
109
+ return [];
110
+ const bankAmounts = new Map(cardsData(l).statements.filter((s) => s.account === account).map((s) => [s.statement_date, s.amount]));
111
+ const ins = instalmentsOf(l, account);
112
+ // owed at the end of each day, from one pass
113
+ const owedAt = (d) => -(holdingsAt(l, d).get(account)?.amount ?? 0);
114
+ const closes = [];
115
+ for (let c = closeOnOrAfter(txs[0].date, sd); c <= asOf; c = nextClose(c, sd))
116
+ closes.push(c);
117
+ const out = [];
118
+ const periods = closes.map((c) => ({ from: addDays(prevClose(c, sd), 1), close: c, open: false }));
119
+ const lastClose = closes[closes.length - 1];
120
+ if (!lastClose || lastClose < asOf)
121
+ periods.push({ from: lastClose ? addDays(lastClose, 1) : addDays(prevClose(closeOnOrAfter(txs[0].date, sd), sd), 1), close: asOf, open: true });
122
+ for (const p of periods) {
123
+ const s = {
124
+ from: p.from, close: p.close, open: p.open, opening: owedAt(addDays(p.from, -1)), purchases: 0, refunds: 0, cashback: 0, fees: 0, charges: 0, payments: 0, adjust: 0,
125
+ closing: 0, deferred: 0, amountDue: 0, bank: null, bankDiff: null, due: null, paidByDue: 0, paid: 0, toPay: 0, status: "open",
126
+ };
127
+ for (const x of txs) {
128
+ if (x.date < p.from || x.date > p.close)
129
+ continue;
130
+ const k = lineKind(x, account, cats);
131
+ if (!k)
132
+ continue;
133
+ if (k.kind === "purchase")
134
+ s.purchases += k.amount;
135
+ else if (k.kind === "fee")
136
+ s.fees += k.amount;
137
+ else if (k.kind === "charge")
138
+ s.charges += k.amount;
139
+ else if (k.kind === "payment")
140
+ s.payments += k.amount;
141
+ else if (k.kind === "refund")
142
+ s.refunds += k.amount;
143
+ else if (k.kind === "cashback")
144
+ s.cashback += k.amount;
145
+ else
146
+ s.adjust += -k.amount;
147
+ }
148
+ s.closing = owedAt(p.close);
149
+ s.deferred = deferredAt(ins, p.close);
150
+ if (!p.open) {
151
+ const computed = Math.max(0, s.closing - s.deferred);
152
+ const bank = bankAmounts.get(p.close);
153
+ s.bank = bank ?? null;
154
+ s.bankDiff = bank === undefined ? null : computed - bank;
155
+ s.amountDue = bank ?? computed;
156
+ s.due = t.dueDay ? dueAfter(p.close, t.dueDay) : null;
157
+ const until = nextClose(p.close, sd) < asOf ? nextClose(p.close, sd) : asOf;
158
+ for (const x of txs) {
159
+ if (x.date <= p.close || x.date > until)
160
+ continue;
161
+ const k = lineKind(x, account, cats);
162
+ if (k?.kind !== "payment")
163
+ continue;
164
+ s.paid += k.amount;
165
+ if (s.due && x.date <= s.due)
166
+ s.paidByDue += k.amount;
167
+ }
168
+ s.toPay = Math.max(0, s.amountDue - s.paid);
169
+ s.status =
170
+ s.amountDue <= 0 ? "none"
171
+ : s.paidByDue >= s.amountDue ? "paid"
172
+ : !s.due || asOf <= s.due ? "due"
173
+ : s.paid >= s.amountDue ? "late"
174
+ : s.paid > 0 ? "partly"
175
+ : "unpaid";
176
+ }
177
+ out.push(s);
178
+ }
179
+ return out;
180
+ }
181
+ function rateFor(cb, category) {
182
+ for (const r of cb.rules)
183
+ if (r.categories.some((c) => category === c || category.startsWith(c + "/")))
184
+ return r.rate;
185
+ return cb.base;
186
+ }
187
+ /** Cashback periods: the statement periods (credit) or monthly cycles from statement_day (debit cards). */
188
+ function cyclesFor(l, account, sd, asOf, from) {
189
+ void l;
190
+ const out = [];
191
+ let c = closeOnOrAfter(from, sd);
192
+ for (; c <= asOf; c = nextClose(c, sd))
193
+ out.push({ from: addDays(prevClose(c, sd), 1), close: c, open: false });
194
+ out.push({ from: addDays(prevClose(c, sd), 1), close: asOf, open: true });
195
+ return out;
196
+ }
197
+ /** Expected against received cashback, per statement (or cashback cycle), for a card with cashback terms. */
198
+ export function cashback(l, account, asOf) {
199
+ const a = l.accounts.find((x) => x.id === account);
200
+ if (!a)
201
+ throw new Error(`no account ${account}`);
202
+ const t = termsOf(a, recordFor(l, account));
203
+ const cb = t.cashback;
204
+ if (!cb)
205
+ return [];
206
+ const sd = t.statementDay ?? 1;
207
+ const { map: cats } = flattenCategories(l.categories);
208
+ const txs = l.transactions.filter((x) => !x.void && x.date <= addMonths(asOf, 2) && (x.lines.some((ln) => ln.account === account) || x.card === account));
209
+ if (!txs.length)
210
+ return [];
211
+ const out = [];
212
+ for (const p of cyclesFor(l, account, sd, asOf, txs[0].date)) {
213
+ const groups = new Map();
214
+ let spend = 0;
215
+ for (const x of txs) {
216
+ if (x.date < p.from || x.date > p.close || x.date > asOf)
217
+ continue;
218
+ const k = lineKind(x, account, cats);
219
+ if (!k || (k.kind !== "purchase" && k.kind !== "refund"))
220
+ continue;
221
+ for (const ln of x.lines) {
222
+ if (!ln.category || isSystemCategory(ln.category) || cats.get(ln.category)?.kind === "income")
223
+ continue;
224
+ const rate = rateFor(cb, ln.category);
225
+ const g = groups.get(String(rate)) ?? { rate, spend: 0, categories: new Set() };
226
+ g.spend += ln.amount;
227
+ g.categories.add(ln.category);
228
+ groups.set(String(rate), g);
229
+ spend += ln.amount;
230
+ }
231
+ }
232
+ const minSpend = cb.min_spend?.amount ?? null;
233
+ const minMet = minSpend === null || spend >= minSpend;
234
+ const scale = cb.spend_max && spend > cb.spend_max.amount ? cb.spend_max.amount / spend : 1;
235
+ let expected = 0;
236
+ let incomplete = false;
237
+ for (const g of groups.values()) {
238
+ if (g.rate === null) {
239
+ if (g.spend > 0)
240
+ incomplete = true;
241
+ continue;
242
+ }
243
+ expected += (Math.max(0, g.spend) * g.rate) / 100;
244
+ }
245
+ expected = minMet ? Math.round(expected * scale) : 0;
246
+ const cap = cb.cap?.amount ?? null;
247
+ if (cap !== null)
248
+ expected = Math.min(expected, cap);
249
+ const payBy = cb.paid_on.kind === "next_statement" ? nextClose(p.open ? closeOnOrAfter(p.close, sd) : p.close, sd) : addDays(p.close, cb.paid_on.days);
250
+ const winFrom = p.open ? payBy : addDays(p.close, 1);
251
+ let received = 0;
252
+ if (!p.open) {
253
+ for (const x of txs) {
254
+ if (x.date < winFrom || x.date > payBy)
255
+ continue;
256
+ const k = lineKind(x, account, cats);
257
+ if (k?.kind === "cashback")
258
+ received += k.amount;
259
+ else if (x.card === account && !x.lines.some((ln) => ln.account === account)) {
260
+ for (const ln of x.lines)
261
+ if (ln.category && topOf(ln.category) === "cashback")
262
+ received += -ln.amount;
263
+ }
264
+ }
265
+ }
266
+ out.push({
267
+ from: p.from, close: p.close, open: p.open, spend,
268
+ byRate: [...groups.values()].map((g) => ({ rate: g.rate, spend: g.spend, categories: [...g.categories] })).sort((x, y) => y.spend - x.spend),
269
+ expected, incomplete, minSpend, minMet, needForMin: minSpend === null ? 0 : Math.max(0, minSpend - spend),
270
+ cap, capLeft: cap === null ? null : Math.max(0, cap - expected), received, payBy,
271
+ });
272
+ }
273
+ return out;
274
+ }
275
+ export function bestCard(l, q) {
276
+ const amount = q.amount ?? 0;
277
+ const owed = holdingsAt(l, q.date);
278
+ const recs = cardsData(l).records;
279
+ const candidates = [];
280
+ for (const a of l.accounts) {
281
+ if (!isOpen(a, q.date))
282
+ continue;
283
+ const rec = recs.find((r) => r.account === a.id);
284
+ if (rec && (rec.status === "cancelled" || rec.status === "locked" || rec.status === "inactive"))
285
+ continue;
286
+ if (a.type === "credit_card" || (rec && rec.kind === "debit" && rec.cashback))
287
+ candidates.push({ a, rec });
288
+ }
289
+ const out = [];
290
+ for (const { a, rec } of candidates) {
291
+ const t = termsOf(a, rec);
292
+ const cb = t.cashback;
293
+ const rate = cb ? rateFor(cb, q.category) : null;
294
+ let capLeft = null;
295
+ let minShort = 0;
296
+ if (cb) {
297
+ const cur = cashback(l, a.id, q.date).find((p) => p.open);
298
+ capLeft = cb.cap ? (cur?.capLeft ?? cb.cap.amount) : null;
299
+ if (cb.min_spend)
300
+ minShort = Math.max(0, cb.min_spend.amount - ((cur?.spend ?? 0) + amount));
301
+ }
302
+ const raw = rate === null ? null : Math.round((amount * rate) / 100);
303
+ const earn = raw === null ? null : capLeft === null ? raw : Math.min(raw, capLeft);
304
+ const payBy = a.type === "credit_card" ? interestFreeUntil(t, q.date) : null;
305
+ const freeDays = payBy ? daysBetween(q.date, payBy) : null;
306
+ const limitLeft = t.limit === null ? null : t.limit + (owed.get(a.id)?.amount ?? 0);
307
+ const bits = [
308
+ rate === null ? "cashback rate not set" : `${rate}%${capLeft !== null ? ` (cap left ${capLeft})` : ""}`,
309
+ ...(minShort > 0 ? [`spend ${minShort} more for the minimum`] : []),
310
+ ...(payBy ? [`pay by ${payBy} (${freeDays} days)`] : []),
311
+ ];
312
+ out.push({ account: a.id, name: a.name, rate, earn, capLeft, minSpendShort: minShort, payBy, freeDays, limitLeft, reason: `${a.name}: ${bits.join(" · ")}` });
313
+ }
314
+ // no cashback (unknown or 0%) ranks by interest-free days and limit instead
315
+ const effective = (b) => (!b.earn ? -1 : b.minSpendShort > 0 ? b.earn / 2 : b.earn);
316
+ return out
317
+ .filter((b) => b.limitLeft === null || b.limitLeft >= amount)
318
+ .sort((x, y) => effective(y) - effective(x) || (effective(y) > 0 ? (y.rate ?? -1) - (x.rate ?? -1) : 0) || (y.freeDays ?? -1) - (x.freeDays ?? -1) || (y.limitLeft ?? 0) - (x.limitLeft ?? 0));
319
+ }
320
+ /** Card year: from the 1st of the fee month on or before asOf, for 12 months. */
321
+ export function cardYear(feeMonth, asOf) {
322
+ const [y, m] = parts(asOf);
323
+ const from = `${m >= feeMonth ? y : y - 1}-${String(feeMonth).padStart(2, "0")}-01`;
324
+ return { from, to: addMonths(from, 12) };
325
+ }
326
+ function spentOn(l, account, from, to) {
327
+ const { map: cats } = flattenCategories(l.categories);
328
+ let s = 0;
329
+ for (const t of l.transactions) {
330
+ if (t.void || t.date < from || t.date > to)
331
+ continue;
332
+ const k = lineKind(t, account, cats);
333
+ if (k?.kind === "purchase")
334
+ s += k.amount;
335
+ else if (k?.kind === "refund")
336
+ s -= k.amount;
337
+ }
338
+ return s;
339
+ }
340
+ export function feeWaiver(l, account, asOf) {
341
+ const a = l.accounts.find((x) => x.id === account);
342
+ if (!a)
343
+ return null;
344
+ const t = termsOf(a, recordFor(l, account));
345
+ if (!t.feeWaiver || !t.feeMonth)
346
+ return null;
347
+ const y = cardYear(t.feeMonth, asOf);
348
+ const spent = spentOn(l, account, y.from, asOf);
349
+ const needed = Math.max(0, t.feeWaiver.spend - spent);
350
+ const daysLeft = daysBetween(asOf, y.to);
351
+ const monthsLeft = Math.max(1, Math.ceil(daysLeft / 30.44));
352
+ const elapsed = Math.max(1, daysBetween(y.from, asOf) + 1);
353
+ const projected = (spent / elapsed) * (elapsed + daysLeft);
354
+ return { account, name: a.name, target: t.feeWaiver.spend, yearFrom: y.from, deadline: y.to, spent, needed, perMonth: Math.round(needed / monthsLeft), daysLeft, onTrack: needed === 0 || projected >= t.feeWaiver.spend, met: needed === 0 };
355
+ }
356
+ function received(l, account, from, to, cats) {
357
+ let cb = 0;
358
+ let fees = 0;
359
+ for (const t of l.transactions) {
360
+ if (t.void || t.date < from || t.date > to)
361
+ continue;
362
+ const k = lineKind(t, account, cats);
363
+ if (k?.kind === "cashback")
364
+ cb += k.amount;
365
+ else if (k?.kind === "fee" && isAnnualFee(t))
366
+ fees += k.amount;
367
+ else if (!k && t.card === account)
368
+ for (const ln of t.lines)
369
+ if (ln.category && topOf(ln.category) === "cashback")
370
+ cb += -ln.amount;
371
+ }
372
+ return { cashback: cb, fees };
373
+ }
374
+ /** benefits + cashback received − annual fees − close fee, since the card was issued and over the last 12 months. */
375
+ export function cardValues(l, asOf) {
376
+ const { map: cats } = flattenCategories(l.categories);
377
+ const recs = cardsData(l).records;
378
+ const out = [];
379
+ const seen = new Set();
380
+ const yearAgo = addMonths(asOf, -12);
381
+ const rows = recs.map((rec) => ({ rec, a: rec.account ? l.accounts.find((x) => x.id === rec.account) : undefined }));
382
+ for (const a of l.accounts)
383
+ if (a.type === "credit_card" && !recs.some((r) => r.account === a.id))
384
+ rows.push({ a });
385
+ for (const { rec, a } of rows) {
386
+ const id = rec?.id ?? a.id;
387
+ if (seen.has(id))
388
+ continue;
389
+ seen.add(id);
390
+ const t = a ? termsOf(a, rec) : null;
391
+ const knownIssued = rec?.issued ?? rec?.activated ?? a?.opened;
392
+ const issued = knownIssued ?? "1900-01-01";
393
+ const all = a ? received(l, a.id, issued, asOf, cats) : { cashback: 0, fees: 0 };
394
+ const y12 = a ? received(l, a.id, yearAgo, asOf, cats) : { cashback: 0, fees: 0 };
395
+ const recFee = rec?.annual_fee ?? t?.annualFee ?? 0;
396
+ let fees = all.fees;
397
+ let fees12 = y12.fees;
398
+ let feesFrom = all.fees ? "ledger" : "none";
399
+ if (!all.fees && recFee) {
400
+ // one fee per started card year; with no issue date known, only the last 12 months can be estimated
401
+ const years = knownIssued ? Math.max(1, Math.ceil(daysBetween(issued, asOf) / 365.25)) : 1;
402
+ fees = recFee * years;
403
+ fees12 = recFee;
404
+ feesFrom = "record";
405
+ }
406
+ const benefits = rec?.benefits ?? 0;
407
+ const benefits12 = issued >= yearAgo ? benefits : 0;
408
+ const closeFee = rec?.status === "cancelled" ? (rec.close_fee ?? 0) : 0;
409
+ out.push({
410
+ card: id,
411
+ account: a?.id ?? null,
412
+ name: rec?.name ?? a?.name ?? id,
413
+ kind: rec?.kind ?? "credit",
414
+ status: rec?.status ?? (a && !isOpen(a, asOf) ? "cancelled" : "active"),
415
+ benefits,
416
+ cashback: all.cashback,
417
+ fees,
418
+ feesFrom,
419
+ closeFee,
420
+ net: benefits + all.cashback - fees - closeFee,
421
+ last12: { benefits: benefits12, cashback: y12.cashback, fees: fees12, net: benefits12 + y12.cashback - fees12 },
422
+ feeMonth: t?.feeMonth ?? null,
423
+ });
424
+ }
425
+ return out.sort((x, y) => x.last12.net - y.last12.net);
426
+ }
@@ -0,0 +1,105 @@
1
+ import type { Account, Ledger } from "../../engine/types.js";
2
+ export interface CashbackRule {
3
+ categories: string[];
4
+ rate: number | null;
5
+ }
6
+ export interface CashbackTerms {
7
+ base: number;
8
+ rules: CashbackRule[];
9
+ cap: {
10
+ amount: number;
11
+ per: "statement" | "month";
12
+ } | null;
13
+ min_spend: {
14
+ amount: number;
15
+ per: "statement" | "month";
16
+ } | null;
17
+ spend_max: {
18
+ amount: number;
19
+ per: "statement" | "month";
20
+ } | null;
21
+ paid_on: {
22
+ kind: "next_statement";
23
+ } | {
24
+ kind: "days_after";
25
+ days: number;
26
+ };
27
+ }
28
+ export interface FeeWaiver {
29
+ spend: number;
30
+ within: "year";
31
+ }
32
+ export interface CardTerms {
33
+ statementDay: number | null;
34
+ dueDay: number | null;
35
+ limit: number | null;
36
+ bank: string | null;
37
+ last4: string | null;
38
+ annualFee: number | null;
39
+ feeMonth: number | null;
40
+ feeWaiver: FeeWaiver | null;
41
+ freeDaysMax: number | null;
42
+ cashback: CashbackTerms | null;
43
+ }
44
+ export declare function parseCashback(v: unknown): CashbackTerms | null;
45
+ /** Terms from the card account's details, with what the card record (cards.yaml) adds for debit cards. */
46
+ export declare function termsOf(a: Account, record?: CardRecord): CardTerms;
47
+ export declare const CARDS_FILE = "data/cards.yaml";
48
+ export declare const STATEMENTS_FILE = "data/cards/statements.yaml";
49
+ export interface CardRecord {
50
+ id: string;
51
+ kind: "credit" | "debit" | "atm";
52
+ account?: string;
53
+ bank?: string;
54
+ name?: string;
55
+ network?: string;
56
+ last4?: string;
57
+ status?: "active" | "locked" | "inactive" | "cancelled";
58
+ issued?: string;
59
+ activated?: string;
60
+ cancelled?: string;
61
+ locked?: string;
62
+ physical?: "physical" | "virtual" | "both";
63
+ apple_pay?: boolean;
64
+ annual_fee?: number;
65
+ close_fee?: number;
66
+ benefits?: number;
67
+ cancel_plan?: {
68
+ by?: string;
69
+ note?: string;
70
+ };
71
+ keep_for_limit?: boolean;
72
+ fees_url?: string;
73
+ note?: string;
74
+ [k: string]: unknown;
75
+ }
76
+ export interface BankStatement {
77
+ account: string;
78
+ statement_date: string;
79
+ amount: number;
80
+ }
81
+ export interface CardsData {
82
+ records: CardRecord[];
83
+ statements: BankStatement[];
84
+ }
85
+ /** The cards module's data, loaded with the ledger (see ModuleDef.load). */
86
+ export declare function cardsData(l: Ledger): CardsData;
87
+ export declare function recordFor(l: Ledger, account: string): CardRecord | undefined;
88
+ /** Category emoji → category path. The owner's mapping can add its own (mapping key `card_emoji`). */
89
+ export declare const DEFAULT_CARD_EMOJI: Record<string, string>;
90
+ export interface NameCodes {
91
+ details: Record<string, unknown>;
92
+ warnings: string[];
93
+ }
94
+ /**
95
+ * Reads the card terms the owner writes into a wallet name: 🗓️7 statement day, 💸3 due day, category emoji
96
+ * before the first "•" (cashback categories), 🎉02/25 the card's anniversary (fee month), 1-5tr the cashback
97
+ * spend band, *4506 the last 4 digits. Anything that looks like a code but can't be read is a warning.
98
+ */
99
+ export declare function parseCardName(name: string, emoji?: Record<string, string>): NameCodes;
100
+ /**
101
+ * Merges codes read from a wallet name into an account's details. `from_name` lists the keys a name gave;
102
+ * any other key already set is the owner's (through Claude or by hand) and is never overwritten by a re-import.
103
+ * Returns null when nothing changes.
104
+ */
105
+ export declare function mergeNameCodes(current: Record<string, unknown> | undefined, codes: Record<string, unknown>): Record<string, unknown> | null;