ownledger 2.1.1 → 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.
package/AGENTS.md CHANGED
@@ -86,7 +86,11 @@ dashboard ("Statement PDF" on a statement) and never reads it. Optional: a repo
86
86
 
87
87
  `imports/statements/sources.yaml`, per account id: `from` (the bank's sender address), `subject` (words in the subject),
88
88
  `password` (the name of the variable in `.env.statements`, e.g. `PW_WOORI`), `password_hint` (what the password is made
89
- of, e.g. "date of birth ddmmyy"; never the password itself). The bank's own email facts, nothing else.
89
+ of, e.g. "date of birth ddmmyy"; never the password itself). The bank's own email facts, nothing else. Optional, how to
90
+ read the statement when the general rules don't fit (data, never code): `closing_label` (the label of the bank's
91
+ closing figure, e.g. "Payable amount"; a string or a list), `credit_words` (words that mark a row as money back on the
92
+ card: payment, refund, cashback…), `skip_words` (lines that are never rows), `amount_column` (which amount on a row is
93
+ its amount when there are several, zeros and other currencies not counted: `1` = first, `-1` = last, the default).
90
94
 
91
95
  Passwords live in `.env.statements` at the repo root (`PW_<ACCOUNT_ID>=…` or `PW_<BANK>=…`, the first word of the id;
92
96
  or the variable `sources.yaml` names). It is git-ignored. Never commit it, print it, or send it anywhere.
@@ -107,13 +111,25 @@ itself never connects to email.
107
111
  again with `--yes` (files and commits).
108
112
  5. `npx ownledger statements list` shows which months are missing between the first and the last; report them.
109
113
 
110
- ### Check a statement against the ledger
114
+ ### Check a card's statements against the ledger
111
115
 
112
- `npx ownledger statements check <account-id> <YYYY-MM>` (`--json` for structured output) prints the period,
113
- ownledger's figures for it, its transactions on the card, and the statement's text. Compare them and tell the owner
114
- what's missing, extra or different (amounts, dates, fees, cashback, the closing balance). Never change anything from
115
- the PDF on your own: each fix is a normal write (preview → go). The bank's statement amount goes in with
116
- `add_statement_amount`.
116
+ **To check a card's statements, run `npx ownledger statements reconcile <account-id>`** (`--from`/`--to YYYY-MM` to
117
+ narrow it, `--json` for data). Don't write your own PDF parsing or matching. For every filed statement it shows the
118
+ bank's closing figure next to ownledger's (gap = ownledger − bank, the change from the month before, and the part of
119
+ the gap that is only timing: rows the bank and the ledger put on opposite sides of a close date). Then it lists rows on
120
+ a statement but not on the ledger, ledger rows on no statement, amounts that differ (typos, FX), rows probably booked
121
+ on another account, and balance adjustments (`_adjust`) covering a gap. Fees booked with their VAT as one row, and
122
+ purchases refunded in full, are matched and shown apart; they need no fix.
123
+
124
+ Propose the fixes to the owner as **one batch** (the connector's `batch` tool: one preview, one go, one commit; the
125
+ `hint` of each item in `--json` is the op to start from: fill in the category). **Never add a balance adjustment to
126
+ cover a gap**: find the real rows. If the closing figure isn't found or rows look wrong, add the layout fields to
127
+ `sources.yaml` (above) rather than working around it. `--save-bank-amounts` saves each month's bank figure in
128
+ `data/cards/statements.yaml` (preview; `--yes` after the owner's go) so `cards` / `card_statement` show the gap
129
+ without the PDFs.
130
+
131
+ `npx ownledger statements check <account-id> <YYYY-MM>` shows one statement: ownledger's figures and transactions for
132
+ the period, the rows read from the PDF, and its text with columns kept.
117
133
 
118
134
  `npx ownledger check` warns about statement files that don't fit (a folder that isn't an account, a name that isn't
119
135
  `YYYY-MM.pdf`, a PDF still locked).
@@ -123,7 +139,7 @@ the PDF on your own: each fix is a normal write (preview → go). The bank's sta
123
139
  1. Show the owner exactly what will change (the transactions, with amounts and accounts) and wait for their go.
124
140
  2. Never invent an amount, date or account. Ask if anything is missing.
125
141
  3. Run `npx ownledger check`; it must pass.
126
- 4. One commit per change, with a readable message.
142
+ 4. One commit per change, with a readable message. Many related transaction fixes are one change: use `batch`.
127
143
 
128
144
  ## First import of a new app
