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,220 @@
1
+ import { flattenCategories, isSystemCategory, SYSTEM_CATEGORIES } from "./categories.js";
2
+ import { isDate } from "./dates.js";
3
+ import { ledgerPath, loadLedger, PATHS } from "./load.js";
4
+ import { typeDef } from "./registry.js";
5
+ import { FORMAT } from "./types.js";
6
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
7
+ const EVERY = new Set(["month", "quarter", "year"]);
8
+ /** Load + check. `ok` is false when there is any error. Warnings never fail. */
9
+ export function checkFiles(files) {
10
+ const { ledger, issues } = loadLedger(files);
11
+ const all = [...issues, ...checkLedger(ledger)];
12
+ const errors = all.filter((i) => i.level === "error");
13
+ const warnings = all.filter((i) => i.level === "warning");
14
+ return { ok: errors.length === 0, errors, warnings, ledger };
15
+ }
16
+ export function checkLedger(l) {
17
+ const out = [];
18
+ const err = (file, where, message) => out.push({ level: "error", file, where, message });
19
+ const warn = (file, where, message) => out.push({ level: "warning", file, where, message });
20
+ // meta
21
+ const fmt = l.meta.format;
22
+ if (typeof fmt !== "number" || fmt < 1)
23
+ err(PATHS.meta, "format", "missing or invalid format version");
24
+ else if (fmt > FORMAT)
25
+ err(PATHS.meta, "format", `data is format ${fmt}; this ownledger reads format ${FORMAT}. Update ownledger.`);
26
+ else if (fmt < FORMAT)
27
+ err(PATHS.meta, "format", `data is format ${fmt}; this ownledger needs format ${FORMAT}. Run \`npx ownledger migrate\`.`);
28
+ const base = l.meta.base;
29
+ if (typeof base !== "string" || !base)
30
+ err(PATHS.meta, "base", "missing base currency");
31
+ // assets
32
+ const assets = new Set([String(base)]);
33
+ const seenAsset = new Set();
34
+ l.assets.forEach((a, i) => {
35
+ const w = `#${i + 1}`;
36
+ if (!a || typeof a.id !== "string" || !a.id)
37
+ return err(PATHS.assets, w, "asset without id");
38
+ if (seenAsset.has(a.id))
39
+ err(PATHS.assets, a.id, "duplicate asset id");
40
+ seenAsset.add(a.id);
41
+ assets.add(a.id);
42
+ });
43
+ // accounts
44
+ const accounts = new Map();
45
+ l.accounts.forEach((a, i) => {
46
+ const w = a && typeof a.id === "string" ? a.id : `#${i + 1}`;
47
+ if (!a || typeof a !== "object")
48
+ return err(PATHS.accounts, w, "not an object");
49
+ if (typeof a.id !== "string" || !ID_RE.test(a.id))
50
+ return err(PATHS.accounts, w, "id must be letters, digits, . _ - (no spaces)");
51
+ if (accounts.has(a.id))
52
+ err(PATHS.accounts, w, "duplicate account id");
53
+ accounts.set(a.id, a);
54
+ if (typeof a.name !== "string" || !a.name)
55
+ err(PATHS.accounts, w, "missing name");
56
+ if (typeof a.type !== "string" || !a.type)
57
+ err(PATHS.accounts, w, "missing type");
58
+ else if (!typeDef(a.type))
59
+ warn(PATHS.accounts, w, `unknown type "${a.type}": treated as a plain account (balance only)`);
60
+ if (a.asset !== undefined && !assets.has(String(a.asset)))
61
+ err(PATHS.accounts, w, `unknown asset "${a.asset}"`);
62
+ if (a.opened !== undefined && a.opened !== null && !isDate(a.opened))
63
+ err(PATHS.accounts, w, `opened is not a date (yyyy-mm-dd)`);
64
+ if (a.closed !== undefined && a.closed !== null && !isDate(a.closed))
65
+ err(PATHS.accounts, w, `closed is not a date (yyyy-mm-dd)`);
66
+ if (isDate(a.opened) && isDate(a.closed) && a.closed < a.opened)
67
+ err(PATHS.accounts, w, "closed before opened");
68
+ const def = typeDef(String(a.type));
69
+ if (a.details !== undefined && (typeof a.details !== "object" || a.details === null || Array.isArray(a.details))) {
70
+ err(PATHS.accounts, w, "details must be a map");
71
+ }
72
+ else if (def?.details && a.details) {
73
+ for (const [k, spec] of Object.entries(def.details)) {
74
+ const v = a.details[k];
75
+ if (v === undefined || v === null)
76
+ continue;
77
+ const ok = spec.kind === "int" ? Number.isInteger(v)
78
+ : spec.kind === "number" ? typeof v === "number" && Number.isFinite(v)
79
+ : spec.kind === "day" ? Number.isInteger(v) && v >= 1 && v <= 31
80
+ : spec.kind === "date" ? isDate(v)
81
+ : spec.kind === "boolean" ? typeof v === "boolean"
82
+ : typeof v === "string";
83
+ if (!ok)
84
+ warn(PATHS.accounts, w, `details.${k} should be ${spec.kind}; ignored by computations`);
85
+ }
86
+ }
87
+ });
88
+ // categories
89
+ const { map: cats, dupes } = flattenCategories(l.categories);
90
+ for (const d of dupes)
91
+ err(PATHS.categories, d, "duplicate category path");
92
+ for (const p of cats.keys()) {
93
+ const leaf = p.split("/").pop();
94
+ if (!ID_RE.test(leaf))
95
+ err(PATHS.categories, p, "category id must be letters, digits, . _ - (no spaces or /)");
96
+ if (isSystemCategory(p))
97
+ err(PATHS.categories, p, "ids starting with _ are reserved for system categories");
98
+ }
99
+ const catOk = (c) => cats.has(c) || Object.prototype.hasOwnProperty.call(SYSTEM_CATEGORIES, c);
100
+ // plans
101
+ const plans = new Set();
102
+ l.plans.forEach((p, i) => {
103
+ const w = p && typeof p.id === "string" ? p.id : `#${i + 1}`;
104
+ if (!p || typeof p.id !== "string" || !ID_RE.test(p.id))
105
+ return err(PATHS.plans, w, "missing or bad id");
106
+ if (plans.has(p.id))
107
+ err(PATHS.plans, w, "duplicate plan id");
108
+ plans.add(p.id);
109
+ if (!accounts.has(p.account))
110
+ err(PATHS.plans, w, `unknown account "${p.account}"`);
111
+ if (!EVERY.has(p.every))
112
+ err(PATHS.plans, w, `every must be month, quarter or year`);
113
+ if (!isDate(p.start))
114
+ err(PATHS.plans, w, "start is not a date");
115
+ if (p.end != null && !isDate(p.end))
116
+ err(PATHS.plans, w, "end is not a date");
117
+ if (p.count !== undefined && (!Number.isInteger(p.count) || p.count < 1))
118
+ err(PATHS.plans, w, "count must be a positive integer");
119
+ for (const k of ["amount", "principal", "fee"]) {
120
+ if (p[k] !== undefined && !Number.isInteger(p[k]))
121
+ err(PATHS.plans, w, `${k} must be an integer amount`);
122
+ }
123
+ if (p.amount === undefined && !(p.principal !== undefined && p.count))
124
+ err(PATHS.plans, w, "needs amount, or principal and count");
125
+ });
126
+ // budgets
127
+ l.budgets.forEach((b, i) => {
128
+ if (!b || !catOk(String(b.category)))
129
+ err(PATHS.budgets, `#${i + 1}`, `unknown category "${b?.category}"`);
130
+ if (!b || !Number.isInteger(b.amount))
131
+ err(PATHS.budgets, `#${i + 1}`, "amount must be an integer");
132
+ });
133
+ // prices
134
+ l.prices.forEach((p, i) => {
135
+ const w = `row ${i + 1}`;
136
+ if (!isDate(p.date))
137
+ err(PATHS.prices, w, `bad date "${p.date}"`);
138
+ if (!assets.has(p.asset))
139
+ err(PATHS.prices, w, `unknown asset "${p.asset}"`);
140
+ if (p.asset === base)
141
+ warn(PATHS.prices, w, "price for the base currency is ignored");
142
+ });
143
+ // transactions
144
+ const ids = new Set();
145
+ const srcKeys = new Map();
146
+ for (const t of l.transactions) {
147
+ const file = (typeof t.id === "string" && l.txFile.get(t.id)) || PATHS.ledgerDir;
148
+ const w = typeof t.id === "string" ? t.id : "(no id)";
149
+ if (typeof t.id !== "string" || !t.id) {
150
+ err(file, w, "transaction without id");
151
+ continue;
152
+ }
153
+ if (ids.has(t.id))
154
+ err(file, w, "duplicate transaction id");
155
+ ids.add(t.id);
156
+ if (!isDate(t.date)) {
157
+ err(file, w, `bad date "${t.date}"`);
158
+ continue;
159
+ }
160
+ if (ledgerPath(t.date) !== file)
161
+ err(file, w, `dated ${t.date} but stored in ${file} (belongs in ${ledgerPath(t.date)})`);
162
+ if (t.time != null && !/^\d{2}:\d{2}(:\d{2})?$/.test(String(t.time)))
163
+ err(file, w, `bad time "${t.time}" (HH:MM)`);
164
+ if (t.tags !== undefined && (!Array.isArray(t.tags) || t.tags.some((x) => typeof x !== "string")))
165
+ err(file, w, "tags must be a list of text");
166
+ if (t.plan != null && !plans.has(String(t.plan)))
167
+ err(file, w, `unknown plan "${t.plan}"`);
168
+ if (t.src) {
169
+ const k = `${t.src.import}:${t.src.key}`;
170
+ if (srcKeys.has(k))
171
+ err(file, w, `same import key as ${srcKeys.get(k)}`);
172
+ srcKeys.set(k, t.id);
173
+ }
174
+ if (!Array.isArray(t.lines) || t.lines.length < 2) {
175
+ err(file, w, "needs at least two lines");
176
+ continue;
177
+ }
178
+ let sum = 0;
179
+ t.lines.forEach((ln, j) => {
180
+ const lw = `${w} line ${j + 1}`;
181
+ if (!ln || typeof ln !== "object")
182
+ return err(file, lw, "not an object");
183
+ const hasA = ln.account !== undefined && ln.account !== null;
184
+ const hasC = ln.category !== undefined && ln.category !== null;
185
+ if (hasA === hasC)
186
+ return err(file, lw, "a line has either account or category (exactly one)");
187
+ if (!Number.isInteger(ln.amount))
188
+ return err(file, lw, `amount must be a whole number in ${base} (got ${ln.amount})`);
189
+ sum += ln.amount;
190
+ if (hasC) {
191
+ if (!catOk(String(ln.category)))
192
+ err(file, lw, `unknown category "${ln.category}"`);
193
+ if (ln.qty !== undefined || ln.asset !== undefined)
194
+ err(file, lw, "category lines have no asset or qty");
195
+ return;
196
+ }
197
+ const acc = accounts.get(String(ln.account));
198
+ if (!acc)
199
+ return err(file, lw, `unknown account "${ln.account}"`);
200
+ const accAsset = acc.asset ?? base;
201
+ const lineAsset = ln.asset ?? accAsset;
202
+ if (lineAsset !== accAsset)
203
+ err(file, lw, `asset ${lineAsset} but account ${acc.id} holds ${accAsset}`);
204
+ if (accAsset !== base) {
205
+ if (typeof ln.qty !== "number" || !Number.isFinite(ln.qty))
206
+ err(file, lw, `account ${acc.id} holds ${accAsset}: line needs qty`);
207
+ }
208
+ else if (ln.qty !== undefined) {
209
+ err(file, lw, "qty only on lines of non-base assets");
210
+ }
211
+ if (isDate(acc.opened) && t.date < acc.opened)
212
+ warn(file, lw, `before account ${acc.id} opened (${acc.opened})`);
213
+ if (isDate(acc.closed) && t.date > acc.closed && !t.void)
214
+ warn(file, lw, `after account ${acc.id} closed (${acc.closed})`);
215
+ });
216
+ if (sum !== 0)
217
+ err(file, w, `lines don't balance: sum is ${sum}, must be 0`);
218
+ }
219
+ return out;
220
+ }
@@ -0,0 +1,15 @@
1
+ import type { ISODate } from "./types.js";
2
+ export declare function isDate(s: unknown): s is ISODate;
3
+ export declare function daysInMonth(y: number, m: number): number;
4
+ export declare function parts(d: ISODate): [number, number, number];
5
+ export declare function fmt(y: number, m: number, d: number): ISODate;
6
+ /** Same day-of-month n months later, clamped to the month's last day. */
7
+ export declare function addMonths(d: ISODate, n: number, day?: number): ISODate;
8
+ export declare function addDays(d: ISODate, n: number): ISODate;
9
+ export declare function daysBetween(a: ISODate, b: ISODate): number;
10
+ /** The date in month (y, m) for a day-of-month, clamped. */
11
+ export declare function dayIn(y: number, m: number, day: number): ISODate;
12
+ export declare function monthOf(d: ISODate): string;
13
+ export declare function monthStart(d: ISODate): ISODate;
14
+ export declare function monthEnd(d: ISODate): ISODate;
15
+ export declare function todayIn(tz?: string, now?: Date): ISODate;
@@ -0,0 +1,56 @@
1
+ const RE = /^(\d{4})-(\d{2})-(\d{2})$/;
2
+ export function isDate(s) {
3
+ if (typeof s !== "string")
4
+ return false;
5
+ const m = RE.exec(s);
6
+ if (!m)
7
+ return false;
8
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
9
+ return mo >= 1 && mo <= 12 && d >= 1 && d <= daysInMonth(y, mo);
10
+ }
11
+ export function daysInMonth(y, m) {
12
+ return new Date(Date.UTC(y, m, 0)).getUTCDate();
13
+ }
14
+ export function parts(d) {
15
+ return [Number(d.slice(0, 4)), Number(d.slice(5, 7)), Number(d.slice(8, 10))];
16
+ }
17
+ export function fmt(y, m, d) {
18
+ return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
19
+ }
20
+ /** Same day-of-month n months later, clamped to the month's last day. */
21
+ export function addMonths(d, n, day) {
22
+ const [y, m, dd] = parts(d);
23
+ const idx = y * 12 + (m - 1) + n;
24
+ const ny = Math.floor(idx / 12);
25
+ const nm = (idx % 12) + 1;
26
+ return fmt(ny, nm, Math.min(day ?? dd, daysInMonth(ny, nm)));
27
+ }
28
+ export function addDays(d, n) {
29
+ const t = Date.UTC(...ymd0(d)) + n * 86400000;
30
+ return new Date(t).toISOString().slice(0, 10);
31
+ }
32
+ export function daysBetween(a, b) {
33
+ return Math.round((Date.UTC(...ymd0(b)) - Date.UTC(...ymd0(a))) / 86400000);
34
+ }
35
+ function ymd0(d) {
36
+ const [y, m, dd] = parts(d);
37
+ return [y, m - 1, dd];
38
+ }
39
+ /** The date in month (y, m) for a day-of-month, clamped. */
40
+ export function dayIn(y, m, day) {
41
+ return fmt(y, m, Math.min(day, daysInMonth(y, m)));
42
+ }
43
+ export function monthOf(d) {
44
+ return d.slice(0, 7);
45
+ }
46
+ export function monthStart(d) {
47
+ return d.slice(0, 7) + "-01";
48
+ }
49
+ export function monthEnd(d) {
50
+ const [y, m] = parts(d);
51
+ return fmt(y, m, daysInMonth(y, m));
52
+ }
53
+ export function todayIn(tz = "Asia/Ho_Chi_Minh", now = new Date()) {
54
+ // en-CA formats as yyyy-mm-dd
55
+ return new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
56
+ }
@@ -0,0 +1,2 @@
1
+ import type { CategoriesFile } from "./types.js";
2
+ export declare function defaultCategories(lang?: "vi" | "en"): CategoriesFile;
@@ -0,0 +1,61 @@
1
+ const INCOME = [
2
+ ["salary", "Lương", "Salary"],
3
+ ["freelance", "Làm thêm", "Freelance"],
4
+ ["interest", "Lãi & cổ tức", "Interest & dividends"],
5
+ ["cashback", "Hoàn tiền & khuyến mãi", "Cashback & promos"],
6
+ ["gifts-received", "Được tặng", "Gifts received"],
7
+ ["other-income", "Thu khác", "Other income"],
8
+ ];
9
+ const EXPENSE = [
10
+ ["food", "Ăn uống", "Food", [
11
+ ["eating-out", "Ăn ngoài", "Eating out"],
12
+ ["cafe", "Cafe", "Cafe"],
13
+ ["groceries", "Đi chợ", "Groceries"],
14
+ ]],
15
+ ["transport", "Đi lại", "Transport", [
16
+ ["fuel", "Xăng", "Fuel"],
17
+ ["fares", "Vé xe & gửi xe", "Fares & parking"],
18
+ ["vehicle", "Sửa xe", "Vehicle repairs"],
19
+ ]],
20
+ ["home", "Nhà cửa", "Home", [
21
+ ["electricity", "Điện nước", "Electricity & water"],
22
+ ["internet", "Internet", "Internet"],
23
+ ["repairs", "Sửa chữa", "Repairs"],
24
+ ["household", "Đồ gia dụng", "Household items"],
25
+ ["plants", "Cây cảnh", "Plants"],
26
+ ]],
27
+ ["family", "Gia đình", "Family", [
28
+ ["parents", "Bố mẹ", "Parents"],
29
+ ["gifts-weddings", "Quà & đám cưới", "Gifts & weddings"],
30
+ ]],
31
+ ["health", "Sức khoẻ & thể thao", "Health & sport", [
32
+ ["sport", "Thể thao", "Sport"],
33
+ ["medical", "Khám chữa bệnh", "Medical"],
34
+ ["personal-care", "Chăm sóc cá nhân", "Personal care"],
35
+ ["insurance", "Phí bảo hiểm", "Insurance premiums"],
36
+ ]],
37
+ ["shopping", "Mua sắm", "Shopping", [
38
+ ["clothes", "Quần áo", "Clothes"],
39
+ ["big-purchases", "Đồ lớn", "Big purchases"],
40
+ ]],
41
+ ["fun", "Giải trí & du lịch", "Fun & travel", [
42
+ ["entertainment", "Giải trí", "Entertainment"],
43
+ ["trips", "Du lịch", "Trips"],
44
+ ]],
45
+ ["learning", "Học tập", "Learning"],
46
+ ["work-tools", "Công cụ làm việc", "Work tools"],
47
+ ["subscriptions", "Điện thoại & dịch vụ", "Phone & subscriptions"],
48
+ ["bank-fees", "Phí & lãi ngân hàng", "Bank fees & interest paid"],
49
+ ["other", "Chi khác", "Other / unknown"],
50
+ ];
51
+ function build(nodes, lang) {
52
+ return nodes.map(([id, vi, en, children]) => {
53
+ const n = { id, name: lang === "vi" ? vi : en };
54
+ if (children)
55
+ n.children = build(children, lang);
56
+ return n;
57
+ });
58
+ }
59
+ export function defaultCategories(lang = "vi") {
60
+ return { income: build(INCOME, lang), expense: build(EXPENSE, lang) };
61
+ }
@@ -0,0 +1,13 @@
1
+ export * from "./types.js";
2
+ export * from "./registry.js";
3
+ export * from "./dates.js";
4
+ export * from "./categories.js";
5
+ export * from "./load.js";
6
+ export * from "./check.js";
7
+ export * from "./balances.js";
8
+ export * from "./reports.js";
9
+ export * from "./networth.js";
10
+ export * from "./schedules.js";
11
+ export * from "./defaults.js";
12
+ export * from "./write.js";
13
+ export * from "./actions.js";
@@ -0,0 +1,13 @@
1
+ export * from "./types.js";
2
+ export * from "./registry.js";
3
+ export * from "./dates.js";
4
+ export * from "./categories.js";
5
+ export * from "./load.js";
6
+ export * from "./check.js";
7
+ export * from "./balances.js";
8
+ export * from "./reports.js";
9
+ export * from "./networth.js";
10
+ export * from "./schedules.js";
11
+ export * from "./defaults.js";
12
+ export * from "./write.js";
13
+ export * from "./actions.js";
@@ -0,0 +1,23 @@
1
+ import type { Issue, Ledger, Price, Transaction } from "./types.js";
2
+ /** Files of a data repo, keyed by path relative to the repo root ("data/meta.yaml"). */
3
+ export type FileMap = Record<string, string>;
4
+ export declare const PATHS: {
5
+ readonly meta: "data/meta.yaml";
6
+ readonly accounts: "data/accounts.yaml";
7
+ readonly assets: "data/assets.yaml";
8
+ readonly categories: "data/categories.yaml";
9
+ readonly plans: "data/plans.yaml";
10
+ readonly budgets: "data/budgets.yaml";
11
+ readonly prices: "data/prices.csv";
12
+ readonly ledgerDir: "data/ledger/";
13
+ };
14
+ export declare const LEDGER_FILE_RE: RegExp;
15
+ export declare function ledgerPath(date: string): string;
16
+ export declare function parsePricesCsv(text: string, issues: Issue[], file?: "data/prices.csv"): Price[];
17
+ export declare function parseJsonl(text: string, file: string, issues: Issue[]): Transaction[];
18
+ export declare function compareTx(a: Transaction, b: Transaction): number;
19
+ /** Parses every data file. Never throws: problems become issues (check adds the semantic ones). */
20
+ export declare function loadLedger(files: FileMap): {
21
+ ledger: Ledger;
22
+ issues: Issue[];
23
+ };
@@ -0,0 +1,129 @@
1
+ import { parse as parseYaml } from "yaml";
2
+ export const PATHS = {
3
+ meta: "data/meta.yaml",
4
+ accounts: "data/accounts.yaml",
5
+ assets: "data/assets.yaml",
6
+ categories: "data/categories.yaml",
7
+ plans: "data/plans.yaml",
8
+ budgets: "data/budgets.yaml",
9
+ prices: "data/prices.csv",
10
+ ledgerDir: "data/ledger/",
11
+ };
12
+ export const LEDGER_FILE_RE = /^data\/ledger\/(\d{4})\/(\d{2})\.jsonl$/;
13
+ export function ledgerPath(date) {
14
+ return `${PATHS.ledgerDir}${date.slice(0, 4)}/${date.slice(5, 7)}.jsonl`;
15
+ }
16
+ function yamlFile(files, path, fallback, issues, required = false) {
17
+ const text = files[path];
18
+ if (text === undefined) {
19
+ if (required)
20
+ issues.push({ level: "error", file: path, message: "missing file" });
21
+ return fallback;
22
+ }
23
+ try {
24
+ const v = parseYaml(text);
25
+ return (v ?? fallback);
26
+ }
27
+ catch (e) {
28
+ issues.push({ level: "error", file: path, message: `YAML parse error: ${e.message.split("\n")[0]}` });
29
+ return fallback;
30
+ }
31
+ }
32
+ export function parsePricesCsv(text, issues, file = PATHS.prices) {
33
+ const out = [];
34
+ const lines = text.split(/\r?\n/);
35
+ lines.forEach((raw, i) => {
36
+ const line = raw.trim();
37
+ if (!line || line.startsWith("#"))
38
+ return;
39
+ if (i === 0 && /^date\s*,/i.test(line))
40
+ return;
41
+ const [date, asset, price] = line.split(",").map((s) => s.trim());
42
+ const p = Number(price);
43
+ if (!date || !asset || !Number.isFinite(p)) {
44
+ issues.push({ level: "error", file, where: `line ${i + 1}`, message: `bad price row "${line}"` });
45
+ return;
46
+ }
47
+ out.push({ date, asset, price: p });
48
+ });
49
+ return out;
50
+ }
51
+ export function parseJsonl(text, file, issues) {
52
+ const out = [];
53
+ text.split(/\r?\n/).forEach((raw, i) => {
54
+ const line = raw.trim();
55
+ if (!line)
56
+ return;
57
+ try {
58
+ const v = JSON.parse(line);
59
+ if (!v || typeof v !== "object" || Array.isArray(v))
60
+ throw new Error("not an object");
61
+ out.push(v);
62
+ }
63
+ catch (e) {
64
+ issues.push({ level: "error", file, where: `line ${i + 1}`, message: `bad JSON: ${e.message}` });
65
+ }
66
+ });
67
+ return out;
68
+ }
69
+ export function compareTx(a, b) {
70
+ if (a.date !== b.date)
71
+ return a.date < b.date ? -1 : 1;
72
+ const ta = a.time ?? "";
73
+ const tb = b.time ?? "";
74
+ if (ta !== tb)
75
+ return ta < tb ? -1 : 1;
76
+ return 0;
77
+ }
78
+ /** Parses every data file. Never throws: problems become issues (check adds the semantic ones). */
79
+ export function loadLedger(files) {
80
+ const issues = [];
81
+ const meta = yamlFile(files, PATHS.meta, { format: 0, base: "VND" }, issues, true);
82
+ const accounts = yamlFile(files, PATHS.accounts, [], issues, true);
83
+ const assets = yamlFile(files, PATHS.assets, [], issues);
84
+ const categories = yamlFile(files, PATHS.categories, { income: [], expense: [] }, issues, true);
85
+ const plans = yamlFile(files, PATHS.plans, [], issues);
86
+ const budgets = yamlFile(files, PATHS.budgets, [], issues);
87
+ const prices = files[PATHS.prices] !== undefined ? parsePricesCsv(files[PATHS.prices], issues) : [];
88
+ const transactions = [];
89
+ const txFile = new Map();
90
+ const ledgerFiles = Object.keys(files)
91
+ .filter((p) => p.startsWith(PATHS.ledgerDir))
92
+ .sort();
93
+ for (const path of ledgerFiles) {
94
+ if (!LEDGER_FILE_RE.test(path)) {
95
+ issues.push({ level: "warning", file: path, message: "not a ledger file name (data/ledger/yyyy/mm.jsonl); ignored" });
96
+ continue;
97
+ }
98
+ for (const tx of parseJsonl(files[path], path, issues)) {
99
+ transactions.push(tx);
100
+ if (typeof tx.id === "string")
101
+ txFile.set(tx.id, path);
102
+ }
103
+ }
104
+ // stable sort keeps file order for equal date+time
105
+ transactions.sort(compareTx);
106
+ const asArray = (v, file) => {
107
+ if (Array.isArray(v))
108
+ return v;
109
+ issues.push({ level: "error", file, message: "expected a list" });
110
+ return [];
111
+ };
112
+ return {
113
+ ledger: {
114
+ meta: meta && typeof meta === "object" ? meta : { format: 0, base: "VND" },
115
+ assets: asArray(assets, PATHS.assets),
116
+ accounts: asArray(accounts, PATHS.accounts),
117
+ categories: {
118
+ income: Array.isArray(categories?.income) ? categories.income : [],
119
+ expense: Array.isArray(categories?.expense) ? categories.expense : [],
120
+ },
121
+ plans: asArray(plans, PATHS.plans),
122
+ budgets: asArray(budgets, PATHS.budgets),
123
+ prices,
124
+ transactions,
125
+ txFile,
126
+ },
127
+ issues,
128
+ };
129
+ }
@@ -0,0 +1,12 @@
1
+ import type { ISODate, Ledger } from "./types.js";
2
+ export interface NetWorth {
3
+ date: ISODate;
4
+ assets: number;
5
+ liabilities: number;
6
+ net: number;
7
+ byType: Record<string, number>;
8
+ unpriced: string[];
9
+ }
10
+ export declare function netWorth(l: Ledger, asOf: ISODate): NetWorth;
11
+ /** Net worth at the end of each month from `from` to `to` (one pass over the ledger). */
12
+ export declare function netWorthSeries(l: Ledger, from: ISODate, to: ISODate): NetWorth[];
@@ -0,0 +1,73 @@
1
+ import { PriceBook, valueAccount } from "./balances.js";
2
+ import { monthEnd } from "./dates.js";
3
+ import { typeDef } from "./registry.js";
4
+ import { monthsBetween } from "./reports.js";
5
+ function summarise(date, vals) {
6
+ let assets = 0;
7
+ let liabilities = 0;
8
+ const byType = {};
9
+ const unpriced = [];
10
+ for (const v of vals) {
11
+ if (v.value === 0 && (v.qty ?? 0) === 0)
12
+ continue;
13
+ const liability = Boolean(typeDef(v.account.type)?.liability) || v.value < 0;
14
+ if (liability && v.value < 0)
15
+ liabilities += v.value;
16
+ else
17
+ assets += v.value;
18
+ byType[v.account.type] = (byType[v.account.type] ?? 0) + v.value;
19
+ if (!v.priced)
20
+ unpriced.push(v.account.id);
21
+ }
22
+ return { date, assets, liabilities, net: assets + liabilities, byType, unpriced };
23
+ }
24
+ export function netWorth(l, asOf) {
25
+ const prices = new PriceBook(l.prices);
26
+ const hs = new Map(l.accounts.map((a) => [a.id, { amount: 0, qty: 0 }]));
27
+ for (const t of l.transactions) {
28
+ if (t.void)
29
+ continue;
30
+ if (t.date > asOf)
31
+ break;
32
+ for (const ln of t.lines) {
33
+ if (ln.account == null)
34
+ continue;
35
+ const h = hs.get(ln.account);
36
+ if (!h)
37
+ continue;
38
+ h.amount += ln.amount;
39
+ if (typeof ln.qty === "number")
40
+ h.qty += ln.qty;
41
+ }
42
+ }
43
+ return summarise(asOf, l.accounts.map((a) => valueAccount(l, a, hs.get(a.id), prices, asOf)));
44
+ }
45
+ /** Net worth at the end of each month from `from` to `to` (one pass over the ledger). */
46
+ export function netWorthSeries(l, from, to) {
47
+ const prices = new PriceBook(l.prices);
48
+ const hs = new Map(l.accounts.map((a) => [a.id, { amount: 0, qty: 0 }]));
49
+ const out = [];
50
+ let i = 0;
51
+ const txs = l.transactions;
52
+ for (const mk of monthsBetween(from, to)) {
53
+ const end = monthEnd(`${mk}-01`);
54
+ const at = end > to ? to : end;
55
+ while (i < txs.length && txs[i].date <= at) {
56
+ const t = txs[i++];
57
+ if (t.void)
58
+ continue;
59
+ for (const ln of t.lines) {
60
+ if (ln.account == null)
61
+ continue;
62
+ const h = hs.get(ln.account);
63
+ if (!h)
64
+ continue;
65
+ h.amount += ln.amount;
66
+ if (typeof ln.qty === "number")
67
+ h.qty += ln.qty;
68
+ }
69
+ }
70
+ out.push(summarise(at, l.accounts.map((a) => valueAccount(l, a, hs.get(a.id), prices, at))));
71
+ }
72
+ return out;
73
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Account types the engine knows. A type not listed here is still accepted: it loads as a plain
3
+ * account (balance only) with a warning. Details keys not listed are kept and passed through.
4
+ */
5
+ export type DetailKind = "int" | "number" | "day" | "date" | "string" | "boolean";
6
+ export interface TypeDef {
7
+ label: {
8
+ en: string;
9
+ vi: string;
10
+ };
11
+ /** true when money in this account is the user's own cash-like money (counted as liquid). */
12
+ liquid?: boolean;
13
+ /** true when the balance is normally negative (money owed). */
14
+ liability?: boolean;
15
+ /** true when the account holds a non-base asset counted in qty (gold, funds...). */
16
+ holdings?: boolean;
17
+ details?: Record<string, {
18
+ kind: DetailKind;
19
+ required?: boolean;
20
+ note?: string;
21
+ }>;
22
+ }
23
+ export declare const TYPES: Record<string, TypeDef>;
24
+ export declare function typeDef(type: string): TypeDef | undefined;