ownledger 1.2.1 → 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 (151) hide show
  1. package/AGENTS.md +28 -1
  2. package/CHANGELOG.md +43 -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 +31 -9
  144. package/dist/worker/bestcard.js +78 -50
  145. package/dist/worker/mcp.js +209 -30
  146. package/dist/worker/version.d.ts +1 -1
  147. package/dist/worker/version.js +1 -1
  148. package/package.json +26 -4
  149. package/presets/misa.mapping.yaml +7 -0
  150. package/assets/app.css +0 -61
  151. package/assets/app.js +0 -369
@@ -23,6 +23,12 @@ export function previousPeriod(p) {
23
23
  const len = daysBetween(p.from, p.to) + 1;
24
24
  return { from: addDays(p.from, -len), to: addDays(p.from, -1) };
25
25
  }
26
+ /** Monday of the week of d (yyyy-mm-dd). */
27
+ function weekOf(d) {
28
+ const [y, m, dd] = parts(d);
29
+ const dow = (new Date(Date.UTC(y, m - 1, dd)).getUTCDay() + 6) % 7;
30
+ return addDays(d, -dow);
31
+ }
26
32
  function inPeriod(t, p) {
27
33
  return t.date >= p.from && t.date <= p.to;
28
34
  }
@@ -58,7 +64,9 @@ function aggregate(l, p, cats, o) {
58
64
  : by === "who" ? [[t.who ?? "(none)", t.who ?? "(none)"]]
59
65
  : by === "event" ? [[t.event ?? "(none)", t.event ?? "(none)"]]
60
66
  : by === "month" ? [[t.date.slice(0, 7), t.date.slice(0, 7)]]
61
- : (t.tags?.length ? t.tags : ["(none)"]).map((g) => [g, g]);
67
+ : by === "day" ? [[t.date, t.date]]
68
+ : by === "week" ? [[weekOf(t.date), weekOf(t.date)]]
69
+ : (t.tags?.length ? t.tags : ["(none)"]).map((g) => [g, g]);
62
70
  for (const [key, name] of keys) {
63
71
  const r = rows.get(key) ?? { key, name, income: 0, expense: 0, count: 0 };
64
72
  r.income += inc;
@@ -102,6 +110,11 @@ export function txSize(t) {
102
110
  export function queryTransactions(l, q) {
103
111
  const text = q.text ? fold(q.text) : "";
104
112
  const hits = [];
113
+ const accounts = q.account === undefined ? null : new Set(Array.isArray(q.account) ? q.account : [q.account]);
114
+ const within = q.hideWithin?.length ? new Set(q.hideWithin) : null;
115
+ const { map: cats } = flattenCategories(l.categories);
116
+ const totals = { income: 0, expense: 0, net: 0, count: 0 };
117
+ const byDay = new Map();
105
118
  for (let i = l.transactions.length - 1; i >= 0; i--) {
106
119
  const t = l.transactions[i];
107
120
  if (t.void && !q.includeVoid)
@@ -110,12 +123,22 @@ export function queryTransactions(l, q) {
110
123
  continue;
111
124
  if (q.to && t.date > q.to)
112
125
  continue;
113
- if (q.account && !t.lines.some((ln) => ln.account === q.account))
126
+ if (q.tx && t.id !== q.tx)
127
+ continue;
128
+ if (accounts && !t.lines.some((ln) => ln.account != null && accounts.has(ln.account)))
114
129
  continue;
115
130
  if (q.category && !t.lines.some((ln) => ln.category === q.category || ln.category?.startsWith(q.category + "/")))
116
131
  continue;
117
132
  if (q.plan && t.plan !== q.plan)
118
133
  continue;
134
+ if (q.who && t.who !== q.who)
135
+ continue;
136
+ if (q.event && t.event !== q.event)
137
+ continue;
138
+ if (q.tag && !(t.tags ?? []).includes(q.tag))
139
+ continue;
140
+ if (within && t.lines.every((ln) => ln.account != null && within.has(ln.account)))
141
+ continue;
119
142
  const size = txSize(t);
120
143
  if (q.min !== undefined && size < q.min)
121
144
  continue;
@@ -127,10 +150,35 @@ export function queryTransactions(l, q) {
127
150
  continue;
128
151
  }
129
152
  hits.push(t);
153
+ if (!t.void) {
154
+ const day = byDay.get(t.date) ?? { income: 0, expense: 0 };
155
+ for (const ln of t.lines) {
156
+ if (ln.category == null || isSystemCategory(ln.category))
157
+ continue;
158
+ if (q.category && !(ln.category === q.category || ln.category.startsWith(q.category + "/")))
159
+ continue;
160
+ if ((cats.get(ln.category)?.kind ?? "expense") === "income") {
161
+ totals.income += -ln.amount;
162
+ day.income += -ln.amount;
163
+ }
164
+ else {
165
+ totals.expense += ln.amount;
166
+ day.expense += ln.amount;
167
+ }
168
+ }
169
+ byDay.set(t.date, day);
170
+ }
130
171
  }
172
+ totals.net = totals.income - totals.expense;
173
+ totals.count = hits.length;
131
174
  const offset = q.offset ?? 0;
132
175
  const limit = Math.min(q.limit ?? 50, 500);
133
- return { total: hits.length, items: hits.slice(offset, offset + limit) };
176
+ const items = hits.slice(offset, offset + limit);
177
+ // totals of every day shown on this page, over the whole filter (a day split across pages still shows its full net)
178
+ const days = {};
179
+ for (const t of items)
180
+ days[t.date] = byDay.get(t.date) ?? { income: 0, expense: 0 };
181
+ return { total: hits.length, items, totals, days };
134
182
  }
135
183
  /** Month keys "yyyy-mm" from first to last inclusive. */
136
184
  export function monthsBetween(from, to) {
@@ -1,87 +1,10 @@
1
- import type { ISODate, Ledger, Plan } from "./types.js";
2
- export interface CardStatus {
3
- account: string;
4
- name: string;
5
- owed: number;
6
- limit: number | null;
7
- available: number | null;
8
- statementDate: ISODate | null;
9
- statementBalance: number | null;
10
- paidSinceStatement: number;
11
- toPay: number | null;
12
- dueDate: ISODate | null;
13
- daysToDue: number | null;
14
- /** details.bank and details.product as the owner wrote them (product: the card's real product name), or null */
15
- bank: string | null;
16
- product: string | null;
17
- period: CardPeriod;
18
- }
19
- /**
20
- * What happened on a card in the current statement period (day after the last statement → asOf), or in the
21
- * calendar month when the card has no statement_day. Only transactions where the card is the only account count
22
- * towards spending; transfers and card payments never do.
23
- */
24
- export interface CardPeriod {
25
- from: ISODate;
26
- to: ISODate;
27
- basis: "statement" | "month";
28
- /** expense lines paid with the card (before refunds) */
29
- spent: number;
30
- /** expense lines refunded to the card */
31
- refunds: number;
32
- /** spent - refunds, per expense category path, largest first */
33
- byCategory: {
34
- category: string;
35
- amount: number;
36
- }[];
37
- /** income under the `cashback` category (and its children) credited to the card */
38
- cashback: number;
39
- /** transactions that touch the card together with other accounts and categories: not split, left out of the figures above */
40
- mixed: number;
41
- }
42
- export declare function cards(l: Ledger, asOf: ISODate): CardStatus[];
43
- export interface PlanStatus {
44
- plan: string;
45
- name: string;
46
- kind: string;
47
- account: string;
48
- perPayment: number;
49
- count: number | null;
50
- paidCount: number;
51
- paidAmount: number;
52
- left: number | null;
53
- leftAmount: number | null;
54
- next: ISODate | null;
55
- overdue: ISODate[];
56
- finished: boolean;
57
- }
58
- export declare function perPayment(p: Plan): number;
59
- /** Due dates of a plan, the first `n` (or until `until`). */
60
- export declare function dueDates(p: Plan, until: ISODate, max?: number): ISODate[];
61
- export declare function planStatus(l: Ledger, asOf: ISODate): PlanStatus[];
62
- export interface DueItem {
63
- plan: string;
64
- name: string;
65
- account: string;
66
- date: ISODate;
67
- amount: number;
68
- overdue: boolean;
69
- }
70
- /** Plan payments due from (earliest unpaid) through asOf + days. */
71
- export declare function plansDue(l: Ledger, asOf: ISODate, days?: number): DueItem[];
72
- export interface DepositStatus {
73
- account: string;
74
- name: string;
75
- balance: number;
76
- principal: number;
77
- rate: number | null;
78
- start: ISODate | null;
79
- maturity: ISODate | null;
80
- daysToMaturity: number | null;
81
- interestAtMaturity: number | null;
82
- rollover: string | null;
83
- }
84
- export declare function deposits(l: Ledger, asOf: ISODate): DepositStatus[];
1
+ import type { ISODate, Ledger } from "./types.js";
2
+ import { type CardStatus } from "../modules/cards/engine.js";
3
+ import { type DepositStatus } from "../modules/deposits/engine.js";
4
+ import { type DueItem } from "../modules/loans/engine.js";
5
+ export * from "../modules/cards/engine.js";
6
+ export * from "../modules/deposits/engine.js";
7
+ export * from "../modules/loans/engine.js";
85
8
  export interface BudgetStatus {
86
9
  category: string;
87
10
  every: "month" | "year";
@@ -1,214 +1,15 @@
1
1
  import { holdingsAt } from "./balances.js";
2
2
  import { flattenCategories } from "./categories.js";
3
- import { addDays, addMonths, dayIn, daysBetween, isDate, monthEnd, monthStart, parts } from "./dates.js";
3
+ import { isDate, monthEnd, monthStart } from "./dates.js";
4
4
  import { typeDef } from "./registry.js";
5
- const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
6
- const day = (v) => (Number.isInteger(v) && v >= 1 && v <= 31 ? v : undefined);
7
- const date = (v) => (isDate(v) ? v : undefined);
5
+ import { cards } from "../modules/cards/engine.js";
6
+ import { deposits } from "../modules/deposits/engine.js";
7
+ import { plansDue } from "../modules/loans/engine.js";
8
+ // Moved into their modules (plan 003); re-exported so the engine's API stays the same.
9
+ export * from "../modules/cards/engine.js";
10
+ export * from "../modules/deposits/engine.js";
11
+ export * from "../modules/loans/engine.js";
8
12
  const open = (a, asOf) => !(isDate(a.closed) && a.closed <= asOf);
9
- function cardPeriod(l, card, from, to, basis, kinds) {
10
- let spent = 0;
11
- let refunds = 0;
12
- let cashback = 0;
13
- let mixed = 0;
14
- const by = new Map();
15
- for (const t of l.transactions) {
16
- if (t.void || t.date < from || t.date > to)
17
- continue;
18
- if (!t.lines.some((ln) => ln.account === card))
19
- continue;
20
- const cats = t.lines.filter((ln) => ln.category !== undefined);
21
- if (!cats.length)
22
- continue; // a transfer or card payment
23
- if (t.lines.some((ln) => ln.account !== undefined && ln.account !== card)) {
24
- mixed++;
25
- continue;
26
- }
27
- for (const ln of cats) {
28
- const c = ln.category;
29
- if (kinds.get(c) === "expense") {
30
- if (ln.amount > 0)
31
- spent += ln.amount;
32
- else
33
- refunds -= ln.amount;
34
- by.set(c, (by.get(c) ?? 0) + ln.amount);
35
- }
36
- else if (kinds.get(c) === "income" && (c === "cashback" || c.startsWith("cashback/"))) {
37
- cashback -= ln.amount;
38
- }
39
- }
40
- }
41
- const byCategory = [...by].filter(([, a]) => a !== 0).map(([category, amount]) => ({ category, amount })).sort((a, b) => b.amount - a.amount);
42
- return { from, to, basis, spent, refunds, byCategory, cashback, mixed };
43
- }
44
- export function cards(l, asOf) {
45
- const now = holdingsAt(l, asOf);
46
- const kinds = new Map([...flattenCategories(l.categories).map].map(([p, c]) => [p, c.kind]));
47
- const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : null);
48
- const out = [];
49
- for (const a of l.accounts) {
50
- if (a.type !== "credit_card" || !open(a, asOf))
51
- continue;
52
- const d = a.details ?? {};
53
- const sd = day(d.statement_day);
54
- const dd = day(d.due_day);
55
- const limit = num(d.limit) ?? null;
56
- const owed = -(now.get(a.id)?.amount ?? 0);
57
- let statementDate = null;
58
- let statementBalance = null;
59
- let paid = 0;
60
- let dueDate = null;
61
- if (sd) {
62
- const [y, m] = parts(asOf);
63
- statementDate = dayIn(y, m, sd);
64
- if (statementDate > asOf) {
65
- const prev = addMonths(`${asOf.slice(0, 7)}-01`, -1);
66
- statementDate = dayIn(...parts(prev).slice(0, 2), sd);
67
- }
68
- statementBalance = -(holdingsAt(l, statementDate).get(a.id)?.amount ?? 0);
69
- for (const t of l.transactions) {
70
- if (t.void || t.date <= statementDate || t.date > asOf)
71
- continue;
72
- for (const ln of t.lines)
73
- if (ln.account === a.id && ln.amount > 0)
74
- paid += ln.amount;
75
- }
76
- if (dd) {
77
- const [sy, sm] = parts(statementDate);
78
- dueDate = dayIn(sy, sm, dd);
79
- if (dueDate <= statementDate) {
80
- const nx = addMonths(`${statementDate.slice(0, 7)}-01`, 1);
81
- dueDate = dayIn(...parts(nx).slice(0, 2), dd);
82
- }
83
- }
84
- }
85
- const toPay = statementBalance === null ? null : Math.max(0, statementBalance - paid);
86
- out.push({
87
- account: a.id,
88
- name: a.name,
89
- owed,
90
- limit,
91
- available: limit === null ? null : limit - owed,
92
- statementDate,
93
- statementBalance,
94
- paidSinceStatement: paid,
95
- toPay,
96
- dueDate,
97
- daysToDue: dueDate ? daysBetween(asOf, dueDate) : null,
98
- bank: str(d.bank),
99
- product: str(d.product),
100
- period: statementDate
101
- ? cardPeriod(l, a.id, addDays(statementDate, 1), asOf, "statement", kinds)
102
- : cardPeriod(l, a.id, monthStart(asOf), asOf, "month", kinds),
103
- });
104
- }
105
- return out;
106
- }
107
- const STEP = { month: 1, quarter: 3, year: 12 };
108
- export function perPayment(p) {
109
- if (p.amount !== undefined)
110
- return p.amount + (p.fee ?? 0);
111
- if (p.principal !== undefined && p.count)
112
- return Math.round(p.principal / p.count) + (p.fee ?? 0);
113
- return 0;
114
- }
115
- /** Due dates of a plan, the first `n` (or until `until`). */
116
- export function dueDates(p, until, max = 1000) {
117
- const out = [];
118
- const step = STEP[p.every] ?? 1;
119
- const d0 = parts(p.start)[2];
120
- for (let i = 0; i < max; i++) {
121
- if (p.count !== undefined && i >= p.count)
122
- break;
123
- const d = addMonths(p.start, i * step, d0);
124
- if (d > until)
125
- break;
126
- if (p.end && d > p.end)
127
- break;
128
- out.push(d);
129
- }
130
- return out;
131
- }
132
- export function planStatus(l, asOf) {
133
- const paid = new Map();
134
- const accOf = new Map(l.plans.map((p) => [p.id, p.account]));
135
- for (const t of l.transactions) {
136
- if (t.void || !t.plan)
137
- continue;
138
- const acc = accOf.get(t.plan);
139
- const s = paid.get(t.plan) ?? { n: 0, amount: 0 };
140
- s.n++;
141
- s.amount += t.lines.filter((ln) => ln.account === acc).reduce((x, ln) => x + Math.abs(ln.amount), 0);
142
- paid.set(t.plan, s);
143
- }
144
- return l.plans.map((p) => {
145
- const per = perPayment(p);
146
- const s = paid.get(p.id) ?? { n: 0, amount: 0 };
147
- const horizon = addDays(asOf, 3660);
148
- const all = dueDates(p, horizon);
149
- const dueByNow = all.filter((d) => d <= asOf);
150
- const overdue = dueByNow.slice(s.n);
151
- const next = all[s.n] ?? null;
152
- const count = p.count ?? null;
153
- const left = count === null ? null : Math.max(0, count - s.n);
154
- return {
155
- plan: p.id,
156
- name: p.name ?? p.note ?? p.id,
157
- kind: p.kind,
158
- account: p.account,
159
- perPayment: per,
160
- count,
161
- paidCount: s.n,
162
- paidAmount: s.amount,
163
- left,
164
- leftAmount: left === null ? null : left * per,
165
- next,
166
- overdue,
167
- finished: left === 0 || (Boolean(p.end) && !next),
168
- };
169
- });
170
- }
171
- /** Plan payments due from (earliest unpaid) through asOf + days. */
172
- export function plansDue(l, asOf, days = 30) {
173
- const until = addDays(asOf, days);
174
- const out = [];
175
- for (const st of planStatus(l, asOf)) {
176
- const p = l.plans.find((x) => x.id === st.plan);
177
- const dates = dueDates(p, until).slice(st.paidCount);
178
- for (const d of dates)
179
- out.push({ plan: p.id, name: st.name, account: p.account, date: d, amount: st.perPayment, overdue: d < asOf });
180
- }
181
- return out.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
182
- }
183
- export function deposits(l, asOf) {
184
- const hs = holdingsAt(l, asOf);
185
- const out = [];
186
- for (const a of l.accounts) {
187
- if (a.type !== "deposit" || !open(a, asOf))
188
- continue;
189
- const d = a.details ?? {};
190
- const balance = hs.get(a.id)?.amount ?? 0;
191
- const principal = num(d.principal) ?? balance;
192
- const rate = num(d.rate) ?? null;
193
- const start = date(d.start) ?? date(a.opened) ?? null;
194
- const term = num(d.term_months);
195
- const maturity = date(d.maturity) ?? (start && term ? addMonths(start, term) : null);
196
- const interest = rate !== null && start && maturity ? Math.round((principal * rate * daysBetween(start, maturity)) / 36500) : null;
197
- out.push({
198
- account: a.id,
199
- name: a.name,
200
- balance,
201
- principal,
202
- rate,
203
- start,
204
- maturity,
205
- daysToMaturity: maturity ? daysBetween(asOf, maturity) : null,
206
- interestAtMaturity: interest,
207
- rollover: typeof d.rollover === "string" ? d.rollover : null,
208
- });
209
- }
210
- return out.sort((a, b) => (a.maturity ?? "9999") < (b.maturity ?? "9999") ? -1 : 1);
211
- }
212
13
  export function budgets(l, asOf) {
213
14
  const { map } = flattenCategories(l.categories);
214
15
  return l.budgets.map((b) => {
@@ -123,6 +123,8 @@ export interface Ledger {
123
123
  transactions: Transaction[];
124
124
  /** Which file each transaction came from (for check messages). */
125
125
  txFile: Map<string, string>;
126
+ /** Modules' own files, keyed by module name (e.g. cards: data/cards.yaml). */
127
+ ext?: Record<string, unknown>;
126
128
  }
127
129
  export interface Issue {
128
130
  level: "error" | "warning";
@@ -1,3 +1,4 @@
1
+ import { type Document } from "yaml";
1
2
  import { type FileMap } from "./load.js";
2
3
  import type { Account, Issue, Price, Transaction } from "./types.js";
3
4
  /** A set of edits to a data repo. applyChange turns it into new file contents (only the files that change). */
@@ -24,6 +25,14 @@ export interface Change {
24
25
  putFiles?: FileMap;
25
26
  }
26
27
  export declare function txLine(t: Transaction): string;
28
+ /**
29
+ * Block style everywhere (one key per line) and quoted values where a hand edit into flow style would
30
+ * split them. Without this, "Đầu tư khác (chứng khoán, CCQ ngoài ví)" is cut at the comma when the file
31
+ * is next read in flow style.
32
+ */
33
+ export declare function tidyYaml(doc: Document): void;
34
+ /** stringify for data files: block style, quoted where needed. */
35
+ export declare function yamlText(v: unknown): string;
27
36
  export declare function applyChange(files: FileMap, ch: Change): FileMap;
28
37
  /** Short human summary of what a change does (for previews and commit messages). */
29
38
  export declare function describeChange(ch: Change): string[];
@@ -1,8 +1,31 @@
1
- import { isMap, isSeq, parseDocument, stringify } from "yaml";
1
+ import { isMap, isPair, isScalar, isSeq, parseDocument, Scalar, stringify, visit } from "yaml";
2
2
  import { compareTx, ledgerPath, LEDGER_FILE_RE, parseJsonl, PATHS } from "./load.js";
3
3
  export function txLine(t) {
4
4
  return JSON.stringify(t);
5
5
  }
6
+ /** Characters that change meaning in flow-style YAML ({ a: b, c }). Values with them are always double-quoted. */
7
+ const FLOW_SPECIAL = /[,:{}\[\]#&*!|>'"%@`]/;
8
+ /**
9
+ * Block style everywhere (one key per line) and quoted values where a hand edit into flow style would
10
+ * split them. Without this, "Đầu tư khác (chứng khoán, CCQ ngoài ví)" is cut at the comma when the file
11
+ * is next read in flow style.
12
+ */
13
+ export function tidyYaml(doc) {
14
+ visit(doc, {
15
+ Map: (_, n) => void (n.flow = false),
16
+ Seq: (_, n) => void (n.flow = false),
17
+ Pair: (_, pair) => {
18
+ if (isPair(pair) && isScalar(pair.value) && typeof pair.value.value === "string" && FLOW_SPECIAL.test(pair.value.value))
19
+ pair.value.type = Scalar.QUOTE_DOUBLE;
20
+ },
21
+ });
22
+ }
23
+ /** stringify for data files: block style, quoted where needed. */
24
+ export function yamlText(v) {
25
+ const doc = parseDocument(stringify(v, { lineWidth: 0 }));
26
+ tidyYaml(doc);
27
+ return doc.toString({ lineWidth: 0 });
28
+ }
6
29
  function upsertYamlList(text, items, mergeOnly = false) {
7
30
  const doc = parseDocument(text ?? "[]\n");
8
31
  if (!isSeq(doc.contents)) {
@@ -31,10 +54,8 @@ function upsertYamlList(text, items, mergeOnly = false) {
31
54
  throw new Error(`no item with id "${item.id}"`);
32
55
  }
33
56
  }
34
- let out = doc.toString({ lineWidth: 0 });
35
- if (out.startsWith("[]"))
36
- out = stringify(items, { lineWidth: 0 });
37
- return out;
57
+ tidyYaml(doc);
58
+ return doc.toString({ lineWidth: 0 });
38
59
  }
39
60
  export function applyChange(files, ch) {
40
61
  const out = {};
@@ -6,6 +6,7 @@ export function parseMapping(text) {
6
6
  throw new Error(`mapping is not valid:\n- ${errs.join("\n- ")}`);
7
7
  return m;
8
8
  }
9
+ const ACCOUNT_KEYS = new Set(["id", "name", "type", "asset", "opened", "closed", "group", "details", "names", "note"]);
9
10
  export function validateMapping(m) {
10
11
  const e = [];
11
12
  if (!m || typeof m !== "object")
@@ -28,6 +29,11 @@ export function validateMapping(m) {
28
29
  for (const [k, a] of Object.entries(m.accounts)) {
29
30
  if (!a || typeof a.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(a.id))
30
31
  e.push(`accounts["${k}"].id: letters, digits, . _ - only`);
32
+ // { name: A (b, c) } in flow style parses as name "A (b" plus a key "c)" with no value: the name was cut at a comma
33
+ for (const [key, v] of Object.entries(a ?? {})) {
34
+ if (v === null && !ACCOUNT_KEYS.has(key))
35
+ e.push(`accounts["${k}"]: "${key}" has no value; a name with a comma was probably cut. Quote it: name: "…"`);
36
+ }
31
37
  }
32
38
  if (!m.categories || typeof m.categories !== "object")
33
39
  e.push("categories: map of source category → ownledger category");
@@ -48,6 +48,13 @@ export interface ImportResult {
48
48
  rows: number;
49
49
  transactions: Transaction[];
50
50
  accounts: Account[];
51
+ /** Card terms read from wallet names (🗓️ statement day, 💸 due day…) for accounts already in the ledger. */
52
+ accountUpdates: {
53
+ id: string;
54
+ set: Record<string, unknown>;
55
+ }[];
56
+ /** Codes in wallet names that couldn't be read (never guessed). */
57
+ nameWarnings: string[];
51
58
  skipped: number;
52
59
  changed: {
53
60
  key: string;
@@ -1,5 +1,6 @@
1
1
  import { isDate } from "../engine/dates.js";
2
2
  import { stableKey } from "./hash.js";
3
+ import { DEFAULT_CARD_EMOJI, mergeNameCodes, parseCardName } from "../modules/cards/terms.js";
3
4
  /* ------------------------------------------------------------------ helpers */
4
5
  const norm = (s) => String(s ?? "").trim().toLowerCase();
5
6
  export function parseAmount(v, decimal = ".") {
@@ -189,7 +190,7 @@ export function runImport(wb, m, ledger) {
189
190
  const { rows, sheets, errors } = readRows(wb, m);
190
191
  const unmatched = m.unmatched_account ?? "import-unmatched";
191
192
  const res = {
192
- ok: false, source: m.source, rows: rows.length, transactions: [], accounts: [], skipped: 0, changed: [], replace: [], gone: [],
193
+ ok: false, source: m.source, rows: rows.length, transactions: [], accounts: [], accountUpdates: [], nameWarnings: [], skipped: 0, changed: [], replace: [], gone: [],
193
194
  unpaired: [], unresolvedCategories: [], unresolvedRows: [], reconcile: [], rounding: [], zeroed: [], errors,
194
195
  };
195
196
  // account targets in categories / uncategorized must be accounts of the mapping or the ledger
@@ -372,6 +373,32 @@ export function runImport(wb, m, ledger) {
372
373
  const { names: _n, ...rest } = a;
373
374
  res.accounts.push({ ...rest, id: a.id, name: a.name ?? a.id, type: a.type ?? "other" });
374
375
  }
376
+ // card terms in wallet names: on every import and re-import (credit cards only; the owner's own values win)
377
+ const emoji = { ...DEFAULT_CARD_EMOJI, ...(m.card_emoji ?? {}) };
378
+ for (const [source, a] of Object.entries(accMap)) {
379
+ if ((a.type ?? ledger?.accounts.find((x) => x.id === a.id)?.type) !== "credit_card")
380
+ continue;
381
+ const names = [...(a.names ?? []), source]; // full names first: sheet names also turn "*" into "_"
382
+ // sheet names are cut at 31 characters: read the longest name the source uses
383
+ const name = [...names].sort((x, y) => [...y].length - [...x].length)[0];
384
+ const codes = parseCardName(name, emoji);
385
+ res.nameWarnings.push(...codes.warnings);
386
+ if (!Object.keys(codes.details).length)
387
+ continue;
388
+ const made1 = res.accounts.find((x) => x.id === a.id);
389
+ if (made1) {
390
+ const merged = mergeNameCodes(made1.details, codes.details);
391
+ if (merged)
392
+ made1.details = merged;
393
+ continue;
394
+ }
395
+ const cur = ledger?.accounts.find((x) => x.id === a.id);
396
+ if (!cur)
397
+ continue;
398
+ const merged = mergeNameCodes(cur.details, codes.details);
399
+ if (merged)
400
+ res.accountUpdates.push({ id: a.id, set: { details: merged } });
401
+ }
375
402
  if (built.some((t) => t.lines.some((l) => l.account === unmatched)) && !existing.has(unmatched) && !made.has(unmatched)) {
376
403
  res.accounts.push({ id: unmatched, name: "Chưa khớp khi nhập / unmatched import", type: "other", note: "Transfers whose other side was not in the file. Should end at 0." });
377
404
  }
@@ -0,0 +1,19 @@
1
+ import type { Env } from "../worker/env.js";
2
+ import type { DataSource, Snapshot } from "../worker/store.js";
3
+ export interface ModuleApiCtx {
4
+ req: Request;
5
+ env: Env;
6
+ src: DataSource;
7
+ snap: Snapshot;
8
+ login: string;
9
+ asOf: string;
10
+ q: URLSearchParams;
11
+ }
12
+ export type ModuleApiResult = {
13
+ body: unknown;
14
+ status?: number;
15
+ } | null;
16
+ type Handler = (path: string, c: ModuleApiCtx) => Promise<ModuleApiResult> | ModuleApiResult;
17
+ export declare function registerModuleApi(name: string, h: Handler): void;
18
+ export declare function moduleApi(path: string, c: ModuleApiCtx): Promise<ModuleApiResult>;
19
+ export {};
@@ -0,0 +1,16 @@
1
+ import { cardsApi } from "./cards/api.js";
2
+ import { moduleByName } from "./index.js";
3
+ /** /api/m/<module>/… : each module's endpoints. A module that's off answers 404. */
4
+ const HANDLERS = { cards: cardsApi };
5
+ export function registerModuleApi(name, h) {
6
+ HANDLERS[name] = h;
7
+ }
8
+ export async function moduleApi(path, c) {
9
+ const i = path.indexOf("/");
10
+ const name = i < 0 ? path : path.slice(0, i);
11
+ const h = HANDLERS[name];
12
+ const m = moduleByName(name);
13
+ if (!h || !m || !m.on(c.snap.ledger, c.asOf, c.snap.files))
14
+ return null;
15
+ return h(i < 0 ? "" : path.slice(i + 1), c);
16
+ }
@@ -0,0 +1,3 @@
1
+ import type { ModuleApiCtx, ModuleApiResult } from "../api.js";
2
+ /** /api/m/cards/… */
3
+ export declare function cardsApi(path: string, c: ModuleApiCtx): ModuleApiResult;