ownledger 2.1.0 → 2.2.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 (84) hide show
  1. package/AGENTS.md +24 -8
  2. package/CHANGELOG.md +33 -0
  3. package/README.md +5 -2
  4. package/assets/index.html +10 -10
  5. package/assets/static/{Account-sw3qGLbB.js → Account-CYrXDU9Z.js} +1 -1
  6. package/assets/static/{Accounts-DWyzX3qB.js → Accounts-BXleOwUO.js} +1 -1
  7. package/assets/static/{Attention-DxV-4qdY.js → Attention-Ci3luOdE.js} +1 -1
  8. package/assets/static/{ByCategory-B4P3ikmE.js → ByCategory-cLVOyjwd.js} +1 -1
  9. package/assets/static/{CardDetail-CayBXBm-.js → CardDetail-BxXfAcMp.js} +1 -1
  10. package/assets/static/{Cards-CVuOP8Bt.js → Cards-DNtITMnA.js} +1 -1
  11. package/assets/static/{Cards-XUBdWxyo.js → Cards-DnIsAWPD.js} +1 -1
  12. package/assets/static/{CardsValue-EoW2jG_0.js → CardsValue-V1-fYMLf.js} +1 -1
  13. package/assets/static/{Cashback-BibVYHf_.js → Cashback-B8lqwRnb.js} +1 -1
  14. package/assets/static/{CategoryIcon-HfjYhH1l.js → CategoryIcon-D4Cdb_ZP.js} +1 -1
  15. package/assets/static/{CategoryPicker-BkmvzX2I.js → CategoryPicker-54vkuxVh.js} +1 -1
  16. package/assets/static/{ChartWidget-u09-whUU.js → ChartWidget-S5F4Ze91.js} +1 -1
  17. package/assets/static/{Combobox-xXeyjGgK.js → Combobox-BvX68J3o.js} +1 -1
  18. package/assets/static/{Deposits-CLAda4dj.js → Deposits-Ct5HhCEc.js} +1 -1
  19. package/assets/static/{DrillLink-Bvfam9FA.js → DrillLink-CZyI-y0-.js} +1 -1
  20. package/assets/static/{Field-tKFmKDEF.js → Field-DYmqEAlI.js} +1 -1
  21. package/assets/static/{HomeEditor-4vxj5LMD.js → HomeEditor-Dv-h_ql-.js} +1 -1
  22. package/assets/static/{Import-DwaaFpRJ.js → Import-B2uhVnEm.js} +1 -1
  23. package/assets/static/{IncomeSpending-RVDSxAK4.js → IncomeSpending-DNT2CWH9.js} +1 -1
  24. package/assets/static/{KV-DMA1AlP-.js → KV-CKWaJkRK.js} +1 -1
  25. package/assets/static/{Left-C_4gTGSX.js → Left-BefXZztB.js} +1 -1
  26. package/assets/static/{Money-PfFNNDOw.js → Money-BwLucm7P.js} +1 -1
  27. package/assets/static/{NetWorth-BSoseczC.js → NetWorth-DeLSapZ2.js} +1 -1
  28. package/assets/static/{Pace-B8p-9174.js → Pace-D6gilOBZ.js} +1 -1
  29. package/assets/static/{Panel-BnfWrw9R.js → Panel-CSe25x0N.js} +1 -1
  30. package/assets/static/{PinDialog-BqAU9Vh4.js → PinDialog-CHiLIKEs.js} +1 -1
  31. package/assets/static/{Plans-2KuQH2_I.js → Plans-D7rJ1yHU.js} +1 -1
  32. package/assets/static/{Recent-Ccmb34bq.js → Recent-Dcqb2yko.js} +1 -1
  33. package/assets/static/{Reports-Dd-dhclr.js → Reports--PDAEnQM.js} +1 -1
  34. package/assets/static/{Settings-BR8WBlen.js → Settings-Bd0oglWl.js} +1 -1
  35. package/assets/static/{Transactions-BAuQ-6Eb.js → Transactions-CQ1yQ1UU.js} +1 -1
  36. package/assets/static/{TxRow-EKIIMQKa.js → TxRow-BGfpKo2m.js} +1 -1
  37. package/assets/static/{Unusual-CwFp8aA5.js → Unusual-DGB4ZOA2.js} +1 -1
  38. package/assets/static/{Upcoming-B28roT9r.js → Upcoming-B0HwBqmG.js} +1 -1
  39. package/assets/static/{WhichCard-B3kLc842.js → WhichCard-BefFKS2q.js} +1 -1
  40. package/assets/static/{arrow-up-D3gxUKLo.js → arrow-up-CRgLRKET.js} +1 -1
  41. package/assets/static/{bits-Dr2E0ObC.js → bits-D34d9IBm.js} +1 -1
  42. package/assets/static/{button-rfwMVz0i.js → button-BKhMn8jX.js} +1 -1
  43. package/assets/static/{cards-Bb5zjzRG.js → cards-Ct0jh73r.js} +1 -1
  44. package/assets/static/{charts-BqP7HKwP.js → charts-D-1glV8L.js} +1 -1
  45. package/assets/static/chevron-down-BWoQwA6m.js +1 -0
  46. package/assets/static/chevron-right-D7Sgw1v1.js +1 -0
  47. package/assets/static/{createLucideIcon-flJrJK2p.js → createLucideIcon-XZ28znwT.js} +1 -1
  48. package/assets/static/{dialog-BuRqO4sc.js → dialog-Bx-cd-2e.js} +1 -1
  49. package/assets/static/{dist-B4_eGtNj.js → dist--HKr0kfV.js} +1 -1
  50. package/assets/static/{dist-B7PR2b0C.js → dist-BFPyD74_.js} +1 -1
  51. package/assets/static/{dist-BDn7ydjn.js → dist-CmbuesVk.js} +1 -1
  52. package/assets/static/{dist-Dl-m8cc2.js → dist-vgyaCpaL.js} +1 -1
  53. package/assets/static/{es2015-DJh4h8NX.js → es2015-DqY4UvQc.js} +1 -1
  54. package/assets/static/{index-eR1GkdC_.js → index-DBHFdsYB.js} +4 -4
  55. package/assets/static/{queries-DZIMMe4i.js → queries-BcMmmb36.js} +1 -1
  56. package/assets/static/{react-dom-wK_7mEjs.js → react-dom-5dgiSOdd.js} +1 -1
  57. package/assets/static/{select-eaSi9K-d.js → select-B5P2TaPX.js} +1 -1
  58. package/assets/static/{shared-Box7on3B.js → shared-BgU6fc7z.js} +1 -1
  59. package/assets/static/{triangle-exclamation-point-CuL0XSJl.js → triangle-exclamation-point-CMy18kC0.js} +1 -1
  60. package/assets/static/{useMutation-_Lw8xXWa.js → useMutation-aC3Z1p9y.js} +1 -1
  61. package/dist/cli/statements.js +153 -5
  62. package/dist/engine/actions.d.ts +28 -0
  63. package/dist/engine/actions.js +109 -3
  64. package/dist/modules/cards/files.d.ts +1 -1
  65. package/dist/modules/cards/files.js +1 -1
  66. package/dist/modules/cards/terms.d.ts +2 -0
  67. package/dist/modules/cards/terms.js +7 -0
  68. package/dist/node/reconcile.d.ts +100 -0
  69. package/dist/node/reconcile.js +176 -0
  70. package/dist/node/statement-rows.d.ts +77 -0
  71. package/dist/node/statement-rows.js +245 -0
  72. package/dist/node/statements.d.ts +2 -1
  73. package/dist/worker/api.js +32 -5
  74. package/dist/worker/github.d.ts +18 -1
  75. package/dist/worker/github.js +53 -6
  76. package/dist/worker/mcp.js +32 -7
  77. package/dist/worker/store.js +1 -1
  78. package/dist/worker/version.d.ts +1 -1
  79. package/dist/worker/version.js +1 -1
  80. package/package.json +1 -1
  81. package/assets/static/chevron-down-Co1w7ApZ.js +0 -1
  82. package/assets/static/chevron-right-Dqh3vs9Y.js +0 -1
  83. package/dist/worker/tar.d.ts +0 -3
  84. package/dist/worker/tar.js +0 -65
