Spending: a Charts tab with filters

Eight charts over the same spend / income rule as the rest of broke (transfers
never count): cash flow, savings rate per month, spending by category over time,
this month so far vs last month and the 3-month average, balance over time per
account and in total (worked back from today's balances), top merchants,
spending by weekday and biggest changes vs the period before.

Filters in the URL: time range or custom dates, grouping, accounts, categories,
tags, direction, merchant search, and compare with the previous period.
Clicking a bar or point opens those transactions in Activity. Every chart has a
legend and a table view; series colors are a validated palette in a fixed order
set by all-time spending, so filters never repaint a series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
MangaValkandClaude Opus 5.5 committed 2026-11-19 20:40:35 +01:00
1 parent 2371a5674f
commit 759b0c0d62
9 files changed
+823 -1

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
// Numbers for the Charts page (app/(app)/charts). Pure: `node src/lib/charts.test.ts` runs it.
// Amounts use the app's sign: positive = money out. Rows arrive already filtered and already split into spend and
// income by the same rule as everywhere else (isSpend / isIncome in lib/data.ts), so transfers never count.
export type Group = "day" | "week" | "month";
export type Row = {
date: string; // YYYY-MM-DD
amount: number;
spend: boolean;
income: boolean;
categoryId: string | null;
merchant: string;
accountId: string | null;
};
export type Period = { key: string; label: string; from: string; to: string };
const DAY = 864e5;
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
const at = (d: string) => Date.parse(`${d}T00:00:00Z`);
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const round2 = (n: number) => Math.round(n * 100) / 100;
/** The period a day falls in: the day itself, the Monday of its week, or its month. */
export function periodKey(d: string, g: Group) {
if (g === "day") return d;
if (g === "month") return d.slice(0, 7);
const t = at(d), wd = (new Date(t).getUTCDay() + 6) % 7; // Monday = 0
return iso(t - wd * DAY);
}
/** Every period from `from` to `to` (inclusive), so empty ones still show as zero. */
export function periods(from: string, to: string, g: Group): Period[] {
const out: Period[] = [];
let key = periodKey(from, g);
const last = periodKey(to, g);
for (let guard = 0; key <= last && guard < 4000; guard++) {
if (g === "month") {
const [y, m] = key.split("-").map(Number);
const next = m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
out.push({ key, label: `${MONTHS[m - 1]}${m === 1 || !out.length ? ` '${String(y).slice(2)}` : ""}`, from: `${key}-01`, to: iso(at(`${next}-01`) - DAY) });
key = next;
} else {
const span = g === "day" ? 1 : 7, d = new Date(at(key));
out.push({ key, label: `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`, from: key, to: iso(at(key) + (span - 1) * DAY) });
key = iso(at(key) + span * DAY);
}
}
return out;
}
/** The same length of time just before [from, to]: what "compare with previous period" compares with. */
export function previousRange(from: string, to: string) {
const len = at(to) - at(from) + DAY;
return { from: iso(at(from) - len), to: iso(at(from) - DAY) };
}
export type Flow = { key: string; income: number; spend: number; net: number };
export function cashFlow(rows: Row[], ps: Period[], g: Group): Flow[] {
const by = new Map(ps.map((p) => [p.key, { key: p.key, income: 0, spend: 0, net: 0 }]));
for (const r of rows) {
const f = by.get(periodKey(r.date, g));
if (!f) continue;
if (r.spend) f.spend += r.amount;
else if (r.income) f.income -= r.amount; // money in is negative in the app's sign
}
return [...by.values()].map((f) => ({ key: f.key, income: round2(f.income), spend: round2(f.spend), net: round2(f.income - f.spend) }));
}
/** Share of income kept, per period. null where nothing came in (a rate of nothing isn't 0%). */
export const savingsRate = (flows: Flow[]) => flows.map((f) => ({ key: f.key, rate: f.income > 0 ? Math.round(((f.income - f.spend) / f.income) * 1000) / 10 : null }));
/** Spending per period per category: the `keep` categories by name, everything else summed as "other". */
export function categoriesOver(rows: Row[], ps: Period[], g: Group, keep: string[]) {
const by = new Map(ps.map((p) => [p.key, Object.fromEntries([...keep, "other"].map((k) => [k, 0])) as Record<string, number>]));
for (const r of rows) {
if (!r.spend) continue;
const b = by.get(periodKey(r.date, g));
if (!b) continue;
const k = r.categoryId && keep.includes(r.categoryId) ? r.categoryId : "other";
b[k] = round2(b[k] + r.amount);
}
return ps.map((p) => ({ key: p.key, values: by.get(p.key)! }));
}
/** Biggest first, by money spent: the stable order categories and merchants take their colors from. */
export function rankBySpend(rows: Row[], of: (r: Row) => string | null) {
const sum = new Map<string, number>();
for (const r of rows) {
const k = of(r);
if (r.spend && k) sum.set(k, (sum.get(k) ?? 0) + r.amount);
}
return [...sum.entries()].sort((a, b) => b[1] - a[1]).map(([k]) => k);
}
/** Running total of spending day by day through a month, for this month, last month and the average of the three before. */
export function monthToDate(rows: Row[], today: string) {
const month = (offset: number) => {
const [y, m] = today.slice(0, 7).split("-").map(Number);
const d = new Date(Date.UTC(y, m - 1 + offset, 1));
return iso(d.getTime()).slice(0, 7);
};
const days = (key: string) => new Date(Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)), 0)).getUTCDate();
const daily = (key: string) => {
const out = new Array(days(key)).fill(0) as number[];
for (const r of rows) if (r.spend && r.date.startsWith(key)) out[Number(r.date.slice(8, 10)) - 1] += r.amount;
let run = 0;
return out.map((v) => (run = round2(run + v)));
};
const thisKey = month(0), lastKey = month(-1);
const upTo = Number(today.slice(8, 10));
const avgOf = [month(-1), month(-2), month(-3)].map(daily);
const avg = Array.from({ length: 31 }, (_, i) => round2(avgOf.reduce((s, m) => s + (m[Math.min(i, m.length - 1)] ?? 0), 0) / avgOf.length));
return {
thisMonth: thisKey, lastMonth: lastKey,
current: daily(thisKey).slice(0, upTo),
last: daily(lastKey),
average: avg.slice(0, days(thisKey)),
};
}
export type Balance = { id: string; name: string; balance: number; owed: boolean };
/** Each account's balance at the end of every day in [from, to], worked back from today's balance: a day's balance is
* today's plus what went out since (minus what came in). A card or loan counts what's owed; the total subtracts it. */
export function balances(accounts: Balance[], rows: Row[], from: string, to: string, step: Group) {
const ds: string[] = [];
for (let t = at(from); t <= at(to); t += DAY) ds.push(iso(t));
const marks = step === "day" ? ds : ds.filter((d, i) => i === ds.length - 1 || periodKey(ds[i + 1], step) !== periodKey(d, step)); // last day of each period
const series = accounts.map((a) => {
const mine = rows.filter((r) => r.accountId === a.id).sort((x, y) => y.date.localeCompare(x.date));
let i = 0, after = 0; // sum of amounts dated after the mark
const values = [...marks].reverse().map((d) => {
while (i < mine.length && mine[i].date > d) after += mine[i++].amount;
return round2(a.owed ? a.balance - after : a.balance + after);
}).reverse();
return { id: a.id, name: a.name, owed: a.owed, values };
});
const total = marks.map((_, j) => round2(series.reduce((s, x) => s + (x.owed ? -x.values[j] : x.values[j]), 0)));
return { days: marks, series, total };
}
/** Average spent on each weekday (Monday first): total spent on those days over how many of them the range holds. */
export function byWeekday(rows: Row[], from: string, to: string) {
const sum = new Array(7).fill(0) as number[], count = new Array(7).fill(0) as number[];
for (let t = at(from); t <= at(to); t += DAY) count[(new Date(t).getUTCDay() + 6) % 7]++;
for (const r of rows) if (r.spend && r.date >= from && r.date <= to) sum[(new Date(at(r.date)).getUTCDay() + 6) % 7] += r.amount;
return sum.map((s, i) => round2(count[i] ? s / count[i] : 0));
}
/** Spending per period for each of the given merchants. */
export function merchantsOver(rows: Row[], ps: Period[], g: Group, names: string[]) {
const by = new Map(names.map((n) => [n, new Map(ps.map((p) => [p.key, 0]))]));
for (const r of rows) {
const m = r.spend ? by.get(r.merchant) : undefined;
const k = periodKey(r.date, g);
if (m?.has(k)) m.set(k, round2(m.get(k)! + r.amount));
}
return names.map((n) => ({ name: n, values: ps.map((p) => by.get(n)!.get(p.key)!) }));
}
export type Change = { id: string; now: number; before: number; delta: number };
/** What went up and down most between two periods, by category and by merchant. Spending only. */
export function biggestChanges(now: Row[], before: Row[], of: (r: Row) => string | null, n = 5) {
const sum = (rows: Row[]) => {
const m = new Map<string, number>();
for (const r of rows) {
const k = of(r);
if (r.spend && k) m.set(k, (m.get(k) ?? 0) + r.amount);
}
return m;
};
const a = sum(now), b = sum(before);
const all = [...new Set([...a.keys(), ...b.keys()])].map((id) => {
const x = round2(a.get(id) ?? 0), y = round2(b.get(id) ?? 0);
return { id, now: x, before: y, delta: round2(x - y) };
}).filter((c) => Math.abs(c.delta) >= 1);
return {
up: all.filter((c) => c.delta > 0).sort((p, q) => q.delta - p.delta).slice(0, n),
down: all.filter((c) => c.delta < 0).sort((p, q) => p.delta - q.delta).slice(0, n),
};
}
/** Totals for the header: spent, earned and kept. */
export function totals(rows: Row[]) {
let spend = 0, income = 0;
for (const r of rows) {
if (r.spend) spend += r.amount;
else if (r.income) income -= r.amount;
}
return { spend: round2(spend), income: round2(income), net: round2(income - spend) };
}