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.
- package/AGENTS.md +93 -0
- package/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +102 -2
- package/assets/_headers +5 -0
- package/assets/app.css +61 -0
- package/assets/app.js +369 -0
- package/assets/icon.svg +1 -0
- package/assets/index.html +30 -0
- package/assets/manifest.webmanifest +1 -0
- package/dist/cli/check.d.ts +3 -0
- package/dist/cli/check.js +21 -0
- package/dist/cli/deploy.d.ts +1 -0
- package/dist/cli/deploy.js +258 -0
- package/dist/cli/dev.d.ts +3 -0
- package/dist/cli/dev.js +107 -0
- package/dist/cli/import.d.ts +3 -0
- package/dist/cli/import.js +151 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +47 -0
- package/dist/cli/init.d.ts +1 -0
- package/dist/cli/init.js +73 -0
- package/dist/cli/jsonc.d.ts +2 -0
- package/dist/cli/jsonc.js +39 -0
- package/dist/engine/actions.d.ts +53 -0
- package/dist/engine/actions.js +205 -0
- package/dist/engine/balances.d.ts +30 -0
- package/dist/engine/balances.js +75 -0
- package/dist/engine/categories.d.ts +17 -0
- package/dist/engine/categories.js +35 -0
- package/dist/engine/check.d.ts +11 -0
- package/dist/engine/check.js +220 -0
- package/dist/engine/dates.d.ts +15 -0
- package/dist/engine/dates.js +56 -0
- package/dist/engine/defaults.d.ts +2 -0
- package/dist/engine/defaults.js +61 -0
- package/dist/engine/index.d.ts +13 -0
- package/dist/engine/index.js +13 -0
- package/dist/engine/load.d.ts +23 -0
- package/dist/engine/load.js +129 -0
- package/dist/engine/networth.d.ts +12 -0
- package/dist/engine/networth.js +73 -0
- package/dist/engine/registry.d.ts +24 -0
- package/dist/engine/registry.js +41 -0
- package/dist/engine/reports.d.ts +68 -0
- package/dist/engine/reports.js +149 -0
- package/dist/engine/schedules.d.ts +75 -0
- package/dist/engine/schedules.js +208 -0
- package/dist/engine/types.d.ts +122 -0
- package/dist/engine/types.js +2 -0
- package/dist/engine/write.d.ts +30 -0
- package/dist/engine/write.js +105 -0
- package/dist/import/hash.d.ts +1 -0
- package/dist/import/hash.js +17 -0
- package/dist/import/index.d.ts +6 -0
- package/dist/import/index.js +6 -0
- package/dist/import/mapping.d.ts +96 -0
- package/dist/import/mapping.js +54 -0
- package/dist/import/profile.d.ts +39 -0
- package/dist/import/profile.js +125 -0
- package/dist/import/run.d.ts +101 -0
- package/dist/import/run.js +416 -0
- package/dist/import/workbook.d.ts +13 -0
- package/dist/import/workbook.js +168 -0
- package/dist/import/xlsx-write.d.ts +6 -0
- package/dist/import/xlsx-write.js +38 -0
- package/dist/node/files.d.ts +3 -0
- package/dist/node/files.js +26 -0
- package/dist/node/scaffold.d.ts +14 -0
- package/dist/node/scaffold.js +45 -0
- package/dist/worker/api.d.ts +3 -0
- package/dist/worker/api.js +139 -0
- package/dist/worker/auth.d.ts +11 -0
- package/dist/worker/auth.js +176 -0
- package/dist/worker/env.d.ts +25 -0
- package/dist/worker/env.js +6 -0
- package/dist/worker/github.d.ts +29 -0
- package/dist/worker/github.js +154 -0
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.js +64 -0
- package/dist/worker/mcp.d.ts +4 -0
- package/dist/worker/mcp.js +292 -0
- package/dist/worker/store.d.ts +42 -0
- package/dist/worker/store.js +92 -0
- package/dist/worker/tar.d.ts +2 -0
- package/dist/worker/tar.js +62 -0
- package/dist/worker/version.d.ts +1 -0
- package/dist/worker/version.js +2 -0
- package/package.json +68 -4
- package/presets/misa.mapping.yaml +48 -0
- package/templates/repo/.github/dependabot.yml +11 -0
- package/templates/repo/.github/workflows/check.yml +15 -0
- package/templates/repo/.github/workflows/deploy.yml +21 -0
- package/templates/repo/README.md +10 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type FileMap } from "./load.js";
|
|
2
|
+
import type { Account, Issue, Price, Transaction } from "./types.js";
|
|
3
|
+
/** A set of edits to a data repo. applyChange turns it into new file contents (only the files that change). */
|
|
4
|
+
export interface Change {
|
|
5
|
+
addTransactions?: Transaction[];
|
|
6
|
+
/** Replace by id (the new version may have another date, so it can move between month files). */
|
|
7
|
+
replaceTransactions?: Transaction[];
|
|
8
|
+
addAccounts?: Account[];
|
|
9
|
+
/** Shallow-merge fields into existing accounts by id (null deletes a key). */
|
|
10
|
+
updateAccounts?: {
|
|
11
|
+
id: string;
|
|
12
|
+
set: Record<string, unknown>;
|
|
13
|
+
}[];
|
|
14
|
+
/** Append to or update a YAML list file by id (plans.yaml, assets.yaml...). */
|
|
15
|
+
upsertList?: {
|
|
16
|
+
path: string;
|
|
17
|
+
items: {
|
|
18
|
+
id: string;
|
|
19
|
+
[k: string]: unknown;
|
|
20
|
+
}[];
|
|
21
|
+
}[];
|
|
22
|
+
addPrices?: Price[];
|
|
23
|
+
/** Replace whole files (e.g. categories.yaml after a remap). */
|
|
24
|
+
putFiles?: FileMap;
|
|
25
|
+
}
|
|
26
|
+
export declare function txLine(t: Transaction): string;
|
|
27
|
+
export declare function applyChange(files: FileMap, ch: Change): FileMap;
|
|
28
|
+
/** Short human summary of what a change does (for previews and commit messages). */
|
|
29
|
+
export declare function describeChange(ch: Change): string[];
|
|
30
|
+
export type { Issue };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { isMap, isSeq, parseDocument, stringify } from "yaml";
|
|
2
|
+
import { compareTx, ledgerPath, LEDGER_FILE_RE, parseJsonl, PATHS } from "./load.js";
|
|
3
|
+
export function txLine(t) {
|
|
4
|
+
return JSON.stringify(t);
|
|
5
|
+
}
|
|
6
|
+
function upsertYamlList(text, items, mergeOnly = false) {
|
|
7
|
+
const doc = parseDocument(text ?? "[]\n");
|
|
8
|
+
if (!isSeq(doc.contents)) {
|
|
9
|
+
if (doc.contents === null)
|
|
10
|
+
doc.contents = doc.createNode([]);
|
|
11
|
+
else
|
|
12
|
+
throw new Error("expected a YAML list");
|
|
13
|
+
}
|
|
14
|
+
const seq = doc.contents;
|
|
15
|
+
for (const item of items) {
|
|
16
|
+
const existing = seq.items.find((n) => isMap(n) && n.get("id") === item.id);
|
|
17
|
+
if (existing && isMap(existing)) {
|
|
18
|
+
for (const [k, v] of Object.entries(item)) {
|
|
19
|
+
if (k === "id")
|
|
20
|
+
continue;
|
|
21
|
+
if (v === null && mergeOnly)
|
|
22
|
+
existing.delete(k);
|
|
23
|
+
else
|
|
24
|
+
existing.set(k, doc.createNode(v));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else if (!mergeOnly) {
|
|
28
|
+
seq.items.push(doc.createNode(item));
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
throw new Error(`no item with id "${item.id}"`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
let out = doc.toString({ lineWidth: 0 });
|
|
35
|
+
if (out.startsWith("[]"))
|
|
36
|
+
out = stringify(items, { lineWidth: 0 });
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
export function applyChange(files, ch) {
|
|
40
|
+
const out = {};
|
|
41
|
+
const cur = (p) => (p in out ? out[p] : files[p]);
|
|
42
|
+
// transactions
|
|
43
|
+
const add = ch.addTransactions ?? [];
|
|
44
|
+
const rep = ch.replaceTransactions ?? [];
|
|
45
|
+
if (add.length || rep.length) {
|
|
46
|
+
const repIds = new Set(rep.map((t) => t.id));
|
|
47
|
+
const touched = new Map();
|
|
48
|
+
const load = (p) => {
|
|
49
|
+
if (!touched.has(p))
|
|
50
|
+
touched.set(p, files[p] !== undefined ? parseJsonl(files[p], p, []) : []);
|
|
51
|
+
return touched.get(p);
|
|
52
|
+
};
|
|
53
|
+
if (repIds.size) {
|
|
54
|
+
for (const p of Object.keys(files)) {
|
|
55
|
+
if (!LEDGER_FILE_RE.test(p))
|
|
56
|
+
continue;
|
|
57
|
+
if (![...repIds].some((id) => files[p].includes(`"${id}"`)))
|
|
58
|
+
continue;
|
|
59
|
+
const arr = load(p);
|
|
60
|
+
touched.set(p, arr.filter((t) => !repIds.has(t.id)));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
for (const t of [...rep, ...add])
|
|
64
|
+
load(ledgerPath(t.date)).push(t);
|
|
65
|
+
for (const [p, arr] of touched) {
|
|
66
|
+
arr.sort(compareTx);
|
|
67
|
+
out[p] = arr.map(txLine).join("\n") + (arr.length ? "\n" : "");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (ch.addAccounts?.length)
|
|
71
|
+
out[PATHS.accounts] = upsertYamlList(cur(PATHS.accounts), ch.addAccounts);
|
|
72
|
+
if (ch.updateAccounts?.length) {
|
|
73
|
+
out[PATHS.accounts] = upsertYamlList(cur(PATHS.accounts), ch.updateAccounts.map((u) => ({ id: u.id, ...u.set })), true);
|
|
74
|
+
}
|
|
75
|
+
for (const u of ch.upsertList ?? [])
|
|
76
|
+
out[u.path] = upsertYamlList(cur(u.path), u.items);
|
|
77
|
+
if (ch.addPrices?.length) {
|
|
78
|
+
let text = cur(PATHS.prices) ?? "date,asset,price\n";
|
|
79
|
+
if (!text.endsWith("\n"))
|
|
80
|
+
text += "\n";
|
|
81
|
+
out[PATHS.prices] = text + ch.addPrices.map((p) => `${p.date},${p.asset},${p.price}`).join("\n") + "\n";
|
|
82
|
+
}
|
|
83
|
+
for (const [p, c] of Object.entries(ch.putFiles ?? {}))
|
|
84
|
+
out[p] = c;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/** Short human summary of what a change does (for previews and commit messages). */
|
|
88
|
+
export function describeChange(ch) {
|
|
89
|
+
const s = [];
|
|
90
|
+
if (ch.addTransactions?.length)
|
|
91
|
+
s.push(`add ${ch.addTransactions.length} transaction(s)`);
|
|
92
|
+
if (ch.replaceTransactions?.length)
|
|
93
|
+
s.push(`update ${ch.replaceTransactions.length} transaction(s)`);
|
|
94
|
+
if (ch.addAccounts?.length)
|
|
95
|
+
s.push(`add ${ch.addAccounts.length} account(s)`);
|
|
96
|
+
if (ch.updateAccounts?.length)
|
|
97
|
+
s.push(`update account(s) ${ch.updateAccounts.map((u) => u.id).join(", ")}`);
|
|
98
|
+
for (const u of ch.upsertList ?? [])
|
|
99
|
+
s.push(`${u.path}: ${u.items.map((i) => i.id).join(", ")}`);
|
|
100
|
+
if (ch.addPrices?.length)
|
|
101
|
+
s.push(`add ${ch.addPrices.length} price(s)`);
|
|
102
|
+
for (const p of Object.keys(ch.putFiles ?? {}))
|
|
103
|
+
s.push(`rewrite ${p}`);
|
|
104
|
+
return s;
|
|
105
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function stableKey(parts: (string | number | null | undefined)[]): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** cyrb53, a fast non-crypto 53-bit hash. Two seeds give a 26-hex-digit key; plenty for import keys. */
|
|
2
|
+
function cyrb53(str, seed) {
|
|
3
|
+
let h1 = 0xdeadbeef ^ seed;
|
|
4
|
+
let h2 = 0x41c6ce57 ^ seed;
|
|
5
|
+
for (let i = 0; i < str.length; i++) {
|
|
6
|
+
const ch = str.charCodeAt(i);
|
|
7
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
8
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
9
|
+
}
|
|
10
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
11
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
12
|
+
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
|
13
|
+
}
|
|
14
|
+
export function stableKey(parts) {
|
|
15
|
+
const s = parts.map((p) => (p === null || p === undefined ? "" : String(p))).join("\u001f");
|
|
16
|
+
return cyrb53(s, 1).toString(16).padStart(14, "0") + cyrb53(s, 2).toString(16).padStart(14, "0").slice(0, 12);
|
|
17
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A mapping file (imports/<source>.mapping.yaml) tells the generic table importer how to read one
|
|
3
|
+
* app's export. The AI writes it once (on the first import); later imports run it as plain code.
|
|
4
|
+
*/
|
|
5
|
+
export interface AccountMap {
|
|
6
|
+
id: string;
|
|
7
|
+
name?: string;
|
|
8
|
+
type?: string;
|
|
9
|
+
asset?: string;
|
|
10
|
+
opened?: string;
|
|
11
|
+
closed?: string | null;
|
|
12
|
+
group?: string;
|
|
13
|
+
details?: Record<string, unknown>;
|
|
14
|
+
/** Full names the source uses for this account in notes (sheet names may be truncated). */
|
|
15
|
+
names?: string[];
|
|
16
|
+
[k: string]: unknown;
|
|
17
|
+
}
|
|
18
|
+
export interface Mapping {
|
|
19
|
+
source: string;
|
|
20
|
+
reader?: "table";
|
|
21
|
+
/** Sheets to read: "all" (default) or a list of sheet names. */
|
|
22
|
+
sheets?: "all" | string[];
|
|
23
|
+
skip_sheets?: string[];
|
|
24
|
+
/** 1-based row of the column headers. Default: the first row containing columns.date. */
|
|
25
|
+
header_row?: number;
|
|
26
|
+
/** Where the source account comes from: one account per sheet (default), a column, or one fixed account. */
|
|
27
|
+
account_from?: "sheet" | "column" | "fixed";
|
|
28
|
+
account_column?: string;
|
|
29
|
+
account?: string;
|
|
30
|
+
columns: {
|
|
31
|
+
date: string;
|
|
32
|
+
time?: string;
|
|
33
|
+
in?: string;
|
|
34
|
+
out?: string;
|
|
35
|
+
amount?: string;
|
|
36
|
+
balance?: string;
|
|
37
|
+
category?: string;
|
|
38
|
+
subcategory?: string;
|
|
39
|
+
who?: string;
|
|
40
|
+
event?: string;
|
|
41
|
+
note?: string;
|
|
42
|
+
tags?: string;
|
|
43
|
+
};
|
|
44
|
+
date_format?: "dd/mm/yyyy" | "mm/dd/yyyy" | "yyyy-mm-dd";
|
|
45
|
+
/** Decimal separator in amounts written as text. Default ".". */
|
|
46
|
+
decimal?: "." | ",";
|
|
47
|
+
/** Newest rows first (default: detected from dates). */
|
|
48
|
+
newest_first?: boolean;
|
|
49
|
+
/** Labels of the source's own figures, found above the header row; the value is the next number to the right. */
|
|
50
|
+
totals?: {
|
|
51
|
+
opening?: string;
|
|
52
|
+
closing?: string;
|
|
53
|
+
in?: string;
|
|
54
|
+
out?: string;
|
|
55
|
+
};
|
|
56
|
+
transfers?: {
|
|
57
|
+
/** Only rows without a category can be transfers (default true). */
|
|
58
|
+
only_without_category?: boolean;
|
|
59
|
+
/** Regex on the note for money leaving to another account; named group "wallet" = the other account's name. */
|
|
60
|
+
out: string;
|
|
61
|
+
in: string;
|
|
62
|
+
};
|
|
63
|
+
/** Source account name (sheet name, column value) → ownledger account. */
|
|
64
|
+
accounts: Record<string, AccountMap>;
|
|
65
|
+
/** Source category "Parent/Child" or "Parent" → ownledger category path, or "account:<id>" for moves between own accounts. */
|
|
66
|
+
categories: Record<string, string>;
|
|
67
|
+
/** Checked first, on every row that is not a transfer: regex on the note (and optionally the source category) → category or account:<id>. */
|
|
68
|
+
rules?: {
|
|
69
|
+
match: string;
|
|
70
|
+
category: string;
|
|
71
|
+
sign?: "in" | "out";
|
|
72
|
+
source_category?: string;
|
|
73
|
+
}[];
|
|
74
|
+
/** Rows with no category that are not transfers: first matching rule wins (regex on the note). */
|
|
75
|
+
uncategorized?: {
|
|
76
|
+
match: string;
|
|
77
|
+
category: string;
|
|
78
|
+
sign?: "in" | "out";
|
|
79
|
+
}[];
|
|
80
|
+
uncategorized_in?: string;
|
|
81
|
+
uncategorized_out?: string;
|
|
82
|
+
/** Transfers whose other side is not in the file (e.g. a skipped sheet): regex on the named wallet → category or account:<id>. */
|
|
83
|
+
unpaired?: {
|
|
84
|
+
wallet: string;
|
|
85
|
+
category: string;
|
|
86
|
+
}[];
|
|
87
|
+
/** Book an _adjust on each closed account's closing date so it ends at exactly 0 (source rounding leftovers). */
|
|
88
|
+
zero_closed?: boolean;
|
|
89
|
+
/** Account that receives transfers whose other side can't be found. Default "import-unmatched". */
|
|
90
|
+
unmatched_account?: string;
|
|
91
|
+
/** Opening balances (from totals.opening) are booked on this date, or on the account's first row date. */
|
|
92
|
+
opening_date?: string;
|
|
93
|
+
[k: string]: unknown;
|
|
94
|
+
}
|
|
95
|
+
export declare function parseMapping(text: string): Mapping;
|
|
96
|
+
export declare function validateMapping(m: Mapping): string[];
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { parse as parseYaml } from "yaml";
|
|
2
|
+
export function parseMapping(text) {
|
|
3
|
+
const m = parseYaml(text);
|
|
4
|
+
const errs = validateMapping(m);
|
|
5
|
+
if (errs.length)
|
|
6
|
+
throw new Error(`mapping is not valid:\n- ${errs.join("\n- ")}`);
|
|
7
|
+
return m;
|
|
8
|
+
}
|
|
9
|
+
export function validateMapping(m) {
|
|
10
|
+
const e = [];
|
|
11
|
+
if (!m || typeof m !== "object")
|
|
12
|
+
return ["not a YAML map"];
|
|
13
|
+
if (typeof m.source !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(m.source))
|
|
14
|
+
e.push("source: short lowercase id (e.g. misa)");
|
|
15
|
+
if (m.reader && m.reader !== "table")
|
|
16
|
+
e.push(`reader: only "table" is supported`);
|
|
17
|
+
if (!m.columns || typeof m.columns.date !== "string")
|
|
18
|
+
e.push("columns.date is required");
|
|
19
|
+
if (m.columns && !m.columns.amount && !(m.columns.in || m.columns.out))
|
|
20
|
+
e.push("columns: give amount, or in and/or out");
|
|
21
|
+
if (m.account_from === "column" && !m.account_column)
|
|
22
|
+
e.push("account_column is required when account_from is column");
|
|
23
|
+
if (m.account_from === "fixed" && !m.account)
|
|
24
|
+
e.push("account is required when account_from is fixed");
|
|
25
|
+
if (!m.accounts || typeof m.accounts !== "object")
|
|
26
|
+
e.push("accounts: map of source account → {id, name, type}");
|
|
27
|
+
else
|
|
28
|
+
for (const [k, a] of Object.entries(m.accounts)) {
|
|
29
|
+
if (!a || typeof a.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(a.id))
|
|
30
|
+
e.push(`accounts["${k}"].id: letters, digits, . _ - only`);
|
|
31
|
+
}
|
|
32
|
+
if (!m.categories || typeof m.categories !== "object")
|
|
33
|
+
e.push("categories: map of source category → ownledger category");
|
|
34
|
+
for (const key of ["out", "in"]) {
|
|
35
|
+
const r = m.transfers?.[key];
|
|
36
|
+
if (r !== undefined) {
|
|
37
|
+
try {
|
|
38
|
+
new RegExp(r, "u");
|
|
39
|
+
}
|
|
40
|
+
catch (x) {
|
|
41
|
+
e.push(`transfers.${key}: bad regex (${x.message})`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
for (const u of [...(m.rules ?? []), ...(m.uncategorized ?? []), ...(m.unpaired ?? []).map((x) => ({ match: x.wallet }))]) {
|
|
46
|
+
try {
|
|
47
|
+
new RegExp(u.match, "iu");
|
|
48
|
+
}
|
|
49
|
+
catch (x) {
|
|
50
|
+
e.push(`uncategorized "${u.match}": bad regex`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return e;
|
|
54
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Cell, Workbook } from "./workbook.js";
|
|
2
|
+
/**
|
|
3
|
+
* Describes an export file so an AI can write its mapping: sheets, header rows, labelled figures
|
|
4
|
+
* above the header, sample rows, distinct values of low-variety columns, and note patterns of rows
|
|
5
|
+
* with an empty column (often transfers). Amounts are shown as they are; this runs on the user's machine.
|
|
6
|
+
*/
|
|
7
|
+
export interface SheetProfile {
|
|
8
|
+
name: string;
|
|
9
|
+
headerRow: number | null;
|
|
10
|
+
headers: string[];
|
|
11
|
+
rows: number;
|
|
12
|
+
firstDate: string | null;
|
|
13
|
+
lastDate: string | null;
|
|
14
|
+
figures: Record<string, Cell>;
|
|
15
|
+
}
|
|
16
|
+
export interface Profile {
|
|
17
|
+
kind: Workbook["kind"];
|
|
18
|
+
sheets: SheetProfile[];
|
|
19
|
+
sameHeaders: boolean;
|
|
20
|
+
samples: {
|
|
21
|
+
sheet: string;
|
|
22
|
+
rows: Record<string, Cell>[];
|
|
23
|
+
}[];
|
|
24
|
+
distinct: Record<string, {
|
|
25
|
+
value: string;
|
|
26
|
+
rows: number;
|
|
27
|
+
}[]>;
|
|
28
|
+
emptyColumnNotes: {
|
|
29
|
+
column: string;
|
|
30
|
+
noteColumn: string;
|
|
31
|
+
patterns: {
|
|
32
|
+
pattern: string;
|
|
33
|
+
rows: number;
|
|
34
|
+
}[];
|
|
35
|
+
}[];
|
|
36
|
+
hints: string[];
|
|
37
|
+
}
|
|
38
|
+
export declare function profileWorkbook(wb: Workbook): Profile;
|
|
39
|
+
export declare function profileText(p: Profile): string;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
const isText = (c) => typeof c === "string" && c.trim() !== "" && !/^[\d.,:/\- ]+$/.test(c);
|
|
2
|
+
const isDateLike = (c) => typeof c === "string" && /^\d{1,4}[/.-]\d{1,2}[/.-]\d{1,4}/.test(c.trim());
|
|
3
|
+
function guessHeader(s) {
|
|
4
|
+
let best = -1;
|
|
5
|
+
let bestScore = 0;
|
|
6
|
+
const limit = Math.min(s.rows.length - 1, 40);
|
|
7
|
+
for (let r = 0; r < limit; r++) {
|
|
8
|
+
const row = s.rows[r] ?? [];
|
|
9
|
+
const texts = row.filter(isText).length;
|
|
10
|
+
const next = s.rows[r + 1] ?? [];
|
|
11
|
+
const filled = next.filter((c) => c !== null).length;
|
|
12
|
+
const score = texts >= 3 && filled >= Math.min(3, texts) ? texts + (next.some(isDateLike) ? 5 : 0) : 0;
|
|
13
|
+
if (score > bestScore) {
|
|
14
|
+
best = r;
|
|
15
|
+
bestScore = score;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return best;
|
|
19
|
+
}
|
|
20
|
+
const mask = (s) => s
|
|
21
|
+
.replace(/\d[\d.,]*/g, "#")
|
|
22
|
+
.replace(/(Chuyển (?:từ|tới)|from|to)\s+[^()]+/giu, "$1 <name>")
|
|
23
|
+
.slice(0, 80);
|
|
24
|
+
export function profileWorkbook(wb) {
|
|
25
|
+
const sheets = [];
|
|
26
|
+
const distinct = new Map();
|
|
27
|
+
const samples = [];
|
|
28
|
+
const empties = new Map(); // "col|noteCol" → pattern → rows
|
|
29
|
+
let firstHeaders = null;
|
|
30
|
+
let same = true;
|
|
31
|
+
for (const s of wb.sheets) {
|
|
32
|
+
const h = guessHeader(s);
|
|
33
|
+
const headers = h >= 0 ? (s.rows[h] ?? []).map((c) => (c === null ? "" : String(c).trim())) : [];
|
|
34
|
+
const figures = {};
|
|
35
|
+
for (let r = 0; r < Math.max(h, 0); r++) {
|
|
36
|
+
const row = s.rows[r] ?? [];
|
|
37
|
+
row.forEach((c, i) => {
|
|
38
|
+
if (!isText(c))
|
|
39
|
+
return;
|
|
40
|
+
const v = row.slice(i + 1).find((x) => typeof x === "number" || (typeof x === "string" && /^-?[\d.,]+$/.test(x)));
|
|
41
|
+
if (v !== undefined)
|
|
42
|
+
figures[String(c).trim()] = v;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const data = h >= 0 ? s.rows.slice(h + 1).filter((r) => r && r.some((c) => c !== null)) : [];
|
|
46
|
+
const dateCol = headers.findIndex((_, i) => data.slice(0, 20).some((r) => isDateLike(r[i] ?? null)));
|
|
47
|
+
const dates = dateCol >= 0 ? data.map((r) => r[dateCol] ?? null).filter(isDateLike).map(String) : [];
|
|
48
|
+
sheets.push({ name: s.name, headerRow: h >= 0 ? h + 1 : null, headers, rows: data.length, firstDate: dates.at(-1) ?? null, lastDate: dates[0] ?? null, figures });
|
|
49
|
+
const sig = headers.join("|");
|
|
50
|
+
if (firstHeaders === null)
|
|
51
|
+
firstHeaders = sig;
|
|
52
|
+
else if (sig !== firstHeaders)
|
|
53
|
+
same = false;
|
|
54
|
+
if (samples.length < 3 && data.length) {
|
|
55
|
+
samples.push({ sheet: s.name, rows: data.slice(0, 5).map((r) => Object.fromEntries(headers.map((hh, i) => [hh || `col${i + 1}`, r[i] ?? null]))) });
|
|
56
|
+
}
|
|
57
|
+
const noteCol = headers.findIndex((x) => /diễn giải|note|description|memo|ghi chú|nội dung/i.test(x));
|
|
58
|
+
headers.forEach((name, i) => {
|
|
59
|
+
if (!name)
|
|
60
|
+
return;
|
|
61
|
+
const m = distinct.get(name) ?? new Map();
|
|
62
|
+
for (const r of data) {
|
|
63
|
+
const v = r[i];
|
|
64
|
+
if (v === null || v === undefined || typeof v === "number")
|
|
65
|
+
continue;
|
|
66
|
+
m.set(String(v), (m.get(String(v)) ?? 0) + 1);
|
|
67
|
+
}
|
|
68
|
+
distinct.set(name, m);
|
|
69
|
+
if (noteCol >= 0 && i !== noteCol && i !== dateCol) {
|
|
70
|
+
const empty = data.filter((r) => (r[i] ?? null) === null);
|
|
71
|
+
if (empty.length && empty.length < data.length) {
|
|
72
|
+
const k = `${name}|${headers[noteCol]}`;
|
|
73
|
+
const pm = empties.get(k) ?? new Map();
|
|
74
|
+
for (const r of empty) {
|
|
75
|
+
const p = mask(String(r[noteCol] ?? ""));
|
|
76
|
+
pm.set(p, (pm.get(p) ?? 0) + 1);
|
|
77
|
+
}
|
|
78
|
+
empties.set(k, pm);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const hints = [];
|
|
84
|
+
const text = wb.sheets.slice(0, 1).flatMap((s) => s.rows.slice(0, 8).flat()).filter(isText).join(" ");
|
|
85
|
+
if (/SỔ THU CHI/i.test(text) && /Bảng Kê Thu Chi/i.test(text))
|
|
86
|
+
hints.push("Looks like MISA Sổ Thu Chi: start from the preset `ownledger import --preset misa` writes (presets/misa.mapping.yaml).");
|
|
87
|
+
if (wb.sheets.length > 1 && same)
|
|
88
|
+
hints.push(`${wb.sheets.length} sheets share the same header: probably one account per sheet (account_from: sheet). Sheet names may be cut to 31 characters; full names often appear in transfer notes.`);
|
|
89
|
+
return {
|
|
90
|
+
kind: wb.kind,
|
|
91
|
+
sheets,
|
|
92
|
+
sameHeaders: same,
|
|
93
|
+
samples,
|
|
94
|
+
distinct: Object.fromEntries([...distinct]
|
|
95
|
+
.filter(([, m]) => m.size > 0 && m.size <= 60)
|
|
96
|
+
.map(([k, m]) => [k, [...m].sort((a, b) => b[1] - a[1]).map(([value, rows]) => ({ value, rows }))])),
|
|
97
|
+
emptyColumnNotes: [...empties]
|
|
98
|
+
.map(([k, pm]) => {
|
|
99
|
+
const [column, noteColumn] = k.split("|");
|
|
100
|
+
return { column, noteColumn, patterns: [...pm].sort((a, b) => b[1] - a[1]).slice(0, 25).map(([pattern, rows]) => ({ pattern, rows })) };
|
|
101
|
+
})
|
|
102
|
+
.filter((e) => e.patterns.length),
|
|
103
|
+
hints,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
export function profileText(p) {
|
|
107
|
+
const out = [];
|
|
108
|
+
out.push(`# Export profile (${p.kind}, ${p.sheets.length} sheet(s))`, "");
|
|
109
|
+
for (const h of p.hints)
|
|
110
|
+
out.push(`> ${h}`);
|
|
111
|
+
out.push("", "## Sheets", "", "| sheet | header row | rows | first → last date | figures above header |", "|---|---|---|---|---|");
|
|
112
|
+
for (const s of p.sheets)
|
|
113
|
+
out.push(`| ${s.name} | ${s.headerRow ?? "?"} | ${s.rows} | ${s.firstDate ?? ""} → ${s.lastDate ?? ""} | ${Object.entries(s.figures).map(([k, v]) => `${k}: ${v}`).join("; ")} |`);
|
|
114
|
+
out.push("", `## Headers${p.sameHeaders ? " (same on every sheet)" : ""}`, "", p.sheets[0]?.headers.filter(Boolean).map((h) => `\`${h}\``).join(", ") ?? "");
|
|
115
|
+
out.push("", "## Sample rows");
|
|
116
|
+
for (const s of p.samples)
|
|
117
|
+
out.push("", `### ${s.sheet}`, "```json", ...s.rows.map((r) => JSON.stringify(r)), "```");
|
|
118
|
+
out.push("", "## Distinct values (columns with ≤ 60 values, all sheets)");
|
|
119
|
+
for (const [k, vs] of Object.entries(p.distinct))
|
|
120
|
+
out.push("", `- **${k}**: ${vs.map((v) => `${v.value} (${v.rows})`).join(" · ")}`);
|
|
121
|
+
out.push("", "## Notes of rows where a column is empty (digits → #, names → <name>)");
|
|
122
|
+
for (const e of p.emptyColumnNotes)
|
|
123
|
+
out.push("", `- **${e.column}** empty → ${e.noteColumn}: ${e.patterns.map((x) => `"${x.pattern}" (${x.rows})`).join(" · ")}`);
|
|
124
|
+
return out.join("\n") + "\n";
|
|
125
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Account, Ledger, Transaction } from "../engine/types.js";
|
|
2
|
+
import type { Mapping } from "./mapping.js";
|
|
3
|
+
import type { Cell, Sheet, Workbook } from "./workbook.js";
|
|
4
|
+
export interface SourceRow {
|
|
5
|
+
sheet: string;
|
|
6
|
+
sourceAccount: string;
|
|
7
|
+
account: string;
|
|
8
|
+
row: number;
|
|
9
|
+
date: string;
|
|
10
|
+
time: string | null;
|
|
11
|
+
cents: number;
|
|
12
|
+
amount: number;
|
|
13
|
+
catKey: string | null;
|
|
14
|
+
note: string;
|
|
15
|
+
who: string | null;
|
|
16
|
+
event: string | null;
|
|
17
|
+
tags: string[];
|
|
18
|
+
key: string;
|
|
19
|
+
kind?: "category" | "transfer" | "unresolved";
|
|
20
|
+
category?: string;
|
|
21
|
+
wallet?: string;
|
|
22
|
+
pairedWith?: SourceRow;
|
|
23
|
+
}
|
|
24
|
+
export interface Reconcile {
|
|
25
|
+
sheet: string;
|
|
26
|
+
account: string;
|
|
27
|
+
rows: number;
|
|
28
|
+
source: {
|
|
29
|
+
opening: number | null;
|
|
30
|
+
in: number | null;
|
|
31
|
+
out: number | null;
|
|
32
|
+
closing: number | null;
|
|
33
|
+
};
|
|
34
|
+
imported: {
|
|
35
|
+
opening: number;
|
|
36
|
+
in: number;
|
|
37
|
+
out: number;
|
|
38
|
+
closing: number;
|
|
39
|
+
};
|
|
40
|
+
rounding: number;
|
|
41
|
+
zeroed: number;
|
|
42
|
+
ok: boolean;
|
|
43
|
+
problems: string[];
|
|
44
|
+
}
|
|
45
|
+
export interface ImportResult {
|
|
46
|
+
ok: boolean;
|
|
47
|
+
source: string;
|
|
48
|
+
rows: number;
|
|
49
|
+
transactions: Transaction[];
|
|
50
|
+
accounts: Account[];
|
|
51
|
+
skipped: number;
|
|
52
|
+
changed: {
|
|
53
|
+
key: string;
|
|
54
|
+
id: string;
|
|
55
|
+
was: string;
|
|
56
|
+
now: string;
|
|
57
|
+
}[];
|
|
58
|
+
/** Opening/rounding transactions whose amount changed on re-import: replaced, since they are derived from the file. */
|
|
59
|
+
replace: Transaction[];
|
|
60
|
+
gone: {
|
|
61
|
+
id: string;
|
|
62
|
+
date: string;
|
|
63
|
+
note?: string;
|
|
64
|
+
key: string;
|
|
65
|
+
}[];
|
|
66
|
+
unpaired: SourceRow[];
|
|
67
|
+
unresolvedCategories: {
|
|
68
|
+
key: string;
|
|
69
|
+
rows: number;
|
|
70
|
+
example: string;
|
|
71
|
+
}[];
|
|
72
|
+
unresolvedRows: SourceRow[];
|
|
73
|
+
reconcile: Reconcile[];
|
|
74
|
+
rounding: {
|
|
75
|
+
sheet: string;
|
|
76
|
+
diff: number;
|
|
77
|
+
}[];
|
|
78
|
+
zeroed: {
|
|
79
|
+
account: string;
|
|
80
|
+
date: string;
|
|
81
|
+
amount: number;
|
|
82
|
+
}[];
|
|
83
|
+
errors: string[];
|
|
84
|
+
}
|
|
85
|
+
export declare function parseAmount(v: Cell, decimal?: "." | ","): number | null;
|
|
86
|
+
export declare function parseDate(v: Cell, fmt: Mapping["date_format"]): string | null;
|
|
87
|
+
/** Excel's sheet name for a full name: forbidden chars → "_", max 31 chars. */
|
|
88
|
+
export declare function excelSheetName(name: string): string;
|
|
89
|
+
declare function readTotals(sheet: Sheet, headerIdx: number, m: Mapping): Record<"closing" | "in" | "opening" | "out", number | null>;
|
|
90
|
+
export declare function readRows(wb: Workbook, m: Mapping): {
|
|
91
|
+
rows: SourceRow[];
|
|
92
|
+
sheets: {
|
|
93
|
+
sheet: Sheet;
|
|
94
|
+
header: number;
|
|
95
|
+
totals: ReturnType<typeof readTotals>;
|
|
96
|
+
rows: SourceRow[];
|
|
97
|
+
}[];
|
|
98
|
+
errors: string[];
|
|
99
|
+
};
|
|
100
|
+
export declare function runImport(wb: Workbook, m: Mapping, ledger: Ledger | null): ImportResult;
|
|
101
|
+
export {};
|