ownledger 2.3.0 → 2.4.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/CHANGELOG.md +30 -0
- package/README.md +26 -0
- package/assets/index.html +10 -10
- package/assets/static/{Account-CYrXDU9Z.js → Account-DIDz6cXc.js} +1 -1
- package/assets/static/{Accounts-BXleOwUO.js → Accounts-BHqMr96X.js} +1 -1
- package/assets/static/{Attention-Ci3luOdE.js → Attention-DW0iYViO.js} +1 -1
- package/assets/static/{ByCategory-cLVOyjwd.js → ByCategory-BcC8nC5_.js} +1 -1
- package/assets/static/CardBudgets-CaXHjpKv.js +1 -0
- package/assets/static/CardDetail-C-EWPz9U.js +1 -0
- package/assets/static/{Cards-DnIsAWPD.js → Cards-2bB7IrMZ.js} +1 -1
- package/assets/static/{Cards-DNtITMnA.js → Cards-CXuGLYDb.js} +1 -1
- package/assets/static/{CardsValue-V1-fYMLf.js → CardsValue-CBP2-s79.js} +1 -1
- package/assets/static/{Cashback-B8lqwRnb.js → Cashback-BRHegG4o.js} +1 -1
- package/assets/static/{CategoryIcon-D4Cdb_ZP.js → CategoryIcon-DZf6uKtg.js} +1 -1
- package/assets/static/{CategoryPicker-54vkuxVh.js → CategoryPicker-CIgSXytj.js} +1 -1
- package/assets/static/{ChartWidget-S5F4Ze91.js → ChartWidget-B5oybW6u.js} +1 -1
- package/assets/static/{Combobox-BvX68J3o.js → Combobox-CK6B8Keq.js} +1 -1
- package/assets/static/{Deposits-Ct5HhCEc.js → Deposits-Ddy3xcdL.js} +1 -1
- package/assets/static/{DrillLink-CZyI-y0-.js → DrillLink-CaBCVQQj.js} +1 -1
- package/assets/static/{Field-DYmqEAlI.js → Field-rwl1eTQR.js} +1 -1
- package/assets/static/{HomeEditor-Dv-h_ql-.js → HomeEditor-Or4bvFoV.js} +1 -1
- package/assets/static/{Import-B2uhVnEm.js → Import-CPpOHxfR.js} +1 -1
- package/assets/static/{IncomeSpending-DNT2CWH9.js → IncomeSpending-Dw_YhoO_.js} +1 -1
- package/assets/static/{KV-CKWaJkRK.js → KV-Cpfsyhnb.js} +1 -1
- package/assets/static/{Left-BefXZztB.js → Left-BiuU811i.js} +1 -1
- package/assets/static/{Money-BwLucm7P.js → Money-DFHYuv5m.js} +1 -1
- package/assets/static/{NetWorth-DeLSapZ2.js → NetWorth-B9uU7Ope.js} +1 -1
- package/assets/static/{Pace-D6gilOBZ.js → Pace-BbOf0yAs.js} +1 -1
- package/assets/static/{Panel-CSe25x0N.js → Panel-tOE_I4OD.js} +1 -1
- package/assets/static/{PinDialog-CHiLIKEs.js → PinDialog-Dj4j0jcD.js} +1 -1
- package/assets/static/{Plans-D7rJ1yHU.js → Plans-COJrKjSX.js} +1 -1
- package/assets/static/{Recent-Dcqb2yko.js → Recent-BJrdjtMv.js} +1 -1
- package/assets/static/{Reports--PDAEnQM.js → Reports-ByrhmAQv.js} +1 -1
- package/assets/static/{Settings-Bd0oglWl.js → Settings-BunM2dfp.js} +1 -1
- package/assets/static/{Transactions-CQ1yQ1UU.js → Transactions-DVJDPqHI.js} +1 -1
- package/assets/static/{TxRow-BGfpKo2m.js → TxRow-CZJ_C-Cp.js} +1 -1
- package/assets/static/{Unusual-DGB4ZOA2.js → Unusual-ChtSsnCm.js} +1 -1
- package/assets/static/{Upcoming-B0HwBqmG.js → Upcoming-D6ab7_fA.js} +1 -1
- package/assets/static/{WhichCard-BefFKS2q.js → WhichCard-BlBXpqMn.js} +1 -1
- package/assets/static/{arrow-up-CRgLRKET.js → arrow-up-7r2T_P3U.js} +1 -1
- package/assets/static/{bits-D34d9IBm.js → bits-CayEEXaW.js} +1 -1
- package/assets/static/{button-BKhMn8jX.js → button-DQvRPLIv.js} +1 -1
- package/assets/static/{cards-Ct0jh73r.js → cards-BP4EqCQY.js} +1 -1
- package/assets/static/{charts-D-1glV8L.js → charts-DzDF8ihe.js} +1 -1
- package/assets/static/chevron-down-wODISwBd.js +1 -0
- package/assets/static/chevron-right-CRhYK7Bh.js +1 -0
- package/assets/static/{createLucideIcon-XZ28znwT.js → createLucideIcon-DI8vbiOO.js} +1 -1
- package/assets/static/{dialog-Bx-cd-2e.js → dialog-B6000kEK.js} +1 -1
- package/assets/static/{dist-BFPyD74_.js → dist-Cb1_dp0K.js} +1 -1
- package/assets/static/{dist--HKr0kfV.js → dist-CqPSw3yk.js} +1 -1
- package/assets/static/{dist-vgyaCpaL.js → dist-DabFVUs-.js} +1 -1
- package/assets/static/{dist-CmbuesVk.js → dist-DiXEmDmz.js} +1 -1
- package/assets/static/{es2015-DqY4UvQc.js → es2015-ConR4hgR.js} +1 -1
- package/assets/static/index-DvdDpUvS.js +14 -0
- package/assets/static/{queries-BcMmmb36.js → queries-Dr6hPr4g.js} +1 -1
- package/assets/static/{react-dom-5dgiSOdd.js → react-dom-DKhzijWz.js} +1 -1
- package/assets/static/{select-B5P2TaPX.js → select-5FcHJXrC.js} +1 -1
- package/assets/static/{shared-BgU6fc7z.js → shared-C3-t8uIq.js} +1 -1
- package/assets/static/{triangle-exclamation-point-CMy18kC0.js → triangle-exclamation-point-B4sQZqpa.js} +1 -1
- package/assets/static/{useMutation-aC3Z1p9y.js → useMutation-Bf1MT3Q_.js} +1 -1
- package/dist/engine/actions.js +22 -7
- package/dist/engine/dashboard.js +1 -0
- package/dist/modules/cards/index.d.ts +2 -1
- package/dist/modules/cards/index.js +51 -19
- package/dist/modules/cards/statements.d.ts +57 -0
- package/dist/modules/cards/statements.js +183 -33
- package/dist/modules/cards/terms.d.ts +18 -0
- package/dist/modules/cards/terms.js +15 -5
- package/dist/node/statement-rows.js +3 -1
- package/dist/worker/bestcard.d.ts +58 -0
- package/dist/worker/bestcard.js +65 -1
- package/dist/worker/mcp.js +38 -7
- package/dist/worker/version.d.ts +1 -1
- package/dist/worker/version.js +1 -1
- package/package.json +1 -1
- package/assets/static/CardDetail-BxXfAcMp.js +0 -1
- package/assets/static/chevron-down-BWoQwA6m.js +0 -1
- package/assets/static/chevron-right-D7Sgw1v1.js +0 -1
- package/assets/static/index-DBHFdsYB.js +0 -14
|
@@ -3,6 +3,7 @@ import { flattenCategories, isSystemCategory, topOf } from "../../engine/categor
|
|
|
3
3
|
import { addDays, addMonths, dayIn, daysBetween, monthStart, parts } from "../../engine/dates.js";
|
|
4
4
|
import { dueDates } from "../loans/engine.js";
|
|
5
5
|
import { isOpen } from "../util.js";
|
|
6
|
+
import { fold } from "../../engine/reports.js";
|
|
6
7
|
import { cardsData, recordFor, termsOf } from "./terms.js";
|
|
7
8
|
/* ------------------------------------------------------------------ dates */
|
|
8
9
|
/** The statement date in month (y, m). */
|
|
@@ -178,11 +179,22 @@ export function statements(l, account, asOf) {
|
|
|
178
179
|
}
|
|
179
180
|
return out;
|
|
180
181
|
}
|
|
181
|
-
|
|
182
|
+
/** Folded words of a transaction a merchant rule looks in. */
|
|
183
|
+
const merchantText = (x) => fold(`${x.merchant ?? ""} ${x.note ?? ""}`);
|
|
184
|
+
function ruleFor(cb, category, text) {
|
|
185
|
+
if (text)
|
|
186
|
+
for (const r of cb.rules)
|
|
187
|
+
if (r.merchants.some((m) => text.includes(fold(m))))
|
|
188
|
+
return r;
|
|
182
189
|
for (const r of cb.rules)
|
|
183
190
|
if (r.categories.some((c) => category === c || category.startsWith(c + "/")))
|
|
184
|
-
return r
|
|
185
|
-
return
|
|
191
|
+
return r;
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
const ruleLabel = (r) => r.label ?? [...r.categories, ...r.merchants].join(", ");
|
|
195
|
+
/** The statement date the open period will close on (the first one after asOf). */
|
|
196
|
+
export function openClose(asOf, sd) {
|
|
197
|
+
return closeOnOrAfter(addDays(asOf, 1), sd);
|
|
186
198
|
}
|
|
187
199
|
/** Cashback periods: the statement periods (credit) or monthly cycles from statement_day (debit cards). */
|
|
188
200
|
function cyclesFor(l, account, sd, asOf, from) {
|
|
@@ -194,6 +206,26 @@ function cyclesFor(l, account, sd, asOf, from) {
|
|
|
194
206
|
out.push({ from: addDays(prevClose(c, sd), 1), close: asOf, open: true });
|
|
195
207
|
return out;
|
|
196
208
|
}
|
|
209
|
+
/** Cashback rows booked for this card in [from, to]: on the card, or elsewhere carrying card: <account>. */
|
|
210
|
+
function cashbackIn(txs, account, cats, from, to) {
|
|
211
|
+
const out = [];
|
|
212
|
+
for (const x of txs) {
|
|
213
|
+
if (x.date < from || x.date > to)
|
|
214
|
+
continue;
|
|
215
|
+
const k = lineKind(x, account, cats);
|
|
216
|
+
let a = 0;
|
|
217
|
+
if (k?.kind === "cashback")
|
|
218
|
+
a = k.amount;
|
|
219
|
+
else if (x.card === account && !x.lines.some((ln) => ln.account === account)) {
|
|
220
|
+
for (const ln of x.lines)
|
|
221
|
+
if (ln.category && topOf(ln.category) === "cashback")
|
|
222
|
+
a += -ln.amount;
|
|
223
|
+
}
|
|
224
|
+
if (a)
|
|
225
|
+
out.push({ date: x.date, amount: a });
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
197
229
|
/** Expected against received cashback, per statement (or cashback cycle), for a card with cashback terms. */
|
|
198
230
|
export function cashback(l, account, asOf) {
|
|
199
231
|
const a = l.accounts.find((x) => x.id === account);
|
|
@@ -208,8 +240,10 @@ export function cashback(l, account, asOf) {
|
|
|
208
240
|
const txs = l.transactions.filter((x) => !x.void && x.date <= addMonths(asOf, 2) && (x.lines.some((ln) => ln.account === account) || x.card === account));
|
|
209
241
|
if (!txs.length)
|
|
210
242
|
return [];
|
|
243
|
+
const hasMerchantRules = cb.rules.some((r) => r.merchants.length);
|
|
211
244
|
const out = [];
|
|
212
245
|
for (const p of cyclesFor(l, account, sd, asOf, txs[0].date)) {
|
|
246
|
+
// one group per rule (by its index), "base" for everything else
|
|
213
247
|
const groups = new Map();
|
|
214
248
|
let spend = 0;
|
|
215
249
|
for (const x of txs) {
|
|
@@ -218,64 +252,164 @@ export function cashback(l, account, asOf) {
|
|
|
218
252
|
const k = lineKind(x, account, cats);
|
|
219
253
|
if (!k || (k.kind !== "purchase" && k.kind !== "refund"))
|
|
220
254
|
continue;
|
|
255
|
+
const text = hasMerchantRules ? merchantText(x) : undefined;
|
|
221
256
|
for (const ln of x.lines) {
|
|
222
257
|
if (!ln.category || isSystemCategory(ln.category) || cats.get(ln.category)?.kind === "income")
|
|
223
258
|
continue;
|
|
224
|
-
const
|
|
225
|
-
const
|
|
259
|
+
const rule = ruleFor(cb, ln.category, text);
|
|
260
|
+
const key = rule ? String(cb.rules.indexOf(rule)) : "base";
|
|
261
|
+
const g = groups.get(key) ?? { rule, spend: 0, categories: new Set() };
|
|
226
262
|
g.spend += ln.amount;
|
|
227
263
|
g.categories.add(ln.category);
|
|
228
|
-
groups.set(
|
|
264
|
+
groups.set(key, g);
|
|
229
265
|
spend += ln.amount;
|
|
230
266
|
}
|
|
231
267
|
}
|
|
268
|
+
// every rule shows in the open period, spent on or not, so its room is known
|
|
269
|
+
if (p.open)
|
|
270
|
+
cb.rules.forEach((r, i) => { if (!groups.has(String(i)))
|
|
271
|
+
groups.set(String(i), { rule: r, spend: 0, categories: new Set() }); });
|
|
232
272
|
const minSpend = cb.min_spend?.amount ?? null;
|
|
233
273
|
const minMet = minSpend === null || spend >= minSpend;
|
|
234
274
|
const scale = cb.spend_max && spend > cb.spend_max.amount ? cb.spend_max.amount / spend : 1;
|
|
235
|
-
let
|
|
275
|
+
let raw = 0;
|
|
236
276
|
let incomplete = false;
|
|
277
|
+
const list = [];
|
|
237
278
|
for (const g of groups.values()) {
|
|
238
|
-
|
|
279
|
+
const rate = g.rule ? g.rule.rate : cb.base;
|
|
280
|
+
let earned = 0;
|
|
281
|
+
if (rate === null) {
|
|
239
282
|
if (g.spend > 0)
|
|
240
283
|
incomplete = true;
|
|
241
|
-
continue;
|
|
242
284
|
}
|
|
243
|
-
|
|
285
|
+
else {
|
|
286
|
+
earned = (Math.max(0, g.spend) * rate) / 100;
|
|
287
|
+
if (g.rule?.cap != null)
|
|
288
|
+
earned = Math.min(earned, g.rule.cap);
|
|
289
|
+
}
|
|
290
|
+
raw += earned;
|
|
291
|
+
list.push({
|
|
292
|
+
label: g.rule ? ruleLabel(g.rule) : "other",
|
|
293
|
+
categories: g.rule ? (g.rule.categories.length ? g.rule.categories : [...g.categories]) : [...g.categories],
|
|
294
|
+
merchants: g.rule?.merchants ?? [],
|
|
295
|
+
rate,
|
|
296
|
+
spend: g.spend,
|
|
297
|
+
earned: Math.round(earned),
|
|
298
|
+
cap: g.rule?.cap ?? null,
|
|
299
|
+
room: null,
|
|
300
|
+
inStore: g.rule?.inStore ?? false,
|
|
301
|
+
});
|
|
244
302
|
}
|
|
245
|
-
expected = minMet ? Math.round(
|
|
303
|
+
let expected = minMet ? Math.round(raw * scale) : 0;
|
|
246
304
|
const cap = cb.cap?.amount ?? null;
|
|
247
305
|
if (cap !== null)
|
|
248
306
|
expected = Math.min(expected, cap);
|
|
307
|
+
// room: what the caps still pay for, counted on what was earned before the minimum (the minimum is its own warning)
|
|
308
|
+
const globalLeft = cap === null ? null : Math.max(0, cap - Math.round(raw * scale));
|
|
309
|
+
for (const g of list) {
|
|
310
|
+
if (g.cap === null || !g.rate)
|
|
311
|
+
continue;
|
|
312
|
+
let left = Math.max(0, g.cap - g.earned);
|
|
313
|
+
if (globalLeft !== null)
|
|
314
|
+
left = Math.min(left, globalLeft);
|
|
315
|
+
g.room = Math.ceil((left * 100) / g.rate);
|
|
316
|
+
}
|
|
317
|
+
const byRateMap = new Map();
|
|
318
|
+
for (const g of list) {
|
|
319
|
+
if (!g.spend && !g.categories.length)
|
|
320
|
+
continue;
|
|
321
|
+
const r = byRateMap.get(String(g.rate)) ?? { rate: g.rate, spend: 0, categories: [] };
|
|
322
|
+
r.spend += g.spend;
|
|
323
|
+
r.categories.push(...g.categories.filter((c) => !r.categories.includes(c)));
|
|
324
|
+
byRateMap.set(String(g.rate), r);
|
|
325
|
+
}
|
|
249
326
|
const payBy = cb.paid_on.kind === "next_statement" ? nextClose(p.open ? closeOnOrAfter(p.close, sd) : p.close, sd) : addDays(p.close, cb.paid_on.days);
|
|
250
327
|
const winFrom = p.open ? payBy : addDays(p.close, 1);
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
for (const x of txs) {
|
|
254
|
-
if (x.date < winFrom || x.date > payBy)
|
|
255
|
-
continue;
|
|
256
|
-
const k = lineKind(x, account, cats);
|
|
257
|
-
if (k?.kind === "cashback")
|
|
258
|
-
received += k.amount;
|
|
259
|
-
else if (x.card === account && !x.lines.some((ln) => ln.account === account)) {
|
|
260
|
-
for (const ln of x.lines)
|
|
261
|
-
if (ln.category && topOf(ln.category) === "cashback")
|
|
262
|
-
received += -ln.amount;
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
out.push({
|
|
328
|
+
const received = p.open ? 0 : cashbackIn(txs, account, cats, winFrom, payBy).reduce((s, x) => s + x.amount, 0);
|
|
329
|
+
const row = {
|
|
267
330
|
from: p.from, close: p.close, open: p.open, spend,
|
|
268
|
-
byRate: [...
|
|
331
|
+
byRate: [...byRateMap.values()].filter((r) => r.spend !== 0).sort((x, y) => y.spend - x.spend),
|
|
332
|
+
groups: list.filter((g) => p.open || g.spend !== 0).sort((x, y) => (y.rate ?? -1) - (x.rate ?? -1)),
|
|
269
333
|
expected, incomplete, minSpend, minMet, needForMin: minSpend === null ? 0 : Math.max(0, minSpend - spend),
|
|
270
334
|
cap, capLeft: cap === null ? null : Math.max(0, cap - expected), received, payBy,
|
|
271
|
-
}
|
|
335
|
+
};
|
|
336
|
+
if (p.open) {
|
|
337
|
+
const closesOn = openClose(asOf, sd);
|
|
338
|
+
const safeUntil = addDays(closesOn, -cb.postMargin);
|
|
339
|
+
const ruleCaps = list.some((g) => g.room !== null);
|
|
340
|
+
const best = Math.max(0, ...list.map((g) => g.rate ?? 0));
|
|
341
|
+
let roomSpend = null;
|
|
342
|
+
let roomEstimate = false;
|
|
343
|
+
if (!ruleCaps) {
|
|
344
|
+
if (cb.spend_max)
|
|
345
|
+
roomSpend = Math.max(0, cb.spend_max.amount - spend);
|
|
346
|
+
else if (globalLeft !== null && best > 0) {
|
|
347
|
+
roomSpend = Math.ceil((globalLeft * 100) / best);
|
|
348
|
+
roomEstimate = true;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const groupLeft = list.reduce((s, g) => s + (g.cap !== null && g.rate ? Math.max(0, g.cap - g.earned) : 0), 0);
|
|
352
|
+
const earnLeft = ruleCaps ? (globalLeft === null ? groupLeft : Math.min(groupLeft, globalLeft)) : globalLeft;
|
|
353
|
+
Object.assign(row, { closesOn, safeUntil, daysLeft: daysBetween(asOf, safeUntil), roomSpend, roomEstimate, earnLeft });
|
|
354
|
+
}
|
|
355
|
+
out.push(row);
|
|
272
356
|
}
|
|
273
357
|
return out;
|
|
274
358
|
}
|
|
359
|
+
/** A points card's balance (details.cashback.payout: points); null for other cards. */
|
|
360
|
+
export function points(l, account, asOf) {
|
|
361
|
+
const a = l.accounts.find((x) => x.id === account);
|
|
362
|
+
if (!a)
|
|
363
|
+
return null;
|
|
364
|
+
const cb = termsOf(a, recordFor(l, account)).cashback;
|
|
365
|
+
if (!cb || cb.payout !== "points")
|
|
366
|
+
return null;
|
|
367
|
+
const periods = cashback(l, account, asOf);
|
|
368
|
+
const { map: cats } = flattenCategories(l.categories);
|
|
369
|
+
const txs = l.transactions.filter((x) => !x.void && x.date <= asOf && (x.lines.some((ln) => ln.account === account) || x.card === account));
|
|
370
|
+
const lots = periods.filter((p) => !p.open && p.expected > 0).map((p) => ({ close: p.close, left: p.expected, expires: cb.expireMonths ? addMonths(p.close, cb.expireMonths) : null }));
|
|
371
|
+
let expired = 0;
|
|
372
|
+
const expireBefore = (d) => {
|
|
373
|
+
for (const x of lots)
|
|
374
|
+
if (x.left > 0 && x.expires && x.expires < d) {
|
|
375
|
+
expired += x.left;
|
|
376
|
+
x.left = 0;
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
const cashed = periods.length ? cashbackIn(txs, account, cats, periods[0].from, asOf).sort((x, y) => (x.date < y.date ? -1 : 1)) : [];
|
|
380
|
+
for (const r of cashed) {
|
|
381
|
+
expireBefore(r.date);
|
|
382
|
+
let left = r.amount;
|
|
383
|
+
for (const x of lots) {
|
|
384
|
+
if (left <= 0)
|
|
385
|
+
break;
|
|
386
|
+
if (x.close >= r.date || x.left <= 0)
|
|
387
|
+
continue;
|
|
388
|
+
const take = Math.min(x.left, left);
|
|
389
|
+
x.left -= take;
|
|
390
|
+
left -= take;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
expireBefore(addDays(asOf, 1));
|
|
394
|
+
const held = lots.filter((x) => x.left > 0);
|
|
395
|
+
const balance = held.reduce((s, x) => s + x.left, 0);
|
|
396
|
+
const open = periods.find((p) => p.open);
|
|
397
|
+
return {
|
|
398
|
+
account,
|
|
399
|
+
name: a.name,
|
|
400
|
+
balance,
|
|
401
|
+
pending: open?.expected ?? 0,
|
|
402
|
+
redeemMin: cb.redeemMin,
|
|
403
|
+
canRedeem: balance > 0 && (cb.redeemMin === null || balance >= cb.redeemMin),
|
|
404
|
+
lots: held,
|
|
405
|
+
expired,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
275
408
|
export function bestCard(l, q) {
|
|
276
409
|
const amount = q.amount ?? 0;
|
|
277
410
|
const owed = holdingsAt(l, q.date);
|
|
278
411
|
const recs = cardsData(l).records;
|
|
412
|
+
const text = q.merchant ? fold(q.merchant) : undefined;
|
|
279
413
|
const candidates = [];
|
|
280
414
|
for (const a of l.accounts) {
|
|
281
415
|
if (!isOpen(a, q.date))
|
|
@@ -290,14 +424,24 @@ export function bestCard(l, q) {
|
|
|
290
424
|
for (const { a, rec } of candidates) {
|
|
291
425
|
const t = termsOf(a, rec);
|
|
292
426
|
const cb = t.cashback;
|
|
293
|
-
const
|
|
427
|
+
const rule = cb ? ruleFor(cb, q.category, text) : null;
|
|
428
|
+
const rate = cb ? (rule ? rule.rate : cb.base) : null;
|
|
294
429
|
let capLeft = null;
|
|
295
430
|
let minShort = 0;
|
|
431
|
+
let safeUntil = null;
|
|
432
|
+
let nextPeriod = false;
|
|
296
433
|
if (cb) {
|
|
297
434
|
const cur = cashback(l, a.id, q.date).find((p) => p.open);
|
|
298
|
-
|
|
435
|
+
const g = rule && cur ? cur.groups.find((x) => x.label === ruleLabel(rule)) : undefined;
|
|
436
|
+
const ruleLeft = rule?.cap != null ? Math.max(0, rule.cap - (g?.earned ?? 0)) : null;
|
|
437
|
+
const cardLeft = cb.cap ? (cur?.capLeft ?? cb.cap.amount) : null;
|
|
438
|
+
capLeft = ruleLeft === null ? cardLeft : cardLeft === null ? ruleLeft : Math.min(ruleLeft, cardLeft);
|
|
299
439
|
if (cb.min_spend)
|
|
300
440
|
minShort = Math.max(0, cb.min_spend.amount - ((cur?.spend ?? 0) + amount));
|
|
441
|
+
if (a.type === "credit_card" && t.statementDay) {
|
|
442
|
+
safeUntil = cur?.safeUntil ?? null;
|
|
443
|
+
nextPeriod = safeUntil !== null && q.date > safeUntil;
|
|
444
|
+
}
|
|
301
445
|
}
|
|
302
446
|
const raw = rate === null ? null : Math.round((amount * rate) / 100);
|
|
303
447
|
const earn = raw === null ? null : capLeft === null ? raw : Math.min(raw, capLeft);
|
|
@@ -305,11 +449,17 @@ export function bestCard(l, q) {
|
|
|
305
449
|
const freeDays = payBy ? daysBetween(q.date, payBy) : null;
|
|
306
450
|
const limitLeft = t.limit === null ? null : t.limit + (owed.get(a.id)?.amount ?? 0);
|
|
307
451
|
const bits = [
|
|
308
|
-
rate === null ? "cashback rate not set" : `${rate}%${capLeft !== null ? ` (cap left ${capLeft})` : ""}`,
|
|
452
|
+
rate === null ? "cashback rate not set" : `${rate}%${rule && (rule.label || rule.merchants.length) ? ` on ${ruleLabel(rule)}` : ""}${capLeft !== null ? ` (cap left ${capLeft})` : ""}`,
|
|
453
|
+
...(rule?.inStore ? ["in store only, not online"] : []),
|
|
309
454
|
...(minShort > 0 ? [`spend ${minShort} more for the minimum`] : []),
|
|
455
|
+
...(nextPeriod ? [`after ${safeUntil}: may post on the next statement`] : safeUntil ? [`last safe day ${safeUntil}`] : []),
|
|
310
456
|
...(payBy ? [`pay by ${payBy} (${freeDays} days)`] : []),
|
|
311
457
|
];
|
|
312
|
-
out.push({
|
|
458
|
+
out.push({
|
|
459
|
+
account: a.id, name: a.name, rate, earn, capLeft, minSpendShort: minShort, payBy, freeDays, limitLeft,
|
|
460
|
+
...(cb ? { rule: rule ? ruleLabel(rule) : null, inStore: rule?.inStore ?? false, safeUntil, nextPeriod } : {}),
|
|
461
|
+
reason: `${a.name}: ${bits.join(" · ")}`,
|
|
462
|
+
});
|
|
313
463
|
}
|
|
314
464
|
// no cashback (unknown or 0%) ranks by interest-free days and limit instead
|
|
315
465
|
const effective = (b) => (!b.earn ? -1 : b.minSpendShort > 0 ? b.earn / 2 : b.earn);
|
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
import type { Account, Ledger } from "../../engine/types.js";
|
|
2
2
|
export interface CashbackRule {
|
|
3
3
|
categories: string[];
|
|
4
|
+
/** words looked for in a transaction's merchant and note (accents and case ignored); a merchant rule wins over a category rule */
|
|
5
|
+
merchants: string[];
|
|
4
6
|
rate: number | null;
|
|
7
|
+
/** the most this rule pays per period (the global cap still applies on top) */
|
|
8
|
+
cap: number | null;
|
|
9
|
+
/** the bank pays it only for in-store payments (the ledger can't tell, so it's a reminder) */
|
|
10
|
+
inStore: boolean;
|
|
11
|
+
label: string | null;
|
|
5
12
|
}
|
|
13
|
+
/** Days before the statement date a purchase should be made to be sure it posts in time. */
|
|
14
|
+
export declare const DEFAULT_POST_MARGIN = 3;
|
|
6
15
|
export interface CashbackTerms {
|
|
7
16
|
base: number;
|
|
8
17
|
rules: CashbackRule[];
|
|
@@ -24,6 +33,14 @@ export interface CashbackTerms {
|
|
|
24
33
|
kind: "days_after";
|
|
25
34
|
days: number;
|
|
26
35
|
};
|
|
36
|
+
/** days before the statement date that are too late to be sure a purchase lands on this statement */
|
|
37
|
+
postMargin: number;
|
|
38
|
+
/** auto: the bank pays it (to the card or an account); points: a balance the owner cashes in */
|
|
39
|
+
payout: "auto" | "points";
|
|
40
|
+
/** points: cash in only from this balance */
|
|
41
|
+
redeemMin: number | null;
|
|
42
|
+
/** points: earned points expire this many months after their statement */
|
|
43
|
+
expireMonths: number | null;
|
|
27
44
|
}
|
|
28
45
|
export interface FeeWaiver {
|
|
29
46
|
spend: number;
|
|
@@ -42,6 +59,7 @@ export interface CardTerms {
|
|
|
42
59
|
cashback: CashbackTerms | null;
|
|
43
60
|
}
|
|
44
61
|
export declare function parseCashback(v: unknown): CashbackTerms | null;
|
|
62
|
+
export declare const validMargin: (v: unknown) => boolean;
|
|
45
63
|
/** Terms from the card account's details, with what the card record (cards.yaml) adds for debit cards. */
|
|
46
64
|
export declare function termsOf(a: Account, record?: CardRecord): CardTerms;
|
|
47
65
|
export declare const CARDS_FILE = "data/cards.yaml";
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { day, int, num, str } from "../util.js";
|
|
2
|
+
/** Days before the statement date a purchase should be made to be sure it posts in time. */
|
|
3
|
+
export const DEFAULT_POST_MARGIN = 3;
|
|
2
4
|
const per = (v) => (v === "month" ? "month" : "statement");
|
|
3
5
|
function amountPer(v) {
|
|
4
6
|
if (typeof v === "number" && Number.isInteger(v) && v > 0)
|
|
@@ -15,14 +17,17 @@ export function parseCashback(v) {
|
|
|
15
17
|
return null;
|
|
16
18
|
const c = v;
|
|
17
19
|
const rules = [];
|
|
20
|
+
const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string" && x.trim() !== "").map((x) => x.trim()) : typeof v === "string" && v.trim() ? [v.trim()] : []);
|
|
18
21
|
for (const r of Array.isArray(c.rules) ? c.rules : []) {
|
|
19
22
|
if (!r || typeof r !== "object")
|
|
20
23
|
continue;
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
if (
|
|
25
|
-
|
|
24
|
+
const x = r;
|
|
25
|
+
const categories = strings(x.categories);
|
|
26
|
+
const merchants = strings(x.merchants);
|
|
27
|
+
if (!categories.length && !merchants.length)
|
|
28
|
+
continue;
|
|
29
|
+
const cap = amountPer(x.cap)?.amount ?? null;
|
|
30
|
+
rules.push({ categories, merchants, rate: num(x.rate) ?? null, cap, inStore: x.in_store === true, label: str(x.label) ?? null });
|
|
26
31
|
}
|
|
27
32
|
const paid = typeof c.paid_on === "string" ? c.paid_on : "next_statement";
|
|
28
33
|
const m = /^days_after:(\d+)$/.exec(paid);
|
|
@@ -33,8 +38,13 @@ export function parseCashback(v) {
|
|
|
33
38
|
min_spend: amountPer(c.min_spend),
|
|
34
39
|
spend_max: amountPer(c.spend_max),
|
|
35
40
|
paid_on: m ? { kind: "days_after", days: Number(m[1]) } : { kind: "next_statement" },
|
|
41
|
+
postMargin: validMargin(c.post_margin_days) ? c.post_margin_days : DEFAULT_POST_MARGIN,
|
|
42
|
+
payout: c.payout === "points" ? "points" : "auto",
|
|
43
|
+
redeemMin: c.payout === "points" ? (amountPer(c.redeem_min)?.amount ?? null) : null,
|
|
44
|
+
expireMonths: c.payout === "points" && Number.isInteger(c.expire_months) && c.expire_months > 0 ? c.expire_months : null,
|
|
36
45
|
};
|
|
37
46
|
}
|
|
47
|
+
export const validMargin = (v) => Number.isInteger(v) && v >= 0 && v <= 10;
|
|
38
48
|
/** Terms from the card account's details, with what the card record (cards.yaml) adds for debit cards. */
|
|
39
49
|
export function termsOf(a, record) {
|
|
40
50
|
const d = { ...(record?.kind !== "credit" ? pickTerms(record) : {}), ...(a.details ?? {}) };
|
|
@@ -124,6 +124,8 @@ export function amountOf(text) {
|
|
|
124
124
|
}
|
|
125
125
|
/** A cell that starts with a date. */
|
|
126
126
|
const STARTS_WITH_DATE = /^(\d{1,2}[/.-]\d{1,2}([/.-](\d{4}|\d{2}))?|\d{4}[/.-]\d{1,2}[/.-]\d{1,2})(?![\d])/;
|
|
127
|
+
/** A period line ("21/06/2025 - 20/07/2025", "01/06/2025 đến 30/06/2025"): a statement's header, never a row. */
|
|
128
|
+
const DATE_RANGE_RE = /\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\s*(?:-|–|~|to|den)\s*\d{1,2}[/.]\d{1,2}[/.]\d{2,4}/;
|
|
127
129
|
const hasWord = (text, words) => {
|
|
128
130
|
const p = plain(text);
|
|
129
131
|
return words.some((w) => {
|
|
@@ -200,7 +202,7 @@ export function parseStatement(lines, period, layout = {}, base) {
|
|
|
200
202
|
if (!date || date < lo || date > hi)
|
|
201
203
|
return;
|
|
202
204
|
const text = l.map((c) => c.text).join(" ");
|
|
203
|
-
if (hasWord(text, skips))
|
|
205
|
+
if (hasWord(text, skips) || DATE_RANGE_RE.test(plain(text)))
|
|
204
206
|
return;
|
|
205
207
|
const amounts = [];
|
|
206
208
|
const desc = [];
|
|
@@ -69,4 +69,62 @@ export declare function bestCard(l: Ledger, asOf: ISODate, ow: OpenWallet | null
|
|
|
69
69
|
} | undefined;
|
|
70
70
|
note: string;
|
|
71
71
|
}>;
|
|
72
|
+
/**
|
|
73
|
+
* OpenWallet's cashback rules for one of the owner's cards, shaped like details.cashback, for the owner to check.
|
|
74
|
+
* Nothing is written: categories are left for the owner to map (OpenWallet's intents and MCCs are hints), and only
|
|
75
|
+
* after their go does set_card_details save the terms as the owner's own facts (no OpenWallet id in the data).
|
|
76
|
+
*/
|
|
77
|
+
export declare function termsFromOpenWallet(l: Ledger, asOf: ISODate, ow: OpenWallet, account: string): Promise<{
|
|
78
|
+
account: string;
|
|
79
|
+
not_matched: NotMatched;
|
|
80
|
+
openwallet?: undefined;
|
|
81
|
+
suggestion?: undefined;
|
|
82
|
+
note?: undefined;
|
|
83
|
+
} | {
|
|
84
|
+
not_matched?: undefined;
|
|
85
|
+
account: string;
|
|
86
|
+
openwallet: {
|
|
87
|
+
id: string;
|
|
88
|
+
name: string;
|
|
89
|
+
url: any;
|
|
90
|
+
lastChecked: any;
|
|
91
|
+
note?: undefined;
|
|
92
|
+
checked?: undefined;
|
|
93
|
+
catalog?: undefined;
|
|
94
|
+
};
|
|
95
|
+
suggestion: null;
|
|
96
|
+
note: string;
|
|
97
|
+
} | {
|
|
98
|
+
not_matched?: undefined;
|
|
99
|
+
note?: undefined;
|
|
100
|
+
account: string;
|
|
101
|
+
openwallet: {
|
|
102
|
+
id: string;
|
|
103
|
+
name: string;
|
|
104
|
+
url: any;
|
|
105
|
+
lastChecked: any;
|
|
106
|
+
checked: any;
|
|
107
|
+
catalog: any;
|
|
108
|
+
note: any;
|
|
109
|
+
};
|
|
110
|
+
suggestion: {
|
|
111
|
+
cashback: {
|
|
112
|
+
base?: number | undefined;
|
|
113
|
+
rules: Record<string, unknown>[];
|
|
114
|
+
cap?: {
|
|
115
|
+
amount: any;
|
|
116
|
+
per: string;
|
|
117
|
+
} | undefined;
|
|
118
|
+
min_spend?: {
|
|
119
|
+
amount: any;
|
|
120
|
+
per: string;
|
|
121
|
+
} | undefined;
|
|
122
|
+
payout: string;
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
to_map: Record<string, unknown>[];
|
|
126
|
+
notes: string[];
|
|
127
|
+
next: string;
|
|
128
|
+
warning?: string | undefined;
|
|
129
|
+
}>;
|
|
72
130
|
export {};
|
package/dist/worker/bestcard.js
CHANGED
|
@@ -117,7 +117,7 @@ async function openWalletRows(l, asOf, ow, mine, input, date) {
|
|
|
117
117
|
export async function bestCard(l, asOf, ow, input) {
|
|
118
118
|
const date = input.date ?? asOf;
|
|
119
119
|
const amount = input.amount ?? 0;
|
|
120
|
-
let local = localBestCard(l, { category: input.category ?? "", amount, date });
|
|
120
|
+
let local = localBestCard(l, { category: input.category ?? "", amount, date, merchant: input.merchant });
|
|
121
121
|
if (input.accounts?.length) {
|
|
122
122
|
const known = new Set(local.map((r) => r.account));
|
|
123
123
|
const unknown = input.accounts.filter((a) => !known.has(a));
|
|
@@ -175,3 +175,67 @@ export async function bestCard(l, asOf, ow, input) {
|
|
|
175
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).",
|
|
176
176
|
};
|
|
177
177
|
}
|
|
178
|
+
/* ------------------------------------------------------------------ copy OpenWallet's terms (a suggestion, never stored here) */
|
|
179
|
+
const pct = (r) => (typeof r === "number" ? Math.round(r * 10000) / 100 : null);
|
|
180
|
+
/**
|
|
181
|
+
* OpenWallet's cashback rules for one of the owner's cards, shaped like details.cashback, for the owner to check.
|
|
182
|
+
* Nothing is written: categories are left for the owner to map (OpenWallet's intents and MCCs are hints), and only
|
|
183
|
+
* after their go does set_card_details save the terms as the owner's own facts (no OpenWallet id in the data).
|
|
184
|
+
*/
|
|
185
|
+
export async function termsFromOpenWallet(l, asOf, ow, account) {
|
|
186
|
+
const c = cards(l, asOf).find((x) => x.account === account);
|
|
187
|
+
if (!c)
|
|
188
|
+
throw new Error(`${account} is not an open credit card`);
|
|
189
|
+
const f = await findCard(ow, c);
|
|
190
|
+
if (!("ow" in f))
|
|
191
|
+
return { account, not_matched: f };
|
|
192
|
+
const card = await ow.call("get_card", { card_id: f.ow.id, include_quotes: false });
|
|
193
|
+
const cb = card?.cashback ?? null;
|
|
194
|
+
if (!cb || !Array.isArray(cb.rules) || !cb.rules.length)
|
|
195
|
+
return { account, openwallet: { id: f.ow.id, name: f.ow.name, url: card?.url ?? f.ow.url ?? null, lastChecked: card?.lastChecked ?? null }, suggestion: null, note: "OpenWallet has no cashback rules for this card." };
|
|
196
|
+
const rules = [];
|
|
197
|
+
const toMap = [];
|
|
198
|
+
let base = null;
|
|
199
|
+
const notes = [];
|
|
200
|
+
for (const r of cb.rules) {
|
|
201
|
+
const rate = pct(r.rate);
|
|
202
|
+
const intents = Array.isArray(r.intents) ? r.intents : [];
|
|
203
|
+
if (intents.includes("all") && !r.merchants?.length) {
|
|
204
|
+
base = rate;
|
|
205
|
+
if (r.cap?.amount)
|
|
206
|
+
notes.push(`the base rate has its own cap of ${r.cap.amount} at OpenWallet; ownledger caps it only through the card's cap`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const merchants = Array.isArray(r.merchants) ? r.merchants.map((m) => m.replace(/-/g, " ")) : [];
|
|
210
|
+
const rule = {
|
|
211
|
+
...(merchants.length ? { merchants } : { categories: [] }),
|
|
212
|
+
rate,
|
|
213
|
+
...(r.cap?.amount ? { cap: r.cap.amount } : {}),
|
|
214
|
+
...(r.scope?.channel === "offline" ? { in_store: true } : {}),
|
|
215
|
+
...(intents.length ? { label: intents.join(", ") } : {}),
|
|
216
|
+
};
|
|
217
|
+
rules.push(rule);
|
|
218
|
+
toMap.push({ rule: rules.length - 1, intents, ...(r.mcc ? { mcc: r.mcc } : {}), ...(r.note ? { note: r.note } : {}), ...(merchants.length ? { merchants_note: "matched in the transaction's merchant or note" } : { categories: "pick the owner's categories (rules tool)" }) });
|
|
219
|
+
}
|
|
220
|
+
const payout = cb.redemption === "auto_statement_credit" || cb.redemption === "auto" ? "auto" : "points";
|
|
221
|
+
if (cb.max_active_rules === 1 && rules.length > 1)
|
|
222
|
+
notes.push("only one group earns at a time (the owner picks it): keep only the chosen rule");
|
|
223
|
+
if (payout === "points")
|
|
224
|
+
notes.push(`paid as points (${cb.redemption ?? "unknown"}): set redeem_min and expire_months if the bank says (see OpenWallet's note)`);
|
|
225
|
+
const suggestion = {
|
|
226
|
+
...(base !== null ? { base } : {}),
|
|
227
|
+
rules,
|
|
228
|
+
...(cb.global_cap?.amount ? { cap: { amount: cb.global_cap.amount, per: "statement" } } : {}),
|
|
229
|
+
...(cb.min_spend?.amount ? { min_spend: { amount: cb.min_spend.amount, per: "statement" } } : {}),
|
|
230
|
+
payout,
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
account,
|
|
234
|
+
openwallet: { id: f.ow.id, name: f.ow.name, url: card?.url ?? f.ow.url ?? null, lastChecked: card?.lastChecked ?? null, checked: card?.checked ?? null, catalog: card?.catalog ?? null, note: cb.note ?? null },
|
|
235
|
+
suggestion: { cashback: suggestion },
|
|
236
|
+
to_map: toMap,
|
|
237
|
+
notes,
|
|
238
|
+
next: "Show the owner these terms with OpenWallet's date and link. Map each rule's intents to the owner's categories, fill what OpenWallet doesn't say (redeem_min, expire_months), then set_card_details (a preview) and apply only after their go.",
|
|
239
|
+
...(card?.checked === false ? { warning: "OpenWallet has not checked this card against the bank (older data): the owner should confirm each rate and cap." } : {}),
|
|
240
|
+
};
|
|
241
|
+
}
|