129
145
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.2.0 (2026-11-23)
4
+
5
+ Batch writes, and checking every statement of a card in one run (plan 005). Data format stays 1.
6
+
7
+ - **Batch writes:** the connector's `batch` tool previews many adds, edits and voids as **one** change: one preview,
8
+ one go from the owner, one commit ("Batch: 28 adds, 4 edits, 4 voids"). Ops run in order on the evolving data, check
9
+ runs once on the result, and if any op fails the whole batch is refused, naming the op. The preview shows every
10
+ transaction (up to 200) and the balance change per account. Each row's trail gets the batch's reason plus the op's
11
+ own. Also `POST /api/batch` + `/api/batch/apply` for the dashboard (no UI yet).
12
+ - **`ownledger statements reconcile <card>`** (`--from`/`--to`, `--json`): every filed statement against the ledger.
13
+ Per month the bank's closing figure next to ownledger's (gap, change from the month before, and the part that is
14
+ only timing), then the rows missing on the ledger, ledger rows on no statement, amounts that differ, rows probably on
15
+ another account, and balance adjustments covering a gap. Fee + VAT (or purchase + DCC fee + VAT) booked as one row,
16
+ and purchases refunded in full, are matched and shown apart. `--json` carries a `batch` op hint per item.
17
+ `--save-bank-amounts` saves each month's bank figure in `data/cards/statements.yaml` (preview; `--yes`). Reads the
18
+ PDFs on your computer only, as before.
19
+ - **Statement rows by general rules**, no bank-specific code: the PDF's text with its columns kept, a row is a date +
20
+ a description + an amount (with CR/DR, minus, brackets, currency marks; foreign-currency amounts skipped; debit and
21
+ credit columns when the statement has them; a description wrapped onto the lines around the row). What a bank does
22
+ differently is data in `imports/statements/sources.yaml`: `closing_label`, `credit_words`, `skip_words`,
23
+ `amount_column`.
24
+ - `ownledger statements check` now shows the rows it read and the text with columns kept.
25
+ - Connector instructions: use `batch` for more than ~3 writes.
26
+
3
27
  ## 2.1.1 (2026-11-23)
4
28
 
5
29
  - **Fix: the dashboard failed to load ("Could not load data:" with no reason) once statement PDFs were filed.** The
package/README.md CHANGED
@@ -102,7 +102,8 @@ ownledger deploy deploy or update your Worker (--openwallet / --no-ope
102
102
  ownledger dev [dir] run your Worker locally against the local folder (sign-in skipped; --openwallet[=<url>])
103
103
  ownledger statements add <card> <file.pdf>… unlock and file bank statement PDFs (preview; --yes files and commits)
104
104
  ownledger statements list [<card>] which months each card has, and which are missing
105
- ownledger statements check <card> <YYYY-MM> the statement's text next to the ledger's figures for that period
105
+ ownledger statements check <card> <YYYY-MM> one statement's rows and text next to the ledger's figures for that period
106
+ ownledger statements reconcile <card> every filed statement against the ledger: gaps per month, missing rows, typos
106
107
  ```
107
108
 
108
109
  ### Bank statements (optional)
@@ -111,7 +112,9 @@ Keep your cards' statement PDFs in your data repo and open them from the dashboa
111
112
  your own AI agent on your computer (Claude Code or similar, with a Gmail connector), following
112
113
  [AGENTS.md](AGENTS.md#collect-statements-from-gmail); ownledger never connects to your email. `ownledger statements add`
113
114
  removes the bank's password (kept in `.env.statements`, git-ignored, on your computer only) and files each PDF under the
114
- month of its statement's close date. `ownledger statements check` lets your agent compare a statement with your ledger.
115
+ month of its statement's close date. `ownledger statements reconcile <card>` checks every statement of a card against
116
+ your ledger in one run (the bank's closing figure per month, rows missing or different), so your agent can propose the
117
+ fixes as one `batch`: one preview, one go, one commit.
115
118
 
116
119
  ## Development
117
120
 
@@ -6,6 +6,11 @@ import { loadLedger } from "../engine/load.js";
6
6
  import { statements } from "../modules/cards/statements.js";
7
7
  import { recordFor, termsOf } from "../modules/cards/terms.js";
8
8
  import { readDataDir } from "../node/files.js";
9
+ import { plan } from "../engine/actions.js";
10
+ import { yamlText } from "../engine/write.js";
11
+ import { STATEMENTS_FILE, withBankAmounts } from "../modules/cards/terms.js";
12
+ import { reconcile } from "../node/reconcile.js";
13
+ import { linesText, parseStatement, pdfLines } from "../node/statement-rows.js";
9
14
  import { ENV_FILE, missingMonths, monthFromText, passwordVars, PdfPasswordError, pdfText, readEnvFile, readSources, scanStatements, STATEMENTS_DIR, unlockPdf, } from "../node/statements.js";
10
15
  const USAGE = `Usage:
11
16
  ownledger statements add <account-id> <file.pdf>... [--month YYYY-MM] [--dir <repo>] [--yes] [--no-commit]
@@ -14,12 +19,17 @@ const USAGE = `Usage:
14
19
  ownledger statements list [<account-id>] [--dir <repo>]
15
20
  Which months each card has, and which are missing between the first and the last.
16
21
  ownledger statements check <account-id> <YYYY-MM> [--dir <repo>] [--json]
17
- The statement's text next to ownledger's figures and transactions for the same period, to compare.`;
22
+ One statement's rows and text (columns kept) next to ownledger's figures and transactions for the same period.
23
+ ownledger statements reconcile <account-id> [--from YYYY-MM] [--to YYYY-MM] [--dir <repo>] [--json] [--save-bank-amounts [--yes]]
24
+ Every filed statement of the card against the ledger: the bank's closing figure next to ownledger's per month,
25
+ rows missing on the ledger, ledger rows on no statement, typos, rows on the wrong account, balance adjustments.
26
+ Reports only. --json is shaped for one \`batch\` call. --save-bank-amounts saves each month's bank figure
27
+ (data/cards/statements.yaml): preview unless --yes.`;
18
28
  function opt(args, name) {
19
29
  const i = args.indexOf(name);
20
30
  return i >= 0 ? args[i + 1] : args.find((a) => a.startsWith(name + "="))?.slice(name.length + 1);
21
31
  }
22
- const positional = (args) => args.filter((a, i) => !a.startsWith("-") && !["--month", "--dir"].includes(args[i - 1] ?? ""));
32
+ const positional = (args) => args.filter((a, i) => !a.startsWith("-") && !["--month", "--dir", "--from", "--to"].includes(args[i - 1] ?? ""));
23
33
  function ledgerAt(root) {
24
34
  return loadLedger(readDataDir(root)).ledger;
25
35
  }
@@ -37,6 +47,8 @@ export async function cmdStatements(args) {
37
47
  return list(root, positional(rest)[0]);
38
48
  if (sub === "check")
39
49
  return check(root, rest);
50
+ if (sub === "reconcile")
51
+ return reconcileCmd(root, rest);
40
52
  console.log(USAGE);
41
53
  return 2;
42
54
  }
@@ -203,15 +215,19 @@ async function check(root, args) {
203
215
  })
