ownledger 1.2.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +73 -1
- package/CHANGELOG.md +64 -0
- package/README.md +13 -0
- package/assets/apple-touch-icon.png +0 -0
- package/assets/icon-192.png +0 -0
- package/assets/icon-512.png +0 -0
- package/assets/icon-maskable-512.png +0 -0
- package/assets/index.html +15 -18
- package/assets/manifest.webmanifest +1 -1
- package/assets/static/Account-sw3qGLbB.js +1 -0
- package/assets/static/Accounts-DWyzX3qB.js +1 -0
- package/assets/static/Attention-DxV-4qdY.js +1 -0
- package/assets/static/ByCategory-B4P3ikmE.js +1 -0
- package/assets/static/CardDetail-CayBXBm-.js +1 -0
- package/assets/static/Cards-CVuOP8Bt.js +1 -0
- package/assets/static/Cards-XUBdWxyo.js +1 -0
- package/assets/static/CardsValue-EoW2jG_0.js +1 -0
- package/assets/static/Cashback-BibVYHf_.js +1 -0
- package/assets/static/CategoryIcon-HfjYhH1l.js +1 -0
- package/assets/static/CategoryPicker-BkmvzX2I.js +1 -0
- package/assets/static/ChartWidget-u09-whUU.js +1 -0
- package/assets/static/Combobox-xXeyjGgK.js +1 -0
- package/assets/static/Deposits-CLAda4dj.js +1 -0
- package/assets/static/DrillLink-Bvfam9FA.js +1 -0
- package/assets/static/Field-tKFmKDEF.js +1 -0
- package/assets/static/HomeEditor-4vxj5LMD.js +1 -0
- package/assets/static/Import-DwaaFpRJ.js +2 -0
- package/assets/static/IncomeSpending-RVDSxAK4.js +1 -0
- package/assets/static/KV-DMA1AlP-.js +1 -0
- package/assets/static/Left-C_4gTGSX.js +1 -0
- package/assets/static/Money-PfFNNDOw.js +1 -0
- package/assets/static/NetWorth-BSoseczC.js +1 -0
- package/assets/static/Pace-B8p-9174.js +1 -0
- package/assets/static/Panel-BnfWrw9R.js +1 -0
- package/assets/static/PinDialog-BqAU9Vh4.js +1 -0
- package/assets/static/Plans-2KuQH2_I.js +1 -0
- package/assets/static/Recent-Ccmb34bq.js +1 -0
- package/assets/static/Reports-Dd-dhclr.js +1 -0
- package/assets/static/Settings-BR8WBlen.js +1 -0
- package/assets/static/Transactions-BAuQ-6Eb.js +1 -0
- package/assets/static/TxRow-EKIIMQKa.js +1 -0
- package/assets/static/Unusual-CwFp8aA5.js +1 -0
- package/assets/static/Upcoming-B28roT9r.js +1 -0
- package/assets/static/WhichCard-B3kLc842.js +1 -0
- package/assets/static/arrow-up-D3gxUKLo.js +1 -0
- package/assets/static/bits-Dr2E0ObC.js +1 -0
- package/assets/static/button-rfwMVz0i.js +1 -0
- package/assets/static/cards-Bb5zjzRG.js +1 -0
- package/assets/static/charts-BqP7HKwP.js +65 -0
- package/assets/static/chevron-down-Co1w7ApZ.js +1 -0
- package/assets/static/chevron-right-Dqh3vs9Y.js +1 -0
- package/assets/static/createLucideIcon-flJrJK2p.js +1 -0
- package/assets/static/dialog-BuRqO4sc.js +1 -0
- package/assets/static/dist-B4_eGtNj.js +1 -0
- package/assets/static/dist-B7PR2b0C.js +1 -0
- package/assets/static/dist-BDn7ydjn.js +1 -0
- package/assets/static/dist-Dl-m8cc2.js +1 -0
- package/assets/static/drill-t1zr57xi.js +1 -0
- package/assets/static/es2015-DJh4h8NX.js +41 -0
- package/assets/static/fold-CGWYt9Iu.js +1 -0
- package/assets/static/index-eR1GkdC_.js +14 -0
- package/assets/static/index-iYMxgw-7.css +1 -0
- package/assets/static/queries-DZIMMe4i.js +1 -0
- package/assets/static/react-dom-wK_7mEjs.js +1 -0
- package/assets/static/select-eaSi9K-d.js +1 -0
- package/assets/static/shared-Box7on3B.js +1 -0
- package/assets/static/triangle-exclamation-point-CuL0XSJl.js +1 -0
- package/assets/static/useMutation-_Lw8xXWa.js +1 -0
- package/dist/cli/cards.d.ts +2 -0
- package/dist/cli/cards.js +86 -0
- package/dist/cli/check.js +7 -1
- package/dist/cli/dev.js +22 -2
- package/dist/cli/import.js +12 -2
- package/dist/cli/index.js +6 -0
- package/dist/cli/statements.d.ts +1 -0
- package/dist/cli/statements.js +231 -0
- package/dist/engine/actions.d.ts +5 -0
- package/dist/engine/actions.js +9 -5
- package/dist/engine/attention.d.ts +15 -0
- package/dist/engine/attention.js +63 -0
- package/dist/engine/check.js +8 -1
- package/dist/engine/dashboard.d.ts +72 -0
- package/dist/engine/dashboard.js +180 -0
- package/dist/engine/features.d.ts +20 -0
- package/dist/engine/features.js +37 -0
- package/dist/engine/index.d.ts +5 -0
- package/dist/engine/index.js +5 -0
- package/dist/engine/insights.d.ts +164 -0
- package/dist/engine/insights.js +534 -0
- package/dist/engine/load.js +6 -0
- package/dist/engine/registry.d.ts +2 -0
- package/dist/engine/registry.js +15 -33
- package/dist/engine/reports.d.ts +21 -2
- package/dist/engine/reports.js +51 -3
- package/dist/engine/schedules.d.ts +7 -84
- package/dist/engine/schedules.js +8 -207
- package/dist/engine/types.d.ts +2 -0
- package/dist/engine/write.d.ts +9 -0
- package/dist/engine/write.js +26 -5
- package/dist/import/mapping.js +6 -0
- package/dist/import/run.d.ts +7 -0
- package/dist/import/run.js +28 -1
- package/dist/modules/api.d.ts +22 -0
- package/dist/modules/api.js +16 -0
- package/dist/modules/cards/api.d.ts +3 -0
- package/dist/modules/cards/api.js +105 -0
- package/dist/modules/cards/engine.d.ts +42 -0
- package/dist/modules/cards/engine.js +102 -0
- package/dist/modules/cards/files.d.ts +11 -0
- package/dist/modules/cards/files.js +17 -0
- package/dist/modules/cards/index.d.ts +26 -0
- package/dist/modules/cards/index.js +304 -0
- package/dist/modules/cards/statements.d.ts +128 -0
- package/dist/modules/cards/statements.js +426 -0
- package/dist/modules/cards/terms.d.ts +105 -0
- package/dist/modules/cards/terms.js +194 -0
- package/dist/modules/cards/tracker.d.ts +36 -0
- package/dist/modules/cards/tracker.js +232 -0
- package/dist/modules/cards/types.d.ts +2 -0
- package/dist/modules/cards/types.js +16 -0
- package/dist/modules/deposits/engine.d.ts +14 -0
- package/dist/modules/deposits/engine.js +32 -0
- package/dist/modules/deposits/index.d.ts +2 -0
- package/dist/modules/deposits/index.js +24 -0
- package/dist/modules/deposits/types.d.ts +2 -0
- package/dist/modules/deposits/types.js +15 -0
- package/dist/modules/index.d.ts +5 -0
- package/dist/modules/index.js +10 -0
- package/dist/modules/insurance/index.d.ts +3 -0
- package/dist/modules/insurance/index.js +8 -0
- package/dist/modules/insurance/types.d.ts +2 -0
- package/dist/modules/insurance/types.js +3 -0
- package/dist/modules/investments/index.d.ts +2 -0
- package/dist/modules/investments/index.js +24 -0
- package/dist/modules/investments/types.d.ts +2 -0
- package/dist/modules/investments/types.js +7 -0
- package/dist/modules/loans/engine.d.ts +30 -0
- package/dist/modules/loans/engine.js +77 -0
- package/dist/modules/loans/index.d.ts +2 -0
- package/dist/modules/loans/index.js +27 -0
- package/dist/modules/loans/types.d.ts +2 -0
- package/dist/modules/loans/types.js +5 -0
- package/dist/modules/types.d.ts +39 -0
- package/dist/modules/types.js +1 -0
- package/dist/modules/util.d.ts +8 -0
- package/dist/modules/util.js +8 -0
- package/dist/node/scaffold.js +2 -2
- package/dist/node/statements.d.ts +64 -0
- package/dist/node/statements.js +218 -0
- package/dist/worker/api.d.ts +11 -1
- package/dist/worker/api.js +169 -13
- package/dist/worker/bestcard.d.ts +31 -9
- package/dist/worker/bestcard.js +78 -50
- package/dist/worker/github.d.ts +3 -1
- package/dist/worker/github.js +13 -2
- package/dist/worker/mcp.js +209 -30
- package/dist/worker/store.d.ts +2 -0
- package/dist/worker/store.js +7 -2
- package/dist/worker/tar.d.ts +2 -1
- package/dist/worker/tar.js +4 -1
- package/dist/worker/version.d.ts +1 -1
- package/dist/worker/version.js +1 -1
- package/package.json +28 -4
- package/presets/misa.mapping.yaml +7 -0
- package/assets/app.css +0 -61
- package/assets/app.js +0 -369
package/dist/worker/api.js
CHANGED
|
@@ -1,21 +1,104 @@
|
|
|
1
1
|
import { accountValues } from "../engine/balances.js";
|
|
2
2
|
import { flattenCategories } from "../engine/categories.js";
|
|
3
|
-
import { addMonths, todayIn } from "../engine/dates.js";
|
|
3
|
+
import { addMonths, monthEnd, todayIn } from "../engine/dates.js";
|
|
4
4
|
import { netWorth, netWorthSeries } from "../engine/networth.js";
|
|
5
5
|
import { TYPES } from "../engine/registry.js";
|
|
6
6
|
import { queryTransactions, report } from "../engine/reports.js";
|
|
7
7
|
import { budgets, cards, deposits, planStatus, plansDue, today } from "../engine/schedules.js";
|
|
8
8
|
import { checkFiles } from "../engine/check.js";
|
|
9
|
+
import { attention } from "../engine/attention.js";
|
|
10
|
+
import { checkDashboard, dashboardPath, defaultWidgets, parseDashboard, poolOf, writeDashboard } from "../engine/dashboard.js";
|
|
11
|
+
import { features } from "../engine/features.js";
|
|
12
|
+
import { pace, series, unusual, usual } from "../engine/insights.js";
|
|
13
|
+
import { moduleApi } from "../modules/api.js";
|
|
9
14
|
import { applyChange } from "../engine/write.js";
|
|
10
15
|
import { parseMapping } from "../import/mapping.js";
|
|
11
16
|
import { runImport } from "../import/run.js";
|
|
12
17
|
import { readWorkbook } from "../import/workbook.js";
|
|
13
18
|
import { sessionLogin } from "./auth.js";
|
|
19
|
+
import { MainMovedError } from "./github.js";
|
|
14
20
|
import { applyPending, savePending, snapshot, sourceFor } from "./store.js";
|
|
15
21
|
import { VERSION } from "./version.js";
|
|
16
22
|
const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
|
|
23
|
+
/** The signed-in person's dashboard file, or null when they have none yet. */
|
|
24
|
+
export function dashboardOf(files, login) {
|
|
25
|
+
try {
|
|
26
|
+
return parseDashboard(files[dashboardPath(login)]);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Commit one dashboard file; if main moved meanwhile, once more on the new head (the file is replaced whole). */
|
|
33
|
+
export async function saveDashboard(env, src, login, d, message) {
|
|
34
|
+
for (let attempt = 0;; attempt++) {
|
|
35
|
+
const s = await snapshot(env, src);
|
|
36
|
+
const path = dashboardPath(login);
|
|
37
|
+
const issues = checkDashboard(path, d, s.ledger);
|
|
38
|
+
const errors = issues.filter((i) => i.level === "error");
|
|
39
|
+
if (errors.length)
|
|
40
|
+
throw new Error(`dashboard refused: ${errors.map((e) => `${e.where ? `[${e.where}] ` : ""}${e.message}`).join("; ")}`);
|
|
41
|
+
try {
|
|
42
|
+
const sha = await src.commit(s.sha, [{ path, content: writeDashboard(d) }], message);
|
|
43
|
+
return { sha, issues: issues.map((i) => `${i.where ? `[${i.where}] ` : ""}${i.message}`) };
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
if (e instanceof MainMovedError && attempt === 0)
|
|
47
|
+
continue;
|
|
48
|
+
throw e;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function lastActivity(L) {
|
|
53
|
+
const out = new Map();
|
|
54
|
+
for (const t of L.transactions) {
|
|
55
|
+
if (t.void)
|
|
56
|
+
continue;
|
|
57
|
+
for (const ln of t.lines)
|
|
58
|
+
if (ln.account)
|
|
59
|
+
out.set(ln.account, t.date);
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
/** Balance of one account after each of its transactions (for the running balance column). */
|
|
64
|
+
function runningBalance(L, account) {
|
|
65
|
+
const out = new Map();
|
|
66
|
+
let b = 0;
|
|
67
|
+
for (const t of L.transactions) {
|
|
68
|
+
if (t.void)
|
|
69
|
+
continue;
|
|
70
|
+
let touched = false;
|
|
71
|
+
for (const ln of t.lines)
|
|
72
|
+
if (ln.account === account) {
|
|
73
|
+
b += ln.amount;
|
|
74
|
+
touched = true;
|
|
75
|
+
}
|
|
76
|
+
if (touched)
|
|
77
|
+
out.set(t.id, b);
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
function seriesQuery(q) {
|
|
82
|
+
const s = (k) => q.get(k) ?? undefined;
|
|
83
|
+
const acc = q.get("account");
|
|
84
|
+
return {
|
|
85
|
+
metric: (s("metric") ?? "spending"),
|
|
86
|
+
category: s("category"),
|
|
87
|
+
account: acc ? (acc.includes(",") ? acc.split(",") : acc) : undefined,
|
|
88
|
+
who: s("who"),
|
|
89
|
+
event: s("event"),
|
|
90
|
+
tag: s("tag"),
|
|
91
|
+
text: s("text"),
|
|
92
|
+
period: s("period"),
|
|
93
|
+
from: s("from"),
|
|
94
|
+
to: s("to"),
|
|
95
|
+
by: s("by"),
|
|
96
|
+
compare: s("compare"),
|
|
97
|
+
limit: q.get("limit") ? Number(q.get("limit")) : undefined,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
17
100
|
/** JSON for the dashboard. Same sign-in allowlist as the connector; read-only except import (Phase 6). */
|
|
18
|
-
export async function api(req, env) {
|
|
101
|
+
export async function api(req, env, source) {
|
|
19
102
|
const login = await sessionLogin(req, env);
|
|
20
103
|
if (!login)
|
|
21
104
|
return json({ error: "sign in", login: "/auth/login" }, 401);
|
|
@@ -25,20 +108,73 @@ export async function api(req, env) {
|
|
|
25
108
|
const url = new URL(req.url);
|
|
26
109
|
const q = url.searchParams;
|
|
27
110
|
const path = url.pathname.slice(5);
|
|
28
|
-
const src = sourceFor(env);
|
|
111
|
+
const src = source ?? sourceFor(env);
|
|
29
112
|
const s = await snapshot(env, src);
|
|
30
113
|
const L = s.ledger;
|
|
31
114
|
const asOf = q.get("date") ?? todayIn(env.TIMEZONE || "Asia/Ho_Chi_Minh");
|
|
115
|
+
const dash = dashboardOf(s.files, login);
|
|
116
|
+
const pool = poolOf(L, dash?.prefs?.pool, asOf);
|
|
117
|
+
/** "pool" in an account filter means every account in the pool. */
|
|
118
|
+
const accountParam = (v) => (!v ? undefined : v === "pool" ? pool.accounts : v.includes(",") ? v.split(",") : v);
|
|
32
119
|
try {
|
|
120
|
+
if (path.startsWith("m/")) {
|
|
121
|
+
const r = await moduleApi(path.slice(2), { req, env, src, snap: s, login, asOf, q });
|
|
122
|
+
if (r && "response" in r)
|
|
123
|
+
return r.response;
|
|
124
|
+
return r ? json(r.body, r.status ?? 200) : json({ error: "not found" }, 404);
|
|
125
|
+
}
|
|
33
126
|
switch (path) {
|
|
34
|
-
case "me":
|
|
35
|
-
|
|
127
|
+
case "me": {
|
|
128
|
+
const f = features(L, asOf, s.files, pool.accounts);
|
|
129
|
+
return json({ login, version: VERSION, data: src.label, commit: s.sha, base: L.meta.base, locale: L.meta.locale ?? "en", name: L.meta.name, today: asOf, check: { errors: s.errors, warnings: s.warnings }, features: f, pool, dashboard: { saved: Boolean(dash), widgets: dash?.widgets ?? defaultWidgets(f), prefs: dash?.prefs ?? {} } });
|
|
130
|
+
}
|
|
131
|
+
case "home": {
|
|
132
|
+
const nw = netWorthSeries(L, addMonths(asOf.slice(0, 7) + "-01", -12), asOf);
|
|
133
|
+
const now = nw[nw.length - 1];
|
|
134
|
+
const lastMonthEnd = nw[nw.length - 2] ?? null;
|
|
135
|
+
const yearAgo = nw[0] ?? null;
|
|
136
|
+
const balances = new Map(accountValues(L, asOf).map((v) => [v.account.id, v.value]));
|
|
137
|
+
const p = pace(L, asOf);
|
|
138
|
+
return json({
|
|
139
|
+
asOf,
|
|
140
|
+
pace: p,
|
|
141
|
+
left: { income: p.income, spent: p.spent, now: p.income - p.spent, monthEnd: p.incomeEstimate - p.estimate },
|
|
142
|
+
attention: attention(L, asOf, { files: s.files, check: { errors: s.errors, warnings: s.warnings } }),
|
|
143
|
+
unusual: unusual(L, asOf),
|
|
144
|
+
netWorth: { net: now.net, assets: now.assets, liabilities: now.liabilities, byType: now.byType, unpriced: now.unpriced, changeMonth: lastMonthEnd ? now.net - lastMonthEnd.net : null, change12: yearAgo && nw.length > 12 ? now.net - yearAgo.net : null, series: nw.slice(1).map((x) => ({ date: x.date, net: x.net })) },
|
|
145
|
+
pool: { ...pool, balance: pool.accounts.reduce((t, id) => t + (balances.get(id) ?? 0), 0) },
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
case "series": {
|
|
149
|
+
const sq = seriesQuery(q);
|
|
150
|
+
if (sq.account === "pool")
|
|
151
|
+
sq.account = pool.accounts;
|
|
152
|
+
return json(series(L, sq, asOf));
|
|
153
|
+
}
|
|
154
|
+
case "dashboard": {
|
|
155
|
+
if (req.method === "PUT") {
|
|
156
|
+
const body = (await req.json());
|
|
157
|
+
const d = { version: 1, widgets: body.widgets ?? dash?.widgets, prefs: body.prefs ?? dash?.prefs };
|
|
158
|
+
if (!d.prefs || !Object.keys(d.prefs).length)
|
|
159
|
+
delete d.prefs;
|
|
160
|
+
const r = await saveDashboard(env, src, login, d, `Dashboard: ${body.prefs && !body.widgets ? "settings" : "layout"} (${login})`);
|
|
161
|
+
return json({ saved: true, commit: r.sha, warnings: r.issues });
|
|
162
|
+
}
|
|
163
|
+
if (req.method === "DELETE") {
|
|
164
|
+
if (!dash)
|
|
165
|
+
return json({ saved: false });
|
|
166
|
+
const sha = await src.commit(s.sha, [{ path: dashboardPath(login), content: writeDashboard({ version: 1, ...(dash.prefs ? { prefs: dash.prefs } : {}) }) }], `Dashboard: reset layout (${login})`);
|
|
167
|
+
return json({ saved: true, commit: sha });
|
|
168
|
+
}
|
|
169
|
+
const f = features(L, asOf, s.files);
|
|
170
|
+
return json({ saved: Boolean(dash), widgets: dash?.widgets ?? defaultWidgets(f), prefs: dash?.prefs ?? {}, path: dashboardPath(login) });
|
|
171
|
+
}
|
|
36
172
|
case "meta": {
|
|
37
173
|
const { map } = flattenCategories(L.categories);
|
|
38
174
|
return json({
|
|
39
175
|
base: L.meta.base,
|
|
40
176
|
locale: L.meta.locale,
|
|
41
|
-
types: Object.fromEntries(Object.entries(TYPES).map(([k, v]) => [k, v.label])),
|
|
177
|
+
types: Object.fromEntries(Object.entries(TYPES).map(([k, v]) => [k, { ...v.label, liquid: Boolean(v.liquid), liability: Boolean(v.liability), holdings: Boolean(v.holdings) }])),
|
|
42
178
|
categories: [...map.values()],
|
|
43
179
|
accounts: L.accounts.map((a) => ({ id: a.id, name: a.name, type: a.type, closed: a.closed ?? null, group: a.group ?? null })),
|
|
44
180
|
assets: L.assets,
|
|
@@ -48,14 +184,26 @@ export async function api(req, env) {
|
|
|
48
184
|
const m = report(L, asOf.slice(0, 7));
|
|
49
185
|
return json({ today: today(L, asOf), month: { income: m.income, expense: m.expense, net: m.net, previous: m.previous, top: m.rows.filter((r) => r.expense).slice(0, 8) }, netWorth: netWorth(L, asOf), series: netWorthSeries(L, addMonths(asOf.slice(0, 7) + "-01", -11), asOf) });
|
|
50
186
|
}
|
|
51
|
-
case "accounts":
|
|
52
|
-
|
|
187
|
+
case "accounts": {
|
|
188
|
+
const last = lastActivity(L);
|
|
189
|
+
const inPool = new Set(pool.accounts);
|
|
190
|
+
return json(accountValues(L, asOf).map((v) => ({ ...v.account, value: v.value, cost: v.cost, qty: v.qty, asset: v.asset, priced: v.priced, price: v.price, lastActivity: last.get(v.account.id) ?? null, pool: inPool.has(v.account.id) })));
|
|
191
|
+
}
|
|
53
192
|
case "transactions": {
|
|
54
193
|
const n = (k) => (q.get(k) ? Number(q.get(k)) : undefined);
|
|
194
|
+
const account = accountParam(q.get("account"));
|
|
195
|
+
const single = typeof account === "string" ? account : null;
|
|
55
196
|
const r = queryTransactions(L, {
|
|
56
197
|
from: q.get("from") ?? undefined,
|
|
57
198
|
to: q.get("to") ?? undefined,
|
|
58
|
-
account
|
|
199
|
+
account,
|
|
200
|
+
who: q.get("who") ?? undefined,
|
|
201
|
+
event: q.get("event") ?? undefined,
|
|
202
|
+
tag: q.get("tag") ?? undefined,
|
|
203
|
+
tx: q.get("tx") ?? undefined,
|
|
204
|
+
plan: q.get("plan") ?? undefined,
|
|
205
|
+
// moves inside the pool are hidden unless asked for, or when looking at one account
|
|
206
|
+
hideWithin: pool.on && !single && q.get("within") !== "1" ? pool.accounts : undefined,
|
|
59
207
|
category: q.get("category") ?? undefined,
|
|
60
208
|
text: q.get("text") ?? undefined,
|
|
61
209
|
min: n("min"),
|
|
@@ -64,11 +212,19 @@ export async function api(req, env) {
|
|
|
64
212
|
offset: n("offset"),
|
|
65
213
|
limit: n("limit") ?? 100,
|
|
66
214
|
});
|
|
215
|
+
if (single) {
|
|
216
|
+
const rb = runningBalance(L, single);
|
|
217
|
+
return json({ ...r, items: r.items.map((t) => ({ ...t, balance: rb.get(t.id) ?? null })) });
|
|
218
|
+
}
|
|
67
219
|
return json(r);
|
|
68
220
|
}
|
|
69
221
|
case "report": {
|
|
70
222
|
const period = q.get("from") && q.get("to") ? { from: q.get("from"), to: q.get("to") } : (q.get("period") ?? asOf.slice(0, 7));
|
|
71
|
-
|
|
223
|
+
if (q.get("usual")) {
|
|
224
|
+
const p = typeof period === "string" ? (period.length === 7 ? { from: `${period}-01`, to: monthEnd(`${period}-01`) } : { from: `${period}-01-01`, to: `${period}-12-31` }) : period;
|
|
225
|
+
return json(usual(L, p, (q.get("by") ?? "top"), { months: Number(q.get("usual")) || 6, kind: q.get("kind") ?? "expense" }));
|
|
226
|
+
}
|
|
227
|
+
return json(report(L, period, { by: (q.get("by") ?? "top"), kind: q.get("kind") ?? undefined, category: q.get("category") ?? undefined, account: typeof accountParam(q.get("account")) === "string" ? q.get("account") : undefined }));
|
|
72
228
|
}
|
|
73
229
|
case "networth":
|
|
74
230
|
return json(netWorthSeries(L, q.get("from") ?? addMonths(asOf.slice(0, 7) + "-01", -23), asOf));
|
|
@@ -96,12 +252,12 @@ export async function api(req, env) {
|
|
|
96
252
|
ok: r.ok, source: r.source, rows: r.rows, new: r.transactions.length, skipped: r.skipped, accounts: r.accounts.map((a) => `${a.id} (${a.type})`),
|
|
97
253
|
reconcile: r.reconcile, rounding: r.rounding, zeroed: r.zeroed, unpaired: r.unpaired.map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
|
|
98
254
|
unresolvedCategories: r.unresolvedCategories, unresolvedRows: r.unresolvedRows.slice(0, 50).map((u) => ({ sheet: u.sheet, row: u.row, date: u.date, amount: u.amount, note: u.note })),
|
|
99
|
-
changed: r.changed, gone: r.gone, replace: r.replace.length, errors: r.errors,
|
|
255
|
+
changed: r.changed, gone: r.gone, replace: r.replace.length, errors: r.errors, cardTerms: r.accountUpdates.map((u) => u.id), nameWarnings: r.nameWarnings,
|
|
100
256
|
sample: r.transactions.slice(0, 20),
|
|
101
257
|
};
|
|
102
|
-
if (!r.ok || (!r.transactions.length && !r.accounts.length && !r.replace.length))
|
|
258
|
+
if (!r.ok || (!r.transactions.length && !r.accounts.length && !r.replace.length && !r.accountUpdates.length))
|
|
103
259
|
return json({ report });
|
|
104
|
-
const changed = applyChange(s.files, { addAccounts: r.accounts, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
260
|
+
const changed = applyChange(s.files, { addAccounts: r.accounts, updateAccounts: r.accountUpdates, addTransactions: r.transactions, replaceTransactions: r.replace });
|
|
105
261
|
const c = checkFiles({ ...s.files, ...changed });
|
|
106
262
|
if (!c.ok)
|
|
107
263
|
return json({ report: { ...report, ok: false, errors: c.errors.slice(0, 20).map((e) => e.message) } });
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { type ISODate, type Ledger } from "../engine/index.js";
|
|
2
|
+
import { type BestCard as LocalRow } from "../modules/cards/statements.js";
|
|
2
3
|
import type { OpenWallet } from "./openwallet.js";
|
|
3
4
|
export interface BestCardInput {
|
|
4
|
-
amount
|
|
5
|
+
amount?: number;
|
|
6
|
+
/** the owner's category path, e.g. food/groceries: picks the rate from the owner's own terms, and the budget left */
|
|
7
|
+
category?: string;
|
|
8
|
+
/** for OpenWallet: where (Shopee, Co.opmart…) or what kind (groceries, dining…) */
|
|
5
9
|
merchant?: string;
|
|
6
10
|
kind?: string;
|
|
7
11
|
date?: ISODate;
|
|
8
|
-
category?: string;
|
|
9
12
|
accounts?: string[];
|
|
10
13
|
}
|
|
11
14
|
interface NotMatched {
|
|
@@ -19,10 +22,29 @@ interface NotMatched {
|
|
|
19
22
|
}[];
|
|
20
23
|
}
|
|
21
24
|
export declare const clearSearchCache: () => void;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
/** One card in the answer, whichever source its cashback comes from. */
|
|
26
|
+
export interface BestCardRow extends LocalRow {
|
|
27
|
+
/** where the cashback figure comes from: the owner's own terms, OpenWallet, or none known */
|
|
28
|
+
source: "yours" | "openwallet" | "none";
|
|
29
|
+
status?: string;
|
|
30
|
+
spend_so_far?: number;
|
|
31
|
+
cap_used?: number;
|
|
32
|
+
openwallet?: {
|
|
33
|
+
id: string;
|
|
34
|
+
name: string;
|
|
35
|
+
url: string | null;
|
|
36
|
+
lastChecked: string | null;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet | null, input: BestCardInput): Promise<{
|
|
40
|
+
purchase: {
|
|
41
|
+
amount: number | null;
|
|
42
|
+
date: string;
|
|
43
|
+
category: string | null;
|
|
44
|
+
merchant: string | null;
|
|
45
|
+
kind: string | null;
|
|
46
|
+
};
|
|
47
|
+
cards: BestCardRow[];
|
|
26
48
|
not_matched?: NotMatched[] | undefined;
|
|
27
49
|
budget?: {
|
|
28
50
|
category: string;
|
|
@@ -40,11 +62,11 @@ export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet, input
|
|
|
40
62
|
none: boolean;
|
|
41
63
|
} | undefined;
|
|
42
64
|
assumptions: string[];
|
|
43
|
-
|
|
44
|
-
name: string;
|
|
65
|
+
openwallet?: {
|
|
45
66
|
url: string;
|
|
46
67
|
catalog: unknown;
|
|
47
|
-
|
|
68
|
+
what: string;
|
|
69
|
+
} | undefined;
|
|
48
70
|
note: string;
|
|
49
71
|
}>;
|
|
50
72
|
export {};
|
package/dist/worker/bestcard.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
// best_card: which of the owner's
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// best_card: which of the owner's cards to use for one purchase. Cards with the owner's own cashback terms
|
|
2
|
+
// (details.cashback / data/cards.yaml) are ranked here, nothing sent anywhere. Cards without terms ask OpenWallet,
|
|
3
|
+
// when the owner turned it on (an outside source): those cards are looked up each time by their product name
|
|
4
|
+
// (details.product, or the account name) and bank, and nothing OpenWallet returns is stored.
|
|
4
5
|
import { budgets, cards, fold } from "../engine/index.js";
|
|
6
|
+
import { bestCard as localBestCard } from "../modules/cards/statements.js";
|
|
7
|
+
import { recordFor, termsOf } from "../modules/cards/terms.js";
|
|
5
8
|
/** letters and digits only, no accents: "Demo Bank" and "demo-bank" are the same */
|
|
6
9
|
const key = (s) => fold(s).replace(/[^a-z0-9]/g, "");
|
|
7
10
|
const isDebit = (t) => (Array.isArray(t) ? t.includes("debit") && !t.includes("credit") : t === "debit");
|
|
@@ -66,19 +69,7 @@ function budgetFor(l, asOf, category) {
|
|
|
66
69
|
const b = all.filter((x) => category === x.category || category.startsWith(x.category + "/")).sort((a, b) => b.category.length - a.category.length)[0];
|
|
67
70
|
return b ? { category: b.category, every: b.every, amount: b.amount, spent: b.spent, left: b.left } : { category, none: true };
|
|
68
71
|
}
|
|
69
|
-
|
|
70
|
-
if (!input.merchant && !input.kind)
|
|
71
|
-
throw new Error("Say what is bought: merchant (e.g. Shopee, Co.opmart) or kind (e.g. groceries).");
|
|
72
|
-
const date = input.date ?? asOf;
|
|
73
|
-
let mine = cards(l, asOf);
|
|
74
|
-
if (input.accounts?.length) {
|
|
75
|
-
const unknown = input.accounts.filter((a) => !mine.some((c) => c.account === a));
|
|
76
|
-
if (unknown.length)
|
|
77
|
-
throw new Error(`not an open credit card: ${unknown.join(", ")}`);
|
|
78
|
-
mine = mine.filter((c) => input.accounts.includes(c.account));
|
|
79
|
-
}
|
|
80
|
-
if (!mine.length)
|
|
81
|
-
throw new Error("No open credit cards in the ledger.");
|
|
72
|
+
async function openWalletRows(l, asOf, ow, mine, input, date) {
|
|
82
73
|
const [what, ...looked] = await Promise.all([resolveWhat(ow, input), ...mine.map((c) => findCard(ow, c))]);
|
|
83
74
|
const found = [];
|
|
84
75
|
const notMatched = [];
|
|
@@ -93,13 +84,9 @@ export async function bestCard(l, asOf, ow, input) {
|
|
|
93
84
|
else
|
|
94
85
|
notMatched.push(r);
|
|
95
86
|
}
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
"cap_used is the cashback booked to the card this period; banks often pay it after the statement closes, so the bank's figure can be higher.",
|
|
99
|
-
];
|
|
100
|
-
let ranking = [];
|
|
87
|
+
const rows = new Map();
|
|
88
|
+
const assumptions = [];
|
|
101
89
|
let catalog = null;
|
|
102
|
-
let purchase = null;
|
|
103
90
|
if (found.length) {
|
|
104
91
|
const states = found.map((f) => ({ id: f.ow.id, spend_so_far: Math.max(0, f.card.period.spent - f.card.period.refunds), cap_used: Math.max(0, f.card.period.cashback) }));
|
|
105
92
|
const r = await ow.call("rank_cards_for_spend", {
|
|
@@ -107,43 +94,84 @@ export async function bestCard(l, asOf, ow, input) {
|
|
|
107
94
|
cards: states,
|
|
108
95
|
limit: 20,
|
|
109
96
|
});
|
|
110
|
-
purchase = r?.purchase ?? null;
|
|
111
97
|
catalog = r?.meta?.catalog ?? null;
|
|
112
|
-
assumptions.push(...(r?.assumptions ?? []));
|
|
113
|
-
|
|
98
|
+
assumptions.push("OpenWallet cards: spend_so_far and cap_used come from the ledger (what is recorded this statement period); banks often pay cashback after the statement closes, so the bank's cap used can be higher.", ...(r?.assumptions ?? []).map((a) => `OpenWallet: ${a}`));
|
|
99
|
+
for (const x of (r?.cards ?? [])) {
|
|
114
100
|
const f = found.find((y) => y.ow.id === x.id);
|
|
115
|
-
const st = states.find((
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
effective_rate: x.effective_rate,
|
|
101
|
+
const st = states.find((y) => y.id === x.id);
|
|
102
|
+
rows.set(f.card.account, {
|
|
103
|
+
source: "openwallet",
|
|
104
|
+
earn: x.cashback ?? null,
|
|
105
|
+
rate: typeof x.effective_rate === "number" ? Math.round(x.effective_rate * 10000) / 100 : null,
|
|
106
|
+
capLeft: x.rule?.cap_remaining ?? x.global_cap_remaining ?? null,
|
|
122
107
|
status: x.status,
|
|
123
|
-
reason: x.reason,
|
|
124
|
-
rule: x.rule ? { rate: x.rule.rate ?? null, cap: x.rule.cap ?? null, cap_remaining: x.rule.cap_remaining ?? null, ...(x.rule.intents ? { kinds: x.rule.intents } : {}) } : null,
|
|
125
|
-
global_cap_remaining: x.global_cap_remaining ?? null,
|
|
126
|
-
min_spend: x.min_spend ?? null,
|
|
127
108
|
spend_so_far: st.spend_so_far,
|
|
128
109
|
cap_used: st.cap_used,
|
|
129
|
-
available: f.card.available,
|
|
130
|
-
enough_credit: f.card.available === null ? null : f.card.available >= input.amount,
|
|
131
|
-
toPay: f.card.toPay,
|
|
132
|
-
dueDate: f.card.dueDate,
|
|
133
110
|
openwallet: { id: f.ow.id, name: f.ow.name, url: x.url ?? f.ow.url ?? null, lastChecked: x.lastChecked ?? f.ow.lastChecked ?? null },
|
|
134
|
-
|
|
135
|
-
|
|
111
|
+
reason: `${f.card.name}: OpenWallet (${f.ow.name}) · ${x.reason ?? x.status}`,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
136
114
|
}
|
|
115
|
+
return { rows, notMatched, assumptions, catalog, what: what.label };
|
|
116
|
+
}
|
|
117
|
+
export async function bestCard(l, asOf, ow, input) {
|
|
118
|
+
const date = input.date ?? asOf;
|
|
119
|
+
const amount = input.amount ?? 0;
|
|
120
|
+
let local = localBestCard(l, { category: input.category ?? "", amount, date });
|
|
121
|
+
if (input.accounts?.length) {
|
|
122
|
+
const known = new Set(local.map((r) => r.account));
|
|
123
|
+
const unknown = input.accounts.filter((a) => !known.has(a));
|
|
124
|
+
if (unknown.length)
|
|
125
|
+
throw new Error(`not a card that can be used: ${unknown.join(", ")}`);
|
|
126
|
+
local = local.filter((r) => input.accounts.includes(r.account));
|
|
127
|
+
}
|
|
128
|
+
if (!local.length)
|
|
129
|
+
throw new Error("No open card to use (closed, cancelled or locked cards are left out, and cards without enough limit left).");
|
|
130
|
+
const hasTerms = (id) => {
|
|
131
|
+
const a = l.accounts.find((x) => x.id === id);
|
|
132
|
+
return termsOf(a, recordFor(l, id)).cashback !== null;
|
|
133
|
+
};
|
|
134
|
+
const assumptions = [];
|
|
135
|
+
if (!input.category)
|
|
136
|
+
assumptions.push("No category given: cards with your own terms use their base rate.");
|
|
137
|
+
const without = local.filter((r) => !hasTerms(r.account));
|
|
138
|
+
const status = cards(l, date);
|
|
139
|
+
const asking = without.map((r) => status.find((c) => c.account === r.account)).filter((c) => Boolean(c));
|
|
140
|
+
let fromOw = null;
|
|
141
|
+
if (ow && asking.length) {
|
|
142
|
+
if (!input.amount)
|
|
143
|
+
assumptions.push("OpenWallet not asked: give the amount.");
|
|
144
|
+
else if (!input.merchant && !input.kind)
|
|
145
|
+
assumptions.push("OpenWallet not asked: give a merchant (e.g. Shopee) or a kind (e.g. groceries) for the cards without your own terms.");
|
|
146
|
+
else
|
|
147
|
+
fromOw = await openWalletRows(l, asOf, ow, asking, { ...input, amount: input.amount }, date);
|
|
148
|
+
}
|
|
149
|
+
if (fromOw)
|
|
150
|
+
assumptions.push(...fromOw.assumptions);
|
|
151
|
+
const rows = local.map((r) => {
|
|
152
|
+
if (hasTerms(r.account))
|
|
153
|
+
return { ...r, source: "yours" };
|
|
154
|
+
const o = fromOw?.rows.get(r.account);
|
|
155
|
+
if (o)
|
|
156
|
+
return { ...r, ...o, source: "openwallet" };
|
|
157
|
+
return {
|
|
158
|
+
...r,
|
|
159
|
+
source: "none",
|
|
160
|
+
earn: null,
|
|
161
|
+
rate: null,
|
|
162
|
+
reason: `${r.name}: no cashback terms set${ow ? " and not found in OpenWallet" : ""}${r.payBy ? ` · pay by ${r.payBy} (${r.freeDays} days)` : ""}`,
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
// most cashback first (a minimum still to reach counts half), then interest-free days, then limit left
|
|
166
|
+
const effective = (b) => (!b.earn ? -1 : b.minSpendShort > 0 ? b.earn / 2 : b.earn);
|
|
167
|
+
rows.sort((x, y) => effective(y) - effective(x) || (y.freeDays ?? -1) - (x.freeDays ?? -1) || (y.limitLeft ?? 0) - (x.limitLeft ?? 0));
|
|
137
168
|
return {
|
|
138
|
-
purchase:
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
...(notMatched.length ? { not_matched: notMatched } : {}),
|
|
169
|
+
purchase: { amount: input.amount ?? null, date, category: input.category ?? null, merchant: input.merchant ?? null, kind: input.kind ?? null },
|
|
170
|
+
cards: rows.slice(0, 10),
|
|
171
|
+
...(fromOw?.notMatched.length ? { not_matched: fromOw.notMatched } : {}),
|
|
142
172
|
...(input.category ? { budget: budgetFor(l, asOf, input.category) } : {}),
|
|
143
173
|
assumptions,
|
|
144
|
-
|
|
145
|
-
note:
|
|
146
|
-
? "Cashback rules are OpenWallet's, quoted with their date (lastChecked, or the catalog date when null: then unverified). Unknown is not 0."
|
|
147
|
-
: "None of the cards could be found in OpenWallet: see not_matched.",
|
|
174
|
+
...(fromOw ? { openwallet: { url: ow.url, catalog: fromOw.catalog, what: fromOw.what } } : {}),
|
|
175
|
+
note: "source says where each cashback figure comes from: yours (your own terms), openwallet (its catalog, quoted with lastChecked or the catalog date), none (unknown, which is not 0).",
|
|
148
176
|
};
|
|
149
177
|
}
|
package/dist/worker/github.d.ts
CHANGED
|
@@ -12,8 +12,10 @@ 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
|
+
/** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball; statement PDFs by path only (""). */
|
|
16
16
|
export declare function filesAt(c: GitHubAppConfig, sha: string): Promise<Record<string, string>>;
|
|
17
|
+
/** One file's bytes at a commit, streamed (null when it isn't there). */
|
|
18
|
+
export declare function blobAt(c: GitHubAppConfig, sha: string, path: string): Promise<Response | null>;
|
|
17
19
|
export interface CommitFile {
|
|
18
20
|
path: string;
|
|
19
21
|
content?: string;
|
package/dist/worker/github.js
CHANGED
|
@@ -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,24 @@ 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
|
+
/** Every file under data/ and imports/*.mapping.yaml at a commit, from one tarball; statement PDFs by path only (""). */
|
|
79
80
|
export async function filesAt(c, sha) {
|
|
80
81
|
const token = await installationToken(c);
|
|
81
82
|
const res = await gh(`/repos/${c.repo}/tarball/${sha}`, token);
|
|
82
83
|
if (!res.ok || !res.body)
|
|
83
84
|
throw new Error(`GitHub tarball: ${res.status}`);
|
|
84
85
|
const { untar } = await import("./tar.js");
|
|
85
|
-
return untar(res.body.pipeThrough(new DecompressionStream("gzip")), (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p));
|
|
86
|
+
return untar(res.body.pipeThrough(new DecompressionStream("gzip")), (p) => p.startsWith("data/") || /^imports\/[^/]+\.mapping\.yaml$/.test(p), (p) => STATEMENT_PDF_RE.test(p));
|
|
87
|
+
}
|
|
88
|
+
/** One file's bytes at a commit, streamed (null when it isn't there). */
|
|
89
|
+
export async function blobAt(c, sha, path) {
|
|
90
|
+
const token = await installationToken(c);
|
|
91
|
+
const res = await gh(`/repos/${c.repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(sha)}`, token, { headers: { Accept: "application/vnd.github.raw" } });
|
|
92
|
+
if (res.status === 404)
|
|
93
|
+
return null;
|
|
94
|
+
if (!res.ok || !res.body)
|
|
95
|
+
throw new Error(`GitHub file: ${res.status}`);
|
|
96
|
+
return res;
|
|
86
97
|
}
|
|
87
98
|
/** One atomic commit on top of `baseSha`; refused (MainMovedError) if the branch moved. */
|
|
88
99
|
export async function commit(c, baseSha, files, message) {
|