ownledger 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AGENTS.md +93 -0
  2. package/CHANGELOG.md +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +102 -2
  5. package/assets/_headers +5 -0
  6. package/assets/app.css +61 -0
  7. package/assets/app.js +369 -0
  8. package/assets/icon.svg +1 -0
  9. package/assets/index.html +30 -0
  10. package/assets/manifest.webmanifest +1 -0
  11. package/dist/cli/check.d.ts +3 -0
  12. package/dist/cli/check.js +21 -0
  13. package/dist/cli/deploy.d.ts +1 -0
  14. package/dist/cli/deploy.js +258 -0
  15. package/dist/cli/dev.d.ts +3 -0
  16. package/dist/cli/dev.js +107 -0
  17. package/dist/cli/import.d.ts +3 -0
  18. package/dist/cli/import.js +151 -0
  19. package/dist/cli/index.d.ts +2 -0
  20. package/dist/cli/index.js +47 -0
  21. package/dist/cli/init.d.ts +1 -0
  22. package/dist/cli/init.js +73 -0
  23. package/dist/cli/jsonc.d.ts +2 -0
  24. package/dist/cli/jsonc.js +39 -0
  25. package/dist/engine/actions.d.ts +53 -0
  26. package/dist/engine/actions.js +205 -0
  27. package/dist/engine/balances.d.ts +30 -0
  28. package/dist/engine/balances.js +75 -0
  29. package/dist/engine/categories.d.ts +17 -0
  30. package/dist/engine/categories.js +35 -0
  31. package/dist/engine/check.d.ts +11 -0
  32. package/dist/engine/check.js +220 -0
  33. package/dist/engine/dates.d.ts +15 -0
  34. package/dist/engine/dates.js +56 -0
  35. package/dist/engine/defaults.d.ts +2 -0
  36. package/dist/engine/defaults.js +61 -0
  37. package/dist/engine/index.d.ts +13 -0
  38. package/dist/engine/index.js +13 -0
  39. package/dist/engine/load.d.ts +23 -0
  40. package/dist/engine/load.js +129 -0
  41. package/dist/engine/networth.d.ts +12 -0
  42. package/dist/engine/networth.js +73 -0
  43. package/dist/engine/registry.d.ts +24 -0
  44. package/dist/engine/registry.js +41 -0
  45. package/dist/engine/reports.d.ts +68 -0
  46. package/dist/engine/reports.js +149 -0
  47. package/dist/engine/schedules.d.ts +75 -0
  48. package/dist/engine/schedules.js +208 -0
  49. package/dist/engine/types.d.ts +122 -0
  50. package/dist/engine/types.js +2 -0
  51. package/dist/engine/write.d.ts +30 -0
  52. package/dist/engine/write.js +105 -0
  53. package/dist/import/hash.d.ts +1 -0
  54. package/dist/import/hash.js +17 -0
  55. package/dist/import/index.d.ts +6 -0
  56. package/dist/import/index.js +6 -0
  57. package/dist/import/mapping.d.ts +96 -0
  58. package/dist/import/mapping.js +54 -0
  59. package/dist/import/profile.d.ts +39 -0
  60. package/dist/import/profile.js +125 -0
  61. package/dist/import/run.d.ts +101 -0
  62. package/dist/import/run.js +416 -0
  63. package/dist/import/workbook.d.ts +13 -0
  64. package/dist/import/workbook.js +168 -0
  65. package/dist/import/xlsx-write.d.ts +6 -0
  66. package/dist/import/xlsx-write.js +38 -0
  67. package/dist/node/files.d.ts +3 -0
  68. package/dist/node/files.js +26 -0
  69. package/dist/node/scaffold.d.ts +14 -0
  70. package/dist/node/scaffold.js +45 -0
  71. package/dist/worker/api.d.ts +3 -0
  72. package/dist/worker/api.js +139 -0
  73. package/dist/worker/auth.d.ts +11 -0
  74. package/dist/worker/auth.js +176 -0
  75. package/dist/worker/env.d.ts +25 -0
  76. package/dist/worker/env.js +6 -0
  77. package/dist/worker/github.d.ts +29 -0
  78. package/dist/worker/github.js +154 -0
  79. package/dist/worker/index.d.ts +5 -0
  80. package/dist/worker/index.js +64 -0
  81. package/dist/worker/mcp.d.ts +4 -0
  82. package/dist/worker/mcp.js +292 -0
  83. package/dist/worker/store.d.ts +42 -0
  84. package/dist/worker/store.js +92 -0
  85. package/dist/worker/tar.d.ts +2 -0
  86. package/dist/worker/tar.js +62 -0
  87. package/dist/worker/version.d.ts +1 -0
  88. package/dist/worker/version.js +2 -0
  89. package/package.json +68 -4
  90. package/presets/misa.mapping.yaml +48 -0
  91. package/templates/repo/.github/dependabot.yml +11 -0
  92. package/templates/repo/.github/workflows/check.yml +15 -0
  93. package/templates/repo/.github/workflows/deploy.yml +21 -0
  94. package/templates/repo/README.md +10 -0
