ownledger 2.1.1 → 2.3.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,27 @@ 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. When a bank prints its closing figure without a label (reconcile says "no closing figure found"),
130
+ read the figures off the PDFs and save them as `statement_amount` ops in the same `batch` (`account`,
131
+ `statement_date` = the close date, `amount`); reconcile then compares those months too.
132
+
133
+ `npx ownledger statements check <account-id> <YYYY-MM>` shows one statement: ownledger's figures and transactions for
134
+ the period, the rows read from the PDF, and its text with columns kept.
117
135
 
118
136
  `npx ownledger check` warns about statement files that don't fit (a folder that isn't an account, a name that isn't
119
137
  `YYYY-MM.pdf`, a PDF still locked).
@@ -123,7 +141,7 @@ the PDF on your own: each fix is a normal write (preview → go). The bank's sta
123
141
  1. Show the owner exactly what will change (the transactions, with amounts and accounts) and wait for their go.
124
142
  2. Never invent an amount, date or account. Ask if anything is missing.
125
143
  3. Run `npx ownledger check`; it must pass.
126
- 4. One commit per change, with a readable message.
144
+ 4. One commit per change, with a readable message. Many related transaction fixes are one change: use `batch`.
127
145
 
128
146
  ## First import of a new app
129
147
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.3.0 (2026-11-23)
4
+
5
+ - **`batch` saves bank statement amounts too:** op `statement_amount` (`account`, `statement_date`, `amount`; 0
6
+ allowed), the same as `add_statement_amount`, so a whole statement check (the transaction fixes and every month's bank
7
+ figure) is one preview and one commit. For banks whose PDFs print the closing figure without a label.
8
+
9
+ ## 2.2.0 (2026-11-23)
10
+
11
+ Batch writes, and checking every statement of a card in one run (plan 005). Data format stays 1.
12
+
13
+ - **Batch writes:** the connector's `batch` tool previews many adds, edits and voids as **one** change: one preview,
14
+ one go from the owner, one commit ("Batch: 28 adds, 4 edits, 4 voids"). Ops run in order on the evolving data, check
15
+ runs once on the result, and if any op fails the whole batch is refused, naming the op. The preview shows every
16
+ transaction (up to 200) and the balance change per account. Each row's trail gets the batch's reason plus the op's
17
+ own. Also `POST /api/batch` + `/api/batch/apply` for the dashboard (no UI yet).
18
+ - **`ownledger statements reconcile <card>`** (`--from`/`--to`, `--json`): every filed statement against the ledger.
19
+ Per month the bank's closing figure next to ownledger's (gap, change from the month before, and the part that is
20
+ only timing), then the rows missing on the ledger, ledger rows on no statement, amounts that differ, rows probably on
21
+ another account, and balance adjustments covering a gap. Fee + VAT (or purchase + DCC fee + VAT) booked as one row,
22
+ and purchases refunded in full, are matched and shown apart. `--json` carries a `batch` op hint per item.
23
+ `--save-bank-amounts` saves each month's bank figure in `data/cards/statements.yaml` (preview; `--yes`). Reads the
24
+ PDFs on your computer only, as before.
25
+ - **Statement rows by general rules**, no bank-specific code: the PDF's text with its columns kept, a row is a date +
26
+ a description + an amount (with CR/DR, minus, brackets, currency marks; foreign-currency amounts skipped; debit and
27
+ credit columns when the statement has them; a description wrapped onto the lines around the row). What a bank does
28
+ differently is data in `imports/statements/sources.yaml`: `closing_label`, `credit_words`, `skip_words`,
29
+ `amount_column`.
30
+ - `ownledger statements check` now shows the rows it read and the text with columns kept.
31
+ - Connector instructions: use `batch` for more than ~3 writes.
32
+
3
33
  ## 2.1.1 (2026-11-23)
4
34
 
5
35
  - **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,43 @@ 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
+ /** The bank's amount for a card statement (data/cards/statements.yaml), like add_statement_amount. */
60
+ | {
61
+ op: "statement_amount";
62
+ account: string;
63
+ statement_date: string;
64
+ amount: number;
65
+ reason?: string;
66
+ };
67
+ export declare const BATCH_MAX = 200;
68
+ export interface BatchPlanned extends Planned {
69
+ /** Change in each account's balance (base currency) over the whole batch. */
70
+ balanceChange: Record<string, number>;
71
+ counts: {
72
+ add: number;
73
+ edit: number;
74
+ void: number;
75
+ statement_amount: number;
76
+ };
77
+ }
78
+ /**
79
+ * Many adds, edits and voids as one change: the ops run one after another on the evolving files
80
+ * (an op can edit or void a row an earlier op added), check runs once on the result, one commit.
81
+ * Any op failing refuses the whole batch, naming the op.
82
+ */
83
+ export declare function batch(files: FileMap, ops: BatchOp[], meta?: WriteMeta): BatchPlanned;
47
84
  /** The ledger of a set of files, for actions that read it before building a change. */
