ownledger 2.0.0 → 2.1.1

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 (87) hide show
  1. package/AGENTS.md +45 -0
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +13 -0
  4. package/assets/index.html +11 -11
  5. package/assets/static/{Account-DEBzshne.js → Account-CYrXDU9Z.js} +1 -1
  6. package/assets/static/{Accounts-C1iNsQsy.js → Accounts-BXleOwUO.js} +1 -1
  7. package/assets/static/{Attention-qo4v70P1.js → Attention-Ci3luOdE.js} +1 -1
  8. package/assets/static/{ByCategory-33P2zSs-.js → ByCategory-cLVOyjwd.js} +1 -1
  9. package/assets/static/CardDetail-BxXfAcMp.js +1 -0
  10. package/assets/static/{Cards-C3AdusmT.js → Cards-DNtITMnA.js} +1 -1
  11. package/assets/static/{Cards-DuqZFxkQ.js → Cards-DnIsAWPD.js} +1 -1
  12. package/assets/static/{CardsValue-BM9WUQmy.js → CardsValue-V1-fYMLf.js} +1 -1
  13. package/assets/static/{Cashback-DsWyjgRr.js → Cashback-B8lqwRnb.js} +1 -1
  14. package/assets/static/{CategoryIcon-E6EWIpbr.js → CategoryIcon-D4Cdb_ZP.js} +1 -1
  15. package/assets/static/{CategoryPicker-BPeJNSuM.js → CategoryPicker-54vkuxVh.js} +1 -1
  16. package/assets/static/{ChartWidget-Bk1TAvJM.js → ChartWidget-S5F4Ze91.js} +1 -1
  17. package/assets/static/{Combobox-lRNTmjKR.js → Combobox-BvX68J3o.js} +1 -1
  18. package/assets/static/{Deposits-CgEFypxb.js → Deposits-Ct5HhCEc.js} +1 -1
  19. package/assets/static/{DrillLink-pa6s17Xu.js → DrillLink-CZyI-y0-.js} +1 -1
  20. package/assets/static/{Field-OkPhoYM1.js → Field-DYmqEAlI.js} +1 -1
  21. package/assets/static/{HomeEditor-DdrzEPe2.js → HomeEditor-Dv-h_ql-.js} +1 -1
  22. package/assets/static/{Import-DrhHmL65.js → Import-B2uhVnEm.js} +1 -1
  23. package/assets/static/{IncomeSpending-Cveqr3xt.js → IncomeSpending-DNT2CWH9.js} +1 -1
  24. package/assets/static/{KV-CKGyL0p7.js → KV-CKWaJkRK.js} +1 -1
  25. package/assets/static/{Left-Bs_oKU19.js → Left-BefXZztB.js} +1 -1
  26. package/assets/static/{Money-DCMKf898.js → Money-BwLucm7P.js} +1 -1
  27. package/assets/static/{NetWorth-Cjd13J56.js → NetWorth-DeLSapZ2.js} +1 -1
  28. package/assets/static/{Pace-CBUDNxzH.js → Pace-D6gilOBZ.js} +1 -1
  29. package/assets/static/{Panel-CXjnsEN0.js → Panel-CSe25x0N.js} +1 -1
  30. package/assets/static/{PinDialog-DoGuAyi4.js → PinDialog-CHiLIKEs.js} +1 -1
  31. package/assets/static/{Plans-EWJdPCJ3.js → Plans-D7rJ1yHU.js} +1 -1
  32. package/assets/static/{Recent-BmJjA5dK.js → Recent-Dcqb2yko.js} +1 -1
  33. package/assets/static/{Reports-DSrLn_wC.js → Reports--PDAEnQM.js} +1 -1
  34. package/assets/static/{Settings-DdiEp2Qi.js → Settings-Bd0oglWl.js} +1 -1
  35. package/assets/static/{Transactions-Cy0kgcLE.js → Transactions-CQ1yQ1UU.js} +1 -1
  36. package/assets/static/{TxRow-IqjFXpya.js → TxRow-BGfpKo2m.js} +1 -1
  37. package/assets/static/{Unusual-D5-L9ZOy.js → Unusual-DGB4ZOA2.js} +1 -1
  38. package/assets/static/{Upcoming-CCqPol8c.js → Upcoming-B0HwBqmG.js} +1 -1
  39. package/assets/static/{WhichCard-Butdi7AN.js → WhichCard-BefFKS2q.js} +1 -1
  40. package/assets/static/{arrow-up-C8D_7x_H.js → arrow-up-CRgLRKET.js} +1 -1
  41. package/assets/static/{bits-BoWPOwTB.js → bits-D34d9IBm.js} +1 -1
  42. package/assets/static/{button-Cj0k8AtB.js → button-BKhMn8jX.js} +1 -1
  43. package/assets/static/{cards-AZlSJQ0z.js → cards-Ct0jh73r.js} +1 -1
  44. package/assets/static/{charts-Cj_hTR4h.js → charts-D-1glV8L.js} +1 -1
  45. package/assets/static/chevron-down-BWoQwA6m.js +1 -0
  46. package/assets/static/chevron-right-D7Sgw1v1.js +1 -0
  47. package/assets/static/{createLucideIcon-DUW9Fpzj.js → createLucideIcon-XZ28znwT.js} +1 -1
  48. package/assets/static/{dialog-BIbLA-XP.js → dialog-Bx-cd-2e.js} +1 -1
  49. package/assets/static/{dist-CbNfxqbd.js → dist--HKr0kfV.js} +1 -1
  50. package/assets/static/{dist-DYP_TYPy.js → dist-BFPyD74_.js} +1 -1
  51. package/assets/static/{dist-CetESl7K.js → dist-CmbuesVk.js} +1 -1
  52. package/assets/static/{dist-DaSyQKU7.js → dist-vgyaCpaL.js} +1 -1
  53. package/assets/static/{es2015-BgAh-EkH.js → es2015-DqY4UvQc.js} +1 -1
  54. package/assets/static/{index-DYyIpxqK.js → index-DBHFdsYB.js} +4 -4
  55. package/assets/static/index-iYMxgw-7.css +1 -0
  56. package/assets/static/{queries-C_4ufx4u.js → queries-BcMmmb36.js} +1 -1
  57. package/assets/static/{react-dom-CI34djkT.js → react-dom-5dgiSOdd.js} +1 -1
  58. package/assets/static/{select-2EwEpMf_.js → select-B5P2TaPX.js} +1 -1
  59. package/assets/static/{shared-CR-hvb-r.js → shared-BgU6fc7z.js} +1 -1
  60. package/assets/static/{triangle-exclamation-point-C6padEUM.js → triangle-exclamation-point-CMy18kC0.js} +1 -1
  61. package/assets/static/{useMutation-BWtHiYPX.js → useMutation-aC3Z1p9y.js} +1 -1
  62. package/dist/cli/check.js +7 -1
  63. package/dist/cli/dev.js +22 -2
  64. package/dist/cli/index.js +3 -0
  65. package/dist/cli/statements.d.ts +1 -0
  66. package/dist/cli/statements.js +231 -0
  67. package/dist/modules/api.d.ts +3 -0
  68. package/dist/modules/cards/api.d.ts +1 -1
  69. package/dist/modules/cards/api.js +34 -2
  70. package/dist/modules/cards/files.d.ts +11 -0
  71. package/dist/modules/cards/files.js +17 -0
  72. package/dist/node/statements.d.ts +64 -0
  73. package/dist/node/statements.js +218 -0
  74. package/dist/worker/api.js +14 -5
  75. package/dist/worker/github.d.ts +20 -1
  76. package/dist/worker/github.js +63 -5
  77. package/dist/worker/store.d.ts +2 -0
  78. package/dist/worker/store.js +8 -3
  79. package/dist/worker/version.d.ts +1 -1
  80. package/dist/worker/version.js +1 -1
  81. package/package.json +3 -1
  82. package/assets/static/CardDetail-CvRo7JPt.js +0 -1
  83. package/assets/static/chevron-down-BLodeu9a.js +0 -1
  84. package/assets/static/chevron-right-BetctQ6k.js +0 -1
  85. package/assets/static/index-CBsgYTMJ.css +0 -1
  86. package/dist/worker/tar.d.ts +0 -2
  87. package/dist/worker/tar.js +0 -62