@@ -0,0 +1,41 @@
1
+ export const TYPES = {
2
+ cash: { label: { en: "Cash", vi: "Tiền mặt" }, liquid: true },
3
+ bank: { label: { en: "Bank account", vi: "Tài khoản ngân hàng" }, liquid: true, details: { bank: { kind: "string" }, number_last4: { kind: "string" } } },
4
+ ewallet: { label: { en: "E-wallet", vi: "Ví điện tử" }, liquid: true, details: { provider: { kind: "string" } } },
5
+ credit_card: {
6
+ label: { en: "Credit card", vi: "Thẻ tín dụng" },
7
+ liability: true,
8
+ details: {
9
+ statement_day: { kind: "day", note: "day of month the statement closes" },
10
+ due_day: { kind: "day", note: "day of month payment is due" },
11
+ limit: { kind: "int" },
12
+ bank: { kind: "string" },
13
+ },
14
+ },
15
+ 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" } } },
16
+ deposit: {
17
+ label: { en: "Term deposit", vi: "Tiền gửi có kỳ hạn" },
18
+ details: {
19
+ bank: { kind: "string" },
20
+ principal: { kind: "int" },
21
+ rate: { kind: "number", note: "annual %" },
22
+ term_months: { kind: "int" },
23
+ start: { kind: "date" },
24
+ maturity: { kind: "date" },
25
+ rollover: { kind: "string", note: "none | principal | principal_interest" },
26
+ },
27
+ },
28
+ savings_goal: { label: { en: "Savings goal", vi: "Mục tiêu tiết kiệm" }, details: { target: { kind: "int" }, by: { kind: "date" } } },
29
+ gold: { label: { en: "Gold", vi: "Vàng" }, holdings: true },
30
+ fund: { label: { en: "Fund", vi: "Chứng chỉ quỹ" }, holdings: true, details: { broker: { kind: "string" } } },
31
+ stock: { label: { en: "Stocks", vi: "Cổ phiếu" }, holdings: true, details: { broker: { kind: "string" } } },
32
+ etf: { label: { en: "ETF", vi: "Quỹ ETF" }, holdings: true, details: { broker: { kind: "string" } } },
33
+ crypto: { label: { en: "Crypto", vi: "Tiền mã hoá" }, holdings: true },
34
+ insurance: { label: { en: "Insurance", vi: "Bảo hiểm" }, details: { insurer: { kind: "string" }, cash_value: { kind: "int" } } },
35
+ loan_given: { label: { en: "Loan given", vi: "Cho vay" }, details: { borrower: { kind: "string" }, rate: { kind: "number" } } },
36
+ loan_taken: { label: { en: "Loan taken", vi: "Đi vay" }, liability: true, details: { lender: { kind: "string" }, rate: { kind: "number" } } },
37
+ other: { label: { en: "Other", vi: "Khác" } },
38
+ };
39
+ export function typeDef(type) {
40
+ return Object.prototype.hasOwnProperty.call(TYPES, type) ? TYPES[type] : undefined;
41
+ }
@@ -0,0 +1,68 @@
1
+ import type { ISODate, Ledger, Transaction } from "./types.js";
2
+ export interface Period {
3
+ from: ISODate;
4
+ to: ISODate;
5
+ }
6
+ /** "2026-11" → that month; "2026" → that year; {from,to} as given. */
7
+ export declare function periodOf(spec: string | Period): Period;
8
+ /** The period of the same shape just before. Whole months/years step by month/year; other spans by days. */
9
+ export declare function previousPeriod(p: Period): Period;
10
+ export type GroupBy = "category" | "top" | "account" | "who" | "event" | "tag" | "month";
11
+ export interface ReportRow {
12
+ key: string;
13
+ name: string;
14
+ income: number;
15
+ expense: number;
16
+ count: number;
17
+ }
18
+ export interface Report {
19
+ period: Period;
20
+ by: GroupBy;
21
+ kind?: "income" | "expense";
22
+ income: number;
23
+ expense: number;
24
+ net: number;
25
+ rows: ReportRow[];
26
+ previous?: {
27
+ period: Period;
28
+ income: number;
29
+ expense: number;
30
+ net: number;
31
+ rows: Record<string, {
32
+ income: number;
33
+ expense: number;
34
+ }>;
35
+ };
36
+ }
37
+ interface ReportOpts {
38
+ by?: GroupBy;
39
+ kind?: "income" | "expense";
40
+ compare?: boolean;
41
+ /** Only lines under this category path (prefix). */
42
+ category?: string;
43
+ account?: string;
44
+ }
45
+ export declare function report(l: Ledger, period: string | Period, o?: ReportOpts): Report;
46
+ export interface TxQuery {
47
+ from?: ISODate;
48
+ to?: ISODate;
49
+ account?: string;
50
+ category?: string;
51
+ text?: string;
52
+ min?: number;
53
+ max?: number;
54
+ plan?: string;
55
+ includeVoid?: boolean;
56
+ offset?: number;
57
+ limit?: number;
58
+ }
59
+ /** Lowercase, no Vietnamese diacritics (đ → d), for search. */
60
+ export declare function fold(s: string): string;
61
+ export declare function txSize(t: Transaction): number;
62
+ export declare function queryTransactions(l: Ledger, q: TxQuery): {
63
+ total: number;
64
+ items: Transaction[];
65
+ };
66
+ /** Month keys "yyyy-mm" from first to last inclusive. */
67
+ export declare function monthsBetween(from: ISODate, to: ISODate): string[];
68
+ export {};
@@ -0,0 +1,149 @@
1
+ import { flattenCategories, isSystemCategory, topOf } from "./categories.js";
2
+ import { addDays, addMonths, daysBetween, monthEnd, monthStart, parts, fmt } from "./dates.js";
3
+ /** "2026-11" → that month; "2026" → that year; {from,to} as given. */
4
+ export function periodOf(spec) {
5
+ if (typeof spec !== "string")
6
+ return spec;
7
+ if (/^\d{4}-\d{2}$/.test(spec))
8
+ return { from: `${spec}-01`, to: monthEnd(`${spec}-01`) };
9
+ if (/^\d{4}$/.test(spec))
10
+ return { from: `${spec}-01-01`, to: `${spec}-12-31` };
11
+ throw new Error(`bad period "${spec}" (use yyyy-mm, yyyy, or from/to dates)`);
12
+ }
13
+ /** The period of the same shape just before. Whole months/years step by month/year; other spans by days. */
14
+ export function previousPeriod(p) {
15
+ const wholeMonths = p.from === monthStart(p.from) && p.to === monthEnd(p.to);
16
+ if (wholeMonths) {
17
+ const [fy, fm] = parts(p.from);
18
+ const [ty, tm] = parts(p.to);
19
+ const n = (ty - fy) * 12 + (tm - fm) + 1;
20
+ const from = addMonths(p.from, -n);
21
+ return { from, to: monthEnd(addMonths(from, n - 1)) };
22
+ }
23
+ const len = daysBetween(p.from, p.to) + 1;
24
+ return { from: addDays(p.from, -len), to: addDays(p.from, -1) };
25
+ }
26
+ function inPeriod(t, p) {
27
+ return t.date >= p.from && t.date <= p.to;
28
+ }
29
+ function aggregate(l, p, cats, o) {
30
+ const by = o.by ?? "category";
31
+ const accName = new Map(l.accounts.map((a) => [a.id, a.name]));
32
+ const rows = new Map();
33
+ let income = 0;
34
+ let expense = 0;
35
+ for (const t of l.transactions) {
36
+ if (t.void || !inPeriod(t, p))
37
+ continue;
38
+ if (o.account && !t.lines.some((ln) => ln.account === o.account))
39
+ continue;
40
+ const firstAccount = t.lines.find((ln) => ln.account != null)?.account ?? "(none)";
41
+ const counted = new Set();
42
+ for (const ln of t.lines) {
43
+ if (ln.category == null || isSystemCategory(ln.category))
44
+ continue;
45
+ if (o.category && !(ln.category === o.category || ln.category.startsWith(o.category + "/")))
46
+ continue;
47
+ const c = cats.get(ln.category);
48
+ const kind = c?.kind ?? "expense";
49
+ if (o.kind && kind !== o.kind)
50
+ continue;
51
+ const inc = kind === "income" ? -ln.amount : 0;
52
+ const exp = kind === "expense" ? ln.amount : 0;
53
+ income += inc;
54
+ expense += exp;
55
+ const keys = by === "category" ? [[ln.category, c?.name ?? ln.category]]
56
+ : by === "top" ? [[topOf(ln.category), cats.get(topOf(ln.category))?.name ?? topOf(ln.category)]]
57
+ : by === "account" ? [[firstAccount, accName.get(firstAccount) ?? firstAccount]]
58
+ : by === "who" ? [[t.who ?? "(none)", t.who ?? "(none)"]]
59
+ : by === "event" ? [[t.event ?? "(none)", t.event ?? "(none)"]]
60
+ : by === "month" ? [[t.date.slice(0, 7), t.date.slice(0, 7)]]
61
+ : (t.tags?.length ? t.tags : ["(none)"]).map((g) => [g, g]);
62
+ for (const [key, name] of keys) {
63
+ const r = rows.get(key) ?? { key, name, income: 0, expense: 0, count: 0 };
64
+ r.income += inc;
65
+ r.expense += exp;
66
+ if (!counted.has(key)) {
67
+ r.count++;
68
+ counted.add(key);
69
+ }
70
+ rows.set(key, r);
71
+ }
72
+ }
73
+ }
74
+ return { income, expense, rows };
75
+ }
76
+ export function report(l, period, o = {}) {
77
+ const p = periodOf(period);
78
+ const { map: cats } = flattenCategories(l.categories);
79
+ const cur = aggregate(l, p, cats, o);
80
+ const rows = [...cur.rows.values()].sort((a, b) => b.expense + b.income - (a.expense + a.income));
81
+ const out = { period: p, by: o.by ?? "category", kind: o.kind, income: cur.income, expense: cur.expense, net: cur.income - cur.expense, rows };
82
+ if (o.compare !== false) {
83
+ const pp = previousPeriod(p);
84
+ const prev = aggregate(l, pp, cats, o);
85
+ out.previous = {
86
+ period: pp,
87
+ income: prev.income,
88
+ expense: prev.expense,
89
+ net: prev.income - prev.expense,
90
+ rows: Object.fromEntries([...prev.rows.values()].map((r) => [r.key, { income: r.income, expense: r.expense }])),
91
+ };
92
+ }
93
+ return out;
94
+ }
95
+ /** Lowercase, no Vietnamese diacritics (đ → d), for search. */
96
+ export function fold(s) {
97
+ return s.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/đ/g, "d").replace(/Đ/g, "d").toLowerCase();
98
+ }
99
+ export function txSize(t) {
100
+ return t.lines.reduce((s, ln) => s + (ln.amount > 0 ? ln.amount : 0), 0);
101
+ }
102
+ export function queryTransactions(l, q) {
103
+ const text = q.text ? fold(q.text) : "";
104
+ const hits = [];
105
+ for (let i = l.transactions.length - 1; i >= 0; i--) {
106
+ const t = l.transactions[i];
107
+ if (t.void && !q.includeVoid)
108
+ continue;
109
+ if (q.from && t.date < q.from)
110
+ continue;
111
+ if (q.to && t.date > q.to)
112
+ continue;
113
+ if (q.account && !t.lines.some((ln) => ln.account === q.account))
114
+ continue;
115
+ if (q.category && !t.lines.some((ln) => ln.category === q.category || ln.category?.startsWith(q.category + "/")))
116
+ continue;
117
+ if (q.plan && t.plan !== q.plan)
118
+ continue;
119
+ const size = txSize(t);
120
+ if (q.min !== undefined && size < q.min)
121
+ continue;
122
+ if (q.max !== undefined && size > q.max)
123
+ continue;
124
+ if (text) {
125
+ const hay = fold([t.note, t.who, t.event, ...(t.tags ?? []), ...t.lines.map((ln) => ln.note)].filter(Boolean).join(" "));
126
+ if (!hay.includes(text))
127
+ continue;
128
+ }
129
+ hits.push(t);
130
+ }
131
+ const offset = q.offset ?? 0;
132
+ const limit = Math.min(q.limit ?? 50, 500);
133
+ return { total: hits.length, items: hits.slice(offset, offset + limit) };
134
+ }
135
+ /** Month keys "yyyy-mm" from first to last inclusive. */
136
+ export function monthsBetween(from, to) {
137
+ const out = [];
138
+ let [y, m] = parts(from);
139
+ const [ty, tm] = parts(to);
140
+ while (y < ty || (y === ty && m <= tm)) {
141
+ out.push(fmt(y, m, 1).slice(0, 7));
142
+ m++;
143
+ if (m > 12) {
144
+ m = 1;
145
+ y++;
146
+ }
147
+ }
148
+ return out;
149
+ }
@@ -0,0 +1,75 @@
1
+ import type { ISODate, Ledger, Plan } from "./types.js";
2
+ export interface CardStatus {
3
+ account: string;
4
+ name: string;
5
+ owed: number;
6
+ limit: number | null;
7
+ available: number | null;
8
+ statementDate: ISODate | null;
9
+ statementBalance: number | null;
10
+ paidSinceStatement: number;
11
+ toPay: number | null;
12
+ dueDate: ISODate | null;
13
+ daysToDue: number | null;
14
+ }
15
+ export declare function cards(l: Ledger, asOf: ISODate): CardStatus[];
16
+ export interface PlanStatus {
17
+ plan: string;
18
+ name: string;
19
+ kind: string;
20
+ account: string;
21
+ perPayment: number;
22
+ count: number | null;
23
+ paidCount: number;
24
+ paidAmount: number;
25
+ left: number | null;
26
+ leftAmount: number | null;
27
+ next: ISODate | null;
28
+ overdue: ISODate[];
29
+ finished: boolean;
30
+ }
31
+ export declare function perPayment(p: Plan): number;
32
+ /** Due dates of a plan, the first `n` (or until `until`). */
33
+ export declare function dueDates(p: Plan, until: ISODate, max?: number): ISODate[];
34
+ export declare function planStatus(l: Ledger, asOf: ISODate): PlanStatus[];
35
+ export interface DueItem {
36
+ plan: string;
37
+ name: string;
38
+ account: string;
39
+ date: ISODate;
40
+ amount: number;
41
+ overdue: boolean;
42
+ }
43
+ /** Plan payments due from (earliest unpaid) through asOf + days. */
44
+ export declare function plansDue(l: Ledger, asOf: ISODate, days?: number): DueItem[];
45
+ export interface DepositStatus {
46
+ account: string;
47
+ name: string;
48
+ balance: number;
49
+ principal: number;
50
+ rate: number | null;
51
+ start: ISODate | null;
52
+ maturity: ISODate | null;
53
+ daysToMaturity: number | null;
54
+ interestAtMaturity: number | null;
55
+ rollover: string | null;
56
+ }
57
+ export declare function deposits(l: Ledger, asOf: ISODate): DepositStatus[];
58
+ export interface BudgetStatus {
59
+ category: string;
60
+ every: "month" | "year";
61
+ amount: number;
62
+ spent: number;
63
+ left: number;
64
+ over: boolean;
65
+ }
66
+ export declare function budgets(l: Ledger, asOf: ISODate): BudgetStatus[];
67
+ export interface Today {
68
+ date: ISODate;
69
+ due: DueItem[];
70
+ cards: CardStatus[];
71
+ maturing: DepositStatus[];
72
+ overBudget: BudgetStatus[];
73
+ odd: string[];
74
+ }
75
+ export declare function today(l: Ledger, asOf: ISODate): Today;
@@ -0,0 +1,208 @@
1
+ import { holdingsAt } from "./balances.js";
2
+ import { flattenCategories } from "./categories.js";
3
+ import { addDays, addMonths, dayIn, daysBetween, isDate, monthEnd, monthStart, parts } from "./dates.js";
4
+ import { typeDef } from "./registry.js";
5
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
6
+ const day = (v) => (Number.isInteger(v) && v >= 1 && v <= 31 ? v : undefined);
7
+ const date = (v) => (isDate(v) ? v : undefined);
8
+ const open = (a, asOf) => !(isDate(a.closed) && a.closed <= asOf);
9
+ export function cards(l, asOf) {
10
+ const now = holdingsAt(l, asOf);
11
+ const out = [];
12
+ for (const a of l.accounts) {
13
+ if (a.type !== "credit_card" || !open(a, asOf))
14
+ continue;
15
+ const d = a.details ?? {};
16
+ const sd = day(d.statement_day);
17
+ const dd = day(d.due_day);
18
+ const limit = num(d.limit) ?? null;
19
+ const owed = -(now.get(a.id)?.amount ?? 0);
20
+ let statementDate = null;
21
+ let statementBalance = null;
22
+ let paid = 0;
23
+ let dueDate = null;
24
+ if (sd) {
25
+ const [y, m] = parts(asOf);
26
+ statementDate = dayIn(y, m, sd);
27
+ if (statementDate > asOf) {
28
+ const prev = addMonths(`${asOf.slice(0, 7)}-01`, -1);
29
+ statementDate = dayIn(...parts(prev).slice(0, 2), sd);
30
+ }
31
+ statementBalance = -(holdingsAt(l, statementDate).get(a.id)?.amount ?? 0);
32
+ for (const t of l.transactions) {
33
+ if (t.void || t.date <= statementDate || t.date > asOf)
34
+ continue;
35
+ for (const ln of t.lines)
36
+ if (ln.account === a.id && ln.amount > 0)
37
+ paid += ln.amount;
38
+ }
39
+ if (dd) {
40
+ const [sy, sm] = parts(statementDate);
41
+ dueDate = dayIn(sy, sm, dd);
42
+ if (dueDate <= statementDate) {
43
+ const nx = addMonths(`${statementDate.slice(0, 7)}-01`, 1);
44
+ dueDate = dayIn(...parts(nx).slice(0, 2), dd);
45
+ }
46
+ }
47
+ }
48
+ const toPay = statementBalance === null ? null : Math.max(0, statementBalance - paid);
49
+ out.push({
50
+ account: a.id,
51
+ name: a.name,
52
+ owed,
53
+ limit,
54
+ available: limit === null ? null : limit - owed,
55
+ statementDate,
56
+ statementBalance,
57
+ paidSinceStatement: paid,
58
+ toPay,
59
+ dueDate,
60
+ daysToDue: dueDate ? daysBetween(asOf, dueDate) : null,
61
+ });
62
+ }
63
+ return out;
64
+ }
65
+ const STEP = { month: 1, quarter: 3, year: 12 };
66
+ export function perPayment(p) {
67
+ if (p.amount !== undefined)
68
+ return p.amount + (p.fee ?? 0);
69
+ if (p.principal !== undefined && p.count)
70
+ return Math.round(p.principal / p.count) + (p.fee ?? 0);
71
+ return 0;
72
+ }
73
+ /** Due dates of a plan, the first `n` (or until `until`). */
74
+ export function dueDates(p, until, max = 1000) {
75
+ const out = [];
76
+ const step = STEP[p.every] ?? 1;
77
+ const d0 = parts(p.start)[2];
78
+ for (let i = 0; i < max; i++) {
79
+ if (p.count !== undefined && i >= p.count)
80
+ break;
81
+ const d = addMonths(p.start, i * step, d0);
82
+ if (d > until)
83
+ break;
84
+ if (p.end && d > p.end)
85
+ break;
86
+ out.push(d);
87
+ }
88
+ return out;
89
+ }
90
+ export function planStatus(l, asOf) {
91
+ const paid = new Map();
92
+ const accOf = new Map(l.plans.map((p) => [p.id, p.account]));
93
+ for (const t of l.transactions) {
94
+ if (t.void || !t.plan)
95
+ continue;
96
+ const acc = accOf.get(t.plan);
97
+ const s = paid.get(t.plan) ?? { n: 0, amount: 0 };
98
+ s.n++;
99
+ s.amount += t.lines.filter((ln) => ln.account === acc).reduce((x, ln) => x + Math.abs(ln.amount), 0);
100
+ paid.set(t.plan, s);
101
+ }
102
+ return l.plans.map((p) => {
103
+ const per = perPayment(p);
104
+ const s = paid.get(p.id) ?? { n: 0, amount: 0 };
105
+ const horizon = addDays(asOf, 3660);
106
+ const all = dueDates(p, horizon);
107
+ const dueByNow = all.filter((d) => d <= asOf);
108
+ const overdue = dueByNow.slice(s.n);
109
+ const next = all[s.n] ?? null;
110
+ const count = p.count ?? null;
111
+ const left = count === null ? null : Math.max(0, count - s.n);
112
+ return {
113
+ plan: p.id,
114
+ name: p.name ?? p.note ?? p.id,
115
+ kind: p.kind,
116
+ account: p.account,
117
+ perPayment: per,
118
+ count,
119
+ paidCount: s.n,
120
+ paidAmount: s.amount,
121
+ left,
122
+ leftAmount: left === null ? null : left * per,
123
+ next,
124
+ overdue,
125
+ finished: left === 0 || (Boolean(p.end) && !next),
126
+ };
127
+ });
128
+ }
129
+ /** Plan payments due from (earliest unpaid) through asOf + days. */
130
+ export function plansDue(l, asOf, days = 30) {
131
+ const until = addDays(asOf, days);
132
+ const out = [];
133
+ for (const st of planStatus(l, asOf)) {
134
+ const p = l.plans.find((x) => x.id === st.plan);
135
+ const dates = dueDates(p, until).slice(st.paidCount);
136
+ for (const d of dates)
137
+ out.push({ plan: p.id, name: st.name, account: p.account, date: d, amount: st.perPayment, overdue: d < asOf });
138
+ }
139
+ return out.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
140
+ }
141
+ export function deposits(l, asOf) {
142
+ const hs = holdingsAt(l, asOf);
143
+ const out = [];
144
+ for (const a of l.accounts) {
145
+ if (a.type !== "deposit" || !open(a, asOf))
146
+ continue;
147
+ const d = a.details ?? {};
148
+ const balance = hs.get(a.id)?.amount ?? 0;
149
+ const principal = num(d.principal) ?? balance;
150
+ const rate = num(d.rate) ?? null;
151
+ const start = date(d.start) ?? date(a.opened) ?? null;
152
+ const term = num(d.term_months);
153
+ const maturity = date(d.maturity) ?? (start && term ? addMonths(start, term) : null);
154
+ const interest = rate !== null && start && maturity ? Math.round((principal * rate * daysBetween(start, maturity)) / 36500) : null;
155
+ out.push({
156
+ account: a.id,
157
+ name: a.name,
158
+ balance,
159
+ principal,
160
+ rate,
161
+ start,
162
+ maturity,
163
+ daysToMaturity: maturity ? daysBetween(asOf, maturity) : null,
164
+ interestAtMaturity: interest,
165
+ rollover: typeof d.rollover === "string" ? d.rollover : null,
166
+ });
167
+ }
168
+ return out.sort((a, b) => (a.maturity ?? "9999") < (b.maturity ?? "9999") ? -1 : 1);
169
+ }
170
+ export function budgets(l, asOf) {
171
+ const { map } = flattenCategories(l.categories);
172
+ return l.budgets.map((b) => {
173
+ const every = b.every ?? "month";
174
+ const from = every === "month" ? monthStart(asOf) : `${asOf.slice(0, 4)}-01-01`;
175
+ const to = every === "month" ? monthEnd(asOf) : `${asOf.slice(0, 4)}-12-31`;
176
+ const kind = map.get(b.category)?.kind ?? "expense";
177
+ let spent = 0;
178
+ for (const t of l.transactions) {
179
+ if (t.void || t.date < from || t.date > to)
180
+ continue;
181
+ for (const ln of t.lines) {
182
+ if (ln.category === b.category || ln.category?.startsWith(b.category + "/"))
183
+ spent += kind === "income" ? -ln.amount : ln.amount;
184
+ }
185
+ }
186
+ return { category: b.category, every, amount: b.amount, spent, left: b.amount - spent, over: spent > b.amount };
187
+ });
188
+ }
189
+ export function today(l, asOf) {
190
+ const odd = [];
191
+ const hs = holdingsAt(l, asOf);
192
+ for (const a of l.accounts) {
193
+ if (!open(a, asOf))
194
+ continue;
195
+ const v = hs.get(a.id)?.amount ?? 0;
196
+ const def = typeDef(a.type);
197
+ if (v < 0 && def && !def.liability && !def.holdings)
198
+ odd.push(`${a.name} (${a.id}) is negative: ${v}`);
199
+ }
200
+ return {
201
+ date: asOf,
202
+ due: plansDue(l, asOf, 7),
203
+ cards: cards(l, asOf).filter((c) => (c.toPay ?? 0) > 0 && c.daysToDue !== null && c.daysToDue <= 10),
204
+ maturing: deposits(l, asOf).filter((d) => d.daysToMaturity !== null && d.daysToMaturity <= 30),
205
+ overBudget: budgets(l, asOf).filter((b) => b.over),
206
+ odd,
207
+ };
208
+ }
@@ -0,0 +1,122 @@
1
+ /** Data format version this package reads and writes. Bump only in a major release, with a migration. */
2
+ export declare const FORMAT = 1;
3
+ export type ISODate = string;
4
+ export interface Meta {
5
+ format: number;
6
+ base: string;
7
+ locale?: string;
8
+ owner?: string;
9
+ name?: string;
10
+ [k: string]: unknown;
11
+ }
12
+ export interface Asset {
13
+ id: string;
14
+ name?: string;
15
+ kind?: string;
16
+ unit?: string;
17
+ decimals?: number;
18
+ [k: string]: unknown;
19
+ }
20
+ export interface Account {
21
+ id: string;
22
+ name: string;
23
+ type: string;
24
+ asset?: string;
25
+ opened?: ISODate;
26
+ closed?: ISODate | null;
27
+ group?: string;
28
+ note?: string;
29
+ details?: Record<string, unknown>;
30
+ [k: string]: unknown;
31
+ }
32
+ export type CategoryKind = "income" | "expense";
33
+ export interface CategoryNode {
34
+ id: string;
35
+ name: string;
36
+ children?: CategoryNode[];
37
+ [k: string]: unknown;
38
+ }
39
+ export interface CategoriesFile {
40
+ income: CategoryNode[];
41
+ expense: CategoryNode[];
42
+ }
43
+ export interface Category {
44
+ path: string;
45
+ name: string;
46
+ kind: CategoryKind;
47
+ parent: string | null;
48
+ }
49
+ export interface Line {
50
+ account?: string;
51
+ category?: string;
52
+ amount: number;
53
+ asset?: string;
54
+ qty?: number;
55
+ note?: string;
56
+ [k: string]: unknown;
57
+ }
58
+ export interface Transaction {
59
+ id: string;
60
+ date: ISODate;
61
+ time?: string | null;
62
+ note?: string;
63
+ tags?: string[];
64
+ who?: string | null;
65
+ event?: string | null;
66
+ plan?: string | null;
67
+ void?: boolean;
68
+ lines: Line[];
69
+ src?: {
70
+ import: string;
71
+ key: string;
72
+ [k: string]: unknown;
73
+ };
74
+ [k: string]: unknown;
75
+ }
76
+ export type PlanKind = "instalment" | "bnpl" | "loan_taken" | "loan_given" | "insurance_premium" | "deposit" | string;
77
+ export interface Plan {
78
+ id: string;
79
+ kind: PlanKind;
80
+ account: string;
81
+ name?: string;
82
+ principal?: number;
83
+ count?: number;
84
+ every: "month" | "quarter" | "year";
85
+ start: ISODate;
86
+ amount?: number;
87
+ fee?: number;
88
+ rate?: number;
89
+ end?: ISODate | null;
90
+ note?: string;
91
+ [k: string]: unknown;
92
+ }
93
+ export interface Budget {
94
+ category: string;
95
+ amount: number;
96
+ every?: "month" | "year";
97
+ [k: string]: unknown;
98
+ }
99
+ export interface Price {
100
+ date: ISODate;
101
+ asset: string;
102
+ price: number;
103
+ }
104
+ export interface Ledger {
105
+ meta: Meta;
106
+ assets: Asset[];
107
+ accounts: Account[];
108
+ categories: CategoriesFile;
109
+ plans: Plan[];
110
+ budgets: Budget[];
111
+ prices: Price[];
112
+ /** All transactions, sorted by date, time, then file order. Includes void ones. */
113
+ transactions: Transaction[];
114
+ /** Which file each transaction came from (for check messages). */
115
+ txFile: Map<string, string>;
116
+ }
117
+ export interface Issue {
118
+ level: "error" | "warning";
119
+ file?: string;
120
+ where?: string;
121
+ message: string;
122
+ }
@@ -0,0 +1,2 @@
1
+ /** Data format version this package reads and writes. Bump only in a major release, with a migration. */
2
+ export const FORMAT = 1;