ownledger 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AGENTS.md +93 -0
  2. package/CHANGELOG.md +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +102 -2
  5. package/assets/_headers +5 -0
  6. package/assets/app.css +61 -0
  7. package/assets/app.js +369 -0
  8. package/assets/icon.svg +1 -0
  9. package/assets/index.html +30 -0
  10. package/assets/manifest.webmanifest +1 -0
  11. package/dist/cli/check.d.ts +3 -0
  12. package/dist/cli/check.js +21 -0
  13. package/dist/cli/deploy.d.ts +1 -0
  14. package/dist/cli/deploy.js +258 -0
  15. package/dist/cli/dev.d.ts +3 -0
  16. package/dist/cli/dev.js +107 -0
  17. package/dist/cli/import.d.ts +3 -0
  18. package/dist/cli/import.js +151 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +47 -0
  21. package/dist/cli/init.d.ts +1 -0
  22. package/dist/cli/init.js +73 -0
  23. package/dist/cli/jsonc.d.ts +2 -0
  24. package/dist/cli/jsonc.js +39 -0
  25. package/dist/engine/actions.d.ts +53 -0
  26. package/dist/engine/actions.js +205 -0
  27. package/dist/engine/balances.d.ts +30 -0
  28. package/dist/engine/balances.js +75 -0
  29. package/dist/engine/categories.d.ts +17 -0
  30. package/dist/engine/categories.js +35 -0
  31. package/dist/engine/check.d.ts +11 -0
  32. package/dist/engine/check.js +220 -0
  33. package/dist/engine/dates.d.ts +15 -0
  34. package/dist/engine/dates.js +56 -0
  35. package/dist/engine/defaults.d.ts +2 -0
  36. package/dist/engine/defaults.js +61 -0
  37. package/dist/engine/index.d.ts +13 -0
  38. package/dist/engine/index.js +13 -0
  39. package/dist/engine/load.d.ts +23 -0
  40. package/dist/engine/load.js +129 -0
  41. package/dist/engine/networth.d.ts +12 -0
  42. package/dist/engine/networth.js +73 -0
  43. package/dist/engine/registry.d.ts +24 -0
  44. package/dist/engine/registry.js +41 -0
  45. package/dist/engine/reports.d.ts +68 -0
  46. package/dist/engine/reports.js +149 -0
  47. package/dist/engine/schedules.d.ts +75 -0
  48. package/dist/engine/schedules.js +208 -0
  49. package/dist/engine/types.d.ts +122 -0
  50. package/dist/engine/types.js +2 -0
  51. package/dist/engine/write.d.ts +30 -0
  52. package/dist/engine/write.js +105 -0
  53. package/dist/import/hash.d.ts +1 -0
  54. package/dist/import/hash.js +17 -0
  55. package/dist/import/index.d.ts +6 -0
  56. package/dist/import/index.js +6 -0
  57. package/dist/import/mapping.d.ts +96 -0
  58. package/dist/import/mapping.js +54 -0
  59. package/dist/import/profile.d.ts +39 -0
  60. package/dist/import/profile.js +125 -0
  61. package/dist/import/run.d.ts +101 -0
  62. package/dist/import/run.js +416 -0
  63. package/dist/import/workbook.d.ts +13 -0
  64. package/dist/import/workbook.js +168 -0
  65. package/dist/import/xlsx-write.d.ts +6 -0
  66. package/dist/import/xlsx-write.js +38 -0
  67. package/dist/node/files.d.ts +3 -0
  68. package/dist/node/files.js +26 -0
  69. package/dist/node/scaffold.d.ts +14 -0
  70. package/dist/node/scaffold.js +45 -0
  71. package/dist/worker/api.d.ts +3 -0
  72. package/dist/worker/api.js +139 -0
  73. package/dist/worker/auth.d.ts +11 -0
  74. package/dist/worker/auth.js +176 -0
  75. package/dist/worker/env.d.ts +25 -0
  76. package/dist/worker/env.js +6 -0
  77. package/dist/worker/github.d.ts +29 -0
  78. package/dist/worker/github.js +154 -0
  79. package/dist/worker/index.d.ts +5 -0
  80. package/dist/worker/index.js +64 -0
  81. package/dist/worker/mcp.d.ts +4 -0
  82. package/dist/worker/mcp.js +292 -0
  83. package/dist/worker/store.d.ts +42 -0
  84. package/dist/worker/store.js +92 -0
  85. package/dist/worker/tar.d.ts +2 -0
  86. package/dist/worker/tar.js +62 -0
  87. package/dist/worker/version.d.ts +1 -0
  88. package/dist/worker/version.js +2 -0
  89. package/package.json +68 -4
  90. package/presets/misa.mapping.yaml +48 -0
  91. package/templates/repo/.github/dependabot.yml +11 -0
  92. package/templates/repo/.github/workflows/check.yml +15 -0
  93. package/templates/repo/.github/workflows/deploy.yml +21 -0
  94. package/templates/repo/README.md +10 -0