204
216
  : [];
205
217
  let text;
218
+ let parsed = null;
206
219
  try {
207
- text = await pdfText(new Uint8Array(readFileSync(join(root, rel))));
220
+ const lines = await pdfLines(new Uint8Array(readFileSync(join(root, rel))));
221
+ text = linesText(lines);
222
+ if (stmt)
223
+ parsed = parseStatement(lines, stmt, readSources(root)[account], l.meta.base);
208
224
  }
209
225
  catch (e) {
210
226
  console.error(`${rel}: can't read the PDF's text (${e instanceof Error ? e.message : e}). Is it still locked? File it with \`ownledger statements add\`.`);
211
227
  return 1;
212
228
  }
213
229
  if (args.includes("--json")) {
214
- console.log(JSON.stringify({ account, month, file: rel, statement: stmt ?? null, transactions: txs, text }, null, 2));
230
+ console.log(JSON.stringify({ account, month, file: rel, statement: stmt ?? null, transactions: txs, bank_closing: parsed?.closing ?? null, rows: parsed?.rows ?? [], text }, null, 2));
215
231
  return 0;
216
232
  }
217
233
  console.log(`# ${account} statement ${month} (${rel})\n`);
@@ -226,6 +242,138 @@ async function check(root, args) {
226
242
  for (const t of txs)
227
243
  console.log(`| ${t.date} | ${fmt(t.amount)} | ${t.note.replace(/\|/g, "/")} | ${t.against} | ${t.id} |`);
228
244
  }
