ownledger 1.2.1 → 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.
Files changed (151) hide show
  1. package/AGENTS.md +28 -1
  2. package/CHANGELOG.md +43 -0
  3. package/assets/apple-touch-icon.png +0 -0
  4. package/assets/icon-192.png +0 -0
  5. package/assets/icon-512.png +0 -0
  6. package/assets/icon-maskable-512.png +0 -0
  7. package/assets/index.html +15 -18
  8. package/assets/manifest.webmanifest +1 -1
  9. package/assets/static/Account-DEBzshne.js +1 -0
  10. package/assets/static/Accounts-C1iNsQsy.js +1 -0
  11. package/assets/static/Attention-qo4v70P1.js +1 -0
  12. package/assets/static/ByCategory-33P2zSs-.js +1 -0
  13. package/assets/static/CardDetail-CvRo7JPt.js +1 -0
  14. package/assets/static/Cards-C3AdusmT.js +1 -0
  15. package/assets/static/Cards-DuqZFxkQ.js +1 -0
  16. package/assets/static/CardsValue-BM9WUQmy.js +1 -0
  17. package/assets/static/Cashback-DsWyjgRr.js +1 -0
  18. package/assets/static/CategoryIcon-E6EWIpbr.js +1 -0
  19. package/assets/static/CategoryPicker-BPeJNSuM.js +1 -0
  20. package/assets/static/ChartWidget-Bk1TAvJM.js +1 -0
  21. package/assets/static/Combobox-lRNTmjKR.js +1 -0
  22. package/assets/static/Deposits-CgEFypxb.js +1 -0
  23. package/assets/static/DrillLink-pa6s17Xu.js +1 -0
  24. package/assets/static/Field-OkPhoYM1.js +1 -0
  25. package/assets/static/HomeEditor-DdrzEPe2.js +1 -0
  26. package/assets/static/Import-DrhHmL65.js +2 -0
  27. package/assets/static/IncomeSpending-Cveqr3xt.js +1 -0
  28. package/assets/static/KV-CKGyL0p7.js +1 -0
  29. package/assets/static/Left-Bs_oKU19.js +1 -0
  30. package/assets/static/Money-DCMKf898.js +1 -0
  31. package/assets/static/NetWorth-Cjd13J56.js +1 -0
  32. package/assets/static/Pace-CBUDNxzH.js +1 -0
  33. package/assets/static/Panel-CXjnsEN0.js +1 -0
  34. package/assets/static/PinDialog-DoGuAyi4.js +1 -0
  35. package/assets/static/Plans-EWJdPCJ3.js +1 -0
  36. package/assets/static/Recent-BmJjA5dK.js +1 -0
  37. package/assets/static/Reports-DSrLn_wC.js +1 -0
  38. package/assets/static/Settings-DdiEp2Qi.js +1 -0
  39. package/assets/static/Transactions-Cy0kgcLE.js +1 -0
  40. package/assets/static/TxRow-IqjFXpya.js +1 -0
  41. package/assets/static/Unusual-D5-L9ZOy.js +1 -0
  42. package/assets/static/Upcoming-CCqPol8c.js +1 -0
  43. package/assets/static/WhichCard-Butdi7AN.js +1 -0
  44. package/assets/static/arrow-up-C8D_7x_H.js +1 -0
  45. package/assets/static/bits-BoWPOwTB.js +1 -0
  46. package/assets/static/button-Cj0k8AtB.js +1 -0
  47. package/assets/static/cards-AZlSJQ0z.js +1 -0
  48. package/assets/static/charts-Cj_hTR4h.js +65 -0
  49. package/assets/static/chevron-down-BLodeu9a.js +1 -0
  50. package/assets/static/chevron-right-BetctQ6k.js +1 -0
  51. package/assets/static/createLucideIcon-DUW9Fpzj.js +1 -0
  52. package/assets/static/dialog-BIbLA-XP.js +1 -0
  53. package/assets/static/dist-CbNfxqbd.js +1 -0
  54. package/assets/static/dist-CetESl7K.js +1 -0
  55. package/assets/static/dist-DYP_TYPy.js +1 -0
  56. package/assets/static/dist-DaSyQKU7.js +1 -0
  57. package/assets/static/drill-t1zr57xi.js +1 -0
  58. package/assets/static/es2015-BgAh-EkH.js +41 -0
  59. package/assets/static/fold-CGWYt9Iu.js +1 -0
  60. package/assets/static/index-CBsgYTMJ.css +1 -0
  61. package/assets/static/index-DYyIpxqK.js +14 -0
  62. package/assets/static/queries-C_4ufx4u.js +1 -0
  63. package/assets/static/react-dom-CI34djkT.js +1 -0
  64. package/assets/static/select-2EwEpMf_.js +1 -0
  65. package/assets/static/shared-CR-hvb-r.js +1 -0
  66. package/assets/static/triangle-exclamation-point-C6padEUM.js +1 -0
  67. package/assets/static/useMutation-BWtHiYPX.js +1 -0
  68. package/dist/cli/cards.d.ts +2 -0
  69. package/dist/cli/cards.js +86 -0
  70. package/dist/cli/import.js +12 -2
  71. package/dist/cli/index.js +3 -0
  72. package/dist/engine/actions.d.ts +5 -0
  73. package/dist/engine/actions.js +9 -5
  74. package/dist/engine/attention.d.ts +15 -0
  75. package/dist/engine/attention.js +63 -0
  76. package/dist/engine/check.js +8 -1
  77. package/dist/engine/dashboard.d.ts +72 -0
  78. package/dist/engine/dashboard.js +180 -0
  79. package/dist/engine/features.d.ts +20 -0
  80. package/dist/engine/features.js +37 -0
  81. package/dist/engine/index.d.ts +5 -0
  82. package/dist/engine/index.js +5 -0
  83. package/dist/engine/insights.d.ts +164 -0
  84. package/dist/engine/insights.js +534 -0
  85. package/dist/engine/load.js +6 -0
  86. package/dist/engine/registry.d.ts +2 -0
  87. package/dist/engine/registry.js +15 -33
  88. package/dist/engine/reports.d.ts +21 -2
  89. package/dist/engine/reports.js +51 -3
  90. package/dist/engine/schedules.d.ts +7 -84
  91. package/dist/engine/schedules.js +8 -207
  92. package/dist/engine/types.d.ts +2 -0
  93. package/dist/engine/write.d.ts +9 -0
  94. package/dist/engine/write.js +26 -5
  95. package/dist/import/mapping.js +6 -0
  96. package/dist/import/run.d.ts +7 -0
  97. package/dist/import/run.js +28 -1
  98. package/dist/modules/api.d.ts +19 -0
  99. package/dist/modules/api.js +16 -0
  100. package/dist/modules/cards/api.d.ts +3 -0
  101. package/dist/modules/cards/api.js +73 -0
  102. package/dist/modules/cards/engine.d.ts +42 -0
  103. package/dist/modules/cards/engine.js +102 -0
  104. package/dist/modules/cards/index.d.ts +26 -0
  105. package/dist/modules/cards/index.js +304 -0
  106. package/dist/modules/cards/statements.d.ts +128 -0
  107. package/dist/modules/cards/statements.js +426 -0
  108. package/dist/modules/cards/terms.d.ts +105 -0
  109. package/dist/modules/cards/terms.js +194 -0
  110. package/dist/modules/cards/tracker.d.ts +36 -0
  111. package/dist/modules/cards/tracker.js +232 -0
  112. package/dist/modules/cards/types.d.ts +2 -0
  113. package/dist/modules/cards/types.js +16 -0
  114. package/dist/modules/deposits/engine.d.ts +14 -0
  115. package/dist/modules/deposits/engine.js +32 -0
  116. package/dist/modules/deposits/index.d.ts +2 -0
  117. package/dist/modules/deposits/index.js +24 -0
  118. package/dist/modules/deposits/types.d.ts +2 -0
  119. package/dist/modules/deposits/types.js +15 -0
  120. package/dist/modules/index.d.ts +5 -0
  121. package/dist/modules/index.js +10 -0
  122. package/dist/modules/insurance/index.d.ts +3 -0
  123. package/dist/modules/insurance/index.js +8 -0
  124. package/dist/modules/insurance/types.d.ts +2 -0
  125. package/dist/modules/insurance/types.js +3 -0
  126. package/dist/modules/investments/index.d.ts +2 -0
  127. package/dist/modules/investments/index.js +24 -0
  128. package/dist/modules/investments/types.d.ts +2 -0
  129. package/dist/modules/investments/types.js +7 -0
  130. package/dist/modules/loans/engine.d.ts +30 -0
  131. package/dist/modules/loans/engine.js +77 -0
  132. package/dist/modules/loans/index.d.ts +2 -0
  133. package/dist/modules/loans/index.js +27 -0
  134. package/dist/modules/loans/types.d.ts +2 -0
  135. package/dist/modules/loans/types.js +5 -0
  136. package/dist/modules/types.d.ts +39 -0
  137. package/dist/modules/types.js +1 -0
  138. package/dist/modules/util.d.ts +8 -0
  139. package/dist/modules/util.js +8 -0
  140. package/dist/node/scaffold.js +2 -2
  141. package/dist/worker/api.d.ts +11 -1
  142. package/dist/worker/api.js +167 -13
  143. package/dist/worker/bestcard.d.ts +31 -9
  144. package/dist/worker/bestcard.js +78 -50
  145. package/dist/worker/mcp.js +209 -30
  146. package/dist/worker/version.d.ts +1 -1
  147. package/dist/worker/version.js +1 -1
  148. package/package.json +26 -4
  149. package/presets/misa.mapping.yaml +7 -0
  150. package/assets/app.css +0 -61
  151. package/assets/app.js +0 -369