@@ -0,0 +1,100 @@
1
+ import type { ISODate, Ledger } from "../engine/types.js";
2
+ import type { StatementRow } from "./statement-rows.js";
3
+ /**
4
+ * Every filed statement of a card against the ledger (plan 005). Reports only; never writes.
5
+ * Amounts are on the card like the ledger: negative = spent, positive = paid back / refunded / cashback.
6
+ */
7
+ export interface FiledStatement {
8
+ month: string;
9
+ path: string;
10
+ rows: StatementRow[];
11
+ closing: number | null;
12
+ error?: string;
13
+ }
14
+ export interface LedgerRow {
15
+ id: string;
16
+ date: ISODate;
17
+ amount: number;
18
+ note: string;
19
+ against: string;
20
+ }
21
+ export interface RowRef {
22
+ date: ISODate;
23
+ amount: number;
24
+ description: string;
25
+ month: string;
26
+ }
27
+ export interface MonthResult {
28
+ month: string;
29
+ from: ISODate;
30
+ close: ISODate;
31
+ file: string;
32
+ rows: number;
33
+ /** The bank's figure: read from the PDF, else the one saved with add_statement_amount. */
34
+ bank: number | null;
35
+ bankFrom: "pdf" | "saved" | null;
36
+ /** ownledger's amount for the same statement (closing − instalments not billed yet, 0 if in credit). */
37
+ ledger: number | null;
38
+ /** ledger − bank (like bankDiff); null without a bank figure. */
39
+ diff: number | null;
40
+ /** diff − the month before's diff: what changed this month. */
41
+ change: number | null;
42
+ /** The part of the gap from matched rows the ledger and the bank put on different sides of a close date (goes away later). */
43
+ timing: number;
44
+ missing: number;
45
+ error?: string;
46
+ }
47
+ export type BatchHint = {
48
+ op: "add";
49
+ date: ISODate;
50
+ kind: "expense" | "income";
51
+ amount: number;
52
+ account: string;
53
+ note: string;
54
+ category: null;
55
+ } | {
56
+ op: "edit";
57
+ id: string;
58
+ amount: number;
59
+ } | {
60
+ op: "edit";
61
+ id: string;
62
+ account: string;
63
+ };
64
+ export interface ReconcileResult {
65
+ account: string;
66
+ from: ISODate;
67
+ to: ISODate;
68
+ months: MonthResult[];
69
+ matched: number;
70
+ /** On a statement, not on the ledger. */
71
+ missing: (RowRef & {
72
+ hint: BatchHint;
73
+ })[];
74
+ /** On the ledger (inside the statements' periods), on no statement. Balance adjustments are listed apart. */
75
+ notOnStatement: LedgerRow[];
76
+ /** Balance adjustments (_adjust) on the card inside the statements' periods: usually covering a gap. */
77
+ adjustments: LedgerRow[];
78
+ /** Same date (±3 days), close amount (digits swapped, or within 1%). */
79
+ amountDiffs: {
80
+ statement: RowRef;
81
+ ledger: LedgerRow;
82
+ hint: BatchHint;
83
+ }[];
84
+ /** A missing row whose amount is on another account the same days: probably booked on the wrong account. */
85
+ otherAccount: {
86
+ statement: RowRef;
87
+ ledger: LedgerRow & {
88
+ account: string;
89
+ };
90
+ hint: BatchHint;
91
+ }[];
92
+ /** Several rows on one side that add up to one row on the other (a fee and its VAT booked as one). */
93
+ joined: {
94
+ statement: RowRef[];
95
+ ledger: LedgerRow[];
96
+ }[];
97
+ /** Statement rows missing on the ledger that cancel out (a purchase refunded in full as cashback). */
98
+ netZero: RowRef[][];
99
+ }
100
+ export declare function reconcile(l: Ledger, account: string, filed: FiledStatement[], asOf: ISODate): ReconcileResult;
@@ -0,0 +1,176 @@
1
+ import { addDays, daysBetween } from "../engine/dates.js";
2
+ import { statements } from "../modules/cards/statements.js";
3
+ const DAYS = 7;
4
+ function ledgerRows(l, account, from, to) {
5
+ return l.transactions
6
+ .filter((t) => !t.void && t.date >= from && t.date <= to && t.lines.some((x) => x.account === account))
7
+ .map((t) => rowOf(t, account));
8
+ }
9
+ function rowOf(t, account) {
10
+ const own = t.lines.filter((x) => x.account === account);
11
+ return {
12
+ id: t.id,
13
+ date: t.date,
14
+ amount: own.reduce((s, x) => s + x.amount, 0),
15
+ note: [t.note, ...own.map((x) => x.note)].filter(Boolean).join(" · "),
16
+ against: t.lines.filter((x) => x.account !== account).map((x) => x.category ?? x.account).filter(Boolean).join(", "),
17
+ };
18
+ }
19
+ const digits = (n) => String(Math.abs(n)).split("").sort().join("");
20
+ const dist = (a, b) => Math.abs(daysBetween(a, b));
21
+ export function reconcile(l, account, filed, asOf) {
22
+ const periods = statements(l, account, asOf).filter((s) => !s.open);
23
+ const byMonth = new Map(periods.map((s) => [s.close.slice(0, 7), s]));
24
+ const used = filed.filter((f) => byMonth.has(f.month)).sort((a, b) => a.month.localeCompare(b.month));
25
+ const months = filed
26
+ .filter((f) => !byMonth.has(f.month))
27
+ .map((f) => ({ month: f.month, from: "", close: "", file: f.path, rows: f.rows.length, bank: f.closing, bankFrom: f.closing === null ? null : "pdf", ledger: null, diff: null, change: null, timing: 0, missing: 0, error: f.error ?? "ownledger has no closed statement period closing this month" }));
28
+ const srows = [];
29
+ for (const f of used)
30
+ for (const r of f.rows)
31
+ srows.push({ date: r.date, amount: r.amount, description: r.description, month: f.month, k: srows.length, done: false });
32
+ const first = used[0] ? byMonth.get(used[0].month) : null;
33
+ const last = used.length ? byMonth.get(used[used.length - 1].month) : null;
34
+ const from = first?.from ?? asOf;
35
+ const to = last?.close ?? asOf;
36
+ const lrows = ledgerRows(l, account, addDays(from, -DAYS), addDays(to, DAYS)).map((r) => ({ ...r, done: false }));
37
+ const ref = (s) => ({ date: s.date, amount: s.amount, description: s.description, month: s.month });
38
+ const plainL = ({ done: _d, ...r }) => r;
39
+ // 1. same signed amount within ±7 days, nearest first
40
+ const pairs = [];
41
+ for (const s of srows)
42
+ for (const r of lrows)
43
+ if (r.amount === s.amount && dist(s.date, r.date) <= DAYS)
44
+ pairs.push({ s, r, d: dist(s.date, r.date) });
45
+ pairs.sort((a, b) => a.d - b.d || a.s.k - b.s.k);
46
+ let matched = 0;
47
+ const kept = []; // matched groups, for timing
48
+ for (const p of pairs) {
49
+ if (p.s.done || p.r.done)
50
+ continue;
51
+ p.s.done = p.r.done = true;
52
+ kept.push({ s: [p.s], r: [p.r] });
53
+ matched++;
54
+ }
55
+ // 2. two or three rows on one side that add up to one on the other (a fee and its VAT; a purchase with its DCC fee and VAT)
56
+ const joined = [];
57
+ const openS = () => srows.filter((s) => !s.done);
58
+ const openL = () => lrows.filter((r) => !r.done);
59
+ /** Sets of 2–3 rows on the same date that sum to `amount`. */
60
+ function sumOf(pool, amount, near) {
61
+ const c = pool.filter((x) => !x.done && dist(x.date, near) <= DAYS);
62
+ for (let i = 0; i < c.length; i++)
63
+ for (let j = i + 1; j < c.length; j++) {
64
+ if (c[i].date !== c[j].date)
65
+ continue;
66
+ if (c[i].amount + c[j].amount === amount)
67
+ return [c[i], c[j]];
68
+ for (let k = j + 1; k < c.length; k++)
69
+ if (c[k].date === c[i].date && c[i].amount + c[j].amount + c[k].amount === amount)
70
+ return [c[i], c[j], c[k]];
71
+ }
72
+ return null;
73
+ }
74
+ for (const r of openL()) {
75
+ const set = sumOf(srows, r.amount, r.date);
76
+ if (!set)
77
+ continue;
78
+ for (const x of set)
79
+ x.done = true;
80
+ r.done = true;
81
+ kept.push({ s: set, r: [r] });
82
+ joined.push({ statement: set.map(ref), ledger: [plainL(r)] });
83
+ }
84
+ for (const s of openS()) {
85
+ const set = sumOf(lrows, s.amount, s.date);
86
+ if (!set)
87
+ continue;
88
+ for (const x of set)
89
+ x.done = true;
90
+ s.done = true;
91
+ kept.push({ s: [s], r: set });
92
+ joined.push({ statement: [ref(s)], ledger: set.map(plainL) });
93
+ }
94
+ // 3. close amounts on close dates: a typo
95
+ const amountDiffs = [];
96
+ for (const s of openS()) {
97
+ const r = openL()
98
+ .filter((x) => Math.sign(x.amount) === Math.sign(s.amount) && dist(x.date, s.date) <= 3 && (digits(x.amount) === digits(s.amount) || Math.abs(x.amount - s.amount) <= Math.abs(s.amount) * 0.01))
99
+ .sort((a, b) => dist(a.date, s.date) - dist(b.date, s.date))[0];
100
+ if (!r)
101
+ continue;
102
+ s.done = r.done = true;
103
+ amountDiffs.push({ statement: ref(s), ledger: plainL(r), hint: { op: "edit", id: r.id, amount: Math.abs(s.amount) } });
104
+ }
105
+ // 4. missing rows that cancel out (purchase + cashback/refund of the same amount)
106
+ const netZero = [];
107
+ for (const a of openS()) {
108
+ if (a.done || a.amount >= 0)
109
+ continue;
110
+ const b = openS().find((x) => x.amount === -a.amount && dist(x.date, a.date) <= 62);
111
+ if (!b)
112
+ continue;
113
+ a.done = b.done = true;
114
+ netZero.push([ref(a), ref(b)]);
115
+ }
116
+ // 5. still missing: is the amount on another account those days?
117
+ const otherAccount = [];
118
+ const missing = [];
119
+ for (const s of openS()) {
120
+ const elsewhere = l.transactions.find((t) => !t.void && dist(t.date, s.date) <= 3 && !t.lines.some((x) => x.account === account) && t.lines.some((x) => x.account && x.account !== account && x.amount === s.amount));
121
+ if (elsewhere) {
122
+ const acc = elsewhere.lines.find((x) => x.account && x.amount === s.amount).account;
123
+ otherAccount.push({ statement: ref(s), ledger: { ...rowOf(elsewhere, acc), account: acc }, hint: { op: "edit", id: elsewhere.id, account } });
124
+ continue;
125
+ }
126
+ missing.push({
127
+ ...ref(s),
128
+ hint: { op: "add", date: s.date, kind: s.amount < 0 ? "expense" : "income", amount: Math.abs(s.amount), account, note: s.description, category: null },
129
+ });
130
+ }
131
+ // on the ledger, on no statement: only inside the filed statements' periods
132
+ const covered = used.map((f) => byMonth.get(f.month)).map((p) => [p.from, p.close]);
133
+ const inside = (d) => covered.some(([a, b]) => d >= a && d <= b);
134
+ const isAdjust = (r) => r.against.split(", ").includes("_adjust");
135
+ const left = openL().filter((r) => inside(r.date)).map(plainL);
136
+ // per month: the bank's figure against the ledger's
137
+ let prev = null;
138
+ const res = used.map((f) => {
139
+ const p = byMonth.get(f.month);
140
+ const ledger = Math.max(0, p.closing - p.deferred);
141
+ const bank = f.closing ?? p.bank;
142
+ const diff = bank === null ? null : ledger - bank;
143
+ const change = diff === null || prev === null ? null : diff - prev;
144
+ // owed by the close on the ledger's side but not yet on the bank's, minus the other way round
145
+ let timing = 0;
146
+ for (const g of kept) {
147
+ for (const r of g.r)
148
+ if (r.date <= p.close)
149
+ timing -= r.amount;
150
+ for (const x of g.s)
151
+ if (byMonth.get(x.month).close <= p.close)
152
+ timing += x.amount;
153
+ }
154
+ const m = {
155
+ month: f.month, from: p.from, close: p.close, file: f.path, rows: f.rows.length, bank, bankFrom: f.closing !== null ? "pdf" : p.bank !== null ? "saved" : null,
156
+ ledger, diff, change, timing, missing: missing.filter((x) => x.month === f.month).length, ...(f.error ? { error: f.error } : {}),
157
+ };
158
+ if (diff !== null)
159
+ prev = diff;
160
+ return m;
161
+ });
162
+ return {
163
+ account,
164
+ from,
165
+ to,
166
+ months: [...months, ...res].sort((a, b) => a.month.localeCompare(b.month)),
167
+ matched,
168
+ missing,
169
+ notOnStatement: left.filter((r) => !isAdjust(r)),
170
+ adjustments: left.filter(isAdjust),
171
+ amountDiffs,
172
+ otherAccount,
173
+ joined,
174
+ netZero,
175
+ };
176
+ }
@@ -0,0 +1,77 @@
1
+ import type { ISODate } from "../engine/types.js";
2
+ /**
3
+ * Rows of a bank statement (plan 005), read on the user's computer only.
4
+ * General rules, no bank-specific code: a row is a date + a description + an amount. Each bank's wording
5
+ * (its closing label, the words of its credit rows) lives in imports/statements/sources.yaml as data.
6
+ */
7
+ /** A piece of text on a line, with where it starts (PDF points from the left). */
8
+ export interface Cell {
9
+ x: number;
10
+ /** Where it ends, when known (amount columns are often right-aligned). */
11
+ end?: number;
12
+ text: string;
13
+ }
14
+ export type Line = Cell[];
15
+ /** What sources.yaml can say about a card's statements (all optional; defaults cover most banks). */
16
+ export interface StatementLayout {
17
+ /** The label of the bank's closing figure, e.g. "Payable amount" (or a list). */
18
+ closing_label?: string | string[];
19
+ /** Words that mark a row as a credit (money back on the card): payment, refund, cashback… */
20
+ credit_words?: string[];
21
+ /** Lines with these words are never rows (headers, totals). */
22
+ skip_words?: string[];
23
+ /** Which amount on a row is the row's amount when there are several (zeros and other currencies not counted): 1 = first, -1 = last (default). */
24
+ amount_column?: number;
25
+ }
26
+ interface PdfItem {
27
+ str: string;
28
+ transform: number[];
29
+ width: number;
30
+ height: number;
31
+ }
32
+ /** The PDF's text as lines of cells, top to bottom, page by page (columns kept by x position). */
33
+ export declare function pdfLines(bytes: Uint8Array): Promise<Line[]>;
34
+ /** Groups text items into lines (same baseline) and cells (a gap wider than about a character starts a new cell). */
35
+ export declare function linesOf(items: PdfItem[]): Line[];
36
+ /** Lines as text, cells split by two spaces (what `statements check` prints). */
37
+ export declare function linesText(lines: Line[]): string;
38
+ /** Lines from plain text (cells split by 2+ spaces or tabs): for tests and pasted text. */
39
+ export declare function linesFromText(text: string): Line[];
40
+ /** Lowercase without Vietnamese marks, for matching words. */
41
+ export declare function plain(s: string): string;
42
+ export declare const DEFAULT_CLOSING_LABELS: string[];
43
+ export declare const DEFAULT_CREDIT_WORDS: string[];
44
+ export declare const DEFAULT_SKIP_WORDS: string[];
45
+ /** The dates written in a cell, as ISO dates (dd/mm with no year: the year that puts it on or before `near`, within a year). */
46
+ export declare function datesOf(text: string, near: ISODate): ISODate[];
47
+ export interface Amount {
48
+ value: number;
49
+ sign: -1 | 1 | 0;
50
+ currency?: string;
51
+ }
52
+ /** A cell that is an amount ("1,234,567", "1.234.567", "909", "-50,000", "(50,000)", "50,000 CR", "CR 50,000", "1,234.00", "VND 33,300", "3,483,958 (VND)"); else null. */
53
+ export declare function amountOf(text: string): Amount | null;
54
+ export interface StatementRow {
55
+ date: ISODate;
56
+ /** On the card, like the ledger: negative = spent (a charge), positive = paid back, refunded, cashback. */
57
+ amount: number;
58
+ description: string;
59
+ /** Why it counts as a credit, when it does. */
60
+ credit?: "mark" | "column" | "word";
61
+ line: number;
62
+ }
63
+ export interface ParsedStatement {
64
+ rows: StatementRow[];
65
+ /** The bank's closing figure (positive = owed), when found. */
66
+ closing: number | null;
67
+ closingLabel?: string;
68
+ }
69
+ /**
70
+ * Rows and the closing figure of one statement. `period`: the statement period the ledger has for it
71
+ * (rows dated far outside are header dates, not rows).
72
+ */
73
+ export declare function parseStatement(lines: Line[], period: {
74
+ from: ISODate;
75
+ close: ISODate;
76
+ }, layout?: StatementLayout, base?: string): ParsedStatement;
77
+ export {};
@@ -0,0 +1,245 @@
1
+ import { addDays } from "../engine/dates.js";
2
+ /** The PDF's text as lines of cells, top to bottom, page by page (columns kept by x position). */
3
+ export async function pdfLines(bytes) {
4
+ const { getDocumentProxy } = await import("unpdf");
5
+ const doc = await getDocumentProxy(new Uint8Array(bytes));
6
+ const out = [];
7
+ for (let p = 1; p <= doc.numPages; p++) {
8
+ const page = await doc.getPage(p);
9
+ const tc = await page.getTextContent();
10
+ out.push(...linesOf(tc.items.filter((i) => typeof i.str === "string")));
11
+ }
12
+ return out;
13
+ }
14
+ /** Groups text items into lines (same baseline) and cells (a gap wider than about a character starts a new cell). */
15
+ export function linesOf(items) {
16
+ const rows = [];
17
+ for (const it of items) {
18
+ if (!it.str.trim())
19
+ continue;
20
+ const y = it.transform[5];
21
+ const size = Math.hypot(it.transform[2], it.transform[3]) || it.height || 10;
22
+ const row = rows.find((r) => Math.abs(r.y - y) <= Math.max(2, size * 0.3));
23
+ if (row)
24
+ row.items.push(it);
25
+ else
26
+ rows.push({ y, size, items: [it] });
27
+ }
28
+ rows.sort((a, b) => b.y - a.y);
29
+ return rows.map((r) => {
30
+ const its = r.items.sort((a, b) => a.transform[4] - b.transform[4]);
31
+ const cells = [];
32
+ let end = -Infinity;
33
+ for (const it of its) {
34
+ const x = it.transform[4];
35
+ const gap = x - end;
36
+ const last = cells[cells.length - 1];
37
+ if (last && gap < r.size * 0.9)
38
+ last.text += (gap > r.size * 0.12 && !last.text.endsWith(" ") && !it.str.startsWith(" ") ? " " : "") + it.str;
39
+ else
40
+ cells.push({ x, text: it.str });
41
+ end = x + (it.width || it.str.length * r.size * 0.5);
42
+ cells[cells.length - 1].end = end;
43
+ }
44
+ return cells.map((c) => ({ x: c.x, end: c.end, text: c.text.replace(/\s+/g, " ").trim() })).filter((c) => c.text);
45
+ });
46
+ }
47
+ /** Lines as text, cells split by two spaces (what `statements check` prints). */
48
+ export function linesText(lines) {
49
+ return lines.map((l) => l.map((c) => c.text).join(" ")).join("\n");
50
+ }
51
+ /** Lines from plain text (cells split by 2+ spaces or tabs): for tests and pasted text. */
52
+ export function linesFromText(text) {
53
+ return text.split(/\r?\n/).filter((l) => l.trim()).map((l) => {
54
+ const cells = [];
55
+ for (const m of l.matchAll(/\S+(?: \S+)*/g))
56
+ cells.push({ x: m.index, end: m.index + m[0].length, text: m[0] });
57
+ return cells;
58
+ });
59
+ }
60
+ /* ------------------------------------------------------------------ words, dates, amounts */
61
+ /** Lowercase without Vietnamese marks, for matching words. */
62
+ export function plain(s) {
63
+ return s.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/đ/g, "d").replace(/Đ/g, "D").toLowerCase();
64
+ }
65
+ export const DEFAULT_CLOSING_LABELS = [
66
+ "tong so tien phai thanh toan", "so tien phai thanh toan", "tong du no cuoi ky", "du no cuoi ky", "so du cuoi ky",
67
+ "payable amount", "total amount due", "total payment due", "new balance", "closing balance", "statement balance", "amount due",
68
+ ];
69
+ export const DEFAULT_CREDIT_WORDS = ["payment", "refund", "cashback", "cash back", "reversal", "hoan tien", "hoan tra", "thanh toan the", "thanh toan du no", "tra no"];
70
+ export const DEFAULT_SKIP_WORDS = [
71
+ "due date", "statement date", "payment due", "minimum", "opening balance", "previous balance", "credit limit", "available", "total",
72
+ "ngay sao ke", "han thanh toan", "toi thieu", "du no dau ky", "han muc", "tong cong",
73
+ ];
74
+ const DATE_RE = /(?<![\d/.-])(\d{1,2})[/.-](\d{1,2})(?:[/.-](\d{4}|\d{2}))?(?![\d/.-])|(?<![\d/.-])(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})(?![\d/.-])/g;
75
+ /** The dates written in a cell, as ISO dates (dd/mm with no year: the year that puts it on or before `near`, within a year). */
76
+ export function datesOf(text, near) {
77
+ const out = [];
78
+ for (const m of text.matchAll(DATE_RE)) {
79
+ let y, mo, d;
80
+ if (m[4])
81
+ (y = +m[4]), (mo = +m[5]), (d = +m[6]);
82
+ else {
83
+ d = +m[1];
84
+ mo = +m[2];
85
+ if (m[3])
86
+ y = m[3].length === 2 ? 2000 + +m[3] : +m[3];
87
+ else {
88
+ y = +near.slice(0, 4);
89
+ if (`${y}-${String(mo).padStart(2, "0")}-${String(d).padStart(2, "0")}` > addDays(near, 31))
90
+ y--;
91
+ }
92
+ }
93
+ if (mo < 1 || mo > 12 || d < 1 || d > 31)
94
+ continue;
95
+ out.push(`${y}-${String(mo).padStart(2, "0")}-${String(d).padStart(2, "0")}`);
96
+ }
97
+ return out;
98
+ }
99
+ const AMOUNT_RE = /^(?:([A-Za-z]{2,3})\s+)?(\(?)\s*([-+]?)\s*(\d{1,3}(?:[.,\s]\d{3})+|\d{1,9})(?:([.,])(\d{1,2}))?\s*(\)?)\s*(?:(cr|dr|[A-Za-z]{3}|vnđ|đ|₫)|\((vnđ|[A-Za-z]{3})\))?\s*([-+]?)$/i;
100
+ /** A cell that is an amount ("1,234,567", "1.234.567", "909", "-50,000", "(50,000)", "50,000 CR", "CR 50,000", "1,234.00", "VND 33,300", "3,483,958 (VND)"); else null. */
101
+ export function amountOf(text) {
102
+ const m = AMOUNT_RE.exec(text.trim());
103
+ if (!m)
104
+ return null;
105
+ const [, before, open, pre, int, , dec, close, unit1, unit2, post] = m;
106
+ if ((open && !close) || (!open && close))
107
+ return null;
108
+ const value = Math.round(Number(int.replace(/[.,\s]/g, "") + (dec ? "." + dec : "")));
109
+ const b = before?.toLowerCase();
110
+ const u = (unit1 ?? unit2)?.toLowerCase();
111
+ const mark = b === "cr" || b === "dr" ? b : u === "cr" || u === "dr" ? u : undefined;
112
+ const curB = b && b !== "cr" && b !== "dr" ? b : undefined;
113
+ if (b && !curB && !mark)
114
+ return null;
115
+ if (curB && curB.length !== 3)
116
+ return null;
117
+ const curU = u && u !== "cr" && u !== "dr" ? u : undefined;
118
+ if (curB && curU)
119
+ return null; // two currencies
120
+ const sign = open || pre === "-" || post === "-" || mark === "cr" ? -1 : pre === "+" || post === "+" || mark === "dr" ? 1 : 0;
121
+ const cur = curB ?? curU;
122
+ const currency = cur === "đ" || cur === "₫" || cur === "vnđ" ? "VND" : cur?.toUpperCase();
123
+ return { value, sign, ...(currency ? { currency } : {}) };
124
+ }
125
+ /** A cell that starts with a date. */
126
+ const STARTS_WITH_DATE = /^(\d{1,2}[/.-]\d{1,2}([/.-](\d{4}|\d{2}))?|\d{4}[/.-]\d{1,2}[/.-]\d{1,2})(?![\d])/;
127
+ const hasWord = (text, words) => {
128
+ const p = plain(text);
129
+ return words.some((w) => {
130
+ const q = plain(w);
131
+ return new RegExp(`(^|[^a-z0-9])${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^a-z0-9])`).test(p);
132
+ });
133
+ };
134
+ /** Where a "credit" column header sits, if the statement has separate debit and credit columns. */
135
+ function creditColumn(lines) {
136
+ for (const l of lines) {
137
+ const d = l.find((c) => /^(debit|ghi no|no|dr|so tien ghi no)$/.test(plain(c.text)));
138
+ const c = l.find((x) => /^(credit|ghi co|co|cr|so tien ghi co)$/.test(plain(x.text)));
139
+ if (d && c)
140
+ return { debit: d, credit: c };
141
+ }
142
+ return null;
143
+ }
144
+ /** How far a cell is from a column header: by left edges or right edges, whichever is closer. */
145
+ function offset(c, h) {
146
+ const left = Math.abs(c.x - h.x);
147
+ return c.end !== undefined && h.end !== undefined ? Math.min(left, Math.abs(c.end - h.end)) : left;
148
+ }
149
+ /**
150
+ * Rows and the closing figure of one statement. `period`: the statement period the ledger has for it
151
+ * (rows dated far outside are header dates, not rows).
152
+ */
153
+ export function parseStatement(lines, period, layout = {}, base) {
154
+ /** Amounts in another currency than the ledger's are the original amounts of foreign purchases: not the billed amount. */
155
+ const billed = (a) => a !== null && (!a.currency || !base || a.currency === base.toUpperCase());
156
+ const labels = (layout.closing_label ? [layout.closing_label].flat() : DEFAULT_CLOSING_LABELS).map(plain);
157
+ const credits = layout.credit_words ?? DEFAULT_CREDIT_WORDS;
158
+ const skips = [...DEFAULT_SKIP_WORDS, ...(layout.skip_words ?? []), ...labels];
159
+ const col = layout.amount_column ?? -1;
160
+ const cols = creditColumn(lines);
161
+ const lo = addDays(period.from, -40);
162
+ const hi = addDays(period.close, 5);
163
+ // closing figure: the first label (in the order given) found on a line; its amount is the first after it, on the line or the next two
164
+ let closing = null;
165
+ let closingLabel;
166
+ for (const label of labels) {
167
+ for (let i = 0; i < lines.length && closing === null; i++) {
168
+ const l = lines[i];
169
+ const at = l.findIndex((c) => plain(c.text).includes(label));
170
+ if (at < 0 || /minimum|toi thieu/.test(plain(l.map((c) => c.text).join(" "))))
171
+ continue;
172
+ // the label's own cell may end with the amount ("Payable amount: 1,234,000")
173
+ const tail = plain(l[at].text).split(label)[1]?.replace(/^[\s:]+/, "") ?? "";
174
+ const own = tail ? amountOf(l[at].text.slice(l[at].text.length - tail.length)) : null;
175
+ // the next lines count only up to a minimum-payment line (its figure is not the closing one)
176
+ const after = [...l.slice(at + 1)];
177
+ for (const n of [lines[i + 1], lines[i + 2]]) {
178
+ if (!n || /minimum|toi thieu/.test(plain(n.map((c) => c.text).join(" "))))
179
+ break;
180
+ after.push(...n);
181
+ }
182
+ const found = (billed(own) ? own : null) ?? after.map((c) => amountOf(c.text)).find(billed) ?? null;
183
+ if (found) {
184
+ closing = found.sign === -1 ? -found.value : found.value;
185
+ closingLabel = label;
186
+ }
187
+ }
188
+ if (closing !== null)
189
+ break;
190
+ }
191
+ const rows = [];
192
+ const isCurrency = (t) => /^[A-Z]{3}$/.test(t.trim());
193
+ const dated = (l) => !!l && l.slice(0, 2).some((c) => STARTS_WITH_DATE.test(c.text));
194
+ lines.forEach((l, i) => {
195
+ if (l.length < 2)
196
+ return;
197
+ // a row starts with a date in its first two cells
198
+ const head = l.slice(0, 2).filter((c) => STARTS_WITH_DATE.test(c.text)).flatMap((c) => datesOf(c.text, period.close));
199
+ const date = head[0];
200
+ if (!date || date < lo || date > hi)
201
+ return;
202
+ const text = l.map((c) => c.text).join(" ");
203
+ if (hasWord(text, skips))
204
+ return;
205
+ const amounts = [];
206
+ const desc = [];
207
+ for (const c of l) {
208
+ const stripped = c.text.replace(DATE_RE, "").trim();
209
+ if (!stripped)
210
+ continue; // a date cell
211
+ const a = amountOf(c.text);
212
+ if (billed(a)) {
213
+ if (a.value)
214
+ amounts.push({ cell: c, a }); // a 0 is an empty column (no discount), not the row's amount
215
+ }
216
+ else if (!a && !isCurrency(stripped))
217
+ desc.push(stripped);
218
+ }
219
+ if (!amounts.length)
220
+ return;
221
+ // no description on the row itself: the bank wrapped it onto the lines around it (lines with no date and no amount)
222
+ if (!desc.length) {
223
+ for (const n of [lines[i - 1], lines[i + 1]]) {
224
+ if (!n || dated(n) || n.some((c) => amountOf(c.text)))
225
+ continue;
226
+ const t = n.map((c) => c.text).join(" ");
227
+ if (!hasWord(t, skips))
228
+ desc.push(t);
229
+ }
230
+ }
231
+ const pick = amounts[col < 0 ? amounts.length + col : col - 1] ?? amounts[amounts.length - 1];
232
+ if (!pick.a.value)
233
+ return;
234
+ const description = desc.join(" ");
235
+ let credit;
236
+ if (pick.a.sign === -1)
237
+ credit = "mark";
238
+ else if (pick.a.sign === 0 && cols && offset(pick.cell, cols.credit) < offset(pick.cell, cols.debit))
239
+ credit = "column";
240
+ else if (pick.a.sign === 0 && hasWord(description, credits))
241
+ credit = "word";
242
+ rows.push({ date, amount: credit ? pick.a.value : -pick.a.value, description, ...(credit ? { credit } : {}), line: i });
243
+ });
244
+ return { rows, closing, ...(closingLabel ? { closingLabel } : {}) };
245
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ISODate } from "../engine/types.js";
2
2
  import { STATEMENTS_DIR } from "../modules/cards/files.js";