229
- console.log(`\n## Statement text (as extracted from the PDF)\n\n${text}`);
245
+ if (parsed) {
246
+ console.log(`\n## Rows read from the statement (${parsed.rows.length}; same signs as above)${parsed.closing !== null ? `, bank's closing figure ${fmt(parsed.closing)} ("${parsed.closingLabel}")` : ", no closing figure found (set closing_label in sources.yaml)"}\n`);
247
+ console.log("| date | amount | description |\n|---|---|---|");
248
+ for (const r of parsed.rows)
249
+ console.log(`| ${r.date} | ${fmt(r.amount)} | ${r.description.replace(/\|/g, "/")} |`);
250
+ }
251
+ console.log(`\n## Statement text (columns kept)\n\n${text}`);
252
+ console.log(`\nTo check every statement of the card at once: ownledger statements reconcile ${account}`);
253
+ return 0;
254
+ }
255
+ /* ------------------------------------------------------------------ reconcile */
256
+ async function reconcileCmd(root, args) {
257
+ const [account] = positional(args);
258
+ const fromM = opt(args, "--from");
259
+ const toM = opt(args, "--to");
260
+ if (!account || [fromM, toM].some((m) => m !== undefined && !/^\d{4}-(0[1-9]|1[0-2])$/.test(m))) {
261
+ console.log(USAGE);
262
+ return 2;
263
+ }
264
+ const files = readDataDir(root);
265
+ const l = loadLedger(files).ledger;
266
+ if (!l.accounts.some((a) => a.id === account)) {
267
+ console.error(`No account "${account}" in data/accounts.yaml.`);
268
+ return 1;
269
+ }
270
+ if (!statementDayOf(l, account)) {
271
+ console.error(`${account} has no statement_day: set it (edit_account details.statement_day) so statement periods are known.`);
272
+ return 1;
273
+ }
274
+ const asOf = todayIn();
275
+ const periods = new Map(statements(l, account, asOf).filter((s) => !s.open).map((s) => [s.close.slice(0, 7), s]));
276
+ const layout = readSources(root)[account];
277
+ const list = scanStatements(root, new Set([account])).files.filter((f) => f.account === account && (!fromM || f.month >= fromM) && (!toM || f.month <= toM));
278
+ if (!list.length) {
279
+ console.error(`No statements filed for ${account}${fromM || toM ? " in that range" : ""} (${STATEMENTS_DIR}/${account}/<YYYY-MM>.pdf). File them with \`ownledger statements add\`.`);
280
+ return 1;
281
+ }
282
+ const filed = [];
283
+ for (const f of list) {
284
+ const p = periods.get(f.month);
285
+ try {
286
+ const lines = await pdfLines(new Uint8Array(readFileSync(join(root, f.path))));
287
+ const parsed = p ? parseStatement(lines, p, layout, l.meta.base) : { rows: [], closing: null };
288
+ filed.push({ month: f.month, path: f.path, rows: parsed.rows, closing: parsed.closing });
289
+ }
290
+ catch (e) {
291
+ filed.push({ month: f.month, path: f.path, rows: [], closing: null, error: `can't read the PDF (${e instanceof Error ? e.message : e}); still locked? file it with \`ownledger statements add\`` });
292
+ }
293
+ }
294
+ const r = reconcile(l, account, filed, asOf);
295
+ if (args.includes("--json"))
296
+ console.log(JSON.stringify(r, null, 2));
297
+ else
298
+ printReconcile(r);
299
+ if (args.includes("--save-bank-amounts"))
300
+ return saveBankAmounts(root, files, l, r, args.includes("--yes"));
301
+ return 0;
302
+ }
303
+ function printReconcile(r) {
304
+ const sign = (n) => (n === null ? "—" : n > 0 ? `+${fmt(n)}` : fmt(n));
305
+ console.log(`# ${r.account}: ${r.months.length} statement(s), ${r.from} … ${r.to}\n`);
306
+ console.log("Amounts on the card like the ledger: negative = spent, positive = paid back / refunded / cashback. Gap = ownledger − bank.\n");
307
+ console.log("| month | period | rows | bank | ownledger | gap | of which timing | change | missing | |\n|---|---|---|---|---|---|---|---|---|---|");
308
+ for (const m of r.months) {
309
+ const note = m.error ?? (m.diff && m.timing === m.diff ? "timing only: rows on the other side of the close date" : m.bankFrom === "saved" ? "bank figure from data/cards/statements.yaml" : m.bank === null ? "no closing figure found: set closing_label in sources.yaml" : "");
310
+ console.log(`| ${m.month} | ${m.from ? `${m.from} … ${m.close}` : ""} | ${m.rows} | ${m.bank === null ? "—" : fmt(m.bank)} | ${m.ledger === null ? "—" : fmt(m.ledger)} | ${m.diff ? sign(m.diff) : m.diff === 0 ? "✓" : "—"} | ${m.timing ? sign(m.timing) : ""} | ${m.change ? sign(m.change) : ""} | ${m.missing || ""} | ${note} |`);
311
+ }
312
+ console.log(`\nMatched ${r.matched} row(s).`);
313
+ const row = (x) => `${x.date} ${fmt(x.amount).padStart(12)} ${(x.description ?? x.note ?? "").slice(0, 70)}`;
314
+ if (r.missing.length) {
315
+ console.log(`\n## On a statement, not on the ledger (${r.missing.length}, total ${fmt(r.missing.reduce((s, x) => s + x.amount, 0))})\n`);
316
+ for (const x of r.missing)
317
+ console.log(`- ${row(x)} (${x.month})`);
318
+ }
319
+ if (r.amountDiffs.length) {
320
+ console.log(`\n## Different amount (${r.amountDiffs.length}): statement → ledger\n`);
321
+ for (const x of r.amountDiffs)
322
+ console.log(`- ${x.statement.date} ${fmt(x.statement.amount)} → ledger ${x.ledger.date} ${fmt(x.ledger.amount)} "${x.ledger.note}" (${x.ledger.id})`);
323
+ }
324
+ if (r.otherAccount.length) {
325
+ console.log(`\n## Probably booked on another account (${r.otherAccount.length})\n`);
326
+ for (const x of r.otherAccount)
327
+ console.log(`- ${row(x.statement)} → on ${x.ledger.account}: ${x.ledger.date} "${x.ledger.note}" (${x.ledger.id})`);
328
+ }
329
+ if (r.notOnStatement.length) {
330
+ console.log(`\n## On the ledger, on no statement (${r.notOnStatement.length}, total ${fmt(r.notOnStatement.reduce((s, x) => s + x.amount, 0))})\n`);
331
+ for (const x of r.notOnStatement)
332
+ console.log(`- ${row(x)} [${x.against}] (${x.id})`);
333
+ }
334
+ if (r.adjustments.length) {
335
+ console.log(`\n## Balance adjustments covering a gap (${r.adjustments.length}): replace them with the real rows above\n`);
336
+ for (const x of r.adjustments)
337
+ console.log(`- ${row(x)} (${x.id})`);
338
+ }
339
+ if (r.joined.length) {
340
+ console.log(`\n## Matched as a sum (${r.joined.length}): fine, shown so you know\n`);
341
+ for (const j of r.joined)
342
+ console.log(`- statement ${j.statement.map((x) => `${x.date} ${fmt(x.amount)}`).join(" + ")} = ledger ${j.ledger.map((x) => `${x.date} ${fmt(x.amount)}`).join(" + ")}`);
343
+ }
344
+ if (r.netZero.length) {
345
+ console.log(`\n## Missing but net 0 (${r.netZero.length}): a purchase and its refund/cashback, both not on the ledger\n`);
346
+ for (const z of r.netZero)
347
+ console.log(`- ${z.map((x) => `${x.date} ${fmt(x.amount)} ${x.description.slice(0, 40)}`).join(" + ")}`);
348
+ }
349
+ const clean = !r.missing.length && !r.amountDiffs.length && !r.otherAccount.length && !r.notOnStatement.length && !r.adjustments.length && r.months.every((m) => !m.diff || m.diff === m.timing);
350
+ console.log(clean ? "\n✓ Every statement agrees with the ledger." : "\nNext: propose the fixes to the owner as ONE batch (connector `batch`, or --json for the hints). Never add a balance adjustment to cover a gap.");
351
+ }
352
+ function saveBankAmounts(root, files, l, r, yes) {
353
+ const set = r.months.filter((m) => m.bank !== null && m.bankFrom === "pdf" && m.close).map((m) => ({ account: r.account, statement_date: m.close, amount: m.bank }));
354
+ const had = new Map(withBankAmounts(l, []).map((x) => [`${x.account}|${x.statement_date}`, x.amount]));
355
+ const changes = set.filter((x) => had.get(`${x.account}|${x.statement_date}`) !== x.amount);
356
+ if (!changes.length) {
357
+ console.log("\nBank amounts: nothing new to save.");
358
+ return 0;
359
+ }
360
+ const p = plan(files, { putFiles: { [STATEMENTS_FILE]: yamlText(withBankAmounts(l, changes)) } }, `Card statements: ${r.account} bank amounts ${changes.map((x) => x.statement_date.slice(0, 7)).join(", ")}`);
361
+ console.log(`\nBank amounts to save in ${STATEMENTS_FILE} (${changes.length}):`);
362
+ for (const x of changes)
363
+ console.log(`- ${x.statement_date}: ${fmt(x.amount)}${had.has(`${x.account}|${x.statement_date}`) ? ` (was ${fmt(had.get(`${x.account}|${x.statement_date}`))})` : ""}`);
364
+ if (!yes) {
365
+ console.log("\nPreview only: nothing written. Run again with --save-bank-amounts --yes after the owner's go.");
366
+ return 0;
367
+ }
368
+ for (const [path, content] of Object.entries(p.files)) {
369
+ mkdirSync(dirname(join(root, path)), { recursive: true });
370
+ writeFileSync(join(root, path), content);
371
+ }
372
+ console.log(`✓ Saved ${STATEMENTS_FILE}`);
373
+ if (existsSync(join(root, ".git"))) {
374
+ execFileSync("git", ["add", ...Object.keys(p.files)], { cwd: root });
375
+ execFileSync("git", ["commit", "-q", "-m", p.message], { cwd: root, stdio: "inherit" });
376
+ console.log(`✓ Committed: ${p.message.split("\n")[0]}`);
377
+ }
230
378
  return 0;
231
379
  }