package/assets/app.css DELETED
@@ -1,61 +0,0 @@
1
- :root {
2
- color-scheme: light;
3
- --surface-0: #f4f4f2;
4
- --surface-1: #fcfcfb;
5
- --border: #e3e2de;
6
- --grid: #ecebe7;
7
- --text-primary: #0b0b0b;
8
- --text-secondary: #52514e;
9
- --text-muted: #7c7b76;
10
- --series-1: #2a78d6; /* income, net worth, magnitude */
11
- --series-2: #eb6834; /* spending */
12
- --good: #1f7a1f;
13
- --critical: #c0392b;
14
- --radius: 12px;
15
- }
16
- * { box-sizing: border-box; }
17
- body { margin: 0; font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: var(--text-primary); background: var(--surface-0); }
18
- a { color: var(--series-1); text-decoration: none; }
19
- a:hover { text-decoration: underline; }
20
- .top { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; padding: .75rem 1.25rem; background: var(--surface-1); border-bottom: 1px solid var(--border); position: sticky; top: 0; z-index: 2; }
21
- .brand { font-weight: 700; color: var(--text-primary); }
22
- nav { display: flex; gap: .25rem; flex-wrap: wrap; flex: 1; }
23
- nav a { color: var(--text-secondary); padding: .3rem .6rem; border-radius: 8px; }
24
- nav a.on { background: var(--surface-0); color: var(--text-primary); }
25
- main { max-width: 1120px; margin: 0 auto; padding: 1.25rem; }
26
- h1 { font-size: 1.35rem; margin: .25rem 0 1rem; }
27
- h2 { font-size: 1.05rem; margin: 0 0 .75rem; }
28
- .muted { color: var(--text-muted); }
29
- .small { font-size: .85rem; }
30
- .grid { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
31
- .grid.two { grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); }
32
- .card { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem 1.1rem; min-width: 0; }
33
- .stat .label { color: var(--text-secondary); font-size: .85rem; }
34
- .stat .value { font-size: 1.6rem; font-weight: 650; font-variant-numeric: tabular-nums; }
35
- .stat .delta { font-size: .85rem; color: var(--text-secondary); }
36
- .num { font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
37
- .neg { color: var(--critical); }
38
- .pos { color: var(--good); }
39
- table { width: 100%; border-collapse: collapse; font-size: .92rem; }
40
- th, td { padding: .45rem .5rem; border-bottom: 1px solid var(--grid); text-align: left; vertical-align: top; }
41
- th { color: var(--text-secondary); font-weight: 600; font-size: .82rem; }
42
- tr.void td { color: var(--text-muted); text-decoration: line-through; }
43
- .filters { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; margin-bottom: 1rem; }
44
- input, select, button { font: inherit; padding: .4rem .6rem; border: 1px solid var(--border); border-radius: 8px; background: var(--surface-1); color: var(--text-primary); }
45
- button { cursor: pointer; }
46
- button.primary { background: var(--text-primary); color: var(--surface-1); border-color: var(--text-primary); }
47
- button:disabled { opacity: .5; cursor: default; }
48
- .pill { display: inline-block; padding: 0 .45rem; border-radius: 999px; background: var(--surface-0); color: var(--text-secondary); font-size: .78rem; margin-right: .25rem; }
49
- .status { display: inline-flex; gap: .3rem; align-items: center; font-weight: 600; }
50
- .status.bad { color: var(--critical); }
51
- .status.ok { color: var(--good); }
52
- .legend { display: flex; gap: 1rem; font-size: .85rem; color: var(--text-secondary); margin-bottom: .4rem; }
53
- .legend i { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: .35rem; vertical-align: -1px; }
54
- svg.chart { width: 100%; height: auto; display: block; overflow: visible; }
55
- svg.chart text { fill: var(--text-muted); font-size: 11px; font-family: inherit; }
56
- svg.chart .grid line { stroke: var(--grid); }
57
- .tip { position: fixed; pointer-events: none; background: var(--surface-1); border: 1px solid var(--border); border-radius: 8px; padding: .4rem .6rem; font-size: .85rem; box-shadow: 0 4px 16px rgba(0,0,0,.08); z-index: 10; }
58
- details.table summary { cursor: pointer; color: var(--text-secondary); font-size: .85rem; margin-top: .5rem; }
59
- .empty { padding: 2rem; text-align: center; color: var(--text-muted); }
60
- pre { white-space: pre-wrap; font-size: .82rem; background: var(--surface-0); padding: .6rem; border-radius: 8px; }
61
- @media (max-width: 640px) { .grid.two { grid-template-columns: 1fr; } .stat .value { font-size: 1.3rem; } main { padding: .75rem; } }
package/assets/app.js DELETED
@@ -1,369 +0,0 @@
1
- // ownledger dashboard: plain JS, no third-party code. All data from /api (same origin, signed session).
2
- const $ = (s, el = document) => el.querySelector(s);
3
- const main = $("#main");
4
- const tip = $("#tip");
5
- let ME = null;
6
- let META = null;
7
-
8
- const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
9
- const fmt = (n) => (n === null || n === undefined ? "—" : new Intl.NumberFormat(ME?.locale === "vi" ? "vi-VN" : "en-US").format(Math.round(n)));
10
- const money = (n) => `${fmt(n)}${ME?.base === "VND" ? " ₫" : ` ${ME?.base ?? ""}`}`;
11
- const short = (n) => {
12
- const a = Math.abs(n);
13
- const s = a >= 1e9 ? `${(a / 1e9).toFixed(a >= 1e10 ? 0 : 1)}B` : a >= 1e6 ? `${(a / 1e6).toFixed(a >= 1e7 ? 0 : 1)}M` : a >= 1e3 ? `${Math.round(a / 1e3)}k` : String(Math.round(a));
14
- return (n < 0 ? "−" : "") + s;
15
- };
16
- const signed = (n) => `<span class="num ${n < 0 ? "neg" : ""}">${money(n)}</span>`;
17
- const pct = (a, b) => (b ? `${a >= b ? "+" : "−"}${Math.abs(Math.round(((a - b) / Math.abs(b)) * 100))}%` : "");
18
-
19
- async function api(path, init) {
20
- const r = await fetch(`/api/${path}`, { credentials: "same-origin", ...init, headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) } });
21
- if (r.status === 401) {
22
- signIn();
23
- throw new Error("sign in");
24
- }
25
- const v = await r.json();
26
- if (!r.ok) throw new Error(v.error ?? r.status);
27
- return v;
28
- }
29
-
30
- function signIn() {
31
- main.innerHTML = `<div class="card empty"><h1>ownledger</h1><p>Your private ledger. Sign in with the GitHub account allowed on this Worker.</p><p><a href="/auth/login"><button class="primary">Sign in with GitHub</button></a></p></div>`;
32
- $("#nav").hidden = true;
33
- }
34
-
35
- /* ------------------------------------------------------------------ charts (SVG, hover tooltips) */
36
-
37
- const NS = "http://www.w3.org/2000/svg";
38
- function el(name, attrs = {}, parent) {
39
- const e = document.createElementNS(NS, name);
40
- for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
41
- if (parent) parent.appendChild(e);
42
- return e;
43
- }
44
- function showTip(ev, html) {
45
- tip.innerHTML = html;
46
- tip.hidden = false;
47
- const x = Math.min(ev.clientX + 14, innerWidth - tip.offsetWidth - 8);
48
- tip.style.left = `${x}px`;
49
- tip.style.top = `${ev.clientY + 14}px`;
50
- }
51
- const hideTip = () => (tip.hidden = true);
52
-
53
- function niceTicks(min, max, n = 4) {
54
- if (min === max) max = min + 1;
55
- const span = max - min;
56
- const step0 = Math.pow(10, Math.floor(Math.log10(span / n)));
57
- const step = [1, 2, 2.5, 5, 10].map((m) => m * step0).find((s) => span / s <= n) ?? step0 * 10;
58
- const lo = Math.floor(min / step) * step;
59
- const hi = Math.ceil(max / step) * step;
60
- const out = [];
61
- for (let v = lo; v <= hi + step / 2; v += step) out.push(v);
62
- return out;
63
- }
64
-
65
- /** One series line (net worth). Crosshair + tooltip. */
66
- function lineChart(points, { label }) {
67
- const W = 480, H = 220, L = 46, R = 10, T = 12, B = 26;
68
- const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, class: "chart", role: "img", "aria-label": label });
69
- const vals = points.map((p) => p.v);
70
- const ticks = niceTicks(Math.min(0, ...vals), Math.max(...vals));
71
- const y0 = ticks[0], y1 = ticks.at(-1);
72
- const x = (i) => L + (points.length === 1 ? 0 : (i * (W - L - R)) / (points.length - 1));
73
- const y = (v) => T + ((y1 - v) * (H - T - B)) / (y1 - y0);
74
- const g = el("g", { class: "grid" }, svg);
75
- for (const t of ticks) {
76
- el("line", { x1: L, x2: W - R, y1: y(t), y2: y(t) }, g);
77
- el("text", { x: L - 6, y: y(t) + 4, "text-anchor": "end" }, svg).textContent = short(t);
78
- }
79
- points.forEach((p, i) => {
80
- if (points.length <= 13 || i % Math.ceil(points.length / 12) === 0) el("text", { x: x(i), y: H - 6, "text-anchor": "middle" }, svg).textContent = p.label;
81
- });
82
- el("path", { d: points.map((p, i) => `${i ? "L" : "M"}${x(i)},${y(p.v)}`).join(""), fill: "none", stroke: "var(--series-1)", "stroke-width": 2, "stroke-linejoin": "round", "stroke-linecap": "round" }, svg);
83
- const last = points.at(-1);
84
- el("circle", { cx: x(points.length - 1), cy: y(last.v), r: 4, fill: "var(--series-1)", stroke: "var(--surface-1)", "stroke-width": 2 }, svg);
85
- const cross = el("line", { y1: T, y2: H - B, stroke: "var(--text-muted)", "stroke-dasharray": "3 3", visibility: "hidden" }, svg);
86
- const dot = el("circle", { r: 4, fill: "var(--series-1)", stroke: "var(--surface-1)", "stroke-width": 2, visibility: "hidden" }, svg);
87
- const hit = el("rect", { x: L, y: T, width: W - L - R, height: H - T - B, fill: "transparent" }, svg);
88
- hit.addEventListener("pointermove", (ev) => {
89
- const r = svg.getBoundingClientRect();
90
- const px = ((ev.clientX - r.left) / r.width) * W;
91
- const i = Math.max(0, Math.min(points.length - 1, Math.round(((px - L) / (W - L - R)) * (points.length - 1))));
92
- cross.setAttribute("x1", x(i)); cross.setAttribute("x2", x(i)); cross.setAttribute("visibility", "visible");
93
- dot.setAttribute("cx", x(i)); dot.setAttribute("cy", y(points[i].v)); dot.setAttribute("visibility", "visible");
94
- showTip(ev, `<b>${esc(points[i].label)}</b><br>${esc(label)}: ${money(points[i].v)}`);
95
- });
96
- hit.addEventListener("pointerleave", () => { hideTip(); cross.setAttribute("visibility", "hidden"); dot.setAttribute("visibility", "hidden"); });
97
- return svg;
98
- }
99
-
100
- /** Grouped columns: income (series-1) and spending (series-2) per month. */
101
- function columns(groups, series) {
102
- const W = 480, H = 220, L = 46, R = 10, T = 12, B = 26;
103
- const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, class: "chart", role: "img", "aria-label": series.map((s) => s.label).join(" and ") });
104
- const max = Math.max(1, ...groups.flatMap((g) => series.map((s) => g[s.key])));
105
- const ticks = niceTicks(0, max);
106
- const y1 = ticks.at(-1);
107
- const y = (v) => T + ((y1 - v) * (H - T - B)) / y1;
108
- const g0 = el("g", { class: "grid" }, svg);
109
- for (const t of ticks) {
110
- el("line", { x1: L, x2: W - R, y1: y(t), y2: y(t) }, g0);
111
- el("text", { x: L - 6, y: y(t) + 4, "text-anchor": "end" }, svg).textContent = short(t);
112
- }
113
- const band = (W - L - R) / groups.length;
114
- const bw = Math.min(24, (band - 8) / series.length - 2);
115
- groups.forEach((g, i) => {
116
- const cx = L + band * i + band / 2;
117
- series.forEach((s, j) => {
118
- const v = g[s.key];
119
- const h = Math.max(0, y(0) - y(v));
120
- const x0 = cx - (series.length * (bw + 2)) / 2 + j * (bw + 2);
121
- const r = Math.min(4, h / 2, bw / 2);
122
- const top = y(0) - h;
123
- el("path", { d: `M${x0},${y(0)} V${top + r} Q${x0},${top} ${x0 + r},${top} H${x0 + bw - r} Q${x0 + bw},${top} ${x0 + bw},${top + r} V${y(0)} Z`, fill: s.color }, svg);
124
- });
125
- el("text", { x: cx, y: H - 6, "text-anchor": "middle" }, svg).textContent = g.label;
126
- const hit = el("rect", { x: L + band * i, y: T, width: band, height: H - T - B, fill: "transparent" }, svg);
127
- hit.addEventListener("pointermove", (ev) => showTip(ev, `<b>${esc(g.label)}</b><br>${series.map((s) => `${esc(s.label)}: ${money(g[s.key])}`).join("<br>")}`));
128
- hit.addEventListener("pointerleave", hideTip);
129
- });
130
- return svg;
131
- }
132
-
133
- /** Horizontal bars, one hue (magnitude), value labels outside the bar end. */
134
- function hbars(rows, { total }) {
135
- const W = 480, rowH = 26, L = 140, R = 90;
136
- const H = rows.length * rowH + 4;
137
- const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, class: "chart", role: "img", "aria-label": "Spending by category" });
138
- const max = Math.max(1, ...rows.map((r) => r.v));
139
- rows.forEach((r, i) => {
140
- const yy = i * rowH + 4;
141
- const w = Math.max(2, ((W - L - R) * r.v) / max);
142
- el("text", { x: L - 8, y: yy + 14, "text-anchor": "end" }, svg).textContent = r.label.length > 22 ? r.label.slice(0, 21) + "…" : r.label;
143
- const rr = Math.min(4, w / 2);
144
- el("path", { d: `M${L},${yy + 3} H${L + w - rr} Q${L + w},${yy + 3} ${L + w},${yy + 3 + rr} V${yy + 17 - rr} Q${L + w},${yy + 17} ${L + w - rr},${yy + 17} H${L} Z`, fill: "var(--series-2)" }, svg);
145
- el("text", { x: L + w + 6, y: yy + 14 }, svg).textContent = `${short(r.v)}${total ? ` · ${Math.round((r.v / total) * 100)}%` : ""}`;
146
- const hit = el("rect", { x: 0, y: yy, width: W, height: rowH, fill: "transparent" }, svg);
147
- hit.addEventListener("pointermove", (ev) => showTip(ev, `<b>${esc(r.label)}</b><br>${money(r.v)}${r.prev !== undefined ? `<br><span class="muted">previous: ${money(r.prev)}</span>` : ""}`));
148
- hit.addEventListener("pointerleave", hideTip);
149
- });
150
- return svg;
151
- }
152
-
153
- const tableOf = (head, rows) =>
154
- `<details class="table"><summary>Table</summary><table><tr>${head.map((h, i) => `<th class="${i ? "num" : ""}">${esc(h)}</th>`).join("")}</tr>${rows.map((r) => `<tr>${r.map((c, i) => `<td class="${i ? "num" : ""}">${i ? money(c) : esc(c)}</td>`).join("")}</tr>`).join("")}</table></details>`;
155
-
156
- /* ------------------------------------------------------------------ pages */
157
-
158
- const catName = (path) => META?.categories.find((c) => c.path === path)?.name ?? path;
159
- const accName = (id) => META?.accounts.find((a) => a.id === id)?.name ?? id;
160
- const typeName = (t) => META?.types[t]?.[ME?.locale === "vi" ? "vi" : "en"] ?? t;
161
- const lineText = (l) => (l.account ? `<span class="pill">${esc(accName(l.account))}</span>` : `${esc(catName(l.category))}`);
162
-
163
- async function overview() {
164
- const o = await api("overview");
165
- const m = o.month;
166
- const t = o.today;
167
- const dueItems = [
168
- ...t.due.map((d) => `<li>${esc(d.date)} · ${esc(d.name)} · ${money(d.amount)}${d.overdue ? ' <span class="status bad">⚠ overdue</span>' : ""}</li>`),
169
- ...t.cards.map((c) => `<li>${esc(c.dueDate)} · ${esc(c.name)} · pay ${money(c.toPay)}</li>`),
170
- ...t.maturing.map((d) => `<li>${esc(d.maturity)} · ${esc(d.name)} matures · ${money(d.principal)}</li>`),
171
- ...t.overBudget.map((b) => `<li><span class="status bad">⚠ over budget</span> ${esc(catName(b.category))}: ${money(b.spent)} / ${money(b.amount)}</li>`),
172
- ...t.odd.map((s) => `<li class="muted">${esc(s)}</li>`),
173
- ];
174
- main.innerHTML = `<h1>${esc(ME.name ?? "Overview")}</h1>
175
- <div class="grid">
176
- <div class="card stat"><div class="label">Net worth</div><div class="value">${money(o.netWorth.net)}</div><div class="delta">assets ${short(o.netWorth.assets)} · owed ${short(-o.netWorth.liabilities)}</div></div>
177
- <div class="card stat"><div class="label">Spent this month</div><div class="value">${money(m.expense)}</div><div class="delta">${m.previous ? `${pct(m.expense, m.previous.expense)} vs last month (${short(m.previous.expense)})` : ""}</div></div>
178
- <div class="card stat"><div class="label">Income this month</div><div class="value">${money(m.income)}</div><div class="delta">${m.previous ? `last month ${short(m.previous.income)}` : ""}</div></div>
179
- </div>
180
- <div class="grid two" style="margin-top:1rem">
181
- <div class="card"><h2>Net worth, 12 months</h2><div id="nw"></div></div>
182
- <div class="card"><h2>Due soon</h2>${dueItems.length ? `<ul>${dueItems.join("")}</ul>` : '<p class="muted">Nothing due in the next days.</p>'}</div>
183
- <div class="card"><h2>Spending this month</h2><div id="top"></div></div>
184
- </div>`;
185
- const pts = o.series.map((s) => ({ label: s.date.slice(2, 7), v: s.net }));
186
- $("#nw").append(lineChart(pts, { label: "Net worth" }));
187
- $("#nw").insertAdjacentHTML("beforeend", tableOf(["Month", "Net worth"], o.series.map((s) => [s.date.slice(0, 7), s.net])));
188
- const top = m.top.map((r) => ({ label: r.name, v: r.expense, prev: m.previous?.rows?.[r.key]?.expense }));
189
- if (top.length) $("#top").append(hbars(top, { total: m.expense }));
190
- else $("#top").innerHTML = '<p class="muted">No spending yet this month.</p>';
191
- }
192
-
193
- async function transactions(params) {
194
- const q = new URLSearchParams(params);
195
- if (!q.get("limit")) q.set("limit", "100");
196
- const r = await api(`transactions?${q}`);
197
- const opts = (list, sel) => list.map(([v, l]) => `<option value="${esc(v)}" ${v === sel ? "selected" : ""}>${esc(l)}</option>`).join("");
198
- main.innerHTML = `<h1>Transactions</h1>
199
- <form class="filters" id="f">
200
- <input name="text" placeholder="Search note, who, event…" value="${esc(q.get("text") ?? "")}">
201
- <select name="account"><option value="">All accounts</option>${opts(META.accounts.filter((a) => !a.closed).map((a) => [a.id, a.name]), q.get("account"))}</select>
202
- <select name="category"><option value="">All categories</option>${opts(META.categories.map((c) => [c.path, `${c.parent ? " " : ""}${c.name}`]), q.get("category"))}</select>
203
- <input name="from" type="date" value="${esc(q.get("from") ?? "")}"> <input name="to" type="date" value="${esc(q.get("to") ?? "")}">
204
- <button class="primary">Filter</button> <span class="muted small">${fmt(r.total)} found</span>
205
- </form>
206
- <div class="card"><table><tr><th>Date</th><th>Note</th><th>Lines</th><th class="num">Amount</th></tr>
207
- ${r.items.map((t) => {
208
- const size = t.lines.reduce((s, l) => s + (l.amount > 0 ? l.amount : 0), 0);
209
- const acc = t.lines.find((l) => l.account);
210
- return `<tr class="${t.void ? "void" : ""}"><td class="small">${esc(t.date)}${t.time ? `<br><span class="muted">${esc(t.time)}</span>` : ""}</td>
211
- <td>${esc(t.note)}${t.who ? ` <span class="pill">${esc(t.who)}</span>` : ""}${t.event ? ` <span class="pill">${esc(t.event)}</span>` : ""}${(t.tags ?? []).map((g) => ` <span class="pill">#${esc(g)}</span>`).join("")}</td>
212
- <td class="small">${t.lines.map(lineText).join(" → ")}</td>
213
- <td class="num">${t.lines.every((l) => l.account) ? money(size) : signed(acc ? acc.amount : -size)}</td></tr>`;
214
- }).join("")}</table>${r.total > r.items.length ? `<p class="muted small">Showing ${r.items.length} of ${fmt(r.total)}. Narrow the filters to see more.</p>` : ""}</div>`;
215
- $("#f").addEventListener("submit", (e) => {
216
- e.preventDefault();
217
- const p = new URLSearchParams([...new FormData(e.target)].filter(([, v]) => v));
218
- location.hash = `#/transactions?${p}`;
219
- });
220
- }
221
-
222
- async function accounts() {
223
- const list = await api("accounts");
224
- const showClosed = location.hash.includes("closed=1");
225
- const groups = {};
226
- for (const a of list) if (showClosed || !a.closed) (groups[a.type] ??= []).push(a);
227
- const cards = await api("cards");
228
- const deps = await api("deposits");
229
- main.innerHTML = `<h1>Accounts</h1><p class="small"><a href="#/accounts${showClosed ? "" : "?closed=1"}">${showClosed ? "Hide" : "Show"} closed accounts</a></p>
230
- <div class="grid two">${Object.entries(groups).map(([type, as]) => `<div class="card"><h2>${esc(typeName(type))} <span class="muted small">${money(as.reduce((s, a) => s + a.value, 0))}</span></h2>
231
- <table>${as.map((a) => {
232
- const c = cards.find((x) => x.account === a.id);
233
- const d = deps.find((x) => x.account === a.id);
234
- const extra = c ? `statement ${esc(c.statementDate ?? "?")} · pay ${money(c.toPay)} by ${esc(c.dueDate ?? "?")}${c.limit ? ` · available ${short(c.available)}` : ""}`
235
- : d ? `${d.rate ?? "?"}% · matures ${esc(d.maturity ?? "?")}${d.interestAtMaturity ? ` · +${short(d.interestAtMaturity)}` : ""}`
236
- : a.qty !== null && a.qty !== undefined ? `${a.qty} ${esc(a.asset)} · cost ${short(a.cost)}${a.priced ? "" : " · no price"}` : "";
237
- return `<tr><td>${esc(a.name)}${a.closed ? ' <span class="pill">closed</span>' : ""}${extra ? `<br><span class="muted small">${extra}</span>` : ""}</td><td class="num">${signed(a.value)}</td></tr>`;
238
- }).join("")}</table></div>`).join("")}</div>`;
239
- }
240
-
241
- async function plans() {
242
- const p = await api("plans?days=90");
243
- main.innerHTML = `<h1>Plans</h1><div class="grid two">
244
- <div class="card"><h2>Due in the next 90 days</h2>${p.due.length ? `<table>${p.due.map((d) => `<tr><td>${esc(d.date)}${d.overdue ? ' <span class="status bad">⚠ overdue</span>' : ""}</td><td>${esc(d.name)}</td><td class="num">${money(d.amount)}</td></tr>`).join("")}</table>` : '<p class="muted">Nothing due.</p>'}</div>
245
- <div class="card"><h2>All plans</h2>${p.status.length ? `<table><tr><th>Plan</th><th class="num">Paid</th><th class="num">Left</th><th>Next</th></tr>${p.status.map((s) => `<tr><td>${esc(s.name)}<br><span class="muted small">${esc(s.kind)} · ${esc(accName(s.account))} · ${money(s.perPayment)}</span></td><td class="num">${s.paidCount}${s.count ? `/${s.count}` : ""}</td><td class="num">${s.leftAmount === null ? "—" : money(s.leftAmount)}</td><td>${s.finished ? '<span class="status ok">✓ done</span>' : esc(s.next ?? "")}</td></tr>`).join("")}</table>` : '<p class="muted">No plans yet. Ask in chat: “add an instalment plan…”.</p>'}</div></div>`;
246
- }
247
-
248
- async function reports(params) {
249
- const q = new URLSearchParams(params);
250
- const period = q.get("period") ?? ME.today.slice(0, 4);
251
- const by = q.get("by") ?? "top";
252
- const r = await api(`report?period=${encodeURIComponent(period)}&by=${by}`);
253
- const months = await api(`report?period=${encodeURIComponent(period.slice(0, 4))}&by=month`);
254
- const years = [];
255
- for (let y = Number(ME.today.slice(0, 4)); y >= Number(ME.today.slice(0, 4)) - 8; y--) years.push(String(y));
256
- main.innerHTML = `<h1>Reports</h1>
257
- <form class="filters" id="f"><select name="period">${years.map((y) => `<option ${y === period ? "selected" : ""}>${y}</option>`).join("")}${period.length === 7 ? `<option selected>${esc(period)}</option>` : ""}</select>
258
- <select name="by">${[["top", "Top category"], ["category", "Category"], ["account", "Account"], ["who", "Who"], ["event", "Event"], ["tag", "Tag"]].map(([v, l]) => `<option value="${v}" ${v === by ? "selected" : ""}>${l}</option>`).join("")}</select>
259
- <input name="month" type="month" value="${period.length === 7 ? esc(period) : ""}" title="or one month"><button class="primary">Show</button></form>
260
- <div class="grid">
261
- <div class="card stat"><div class="label">Income</div><div class="value">${money(r.income)}</div><div class="delta">${r.previous ? `${pct(r.income, r.previous.income)} vs ${esc(r.previous.period.from.slice(0, 7))}…` : ""}</div></div>
262
- <div class="card stat"><div class="label">Spending</div><div class="value">${money(r.expense)}</div><div class="delta">${r.previous ? `${pct(r.expense, r.previous.expense)} vs previous` : ""}</div></div>
263
- <div class="card stat"><div class="label">Net</div><div class="value">${signed(r.net)}</div></div>
264
- </div>
265
- <div class="grid two" style="margin-top:1rem">
266
- <div class="card"><h2>By month, ${esc(period.slice(0, 4))}</h2><div class="legend"><span><i style="background:var(--series-1)"></i>Income</span><span><i style="background:var(--series-2)"></i>Spending</span></div><div id="cols"></div></div>
267
- <div class="card"><h2>Spending by ${by === "top" ? "category" : esc(by)}</h2><div id="bars"></div></div>
268
- </div>
269
- <div class="card" style="margin-top:1rem"><h2>Detail</h2><table><tr><th></th><th class="num">Income</th><th class="num">Spending</th><th class="num">Previous</th><th class="num">Rows</th></tr>
270
- ${r.rows.map((x) => { const pv = r.previous?.rows?.[x.key]; return `<tr><td>${esc(x.name)}</td><td class="num">${x.income ? money(x.income) : ""}</td><td class="num">${x.expense ? money(x.expense) : ""}</td><td class="num muted">${pv ? money(pv.expense || pv.income) : ""}</td><td class="num">${x.count}</td></tr>`; }).join("")}</table></div>`;
271
- const groups = months.rows.sort((a, b) => (a.key < b.key ? -1 : 1)).map((m) => ({ label: m.key.slice(5), income: m.income, expense: m.expense }));
272
- $("#cols").append(columns(groups, [{ key: "income", label: "Income", color: "var(--series-1)" }, { key: "expense", label: "Spending", color: "var(--series-2)" }]));
273
- $("#cols").insertAdjacentHTML("beforeend", tableOf(["Month", "Income", "Spending"], groups.map((g) => [g.label, g.income, g.expense])));
274
- const bars = r.rows.filter((x) => x.expense > 0).slice(0, 12).map((x) => ({ label: x.name, v: x.expense, prev: r.previous?.rows?.[x.key]?.expense }));
275
- if (bars.length) $("#bars").append(hbars(bars, { total: r.expense }));
276
- $("#f").addEventListener("submit", (e) => {
277
- e.preventDefault();
278
- const f = new FormData(e.target);
279
- location.hash = `#/reports?period=${f.get("month") || f.get("period")}&by=${f.get("by")}`;
280
- });
281
- }
282
-
283
- async function importPage() {
284
- const maps = await api("import/mappings");
285
- main.innerHTML = `<h1>Import</h1>
286
- <div class="card"><p>Import a newer export from an app you already imported once (its mapping is in <code>imports/</code>). The file is read in your browser and sent only to your own Worker. Nothing is written until you confirm.</p>
287
- ${maps.length ? `<form class="filters" id="f"><input type="file" name="file" accept=".xlsx,.csv,.json" required>
288
- <select name="mapping">${maps.map((m) => `<option>${esc(m)}</option>`).join("")}</select><button class="primary">Preview</button></form>`
289
- : '<p class="muted">No mapping yet. The first import of a new app is done once with the CLI and your AI (<code>npx ownledger import &lt;file&gt;</code>, see AGENTS.md).</p>'}
290
- <div id="out"></div></div>`;
291
- $("#f")?.addEventListener("submit", async (e) => {
292
- e.preventDefault();
293
- const f = new FormData(e.target);
294
- const file = f.get("file");
295
- const buf = new Uint8Array(await file.arrayBuffer());
296
- let bin = "";
297
- for (let i = 0; i < buf.length; i += 0x8000) bin += String.fromCharCode(...buf.subarray(i, i + 0x8000));
298
- $("#out").innerHTML = '<p class="muted">Reading and reconciling…</p>';
299
- try {
300
- const r = await api("import/preview", { method: "POST", body: JSON.stringify({ file_name: file.name, base64: btoa(bin), mapping: f.get("mapping") }) });
301
- const p = r.report;
302
- const bad = p.reconcile.filter((x) => !x.ok);
303
- $("#out").innerHTML = `<h2>${p.ok ? '<span class="status ok">✓ Reconciles</span>' : '<span class="status bad">✗ Refused</span>'}</h2>
304
- <p>${fmt(p.rows)} rows · <b>${fmt(p.new)} new</b> · ${fmt(p.skipped)} already imported · ${p.accounts.length} new account(s) ${p.accounts.map((a) => `<span class="pill">${esc(a)}</span>`).join("")}</p>
305
- <p>${p.reconcile.length - bad.length}/${p.reconcile.length} accounts match the app's own balances.</p>
306
- ${bad.length ? `<table><tr><th>Account</th><th>Problem</th></tr>${bad.map((b) => `<tr><td>${esc(b.sheet)}</td><td>${esc(b.problems.join("; "))}</td></tr>`).join("")}</table>` : ""}
307
- ${p.unresolvedCategories.length ? `<p class="status bad">Categories not in the mapping:</p><ul>${p.unresolvedCategories.map((u) => `<li>${esc(u.key)} (${u.rows})</li>`).join("")}</ul>` : ""}
308
- ${p.unpaired.length ? `<p>Transfers without their other side: ${p.unpaired.length}</p>` : ""}
309
- ${p.changed.length || p.gone.length ? `<p class="status bad">⚠ ${p.changed.length} changed and ${p.gone.length} gone in the source: not applied, decide by hand.</p>` : ""}
310
- ${p.errors.length ? `<pre>${esc(p.errors.join("\n"))}</pre>` : ""}
311
- ${p.sample.length ? `<details class="table" open><summary>New transactions (first ${p.sample.length})</summary><table>${p.sample.map((t) => `<tr><td class="small">${esc(t.date)}</td><td>${esc(t.note)}</td><td class="small">${t.lines.map(lineText).join(" → ")}</td></tr>`).join("")}</table></details>` : ""}
312
- ${r.preview_id ? `<p><button class="primary" id="apply">Commit ${fmt(p.new)} transaction(s)</button> <span class="muted small">${esc(r.message)}</span></p>` : p.ok ? '<p class="muted">Nothing new to import.</p>' : ""}`;
313
- $("#apply")?.addEventListener("click", async (ev) => {
314
- ev.target.disabled = true;
315
- try {
316
- const a = await api("import/apply", { method: "POST", body: JSON.stringify({ preview_id: r.preview_id }) });
317
- $("#out").insertAdjacentHTML("beforeend", `<p class="status ok">✓ Committed ${esc(a.sha.slice(0, 10))}: ${esc(a.message)}</p>`);
318
- } catch (err) {
319
- $("#out").insertAdjacentHTML("beforeend", `<p class="status bad">✗ ${esc(err.message)}</p>`);
320
- }
321
- });
322
- } catch (err) {
323
- $("#out").innerHTML = `<p class="status bad">✗ ${esc(err.message)}</p>`;
324
- }
325
- });
326
- }
327
-
328
- async function settings() {
329
- const grants = await api("grants").catch(() => []);
330
- main.innerHTML = `<h1>Settings</h1><div class="grid two">
331
- <div class="card"><h2>Your ledger</h2><table>
332
- <tr><td>Signed in</td><td>${esc(ME.login)}</td></tr><tr><td>Data</td><td>${esc(ME.data)}</td></tr>
333
- <tr><td>Commit</td><td><code>${esc(ME.commit.slice(0, 12))}</code></td></tr><tr><td>ownledger</td><td>${esc(ME.version)}</td></tr>
334
- <tr><td>Check</td><td>${ME.check.errors ? `<span class="status bad">✗ ${ME.check.errors} error(s)</span>` : '<span class="status ok">✓ ok</span>'} ${ME.check.warnings ? `· ${ME.check.warnings} warning(s)` : ""}</td></tr>
335
- <tr><td>Connector</td><td><code>${esc(location.origin)}/mcp</code></td></tr></table>
336
- <form method="post" action="/auth/logout" style="margin-top:1rem"><button>Sign out</button></form></div>
337
- <div class="card"><h2>Connected AI apps</h2>${grants.length ? `<table>${grants.map((g) => `<tr><td>${esc(g.client)}<br><span class="muted small">since ${esc(new Date(g.created * 1000).toISOString().slice(0, 10))}</span></td><td class="num"><button data-g="${esc(g.id)}">Revoke</button></td></tr>`).join("")}</table>` : '<p class="muted">None yet. Add the connector URL in Claude or ChatGPT.</p>'}</div></div>`;
338
- main.querySelectorAll("button[data-g]").forEach((b) =>
339
- b.addEventListener("click", async () => {
340
- b.disabled = true;
341
- await api(`grants?id=${encodeURIComponent(b.dataset.g)}`, { method: "DELETE" });
342
- settings();
343
- }),
344
- );
345
- }
346
-
347
- /* ------------------------------------------------------------------ router */
348
-
349
- const routes = { "": overview, transactions, accounts, plans, reports, import: importPage, settings };
350
-
351
- async function route() {
352
- const [path, qs] = location.hash.replace(/^#\/?/, "").split("?");
353
- const page = routes[path] ?? overview;
354
- document.querySelectorAll("#nav a").forEach((a) => a.classList.toggle("on", a.getAttribute("href") === `#/${path}`));
355
- hideTip();
356
- try {
357
- if (!ME) {
358
- ME = await api("me");
359
- META = await api("meta");
360
- $("#who").textContent = ME.login;
361
- document.documentElement.lang = ME.locale ?? "en";
362
- }
363
- await page(Object.fromEntries(new URLSearchParams(qs ?? "")));
364
- } catch (e) {
365
- if (e.message !== "sign in") main.innerHTML = `<div class="card"><p class="status bad">✗ ${esc(e.message)}</p></div>`;
366
- }
367
- }
368
- addEventListener("hashchange", route);
369
- route();