@@ -0,0 +1,64 @@
1
+ import type { ISODate } from "../engine/types.js";
2
+ import { STATEMENTS_DIR } from "../modules/cards/files.js";
3
+ /**
4
+ * Bank statements (plan 004): imports/statements/<account-id>/<YYYY-MM>.pdf, unlocked.
5
+ * Read on the user's computer only (CLI); the Worker never parses them.
6
+ */
7
+ export { STATEMENTS_DIR };
8
+ export declare const SOURCES_FILE = "imports/statements/sources.yaml";
9
+ export declare const ENV_FILE = ".env.statements";
10
+ export declare class PdfPasswordError extends Error {
11
+ }
12
+ /**
13
+ * The PDF without any encryption (same bytes for the same input: --deterministic-id).
14
+ * Throws PdfPasswordError when it needs a password and none (or a wrong one) is given.
15
+ */
16
+ export declare function unlockPdf(bytes: Uint8Array, password?: string): Promise<{
17
+ bytes: Uint8Array;
18
+ wasLocked: boolean;
19
+ }>;
20
+ /** True when the PDF can't be opened without a password. */
21
+ export declare function isLocked(bytes: Uint8Array): Promise<boolean>;
22
+ /** The PDF's text, pages joined (pdf.js via unpdf). */
23
+ export declare function pdfText(bytes: Uint8Array): Promise<string>;
24
+ /** Every calendar date written in the text (dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy, yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd). */
25
+ export declare function datesIn(text: string): Set<ISODate>;
26
+ export interface MonthGuess {
27
+ month: string | null;
28
+ from?: ISODate;
29
+ close?: ISODate;
30
+ why: string;
31
+ }
32
+ /**
33
+ * The statement period a statement's text is about, from the card's statement day: the period whose first and
34
+ * last days both appear in the text; else the one period whose close date appears. Never guesses between two.
35
+ */
36
+ export declare function monthFromText(text: string, statementDay: number | null): MonthGuess;
37
+ /** KEY=value lines of .env.statements (quotes stripped, # comments). Missing file: {}. */
38
+ export declare function readEnvFile(root: string): Record<string, string>;
39
+ export interface StatementSource {
40
+ from?: string;
41
+ subject?: string;
42
+ /** Name of the variable in .env.statements. */
43
+ password?: string;
44
+ /** What the password is made of (never the password). */
45
+ password_hint?: string;
46
+ }
47
+ /** imports/statements/sources.yaml: account id → how to find its statements in email. Missing file: {}. */
48
+ export declare function readSources(root: string): Record<string, StatementSource>;
49
+ /** The variables tried for a card's password, in order: sources.yaml's, PW_<ACCOUNT_ID>, PW_<FIRST WORD>. */
50
+ export declare function passwordVars(account: string, source?: StatementSource): string[];
51
+ export interface StatementFile {
52
+ account: string;
53
+ month: string;
54
+ path: string;
55
+ }
56
+ /** The statement PDFs on disk, and what doesn't fit the convention (warnings, never errors). */
57
+ export declare function scanStatements(root: string, accountIds: Set<string>): {
58
+ files: StatementFile[];
59
+ warnings: string[];
60
+ };
61
+ /** Months between the first and last filed month that have no file. */
62
+ export declare function missingMonths(months: string[]): string[];
63
+ /** Warnings for `ownledger check`: the convention, plus PDFs still locked. */
64
+ export declare function statementWarnings(root: string, accountIds: Set<string>): Promise<string[]>;
@@ -0,0 +1,218 @@
1
+ import { createRequire } from "node:module";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { parse as parseYaml } from "yaml";
5
+ import { addDays } from "../engine/dates.js";
6
+ import { STATEMENTS_DIR } from "../modules/cards/files.js";
7
+ import { closeOnOrAfter, prevClose } from "../modules/cards/statements.js";
8
+ /**
9
+ * Bank statements (plan 004): imports/statements/<account-id>/<YYYY-MM>.pdf, unlocked.
10
+ * Read on the user's computer only (CLI); the Worker never parses them.
11
+ */
12
+ export { STATEMENTS_DIR };
13
+ export const SOURCES_FILE = `${STATEMENTS_DIR}/sources.yaml`;
14
+ export const ENV_FILE = ".env.statements";
15
+ const MONTH_FILE = /^\d{4}-(0[1-9]|1[0-2])\.pdf$/;
16
+ const require = createRequire(import.meta.url);
17
+ /** Runs qpdf once in a fresh instance (an Emscripten program isn't meant to run twice) on /in.pdf → /out.pdf. */
18
+ async function qpdf(args, input) {
19
+ const { default: createModule } = (await import("@neslinesli93/qpdf-wasm"));
20
+ const wasm = require.resolve("@neslinesli93/qpdf-wasm/dist/qpdf.wasm");
21
+ let err = "";
22
+ // the build binds its output to console.log/console.error when created (print/printErr options are ignored):
23
+ // catch it for the error message instead of letting it reach the user's terminal
24
+ const { log, error } = console;
25
+ console.log = () => { };
26
+ console.error = (...a) => void (err += a.join(" ") + "\n");
27
+ const exitCode = process.exitCode; // qpdf's exit sets Node's exit code; keep ours
28
+ let rc;
29
+ let q;
30
+ try {
31
+ q = await createModule({ locateFile: () => wasm, noInitialRun: true });
32
+ q.FS.writeFile("/in.pdf", input);
33
+ try {
34
+ rc = q.callMain([...args, "/in.pdf", "/out.pdf"]);
35
+ }
36
+ catch (e) {
37
+ rc = typeof e.status === "number" ? e.status : 2;
38
+ }
39
+ }
40
+ finally {
41
+ console.log = log;
42
+ console.error = error;
43
+ process.exitCode = exitCode;
44
+ }
45
+ let out = null;
46
+ try {
47
+ out = q.FS.readFile("/out.pdf");
48
+ }
49
+ catch {
50
+ /* no output */
51
+ }
52
+ return { rc, out, err };
53
+ }
54
+ export class PdfPasswordError extends Error {
55
+ }
56
+ /**
57
+ * The PDF without any encryption (same bytes for the same input: --deterministic-id).
58
+ * Throws PdfPasswordError when it needs a password and none (or a wrong one) is given.
59
+ */
60
+ export async function unlockPdf(bytes, password) {
61
+ const tries = password ? [undefined, password] : [undefined];
62
+ for (const pw of tries) {
63
+ const r = await qpdf([...(pw ? [`--password=${pw}`] : []), "--decrypt", "--deterministic-id"], bytes);
64
+ if (r.rc === 0 || (r.rc === 3 && r.out))
65
+ return { bytes: r.out, wasLocked: pw !== undefined };
66
+ if (!/invalid password/i.test(r.err))
67
+ throw new Error(`not a readable PDF (${r.err.trim().split("\n").pop() ?? `qpdf ${r.rc}`})`);
68
+ }
69
+ throw new PdfPasswordError(password ? "wrong password" : "the PDF needs a password");
70
+ }
71
+ /** True when the PDF can't be opened without a password. */
72
+ export async function isLocked(bytes) {
73
+ const r = await qpdf(["--decrypt"], bytes);
74
+ return r.rc !== 0 && r.rc !== 3 && /invalid password/i.test(r.err);
75
+ }
76
+ /** The PDF's text, pages joined (pdf.js via unpdf). */
77
+ export async function pdfText(bytes) {
78
+ const { extractText, getDocumentProxy } = await import("unpdf");
79
+ const doc = await getDocumentProxy(new Uint8Array(bytes)); // pdf.js takes over the buffer: give it a copy
80
+ const { text } = await extractText(doc, { mergePages: true });
81
+ return text;
82
+ }
83
+ /* ------------------------------------------------------------------ month of a statement */
84
+ /** Every calendar date written in the text (dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy, yyyy-mm-dd, yyyy/mm/dd, yyyy.mm.dd). */
85
+ export function datesIn(text) {
86
+ const out = new Set();
87
+ const add = (y, m, d) => {
88
+ const mm = Number(m), dd = Number(d);
89
+ if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31)
90
+ out.add(`${y}-${String(mm).padStart(2, "0")}-${String(dd).padStart(2, "0")}`);
91
+ };
92
+ for (const m of text.matchAll(/(?<!\d)(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})(?!\d)/g))
93
+ add(m[3], m[2], m[1]);
94
+ for (const m of text.matchAll(/(?<!\d)(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})(?!\d)/g))
95
+ add(m[1], m[2], m[3]);
96
+ return out;
97
+ }
98
+ /**
99
+ * The statement period a statement's text is about, from the card's statement day: the period whose first and
100
+ * last days both appear in the text; else the one period whose close date appears. Never guesses between two.
101
+ */
102
+ export function monthFromText(text, statementDay) {
103
+ if (!statementDay)
104
+ return { month: null, why: "the card has no statement_day" };
105
+ const dates = datesIn(text);
106
+ const periods = new Map(); // close → from
107
+ for (const d of dates) {
108
+ const c = closeOnOrAfter(d, statementDay);
109
+ periods.set(c, addDays(prevClose(c, statementDay), 1));
110
+ }
111
+ const both = [...periods].filter(([c, f]) => dates.has(c) && dates.has(f));
112
+ const closeOnly = [...periods].filter(([c]) => dates.has(c));
113
+ const pick = both.length ? both : closeOnly;
114
+ if (pick.length === 1) {
115
+ const [close, from] = pick[0];
116
+ return { month: close.slice(0, 7), from, close, why: both.length ? "period dates in the text" : "close date in the text" };
117
+ }
118
+ if (!pick.length)
119
+ return { month: null, why: "no statement period's dates found in the text" };
120
+ return { month: null, why: `several periods fit (${pick.map(([c]) => c.slice(0, 7)).join(", ")})` };
121
+ }
122
+ /* ------------------------------------------------------------------ passwords and sources */
123
+ /** KEY=value lines of .env.statements (quotes stripped, # comments). Missing file: {}. */
124
+ export function readEnvFile(root) {
125
+ const p = join(root, ENV_FILE);
126
+ if (!existsSync(p))
127
+ return {};
128
+ const out = {};
129
+ for (const line of readFileSync(p, "utf8").split(/\r?\n/)) {
130
+ const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
131
+ if (!m || line.trimStart().startsWith("#"))
132
+ continue;
133
+ out[m[1]] = m[2].replace(/^(['"])(.*)\1$/, "$2");
134
+ }
135
+ return out;
136
+ }
137
+ /** imports/statements/sources.yaml: account id → how to find its statements in email. Missing file: {}. */
138
+ export function readSources(root) {
139
+ const p = join(root, SOURCES_FILE);
140
+ if (!existsSync(p))
141
+ return {};
142
+ const y = parseYaml(readFileSync(p, "utf8"));
143
+ if (y === null || y === undefined)
144
+ return {};
145
+ if (typeof y !== "object" || Array.isArray(y))
146
+ throw new Error(`${SOURCES_FILE}: expected account ids as keys`);
147
+ return y;
148
+ }
149
+ const envName = (s) => s.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
150
+ /** The variables tried for a card's password, in order: sources.yaml's, PW_<ACCOUNT_ID>, PW_<FIRST WORD>. */
151
+ export function passwordVars(account, source) {
152
+ const out = [source?.password, `PW_${envName(account)}`, `PW_${envName(account.split(/[-_]/)[0])}`].filter((x) => !!x);
153
+ return [...new Set(out)];
154
+ }
155
+ /** The statement PDFs on disk, and what doesn't fit the convention (warnings, never errors). */
156
+ export function scanStatements(root, accountIds) {
157
+ const dir = join(root, STATEMENTS_DIR);
158
+ const files = [];
159
+ const warnings = [];
160
+ if (!existsSync(dir))
161
+ return { files, warnings };
162
+ for (const acc of readdirSync(dir).sort()) {
163
+ if (acc.startsWith("."))
164
+ continue;
165
+ const p = join(dir, acc);
166
+ if (!statSync(p).isDirectory()) {
167
+ if (acc !== "sources.yaml" && !/^readme\.md$/i.test(acc))
168
+ warnings.push(`${STATEMENTS_DIR}/${acc}: not a statement folder (expected <account-id>/<YYYY-MM>.pdf)`);
169
+ continue;
170
+ }
171
+ if (!accountIds.has(acc))
172
+ warnings.push(`${STATEMENTS_DIR}/${acc}/: no account "${acc}" in data/accounts.yaml`);
173
+ for (const f of readdirSync(p).sort()) {
174
+ if (f.startsWith("."))
175
+ continue;
176
+ if (!MONTH_FILE.test(f))
177
+ warnings.push(`${STATEMENTS_DIR}/${acc}/${f}: name should be <YYYY-MM>.pdf (the month of the statement's close date)`);
178
+ else
179
+ files.push({ account: acc, month: f.slice(0, 7), path: `${STATEMENTS_DIR}/${acc}/${f}` });
180
+ }
181
+ }
182
+ return { files, warnings };
183
+ }
184
+ /** Months between the first and last filed month that have no file. */
185
+ export function missingMonths(months) {
186
+ if (!months.length)
187
+ return [];
188
+ const have = new Set(months);
189
+ const sorted = [...have].sort();
190
+ const out = [];
191
+ let [y, m] = sorted[0].split("-").map(Number);
192
+ const last = sorted[sorted.length - 1];
193
+ for (;;) {
194
+ const k = `${y}-${String(m).padStart(2, "0")}`;
195
+ if (k > last)
196
+ break;
197
+ if (!have.has(k))
198
+ out.push(k);
199
+ m++;
200
+ if (m > 12)
201
+ (m = 1), y++;
202
+ }
203
+ return out;
204
+ }
205
+ /** Warnings for `ownledger check`: the convention, plus PDFs still locked. */
206
+ export async function statementWarnings(root, accountIds) {
207
+ const { files, warnings } = scanStatements(root, accountIds);
208
+ for (const f of files) {
209
+ try {
210
+ if (await isLocked(new Uint8Array(readFileSync(join(root, f.path)))))
211
+ warnings.push(`${f.path}: still locked with a password (file it with \`ownledger statements add\`)`);
212
+ }
213
+ catch {
214
+ warnings.push(`${f.path}: can't be read as a PDF`);
215
+ }
216
+ }
217
+ return warnings;
218
+ }
@@ -109,16 +109,25 @@ export async function api(req, env, source) {
109
109
  const q = url.searchParams;
110
110
  const path = url.pathname.slice(5);
111
111
  const src = source ?? sourceFor(env);
112
- const s = await snapshot(env, src);
112
+ let s;
113
+ try {
114
+ s = await snapshot(env, src);
115
+ }
116
+ catch (e) {
117
+ // Loading the data repo failed (GitHub down, app not installed…): say why, as JSON, instead of a bare 500.
118
+ return json({ error: `could not load the data repo (${src.label}): ${e.message}` }, 502);
119
+ }
113
120
  const L = s.ledger;
114
121
  const asOf = q.get("date") ?? todayIn(env.TIMEZONE || "Asia/Ho_Chi_Minh");
115
- const dash = dashboardOf(s.files, login);
116
- const pool = poolOf(L, dash?.prefs?.pool, asOf);
117
- /** "pool" in an account filter means every account in the pool. */
118
- const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
119
122
  try {
123
+ const dash = dashboardOf(s.files, login);
124
+ const pool = poolOf(L, dash?.prefs?.pool, asOf);
125
+ /** "pool" in an account filter means every account in the pool. */
126
+ const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
120
127
  if (path.startsWith("m/")) {
121
128
  const r = await moduleApi(path.slice(2), { req, env, src, snap: s, login, asOf, q });
129
+ if (r && "response" in r)
130
+ return r.response;
122
131
  return r ? json(r.body, r.status ?? 200) : json({ error: "not found" }, 404);
123
132
  }
124
133
  switch (path) {
@@ -12,8 +12,26 @@ export interface GitHubAppConfig {
12
12
  }
13
13
  export declare function installationToken(c: GitHubAppConfig): Promise<string>;
14
14
  export declare function headSha(c: GitHubAppConfig): Promise<string>;
15
- /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball. */
15
+ /** Files the Worker reads as text: everything under data/ and imports/*.mapping.yaml. */
16
+ export declare const isDataFile: (p: string) => boolean;
17
+ interface TreeEntry {
18
+ path: string;
19
+ type: string;
20
+ sha: string;
21
+ }
22
+ /** Which tree entries to read as text, and which to list by path only (statement PDFs, never downloaded). */
23
+ export declare function pickFiles(tree: TreeEntry[]): {
24
+ text: TreeEntry[];
25
+ pathOnly: string[];
26
+ };
27
+ /**
28
+ * Every file under data/ and imports/*.mapping.yaml at a commit; statement PDFs by path only ("").
29
+ * One tree listing plus one GraphQL call per 100 files: no tarball, so binary files in the repo
30
+ * (statement PDFs, raw exports) cost the Worker nothing (a tarball of them ran past the Free plan's CPU limit).
31
+ */
16
32
  export declare function filesAt(c: GitHubAppConfig, sha: string): Promise<Record<string, string>>;
33
+ /** One file's bytes at a commit, streamed (null when it isn't there). */
34
+ export declare function blobAt(c: GitHubAppConfig, sha: string, path: string): Promise<Response | null>;
17
35
  export interface CommitFile {
18
36
  path: string;
19
37
  content?: string;
@@ -27,3 +45,4 @@ export declare function githubAuthorizeUrl(clientId: string, redirectUri: string
27
45
  export declare function githubLogin(clientId: string, clientSecret: string, code: string, verifier: string, redirectUri: string): Promise<string>;
28
46
  export declare function s256(verifier: string): Promise<string>;
29
47
  export declare function randomToken(bytes?: number): string;
48
+ export {};
@@ -2,6 +2,7 @@
2
2
  * The Worker's only network peer: GitHub's API, through the user's own GitHub App.
3
3
  * Installation tokens are short-lived and limited to the one data repo.
4
4
  */
5
+ import { STATEMENT_PDF_RE } from "../modules/cards/files.js";
5
6
  const API = "https://api.github.com";
6
7
  const UA = "ownledger-worker";
7
8
  export class MainMovedError extends Error {
@@ -75,14 +76,71 @@ export async function headSha(c) {
75
76
  throw new Error(`GitHub head of ${c.branch}: ${res.status}`);
76
77
  return (await res.text()).trim();
77
78
  }
78
- /** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball. */
79
+ /** Files the Worker reads as text: everything under data/ and imports/*.mapping.yaml. */
80
+ export const isDataFile = (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p);
81
+ /** Which tree entries to read as text, and which to list by path only (statement PDFs, never downloaded). */
82
+ export function pickFiles(tree) {
83
+ const text = [];
84
+ const pathOnly = [];
85
+ for (const e of tree) {
86
+ if (e.type !== "blob")
87
+ continue;
88
+ if (isDataFile(e.path))
89
+ text.push(e);
90
+ else if (STATEMENT_PDF_RE.test(e.path))
91
+ pathOnly.push(e.path);
92
+ }
93
+ return { text, pathOnly };
94
+ }
95
+ const GRAPHQL_BATCH = 100;
96
+ /**
97
+ * Every file under data/ and imports/*.mapping.yaml at a commit; statement PDFs by path only ("").
98
+ * One tree listing plus one GraphQL call per 100 files: no tarball, so binary files in the repo
99
+ * (statement PDFs, raw exports) cost the Worker nothing (a tarball of them ran past the Free plan's CPU limit).
100
+ */
79
101
  export async function filesAt(c, sha) {
80
102
  const token = await installationToken(c);
81
- const res = await gh(`/repos/${c.repo}/tarball/${sha}`, token);
103
+ const t = await ok(await gh(`/repos/${c.repo}/git/trees/${sha}?recursive=1`, token), "list the data repo's files");
104
+ if (t.truncated)
105
+ throw new Error("GitHub file list: the data repo has too many files for one listing (over 100,000)");
106
+ const { text, pathOnly } = pickFiles(t.tree);
107
+ const out = {};
108
+ for (const p of pathOnly)
109
+ out[p] = "";
110
+ const [owner, name] = c.repo.split("/");
111
+ for (let i = 0; i < text.length; i += GRAPHQL_BATCH) {
112
+ const batch = text.slice(i, i + GRAPHQL_BATCH);
113
+ const fields = batch.map((e, j) => `f${j}: object(oid: ${JSON.stringify(e.sha)}) { ... on Blob { text isTruncated } }`).join("\n");
114
+ const res = await gh(`/graphql`, token, {
115
+ method: "POST",
116
+ body: JSON.stringify({ query: `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`, variables: { owner, name } }),
117
+ });
118
+ const j = await ok(res, "read the data files");
119
+ if (j.errors?.length || !j.data)
120
+ throw new Error(`GitHub read the data files: ${j.errors?.map((e) => e.message).join("; ") ?? "no data"}`);
121
+ for (const [k, e] of batch.entries()) {
122
+ const b = j.data.repository[`f${k}`];
123
+ // Too big for GraphQL's text field: fetch that one file raw.
124
+ out[e.path] = b && b.text !== null && !b.isTruncated ? b.text : await blobText(c.repo, e, token);
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+ async function blobText(repo, e, token) {
130
+ const res = await gh(`/repos/${repo}/git/blobs/${e.sha}`, token, { headers: { Accept: "application/vnd.github.raw+json" } });
131
+ if (!res.ok)
132
+ throw new Error(`GitHub file ${e.path}: ${res.status}`);
133
+ return res.text();
134
+ }
135
+ /** One file's bytes at a commit, streamed (null when it isn't there). */
136
+ export async function blobAt(c, sha, path) {
137
+ const token = await installationToken(c);
138
+ const res = await gh(`/repos/${c.repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(sha)}`, token, { headers: { Accept: "application/vnd.github.raw" } });
139
+ if (res.status === 404)
140
+ return null;
82
141
  if (!res.ok || !res.body)
83
- throw new Error(`GitHub tarball: ${res.status}`);
84
- const { untar } = await import("./tar.js");
85
- return untar(res.body.pipeThrough(new DecompressionStream("gzip")), (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p));
142
+ throw new Error(`GitHub file: ${res.status}`);
143
+ return res;
86
144
  }
87
145
  /** One atomic commit on top of `baseSha`; refused (MainMovedError) if the branch moved. */
88
146
  export async function commit(c, baseSha, files, message) {
@@ -6,6 +6,8 @@ import type { Env } from "./env.js";
6
6
  export interface DataSource {
7
7
  head(): Promise<string>;
8
8
  files(sha: string): Promise<FileMap>;
9
+ /** One file's bytes at a commit (statement PDFs), streamed; null if missing. */
10
+ blob(sha: string, path: string): Promise<Response | null>;
9
11
  commit(baseSha: string, files: CommitFile[], message: string): Promise<string>;
10
12
  label: string;
11
13
  }
@@ -1,11 +1,12 @@
1
1
  import { checkFiles } from "../engine/check.js";
2
- import { commit, filesAt, headSha } from "./github.js";
2
+ import { blobAt, commit, filesAt, headSha } from "./github.js";
3
3
  export function githubSource(env) {
4
4
  const c = { appId: env.GITHUB_APP_ID, privateKey: env.GITHUB_APP_PRIVATE_KEY, repo: env.DATA_REPO, branch: env.DATA_BRANCH || "main" };
5
5
  return {
6
6
  label: `github.com/${c.repo}@${c.branch}`,
7
7
  head: () => headSha(c),
8
8
  files: (sha) => filesAt(c, sha),
9
+ blob: (sha, path) => blobAt(c, sha, path),
9
10
  commit: (base, files, message) => commit(c, base, files, message),
10
11
  };
11
12
  }
@@ -16,6 +17,10 @@ export function devSource(env) {
16
17
  label: `local ${base}`,
17
18
  head: async () => (await (await fetch(`${base}/head`)).text()).trim(),
18
19
  files: async () => (await (await fetch(`${base}/files`)).json()),
20
+ blob: async (_sha, path) => {
21
+ const r = await fetch(`${base}/blob?path=${encodeURIComponent(path)}`);
22
+ return r.status === 404 ? null : r.ok ? r : Promise.reject(new Error(`dev blob: ${r.status}`));
23
+ },
19
24
  commit: async (baseSha, files, message) => {
20
25
  const r = await fetch(`${base}/commit`, { method: "POST", body: JSON.stringify({ baseSha, files, message }) });
21
26
  if (r.status === 409) {
@@ -32,9 +37,9 @@ export function sourceFor(env) {
32
37
  return env.DEV_DATA_URL ? devSource(env) : githubSource(env);
33
38
  }
34
39
  // Parsed ledgers live in the isolate's memory (keyed by commit); raw files also in KV, so a cold isolate
35
- // needs no GitHub tarball for a commit it has seen. Both are safe to drop: GitHub is the only store.
40
+ // needs no GitHub reads for a commit it has seen. Both are safe to drop: GitHub is the only store.
36
41
  const memory = new Map();
37
- const KV_PREFIX = "ownledger:files:";
42
+ const KV_PREFIX = "ownledger:files2:"; // 2: with statement PDF paths (plan 004)
38
43
  export async function snapshot(env, src, sha) {
39
44
  const head = sha ?? (await src.head());
40
45
  const hit = memory.get(head);
@@ -1 +1 @@
1
- export declare const VERSION = "2.0.0";
1
+ export declare const VERSION = "2.1.1";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "2.0.0";
2
+ export const VERSION = "2.1.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "Personal finance ledger used through AI chat (MCP). Your data in your own private GitHub repo, served by your own Cloudflare Worker.",
5
5
  "license": "MIT",
6
6
  "author": "phucbm",
@@ -54,7 +54,9 @@
54
54
  "dependencies": {
55
55
  "@cloudflare/workers-oauth-provider": "1.2.4",
56
56
  "@modelcontextprotocol/server": "2.4.0",
57
+ "@neslinesli93/qpdf-wasm": "0.3.1",
57
58
  "fflate": "0.8.3",
59
+ "unpdf": "2.2.1",
58
60
  "yaml": "2.9.1",
59
61
  "zod": "4.6.7"
60
62
  },
@@ -1 +0,0 @@
1
- import{t as e}from"./createLucideIcon-DUW9Fpzj.js";import{t}from"./chevron-right-BetctQ6k.js";import{B as n,I as r,L as i,T as a,d as o,h as s,r as c,w as l,y as u}from"./queries-C_4ufx4u.js";import{A as d,G as f,J as p,K as m,W as h,Y as g,a as _,k as v,l as y,q as b,r as x,s as S,t as C}from"./index-DYyIpxqK.js";import{t as w}from"./DrillLink-pa6s17Xu.js";import{t as T}from"./KV-CKGyL0p7.js";import{t as E}from"./Money-DCMKf898.js";import{t as D}from"./Panel-CXjnsEN0.js";import{a as O,i as k,n as A,o as j,r as M}from"./bits-BoWPOwTB.js";import{n as N,t as P}from"./TxRow-IqjFXpya.js";import{a as F,n as I,t as L}from"./charts-Cj_hTR4h.js";import{n as R,r as z}from"./cards-AZlSJQ0z.js";var B={name:`arrow-left`,size:24,node:[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]};B.node;var V=e(B),H=n(r(),1),U=i();function W({account:e,close:t,onClose:n}){let{t:r,lang:i}=l(),a=v(`(max-width: 767px)`),{data:c,error:u,isLoading:d}=s(e,t),_=N(o().data),y=c?.statement;return(0,U.jsx)(f,{open:t!==null,onOpenChange:e=>!e&&n(),children:(0,U.jsxs)(m,{side:a?`bottom`:`right`,className:a?`max-h-[85svh] overflow-auto rounded-t-xl`:`overflow-auto sm:max-w-md`,children:[(0,U.jsxs)(p,{children:[(0,U.jsx)(g,{children:y?.open?r(`cards.currentPeriod`):r(`cards.statementOf`,{date:t?S(t,i):``})}),(0,U.jsx)(b,{children:y?`${S(y.from,i)} – ${S(y.close,i)}`:r(`common.loading`)})]}),(0,U.jsx)(`div`,{className:`flex flex-col gap-3 px-4 pb-4`,children:u?(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r(`common.error`,{message:u.message})}):d||!c||!y?(0,U.jsx)(h,{className:`h-40 w-full`}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`dl`,{className:`divide-y rounded-lg border px-3`,children:[(0,U.jsx)(T,{label:r(`cards.opening`),children:(0,U.jsx)(E,{amount:y.opening})}),(0,U.jsx)(T,{label:r(`cards.k.purchase`),children:(0,U.jsx)(E,{amount:y.purchases})}),y.fees>0&&(0,U.jsx)(T,{label:r(`cards.k.fee`),children:(0,U.jsx)(E,{amount:y.fees})}),y.refunds>0&&(0,U.jsx)(T,{label:r(`cards.k.refund`),children:(0,U.jsx)(E,{amount:-y.refunds})}),y.cashback>0&&(0,U.jsx)(T,{label:r(`cards.k.cashback`),children:(0,U.jsx)(E,{amount:-y.cashback})}),y.payments>0&&(0,U.jsx)(T,{label:r(`cards.k.payment`),children:(0,U.jsx)(E,{amount:-y.payments})}),(0,U.jsx)(T,{label:r(`cards.closing`),className:`font-medium`,children:(0,U.jsx)(E,{amount:y.closing})})]}),(0,U.jsx)(`ul`,{children:c.transactions.map(t=>(0,U.jsxs)(`li`,{className:`flex flex-col`,children:[t.kind&&(0,U.jsx)(`span`,{className:`px-2 pt-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase`,children:r(`cards.k.${t.kind}`)}),(0,U.jsx)(P,{tx:t,names:_,account:e})]},t.id))}),c.transactions.length===0&&(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r(`tx.emptyFiltered`)})]})})]})})}function G({value:e,max:t,label:n}){let r=t>0?Math.min(1,e/t):0;return(0,U.jsx)(`div`,{role:`progressbar`,"aria-label":n,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(r*100),className:`h-2 w-full rounded-full bg-muted`,children:(0,U.jsx)(`div`,{className:`h-2 rounded-full bg-[var(--chart-1)]`,style:{width:`${Math.max(r?2:0,r*100)}%`}})})}function K({d:e,asOf:t}){let{t:n,lang:r}=l(),i=e.summary?.current,a=e.terms.statementDay,o=e.account.id;return(0,U.jsx)(D,{title:n(`cards.currentPeriod`),children:i?(0,U.jsxs)(`dl`,{className:`divide-y`,children:[(0,U.jsx)(T,{label:n(`cards.purchasesSoFar`),children:(0,U.jsx)(w,{filter:{account:o,from:i.from,to:t},className:`font-medium`,children:(0,U.jsx)(E,{amount:i.purchases})})}),a&&(0,U.jsxs)(T,{label:n(`cards.closesOn`),children:[S(z(t,a),r),` · `,(0,U.jsx)(`span`,{className:`text-muted-foreground`,children:n(`cards.daysLeft`,{n:R(t,a)})})]}),e.payByToday&&(0,U.jsxs)(T,{label:n(`cards.payByToday`),children:[(0,U.jsx)(`span`,{className:`font-medium`,children:S(e.payByToday,r)}),` · `,(0,U.jsx)(`span`,{className:`text-muted-foreground`,children:n(`cards.daysLeft`,{n:x(t,e.payByToday)})})]})]}):(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n(a?`cards.noActivity`:`cards.noStatementDay`)})})}function q({s:e,id:t,asOf:n}){let{t:r,lang:i}=l();return(0,U.jsx)(D,{title:e?r(`cards.statementOf`,{date:S(e.close,i)}):r(`cards.lastStatement`),action:e?(0,U.jsx)(O,{status:e.status}):void 0,children:e?(0,U.jsxs)(`dl`,{className:`divide-y`,children:[(0,U.jsx)(T,{label:r(`cards.amountDue`),children:(0,U.jsx)(w,{filter:{account:t,from:e.from,to:e.close},className:`text-lg font-semibold`,children:(0,U.jsx)(E,{amount:e.amountDue})})}),e.due&&(0,U.jsxs)(T,{label:r(`cards.dueDate`),children:[S(e.due,i),` `,e.toPay>0&&(0,U.jsx)(M,{days:x(n,e.due),className:`ml-1`})]}),(0,U.jsx)(T,{label:r(`cards.paid`),children:(0,U.jsx)(w,{filter:{account:t,from:C(e.close,1),to:n},children:(0,U.jsx)(E,{amount:e.paid})})}),(0,U.jsx)(T,{label:r(`cards.toPay`),className:`font-medium`,children:(0,U.jsx)(E,{amount:e.toPay})}),e.deferred>0&&(0,U.jsx)(T,{label:r(`cards.deferred`),children:(0,U.jsx)(E,{amount:e.deferred})}),e.bank!==null&&(0,U.jsxs)(T,{label:r(`cards.bankAmount`),children:[(0,U.jsx)(E,{amount:e.bank}),e.bankDiff!==null&&e.bankDiff!==0&&(0,U.jsx)(`span`,{className:`block text-xs text-warning`,children:r(`cards.bankDiff`,{amount:`${e.bankDiff>0?`+`:`−`}${y(Math.abs(e.bankDiff),i)}`})})]})]}):(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r(`cards.noClosed`)})})}function J({list:e,onOpen:n}){let{t:r,lang:i}=l();return(0,U.jsx)(D,{title:r(`cards.history`),children:e.length===0?(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r(`cards.noHistory`)}):(0,U.jsx)(`ul`,{className:`-mx-2 flex flex-col divide-y`,children:e.map(e=>(0,U.jsx)(`li`,{children:(0,U.jsxs)(`button`,{type:`button`,onClick:()=>n(e.close),className:`flex min-h-12 w-full items-center gap-3 rounded-md px-2 py-1.5 text-left outline-none hover:bg-muted/50 focus-visible:ring-3 focus-visible:ring-ring/50`,children:[(0,U.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,U.jsx)(`span`,{className:`truncate text-sm font-medium`,children:e.open?r(`cards.currentPeriod`):S(e.close,i)}),(0,U.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[S(e.from,i,{day:`2-digit`,month:`2-digit`}),` – `,S(e.close,i,{day:`2-digit`,month:`2-digit`}),` · `,r(`cards.purchasesShort`),` `,(0,U.jsx)(E,{amount:e.purchases,mode:`short`})]})]}),(0,U.jsxs)(`span`,{className:`flex shrink-0 flex-col items-end`,children:[(0,U.jsx)(E,{amount:e.open?e.closing:e.amountDue,mode:`short`,className:`text-sm font-medium`}),!e.open&&(0,U.jsx)(O,{status:e.status})]}),(0,U.jsx)(t,{className:`size-4 shrink-0 text-muted-foreground`,"aria-hidden":!0})]})},e.close))})})}function Y({d:e}){let{t,lang:n}=l(),r=e.summary?.cashback??null,i=(0,H.useMemo)(()=>[...e.cashback].filter(e=>!e.open).reverse().slice(-12),[e.cashback]).map(e=>({ym:e.close,label:_(e.close.slice(0,7)),expected:e.expected,received:e.received}));return!e.terms.cashback&&!e.cashback.some(e=>e.expected>0||e.received>0)?(0,U.jsxs)(D,{title:t(`cards.cashback`),children:[(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`cards.noCashback`)}),(0,U.jsx)(d,{prompt:t(`ask.cardTerms`,{name:e.account.name,list:t(`cards.missing.cashback_rates`)})})]}):(0,U.jsxs)(D,{title:t(`cards.cashback`),children:[r&&(0,U.jsxs)(`dl`,{className:`divide-y`,children:[(0,U.jsx)(T,{label:t(`cards.spendThisPeriod`),children:(0,U.jsx)(w,{filter:{account:e.account.id,from:r.from,to:r.close},children:(0,U.jsx)(E,{amount:r.spend})})}),(0,U.jsx)(T,{label:t(`cards.expected`),children:r.incomplete?(0,U.jsx)(`span`,{className:`text-warning`,children:t(`cards.rateNotSet`)}):(0,U.jsx)(E,{amount:r.expected,className:`font-medium`})}),r.cap!==null&&r.capLeft!==null&&(0,U.jsxs)(T,{label:t(`cards.capLeftLabel`),children:[(0,U.jsx)(E,{amount:r.capLeft}),` `,(0,U.jsxs)(`span`,{className:`text-muted-foreground`,children:[`/ `,(0,U.jsx)(E,{amount:r.cap,mode:`short`})]})]})]}),r&&r.minSpend!==null&&(0,U.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,U.jsx)(G,{value:r.spend,max:r.minSpend,label:t(`cards.minSpend`)}),(0,U.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r.minMet?t(`cards.minMet`,{amount:y(r.minSpend,n)}):t(`cards.minNeed`,{amount:y(r.needForMin,n),min:y(r.minSpend,n)})})]}),i.length>0&&(0,U.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,U.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:t(`cards.last12`)}),(0,U.jsx)(`div`,{className:`flex h-40 flex-col`,children:(0,U.jsx)(L,{legend:[{label:t(`cards.earned`),color:F.accent},{label:t(`cards.expected`),color:F.second}],table:{head:[t(`chart.month`),t(`cards.earned`),t(`cards.expected`)],rows:i.map(e=>[e.label,y(e.received,n),y(e.expected,n)])},children:(0,U.jsx)(I,{data:i,xKey:`label`,series:[{key:`received`,label:t(`cards.earned`),color:F.accent},{key:`expected`,label:t(`cards.expected`),color:F.second}]})})})]})]})}function X({d:e,asOf:t}){let{t:n,lang:r}=l(),i=e.feeWaiver;return!i&&!e.terms.annualFee?null:(0,U.jsx)(D,{title:n(`cards.feeWaiver`),children:i?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(G,{value:i.spent,max:i.target,label:n(`cards.feeWaiver`)}),(0,U.jsxs)(`dl`,{className:`divide-y`,children:[(0,U.jsxs)(T,{label:n(`cards.spent`),children:[(0,U.jsx)(w,{filter:{account:e.account.id,from:i.yearFrom,to:t},children:(0,U.jsx)(E,{amount:i.spent})}),` `,(0,U.jsxs)(`span`,{className:`text-muted-foreground`,children:[`/ `,(0,U.jsx)(E,{amount:i.target,mode:`short`})]})]}),(0,U.jsxs)(T,{label:n(`cards.deadline`),children:[S(i.deadline,r),` `,(0,U.jsxs)(`span`,{className:`text-muted-foreground`,children:[`· `,n(`cards.daysLeft`,{n:i.daysLeft})]})]}),!i.met&&(0,U.jsx)(T,{label:n(`cards.perMonth`),children:(0,U.jsx)(E,{amount:i.perMonth})}),e.terms.annualFee?(0,U.jsx)(T,{label:n(`cards.annualFee`),children:(0,U.jsx)(E,{amount:e.terms.annualFee})}):null]}),(0,U.jsx)(`p`,{className:a(`text-sm font-medium`,i.met||i.onTrack?`text-foreground`:`text-critical`),children:i.met?n(`cards.feeMet`):i.onTrack?n(`cards.onTrack`):n(`cards.behind`)})]}):(0,U.jsxs)(`dl`,{children:[(0,U.jsx)(T,{label:n(`cards.annualFee`),children:(0,U.jsx)(E,{amount:e.terms.annualFee})}),(0,U.jsx)(`p`,{className:`py-1 text-sm text-muted-foreground`,children:n(`cards.noWaiver`)})]})})}function Z({d:e}){let{t}=l();return e.instalments.length===0?null:(0,U.jsx)(D,{title:t(`cards.instalments`),children:(0,U.jsx)(`ul`,{className:`flex flex-col gap-3`,children:e.instalments.map(e=>(0,U.jsxs)(`li`,{className:`flex flex-col gap-1`,children:[(0,U.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-sm`,children:[(0,U.jsx)(w,{filter:{plan:e.plan},className:`min-w-0 truncate font-medium`,children:e.name}),(0,U.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground tabular-nums`,children:[e.paidCount,`/`,e.count??`–`]})]}),(0,U.jsx)(G,{value:e.paidCount,max:e.count??0,label:e.name}),(0,U.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[t(`cards.perMonthPay`),` `,(0,U.jsx)(E,{amount:e.perPayment,mode:`short`}),e.leftAmount!==null&&(0,U.jsxs)(U.Fragment,{children:[` · `,t(`cards.left`),` `,(0,U.jsx)(E,{amount:e.leftAmount,mode:`short`})]})]})]},e.plan))})})}function Q({d:e}){let{t,lang:n}=l(),r=e.record;if(!r)return(0,U.jsxs)(D,{title:t(`cards.lifecycle`),children:[(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`cards.noRecord`)}),(0,U.jsx)(d,{prompt:t(`ask.cardRecord`,{name:e.account.name})})]});let i=e=>e?S(e,n):null,a=[[t(`cards.issued`),i(r.issued)],[t(`cards.activated`),i(r.activated)],[t(`cards.lockedOn`),i(r.locked)],[t(`cards.cancelledOn`),i(r.cancelled)],[t(`cards.network`),r.network?r.network.toUpperCase():null],[t(`cards.form`),r.physical?t(`cards.physical.${r.physical}`):null]];return(0,U.jsxs)(D,{title:t(`cards.lifecycle`),action:(0,U.jsx)(A,{status:r.status??`active`}),children:[(0,U.jsxs)(`dl`,{className:`divide-y`,children:[a.filter(([,e])=>e).map(([e,t])=>(0,U.jsx)(T,{label:e,children:t},e)),r.annual_fee?(0,U.jsx)(T,{label:t(`cards.annualFee`),children:(0,U.jsx)(E,{amount:r.annual_fee})}):null,r.close_fee?(0,U.jsx)(T,{label:t(`cards.closeFee`),children:(0,U.jsx)(E,{amount:r.close_fee})}):null,r.keep_for_limit&&(0,U.jsx)(T,{label:t(`cards.keepForLimit`),children:t(`cards.yes`)})]}),r.cancel_plan&&(0,U.jsxs)(`div`,{className:`rounded-md bg-muted/60 p-3 text-sm`,children:[(0,U.jsx)(`p`,{className:`font-medium`,children:t(`cards.cancelPlan`,{by:r.cancel_plan.by??``})}),r.cancel_plan.note&&(0,U.jsx)(`p`,{className:`text-muted-foreground`,children:r.cancel_plan.note})]}),r.note&&(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.note})]})}function $({d:e}){let{t}=l(),n=e.value;return n?(0,U.jsx)(D,{title:t(`cards.netValue`),children:(0,U.jsxs)(`dl`,{className:`divide-y`,children:[(0,U.jsx)(T,{label:t(`cards.value.benefits`),children:(0,U.jsx)(E,{amount:n.benefits})}),(0,U.jsx)(T,{label:t(`cards.cashback`),children:(0,U.jsx)(E,{amount:n.cashback})}),(0,U.jsx)(T,{label:n.feesFrom===`record`?`${t(`cards.value.fees`)} (${t(`cards.value.estimated`)})`:t(`cards.value.fees`),children:(0,U.jsx)(E,{amount:-n.fees})}),n.closeFee>0&&(0,U.jsx)(T,{label:t(`cards.closeFee`),children:(0,U.jsx)(E,{amount:-n.closeFee})}),(0,U.jsx)(T,{label:t(`cards.value.sinceIssued`),className:`font-medium`,children:(0,U.jsx)(E,{amount:n.net,tone:`auto`})}),(0,U.jsx)(T,{label:t(`cards.value.last12`),className:`font-medium`,children:(0,U.jsx)(E,{amount:n.last12.net,tone:`auto`})})]})}):null}function ee({params:e}){let{t}=l(),n=decodeURIComponent(e.account),{data:r,error:i,isLoading:a}=c(n),[o,s]=(0,H.useState)(null),d=(0,U.jsxs)(`a`,{href:`#/cards`,className:`inline-flex min-h-11 items-center gap-1 self-start rounded-md text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50`,children:[(0,U.jsx)(V,{className:`size-4`,"aria-hidden":!0}),t(`cards.back`)]});if(i)return(0,U.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[d,(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i instanceof u&&i.status===404?t(`cards.notFound`):t(`common.error`,{message:i.message})})]});if(a||!r)return(0,U.jsxs)(`div`,{className:`flex flex-col gap-3`,"aria-busy":`true`,children:[d,(0,U.jsx)(h,{className:`h-8 w-56`}),(0,U.jsx)(h,{className:`h-40 w-full`})]});let f=r.summary,p=r.record?.status??(r.account.closed?`cancelled`:`active`),m=r.terms.last4,g=[r.terms.bank,m?t(`cards.last4`,{n:m}):null].filter(Boolean).join(` · `);return(0,U.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[d,(0,U.jsxs)(`header`,{className:`flex flex-col gap-2`,children:[(0,U.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,U.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:r.account.name}),(0,U.jsx)(A,{status:p})]}),g&&(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:g}),f&&(0,U.jsx)(j,{owed:f.owed,limit:f.limit,atLeast:f.limitAtLeast,className:`max-w-md`}),f&&(0,U.jsx)(k,{card:f,className:`max-w-md`})]}),(0,U.jsxs)(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,children:[(0,U.jsx)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:f?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(K,{d:r,asOf:r.asOf}),(0,U.jsx)(q,{s:f.last,id:r.account.id,asOf:r.asOf}),(0,U.jsx)(J,{list:r.statements,onOpen:s})]}):(0,U.jsx)(D,{title:t(`cards.statements`),children:(0,U.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t(`cards.noStatements`)})})}),(0,U.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-4`,children:[(0,U.jsx)(Y,{d:r}),(0,U.jsx)(X,{d:r,asOf:r.asOf}),(0,U.jsx)(Z,{d:r}),(0,U.jsx)(Q,{d:r}),(0,U.jsx)($,{d:r})]})]}),(0,U.jsx)(W,{account:r.account.id,close:o,onClose:()=>s(null)})]})}export{ee as default};
@@ -1 +0,0 @@
1
- import{t as e}from"./createLucideIcon-DUW9Fpzj.js";var t={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};t.node;var n=e(t);export{n as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./createLucideIcon-DUW9Fpzj.js";var t={name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]};t.node;var n=e(t);export{n as t};