@@ -0,0 +1,416 @@
1
+ import { isDate } from "../engine/dates.js";
2
+ import { stableKey } from "./hash.js";
3
+ /* ------------------------------------------------------------------ helpers */
4
+ const norm = (s) => String(s ?? "").trim().toLowerCase();
5
+ export function parseAmount(v, decimal = ".") {
6
+ if (v === null || v === undefined || v === "")
7
+ return null;
8
+ if (typeof v === "number")
9
+ return Number.isFinite(v) ? v : null;
10
+ let s = v.trim().replace(/\s|₫|đ|VND/gi, "");
11
+ if (!s)
12
+ return null;
13
+ const neg = /^\(.*\)$/.test(s) || s.startsWith("-");
14
+ s = s.replace(/[()\-+]/g, "");
15
+ s = decimal === "," ? s.replace(/\./g, "").replace(",", ".") : s.replace(/,/g, "");
16
+ const n = Number(s);
17
+ return Number.isFinite(n) ? (neg ? -n : n) : null;
18
+ }
19
+ export function parseDate(v, fmt) {
20
+ if (v === null)
21
+ return null;
22
+ if (typeof v === "number") {
23
+ // Excel serial date
24
+ const d = new Date(Date.UTC(1899, 11, 30) + Math.round(v) * 86400000);
25
+ return d.toISOString().slice(0, 10);
26
+ }
27
+ const s = v.trim();
28
+ let m = /^(\d{4})-(\d{1,2})-(\d{1,2})/.exec(s);
29
+ if (m && (fmt === undefined || fmt === "yyyy-mm-dd"))
30
+ return iso(m[1], m[2], m[3]);
31
+ m = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})/.exec(s);
32
+ if (m)
33
+ return fmt === "mm/dd/yyyy" ? iso(m[3], m[1], m[2]) : iso(m[3], m[2], m[1]);
34
+ return null;
35
+ }
36
+ const iso = (y, mo, d) => {
37
+ const r = `${y}-${mo.padStart(2, "0")}-${d.padStart(2, "0")}`;
38
+ return isDate(r) ? r : null;
39
+ };
40
+ function parseTime(v) {
41
+ if (v === null)
42
+ return null;
43
+ if (typeof v === "number") {
44
+ const mins = Math.round((v % 1) * 1440);
45
+ return `${String(Math.floor(mins / 60)).padStart(2, "0")}:${String(mins % 60).padStart(2, "0")}`;
46
+ }
47
+ const m = /^(\d{1,2}):(\d{2})/.exec(v.trim());
48
+ return m ? `${m[1].padStart(2, "0")}:${m[2]}` : null;
49
+ }
50
+ /** Excel's sheet name for a full name: forbidden chars → "_", max 31 chars. */
51
+ export function excelSheetName(name) {
52
+ // Excel counts UTF-16 units; a cut surrogate pair leaves half an emoji (MISA writes it as _xD83D_)
53
+ return name.replace(/[\\/?*[\]:]/g, "_").slice(0, 31).replace(/[\uD800-\uDBFF]$/, "");
54
+ }
55
+ function nameMatchesSheet(name, sheet, acc) {
56
+ const n = norm(name);
57
+ if (acc?.names?.some((x) => norm(x) === n))
58
+ return true;
59
+ if (norm(acc?.name) === n)
60
+ return true;
61
+ const s = norm(sheet).replace(/[\uD800-\uDBFF]$/, "");
62
+ const base = s.replace(/_\d+$/, "");
63
+ const en = norm(excelSheetName(name));
64
+ if (en === s || en === base)
65
+ return true;
66
+ // truncated by Excel (31 chars, emoji surrogates may become _xD83D_ fragments)
67
+ const cut = base.replace(/_x[0-9a-f]{4}_?$/i, "").replace(/_$/, "");
68
+ return cut.length >= 4 && en.startsWith(cut);
69
+ }
70
+ /* ------------------------------------------------------------------ reading */
71
+ function findHeader(sheet, m) {
72
+ if (m.header_row)
73
+ return m.header_row - 1;
74
+ const want = norm(m.columns.date);
75
+ return sheet.rows.findIndex((r) => r?.some((c) => norm(c) === want));
76
+ }
77
+ function readTotals(sheet, headerIdx, m) {
78
+ const out = { opening: null, closing: null, in: null, out: null };
79
+ if (!m.totals)
80
+ return out;
81
+ for (let r = 0; r < headerIdx; r++) {
82
+ const row = sheet.rows[r] ?? [];
83
+ row.forEach((c, i) => {
84
+ for (const k of Object.keys(out)) {
85
+ const label = m.totals?.[k];
86
+ if (label && norm(c) === norm(label)) {
87
+ for (let j = i + 1; j < row.length; j++) {
88
+ const v = parseAmount(row[j] ?? null, m.decimal);
89
+ if (v !== null) {
90
+ out[k] = v;
91
+ break;
92
+ }
93
+ }
94
+ }
95
+ }
96
+ });
97
+ }
98
+ return out;
99
+ }
100
+ export function readRows(wb, m) {
101
+ const errors = [];
102
+ const all = [];
103
+ const perSheet = [];
104
+ const wanted = m.sheets && m.sheets !== "all" ? new Set(m.sheets) : null;
105
+ const skip = new Set(m.skip_sheets ?? []);
106
+ for (const sheet of wb.sheets) {
107
+ if (wanted && !wanted.has(sheet.name))
108
+ continue;
109
+ if (skip.has(sheet.name))
110
+ continue;
111
+ const h = findHeader(sheet, m);
112
+ if (h < 0) {
113
+ errors.push(`sheet "${sheet.name}": no header row with column "${m.columns.date}"`);
114
+ continue;
115
+ }
116
+ const headers = (sheet.rows[h] ?? []).map(norm);
117
+ const col = (name) => {
118
+ if (!name)
119
+ return -1;
120
+ const i = headers.indexOf(norm(name));
121
+ if (i < 0)
122
+ errors.push(`sheet "${sheet.name}": column "${name}" not found`);
123
+ return i;
124
+ };
125
+ const c = Object.fromEntries(Object.entries(m.columns).map(([k, v]) => [k, col(v)]));
126
+ const accCol = m.account_from === "column" ? col(m.account_column) : -1;
127
+ const totals = readTotals(sheet, h, m);
128
+ const rows = [];
129
+ for (let r = h + 1; r < sheet.rows.length; r++) {
130
+ const row = sheet.rows[r];
131
+ if (!row || row.every((x) => x === null))
132
+ continue;
133
+ const at = (i) => (i !== undefined && i >= 0 ? (row[i] ?? null) : null);
134
+ const date = parseDate(at(c.date), m.date_format);
135
+ if (!date) {
136
+ if (at(c.date) !== null)
137
+ errors.push(`sheet "${sheet.name}" row ${r + 1}: can't read date "${at(c.date)}"`);
138
+ continue;
139
+ }
140
+ let value;
141
+ if (c.amount !== undefined && c.amount >= 0)
142
+ value = parseAmount(at(c.amount), m.decimal);
143
+ else
144
+ value = (parseAmount(at(c.in), m.decimal) ?? 0) - (parseAmount(at(c.out), m.decimal) ?? 0);
145
+ if (value === null) {
146
+ errors.push(`sheet "${sheet.name}" row ${r + 1}: no amount`);
147
+ continue;
148
+ }
149
+ const sourceAccount = m.account_from === "column" ? String(at(accCol) ?? "") : m.account_from === "fixed" ? m.account : sheet.name;
150
+ const parent = at(c.category);
151
+ const child = at(c.subcategory);
152
+ const catKey = parent !== null ? (child !== null ? `${String(parent).trim()}/${String(child).trim()}` : String(parent).trim()) : child !== null ? String(child).trim() : null;
153
+ const cents = Math.round(value * 100);
154
+ rows.push({
155
+ sheet: sheet.name,
156
+ sourceAccount,
157
+ account: m.accounts?.[sourceAccount]?.id ?? "",
158
+ row: r + 1,
159
+ date,
160
+ time: parseTime(at(c.time)),
161
+ cents,
162
+ amount: Math.round(cents / 100),
163
+ catKey,
164
+ note: String(at(c.note) ?? "").trim(),
165
+ who: at(c.who) !== null ? String(at(c.who)).trim() : null,
166
+ event: at(c.event) !== null ? String(at(c.event)).trim() : null,
167
+ tags: at(c.tags) !== null ? String(at(c.tags)).split(/[,;]/).map((s) => s.trim()).filter(Boolean) : [],
168
+ key: "",
169
+ });
170
+ }
171
+ // stable keys: occurrence index among identical rows, counted oldest first
172
+ const newestFirst = m.newest_first ?? (rows.length > 1 && rows[0].date > rows[rows.length - 1].date);
173
+ const ordered = newestFirst ? [...rows].reverse() : rows;
174
+ const seen = new Map();
175
+ for (const sr of ordered) {
176
+ const base = [m.source, sr.sourceAccount, sr.date, sr.time, sr.cents, sr.catKey, sr.note];
177
+ const b = JSON.stringify(base);
178
+ const n = seen.get(b) ?? 0;
179
+ seen.set(b, n + 1);
180
+ sr.key = stableKey([...base, n]);
181
+ }
182
+ perSheet.push({ sheet, header: h, totals, rows: ordered });
183
+ all.push(...ordered);
184
+ }
185
+ return { rows: all, sheets: perSheet, errors };
186
+ }
187
+ /* ------------------------------------------------------------------ run */
188
+ export function runImport(wb, m, ledger) {
189
+ const { rows, sheets, errors } = readRows(wb, m);
190
+ const unmatched = m.unmatched_account ?? "import-unmatched";
191
+ const res = {
192
+ ok: false, source: m.source, rows: rows.length, transactions: [], accounts: [], skipped: 0, changed: [], replace: [], gone: [],
193
+ unpaired: [], unresolvedCategories: [], unresolvedRows: [], reconcile: [], rounding: [], zeroed: [], errors,
194
+ };
195
+ // account targets in categories / uncategorized must be accounts of the mapping or the ledger
196
+ const knownIds = new Set([...Object.values(m.accounts ?? {}).map((a) => a.id), ...(ledger?.accounts.map((a) => a.id) ?? [])]);
197
+ for (const v of [...Object.values(m.categories ?? {}), ...[...(m.rules ?? []), ...(m.uncategorized ?? [])].map((u) => u.category), m.uncategorized_in, m.uncategorized_out]) {
198
+ if (typeof v === "string" && v.startsWith("account:") && !knownIds.has(v.slice(8)))
199
+ errors.push(`"${v}": no such account in the mapping's accounts or the ledger`);
200
+ }
201
+ // accounts named in the file must be mapped
202
+ const missingAcc = new Set(rows.filter((r) => !r.account).map((r) => r.sourceAccount));
203
+ for (const a of missingAcc)
204
+ errors.push(`source account "${a}" is not in the mapping's accounts`);
205
+ // classify
206
+ const outRe = m.transfers?.out ? new RegExp(m.transfers.out, "u") : null;
207
+ const inRe = m.transfers?.in ? new RegExp(m.transfers.in, "u") : null;
208
+ const onlyNoCat = m.transfers?.only_without_category ?? true;
209
+ const unresolvedCats = new Map();
210
+ for (const r of rows) {
211
+ const tr = r.cents < 0 ? outRe : inRe;
212
+ const tm = tr && (!onlyNoCat || r.catKey === null) ? tr.exec(r.note) : null;
213
+ if (tm) {
214
+ r.kind = "transfer";
215
+ r.wallet = (tm.groups?.wallet ?? "").trim();
216
+ continue;
217
+ }
218
+ const rule0 = (m.rules ?? []).find((u) => (!u.sign || (u.sign === "in") === r.cents > 0) && (!u.source_category || u.source_category === r.catKey || u.source_category === r.catKey?.split("/")[0]) && new RegExp(u.match, "iu").test(r.note));
219
+ if (rule0) {
220
+ r.kind = "category";
221
+ r.category = rule0.category;
222
+ continue;
223
+ }
224
+ if (r.catKey !== null) {
225
+ const parent = r.catKey.split("/")[0];
226
+ const cat = m.categories[r.catKey] ?? m.categories[parent];
227
+ if (cat) {
228
+ r.kind = "category";
229
+ r.category = cat;
230
+ }
231
+ else {
232
+ r.kind = "unresolved";
233
+ const u = unresolvedCats.get(r.catKey) ?? { rows: 0, example: `${r.date} ${r.amount} ${r.note}` };
234
+ u.rows++;
235
+ unresolvedCats.set(r.catKey, u);
236
+ }
237
+ continue;
238
+ }
239
+ const rule = (m.uncategorized ?? []).find((u) => (!u.sign || (u.sign === "in") === r.cents > 0) && new RegExp(u.match, "iu").test(r.note));
240
+ const fallback = r.cents > 0 ? m.uncategorized_in : m.uncategorized_out;
241
+ if (rule || fallback) {
242
+ r.kind = "category";
243
+ r.category = rule?.category ?? fallback;
244
+ }
245
+ else {
246
+ r.kind = "unresolved";
247
+ res.unresolvedRows.push(r);
248
+ }
249
+ }
250
+ res.unresolvedCategories = [...unresolvedCats].map(([key, v]) => ({ key, ...v }));
251
+ // pair transfers: same date, time and amount, opposite signs, different source accounts; names break ties
252
+ const ins = new Map();
253
+ for (const r of rows) {
254
+ if (r.kind !== "transfer" || r.cents <= 0)
255
+ continue;
256
+ const k = `${r.date}|${r.cents}`;
257
+ (ins.get(k) ?? ins.set(k, []).get(k)).push(r);
258
+ }
259
+ const accMap = m.accounts ?? {};
260
+ const score = (o, i) => (o.time === i.time ? 4 : 0) +
261
+ (nameMatchesSheet(o.wallet ?? "", i.sheet, accMap[i.sourceAccount]) ? 2 : 0) +
262
+ (nameMatchesSheet(i.wallet ?? "", o.sheet, accMap[o.sourceAccount]) ? 1 : 0);
263
+ for (const pass of [0, 1]) {
264
+ for (const o of rows) {
265
+ if (o.kind !== "transfer" || o.cents >= 0 || o.pairedWith)
266
+ continue;
267
+ const cands = (ins.get(`${o.date}|${-o.cents}`) ?? []).filter((i) => !i.pairedWith && i.sourceAccount !== o.sourceAccount && (pass === 1 || i.time === o.time));
268
+ if (!cands.length)
269
+ continue;
270
+ cands.sort((a, b) => score(o, b) - score(o, a));
271
+ const best = cands[0];
272
+ if (pass === 1 && score(o, best) < 2)
273
+ continue; // without the same time, at least the names must agree
274
+ o.pairedWith = best;
275
+ best.pairedWith = o;
276
+ }
277
+ }
278
+ res.unpaired = rows.filter((r) => r.kind === "transfer" && !r.pairedWith && !(m.unpaired ?? []).some((u) => new RegExp(u.wallet, "iu").test(r.wallet ?? "")));
279
+ // build transactions
280
+ const built = [];
281
+ const tx = (key, date, time, note, lines, extra = {}) => ({
282
+ id: `t_${key.slice(0, 14)}`,
283
+ date,
284
+ time,
285
+ note,
286
+ ...(extra.who ? { who: extra.who } : {}),
287
+ ...(extra.event ? { event: extra.event } : {}),
288
+ ...(extra.tags?.length ? { tags: extra.tags } : {}),
289
+ lines,
290
+ src: { import: m.source, key, ...(extra.src ?? {}) },
291
+ });
292
+ const stripTransfer = (note, re) => (re ? note.replace(re, "").replace(/\s*\(\s*$/, "").trim() : note);
293
+ for (const r of rows) {
294
+ if (r.kind === "category") {
295
+ // "account:<id>" sends the other side to an account (a move between the owner's own accounts, not income or spending)
296
+ const other = r.category.startsWith("account:") ? { account: r.category.slice(8), amount: -r.amount } : { category: r.category, amount: -r.amount };
297
+ built.push(tx(r.key, r.date, r.time, r.note, [{ account: r.account, amount: r.amount }, other], { who: r.who, event: r.event, tags: r.tags }));
298
+ }
299
+ else if (r.kind === "transfer") {
300
+ if (r.pairedWith) {
301
+ if (r.cents > 0)
302
+ continue; // built from the out side
303
+ const i = r.pairedWith;
304
+ const note = stripTransfer(r.note, outRe) || stripTransfer(i.note, inRe) || "";
305
+ built.push(tx(r.key, r.date, r.time, note, [{ account: r.account, amount: r.amount }, { account: i.account, amount: i.amount }], { who: r.who, event: r.event, tags: r.tags, src: { pair: i.key } }));
306
+ }
307
+ else {
308
+ const rule = (m.unpaired ?? []).find((u) => new RegExp(u.wallet, "iu").test(r.wallet ?? ""));
309
+ const target = rule?.category;
310
+ const other = !target ? { account: unmatched, amount: -r.amount } : target.startsWith("account:") ? { account: target.slice(8), amount: -r.amount } : { category: target, amount: -r.amount };
311
+ built.push(tx(r.key, r.date, r.time, r.note, [{ account: r.account, amount: r.amount }, other], { who: r.who, event: r.event }));
312
+ }
313
+ }
314
+ }
315
+ // paired amounts must agree in whole units (they do, same cents); guard anyway
316
+ for (const t of built) {
317
+ const s = t.lines.reduce((a, l) => a + l.amount, 0);
318
+ if (s !== 0)
319
+ errors.push(`internal: transaction ${t.id} does not balance (${s})`);
320
+ }
321
+ // opening balances, rounding and reconcile per sheet
322
+ for (const s of sheets) {
323
+ const sheetName = s.sheet.name;
324
+ const acc = accMap[s.rows[0]?.sourceAccount ?? sheetName]?.id ?? "";
325
+ const t = s.totals;
326
+ const problems = [];
327
+ const inC = s.rows.filter((r) => r.cents > 0).reduce((a, r) => a + r.cents, 0);
328
+ const outC = -s.rows.filter((r) => r.cents < 0).reduce((a, r) => a + r.cents, 0);
329
+ const openC = Math.round((t.opening ?? 0) * 100);
330
+ const near = (a, b) => Math.abs(a - b) <= 1; // ±1 cent of float noise
331
+ if (t.in !== null && !near(inC, Math.round(t.in * 100)))
332
+ problems.push(`money in ${inC / 100} ≠ source ${t.in}`);
333
+ if (t.out !== null && !near(outC, Math.round(t.out * 100)))
334
+ problems.push(`money out ${outC / 100} ≠ source ${t.out}`);
335
+ if (t.closing !== null && !near(openC + inC - outC, Math.round(t.closing * 100)))
336
+ problems.push(`opening + in − out = ${(openC + inC - outC) / 100} ≠ source closing ${t.closing}`);
337
+ const opening = Math.round(openC / 100);
338
+ const sumRounded = s.rows.reduce((a, r) => a + r.amount, 0);
339
+ const closingTarget = t.closing !== null ? Math.round(t.closing) : opening + Math.round((inC - outC) / 100);
340
+ const diff = closingTarget - (opening + sumRounded);
341
+ const first = s.rows[0];
342
+ const last = s.rows[s.rows.length - 1];
343
+ if (opening !== 0 && first) {
344
+ built.push(tx(stableKey([m.source, sheetName, "opening"]), m.opening_date ?? first.date, "00:00", "Số dư đầu kì / opening balance", [{ account: acc, amount: opening }, { category: "_opening", amount: -opening }], { src: { derived: "opening" } }));
345
+ }
346
+ if (diff !== 0 && last) {
347
+ res.rounding.push({ sheet: sheetName, diff });
348
+ built.push(tx(stableKey([m.source, sheetName, "rounding"]), last.date, "23:59", "Làm tròn khi nhập / import rounding", [{ account: acc, amount: diff }, { category: "_adjust", amount: -diff }], { src: { derived: "rounding" } }));
349
+ }
350
+ const imported = { opening, in: Math.round(inC / 100), out: Math.round(outC / 100), closing: opening + sumRounded + diff };
351
+ let zeroed = 0;
352
+ const closedOn = accMap[s.rows[0]?.sourceAccount ?? sheetName]?.closed;
353
+ if (m.zero_closed && closedOn && imported.closing !== 0) {
354
+ zeroed = -imported.closing;
355
+ res.zeroed.push({ account: acc, date: closedOn, amount: zeroed });
356
+ built.push(tx(stableKey([m.source, sheetName, "zero"]), closedOn, "23:59", "Về 0 khi tất toán / zeroed on closing", [{ account: acc, amount: zeroed }, { category: "_adjust", amount: -zeroed }], { src: { derived: "zero" } }));
357
+ }
358
+ res.reconcile.push({
359
+ sheet: sheetName, account: acc, rows: s.rows.length,
360
+ source: { opening: t.opening, in: t.in, out: t.out, closing: t.closing },
361
+ imported, rounding: diff, zeroed, ok: problems.length === 0, problems,
362
+ });
363
+ }
364
+ // accounts to create
365
+ const existing = new Set(ledger?.accounts.map((a) => a.id) ?? []);
366
+ const made = new Set();
367
+ const used = new Set(built.flatMap((t) => t.lines.map((l) => l.account).filter(Boolean)));
368
+ for (const [, a] of Object.entries(accMap)) {
369
+ if (existing.has(a.id) || made.has(a.id) || !used.has(a.id))
370
+ continue;
371
+ made.add(a.id);
372
+ const { names: _n, ...rest } = a;
373
+ res.accounts.push({ ...rest, id: a.id, name: a.name ?? a.id, type: a.type ?? "other" });
374
+ }
375
+ if (built.some((t) => t.lines.some((l) => l.account === unmatched)) && !existing.has(unmatched) && !made.has(unmatched)) {
376
+ res.accounts.push({ id: unmatched, name: "Chưa khớp khi nhập / unmatched import", type: "other", note: "Transfers whose other side was not in the file. Should end at 0." });
377
+ }
378
+ // re-import: skip known keys, report changed and gone
379
+ const known = new Map();
380
+ for (const t of ledger?.transactions ?? [])
381
+ if (t.src?.import === m.source)
382
+ known.set(t.src.key, t);
383
+ const builtKeys = new Set();
384
+ const sig = (t) => JSON.stringify([t.date, t.lines.map((l) => [l.account ?? l.category, l.amount])]);
385
+ for (const t of built) {
386
+ builtKeys.add(t.src.key);
387
+ if (t.src.pair)
388
+ builtKeys.add(String(t.src.pair));
389
+ const k = known.get(t.src.key);
390
+ if (!k) {
391
+ res.transactions.push(t);
392
+ continue;
393
+ }
394
+ res.skipped++;
395
+ if (sig(k) === sig(t))
396
+ continue;
397
+ if (t.src.derived)
398
+ res.replace.push({ ...t, id: k.id });
399
+ else
400
+ res.changed.push({ key: t.src.key, id: k.id, was: sig(k), now: sig(t) });
401
+ }
402
+ for (const [key, t] of known) {
403
+ if (builtKeys.has(key) || t.void)
404
+ continue;
405
+ if (t.src?.derived)
406
+ res.replace.push({ ...t, void: true });
407
+ else
408
+ res.gone.push({ id: t.id, date: t.date, note: t.note, key });
409
+ }
410
+ res.ok =
411
+ errors.length === 0 &&
412
+ res.unresolvedCategories.length === 0 &&
413
+ res.unresolvedRows.length === 0 &&
414
+ res.reconcile.every((r) => r.ok);
415
+ return res;
416
+ }
@@ -0,0 +1,13 @@
1
+ export type Cell = string | number | null;
2
+ export interface Sheet {
3
+ name: string;
4
+ rows: Cell[][];
5
+ }
6
+ export interface Workbook {
7
+ kind: "xlsx" | "csv" | "json";
8
+ sheets: Sheet[];
9
+ }
10
+ export declare function readXlsx(data: Uint8Array): Workbook;
11
+ export declare function readCsv(text: string, name?: string): Workbook;
12
+ export declare function readJson(text: string, name?: string): Workbook;
13
+ export declare function readWorkbook(fileName: string, data: Uint8Array): Workbook;
@@ -0,0 +1,168 @@
1
+ import { strFromU8, unzipSync } from "fflate";
2
+ /* ------------------------------------------------------------------ xlsx */
3
+ const XML_ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
4
+ function unxml(s) {
5
+ return s
6
+ .replace(/_x([0-9A-Fa-f]{4})_/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
7
+ .replace(/&(#x[0-9a-fA-F]+|#\d+|\w+);/g, (m, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : (XML_ENT[e] ?? m));
8
+ }
9
+ function textOf(xml) {
10
+ // concatenates <t> runs (rich text), ignoring phonetic runs
11
+ let out = "";
12
+ const re = /<t(?:\s[^>]*)?>([\s\S]*?)<\/t>|<t(?:\s[^>]*)?\/>/g;
13
+ const noPh = xml.replace(/<rPh[\s\S]*?<\/rPh>/g, "");
14
+ for (let m; (m = re.exec(noPh));)
15
+ out += m[1] ?? "";
16
+ return unxml(out);
17
+ }
18
+ function colIndex(ref) {
19
+ let n = 0;
20
+ for (const ch of ref) {
21
+ const c = ch.charCodeAt(0);
22
+ if (c < 65 || c > 90)
23
+ break;
24
+ n = n * 26 + (c - 64);
25
+ }
26
+ return n - 1;
27
+ }
28
+ function attr(tag, name) {
29
+ const m = new RegExp(`\\s${name}="([^"]*)"`).exec(tag);
30
+ return m ? unxml(m[1]) : undefined;
31
+ }
32
+ export function readXlsx(data) {
33
+ const files = unzipSync(data, { filter: (f) => f.name.startsWith("xl/") && f.name.endsWith(".xml") || f.name.endsWith(".rels") });
34
+ const get = (p) => (files[p] ? strFromU8(files[p]) : undefined);
35
+ const wb = get("xl/workbook.xml");
36
+ if (!wb)
37
+ throw new Error("not an xlsx file (xl/workbook.xml missing)");
38
+ const rels = get("xl/_rels/workbook.xml.rels") ?? "";
39
+ const relMap = new Map();
40
+ for (const m of rels.matchAll(/<Relationship\b[^>]*>/g)) {
41
+ const id = attr(m[0], "Id");
42
+ const target = attr(m[0], "Target");
43
+ if (id && target)
44
+ relMap.set(id, target.startsWith("/") ? target.slice(1) : `xl/${target}`);
45
+ }
46
+ const shared = [];
47
+ const sst = get("xl/sharedStrings.xml");
48
+ if (sst)
49
+ for (const m of sst.matchAll(/<si>([\s\S]*?)<\/si>/g))
50
+ shared.push(textOf(m[1]));
51
+ const sheets = [];
52
+ for (const m of wb.matchAll(/<sheet\b[^>]*>/g)) {
53
+ const name = attr(m[0], "name") ?? `Sheet${sheets.length + 1}`;
54
+ const rid = attr(m[0], "r:id");
55
+ const path = rid ? relMap.get(rid) : undefined;
56
+ const xml = path ? get(path) : undefined;
57
+ if (!xml)
58
+ continue;
59
+ const rows = [];
60
+ for (const rm of xml.matchAll(/<row\b([^>]*)>([\s\S]*?)<\/row>|<row\b([^>]*)\/>/g)) {
61
+ const r = Number(attr(rm[1] ?? rm[3] ?? "", "r") ?? rows.length + 1) - 1;
62
+ const row = [];
63
+ for (const cm of (rm[2] ?? "").matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
64
+ const a = cm[1] ?? "";
65
+ const inner = cm[2] ?? "";
66
+ const ref = attr(a, "r");
67
+ const c = ref ? colIndex(ref) : row.length;
68
+ const t = attr(a, "t");
69
+ const v = /<v>([\s\S]*?)<\/v>/.exec(inner)?.[1];
70
+ let val = null;
71
+ if (t === "s")
72
+ val = v !== undefined ? (shared[Number(v)] ?? "") : null;
73
+ else if (t === "inlineStr")
74
+ val = textOf(inner);
75
+ else if (t === "str" || t === "e")
76
+ val = v !== undefined ? unxml(v) : null;
77
+ else if (t === "b")
78
+ val = v === "1" ? 1 : 0;
79
+ else if (v !== undefined)
80
+ val = Number(v);
81
+ if (val === "")
82
+ val = null;
83
+ while (row.length < c)
84
+ row.push(null);
85
+ row[c] = val;
86
+ }
87
+ while (rows.length < r)
88
+ rows.push([]);
89
+ rows[r] = row;
90
+ }
91
+ sheets.push({ name: unxml(name), rows });
92
+ }
93
+ return { kind: "xlsx", sheets };
94
+ }
95
+ /* ------------------------------------------------------------------ csv */
96
+ export function readCsv(text, name = "csv") {
97
+ const t = text.replace(/^/, "");
98
+ const first = t.slice(0, t.indexOf("\n") >>> 0 || t.length);
99
+ const delim = [",", ";", "\t"].map((d) => [d, first.split(d).length]).sort((a, b) => b[1] - a[1])[0][0];
100
+ const rows = [];
101
+ let row = [];
102
+ let field = "";
103
+ let q = false;
104
+ let quoted = false;
105
+ const push = () => {
106
+ row.push(field === "" && !quoted ? null : field);
107
+ field = "";
108
+ quoted = false;
109
+ };
110
+ for (let i = 0; i < t.length; i++) {
111
+ const ch = t[i];
112
+ if (q) {
113
+ if (ch === '"') {
114
+ if (t[i + 1] === '"') {
115
+ field += '"';
116
+ i++;
117
+ }
118
+ else
119
+ q = false;
120
+ }
121
+ else
122
+ field += ch;
123
+ }
124
+ else if (ch === '"') {
125
+ q = true;
126
+ quoted = true;
127
+ }
128
+ else if (ch === delim)
129
+ push();
130
+ else if (ch === "\n" || ch === "\r") {
131
+ if (ch === "\r" && t[i + 1] === "\n")
132
+ i++;
133
+ push();
134
+ rows.push(row);
135
+ row = [];
136
+ }
137
+ else
138
+ field += ch;
139
+ }
140
+ if (field !== "" || row.length) {
141
+ push();
142
+ rows.push(row);
143
+ }
144
+ return { kind: "csv", sheets: [{ name, rows }] };
145
+ }
146
+ /* ------------------------------------------------------------------ json */
147
+ export function readJson(text, name = "json") {
148
+ const v = JSON.parse(text);
149
+ const arr = Array.isArray(v) ? v : Array.isArray(v?.data) ? v.data : Array.isArray(v?.items) ? v.items : [];
150
+ const headers = [...new Set(arr.flatMap((o) => Object.keys(o ?? {})))];
151
+ const rows = [headers];
152
+ for (const o of arr) {
153
+ rows.push(headers.map((h) => {
154
+ const x = o[h];
155
+ return x === undefined || x === null ? null : typeof x === "number" ? x : typeof x === "object" ? JSON.stringify(x) : String(x);
156
+ }));
157
+ }
158
+ return { kind: "json", sheets: [{ name, rows }] };
159
+ }
160
+ export function readWorkbook(fileName, data) {
161
+ const lower = fileName.toLowerCase();
162
+ if (lower.endsWith(".xlsx") || (data[0] === 0x50 && data[1] === 0x4b))
163
+ return readXlsx(data);
164
+ const text = new TextDecoder().decode(data);
165
+ if (lower.endsWith(".json"))
166
+ return readJson(text, fileName);
167
+ return readCsv(text, fileName);
168
+ }
@@ -0,0 +1,6 @@
1
+ import type { Cell } from "./workbook.js";
2
+ /** Minimal xlsx writer (shared strings, numbers). Used for fixtures and exports. */
3
+ export declare function writeXlsx(sheets: {
4
+ name: string;
5
+ rows: Cell[][];
6
+ }[]): Uint8Array;
@@ -0,0 +1,38 @@
1
+ import { strToU8, zipSync } from "fflate";
2
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
3
+ const colName = (i) => (i < 26 ? String.fromCharCode(65 + i) : colName(Math.floor(i / 26) - 1) + String.fromCharCode(65 + (i % 26)));
4
+ /** Minimal xlsx writer (shared strings, numbers). Used for fixtures and exports. */
5
+ export function writeXlsx(sheets) {
6
+ const shared = [];
7
+ const idx = new Map();
8
+ const si = (s) => {
9
+ if (!idx.has(s)) {
10
+ idx.set(s, shared.length);
11
+ shared.push(s);
12
+ }
13
+ return idx.get(s);
14
+ };
15
+ const files = {};
16
+ sheets.forEach((sh, n) => {
17
+ const rows = sh.rows
18
+ .map((row, r) => {
19
+ const cells = row
20
+ .map((c, i) => {
21
+ if (c === null || c === undefined)
22
+ return "";
23
+ const ref = `${colName(i)}${r + 1}`;
24
+ return typeof c === "number" ? `<c r="${ref}"><v>${c}</v></c>` : `<c r="${ref}" t="s"><v>${si(c)}</v></c>`;
25
+ })
26
+ .join("");
27
+ return `<row r="${r + 1}">${cells}</row>`;
28
+ })
29
+ .join("");
30
+ files[`xl/worksheets/sheet${n + 1}.xml`] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${rows}</sheetData></worksheet>`);
31
+ });
32
+ files["xl/sharedStrings.xml"] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="${shared.length}" uniqueCount="${shared.length}">${shared.map((s) => `<si><t xml:space="preserve">${esc(s)}</t></si>`).join("")}</sst>`);
33
+ files["xl/workbook.xml"] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>${sheets.map((s, i) => `<sheet name="${esc(s.name)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join("")}</sheets></workbook>`);
34
+ files["xl/_rels/workbook.xml.rels"] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${sheets.map((_, i) => `<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`).join("")}<Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/></Relationships>`);
35
+ files["[Content_Types].xml"] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${sheets.map((_, i) => `<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join("")}<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/></Types>`);
36
+ files["_rels/.rels"] = strToU8(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`);
37
+ return zipSync(files);
38
+ }
@@ -0,0 +1,3 @@
1
+ import type { FileMap } from "../engine/load.js";
2
+ /** Reads a data repo's data/ folder into a FileMap (paths relative to the repo root, "/" separators). */
3
+ export declare function readDataDir(root: string): FileMap;