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
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const INVESTMENT_TYPES = {
|
|
2
|
+
gold: { label: { en: "Gold", vi: "Vàng" }, holdings: true },
|
|
3
|
+
fund: { label: { en: "Fund", vi: "Chứng chỉ quỹ" }, holdings: true, details: { broker: { kind: "string" } } },
|
|
4
|
+
stock: { label: { en: "Stocks", vi: "Cổ phiếu" }, holdings: true, details: { broker: { kind: "string" } } },
|
|
5
|
+
etf: { label: { en: "ETF", vi: "Quỹ ETF" }, holdings: true, details: { broker: { kind: "string" } } },
|
|
6
|
+
crypto: { label: { en: "Crypto", vi: "Tiền mã hoá" }, holdings: true },
|
|
7
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ISODate, Ledger, Plan } from "../../engine/types.js";
|
|
2
|
+
export interface PlanStatus {
|
|
3
|
+
plan: string;
|
|
4
|
+
name: string;
|
|
5
|
+
kind: string;
|
|
6
|
+
account: string;
|
|
7
|
+
perPayment: number;
|
|
8
|
+
count: number | null;
|
|
9
|
+
paidCount: number;
|
|
10
|
+
paidAmount: number;
|
|
11
|
+
left: number | null;
|
|
12
|
+
leftAmount: number | null;
|
|
13
|
+
next: ISODate | null;
|
|
14
|
+
overdue: ISODate[];
|
|
15
|
+
finished: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function perPayment(p: Plan): number;
|
|
18
|
+
/** Due dates of a plan, the first `n` (or until `until`). */
|
|
19
|
+
export declare function dueDates(p: Plan, until: ISODate, max?: number): ISODate[];
|
|
20
|
+
export declare function planStatus(l: Ledger, asOf: ISODate): PlanStatus[];
|
|
21
|
+
export interface DueItem {
|
|
22
|
+
plan: string;
|
|
23
|
+
name: string;
|
|
24
|
+
account: string;
|
|
25
|
+
date: ISODate;
|
|
26
|
+
amount: number;
|
|
27
|
+
overdue: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** Plan payments due from (earliest unpaid) through asOf + days. */
|
|
30
|
+
export declare function plansDue(l: Ledger, asOf: ISODate, days?: number): DueItem[];
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { addDays, addMonths, parts } from "../../engine/dates.js";
|
|
2
|
+
const STEP = { month: 1, quarter: 3, year: 12 };
|
|
3
|
+
export function perPayment(p) {
|
|
4
|
+
if (p.amount !== undefined)
|
|
5
|
+
return p.amount + (p.fee ?? 0);
|
|
6
|
+
if (p.principal !== undefined && p.count)
|
|
7
|
+
return Math.round(p.principal / p.count) + (p.fee ?? 0);
|
|
8
|
+
return 0;
|
|
9
|
+
}
|
|
10
|
+
/** Due dates of a plan, the first `n` (or until `until`). */
|
|
11
|
+
export function dueDates(p, until, max = 1000) {
|
|
12
|
+
const out = [];
|
|
13
|
+
const step = STEP[p.every] ?? 1;
|
|
14
|
+
const d0 = parts(p.start)[2];
|
|
15
|
+
for (let i = 0; i < max; i++) {
|
|
16
|
+
if (p.count !== undefined && i >= p.count)
|
|
17
|
+
break;
|
|
18
|
+
const d = addMonths(p.start, i * step, d0);
|
|
19
|
+
if (d > until)
|
|
20
|
+
break;
|
|
21
|
+
if (p.end && d > p.end)
|
|
22
|
+
break;
|
|
23
|
+
out.push(d);
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
export function planStatus(l, asOf) {
|
|
28
|
+
const paid = new Map();
|
|
29
|
+
const accOf = new Map(l.plans.map((p) => [p.id, p.account]));
|
|
30
|
+
for (const t of l.transactions) {
|
|
31
|
+
if (t.void || !t.plan)
|
|
32
|
+
continue;
|
|
33
|
+
const acc = accOf.get(t.plan);
|
|
34
|
+
const s = paid.get(t.plan) ?? { n: 0, amount: 0 };
|
|
35
|
+
s.n++;
|
|
36
|
+
s.amount += t.lines.filter((ln) => ln.account === acc).reduce((x, ln) => x + Math.abs(ln.amount), 0);
|
|
37
|
+
paid.set(t.plan, s);
|
|
38
|
+
}
|
|
39
|
+
return l.plans.map((p) => {
|
|
40
|
+
const per = perPayment(p);
|
|
41
|
+
const s = paid.get(p.id) ?? { n: 0, amount: 0 };
|
|
42
|
+
const horizon = addDays(asOf, 3660);
|
|
43
|
+
const all = dueDates(p, horizon);
|
|
44
|
+
const dueByNow = all.filter((d) => d <= asOf);
|
|
45
|
+
const overdue = dueByNow.slice(s.n);
|
|
46
|
+
const next = all[s.n] ?? null;
|
|
47
|
+
const count = p.count ?? null;
|
|
48
|
+
const left = count === null ? null : Math.max(0, count - s.n);
|
|
49
|
+
return {
|
|
50
|
+
plan: p.id,
|
|
51
|
+
name: p.name ?? p.note ?? p.id,
|
|
52
|
+
kind: p.kind,
|
|
53
|
+
account: p.account,
|
|
54
|
+
perPayment: per,
|
|
55
|
+
count,
|
|
56
|
+
paidCount: s.n,
|
|
57
|
+
paidAmount: s.amount,
|
|
58
|
+
left,
|
|
59
|
+
leftAmount: left === null ? null : left * per,
|
|
60
|
+
next,
|
|
61
|
+
overdue,
|
|
62
|
+
finished: left === 0 || (Boolean(p.end) && !next),
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Plan payments due from (earliest unpaid) through asOf + days. */
|
|
67
|
+
export function plansDue(l, asOf, days = 30) {
|
|
68
|
+
const until = addDays(asOf, days);
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const st of planStatus(l, asOf)) {
|
|
71
|
+
const p = l.plans.find((x) => x.id === st.plan);
|
|
72
|
+
const dates = dueDates(p, until).slice(st.paidCount);
|
|
73
|
+
for (const d of dates)
|
|
74
|
+
out.push({ plan: p.id, name: st.name, account: p.account, date: d, amount: st.perPayment, overdue: d < asOf });
|
|
75
|
+
}
|
|
76
|
+
return out.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
|
|
77
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { isOpen } from "../util.js";
|
|
2
|
+
import { plansDue } from "./engine.js";
|
|
3
|
+
import { LOAN_TYPES } from "./types.js";
|
|
4
|
+
export const loansModule = {
|
|
5
|
+
name: "loans",
|
|
6
|
+
types: LOAN_TYPES,
|
|
7
|
+
on: (l, asOf) => l.plans.length > 0 || l.accounts.some((a) => a.type in LOAN_TYPES && isOpen(a, asOf)),
|
|
8
|
+
attention(l, asOf) {
|
|
9
|
+
return plansDue(l, asOf, 7).map((d) => {
|
|
10
|
+
const days = Math.round((Date.parse(d.date) - Date.parse(asOf)) / 86400000);
|
|
11
|
+
return {
|
|
12
|
+
kind: d.overdue ? "plan_overdue" : "plan_due",
|
|
13
|
+
module: "loans",
|
|
14
|
+
severity: d.overdue ? "red" : "amber",
|
|
15
|
+
date: d.date,
|
|
16
|
+
title: `${d.overdue ? "Overdue" : "Due"}: ${d.name} ${d.amount} on ${d.date}`,
|
|
17
|
+
amount: d.amount,
|
|
18
|
+
account: d.account,
|
|
19
|
+
name: d.name,
|
|
20
|
+
days,
|
|
21
|
+
params: { plan: d.plan },
|
|
22
|
+
link: "#/plans",
|
|
23
|
+
ask: true,
|
|
24
|
+
};
|
|
25
|
+
});
|
|
26
|
+
},
|
|
27
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export const LOAN_TYPES = {
|
|
2
|
+
bnpl: { label: { en: "Buy now pay later", vi: "Mua trước trả sau" }, liability: true, details: { provider: { kind: "string" }, limit: { kind: "int" }, due_day: { kind: "day" } } },
|
|
3
|
+
loan_given: { label: { en: "Loan given", vi: "Cho vay" }, details: { borrower: { kind: "string" }, rate: { kind: "number" } } },
|
|
4
|
+
loan_taken: { label: { en: "Loan taken", vi: "Đi vay" }, liability: true, details: { lender: { kind: "string" }, rate: { kind: "number" } } },
|
|
5
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { TypeDef } from "../engine/registry.js";
|
|
2
|
+
import type { FileMap } from "../engine/load.js";
|
|
3
|
+
import type { ISODate, Issue, Ledger } from "../engine/types.js";
|
|
4
|
+
/**
|
|
5
|
+
* One item for "Needs you". Text is not stored here: the dashboard translates by `kind` (with `params`),
|
|
6
|
+
* the connector reads `title` (plain English) and the fields.
|
|
7
|
+
*/
|
|
8
|
+
export interface AttentionItem {
|
|
9
|
+
kind: string;
|
|
10
|
+
module?: string;
|
|
11
|
+
severity: "red" | "amber" | "info";
|
|
12
|
+
/** Sort key: the date it is about (due date, maturity…), or asOf for housekeeping. */
|
|
13
|
+
date: ISODate;
|
|
14
|
+
title: string;
|
|
15
|
+
amount?: number;
|
|
16
|
+
account?: string;
|
|
17
|
+
name?: string;
|
|
18
|
+
days?: number;
|
|
19
|
+
count?: number;
|
|
20
|
+
params?: Record<string, string | number | null>;
|
|
21
|
+
/** Where it's fixed in the dashboard (hash route), e.g. "#/transactions?category=" */
|
|
22
|
+
link?: string;
|
|
23
|
+
/** true when the fix is a chat with the AI (the dashboard shows "Ask AI"). */
|
|
24
|
+
ask?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/** A built-in module: what it adds around one or more account types. Built in, never third-party. */
|
|
27
|
+
export interface ModuleDef {
|
|
28
|
+
name: string;
|
|
29
|
+
/** Account types it owns (label, liquid/liability/holdings, the details fields check validates). */
|
|
30
|
+
types: Record<string, TypeDef>;
|
|
31
|
+
/** On when the ledger has what the module is about (usually an open account of its types). */
|
|
32
|
+
on(l: Ledger, asOf: ISODate, files?: FileMap): boolean;
|
|
33
|
+
/** Reads the module's own files into ledger.ext[name] when the ledger loads (problems go to issues). */
|
|
34
|
+
load?(files: FileMap, issues: Issue[]): unknown;
|
|
35
|
+
/** Extra checks for its own files and fields, run by `ownledger check` when on. */
|
|
36
|
+
check?(l: Ledger, files: FileMap): Issue[];
|
|
37
|
+
/** Its items for "Needs you". */
|
|
38
|
+
attention?(l: Ledger, asOf: ISODate, files?: FileMap): AttentionItem[];
|
|
39
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Account, ISODate } from "../engine/types.js";
|
|
2
|
+
export declare const num: (v: unknown) => number | undefined;
|
|
3
|
+
export declare const int: (v: unknown) => number | undefined;
|
|
4
|
+
export declare const day: (v: unknown) => number | undefined;
|
|
5
|
+
export declare const date: (v: unknown) => ISODate | undefined;
|
|
6
|
+
export declare const str: (v: unknown) => string | undefined;
|
|
7
|
+
/** Open on asOf: not closed on or before it. */
|
|
8
|
+
export declare const isOpen: (a: Account, asOf: ISODate) => boolean;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { isDate } from "../engine/dates.js";
|
|
2
|
+
export const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
3
|
+
export const int = (v) => (Number.isInteger(v) ? v : undefined);
|
|
4
|
+
export const day = (v) => (Number.isInteger(v) && v >= 1 && v <= 31 ? v : undefined);
|
|
5
|
+
export const date = (v) => (isDate(v) ? v : undefined);
|
|
6
|
+
export const str = (v) => (typeof v === "string" && v ? v : undefined);
|
|
7
|
+
/** Open on asOf: not closed on or before it. */
|
|
8
|
+
export const isOpen = (a, asOf) => !(isDate(a.closed) && a.closed <= asOf);
|
package/dist/node/scaffold.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { fileURLToPath } from "node:url";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { yamlText } from "../engine/write.js";
|
|
5
5
|
import { defaultCategories } from "../engine/defaults.js";
|
|
6
6
|
import { FORMAT } from "../engine/types.js";
|
|
7
7
|
const CURRENCY_NAMES = { VND: "Việt Nam đồng", USD: "US dollar", EUR: "Euro" };
|
|
@@ -18,7 +18,7 @@ export function pkgVersion() {
|
|
|
18
18
|
}
|
|
19
19
|
/** The files `init` writes into a new data repo. */
|
|
20
20
|
export function scaffold(o) {
|
|
21
|
-
const y =
|
|
21
|
+
const y = yamlText;
|
|
22
22
|
const files = {
|
|
23
23
|
"data/meta.yaml": y({ format: FORMAT, base: o.base, locale: o.lang, owner: o.owner ?? null, name: o.name }),
|
|
24
24
|
"data/assets.yaml": y([{ id: o.base, name: CURRENCY_NAMES[o.base] ?? o.base, kind: "currency", decimals: DECIMALS[o.base] ?? 2 }]),
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ISODate } from "../engine/types.js";
|
|
2
|
+
import { STATEMENTS_DIR } from "../modules/cards/files.js";
|
|
3
|
+
/**
|
|
4
|
+
* Bank statements (plan 004): imports/statements/<account-id>/<YYYY-MM>.pdf, unlocked.
|
|
5
|
+
* Read on the user's computer only (CLI); the Worker never parses them.
|
|
6
|
+
*/
|
|
7
|
+
export { STATEMENTS_DIR };
|
|
8
|
+
export declare const SOURCES_FILE = "imports/statements/sources.yaml";
|
|
9
|
+
export declare const ENV_FILE = ".env.statements";
|
|
10
|
+
export declare class PdfPasswordError extends Error {
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The PDF without any encryption (same bytes for the same input: --deterministic-id).
|
|
14
|
+
* Throws PdfPasswordError when it needs a password and none (or a wrong one) is given.
|
|
15
|
+
*/
|
|
16
|
+
export declare function unlockPdf(bytes: Uint8Array, password?: string): Promise<{
|
|
17
|
+
bytes: Uint8Array;
|
|
18
|
+
wasLocked: boolean;
|
|
19
|
+
}>;
|
|
20
|
+
/** True when the PDF can't be opened without a password. */
|
|
21
|
+
export declare function isLocked(bytes: Uint8Array): Promise<boolean>;
|
|
22
|
+
/** The PDF's text, pages joined (pdf.js via unpdf). */
|
|
23
|
+
export declare function pdfText(bytes: Uint8Array): Promise<string>;
|
|
24
|
+
/** Every calendar date written in the text (dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy, yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd). */
|
|
25
|
+
export declare function datesIn(text: string): Set<ISODate>;
|
|
26
|
+
export interface MonthGuess {
|
|
27
|
+
month: string | null;
|
|
28
|
+
from?: ISODate;
|
|
29
|
+
close?: ISODate;
|
|
30
|
+
why: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The statement period a statement's text is about, from the card's statement day: the period whose first and
|
|
34
|
+
* last days both appear in the text; else the one period whose close date appears. Never guesses between two.
|
|
35
|
+
*/
|
|
36
|
+
export declare function monthFromText(text: string, statementDay: number | null): MonthGuess;
|
|
37
|
+
/** KEY=value lines of .env.statements (quotes stripped, # comments). Missing file: {}. */
|
|
38
|
+
export declare function readEnvFile(root: string): Record<string, string>;
|
|
39
|
+
export interface StatementSource {
|
|
40
|
+
from?: string;
|
|
41
|
+
subject?: string;
|
|
42
|
+
/** Name of the variable in .env.statements. */
|
|
43
|
+
password?: string;
|
|
44
|
+
/** What the password is made of (never the password). */
|
|
45
|
+
password_hint?: string;
|
|
46
|
+
}
|
|
47
|
+
/** imports/statements/sources.yaml: account id → how to find its statements in email. Missing file: {}. */
|
|
48
|
+
export declare function readSources(root: string): Record<string, StatementSource>;
|
|
49
|
+
/** The variables tried for a card's password, in order: sources.yaml's, PW_<ACCOUNT_ID>, PW_<FIRST WORD>. */
|
|
50
|
+
export declare function passwordVars(account: string, source?: StatementSource): string[];
|
|
51
|
+
export interface StatementFile {
|
|
52
|
+
account: string;
|
|
53
|
+
month: string;
|
|
54
|
+
path: string;
|
|
55
|
+
}
|
|
56
|
+
/** The statement PDFs on disk, and what doesn't fit the convention (warnings, never errors). */
|
|
57
|
+
export declare function scanStatements(root: string, accountIds: Set<string>): {
|
|
58
|
+
files: StatementFile[];
|
|
59
|
+
warnings: string[];
|
|
60
|
+
};
|
|
61
|
+
/** Months between the first and last filed month that have no file. */
|
|
62
|
+
export declare function missingMonths(months: string[]): string[];
|
|
63
|
+
/** Warnings for `ownledger check`: the convention, plus PDFs still locked. */
|
|
64
|
+
export declare function statementWarnings(root: string, accountIds: Set<string>): Promise<string[]>;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parse as parseYaml } from "yaml";
|
|
5
|
+
import { addDays } from "../engine/dates.js";
|
|
6
|
+
import { STATEMENTS_DIR } from "../modules/cards/files.js";
|
|
7
|
+
import { closeOnOrAfter, prevClose } from "../modules/cards/statements.js";
|
|
8
|
+
/**
|
|
9
|
+
* Bank statements (plan 004): imports/statements/<account-id>/<YYYY-MM>.pdf, unlocked.
|
|
10
|
+
* Read on the user's computer only (CLI); the Worker never parses them.
|
|
11
|
+
*/
|
|
12
|
+
export { STATEMENTS_DIR };
|
|
13
|
+
export const SOURCES_FILE = `${STATEMENTS_DIR}/sources.yaml`;
|
|
14
|
+
export const ENV_FILE = ".env.statements";
|
|
15
|
+
const MONTH_FILE = /^\d{4}-(0[1-9]|1[0-2])\.pdf$/;
|
|
16
|
+
const require = createRequire(import.meta.url);
|
|
17
|
+
/** Runs qpdf once in a fresh instance (an Emscripten program isn't meant to run twice) on /in.pdf → /out.pdf. */
|
|
18
|
+
async function qpdf(args, input) {
|
|
19
|
+
const { default: createModule } = (await import("@neslinesli93/qpdf-wasm"));
|
|
20
|
+
const wasm = require.resolve("@neslinesli93/qpdf-wasm/dist/qpdf.wasm");
|
|
21
|
+
let err = "";
|
|
22
|
+
// the build binds its output to console.log/console.error when created (print/printErr options are ignored):
|
|
23
|
+
// catch it for the error message instead of letting it reach the user's terminal
|
|
24
|
+
const { log, error } = console;
|
|
25
|
+
console.log = () => { };
|
|
26
|
+
console.error = (...a) => void (err += a.join(" ") + "\n");
|
|
27
|
+
const exitCode = process.exitCode; // qpdf's exit sets Node's exit code; keep ours
|
|
28
|
+
let rc;
|
|
29
|
+
let q;
|
|
30
|
+
try {
|
|
31
|
+
q = await createModule({ locateFile: () => wasm, noInitialRun: true });
|
|
32
|
+
q.FS.writeFile("/in.pdf", input);
|
|
33
|
+
try {
|
|
34
|
+
rc = q.callMain([...args, "/in.pdf", "/out.pdf"]);
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
rc = typeof e.status === "number" ? e.status : 2;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
console.log = log;
|
|
42
|
+
console.error = error;
|
|
43
|
+
process.exitCode = exitCode;
|
|
44
|
+
}
|
|
45
|
+
let out = null;
|
|
46
|
+
try {
|
|
47
|
+
out = q.FS.readFile("/out.pdf");
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
/* no output */
|
|
51
|
+
}
|
|
52
|
+
return { rc, out, err };
|
|
53
|
+
}
|
|
54
|
+
export class PdfPasswordError extends Error {
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The PDF without any encryption (same bytes for the same input: --deterministic-id).
|
|
58
|
+
* Throws PdfPasswordError when it needs a password and none (or a wrong one) is given.
|
|
59
|
+
*/
|
|
60
|
+
export async function unlockPdf(bytes, password) {
|
|
61
|
+
const tries = password ? [undefined, password] : [undefined];
|
|
62
|
+
for (const pw of tries) {
|
|
63
|
+
const r = await qpdf([...(pw ? [`--password=${pw}`] : []), "--decrypt", "--deterministic-id"], bytes);
|
|
64
|
+
if (r.rc === 0 || (r.rc === 3 && r.out))
|
|
65
|
+
return { bytes: r.out, wasLocked: pw !== undefined };
|
|
66
|
+
if (!/invalid password/i.test(r.err))
|
|
67
|
+
throw new Error(`not a readable PDF (${r.err.trim().split("\n").pop() ?? `qpdf ${r.rc}`})`);
|
|
68
|
+
}
|
|
69
|
+
throw new PdfPasswordError(password ? "wrong password" : "the PDF needs a password");
|
|
70
|
+
}
|
|
71
|
+
/** True when the PDF can't be opened without a password. */
|
|
72
|
+
export async function isLocked(bytes) {
|
|
73
|
+
const r = await qpdf(["--decrypt"], bytes);
|
|
74
|
+
return r.rc !== 0 && r.rc !== 3 && /invalid password/i.test(r.err);
|
|
75
|
+
}
|
|
76
|
+
/** The PDF's text, pages joined (pdf.js via unpdf). */
|
|
77
|
+
export async function pdfText(bytes) {
|
|
78
|
+
const { extractText, getDocumentProxy } = await import("unpdf");
|
|
79
|
+
const doc = await getDocumentProxy(new Uint8Array(bytes)); // pdf.js takes over the buffer: give it a copy
|
|
80
|
+
const { text } = await extractText(doc, { mergePages: true });
|
|
81
|
+
return text;
|
|
82
|
+
}
|
|
83
|
+
/* ------------------------------------------------------------------ month of a statement */
|
|
84
|
+
/** Every calendar date written in the text (dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy, yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd). */
|
|
85
|
+
export function datesIn(text) {
|
|
86
|
+
const out = new Set();
|
|
87
|
+
const add = (y, m, d) => {
|
|
88
|
+
const mm = Number(m), dd = Number(d);
|
|
89
|
+
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31)
|
|
90
|
+
out.add(`${y}-${String(mm).padStart(2, "0")}-${String(dd).padStart(2, "0")}`);
|
|
91
|
+
};
|
|
92
|
+
for (const m of text.matchAll(/(?<!\d)(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})(?!\d)/g))
|
|
93
|
+
add(m[3], m[2], m[1]);
|
|
94
|
+
for (const m of text.matchAll(/(?<!\d)(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})(?!\d)/g))
|
|
95
|
+
add(m[1], m[2], m[3]);
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The statement period a statement's text is about, from the card's statement day: the period whose first and
|
|
100
|
+
* last days both appear in the text; else the one period whose close date appears. Never guesses between two.
|
|
101
|
+
*/
|
|
102
|
+
export function monthFromText(text, statementDay) {
|
|
103
|
+
if (!statementDay)
|
|
104
|
+
return { month: null, why: "the card has no statement_day" };
|
|
105
|
+
const dates = datesIn(text);
|
|
106
|
+
const periods = new Map(); // close → from
|
|
107
|
+
for (const d of dates) {
|
|
108
|
+
const c = closeOnOrAfter(d, statementDay);
|
|
109
|
+
periods.set(c, addDays(prevClose(c, statementDay), 1));
|
|
110
|
+
}
|
|
111
|
+
const both = [...periods].filter(([c, f]) => dates.has(c) && dates.has(f));
|
|
112
|
+
const closeOnly = [...periods].filter(([c]) => dates.has(c));
|
|
113
|
+
const pick = both.length ? both : closeOnly;
|
|
114
|
+
if (pick.length === 1) {
|
|
115
|
+
const [close, from] = pick[0];
|
|
116
|
+
return { month: close.slice(0, 7), from, close, why: both.length ? "period dates in the text" : "close date in the text" };
|
|
117
|
+
}
|
|
118
|
+
if (!pick.length)
|
|
119
|
+
return { month: null, why: "no statement period's dates found in the text" };
|
|
120
|
+
return { month: null, why: `several periods fit (${pick.map(([c]) => c.slice(0, 7)).join(", ")})` };
|
|
121
|
+
}
|
|
122
|
+
/* ------------------------------------------------------------------ passwords and sources */
|
|
123
|
+
/** KEY=value lines of .env.statements (quotes stripped, # comments). Missing file: {}. */
|
|
124
|
+
export function readEnvFile(root) {
|
|
125
|
+
const p = join(root, ENV_FILE);
|
|
126
|
+
if (!existsSync(p))
|
|
127
|
+
return {};
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const line of readFileSync(p, "utf8").split(/\r?\n/)) {
|
|
130
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
|
|
131
|
+
if (!m || line.trimStart().startsWith("#"))
|
|
132
|
+
continue;
|
|
133
|
+
out[m[1]] = m[2].replace(/^(['"])(.*)\1$/, "$2");
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
/** imports/statements/sources.yaml: account id → how to find its statements in email. Missing file: {}. */
|
|
138
|
+
export function readSources(root) {
|
|
139
|
+
const p = join(root, SOURCES_FILE);
|
|
140
|
+
if (!existsSync(p))
|
|
141
|
+
return {};
|
|
142
|
+
const y = parseYaml(readFileSync(p, "utf8"));
|
|
143
|
+
if (y === null || y === undefined)
|
|
144
|
+
return {};
|
|
145
|
+
if (typeof y !== "object" || Array.isArray(y))
|
|
146
|
+
throw new Error(`${SOURCES_FILE}: expected account ids as keys`);
|
|
147
|
+
return y;
|
|
148
|
+
}
|
|
149
|
+
const envName = (s) => s.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
|
|
150
|
+
/** The variables tried for a card's password, in order: sources.yaml's, PW_<ACCOUNT_ID>, PW_<FIRST WORD>. */
|
|
151
|
+
export function passwordVars(account, source) {
|
|
152
|
+
const out = [source?.password, `PW_${envName(account)}`, `PW_${envName(account.split(/[-_]/)[0])}`].filter((x) => !!x);
|
|
153
|
+
return [...new Set(out)];
|
|
154
|
+
}
|
|
155
|
+
/** The statement PDFs on disk, and what doesn't fit the convention (warnings, never errors). */
|
|
156
|
+
export function scanStatements(root, accountIds) {
|
|
157
|
+
const dir = join(root, STATEMENTS_DIR);
|
|
158
|
+
const files = [];
|
|
159
|
+
const warnings = [];
|
|
160
|
+
if (!existsSync(dir))
|
|
161
|
+
return { files, warnings };
|
|
162
|
+
for (const acc of readdirSync(dir).sort()) {
|
|
163
|
+
if (acc.startsWith("."))
|
|
164
|
+
continue;
|
|
165
|
+
const p = join(dir, acc);
|
|
166
|
+
if (!statSync(p).isDirectory()) {
|
|
167
|
+
if (acc !== "sources.yaml" && !/^readme\.md$/i.test(acc))
|
|
168
|
+
warnings.push(`${STATEMENTS_DIR}/${acc}: not a statement folder (expected <account-id>/<YYYY-MM>.pdf)`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (!accountIds.has(acc))
|
|
172
|
+
warnings.push(`${STATEMENTS_DIR}/${acc}/: no account "${acc}" in data/accounts.yaml`);
|
|
173
|
+
for (const f of readdirSync(p).sort()) {
|
|
174
|
+
if (f.startsWith("."))
|
|
175
|
+
continue;
|
|
176
|
+
if (!MONTH_FILE.test(f))
|
|
177
|
+
warnings.push(`${STATEMENTS_DIR}/${acc}/${f}: name should be <YYYY-MM>.pdf (the month of the statement's close date)`);
|
|
178
|
+
else
|
|
179
|
+
files.push({ account: acc, month: f.slice(0, 7), path: `${STATEMENTS_DIR}/${acc}/${f}` });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return { files, warnings };
|
|
183
|
+
}
|
|
184
|
+
/** Months between the first and last filed month that have no file. */
|
|
185
|
+
export function missingMonths(months) {
|
|
186
|
+
if (!months.length)
|
|
187
|
+
return [];
|
|
188
|
+
const have = new Set(months);
|
|
189
|
+
const sorted = [...have].sort();
|
|
190
|
+
const out = [];
|
|
191
|
+
let [y, m] = sorted[0].split("-").map(Number);
|
|
192
|
+
const last = sorted[sorted.length - 1];
|
|
193
|
+
for (;;) {
|
|
194
|
+
const k = `${y}-${String(m).padStart(2, "0")}`;
|
|
195
|
+
if (k > last)
|
|
196
|
+
break;
|
|
197
|
+
if (!have.has(k))
|
|
198
|
+
out.push(k);
|
|
199
|
+
m++;
|
|
200
|
+
if (m > 12)
|
|
201
|
+
(m = 1), y++;
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/** Warnings for `ownledger check`: the convention, plus PDFs still locked. */
|
|
206
|
+
export async function statementWarnings(root, accountIds) {
|
|
207
|
+
const { files, warnings } = scanStatements(root, accountIds);
|
|
208
|
+
for (const f of files) {
|
|
209
|
+
try {
|
|
210
|
+
if (await isLocked(new Uint8Array(readFileSync(join(root, f.path)))))
|
|
211
|
+
warnings.push(`${f.path}: still locked with a password (file it with \`ownledger statements add\`)`);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
warnings.push(`${f.path}: can't be read as a PDF`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return warnings;
|
|
218
|
+
}
|
package/dist/worker/api.d.ts
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
+
import { type Dashboard } from "../engine/dashboard.js";
|
|
2
|
+
import type { FileMap } from "../engine/load.js";
|
|
1
3
|
import type { Env } from "./env.js";
|
|
4
|
+
import { type DataSource } from "./store.js";
|
|
5
|
+
/** The signed-in person's dashboard file, or null when they have none yet. */
|
|
6
|
+
export declare function dashboardOf(files: FileMap, login: string): Dashboard | null;
|
|
7
|
+
/** Commit one dashboard file; if main moved meanwhile, once more on the new head (the file is replaced whole). */
|
|
8
|
+
export declare function saveDashboard(env: Env, src: DataSource, login: string, d: Dashboard, message: string): Promise<{
|
|
9
|
+
sha: string;
|
|
10
|
+
issues: string[];
|
|
11
|
+
}>;
|
|
2
12
|
/** JSON for the dashboard. Same sign-in allowlist as the connector; read-only except import (Phase 6). */
|
|
3
|
-
export declare function api(req: Request, env: Env): Promise<Response>;
|
|
13
|
+
export declare function api(req: Request, env: Env, source?: DataSource): Promise<Response>;
|