@@ -44,6 +44,34 @@ export declare function linesOf(t: SimpleTx): Line[];
44
44
  export declare function addTransaction(files: FileMap, t: SimpleTx, meta?: WriteMeta): Planned;
45
45
  export declare function editTransaction(files: FileMap, id: string, patch: Partial<SimpleTx>, meta?: WriteMeta): Planned;
46
46
  export declare function voidTransaction(files: FileMap, id: string, reason?: string, meta?: WriteMeta): Planned;
47
+ export type BatchOp = ({
48
+ op: "add";
49
+ reason?: string;
50
+ } & SimpleTx) | ({
51
+ op: "edit";
52
+ id: string;
53
+ reason?: string;
54
+ } & Partial<SimpleTx>) | {
55
+ op: "void";
56
+ id: string;
57
+ reason?: string;
58
+ };
59
+ export declare const BATCH_MAX = 200;
60
+ export interface BatchPlanned extends Planned {
61
+ /** Change in each account's balance (base currency) over the whole batch. */
62
+ balanceChange: Record<string, number>;
63
+ counts: {
64
+ add: number;
65
+ edit: number;
66
+ void: number;
67
+ };
68
+ }
69
+ /**
70
+ * Many adds, edits and voids as one change: the ops run one after another on the evolving files
71
+ * (an op can edit or void a row an earlier op added), check runs once on the result, one commit.
72
+ * Any op failing refuses the whole batch, naming the op.
73
+ */
74
+ export declare function batch(files: FileMap, ops: BatchOp[], meta?: WriteMeta): BatchPlanned;
47
75
  /** The ledger of a set of files, for actions that read it before building a change. */
