ownledger 1.2.1 → 2.1.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 +73 -1
- package/CHANGELOG.md +64 -0
- package/README.md +13 -0
- package/assets/apple-touch-icon.png +0 -0
- package/assets/icon-192.png +0 -0
- package/assets/icon-512.png +0 -0
- package/assets/icon-maskable-512.png +0 -0
- package/assets/index.html +15 -18
- package/assets/manifest.webmanifest +1 -1
- package/assets/static/Account-sw3qGLbB.js +1 -0
- package/assets/static/Accounts-DWyzX3qB.js +1 -0
- package/assets/static/Attention-DxV-4qdY.js +1 -0
- package/assets/static/ByCategory-B4P3ikmE.js +1 -0
- package/assets/static/CardDetail-CayBXBm-.js +1 -0
- package/assets/static/Cards-CVuOP8Bt.js +1 -0
- package/assets/static/Cards-XUBdWxyo.js +1 -0
- package/assets/static/CardsValue-EoW2jG_0.js +1 -0
- package/assets/static/Cashback-BibVYHf_.js +1 -0
- package/assets/static/CategoryIcon-HfjYhH1l.js +1 -0
- package/assets/static/CategoryPicker-BkmvzX2I.js +1 -0
- package/assets/static/ChartWidget-u09-whUU.js +1 -0
- package/assets/static/Combobox-xXeyjGgK.js +1 -0
- package/assets/static/Deposits-CLAda4dj.js +1 -0
- package/assets/static/DrillLink-Bvfam9FA.js +1 -0
- package/assets/static/Field-tKFmKDEF.js +1 -0
- package/assets/static/HomeEditor-4vxj5LMD.js +1 -0
- package/assets/static/Import-DwaaFpRJ.js +2 -0
- package/assets/static/IncomeSpending-RVDSxAK4.js +1 -0
- package/assets/static/KV-DMA1AlP-.js +1 -0
- package/assets/static/Left-C_4gTGSX.js +1 -0
- package/assets/static/Money-PfFNNDOw.js +1 -0
- package/assets/static/NetWorth-BSoseczC.js +1 -0
- package/assets/static/Pace-B8p-9174.js +1 -0
- package/assets/static/Panel-BnfWrw9R.js +1 -0
- package/assets/static/PinDialog-BqAU9Vh4.js +1 -0
- package/assets/static/Plans-2KuQH2_I.js +1 -0
- package/assets/static/Recent-Ccmb34bq.js +1 -0
- package/assets/static/Reports-Dd-dhclr.js +1 -0
- package/assets/static/Settings-BR8WBlen.js +1 -0
- package/assets/static/Transactions-BAuQ-6Eb.js +1 -0
- package/assets/static/TxRow-EKIIMQKa.js +1 -0
- package/assets/static/Unusual-CwFp8aA5.js +1 -0
- package/assets/static/Upcoming-B28roT9r.js +1 -0
- package/assets/static/WhichCard-B3kLc842.js +1 -0
- package/assets/static/arrow-up-D3gxUKLo.js +1 -0
- package/assets/static/bits-Dr2E0ObC.js +1 -0
- package/assets/static/button-rfwMVz0i.js +1 -0
- package/assets/static/cards-Bb5zjzRG.js +1 -0
- package/assets/static/charts-BqP7HKwP.js +65 -0
- package/assets/static/chevron-down-Co1w7ApZ.js +1 -0
- package/assets/static/chevron-right-Dqh3vs9Y.js +1 -0
- package/assets/static/createLucideIcon-flJrJK2p.js +1 -0
- package/assets/static/dialog-BuRqO4sc.js +1 -0
- package/assets/static/dist-B4_eGtNj.js +1 -0
- package/assets/static/dist-B7PR2b0C.js +1 -0
- package/assets/static/dist-BDn7ydjn.js +1 -0
- package/assets/static/dist-Dl-m8cc2.js +1 -0
- package/assets/static/drill-t1zr57xi.js +1 -0
- package/assets/static/es2015-DJh4h8NX.js +41 -0
- package/assets/static/fold-CGWYt9Iu.js +1 -0
- package/assets/static/index-eR1GkdC_.js +14 -0
- package/assets/static/index-iYMxgw-7.css +1 -0
- package/assets/static/queries-DZIMMe4i.js +1 -0
- package/assets/static/react-dom-wK_7mEjs.js +1 -0
- package/assets/static/select-eaSi9K-d.js +1 -0
- package/assets/static/shared-Box7on3B.js +1 -0
- package/assets/static/triangle-exclamation-point-CuL0XSJl.js +1 -0
- package/assets/static/useMutation-_Lw8xXWa.js +1 -0
- package/dist/cli/cards.d.ts +2 -0
- package/dist/cli/cards.js +86 -0
- package/dist/cli/check.js +7 -1
- package/dist/cli/dev.js +22 -2
- package/dist/cli/import.js +12 -2
- package/dist/cli/index.js +6 -0
- package/dist/cli/statements.d.ts +1 -0
- package/dist/cli/statements.js +231 -0
- package/dist/engine/actions.d.ts +5 -0
- package/dist/engine/actions.js +9 -5
- package/dist/engine/attention.d.ts +15 -0
- package/dist/engine/attention.js +63 -0
- package/dist/engine/check.js +8 -1
- package/dist/engine/dashboard.d.ts +72 -0
- package/dist/engine/dashboard.js +180 -0
- package/dist/engine/features.d.ts +20 -0
- package/dist/engine/features.js +37 -0
- package/dist/engine/index.d.ts +5 -0
- package/dist/engine/index.js +5 -0
- package/dist/engine/insights.d.ts +164 -0
- package/dist/engine/insights.js +534 -0
- package/dist/engine/load.js +6 -0
- package/dist/engine/registry.d.ts +2 -0
- package/dist/engine/registry.js +15 -33
- package/dist/engine/reports.d.ts +21 -2
- package/dist/engine/reports.js +51 -3
- package/dist/engine/schedules.d.ts +7 -84
- package/dist/engine/schedules.js +8 -207
- package/dist/engine/types.d.ts +2 -0
- package/dist/engine/write.d.ts +9 -0
- package/dist/engine/write.js +26 -5
- package/dist/import/mapping.js +6 -0
- package/dist/import/run.d.ts +7 -0
- package/dist/import/run.js +28 -1
- package/dist/modules/api.d.ts +22 -0
- package/dist/modules/api.js +16 -0
- package/dist/modules/cards/api.d.ts +3 -0
- package/dist/modules/cards/api.js +105 -0
- package/dist/modules/cards/engine.d.ts +42 -0
- package/dist/modules/cards/engine.js +102 -0
- package/dist/modules/cards/files.d.ts +11 -0
- package/dist/modules/cards/files.js +17 -0
- package/dist/modules/cards/index.d.ts +26 -0
- package/dist/modules/cards/index.js +304 -0
- package/dist/modules/cards/statements.d.ts +128 -0
- package/dist/modules/cards/statements.js +426 -0
- package/dist/modules/cards/terms.d.ts +105 -0
- package/dist/modules/cards/terms.js +194 -0
- package/dist/modules/cards/tracker.d.ts +36 -0
- package/dist/modules/cards/tracker.js +232 -0
- package/dist/modules/cards/types.d.ts +2 -0
- package/dist/modules/cards/types.js +16 -0
- package/dist/modules/deposits/engine.d.ts +14 -0
- package/dist/modules/deposits/engine.js +32 -0
- package/dist/modules/deposits/index.d.ts +2 -0
- package/dist/modules/deposits/index.js +24 -0
- package/dist/modules/deposits/types.d.ts +2 -0
- package/dist/modules/deposits/types.js +15 -0
- package/dist/modules/index.d.ts +5 -0
- package/dist/modules/index.js +10 -0
- package/dist/modules/insurance/index.d.ts +3 -0
- package/dist/modules/insurance/index.js +8 -0
- package/dist/modules/insurance/types.d.ts +2 -0
- package/dist/modules/insurance/types.js +3 -0
- package/dist/modules/investments/index.d.ts +2 -0
- package/dist/modules/investments/index.js +24 -0
- package/dist/modules/investments/types.d.ts +2 -0
- package/dist/modules/investments/types.js +7 -0
- package/dist/modules/loans/engine.d.ts +30 -0
- package/dist/modules/loans/engine.js +77 -0
- package/dist/modules/loans/index.d.ts +2 -0
- package/dist/modules/loans/index.js +27 -0
- package/dist/modules/loans/types.d.ts +2 -0
- package/dist/modules/loans/types.js +5 -0
- package/dist/modules/types.d.ts +39 -0
- package/dist/modules/types.js +1 -0
- package/dist/modules/util.d.ts +8 -0
- package/dist/modules/util.js +8 -0
- package/dist/node/scaffold.js +2 -2
- package/dist/node/statements.d.ts +64 -0
- package/dist/node/statements.js +218 -0
- package/dist/worker/api.d.ts +11 -1
- package/dist/worker/api.js +169 -13
- package/dist/worker/bestcard.d.ts +31 -9
- package/dist/worker/bestcard.js +78 -50
- package/dist/worker/github.d.ts +3 -1
- package/dist/worker/github.js +13 -2
- package/dist/worker/mcp.js +209 -30
- package/dist/worker/store.d.ts +2 -0
- package/dist/worker/store.js +7 -2
- package/dist/worker/tar.d.ts +2 -1
- package/dist/worker/tar.js +4 -1
- package/dist/worker/version.d.ts +1 -1
- package/dist/worker/version.js +1 -1
- package/package.json +28 -4
- package/presets/misa.mapping.yaml +7 -0
- package/assets/app.css +0 -61
- package/assets/app.js +0 -369
package/dist/cli/import.js
CHANGED
|
@@ -45,6 +45,16 @@ export function importReport(r, verbose = false) {
|
|
|
45
45
|
}
|
|
46
46
|
if (r.replace.length)
|
|
47
47
|
out.push("", `Derived opening/rounding transactions updated: ${r.replace.length}`);
|
|
48
|
+
if (r.accountUpdates.length) {
|
|
49
|
+
out.push("", `Card terms read from wallet names (your own values are kept), ${r.accountUpdates.length}:`);
|
|
50
|
+
for (const u of r.accountUpdates)
|
|
51
|
+
out.push(` - ${u.id}: ${JSON.stringify(Object.fromEntries(Object.entries(u.set.details).filter(([k]) => k !== "from_name")))}`);
|
|
52
|
+
}
|
|
53
|
+
if (r.nameWarnings.length) {
|
|
54
|
+
out.push("", `! Codes in wallet names that couldn't be read (nothing guessed, ${r.nameWarnings.length}):`);
|
|
55
|
+
for (const w of r.nameWarnings)
|
|
56
|
+
out.push(` - ${w}`);
|
|
57
|
+
}
|
|
48
58
|
if (r.changed.length) {
|
|
49
59
|
out.push("", `! Rows already imported whose content changed in the source (not applied; decide by hand, ${r.changed.length}):`);
|
|
50
60
|
for (const c of r.changed.slice(0, 30))
|
|
@@ -112,7 +122,7 @@ export async function cmdImport(args) {
|
|
|
112
122
|
console.log(importReport(r, args.includes("--verbose")));
|
|
113
123
|
if (!r.ok)
|
|
114
124
|
return 1;
|
|
115
|
-
if (!r.transactions.length && !r.accounts.length && !r.replace.length) {
|
|
125
|
+
if (!r.transactions.length && !r.accounts.length && !r.replace.length && !r.accountUpdates.length) {
|
|
116
126
|
console.log("Nothing new to import.");
|
|
117
127
|
return 0;
|
|
118
128
|
}
|
|
@@ -121,7 +131,7 @@ export async function cmdImport(args) {
|
|
|
121
131
|
return 0;
|
|
122
132
|
}
|
|
123
133
|
// write: build the new files in memory, check them, then write and commit
|
|
124
|
-
const change = applyChange(files, { addAccounts: r.accounts, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
134
|
+
const change = applyChange(files, { addAccounts: r.accounts, updateAccounts: r.accountUpdates, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
125
135
|
const result = checkFiles({ ...files, ...change });
|
|
126
136
|
if (!result.ok) {
|
|
127
137
|
console.log("\n✗ The data would not pass check after this import; nothing written:");
|
package/dist/cli/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { pkgVersion } from "../node/scaffold.js";
|
|
3
|
+
import { cmdCards } from "./cards.js";
|
|
3
4
|
import { cmdCheck } from "./check.js";
|
|
4
5
|
import { cmdDeploy } from "./deploy.js";
|
|
5
6
|
import { cmdDev } from "./dev.js";
|
|
6
7
|
import { cmdImport } from "./import.js";
|
|
7
8
|
import { cmdInit } from "./init.js";
|
|
9
|
+
import { cmdStatements } from "./statements.js";
|
|
8
10
|
const pkg = { version: pkgVersion() };
|
|
9
11
|
const HELP = `ownledger ${pkg.version}
|
|
10
12
|
|
|
@@ -13,8 +15,10 @@ Usage: ownledger <command> [options]
|
|
|
13
15
|
init [name] Create a data repo (asks base currency, category language; private GitHub repo via gh)
|
|
14
16
|
check [dir] Check the data repo (default: current folder)
|
|
15
17
|
import <file> Import an export (profile first; preview; --yes writes, checks and commits)
|
|
18
|
+
cards load <csv> Load a card tracker (CSV) into data/cards.yaml and the cards' limits (preview; --yes writes)
|
|
16
19
|
deploy Deploy your Worker to your Cloudflare (GitHub App, secrets, KV); prints the connector URL
|
|
17
20
|
--openwallet[=<url>] turns on the OpenWallet card catalog (best_card), --no-openwallet off
|
|
21
|
+
statements add|list|check Bank statement PDFs in imports/statements/ (unlock and file, list months, compare with the ledger)
|
|
18
22
|
dev [dir] Run your Worker locally against the local data/ (fake sign-in); --openwallet[=<url>] as above
|
|
19
23
|
--version Print the version
|
|
20
24
|
`;
|
|
@@ -22,6 +26,8 @@ const commands = {
|
|
|
22
26
|
init: cmdInit,
|
|
23
27
|
check: cmdCheck,
|
|
24
28
|
import: cmdImport,
|
|
29
|
+
cards: cmdCards,
|
|
30
|
+
statements: cmdStatements,
|
|
25
31
|
dev: cmdDev,
|
|
26
32
|
deploy: cmdDeploy,
|
|
27
33
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdStatements(args: string[]): Promise<number>;
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { todayIn } from "../engine/dates.js";
|
|
5
|
+
import { loadLedger } from "../engine/load.js";
|
|
6
|
+
import { statements } from "../modules/cards/statements.js";
|
|
7
|
+
import { recordFor, termsOf } from "../modules/cards/terms.js";
|
|
8
|
+
import { readDataDir } from "../node/files.js";
|
|
9
|
+
import { ENV_FILE, missingMonths, monthFromText, passwordVars, PdfPasswordError, pdfText, readEnvFile, readSources, scanStatements, STATEMENTS_DIR, unlockPdf, } from "../node/statements.js";
|
|
10
|
+
const USAGE = `Usage:
|
|
11
|
+
ownledger statements add <account-id> <file.pdf>... [--month YYYY-MM] [--dir <repo>] [--yes] [--no-commit]
|
|
12
|
+
Unlock (password from ${ENV_FILE}) and file the bank's statement PDFs as ${STATEMENTS_DIR}/<account-id>/<YYYY-MM>.pdf.
|
|
13
|
+
YYYY-MM is the month of the statement's close date, read from the PDF unless --month is given. Preview unless --yes.
|
|
14
|
+
ownledger statements list [<account-id>] [--dir <repo>]
|
|
15
|
+
Which months each card has, and which are missing between the first and the last.
|
|
16
|
+
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.`;
|
|
18
|
+
function opt(args, name) {
|
|
19
|
+
const i = args.indexOf(name);
|
|
20
|
+
return i >= 0 ? args[i + 1] : args.find((a) => a.startsWith(name + "="))?.slice(name.length + 1);
|
|
21
|
+
}
|
|
22
|
+
const positional = (args) => args.filter((a, i) => !a.startsWith("-") && !["--month", "--dir"].includes(args[i - 1] ?? ""));
|
|
23
|
+
function ledgerAt(root) {
|
|
24
|
+
return loadLedger(readDataDir(root)).ledger;
|
|
25
|
+
}
|
|
26
|
+
function statementDayOf(l, id) {
|
|
27
|
+
const a = l.accounts.find((x) => x.id === id);
|
|
28
|
+
return a ? termsOf(a, recordFor(l, id)).statementDay : null;
|
|
29
|
+
}
|
|
30
|
+
const fmt = (n) => Math.round(n).toLocaleString("en-US");
|
|
31
|
+
export async function cmdStatements(args) {
|
|
32
|
+
const [sub, ...rest] = args;
|
|
33
|
+
const root = resolve(opt(rest, "--dir") ?? ".");
|
|
34
|
+
if (sub === "add")
|
|
35
|
+
return add(root, rest);
|
|
36
|
+
if (sub === "list")
|
|
37
|
+
return list(root, positional(rest)[0]);
|
|
38
|
+
if (sub === "check")
|
|
39
|
+
return check(root, rest);
|
|
40
|
+
console.log(USAGE);
|
|
41
|
+
return 2;
|
|
42
|
+
}
|
|
43
|
+
async function add(root, args) {
|
|
44
|
+
const [account, ...files] = positional(args);
|
|
45
|
+
if (!account || !files.length) {
|
|
46
|
+
console.log(USAGE);
|
|
47
|
+
return 2;
|
|
48
|
+
}
|
|
49
|
+
const month = opt(args, "--month");
|
|
50
|
+
if (month && !/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) {
|
|
51
|
+
console.error(`--month must be YYYY-MM (got "${month}")`);
|
|
52
|
+
return 2;
|
|
53
|
+
}
|
|
54
|
+
if (month && files.length > 1) {
|
|
55
|
+
console.error("--month goes with one file at a time");
|
|
56
|
+
return 2;
|
|
57
|
+
}
|
|
58
|
+
const l = ledgerAt(root);
|
|
59
|
+
if (!l.accounts.some((a) => a.id === account)) {
|
|
60
|
+
console.error(`No account "${account}" in data/accounts.yaml.`);
|
|
61
|
+
return 1;
|
|
62
|
+
}
|
|
63
|
+
const sd = statementDayOf(l, account);
|
|
64
|
+
const sources = readSources(root);
|
|
65
|
+
const env = readEnvFile(root);
|
|
66
|
+
const vars = passwordVars(account, sources[account]);
|
|
67
|
+
const password = vars.map((v) => env[v]).find((v) => v);
|
|
68
|
+
const planned = [];
|
|
69
|
+
for (const file of files) {
|
|
70
|
+
const p = { file, month: month ?? null, status: "error", note: "" };
|
|
71
|
+
planned.push(p);
|
|
72
|
+
let unlocked;
|
|
73
|
+
try {
|
|
74
|
+
unlocked = (await unlockPdf(new Uint8Array(readFileSync(file)), password)).bytes;
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
if (e instanceof PdfPasswordError) {
|
|
78
|
+
const hint = sources[account]?.password_hint;
|
|
79
|
+
p.note = password
|
|
80
|
+
? `wrong password (from ${vars.find((v) => env[v])} in ${ENV_FILE})`
|
|
81
|
+
: `needs a password: set ${vars.join(" or ")} in ${ENV_FILE}${hint ? ` (${hint})` : ""}`;
|
|
82
|
+
}
|
|
83
|
+
else
|
|
84
|
+
p.note = e instanceof Error ? e.message : String(e);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (!month) {
|
|
88
|
+
const g = monthFromText(await pdfText(unlocked), sd);
|
|
89
|
+
if (!g.month) {
|
|
90
|
+
p.note = `can't tell the month (${g.why}): pass --month YYYY-MM`;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
p.month = g.month;
|
|
94
|
+
p.period = `${g.from} … ${g.close}`;
|
|
95
|
+
}
|
|
96
|
+
if (planned.some((o) => o !== p && o.month === p.month && o.status !== "error")) {
|
|
97
|
+
p.note = `another file in this run is also ${p.month}`;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const target = join(root, STATEMENTS_DIR, account, `${p.month}.pdf`);
|
|
101
|
+
if (existsSync(target)) {
|
|
102
|
+
// same bytes, or the same text (a copy unlocked by another tool differs in bytes only)
|
|
103
|
+
const had = readFileSync(target);
|
|
104
|
+
const same = Buffer.compare(had, Buffer.from(unlocked)) === 0 || (await pdfText(new Uint8Array(had)).catch(() => null)) === (await pdfText(unlocked));
|
|
105
|
+
p.status = same ? "same" : "different";
|
|
106
|
+
p.note = same ? "already filed" : `a different file is already filed for ${p.month}: delete it first if this one replaces it`;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
p.status = "new";
|
|
110
|
+
p.bytes = unlocked;
|
|
111
|
+
}
|
|
112
|
+
console.log(`Statements for ${account}:\n`);
|
|
113
|
+
console.log("| file | month | period | |\n|---|---|---|---|");
|
|
114
|
+
for (const p of planned)
|
|
115
|
+
console.log(`| ${basename(p.file)} | ${p.month ?? "?"} | ${p.period ?? ""} | ${p.status === "new" ? "✓ new" : p.status === "same" ? "= " + p.note : "✗ " + p.note} |`);
|
|
116
|
+
const news = planned.filter((p) => p.status === "new");
|
|
117
|
+
const failed = planned.some((p) => p.status === "error" || p.status === "different");
|
|
118
|
+
if (!news.length) {
|
|
119
|
+
console.log("\nNothing to file.");
|
|
120
|
+
return failed ? 1 : 0;
|
|
121
|
+
}
|
|
122
|
+
if (!args.includes("--yes")) {
|
|
123
|
+
console.log(`\nPreview only: nothing written. Run again with --yes to file ${news.length} statement(s)${existsSync(join(root, ".git")) ? " and commit" : ""}.`);
|
|
124
|
+
return failed ? 1 : 0;
|
|
125
|
+
}
|
|
126
|
+
const paths = [];
|
|
127
|
+
for (const p of news) {
|
|
128
|
+
const rel = `${STATEMENTS_DIR}/${account}/${p.month}.pdf`;
|
|
129
|
+
mkdirSync(dirname(join(root, rel)), { recursive: true });
|
|
130
|
+
writeFileSync(join(root, rel), p.bytes);
|
|
131
|
+
paths.push(rel);
|
|
132
|
+
}
|
|
133
|
+
console.log(`\n✓ Filed: ${paths.join(", ")}`);
|
|
134
|
+
if (existsSync(join(root, ".git")) && !args.includes("--no-commit")) {
|
|
135
|
+
const msg = `Statements: ${account} ${news.map((p) => p.month).sort().reverse().join(", ")}`;
|
|
136
|
+
execFileSync("git", ["add", ...paths], { cwd: root });
|
|
137
|
+
execFileSync("git", ["commit", "-q", "-m", msg], { cwd: root, stdio: "inherit" });
|
|
138
|
+
console.log(`✓ Committed: ${msg}`);
|
|
139
|
+
}
|
|
140
|
+
return failed ? 1 : 0;
|
|
141
|
+
}
|
|
142
|
+
/* ------------------------------------------------------------------ list */
|
|
143
|
+
async function list(root, only) {
|
|
144
|
+
const l = ledgerAt(root);
|
|
145
|
+
const { files, warnings } = scanStatements(root, new Set(l.accounts.map((a) => a.id)));
|
|
146
|
+
const by = new Map();
|
|
147
|
+
for (const f of files)
|
|
148
|
+
if (!only || f.account === only)
|
|
149
|
+
(by.get(f.account) ?? by.set(f.account, []).get(f.account)).push(f.month);
|
|
150
|
+
if (!by.size) {
|
|
151
|
+
console.log(only ? `No statements filed for ${only}.` : `No statements filed (${STATEMENTS_DIR}/<account-id>/<YYYY-MM>.pdf).`);
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
console.log("| account | statements | from | to | missing |\n|---|---|---|---|---|");
|
|
155
|
+
for (const [acc, months] of [...by].sort()) {
|
|
156
|
+
const s = months.sort();
|
|
157
|
+
const miss = missingMonths(s);
|
|
158
|
+
console.log(`| ${acc} | ${s.length} | ${s[0]} | ${s[s.length - 1]} | ${miss.join(", ") || "—"} |`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
for (const w of warnings)
|
|
162
|
+
console.log(`! ${w}`);
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
/* ------------------------------------------------------------------ check */
|
|
166
|
+
async function check(root, args) {
|
|
167
|
+
const [account, month] = positional(args);
|
|
168
|
+
if (!account || !month || !/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) {
|
|
169
|
+
console.log(USAGE);
|
|
170
|
+
return 2;
|
|
171
|
+
}
|
|
172
|
+
const rel = `${STATEMENTS_DIR}/${account}/${month}.pdf`;
|
|
173
|
+
if (!existsSync(join(root, rel))) {
|
|
174
|
+
console.error(`No statement filed at ${rel}.`);
|
|
175
|
+
return 1;
|
|
176
|
+
}
|
|
177
|
+
const l = ledgerAt(root);
|
|
178
|
+
if (!l.accounts.some((a) => a.id === account)) {
|
|
179
|
+
console.error(`No account "${account}" in data/accounts.yaml.`);
|
|
180
|
+
return 1;
|
|
181
|
+
}
|
|
182
|
+
let stmt;
|
|
183
|
+
try {
|
|
184
|
+
stmt = statements(l, account, todayIn()).find((s) => !s.open && s.close.slice(0, 7) === month);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
stmt = undefined;
|
|
188
|
+
}
|
|
189
|
+
const txs = stmt
|
|
190
|
+
? l.transactions
|
|
191
|
+
.filter((t) => !t.void && t.date >= stmt.from && t.date <= stmt.close && t.lines.some((ln) => ln.account === account))
|
|
192
|
+
.sort((a, b) => (a.date + (a.time ?? "")).localeCompare(b.date + (b.time ?? "")))
|
|
193
|
+
.map((t) => {
|
|
194
|
+
const own = t.lines.filter((ln) => ln.account === account);
|
|
195
|
+
const other = t.lines.filter((ln) => ln.account !== account);
|
|
196
|
+
return {
|
|
197
|
+
id: t.id,
|
|
198
|
+
date: t.date,
|
|
199
|
+
amount: own.reduce((s, ln) => s + ln.amount, 0),
|
|
200
|
+
note: [t.note, ...own.map((ln) => ln.note)].filter(Boolean).join(" · "),
|
|
201
|
+
against: other.map((ln) => ln.category ?? ln.account).filter(Boolean).join(", "),
|
|
202
|
+
};
|
|
203
|
+
})
|
|
204
|
+
: [];
|
|
205
|
+
let text;
|
|
206
|
+
try {
|
|
207
|
+
text = await pdfText(new Uint8Array(readFileSync(join(root, rel))));
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
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
|
+
return 1;
|
|
212
|
+
}
|
|
213
|
+
if (args.includes("--json")) {
|
|
214
|
+
console.log(JSON.stringify({ account, month, file: rel, statement: stmt ?? null, transactions: txs, text }, null, 2));
|
|
215
|
+
return 0;
|
|
216
|
+
}
|
|
217
|
+
console.log(`# ${account} statement ${month} (${rel})\n`);
|
|
218
|
+
if (!stmt)
|
|
219
|
+
console.log(`ownledger has no closed statement period for ${account} closing in ${month} (no statement_day, or no transactions then).\n`);
|
|
220
|
+
else {
|
|
221
|
+
console.log(`Period ${stmt.from} … ${stmt.close}${stmt.due ? `, due ${stmt.due}` : ""}. Amounts as owed (positive = you owe).\n`);
|
|
222
|
+
console.log("| opening | purchases | refunds | cashback | fees | charges | payments | adjust | closing | deferred | amount due | bank's amount |\n|---|---|---|---|---|---|---|---|---|---|---|---|");
|
|
223
|
+
console.log(`| ${[stmt.opening, stmt.purchases, stmt.refunds, stmt.cashback, stmt.fees, stmt.charges, stmt.payments, stmt.adjust, stmt.closing, stmt.deferred, stmt.amountDue].map(fmt).join(" | ")} | ${stmt.bank === null ? "—" : fmt(stmt.bank)} |`);
|
|
224
|
+
console.log(`\n## ownledger's transactions on ${account} (${txs.length}; amount on the card: negative = spent, positive = paid/refunded)\n`);
|
|
225
|
+
console.log("| date | amount | note | against | id |\n|---|---|---|---|---|");
|
|
226
|
+
for (const t of txs)
|
|
227
|
+
console.log(`| ${t.date} | ${fmt(t.amount)} | ${t.note.replace(/\|/g, "/")} | ${t.against} | ${t.id} |`);
|
|
228
|
+
}
|
|
229
|
+
console.log(`\n## Statement text (as extracted from the PDF)\n\n${text}`);
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
package/dist/engine/actions.d.ts
CHANGED
|
@@ -44,6 +44,11 @@ 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
|
+
/** The ledger of a set of files, for actions that read it before building a change. */
|
|
48
|
+
export declare function loadForAction(files: FileMap): {
|
|
49
|
+
ledger: import("./types.js").Ledger;
|
|
50
|
+
issues: Issue[];
|
|
51
|
+
};
|
|
47
52
|
export declare function addAccount(files: FileMap, a: Account): Planned;
|
|
48
53
|
export declare function editAccount(files: FileMap, id: string, set: Record<string, unknown>): Planned;
|
|
49
54
|
export declare function addPlan(files: FileMap, p: Plan): Planned;
|
package/dist/engine/actions.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { parse as parseYaml
|
|
1
|
+
import { parse as parseYaml } from "yaml";
|
|
2
2
|
import { checkFiles } from "./check.js";
|
|
3
3
|
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
|
-
import { applyChange, describeChange } from "./write.js";
|
|
6
|
+
import { applyChange, describeChange, yamlText } from "./write.js";
|
|
7
7
|
export class ActionError extends Error {
|
|
8
8
|
}
|
|
9
9
|
function newId(prefix = "t_") {
|
|
@@ -128,6 +128,10 @@ export function voidTransaction(files, id, reason, meta) {
|
|
|
128
128
|
const next = { ...old, void: true, ...(reason ? { void_reason: reason } : {}) };
|
|
129
129
|
return plan(files, { replaceTransactions: [trailed(next, "void", meta)] }, withMeta(`Void: ${old.date} ${old.note ?? ""}`.trim(), meta));
|
|
130
130
|
}
|
|
131
|
+
/** The ledger of a set of files, for actions that read it before building a change. */
|
|
132
|
+
export function loadForAction(files) {
|
|
133
|
+
return loadLedger(files);
|
|
134
|
+
}
|
|
131
135
|
/* ------------------------------------------------------------------ accounts, plans, prices */
|
|
132
136
|
export function addAccount(files, a) {
|
|
133
137
|
return plan(files, { addAccounts: [a] }, `Add account: ${a.name} (${a.type})`);
|
|
@@ -181,7 +185,7 @@ export function addCategory(files, c) {
|
|
|
181
185
|
if (list.some((x) => x.id === c.id))
|
|
182
186
|
throw new ActionError(`category ${c.parent ? c.parent + "/" : ""}${c.id} exists`);
|
|
183
187
|
list.push({ id: c.id, name: c.name });
|
|
184
|
-
return plan(files, { putFiles: { [PATHS.categories]:
|
|
188
|
+
return plan(files, { putFiles: { [PATHS.categories]: yamlText(cats) } }, `Add category: ${c.parent ? c.parent + "/" : ""}${c.id}`);
|
|
185
189
|
}
|
|
186
190
|
/** Rename a category (name), or move/rename its path and remap every line that uses it (or its children). */
|
|
187
191
|
export function editCategory(files, path, set) {
|
|
@@ -219,9 +223,9 @@ export function editCategory(files, path, set) {
|
|
|
219
223
|
change.replaceTransactions = replace;
|
|
220
224
|
const budgets = parseYaml(files[PATHS.budgets] ?? "[]");
|
|
221
225
|
if (budgets?.some((b) => remap(b.category) !== b.category)) {
|
|
222
|
-
change.putFiles = { [PATHS.budgets]:
|
|
226
|
+
change.putFiles = { [PATHS.budgets]: yamlText(budgets.map((b) => ({ ...b, category: remap(b.category) }))) };
|
|
223
227
|
}
|
|
224
228
|
}
|
|
225
|
-
change.putFiles = { ...(change.putFiles ?? {}), [PATHS.categories]:
|
|
229
|
+
change.putFiles = { ...(change.putFiles ?? {}), [PATHS.categories]: yamlText(cats) };
|
|
226
230
|
return plan(files, change, set.new_path ? `Move category: ${path} → ${set.new_path}` : `Rename category: ${path}`);
|
|
227
231
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { FileMap } from "./load.js";
|
|
2
|
+
import type { ISODate, Ledger } from "./types.js";
|
|
3
|
+
import { type AttentionItem } from "../modules/index.js";
|
|
4
|
+
export type { AttentionItem };
|
|
5
|
+
/**
|
|
6
|
+
* "Needs you": what's due (from the modules that are on), then housekeeping. Sorted: red, amber, info;
|
|
7
|
+
* within each, by date. Money items come before housekeeping at the same severity.
|
|
8
|
+
*/
|
|
9
|
+
export declare function attention(l: Ledger, asOf: ISODate, o?: {
|
|
10
|
+
files?: FileMap;
|
|
11
|
+
check?: {
|
|
12
|
+
errors: number;
|
|
13
|
+
warnings: number;
|
|
14
|
+
};
|
|
15
|
+
}): AttentionItem[];
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { holdingsAt } from "./balances.js";
|
|
2
|
+
import { isSystemCategory } from "./categories.js";
|
|
3
|
+
import { addMonths, monthStart } from "./dates.js";
|
|
4
|
+
import { UNCATEGORISED } from "./insights.js";
|
|
5
|
+
import { typeDef } from "./registry.js";
|
|
6
|
+
import { budgets } from "./schedules.js";
|
|
7
|
+
import { MODULES } from "../modules/index.js";
|
|
8
|
+
const RANK = { red: 0, amber: 1, info: 2 };
|
|
9
|
+
/**
|
|
10
|
+
* "Needs you": what's due (from the modules that are on), then housekeeping. Sorted: red, amber, info;
|
|
11
|
+
* within each, by date. Money items come before housekeeping at the same severity.
|
|
12
|
+
*/
|
|
13
|
+
export function attention(l, asOf, o = {}) {
|
|
14
|
+
const files = o.files ?? {};
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const m of MODULES)
|
|
17
|
+
if (m.attention && m.on(l, asOf, files))
|
|
18
|
+
out.push(...m.attention(l, asOf, files));
|
|
19
|
+
for (const b of budgets(l, asOf).filter((x) => x.over)) {
|
|
20
|
+
out.push({ kind: "over_budget", severity: "amber", date: asOf, title: `Over budget: ${b.category} (${b.spent} of ${b.amount})`, amount: b.spent - b.amount, params: { category: b.category, budget: b.amount, spent: b.spent }, link: `#/transactions?category=${encodeURIComponent(b.category)}` });
|
|
21
|
+
}
|
|
22
|
+
// housekeeping
|
|
23
|
+
const from = addMonths(monthStart(asOf), -1);
|
|
24
|
+
let uncat = 0;
|
|
25
|
+
for (const t of l.transactions) {
|
|
26
|
+
if (t.void || t.date < from)
|
|
27
|
+
continue;
|
|
28
|
+
if (t.date > asOf)
|
|
29
|
+
break;
|
|
30
|
+
if (t.lines.some((ln) => ln.category && !isSystemCategory(ln.category) && UNCATEGORISED.has(ln.category.split("/")[0])))
|
|
31
|
+
uncat++;
|
|
32
|
+
}
|
|
33
|
+
if (uncat)
|
|
34
|
+
out.push({ kind: "uncategorised", severity: "info", date: asOf, title: `${uncat} transaction(s) since ${from} have no real category (other)`, count: uncat, params: { from }, link: `#/transactions?category=other&from=${from}`, ask: true });
|
|
35
|
+
const hs = holdingsAt(l, asOf);
|
|
36
|
+
const unmatched = new Set(["import-unmatched"]);
|
|
37
|
+
for (const [p, text] of Object.entries(files)) {
|
|
38
|
+
if (!/^imports\/[^/]+\.mapping\.yaml$/.test(p))
|
|
39
|
+
continue;
|
|
40
|
+
const m = /^unmatched_account:\s*["']?([A-Za-z0-9._-]+)/m.exec(text);
|
|
41
|
+
if (m)
|
|
42
|
+
unmatched.add(m[1]);
|
|
43
|
+
}
|
|
44
|
+
for (const a of l.accounts) {
|
|
45
|
+
if (a.closed && a.closed <= asOf)
|
|
46
|
+
continue;
|
|
47
|
+
const v = hs.get(a.id)?.amount ?? 0;
|
|
48
|
+
if (unmatched.has(a.id)) {
|
|
49
|
+
if (v !== 0)
|
|
50
|
+
out.push({ kind: "unmatched", severity: "info", date: asOf, title: `Transfers without their other side: ${a.name} holds ${v} (should be 0)`, amount: v, account: a.id, name: a.name, link: `#/transactions?account=${encodeURIComponent(a.id)}`, ask: true });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const def = typeDef(a.type);
|
|
54
|
+
if (v < 0 && def && !def.liability && !def.holdings)
|
|
55
|
+
out.push({ kind: "negative", severity: "info", date: asOf, title: `${a.name} (${a.id}) is negative: ${v}`, amount: v, account: a.id, name: a.name, link: `#/transactions?account=${encodeURIComponent(a.id)}`, ask: true });
|
|
56
|
+
}
|
|
57
|
+
if (o.check?.errors)
|
|
58
|
+
out.push({ kind: "check_errors", severity: "red", date: asOf, title: `ownledger check: ${o.check.errors} error(s)`, count: o.check.errors, link: "#/settings", ask: true });
|
|
59
|
+
if (o.check?.warnings)
|
|
60
|
+
out.push({ kind: "check_warnings", severity: "info", date: asOf, title: `ownledger check: ${o.check.warnings} warning(s)`, count: o.check.warnings, link: "#/settings", ask: true });
|
|
61
|
+
const house = (k) => ["uncategorised", "unmatched", "negative", "check_warnings", "unpriced"].includes(k);
|
|
62
|
+
return out.sort((a, b) => RANK[a.severity] - RANK[b.severity] || Number(house(a.kind)) - Number(house(b.kind)) || (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
|
|
63
|
+
}
|
package/dist/engine/check.js
CHANGED
|
@@ -3,12 +3,19 @@ import { isDate } from "./dates.js";
|
|
|
3
3
|
import { ledgerPath, loadLedger, PATHS } from "./load.js";
|
|
4
4
|
import { typeDef } from "./registry.js";
|
|
5
5
|
import { FORMAT } from "./types.js";
|
|
6
|
+
import { checkDashboards } from "./dashboard.js";
|
|
7
|
+
import { todayIn } from "./dates.js";
|
|
8
|
+
import { MODULES } from "../modules/index.js";
|
|
6
9
|
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
7
10
|
const EVERY = new Set(["month", "quarter", "year"]);
|
|
8
11
|
/** Load + check. `ok` is false when there is any error. Warnings never fail. */
|
|
9
12
|
export function checkFiles(files) {
|
|
10
13
|
const { ledger, issues } = loadLedger(files);
|
|
11
|
-
const
|
|
14
|
+
const asOf = todayIn();
|
|
15
|
+
const all = [...issues, ...checkLedger(ledger), ...checkDashboards(files, ledger)];
|
|
16
|
+
for (const m of MODULES)
|
|
17
|
+
if (m.check && m.on(ledger, asOf, files))
|
|
18
|
+
all.push(...m.check(ledger, files));
|
|
12
19
|
const errors = all.filter((i) => i.level === "error");
|
|
13
20
|
const warnings = all.filter((i) => i.level === "warning");
|
|
14
21
|
return { ok: errors.length === 0, errors, warnings, ledger };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type SeriesQuery } from "./insights.js";
|
|
2
|
+
import type { Issue, Ledger } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* A person's dashboard: data/dashboards/<login>.yaml in the data repo. Widgets on a 12-column grid,
|
|
5
|
+
* and personal preferences (the "My money" pool). One file per GitHub login; no file = the defaults.
|
|
6
|
+
*/
|
|
7
|
+
export declare const GRID_COLS = 12;
|
|
8
|
+
export declare const DASHBOARD_DIR = "data/dashboards/";
|
|
9
|
+
export declare const dashboardPath: (login: string) => string;
|
|
10
|
+
/** Built-in widget types and the module they need (none = core). */
|
|
11
|
+
export declare const WIDGET_TYPES: Record<string, {
|
|
12
|
+
module?: string;
|
|
13
|
+
options?: string[];
|
|
14
|
+
}>;
|
|
15
|
+
export declare const CHART_KINDS: readonly ["stat", "line", "bar", "hbar", "table"];
|
|
16
|
+
export interface Widget {
|
|
17
|
+
id: string;
|
|
18
|
+
type: string;
|
|
19
|
+
x: number;
|
|
20
|
+
y: number;
|
|
21
|
+
w: number;
|
|
22
|
+
h: number;
|
|
23
|
+
title?: string;
|
|
24
|
+
query?: SeriesQuery;
|
|
25
|
+
chart?: (typeof CHART_KINDS)[number];
|
|
26
|
+
/** Options of built-in widgets (period, account, count, months). */
|
|
27
|
+
period?: string;
|
|
28
|
+
account?: string;
|
|
29
|
+
count?: number;
|
|
30
|
+
months?: number;
|
|
31
|
+
/** Added by the AI through the connector (the dashboard marks it). */
|
|
32
|
+
by_ai?: boolean;
|
|
33
|
+
[k: string]: unknown;
|
|
34
|
+
}
|
|
35
|
+
export interface PoolPrefs {
|
|
36
|
+
/** Group everyday accounts (cash, bank, e-wallet) into one balance. Default on. */
|
|
37
|
+
on?: boolean;
|
|
38
|
+
/** Its name (default "Tiền của tôi" / "My money", translated by the dashboard). */
|
|
39
|
+
name?: string;
|
|
40
|
+
/** Liquid accounts kept out of the pool (all liquid accounts are in it by default, new ones too). */
|
|
41
|
+
exclude?: string[];
|
|
42
|
+
/** Where everyday spending goes when no account is named. */
|
|
43
|
+
default_account?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface Dashboard {
|
|
46
|
+
version: 1;
|
|
47
|
+
widgets?: Widget[];
|
|
48
|
+
prefs?: {
|
|
49
|
+
pool?: PoolPrefs;
|
|
50
|
+
[k: string]: unknown;
|
|
51
|
+
};
|
|
52
|
+
[k: string]: unknown;
|
|
53
|
+
}
|
|
54
|
+
/** The default Home: what fits the ledger (features), four widgets. */
|
|
55
|
+
export declare function defaultWidgets(f: {
|
|
56
|
+
historyMonths: number;
|
|
57
|
+
empty: boolean;
|
|
58
|
+
}): Widget[];
|
|
59
|
+
export declare function parseDashboard(text: string | undefined): Dashboard | null;
|
|
60
|
+
export declare function writeDashboard(d: Dashboard): string;
|
|
61
|
+
/** Issues in one dashboard file. Errors make PUT /api/dashboard refuse it; unknown categories/accounts are warnings. */
|
|
62
|
+
export declare function checkDashboard(file: string, d: unknown, l: Ledger): Issue[];
|
|
63
|
+
/** Every dashboard file in the repo, checked. */
|
|
64
|
+
export declare function checkDashboards(files: Record<string, string>, l: Ledger): Issue[];
|
|
65
|
+
export interface Pool {
|
|
66
|
+
on: boolean;
|
|
67
|
+
name: string | null;
|
|
68
|
+
accounts: string[];
|
|
69
|
+
default_account: string | null;
|
|
70
|
+
}
|
|
71
|
+
/** The pool for a person's prefs: a view over the accounts, never a change to them. */
|
|
72
|
+
export declare function poolOf(l: Ledger, prefs: PoolPrefs | undefined, asOf: string): Pool;
|