48
85
  export declare function loadForAction(files: FileMap): {
49
86
  ledger: import("./types.js").Ledger;
@@ -4,6 +4,7 @@ import { flattenCategories } from "./categories.js";
4
4
  import { isDate } from "./dates.js";
5
5
  import { LEDGER_FILE_RE, loadLedger, parseJsonl, PATHS } from "./load.js";
6
6
  import { applyChange, describeChange, yamlText } from "./write.js";
7
+ import { STATEMENTS_FILE, withBankAmounts } from "../modules/cards/terms.js";
7
8
  export class ActionError extends Error {
8
9
  }
9
10
  function newId(prefix = "t_") {
@@ -67,6 +68,10 @@ export function linesOf(t) {
67
68
  : [{ account: t.account, amount: -a }, { category: t.category, amount: a }];
68
69
  }
69
70
  export function addTransaction(files, t, meta) {
71
+ const b = buildAdd(t, meta);
72
+ return plan(files, b.change, b.message);
73
+ }
74
+ function buildAdd(t, meta) {
70
75
  if (!isDate(t.date))
71
76
  throw new ActionError("date must be yyyy-mm-dd");
72
77
  const tx = {
@@ -80,7 +85,8 @@ export function addTransaction(files, t, meta) {
80
85
  ...(t.plan ? { plan: t.plan } : {}),
81
86
  lines: linesOf(t),
82
87
  };
83
- return plan(files, { addTransactions: [trailed(tx, "add", meta)] }, withMeta(`Add: ${t.date} ${t.note ?? ""}`.trim(), meta));
88
+ const done = trailed(tx, "add", meta);
89
+ return { change: { addTransactions: [done] }, message: withMeta(`Add: ${t.date} ${t.note ?? ""}`.trim(), meta), tx: done };
84
90
  }
85
91
  function findTx(files, id) {
86
92
  for (const [p, text] of Object.entries(files)) {
@@ -93,6 +99,10 @@ function findTx(files, id) {
93
99
  throw new ActionError(`no transaction ${id}`);
94
100
  }
95
101
  export function editTransaction(files, id, patch, meta) {
102
+ const b = buildEdit(files, id, patch, meta);
103
+ return plan(files, b.change, b.message);
104
+ }
105
+ function buildEdit(files, id, patch, meta) {
96
106
  const old = findTx(files, id);
97
107
  const next = { ...old };
98
108
  for (const k of ["date", "time", "note", "who", "event", "tags", "plan"]) {
@@ -104,7 +114,8 @@ export function editTransaction(files, id, patch, meta) {
104
114
  }
105
115
  if (!isDate(next.date))
106
116
  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));
117
+ const done = trailed(next, "edit", meta);
118
+ return { change: { replaceTransactions: [done] }, message: withMeta(`Edit: ${next.date} ${next.note ?? ""}`.trim(), meta), tx: done, old };
108
119
  }
109
120
  /** Best-effort simple view of a transaction (to let an edit change just one field). */
110
121
  function simpleOf(t) {
@@ -122,11 +133,125 @@ function simpleOf(t) {
122
133
  return { lines: t.lines };
123
134
  }
124
135
  export function voidTransaction(files, id, reason, meta) {
136
+ const b = buildVoid(files, id, reason, meta);
137
+ return plan(files, b.change, b.message);
138
+ }
139
+ function buildVoid(files, id, reason, meta) {
125
140
  const old = findTx(files, id);
126
141
  if (old.void)
127
142
  throw new ActionError(`${id} is already void`);
128
143
  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));
144
+ const done = trailed(next, "void", meta);
145
+ return { change: { replaceTransactions: [done] }, message: withMeta(`Void: ${old.date} ${old.note ?? ""}`.trim(), meta), tx: done, old };
146
+ }
147
+ export const BATCH_MAX = 200;
148
+ function joinReason(batch, own) {
149
+ const r = [batch?.trim(), own?.trim()].filter(Boolean).join("; ").replace(/\s+/g, " ");
150
+ if (!r)
151
+ return undefined;
152
+ return r.length > REASON_MAX ? r.slice(0, REASON_MAX - 1) + "…" : r;
153
+ }
154
+ /**
155
+ * Many adds, edits and voids as one change: the ops run one after another on the evolving files
156
+ * (an op can edit or void a row an earlier op added), check runs once on the result, one commit.
157
+ * Any op failing refuses the whole batch, naming the op.
158
+ */
159
+ export function batch(files, ops, meta) {
160
+ if (!ops.length)
161
+ throw new ActionError("batch: no ops");
162
+ if (ops.length > BATCH_MAX)
163
+ throw new ActionError(`batch: at most ${BATCH_MAX} ops (got ${ops.length})`);
164
+ let cur = files;
165
+ const changed = new Set();
166
+ const finals = new Map(); // id -> final version
167
+ const originals = new Map(); // id -> version before the batch (null: added here)
168
+ const counts = { add: 0, edit: 0, void: 0, statement_amount: 0 };
169
+ const amounts = [];
170
+ ops.forEach((o, i) => {
171
+ const m = meta ? { ...meta, reason: joinReason(meta.reason, o.reason) } : undefined;
172
+ let b;
173
+ if (o.op === "statement_amount") {
174
+ if (!isDate(o.statement_date) || !Number.isInteger(o.amount))
175
+ throw new ActionError(`batch refused: op ${i + 1} (statement_amount) needs statement_date yyyy-mm-dd and a whole amount`);
176
+ const k = amounts.findIndex((x) => x.account === o.account && x.statement_date === o.statement_date);
177
+ if (k >= 0)
178
+ amounts.splice(k, 1);
179
+ amounts.push({ account: o.account, statement_date: o.statement_date, amount: o.amount });
180
+ counts.statement_amount++;
181
+ return;
182
+ }
183
+ try {
184
+ if (o.op === "add") {
185
+ const { op: _op, reason: _r, ...t } = o;
186
+ b = buildAdd(t, m);
187
+ }
188
+ else if (o.op === "edit") {
189
+ const { op: _op, reason: _r, id, ...patch } = o;
190
+ b = buildEdit(cur, id, patch, m);
191
+ }
192
+ else if (o.op === "void") {
193
+ b = buildVoid(cur, o.id, o.reason ?? meta?.reason, m);
194
+ }
195
+ else
196
+ throw new ActionError(`unknown op "${o.op}"`);
197
+ }
198
+ catch (e) {
199
+ throw new ActionError(`batch refused: op ${i + 1} (${o.op}${"id" in o && o.id ? ` ${o.id}` : ""}) failed: ${e.message}`);
200
+ }
201
+ counts[o.op]++;
202
+ if (!originals.has(b.tx.id))
203
+ originals.set(b.tx.id, b.old ?? null);
204
+ finals.set(b.tx.id, b.tx);
205
+ const out = applyChange(cur, b.change);
206
+ for (const p of Object.keys(out))
207
+ changed.add(p);
208
+ cur = { ...cur, ...out };
209
+ });
210
+ if (amounts.length) {
211
+ const unknown = amounts.find((x) => !loadLedger(cur).ledger.accounts.some((a) => a.id === x.account));
212
+ if (unknown)
213
+ throw new ActionError(`batch refused: statement_amount: no account ${unknown.account}`);
214
+ cur = { ...cur, [STATEMENTS_FILE]: yamlText(withBankAmounts(loadLedger(cur).ledger, amounts)) };
215
+ changed.add(STATEMENTS_FILE);
216
+ }
217
+ const r = checkFiles(cur);
218
+ if (!r.ok)
219
+ 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")}`);
220
+ const before = new Set(checkFiles(files).warnings.map((w) => `${w.file}|${w.where}|${w.message}`));
221
+ const out = {};
222
+ for (const p of changed)
223
+ if (cur[p] !== files[p])
224
+ out[p] = cur[p];
225
+ const add = [];
226
+ const rep = [];
227
+ const balanceChange = {};
228
+ const bump = (t, sign) => {
229
+ if (!t || t.void)
230
+ return;
231
+ for (const l of t.lines)
232
+ if (l.account)
233
+ balanceChange[l.account] = (balanceChange[l.account] ?? 0) + sign * l.amount;
234
+ };
235
+ for (const [id, t] of finals) {
236
+ const old = originals.get(id) ?? null;
237
+ (old ? rep : add).push(t);
238
+ bump(t, 1);
239
+ bump(old, -1);
240
+ }
241
+ for (const [k, v] of Object.entries(balanceChange))
242
+ if (v === 0)
243
+ delete balanceChange[k];
244
+ 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" : ""}`, counts.statement_amount && `${counts.statement_amount} bank amount${counts.statement_amount > 1 ? "s" : ""}`].filter(Boolean);
245
+ const change = { ...(add.length ? { addTransactions: add } : {}), ...(rep.length ? { replaceTransactions: rep } : {}) };
246
+ return {
247
+ change,
248
+ files: out,
249
+ summary: [`batch: ${parts.join(", ")}`, ...describeChange(change), ...amounts.map((x) => `bank amount ${x.account} ${x.statement_date}: ${x.amount}`)],
250
+ message: withMeta(`Batch: ${parts.join(", ")}`, meta),
251
+ warnings: r.warnings.filter((w) => !before.has(`${w.file}|${w.where}|${w.message}`)),
252
+ balanceChange,
253
+ counts,
254
+ };
130
255
  }
131
256
  /** The ledger of a set of files, for actions that read it before building a change. */
132
257
  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
  }