ownledger 1.2.0 → 2.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 +28 -1
- package/CHANGELOG.md +48 -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-DEBzshne.js +1 -0
- package/assets/static/Accounts-C1iNsQsy.js +1 -0
- package/assets/static/Attention-qo4v70P1.js +1 -0
- package/assets/static/ByCategory-33P2zSs-.js +1 -0
- package/assets/static/CardDetail-CvRo7JPt.js +1 -0
- package/assets/static/Cards-C3AdusmT.js +1 -0
- package/assets/static/Cards-DuqZFxkQ.js +1 -0
- package/assets/static/CardsValue-BM9WUQmy.js +1 -0
- package/assets/static/Cashback-DsWyjgRr.js +1 -0
- package/assets/static/CategoryIcon-E6EWIpbr.js +1 -0
- package/assets/static/CategoryPicker-BPeJNSuM.js +1 -0
- package/assets/static/ChartWidget-Bk1TAvJM.js +1 -0
- package/assets/static/Combobox-lRNTmjKR.js +1 -0
- package/assets/static/Deposits-CgEFypxb.js +1 -0
- package/assets/static/DrillLink-pa6s17Xu.js +1 -0
- package/assets/static/Field-OkPhoYM1.js +1 -0
- package/assets/static/HomeEditor-DdrzEPe2.js +1 -0
- package/assets/static/Import-DrhHmL65.js +2 -0
- package/assets/static/IncomeSpending-Cveqr3xt.js +1 -0
- package/assets/static/KV-CKGyL0p7.js +1 -0
- package/assets/static/Left-Bs_oKU19.js +1 -0
- package/assets/static/Money-DCMKf898.js +1 -0
- package/assets/static/NetWorth-Cjd13J56.js +1 -0
- package/assets/static/Pace-CBUDNxzH.js +1 -0
- package/assets/static/Panel-CXjnsEN0.js +1 -0
- package/assets/static/PinDialog-DoGuAyi4.js +1 -0
- package/assets/static/Plans-EWJdPCJ3.js +1 -0
- package/assets/static/Recent-BmJjA5dK.js +1 -0
- package/assets/static/Reports-DSrLn_wC.js +1 -0
- package/assets/static/Settings-DdiEp2Qi.js +1 -0
- package/assets/static/Transactions-Cy0kgcLE.js +1 -0
- package/assets/static/TxRow-IqjFXpya.js +1 -0
- package/assets/static/Unusual-D5-L9ZOy.js +1 -0
- package/assets/static/Upcoming-CCqPol8c.js +1 -0
- package/assets/static/WhichCard-Butdi7AN.js +1 -0
- package/assets/static/arrow-up-C8D_7x_H.js +1 -0
- package/assets/static/bits-BoWPOwTB.js +1 -0
- package/assets/static/button-Cj0k8AtB.js +1 -0
- package/assets/static/cards-AZlSJQ0z.js +1 -0
- package/assets/static/charts-Cj_hTR4h.js +65 -0
- package/assets/static/chevron-down-BLodeu9a.js +1 -0
- package/assets/static/chevron-right-BetctQ6k.js +1 -0
- package/assets/static/createLucideIcon-DUW9Fpzj.js +1 -0
- package/assets/static/dialog-BIbLA-XP.js +1 -0
- package/assets/static/dist-CbNfxqbd.js +1 -0
- package/assets/static/dist-CetESl7K.js +1 -0
- package/assets/static/dist-DYP_TYPy.js +1 -0
- package/assets/static/dist-DaSyQKU7.js +1 -0
- package/assets/static/drill-t1zr57xi.js +1 -0
- package/assets/static/es2015-BgAh-EkH.js +41 -0
- package/assets/static/fold-CGWYt9Iu.js +1 -0
- package/assets/static/index-CBsgYTMJ.css +1 -0
- package/assets/static/index-DYyIpxqK.js +14 -0
- package/assets/static/queries-C_4ufx4u.js +1 -0
- package/assets/static/react-dom-CI34djkT.js +1 -0
- package/assets/static/select-2EwEpMf_.js +1 -0
- package/assets/static/shared-CR-hvb-r.js +1 -0
- package/assets/static/triangle-exclamation-point-C6padEUM.js +1 -0
- package/assets/static/useMutation-BWtHiYPX.js +1 -0
- package/dist/cli/cards.d.ts +2 -0
- package/dist/cli/cards.js +86 -0
- package/dist/cli/import.js +12 -2
- package/dist/cli/index.js +3 -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 +19 -0
- package/dist/modules/api.js +16 -0
- package/dist/modules/cards/api.d.ts +3 -0
- package/dist/modules/cards/api.js +73 -0
- package/dist/modules/cards/engine.d.ts +42 -0
- package/dist/modules/cards/engine.js +102 -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/worker/api.d.ts +11 -1
- package/dist/worker/api.js +167 -13
- package/dist/worker/bestcard.d.ts +32 -9
- package/dist/worker/bestcard.js +91 -51
- package/dist/worker/mcp.js +209 -30
- package/dist/worker/openwallet.d.ts +1 -1
- package/dist/worker/openwallet.js +41 -11
- package/dist/worker/version.d.ts +1 -1
- package/dist/worker/version.js +1 -1
- package/package.json +26 -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 }]),
|
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>;
|
package/dist/worker/api.js
CHANGED
|
@@ -1,21 +1,104 @@
|
|
|
1
1
|
import { accountValues } from "../engine/balances.js";
|
|
2
2
|
import { flattenCategories } from "../engine/categories.js";
|
|
3
|
-
import { addMonths, todayIn } from "../engine/dates.js";
|
|
3
|
+
import { addMonths, monthEnd, todayIn } from "../engine/dates.js";
|
|
4
4
|
import { netWorth, netWorthSeries } from "../engine/networth.js";
|
|
5
5
|
import { TYPES } from "../engine/registry.js";
|
|
6
6
|
import { queryTransactions, report } from "../engine/reports.js";
|
|
7
7
|
import { budgets, cards, deposits, planStatus, plansDue, today } from "../engine/schedules.js";
|
|
8
8
|
import { checkFiles } from "../engine/check.js";
|
|
9
|
+
import { attention } from "../engine/attention.js";
|
|
10
|
+
import { checkDashboard, dashboardPath, defaultWidgets, parseDashboard, poolOf, writeDashboard } from "../engine/dashboard.js";
|
|
11
|
+
import { features } from "../engine/features.js";
|
|
12
|
+
import { pace, series, unusual, usual } from "../engine/insights.js";
|
|
13
|
+
import { moduleApi } from "../modules/api.js";
|
|
9
14
|
import { applyChange } from "../engine/write.js";
|
|
10
15
|
import { parseMapping } from "../import/mapping.js";
|
|
11
16
|
import { runImport } from "../import/run.js";
|
|
12
17
|
import { readWorkbook } from "../import/workbook.js";
|
|
13
18
|
import { sessionLogin } from "./auth.js";
|
|
19
|
+
import { MainMovedError } from "./github.js";
|
|
14
20
|
import { applyPending, savePending, snapshot, sourceFor } from "./store.js";
|
|
15
21
|
import { VERSION } from "./version.js";
|
|
16
22
|
const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
|
|
23
|
+
/** The signed-in person's dashboard file, or null when they have none yet. */
|
|
24
|
+
export function dashboardOf(files, login) {
|
|
25
|
+
try {
|
|
26
|
+
return parseDashboard(files[dashboardPath(login)]);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Commit one dashboard file; if main moved meanwhile, once more on the new head (the file is replaced whole). */
|
|
33
|
+
export async function saveDashboard(env, src, login, d, message) {
|
|
34
|
+
for (let attempt = 0;; attempt++) {
|
|
35
|
+
const s = await snapshot(env, src);
|
|
36
|
+
const path = dashboardPath(login);
|
|
37
|
+
const issues = checkDashboard(path, d, s.ledger);
|
|
38
|
+
const errors = issues.filter((i) => i.level === "error");
|
|
39
|
+
if (errors.length)
|
|
40
|
+
throw new Error(`dashboard refused: ${errors.map((e) => `${e.where ? `[${e.where}] ` : ""}${e.message}`).join("; ")}`);
|
|
41
|
+
try {
|
|
42
|
+
const sha = await src.commit(s.sha, [{ path, content: writeDashboard(d) }], message);
|
|
43
|
+
return { sha, issues: issues.map((i) => `${i.where ? `[${i.where}] ` : ""}${i.message}`) };
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
if (e instanceof MainMovedError && attempt === 0)
|
|
47
|
+
continue;
|
|
48
|
+
throw e;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function lastActivity(L) {
|
|
53
|
+
const out = new Map();
|
|
54
|
+
for (const t of L.transactions) {
|
|
55
|
+
if (t.void)
|
|
56
|
+
continue;
|
|
57
|
+
for (const ln of t.lines)
|
|
58
|
+
if (ln.account)
|
|
59
|
+
out.set(ln.account, t.date);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** Balance of one account after each of its transactions (for the running balance column). */
|
|
64
|
+
function runningBalance(L, account) {
|
|
65
|
+
const out = new Map();
|
|
66
|
+
let b = 0;
|
|
67
|
+
for (const t of L.transactions) {
|
|
68
|
+
if (t.void)
|
|
69
|
+
continue;
|
|
70
|
+
let touched = false;
|
|
71
|
+
for (const ln of t.lines)
|
|
72
|
+
if (ln.account === account) {
|
|
73
|
+
b += ln.amount;
|
|
74
|
+
touched = true;
|
|
75
|
+
}
|
|
76
|
+
if (touched)
|
|
77
|
+
out.set(t.id, b);
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
function seriesQuery(q) {
|
|
82
|
+
const s = (k) => q.get(k) ?? undefined;
|
|
83
|
+
const acc = q.get("account");
|
|
84
|
+
return {
|
|
85
|
+
metric: (s("metric") ?? "spending"),
|
|
86
|
+
category: s("category"),
|
|
87
|
+
account: acc ? (acc.includes(",") ? acc.split(",") : acc) : undefined,
|
|
88
|
+
who: s("who"),
|
|
89
|
+
event: s("event"),
|
|
90
|
+
tag: s("tag"),
|
|
91
|
+
text: s("text"),
|
|
92
|
+
period: s("period"),
|
|
93
|
+
from: s("from"),
|
|
94
|
+
to: s("to"),
|
|
95
|
+
by: s("by"),
|
|
96
|
+
compare: s("compare"),
|
|
97
|
+
limit: q.get("limit") ? Number(q.get("limit")) : undefined,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
17
100
|
/** JSON for the dashboard. Same sign-in allowlist as the connector; read-only except import (Phase 6). */
|
|
18
|
-
export async function api(req, env) {
|
|
101
|
+
export async function api(req, env, source) {
|
|
19
102
|
const login = await sessionLogin(req, env);
|
|
20
103
|
if (!login)
|
|
21
104
|
return json({ error: "sign in", login: "/auth/login" }, 401);
|
|
@@ -25,20 +108,71 @@ export async function api(req, env) {
|
|
|
25
108
|
const url = new URL(req.url);
|
|
26
109
|
const q = url.searchParams;
|
|
27
110
|
const path = url.pathname.slice(5);
|
|
28
|
-
const src = sourceFor(env);
|
|
111
|
+
const src = source ?? sourceFor(env);
|
|
29
112
|
const s = await snapshot(env, src);
|
|
30
113
|
const L = s.ledger;
|
|
31
114
|
const asOf = q.get("date") ?? todayIn(env.TIMEZONE || "Asia/Ho_Chi_Minh");
|
|
115
|
+
const dash = dashboardOf(s.files, login);
|
|
116
|
+
const pool = poolOf(L, dash?.prefs?.pool, asOf);
|
|
117
|
+
/** "pool" in an account filter means every account in the pool. */
|
|
118
|
+
const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
|
|
32
119
|
try {
|
|
120
|
+
if (path.startsWith("m/")) {
|
|
121
|
+
const r = await moduleApi(path.slice(2), { req, env, src, snap: s, login, asOf, q });
|
|
122
|
+
return r ? json(r.body, r.status ?? 200) : json({ error: "not found" }, 404);
|
|
123
|
+
}
|
|
33
124
|
switch (path) {
|
|
34
|
-
case "me":
|
|
35
|
-
|
|
125
|
+
case "me": {
|
|
126
|
+
const f = features(L, asOf, s.files, pool.accounts);
|
|
127
|
+
return json({ login, version: VERSION, data: src.label, commit: s.sha, base: L.meta.base, locale: L.meta.locale ?? "en", name: L.meta.name, today: asOf, check: { errors: s.errors, warnings: s.warnings }, features: f, pool, dashboard: { saved: Boolean(dash), widgets: dash?.widgets ?? defaultWidgets(f), prefs: dash?.prefs ?? {} } });
|
|
128
|
+
}
|
|
129
|
+
case "home": {
|
|
130
|
+
const nw = netWorthSeries(L, addMonths(asOf.slice(0, 7) + "-01", -12), asOf);
|
|
131
|
+
const now = nw[nw.length - 1];
|
|
132
|
+
const lastMonthEnd = nw[nw.length - 2] ?? null;
|
|
133
|
+
const yearAgo = nw[0] ?? null;
|
|
134
|
+
const balances = new Map(accountValues(L, asOf).map((v) => [v.account.id, v.value]));
|
|
135
|
+
const p = pace(L, asOf);
|
|
136
|
+
return json({
|
|
137
|
+
asOf,
|
|
138
|
+
pace: p,
|
|
139
|
+
left: { income: p.income, spent: p.spent, now: p.income - p.spent, monthEnd: p.incomeEstimate - p.estimate },
|
|
140
|
+
attention: attention(L, asOf, { files: s.files, check: { errors: s.errors, warnings: s.warnings } }),
|
|
141
|
+
unusual: unusual(L, asOf),
|
|
142
|
+
netWorth: { net: now.net, assets: now.assets, liabilities: now.liabilities, byType: now.byType, unpriced: now.unpriced, changeMonth: lastMonthEnd ? now.net - lastMonthEnd.net : null, change12: yearAgo && nw.length > 12 ? now.net - yearAgo.net : null, series: nw.slice(1).map((x) => ({ date: x.date, net: x.net })) },
|
|
143
|
+
pool: { ...pool, balance: pool.accounts.reduce((t, id) => t + (balances.get(id) ?? 0), 0) },
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
case "series": {
|
|
147
|
+
const sq = seriesQuery(q);
|
|
148
|
+
if (sq.account === "pool")
|
|
149
|
+
sq.account = pool.accounts;
|
|
150
|
+
return json(series(L, sq, asOf));
|
|
151
|
+
}
|
|
152
|
+
case "dashboard": {
|
|
153
|
+
if (req.method === "PUT") {
|
|
154
|
+
const body = (await req.json());
|
|
155
|
+
const d = { version: 1, widgets: body.widgets ?? dash?.widgets, prefs: body.prefs ?? dash?.prefs };
|
|
156
|
+
if (!d.prefs || !Object.keys(d.prefs).length)
|
|
157
|
+
delete d.prefs;
|
|
158
|
+
const r = await saveDashboard(env, src, login, d, `Dashboard: ${body.prefs && !body.widgets ? "settings" : "layout"} (${login})`);
|
|
159
|
+
return json({ saved: true, commit: r.sha, warnings: r.issues });
|
|
160
|
+
}
|
|
161
|
+
if (req.method === "DELETE") {
|
|
162
|
+
if (!dash)
|
|
163
|
+
return json({ saved: false });
|
|
164
|
+
const sha = await src.commit(s.sha, [{ path: dashboardPath(login), content: writeDashboard({ version: 1, ...(dash.prefs ? { prefs: dash.prefs } : {}) }) }], `Dashboard: reset layout (${login})`);
|
|
165
|
+
return json({ saved: true, commit: sha });
|
|
166
|
+
}
|
|
167
|
+
const f = features(L, asOf, s.files);
|
|
168
|
+
return json({ saved: Boolean(dash), widgets: dash?.widgets ?? defaultWidgets(f), prefs: dash?.prefs ?? {}, path: dashboardPath(login) });
|
|
169
|
+
}
|
|
36
170
|
case "meta": {
|
|
37
171
|
const { map } = flattenCategories(L.categories);
|
|
38
172
|
return json({
|
|
39
173
|
base: L.meta.base,
|
|
40
174
|
locale: L.meta.locale,
|
|
41
|
-
types: Object.fromEntries(Object.entries(TYPES).map(([k, v]) => [k, v.label])),
|
|
175
|
+
types: Object.fromEntries(Object.entries(TYPES).map(([k, v]) => [k, { ...v.label, liquid: Boolean(v.liquid), liability: Boolean(v.liability), holdings: Boolean(v.holdings) }])),
|
|
42
176
|
categories: [...map.values()],
|
|
43
177
|
accounts: L.accounts.map((a) => ({ id: a.id, name: a.name, type: a.type, closed: a.closed ?? null, group: a.group ?? null })),
|
|
44
178
|
assets: L.assets,
|
|
@@ -48,14 +182,26 @@ export async function api(req, env) {
|
|
|
48
182
|
const m = report(L, asOf.slice(0, 7));
|
|
49
183
|
return json({ today: today(L, asOf), month: { income: m.income, expense: m.expense, net: m.net, previous: m.previous, top: m.rows.filter((r) => r.expense).slice(0, 8) }, netWorth: netWorth(L, asOf), series: netWorthSeries(L, addMonths(asOf.slice(0, 7) + "-01", -11), asOf) });
|
|
50
184
|
}
|
|
51
|
-
case "accounts":
|
|
52
|
-
|
|
185
|
+
case "accounts": {
|
|
186
|
+
const last = lastActivity(L);
|
|
187
|
+
const inPool = new Set(pool.accounts);
|
|
188
|
+
return json(accountValues(L, asOf).map((v) => ({ ...v.account, value: v.value, cost: v.cost, qty: v.qty, asset: v.asset, priced: v.priced, price: v.price, lastActivity: last.get(v.account.id) ?? null, pool: inPool.has(v.account.id) })));
|
|
189
|
+
}
|
|
53
190
|
case "transactions": {
|
|
54
191
|
const n = (k) => (q.get(k) ? Number(q.get(k)) : undefined);
|
|
192
|
+
const account = accountParam(q.get("account"));
|
|
193
|
+
const single = typeof account === "string" ? account : null;
|
|
55
194
|
const r = queryTransactions(L, {
|
|
56
195
|
from: q.get("from") ?? undefined,
|
|
57
196
|
to: q.get("to") ?? undefined,
|
|
58
|
-
account
|
|
197
|
+
account,
|
|
198
|
+
who: q.get("who") ?? undefined,
|
|
199
|
+
event: q.get("event") ?? undefined,
|
|
200
|
+
tag: q.get("tag") ?? undefined,
|
|
201
|
+
tx: q.get("tx") ?? undefined,
|
|
202
|
+
plan: q.get("plan") ?? undefined,
|
|
203
|
+
// moves inside the pool are hidden unless asked for, or when looking at one account
|
|
204
|
+
hideWithin: pool.on && !single && q.get("within") !== "1" ? pool.accounts : undefined,
|
|
59
205
|
category: q.get("category") ?? undefined,
|
|
60
206
|
text: q.get("text") ?? undefined,
|
|
61
207
|
min: n("min"),
|
|
@@ -64,11 +210,19 @@ export async function api(req, env) {
|
|
|
64
210
|
offset: n("offset"),
|
|
65
211
|
limit: n("limit") ?? 100,
|
|
66
212
|
});
|
|
213
|
+
if (single) {
|
|
214
|
+
const rb = runningBalance(L, single);
|
|
215
|
+
return json({ ...r, items: r.items.map((t) => ({ ...t, balance: rb.get(t.id) ?? null })) });
|
|
216
|
+
}
|
|
67
217
|
return json(r);
|
|
68
218
|
}
|
|
69
219
|
case "report": {
|
|
70
220
|
const period = q.get("from") && q.get("to") ? { from: q.get("from"), to: q.get("to") } : (q.get("period") ?? asOf.slice(0, 7));
|
|
71
|
-
|
|
221
|
+
if (q.get("usual")) {
|
|
222
|
+
const p = typeof period === "string" ? (period.length === 7 ? { from: `${period}-01`, to: monthEnd(`${period}-01`) } : { from: `${period}-01-01`, to: `${period}-12-31` }) : period;
|
|
223
|
+
return json(usual(L, p, (q.get("by") ?? "top"), { months: Number(q.get("usual")) || 6, kind: q.get("kind") ?? "expense" }));
|
|
224
|
+
}
|
|
225
|
+
return json(report(L, period, { by: (q.get("by") ?? "top"), kind: q.get("kind") ?? undefined, category: q.get("category") ?? undefined, account: typeof accountParam(q.get("account")) === "string" ? q.get("account") : undefined }));
|
|
72
226
|
}
|
|
73
227
|
case "networth":
|
|
74
228
|
return json(netWorthSeries(L, q.get("from") ?? addMonths(asOf.slice(0, 7) + "-01", -23), asOf));
|
|
@@ -96,12 +250,12 @@ export async function api(req, env) {
|
|
|
96
250
|
ok: r.ok, source: r.source, rows: r.rows, new: r.transactions.length, skipped: r.skipped, accounts: r.accounts.map((a) => `${a.id} (${a.type})`),
|
|
97
251
|
reconcile: r.reconcile, rounding: r.rounding, zeroed: r.zeroed, unpaired: r.unpaired.map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
|
|
98
252
|
unresolvedCategories: r.unresolvedCategories, unresolvedRows: r.unresolvedRows.slice(0, 50).map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
|
|
99
|
-
changed: r.changed, gone: r.gone, replace: r.replace.length, errors: r.errors,
|
|
253
|
+
changed: r.changed, gone: r.gone, replace: r.replace.length, errors: r.errors, cardTerms: r.accountUpdates.map((u) => u.id), nameWarnings: r.nameWarnings,
|
|
100
254
|
sample: r.transactions.slice(0, 20),
|
|
101
255
|
};
|
|
102
|
-
if (!r.ok || (!r.transactions.length && !r.accounts.length && !r.replace.length))
|
|
256
|
+
if (!r.ok || (!r.transactions.length && !r.accounts.length && !r.replace.length && !r.accountUpdates.length))
|
|
103
257
|
return json({ report });
|
|
104
|
-
const changed = applyChange(s.files, { addAccounts: r.accounts, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
258
|
+
const changed = applyChange(s.files, { addAccounts: r.accounts, updateAccounts: r.accountUpdates, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
105
259
|
const c = checkFiles({ ...s.files, ...changed });
|
|
106
260
|
if (!c.ok)
|
|
107
261
|
return json({ report: { ...report, ok: false, errors: c.errors.slice(0, 20).map((e) => e.message) } });
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { type ISODate, type Ledger } from "../engine/index.js";
|
|
2
|
+
import { type BestCard as LocalRow } from "../modules/cards/statements.js";
|
|
2
3
|
import type { OpenWallet } from "./openwallet.js";
|
|
3
4
|
export interface BestCardInput {
|
|
4
|
-
amount
|
|
5
|
+
amount?: number;
|
|
6
|
+
/** the owner's category path, e.g. food/groceries: picks the rate from the owner's own terms, and the budget left */
|
|
7
|
+
category?: string;
|
|
8
|
+
/** for OpenWallet: where (Shopee, Co.opmart…) or what kind (groceries, dining…) */
|
|
5
9
|
merchant?: string;
|
|
6
10
|
kind?: string;
|
|
7
11
|
date?: ISODate;
|
|
8
|
-
category?: string;
|
|
9
12
|
accounts?: string[];
|
|
10
13
|
}
|
|
11
14
|
interface NotMatched {
|
|
@@ -18,10 +21,30 @@ interface NotMatched {
|
|
|
18
21
|
name: string;
|
|
19
22
|
}[];
|
|
20
23
|
}
|
|
21
|
-
export declare
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
24
|
+
export declare const clearSearchCache: () => void;
|
|
25
|
+
/** One card in the answer, whichever source its cashback comes from. */
|
|
26
|
+
export interface BestCardRow extends LocalRow {
|
|
27
|
+
/** where the cashback figure comes from: the owner's own terms, OpenWallet, or none known */
|
|
28
|
+
source: "yours" | "openwallet" | "none";
|
|
29
|
+
status?: string;
|
|
30
|
+
spend_so_far?: number;
|
|
31
|
+
cap_used?: number;
|
|
32
|
+
openwallet?: {
|
|
33
|
+
id: string;
|
|
34
|
+
name: string;
|
|
35
|
+
url: string | null;
|
|
36
|
+
lastChecked: string | null;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet | null, input: BestCardInput): Promise<{
|
|
40
|
+
purchase: {
|
|
41
|
+
amount: number | null;
|
|
42
|
+
date: string;
|
|
43
|
+
category: string | null;
|
|
44
|
+
merchant: string | null;
|
|
45
|
+
kind: string | null;
|
|
46
|
+
};
|
|
47
|
+
cards: BestCardRow[];
|
|
25
48
|
not_matched?: NotMatched[] | undefined;
|
|
26
49
|
budget?: {
|
|
27
50
|
category: string;
|
|
@@ -39,11 +62,11 @@ export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet, input
|
|
|
39
62
|
none: boolean;
|
|
40
63
|
} | undefined;
|
|
41
64
|
assumptions: string[];
|
|
42
|
-
|
|
43
|
-
name: string;
|
|
65
|
+
openwallet?: {
|
|
44
66
|
url: string;
|
|
45
67
|
catalog: unknown;
|
|
46
|
-
|
|
68
|
+
what: string;
|
|
69
|
+
} | undefined;
|
|
47
70
|
note: string;
|
|
48
71
|
}>;
|
|
49
72
|
export {};
|