3
+ import type { StatementLayout } from "./statement-rows.js";
3
4
  /**
4
5
  * Bank statements (plan 004): imports/statements/<account-id>/<YYYY-MM>.pdf, unlocked.
5
6
  * Read on the user's computer only (CLI); the Worker never parses them.
@@ -36,7 +37,7 @@ export interface MonthGuess {
36
37
  export declare function monthFromText(text: string, statementDay: number | null): MonthGuess;
37
38
  /** KEY=value lines of .env.statements (quotes stripped, # comments). Missing file: {}. */
38
39
  export declare function readEnvFile(root: string): Record<string, string>;
39
- export interface StatementSource {
40
+ export interface StatementSource extends StatementLayout {
40
41
  from?: string;
41
42
  subject?: string;
42
43
  /** Name of the variable in .env.statements. */
@@ -12,6 +12,7 @@ import { features } from "../engine/features.js";
12
12
  import { pace, series, unusual, usual } from "../engine/insights.js";
13
13
  import { moduleApi } from "../modules/api.js";
14
14
  import { applyChange } from "../engine/write.js";
15
+ import { batch, BATCH_MAX } from "../engine/actions.js";
15
16
  import { parseMapping } from "../import/mapping.js";
16
17
  import { runImport } from "../import/run.js";
17
18
  import { readWorkbook } from "../import/workbook.js";
@@ -109,14 +110,21 @@ export async function api(req, env, source) {
109
110
  const q = url.searchParams;
110
111
  const path = url.pathname.slice(5);
111
112
  const src = source ?? sourceFor(env);
112
- const s = await snapshot(env, src);
113
+ let s;
114
+ try {
115
+ s = await snapshot(env, src);
116
+ }
117
+ catch (e) {
118
+ // Loading the data repo failed (GitHub down, app not installed…): say why, as JSON, instead of a bare 500.
119
+ return json({ error: `could not load the data repo (${src.label}): ${e.message}` }, 502);
120
+ }
113
121
  const L = s.ledger;
114
122
  const asOf = q.get("date") ?? todayIn(env.TIMEZONE || "Asia/Ho_Chi_Minh");
115
- const dash = dashboardOf(s.files, login);
116
- const pool = poolOf(L, dash?.prefs?.pool, asOf);
117
- /** "pool" in an account filter means every account in the pool. */
118
- const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
119
123
  try {
124
+ const dash = dashboardOf(s.files, login);
125
+ const pool = poolOf(L, dash?.prefs?.pool, asOf);
126
+ /** "pool" in an account filter means every account in the pool. */
127
+ const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
120
128
  if (path.startsWith("m/")) {
121
129
  const r = await moduleApi(path.slice(2), { req, env, src, snap: s, login, asOf, q });
122
130
  if (r && "response" in r)
@@ -273,6 +281,25 @@ export async function api(req, env, source) {
273
281
  const { preview_id } = (await req.json());
274
282
  return json(await applyPending(env, src, preview_id));
275
283
  }
284
+ case "batch": {
285
+ // Preview many transaction adds/edits/voids as one change; POST batch/apply commits it (one commit).
286
+ if (req.method !== "POST")
287
+ return json({ error: "POST" }, 405);
288
+ const body = (await req.json());
289
+ if (!Array.isArray(body.ops) || !body.ops.length || body.ops.length > BATCH_MAX)
290
+ return json({ error: `ops: 1 to ${BATCH_MAX}` }, 400);
291
+ if (!body.reason?.trim())
292
+ return json({ error: "reason is required" }, 400);
293
+ const p = batch(s.files, body.ops, { via: "dashboard", client: login, reason: body.reason });
294
+ const id = await savePending(env, { baseSha: s.sha, files: p.files, message: p.message, summary: p.summary, created: new Date().toISOString() });
295
+ return json({ preview_id: id, will: p.summary, message: p.message, counts: p.counts, balance_change: p.balanceChange, transactions: [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])], warnings: p.warnings.map((w) => w.message) });
296
+ }
297
+ case "batch/apply": {
298
+ if (req.method !== "POST")
299
+ return json({ error: "POST" }, 405);
300
+ const { preview_id } = (await req.json());
301
+ return json(await applyPending(env, src, preview_id));
302
+ }
276
303
  case "grants": {
277
304
  if (req.method === "DELETE") {
278
305
  const id = q.get("id");