48
76
  export declare function loadForAction(files: FileMap): {
49
77
  ledger: import("./types.js").Ledger;
@@ -67,6 +67,10 @@ export function linesOf(t) {
67
67
  : [{ account: t.account, amount: -a }, { category: t.category, amount: a }];
68
68
  }
69
69
  export function addTransaction(files, t, meta) {
70
+ const b = buildAdd(t, meta);
71
+ return plan(files, b.change, b.message);
72
+ }
73
+ function buildAdd(t, meta) {
70
74
  if (!isDate(t.date))
71
75
  throw new ActionError("date must be yyyy-mm-dd");
72
76
  const tx = {
@@ -80,7 +84,8 @@ export function addTransaction(files, t, meta) {
80
84
  ...(t.plan ? { plan: t.plan } : {}),
81
85
  lines: linesOf(t),
82
86
  };
83
- return plan(files, { addTransactions: [trailed(tx, "add", meta)] }, withMeta(`Add: ${t.date} ${t.note ?? ""}`.trim(), meta));
87
+ const done = trailed(tx, "add", meta);
88
+ return { change: { addTransactions: [done] }, message: withMeta(`Add: ${t.date} ${t.note ?? ""}`.trim(), meta), tx: done };
84
89
  }
85
90
  function findTx(files, id) {
86
91
  for (const [p, text] of Object.entries(files)) {
@@ -93,6 +98,10 @@ function findTx(files, id) {
93
98
  throw new ActionError(`no transaction ${id}`);
94
99
  }
95
100
  export function editTransaction(files, id, patch, meta) {
101
+ const b = buildEdit(files, id, patch, meta);
102
+ return plan(files, b.change, b.message);
103
+ }
104
+ function buildEdit(files, id, patch, meta) {
96
105
  const old = findTx(files, id);
97
106
  const next = { ...old };
98
107
  for (const k of ["date", "time", "note", "who", "event", "tags", "plan"]) {
@@ -104,7 +113,8 @@ export function editTransaction(files, id, patch, meta) {
104
113
  }
105
114
  if (!isDate(next.date))
106
115
  throw new ActionError("date must be yyyy-mm-dd");
107
- return plan(files, { replaceTransactions: [trailed(next, "edit", meta)] }, withMeta(`Edit: ${next.date} ${next.note ?? ""}`.trim(), meta));
116
+ const done = trailed(next, "edit", meta);
117
+ return { change: { replaceTransactions: [done] }, message: withMeta(`Edit: ${next.date} ${next.note ?? ""}`.trim(), meta), tx: done, old };
108
118
  }
109
119
  /** Best-effort simple view of a transaction (to let an edit change just one field). */
110
120
  function simpleOf(t) {
@@ -122,11 +132,107 @@ function simpleOf(t) {
122
132
  return { lines: t.lines };
123
133
  }
124
134
  export function voidTransaction(files, id, reason, meta) {
135
+ const b = buildVoid(files, id, reason, meta);
136
+ return plan(files, b.change, b.message);
137
+ }
138
+ function buildVoid(files, id, reason, meta) {
125
139
  const old = findTx(files, id);
126
140
  if (old.void)
127
141
  throw new ActionError(`${id} is already void`);
128
142
  const next = { ...old, void: true, ...(reason ? { void_reason: reason } : {}) };
129
- return plan(files, { replaceTransactions: [trailed(next, "void", meta)] }, withMeta(`Void: ${old.date} ${old.note ?? ""}`.trim(), meta));
143
+ const done = trailed(next, "void", meta);
144
+ return { change: { replaceTransactions: [done] }, message: withMeta(`Void: ${old.date} ${old.note ?? ""}`.trim(), meta), tx: done, old };
145
+ }
146
+ export const BATCH_MAX = 200;
147
+ function joinReason(batch, own) {
148
+ const r = [batch?.trim(), own?.trim()].filter(Boolean).join("; ").replace(/\s+/g, " ");
149
+ if (!r)
150
+ return undefined;
151
+ return r.length > REASON_MAX ? r.slice(0, REASON_MAX - 1) + "…" : r;
152
+ }
153
+ /**
154
+ * Many adds, edits and voids as one change: the ops run one after another on the evolving files
155
+ * (an op can edit or void a row an earlier op added), check runs once on the result, one commit.
156
+ * Any op failing refuses the whole batch, naming the op.
157
+ */
158
+ export function batch(files, ops, meta) {
159
+ if (!ops.length)
160
+ throw new ActionError("batch: no ops");
161
+ if (ops.length > BATCH_MAX)
162
+ throw new ActionError(`batch: at most ${BATCH_MAX} ops (got ${ops.length})`);
163
+ let cur = files;
164
+ const changed = new Set();
165
+ const finals = new Map(); // id -> final version
166
+ const originals = new Map(); // id -> version before the batch (null: added here)
167
+ const counts = { add: 0, edit: 0, void: 0 };
168
+ ops.forEach((o, i) => {
169
+ const m = meta ? { ...meta, reason: joinReason(meta.reason, o.reason) } : undefined;
170
+ let b;
171
+ try {
172
+ if (o.op === "add") {
173
+ const { op: _op, reason: _r, ...t } = o;
174
+ b = buildAdd(t, m);
175
+ }
176
+ else if (o.op === "edit") {
177
+ const { op: _op, reason: _r, id, ...patch } = o;
178
+ b = buildEdit(cur, id, patch, m);
179
+ }
180
+ else if (o.op === "void") {
181
+ b = buildVoid(cur, o.id, o.reason ?? meta?.reason, m);
182
+ }
183
+ else
184
+ throw new ActionError(`unknown op "${o.op}"`);
185
+ }
186
+ catch (e) {
187
+ throw new ActionError(`batch refused: op ${i + 1} (${o.op}${"id" in o && o.id ? ` ${o.id}` : ""}) failed: ${e.message}`);
188
+ }
189
+ counts[o.op]++;
190
+ if (!originals.has(b.tx.id))
191
+ originals.set(b.tx.id, b.old ?? null);
192
+ finals.set(b.tx.id, b.tx);
193
+ const out = applyChange(cur, b.change);
194
+ for (const p of Object.keys(out))
195
+ changed.add(p);
196
+ cur = { ...cur, ...out };
197
+ });
198
+ const r = checkFiles(cur);
199
+ if (!r.ok)
200
+ throw new ActionError(`batch refused, the result would not pass check:\n${r.errors.slice(0, 10).map((e) => `- ${e.where ? `[${e.where}] ` : ""}${e.message}`).join("\n")}`);
201
+ const before = new Set(checkFiles(files).warnings.map((w) => `${w.file}|${w.where}|${w.message}`));
202
+ const out = {};
203
+ for (const p of changed)
204
+ if (cur[p] !== files[p])
205
+ out[p] = cur[p];
206
+ const add = [];
207
+ const rep = [];
208
+ const balanceChange = {};
209
+ const bump = (t, sign) => {
210
+ if (!t || t.void)
211
+ return;
212
+ for (const l of t.lines)
213
+ if (l.account)
214
+ balanceChange[l.account] = (balanceChange[l.account] ?? 0) + sign * l.amount;
215
+ };
216
+ for (const [id, t] of finals) {
217
+ const old = originals.get(id) ?? null;
218
+ (old ? rep : add).push(t);
219
+ bump(t, 1);
220
+ bump(old, -1);
221
+ }
222
+ for (const [k, v] of Object.entries(balanceChange))
223
+ if (v === 0)
224
+ delete balanceChange[k];
225
+ const parts = [counts.add && `${counts.add} add${counts.add > 1 ? "s" : ""}`, counts.edit && `${counts.edit} edit${counts.edit > 1 ? "s" : ""}`, counts.void && `${counts.void} void${counts.void > 1 ? "s" : ""}`].filter(Boolean);
226
+ const change = { ...(add.length ? { addTransactions: add } : {}), ...(rep.length ? { replaceTransactions: rep } : {}) };
227
+ return {
228
+ change,
229
+ files: out,
230
+ summary: [`batch: ${parts.join(", ")}`, ...describeChange(change)],
231
+ message: withMeta(`Batch: ${parts.join(", ")}`, meta),
232
+ warnings: r.warnings.filter((w) => !before.has(`${w.file}|${w.where}|${w.message}`)),
233
+ balanceChange,
234
+ counts,
235
+ };
130
236
  }
131
237
  /** The ledger of a set of files, for actions that read it before building a change. */
132
238
  export function loadForAction(files) {
@@ -84,6 +84,8 @@ export interface CardsData {
84
84
  }
85
85
  /** The cards module's data, loaded with the ledger (see ModuleDef.load). */
86
86
  export declare function cardsData(l: Ledger): CardsData;
87
+ /** data/cards/statements.yaml with these bank amounts set (one per account + statement date), sorted. */
88
+ export declare function withBankAmounts(l: Ledger, set: BankStatement[]): BankStatement[];
87
89
  export declare function recordFor(l: Ledger, account: string): CardRecord | undefined;
88
90
  /** Category emoji → category path. The owner's mapping can add its own (mapping key `card_emoji`). */
89
91
  export declare const DEFAULT_CARD_EMOJI: Record<string, string>;
@@ -70,6 +70,13 @@ export const STATEMENTS_FILE = "data/cards/statements.yaml";
70
70
  export function cardsData(l) {
71
71
  return l.ext?.cards ?? { records: [], statements: [] };
72
72
  }
73
+ /** data/cards/statements.yaml with these bank amounts set (one per account + statement date), sorted. */
74
+ export function withBankAmounts(l, set) {
75
+ const key = (x) => `${x.account}|${x.statement_date}`;
76
+ const keys = new Set(set.map(key));
77
+ const list = [...cardsData(l).statements.filter((x) => !keys.has(key(x))), ...set];
78
+ return list.sort((x, y) => (x.statement_date < y.statement_date ? -1 : x.statement_date > y.statement_date ? 1 : x.account < y.account ? -1 : 1));
79
+ }
73
80
  export function recordFor(l, account) {
74
81
  return cardsData(l).records.find((r) => r.account === account);
75
82
  }
@@ -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";
@@ -280,6 +281,25 @@ export async function api(req, env, source) {
280
281
  const { preview_id } = (await req.json());
281
282
  return json(await applyPending(env, src, preview_id));
282
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
+ }
283
303
  case "grants": {
284
304
  if (req.method === "DELETE") {
285
305
  const id = q.get("id");
@@ -19,14 +19,14 @@ import { yamlText } from "../engine/write.js";
19
19
  import { dashboardOf } from "./api.js";
20
20
  import { cardList } from "../modules/cards/index.js";
21
21
  import { cashback, closeOnOrAfter, feeWaiver, lineKind, statements } from "../modules/cards/statements.js";
22
- import { cardsData, STATEMENTS_FILE, termsOf, recordFor } from "../modules/cards/terms.js";
22
+ import { STATEMENTS_FILE, termsOf, recordFor, withBankAmounts } from "../modules/cards/terms.js";
23
23
  import { bestCard } from "./bestcard.js";
24
24
  import { openWalletClient } from "./openwallet.js";
25
25
  const out = (v) => ({ content: [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v) }] });
26
26
  const fail = (msg) => ({ content: [{ type: "text", text: msg }], isError: true });
27
27
  const INSTRUCTIONS = `ownledger: the owner's personal finance ledger, kept in their private GitHub repo.
28
28
  Amounts are whole numbers in the base currency (see about). Answers are computed here; never add up raw rows yourself when a tool computes it.
29
- Writes: the add_/edit_/void_/set_/remove_ tools only PREVIEW. Show the owner the preview (what, amounts, accounts), wait for their explicit go, then call apply with the preview_id. Never invent an amount, date, account or category: ask. Call rules once before the first write.
29
+ Writes: the add_/edit_/void_/set_/remove_ tools and batch only PREVIEW. Show the owner the preview (what, amounts, accounts), wait for their explicit go, then call apply with the preview_id. Never invent an amount, date, account or category: ask. Call rules once before the first write. For more than ~3 transaction writes at once, use batch: one preview, one go, one commit.
30
30
  Dashboard: when the owner asks to "track", "watch" or "put on my dashboard" something, offer a widget (add_widget), using the categories and accounts from rules.
31
31
  Cards: for "which card should I use", call best_card; statements, cashback and fee waivers come from cards and card_statement.`;
32
32
  const OPENWALLET_LINE = `
@@ -92,18 +92,22 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
92
92
  return fail(`error: ${e.message}`);
93
93
  }
94
94
  };
95
- const preview = async (build) => {
95
+ const preview = async (build, show = 20) => {
96
96
  const s = await snap();
97
97
  const p = build(s.files);
98
98
  const id = await savePending(env, { baseSha: s.sha, files: p.files, message: p.message, summary: p.summary, created: new Date().toISOString() });
99
99
  const shown = [];
100
- for (const t of [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])].slice(0, 20))
100
+ const all = [...(p.change.addTransactions ?? []), ...(p.change.replaceTransactions ?? [])];
101
+ for (const t of all.slice(0, show))
101
102
  shown.push(compactTx(t));
103
+ const b = p;
102
104
  return {
103
105
  preview_id: id,
104
106
  will: p.summary,
105
107
  commit_message: p.message,
106
108
  ...(shown.length ? { transactions: shown } : {}),
109
+ ...(all.length > shown.length ? { not_shown: all.length - shown.length } : {}),
110
+ ...(b.balanceChange ? { balance_change: b.balanceChange } : {}),
107
111
  ...(p.warnings.length ? { warnings: p.warnings.map((w) => w.message) } : {}),
108
112
  next: "Show this to the owner. Only after their explicit go, call apply with this preview_id.",
109
113
  };
@@ -327,6 +331,29 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
327
331
  }));
328
332
  server.registerTool("edit_transaction", { description: "PREVIEW changes to a transaction by id (only the fields given change).", inputSchema: z.object({ id: z.string(), ...txFields, date: z.string().optional(), reason }), annotations: pv }, wrap(async ({ id, reason, ...patch }) => preview((f) => A.editTransaction(f, id, patch, meta(reason)))));
329
333
  server.registerTool("void_transaction", { description: "PREVIEW voiding a transaction (kept in history, excluded everywhere).", inputSchema: z.object({ id: z.string(), reason }), annotations: pv }, wrap(async ({ id, reason }) => preview((f) => A.voidTransaction(f, id, reason, meta(reason)))));
334
+ const batchOp = z.object(txFields).partial().extend({
335
+ op: z.enum(["add", "edit", "void"]),
336
+ id: z.string().optional().describe("edit / void: the transaction id"),
337
+ reason: z.string().trim().max(A.REASON_MAX).optional().describe("optional: this op's own reason, added to the batch's"),
338
+ });
339
+ server.registerTool("batch", {
340
+ description: `PREVIEW many adds, edits and voids as ONE change (writes nothing): one preview, one go, one commit. Use it for more than ~3 writes (e.g. fixes from a statement check). Each op takes the same fields as add_transaction / edit_transaction / void_transaction plus op. Ops run in order; if any op fails, the whole batch is refused and the reply names the op. Max ${A.BATCH_MAX} ops.`,
341
+ inputSchema: z.object({ ops: z.array(batchOp).min(1).max(A.BATCH_MAX), reason }),
342
+ annotations: pv,
343
+ }, wrap(async ({ ops, reason }) => {
344
+ const s = await snap();
345
+ const p = poolOf(s.ledger, dashboardOf(s.files, props.login)?.prefs?.pool, now());
346
+ const list = ops.map((o, i) => {
347
+ if (o.op !== "add" && !o.id)
348
+ throw new A.ActionError(`batch refused: op ${i + 1} (${o.op}) needs an id`);
349
+ if (o.op === "add" && !o.date)
350
+ throw new A.ActionError(`batch refused: op ${i + 1} (add) needs a date`);
351
+ if (o.op === "add" && !o.lines?.length && !o.account && p.on && p.default_account)
352
+ return { ...o, account: p.default_account };
353
+ return o;
354
+ });
355
+ return preview((f) => A.batch(f, list, meta(reason)), A.BATCH_MAX);
356
+ }));
330
357
  const accountFields = {
331
358
  name: z.string(),
332
359
  type: z.string().describe("cash, bank, ewallet, credit_card, bnpl, deposit, savings_goal, gold, fund, stock, etf, crypto, insurance, loan_given, loan_taken, other (or a new one)"),
@@ -410,9 +437,7 @@ export function buildServer(env, props, src = sourceFor(env), deps = {}) {
410
437
  const { ledger } = A.loadForAction(f);
411
438
  if (!ledger.accounts.some((a) => a.id === account))
412
439
  throw new A.ActionError(`no account ${account}`);
413
- const list = cardsData(ledger).statements.filter((x) => !(x.account === account && x.statement_date === statement_date));
414
- list.push({ account, statement_date, amount });
415
- list.sort((x, y) => (x.statement_date < y.statement_date ? -1 : x.statement_date > y.statement_date ? 1 : x.account < y.account ? -1 : 1));
440
+ const list = withBankAmounts(ledger, [{ account, statement_date, amount }]);
416
441
  return A.plan(f, { putFiles: { [STATEMENTS_FILE]: yamlText(list) } }, `Card statement: ${account} ${statement_date}`);
417
442
  })));
418
443
  server.registerTool("add_instalment", { description: "PREVIEW turning a card purchase into a 0% instalment plan (trả góp 0%): each statement then counts only the monthly amount.", inputSchema: z.object({ transaction: z.string().describe("id of the purchase on the card"), count: z.number().int().min(2).max(60), fee: z.number().int().min(0).optional().describe("conversion fee per month, if any"), id: z.string().optional(), name: z.string().optional(), first_statement: z.string().optional().describe("yyyy-mm-dd; default the first statement after the purchase") }), annotations: pv }, wrap(async ({ transaction, count, fee, id, name, first_statement }) => preview((f) => {
@@ -1 +1 @@
1
- export declare const VERSION = "2.1.1";
1
+ export declare const VERSION = "2.2.0";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "2.1.1";
2
+ export const VERSION = "2.2.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "2.1.1",
3
+ "version": "2.2.0",
4
4
  "description": "Personal finance ledger used through AI chat (MCP). Your data in your own private GitHub repo, served by your own Cloudflare Worker.",
5
5
  "license": "MIT",
6
6
  "author": "phucbm",