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

+1
View File
@@ -17,6 +17,7 @@ brokeless is a self-hosted copy of [broke](https://github.com/nextwork-projects/
| ING Netherlands CSV | Spending and income all came in as income | Reads the "Af Bij" column | | ING Netherlands CSV | Spending and income all came in as income | Reads the "Af Bij" column |
| ABN AMRO TXT/TAB | Imported nothing (no header row) and kept coded descriptions | Recognized, with the name pulled out of `/NAME/`, card and `Naam:` text | | ABN AMRO TXT/TAB | Imported nothing (no header row) and kept coded descriptions | Recognized, with the name pulled out of `/NAME/`, card and `Naam:` text |
| Updates | Pulls from GitHub on every start | Never by itself. You review upstream commits and merge the ones you want. | | Updates | Pulls from GitHub on every start | Never by itself. You review upstream commits and merge the ones you want. |
| Charts | Month bars and a category breakdown | A Charts tab under Spending: cash flow, savings rate, categories over time, this month vs last, balance over time, top merchants, spending by weekday and biggest changes, with filters and compare |
| Calls out | Update check on GitHub, exchange rates from frankfurter.dev | Both off (`BROKE_OFFLINE=1`) | | Calls out | Update check on GitHub, exchange rates from frankfurter.dev | Both off (`BROKE_OFFLINE=1`) |
| Next.js and React | 15.5.4 and 19.1.0 (critical advisory) | 15.5.29 and 19.1.10 | | Next.js and React | 15.5.4 and 19.1.0 (critical advisory) | 15.5.29 and 19.1.10 |
+123
View File
@@ -0,0 +1,123 @@
import { ChartFilters } from "@/components/charts/ChartFilters";
import { ChartsView, type ChartsData } from "@/components/charts/ChartsView";
import { EmptyBank } from "@/components/EmptyBank";
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Row } from "@/lib/charts";
import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, today, transactionsSince } from "@/lib/data";
import { ymd } from "@/lib/format";
// Charts: money over time with filters. Every number comes from lib/charts.ts over the same spend / income rule as
// the rest of broke (isSpend / isIncome), so transfers between own accounts never count. Home-currency rows only.
type Search = { range?: string; from?: string; to?: string; g?: string; acct?: string; cat?: string; tag?: string; q?: string; dir?: string; cmp?: string };
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const ids = (s?: string) => (s ?? "").split(",").filter((x) => UUID.test(x));
const MS = 864e5;
export default async function Charts({ searchParams }: { searchParams: Promise<Search> }) {
const sp = await searchParams;
const { supabase, user } = await getUser();
const now = ymd(await today());
const [txns, cats, tags, { data: accts }] = await Promise.all([
transactionsSince("1900-01-01"),
categories(),
allTags(),
supabase.from("accounts").select("id, name, custom_name, type, current_balance, balance, manual, included").eq("user_id", user!.id).order("name"),
]);
if (!txns.length) return <EmptyBank />;
// Rows in the home currency, split into spend and income the way every other page does.
const home = (user?.user_metadata?.profile?.currency as string | undefined) ?? null;
const mine = (c: string | null) => !c || c === home;
const otherCurrency = txns.filter((t) => !mine(t.currency)).length;
const all: (Row & { tags: string[]; text: string })[] = txns.filter((t) => mine(t.currency)).map((t) => ({
date: t.date, amount: Number(t.amount), spend: isSpend(t), income: isIncome(t), categoryId: t.category_id,
merchant: displayName(t), accountId: t.account?.id ?? null, tags: t.tags ?? [],
text: `${t.name} ${t.merchant_name ?? ""} ${t.custom_name ?? ""}`.toLowerCase(),
}));
const first = all.reduce((m, r) => (r.date < m ? r.date : m), now);
// Time range: a preset, or custom dates (either end open).
const range = sp.range ?? "12m";
const monthsBack = (n: number) => { const d = new Date(`${now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return ymd(d); };
const preset = range === "1m" ? monthsBack(1) : range === "3m" ? monthsBack(3) : range === "6m" ? monthsBack(6) : range === "ytd" ? `${now.slice(0, 4)}-01-01` : range === "all" ? first : monthsBack(12);
const from = DAY.test(sp.from ?? "") ? sp.from! : DAY.test(sp.to ?? "") ? first : preset;
const to = DAY.test(sp.to ?? "") ? sp.to! : now;
const days = (Date.parse(to) - Date.parse(from)) / MS + 1;
const group: Group = sp.g === "day" || sp.g === "week" || sp.g === "month" ? sp.g : days <= 31 ? "day" : days <= 120 ? "week" : "month";
// Filters. Balances follow only the account filter: a balance is the whole account, not a slice of it.
const acct = ids(sp.acct), cat = ids(sp.cat), tag = (sp.tag ?? "").split(",").filter((t) => t && t.length <= 100);
const q = (sp.q ?? "").trim().toLowerCase().slice(0, 100);
const dir = sp.dir === "in" || sp.dir === "out" ? sp.dir : null;
const filtered = all
.filter((r) => !acct.length || (r.accountId && acct.includes(r.accountId)))
.filter((r) => !cat.length || (r.categoryId && cat.includes(r.categoryId)))
.filter((r) => !tag.length || tag.some((t) => r.tags.includes(t)))
.filter((r) => !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q))
.map((r) => (dir === "out" ? { ...r, income: false } : dir === "in" ? { ...r, spend: false } : r));
const within = (a: string, b: string) => filtered.filter((r) => r.date >= a && r.date <= b);
const ps = periods(from, to, group);
const rows = within(from, to);
const compare = sp.cmp === "1";
const prev = previousRange(from, to);
const before = within(prev.from, prev.to);
// The period before, lined up period by period with this one (same length, same grouping).
const psBefore = periods(prev.from, prev.to, group).slice(-ps.length);
const flowBefore = compare ? cashFlow(before, psBefore, group) : null;
const pad = <T,>(xs: T[] | null) => (xs ? [...Array(Math.max(0, ps.length - xs.length)).fill(null), ...xs] : null);
// Stable colors: slots follow all-time spending, so filtering never repaints a category, merchant or account.
const catRank = rankBySpend(all, (r) => r.categoryId);
const catSlot = new Map(catRank.slice(0, 7).map((id, i) => [id, i + 1]));
const label = new Map(cats.map((c) => [c.id, c.label]));
const keep = rankBySpend(rows, (r) => r.categoryId).filter((id) => catSlot.has(id)).slice(0, 7);
const merchRank = rankBySpend(all, (r) => r.merchant);
const topMerch = rankBySpend(rows, (r) => r.merchant).slice(0, 5);
const merchSlot = (m: string) => { const i = merchRank.indexOf(m); return i >= 0 && i < 8 ? i + 1 : 0; };
const accounts = (accts ?? []).filter((a) => a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id)));
const bal = balances(
accounts.map((a) => ({ id: a.id, name: accountName(a), balance: Number((a.manual ? a.balance : a.current_balance) ?? 0), owed: a.type === "credit" || a.type === "loan" })),
all.filter((r) => r.date > from), from, to, group,
);
const flow = cashFlow(rows, ps, group);
const psMonth = periods(from, to, "month");
const ch = biggestChanges(rows, before, (r) => r.categoryId);
const data: ChartsData = {
periods: ps,
compare,
totals: totals(rows),
totalsBefore: compare ? totals(before) : null,
flow,
flowBefore: flowBefore ? (pad(flowBefore) as ChartsData["flow"]).map((f, i) => f ?? { key: ps[i].key, income: 0, spend: 0, net: 0 }) : null,
// Savings rate is per month whatever the grouping: most weeks have no pay in them, and a rate of nothing isn't 0%.
rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month")).map((r) => r.rate) },
rateBefore: compare ? (() => { const pm = periods(prev.from, prev.to, "month").slice(-psMonth.length); const v = savingsRate(cashFlow(before, pm, "month")).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null,
cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep).map((c) => c.values) },
mtd: monthToDate(filtered, now),
balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) },
weekday: byWeekday(rows, from, to),
weekdayBefore: compare ? byWeekday(before, prev.from, prev.to) : null,
merchants: merchantsOver(rows, ps, group, topMerch).map((m) => ({ ...m, slot: merchSlot(m.name) })),
changes: {
categories: { up: ch.up.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })), down: ch.down.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })) },
merchants: biggestChanges(rows, before, (r) => r.merchant),
},
// Activity takes one account, one tag and a search: pass them on when exactly one is picked.
otherCurrency,
link: Object.fromEntries(Object.entries({ account: acct.length === 1 ? acct[0] : "", tag: tag.length === 1 ? tag[0] : "", q: sp.q?.trim() ?? "" }).filter(([, v]) => v)),
};
return (
<div className="space-y-4">
<ChartFilters
accounts={(accts ?? []).map((a) => ({ value: a.id, label: accountName(a) }))}
categories={cats.filter((c) => c.kind !== "transfer").map((c) => ({ value: c.id, label: c.label }))}
tags={tags.map((t) => ({ value: t, label: t }))}
/>
<ChartsView d={data} />
</div>
);
}
+6
View File
@@ -26,6 +26,10 @@
--shadow-card: 0 1px 2px #0000000a, 0 6px 20px -8px #00000014; --shadow-card: 0 1px 2px #0000000a, 0 6px 20px -8px #00000014;
--shadow-pop: 0 1px 3px #0000000f, 0 18px 44px -14px #00000038; --shadow-pop: 0 1px 3px #0000000f, 0 18px 44px -14px #00000038;
--backdrop: #0000004d; /* behind a modal */ --backdrop: #0000004d; /* behind a modal */
/* Charts page: categorical series, in this fixed order (validated for colour blindness on #fff; three sit below 3:1,
so every chart has a legend, tooltips and a table view). "other" is the fold for everything past slot 7. */
--series-1: #2a78d6; --series-2: #eb6834; --series-3: #1baf7a; --series-4: #eda100;
--series-5: #e87ba4; --series-6: #008300; --series-7: #6250d6; --series-8: #e34948; --series-other: #a3a3a0;
color-scheme: light; color-scheme: light;
} }
@@ -37,6 +41,7 @@
/* Dark lifts cards with a top highlight, not a shadow. */ /* Dark lifts cards with a top highlight, not a shadow. */
--shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3; --shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3;
--good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark; --good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark;
--series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500; --series-5: #d55181; --series-6: #0ca30c; --series-7: #9085e9; --series-8: #e66767; --series-other: #6b6b72;
/* Tailwind's pale status tints, dimmed for dark surfaces. */ /* Tailwind's pale status tints, dimmed for dark surfaces. */
--color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24; --color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24;
} }
@@ -47,6 +52,7 @@
/* Dark lifts cards with a top highlight, not a shadow. */ /* Dark lifts cards with a top highlight, not a shadow. */
--shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3; --shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3;
--good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark; --good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark;
--series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500; --series-5: #d55181; --series-6: #0ca30c; --series-7: #9085e9; --series-8: #e66767; --series-other: #6b6b72;
--color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24; --color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24;
} }
+1 -1
View File
@@ -19,7 +19,7 @@ const LINKS: { href: string; label: string; icon: Icon }[] = [
{ href: "/accounts", label: "Accounts", icon: Landmark }, { href: "/accounts", label: "Accounts", icon: Landmark },
{ href: "/more", label: "More", icon: Ellipsis }, { href: "/more", label: "More", icon: Ellipsis },
]; ];
const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/budgets", label: "Budgets" }, { href: "/recurring", label: "Recurring" }]; const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/charts", label: "Charts" }, { href: "/budgets", label: "Budgets" }, { href: "/recurring", label: "Recurring" }];
const PLAN = [{ href: "/plan", label: "Money plan" }, { href: "/optimize", label: "Optimize" }, { href: "/bonuses", label: "Bonuses" }, { href: "/cards", label: "Cards" }]; const PLAN = [{ href: "/plan", label: "Money plan" }, { href: "/optimize", label: "Optimize" }, { href: "/bonuses", label: "Bonuses" }, { href: "/cards", label: "Cards" }];
const under = (path: string, href: string) => (href === "/" ? path === "/" : path === href || path.startsWith(href + "/")); const under = (path: string, href: string) => (href === "/" ? path === "/" : path === href || path.startsWith(href + "/"));
const tabsOf = (path: string) => [SPENDING, PLAN].find((g) => g.some((t) => under(path, t.href))); const tabsOf = (path: string) => [SPENDING, PLAN].find((g) => g.some((t) => under(path, t.href)));
+99
View File
@@ -0,0 +1,99 @@
"use client";
import { Search } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { Dropdown } from "@/components/Dropdown";
// The Charts page's filters, in one row above the charts. Each one lives in the URL, so back, refresh and links keep it.
// Lists (accounts, categories, tags) are comma-separated ids; empty means all.
type Opt = { value: string; label: string };
const RANGES = [
{ value: "1m", label: "This month" }, { value: "3m", label: "Last 3 months" }, { value: "6m", label: "Last 6 months" },
{ value: "12m", label: "Last 12 months" }, { value: "ytd", label: "This year" }, { value: "all", label: "Everything" },
];
const GROUPS = [{ value: "", label: "Group: automatic" }, { value: "day", label: "By day" }, { value: "week", label: "By week" }, { value: "month", label: "By month" }];
const DIRS = [{ value: "", label: "Money in and out" }, { value: "out", label: "Only money out" }, { value: "in", label: "Only money in" }];
function Multi({ label, all, options, value, onChange }: { label: string; all: string; options: Opt[]; value: string[]; onChange: (v: string[]) => void }) {
const [open, setOpen] = useState(false);
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const close = (e: PointerEvent) => { if (!box.current?.contains(e.target as Node)) setOpen(false); };
document.addEventListener("pointerdown", close);
return () => document.removeEventListener("pointerdown", close);
}, [open]);
const picked = options.filter((o) => value.includes(o.value));
const text = !picked.length ? all : picked.length === 1 ? picked[0].label : `${label}: ${picked.length}`;
return (
<div ref={box} className="relative">
<button type="button" aria-haspopup="listbox" aria-expanded={open} aria-label={`${label}: ${text}`} onClick={() => setOpen(!open)}
className={`btn !py-1.5 text-sm ${picked.length ? "!bg-ink !text-on-ink" : ""}`}>{text}</button>
{open && (
<div role="listbox" aria-multiselectable className="absolute z-20 mt-1 w-64 max-h-72 overflow-auto card p-2 shadow-[var(--shadow-pop)]">
<button type="button" className="w-full text-left text-xs text-muted px-2 py-1 hover:text-ink" onClick={() => onChange([])}>{all}</button>
{options.map((o) => (
<label key={o.value} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-[var(--hover)] text-sm cursor-pointer">
<input type="checkbox" checked={value.includes(o.value)} onChange={(e) => onChange(e.target.checked ? [...value, o.value] : value.filter((v) => v !== o.value))} />
<span className="truncate">{o.label}</span>
</label>
))}
</div>
)}
</div>
);
}
export function ChartFilters({ accounts, categories, tags }: { accounts: Opt[]; categories: Opt[]; tags: Opt[] }) {
const router = useRouter(), path = usePathname(), params = useSearchParams();
const set = (patch: Record<string, string | null>) => {
const next = new URLSearchParams(params);
for (const [k, v] of Object.entries(patch)) {
if (v) next.set(k, v);
else next.delete(k);
}
router.replace(`${path}?${next}`, { scroll: false });
};
const list = (k: string) => (params.get(k) ?? "").split(",").filter(Boolean);
const [q, setQ] = useState(params.get("q") ?? "");
useEffect(() => {
if (q === (params.get("q") ?? "")) return;
const t = setTimeout(() => set({ q: q.trim() || null }), 400);
return () => clearTimeout(t);
});
const custom = !!(params.get("from") || params.get("to"));
const any = ["acct", "cat", "tag", "q", "dir", "from", "to", "g"].some((k) => params.get(k));
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<Dropdown label="Time range" value={custom ? "custom" : params.get("range") ?? "12m"}
options={[...RANGES, ...(custom ? [{ value: "custom", label: "Custom dates" }] : [])]}
onChange={(v) => set({ range: v === "12m" ? null : v, from: null, to: null })} />
<label className="flex items-center gap-1 text-sm text-muted">
<input type="date" aria-label="From" className="select !py-1 !w-auto" value={params.get("from") ?? ""} onChange={(e) => set({ from: e.target.value || null, range: null })} />
–
<input type="date" aria-label="To" className="select !py-1 !w-auto" value={params.get("to") ?? ""} onChange={(e) => set({ to: e.target.value || null, range: null })} />
</label>
<Dropdown label="Group" value={params.get("g") ?? ""} options={GROUPS} onChange={(v) => set({ g: v || null })} />
<label className="flex items-center gap-2 text-sm ml-auto cursor-pointer">
<input type="checkbox" role="switch" checked={params.get("cmp") === "1"} onChange={(e) => set({ cmp: e.target.checked ? "1" : null })} />
Compare with previous period
</label>
</div>
<div className="flex flex-wrap items-center gap-2">
<Multi label="Accounts" all="All accounts" options={accounts} value={list("acct")} onChange={(v) => set({ acct: v.join(",") || null })} />
<Multi label="Categories" all="All categories" options={categories} value={list("cat")} onChange={(v) => set({ cat: v.join(",") || null })} />
{!!tags.length && <Multi label="Tags" all="All tags" options={tags} value={list("tag")} onChange={(v) => set({ tag: v.join(",") || null })} />}
<Dropdown label="Direction" value={params.get("dir") ?? ""} options={DIRS} onChange={(v) => set({ dir: v || null })} />
<label className="flex items-center gap-2 select !py-1.5 !w-56">
<Search size={14} className="text-muted shrink-0" aria-hidden />
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Merchant or name" aria-label="Search merchant or name" className="bg-transparent outline-none w-full text-sm" />
</label>
{any && <button type="button" className="text-sm text-muted hover:text-ink underline underline-offset-2" onClick={() => { setQ(""); router.replace(`${path}${params.get("cmp") ? "?cmp=1" : ""}`, { scroll: false }); }}>Clear filters</button>}
</div>
</div>
);
}
+185
View File
@@ -0,0 +1,185 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, type ReactNode } from "react";
// The Charts page's pieces, drawn in SVG to match broke's own charts. One y-axis per chart, thin marks, recessive grid,
// a legend for 2+ series, a tooltip on hover, and a table view for every chart (some light colors sit below 3:1).
export type Series = { name: string; color: string; values: (number | null)[]; faint?: (number | null)[]; width?: number; dashed?: boolean };
type Fmt = (n: number) => string;
function useWidth() {
const ref = useRef<HTMLDivElement>(null);
const [w, setW] = useState(640);
useEffect(() => {
const el = ref.current;
if (!el) return;
const ro = new ResizeObserver(([e]) => setW(Math.max(280, Math.round(e.contentRect.width))));
ro.observe(el);
return () => ro.disconnect();
}, []);
return { ref, w };
}
/** Round-number ticks from 0 (or below, for negatives) to the top. */
function ticks(min: number, max: number) {
const span = Math.max(1, max - Math.min(0, min));
const raw = span / 4, mag = 10 ** Math.floor(Math.log10(raw)), step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw)!;
const lo = Math.floor(Math.min(0, min) / step) * step, hi = Math.ceil(max / step) * step || step;
const out: number[] = [];
for (let v = lo; v <= hi + 1e-9; v += step) out.push(Math.round(v * 100) / 100);
return out;
}
export function Card({ title, note, legend, table, children }: { title: string; note?: string; legend?: { name: string; color: string; dashed?: boolean }[]; table?: { head: string[]; rows: (string | number)[][] }; children: ReactNode }) {
const [asTable, setAsTable] = useState(false);
return (
<section className="card p-5 space-y-3 min-w-0">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="card-title">{title}</div>
{note && <p className="text-xs text-muted mt-0.5">{note}</p>}
</div>
{table && <button type="button" className="text-xs text-muted hover:text-ink underline underline-offset-2" onClick={() => setAsTable(!asTable)}>{asTable ? "Show chart" : "Show table"}</button>}
</div>
{legend && legend.length > 1 && !asTable && (
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
{legend.map((l) => (
<span key={l.name} className="flex items-center gap-1.5">
<span className="w-3 h-0.5 rounded" style={l.dashed ? { borderTop: `2px dashed ${l.color}`, height: 0 } : { background: l.color, height: 3 }} />{l.name}
</span>
))}
</div>
)}
{asTable && table ? (
<div className="overflow-x-auto">
<table className="w-full text-xs tabular">
<thead><tr>{table.head.map((h, i) => <th key={i} className={`py-1.5 pr-3 font-medium text-muted ${i ? "text-right" : "text-left"}`}>{h}</th>)}</tr></thead>
<tbody>{table.rows.map((r, i) => <tr key={i} className="border-t border-line">{r.map((c, j) => <td key={j} className={`py-1.5 pr-3 ${j ? "text-right" : ""}`}>{c}</td>)}</tr>)}</tbody>
</table>
</div>
) : children}
</section>
);
}
function Tip({ x, w, children }: { x: number; w: number; children: ReactNode }) {
const left = Math.min(Math.max(x, 90), w - 90);
return <div className="absolute top-0 -translate-x-1/2 bg-ink text-on-ink text-[11px] rounded-lg px-2.5 py-1.5 shadow-lg pointer-events-none z-10 whitespace-nowrap space-y-0.5" style={{ left }}>{children}</div>;
}
const H = 200, PAD = { l: 52, r: 8, t: 12, b: 24 };
/** Bars per period: side by side, or stacked. `faint` draws the previous period as a pale outline behind each bar. */
export function Bars({ labels, series, stacked = false, fmt, hrefs }: { labels: string[]; series: Series[]; stacked?: boolean; fmt: Fmt; hrefs?: (i: number, s?: number) => string | null }) {
const { ref, w } = useWidth();
const router = useRouter();
const [hover, setHover] = useState<number | null>(null);
const n = labels.length;
const vals = (i: number) => series.map((s) => s.values[i] ?? 0);
const top = Math.max(1, ...labels.map((_, i) => (stacked ? vals(i).reduce((a, b) => a + Math.max(0, b), 0) : Math.max(...vals(i), ...series.map((s) => s.faint?.[i] ?? 0)))));
const low = Math.min(0, ...labels.flatMap((_, i) => vals(i)));
const tk = ticks(low, top), y0 = tk[0], y1 = tk[tk.length - 1];
const y = (v: number) => PAD.t + (H - PAD.t - PAD.b) * (1 - (v - y0) / (y1 - y0 || 1));
const band = (w - PAD.l - PAD.r) / Math.max(1, n), inner = Math.min(band * 0.72, 56);
const per = stacked ? inner : (inner - 2 * (series.length - 1)) / series.length; // 2px gap between bars in a group
const every = Math.ceil(n / Math.max(1, Math.floor((w - PAD.l) / 54))); // label every k-th period so they don't collide
return (
<div ref={ref} className="relative" onPointerLeave={() => setHover(null)}>
{hover !== null && (
<Tip x={PAD.l + band * (hover + 0.5)} w={w}>
<div className="font-medium">{labels[hover]}</div>
{series.map((s) => <div key={s.name} className="flex items-center gap-1.5"><span className="size-2 rounded-sm" style={{ background: s.color }} />{s.name}: {fmt(s.values[hover] ?? 0)}{s.faint ? <span className="opacity-70"> (before: {fmt(s.faint[hover] ?? 0)})</span> : null}</div>)}
</Tip>
)}
<svg width={w} height={H} role="img" aria-label={`${series.map((s) => s.name).join(", ")} per period`}>
{tk.map((t) => (
<g key={t}>
<line x1={PAD.l} x2={w - PAD.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeWidth={t === 0 ? 1.5 : 1} />
<text x={PAD.l - 6} y={y(t) + 3} textAnchor="end" fontSize="10" fill="var(--muted)">{fmt(t)}</text>
</g>
))}
{labels.map((l, i) => {
const x0 = PAD.l + band * i + (band - inner) / 2;
let stack = 0;
const dim = hover !== null && hover !== i;
const go = (s?: number) => { const h = hrefs?.(i, s); if (h) router.push(h); };
return (
<g key={i} opacity={dim ? 0.45 : 1} style={{ cursor: hrefs ? "pointer" : undefined }} onPointerEnter={() => setHover(i)} onClick={() => go()}>
<rect x={PAD.l + band * i} y={PAD.t} width={band} height={H - PAD.t - PAD.b} fill="transparent" />
{series.map((s, j) => {
const v = s.values[i] ?? 0;
if (stacked) {
if (v <= 0) return null;
const yTop = y(stack + v), yBot = y(stack);
stack += v;
return <rect key={j} x={x0} y={yTop} width={inner} height={Math.max(0, yBot - yTop - 2)} rx={2} fill={s.color} onClick={(e) => { e.stopPropagation(); go(j); }} />;
}
const bx = x0 + j * (per + 2);
const f = s.faint?.[i];
return (
<g key={j}>
{f ? <rect x={bx} y={y(Math.max(0, f))} width={per} height={Math.abs(y(f) - y(0))} rx={4} fill="none" stroke={s.color} strokeOpacity={0.45} strokeDasharray="3 2" /> : null}
<rect x={bx} y={y(Math.max(0, v))} width={per} height={Math.max(v ? 2 : 0, Math.abs(y(v) - y(0)))} rx={4} fill={s.color} onClick={(e) => { e.stopPropagation(); go(j); }} />
</g>
);
})}
{i % every === 0 && <text x={PAD.l + band * (i + 0.5)} y={H - 6} textAnchor="middle" fontSize="10" fill="var(--muted)">{l}</text>}
</g>
);
})}
</svg>
</div>
);
}
/** Lines over the same periods, with a crosshair and one tooltip for every series at that point. */
export function Lines({ labels, series, fmt, hrefs, zero = true }: { labels: string[]; series: Series[]; fmt: Fmt; hrefs?: (i: number) => string | null; zero?: boolean }) {
const { ref, w } = useWidth();
const router = useRouter();
const [hover, setHover] = useState<number | null>(null);
const n = labels.length;
const all = series.flatMap((s) => [...s.values, ...(s.faint ?? [])]).filter((v): v is number => v !== null);
const hi = Math.max(zero ? 1 : -Infinity, ...all), lo = Math.min(zero ? 0 : Infinity, ...all);
const tk = zero ? ticks(lo, hi) : ticks(lo - (hi - lo) * 0.1, hi).filter((t) => t >= lo - (hi - lo) * 0.25);
const y0 = tk[0], y1 = tk[tk.length - 1];
const x = (i: number) => PAD.l + (n <= 1 ? 0 : ((w - PAD.l - PAD.r) * i) / (n - 1));
const y = (v: number) => PAD.t + (H - PAD.t - PAD.b) * (1 - (v - y0) / (y1 - y0 || 1));
const path = (vs: (number | null)[]) => vs.map((v, i) => (v === null ? "" : `${i && vs[i - 1] !== null ? "L" : "M"}${x(i).toFixed(1)},${y(v).toFixed(1)}`)).join("");
const every = Math.ceil(n / Math.max(1, Math.floor((w - PAD.l) / 54)));
const pick = (cx: number) => Math.max(0, Math.min(n - 1, Math.round(((cx - PAD.l) / Math.max(1, w - PAD.l - PAD.r)) * (n - 1))));
return (
<div ref={ref} className="relative" onPointerLeave={() => setHover(null)}>
{hover !== null && (
<Tip x={x(hover)} w={w}>
<div className="font-medium">{labels[hover]}</div>
{series.filter((s) => s.values[hover] !== null).map((s) => <div key={s.name} className="flex items-center gap-1.5"><span className="size-2 rounded-full" style={{ background: s.color }} />{s.name}: {fmt(s.values[hover]!)}{s.faint?.[hover] != null ? <span className="opacity-70"> (before: {fmt(s.faint[hover]!)})</span> : null}</div>)}
</Tip>
)}
<svg width={w} height={H} role="img" aria-label={`${series.map((s) => s.name).join(", ")} over time`}
style={{ cursor: hrefs ? "pointer" : undefined }}
onPointerMove={(e) => setHover(pick(e.clientX - e.currentTarget.getBoundingClientRect().left))}
onClick={() => { if (hover !== null) { const h = hrefs?.(hover); if (h) router.push(h); } }}>
{tk.map((t) => (
<g key={t}>
<line x1={PAD.l} x2={w - PAD.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeWidth={t === 0 && zero ? 1.5 : 1} />
<text x={PAD.l - 6} y={y(t) + 3} textAnchor="end" fontSize="10" fill="var(--muted)">{fmt(t)}</text>
</g>
))}
{labels.map((l, i) => (i % every === 0 ? <text key={i} x={x(i)} y={H - 6} textAnchor={i === 0 ? "start" : "middle"} fontSize="10" fill="var(--muted)">{l}</text> : null))}
{series.map((s) => s.faint && <path key={`f${s.name}`} d={path(s.faint)} fill="none" stroke={s.color} strokeOpacity={0.35} strokeWidth={1.5} strokeDasharray="4 3" />)}
{series.map((s) => <path key={s.name} d={path(s.values)} fill="none" stroke={s.color} strokeWidth={s.width ?? 2} strokeLinejoin="round" strokeLinecap="round" strokeDasharray={s.dashed ? "5 4" : undefined} />)}
{/* A point with no neighbor draws no line: give it a dot so it doesn't vanish. */}
{series.map((s) => s.values.map((v, i) => v !== null && (s.values[i - 1] ?? null) === null && (s.values[i + 1] ?? null) === null
? <circle key={`${s.name}${i}`} cx={x(i)} cy={y(v)} r={4} fill={s.color} stroke="var(--surface)" strokeWidth={2} /> : null))}
{hover !== null && (
<g pointerEvents="none">
<line x1={x(hover)} x2={x(hover)} y1={PAD.t} y2={H - PAD.b} stroke="var(--muted)" strokeOpacity={0.5} />
{series.map((s) => s.values[hover] !== null && <circle key={s.name} cx={x(hover)} cy={y(s.values[hover]!)} r={4} fill={s.color} stroke="var(--surface)" strokeWidth={2} />)}
</g>
)}
</svg>
</div>
);
}
+157
View File
@@ -0,0 +1,157 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { useMoney } from "@/components/Money";
import { Bars, Card, Lines, type Series } from "@/components/charts/ChartKit";
import type { Change, Flow, Period } from "@/lib/charts";
// Everything here is worked out on the server (app/(app)/charts/page.tsx, lib/charts.ts). This only draws it.
// Colors: income and spending keep broke's own (--good, --chart); categories, merchants and accounts take the series
// slots in a fixed order set by all-time spending, so a filter never repaints one.
export type ChartsData = {
periods: Period[];
compare: boolean;
totals: { spend: number; income: number; net: number };
totalsBefore: { spend: number; income: number; net: number } | null;
flow: Flow[];
flowBefore: Flow[] | null;
rate: { periods: Period[]; values: (number | null)[] };
rateBefore: (number | null)[] | null;
cats: { order: { id: string; label: string; slot: number }[]; values: Record<string, number>[] };
mtd: { thisMonth: string; lastMonth: string; current: number[]; last: number[]; average: number[] };
balance: { days: string[]; series: { id: string; name: string; owed: boolean; slot: number; values: number[] }[]; total: number[] };
weekday: number[];
weekdayBefore: number[] | null;
merchants: { name: string; slot: number; values: number[] }[];
changes: { categories: { up: (Change & { label: string })[]; down: (Change & { label: string })[] }; merchants: { up: Change[]; down: Change[] } } | null;
otherCurrency: number; // transactions in another currency, left out of every chart
link: Record<string, string>; // filters Activity understands: account, tag, q (only when exactly one is picked)
};
const slot = (n: number) => (n >= 1 && n <= 8 ? `var(--series-${n})` : "var(--series-other)");
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const monthName = (k: string) => new Date(`${k}-15T12:00:00Z`).toLocaleDateString("en-US", { month: "long", timeZone: "UTC" });
const day = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
export function ChartsView({ d }: { d: ChartsData }) {
const { money0 } = useMoney();
const pct = (n: number) => `${Math.round(n)}%`;
const labels = d.periods.map((p) => p.label);
const activity = (extra: Record<string, string | undefined>) => {
const q = new URLSearchParams(Object.entries({ ...d.link, ...extra }).filter((e): e is [string, string] => !!e[1]));
return `/transactions?${q}`;
};
const inPeriod = (i: number, extra: Record<string, string | undefined> = {}) => activity({ from: d.periods[i].from, to: d.periods[i].to, ...extra });
const tableOf = (head: string[], cols: (string | number)[][]) => ({ head, rows: labels.map((l, i) => [l, ...cols.map((c) => c[i])]) });
const change = (now: number, before?: number) => {
if (before === undefined) return null;
if (!before) return null;
const p = ((now - before) / Math.abs(before)) * 100;
return <span className="text-xs text-muted"> {p >= 0 ? "+" : ""}{Math.round(p)}% vs before</span>;
};
const [hidden, setHidden] = useState<Set<string>>(new Set());
const toggle = (id: string) => setHidden((h) => { const n = new Set(h); if (n.has(id)) n.delete(id); else n.add(id); return n; });
const flowSeries: Series[] = [
{ name: "Money in", color: "var(--good)", values: d.flow.map((f) => f.income), faint: d.flowBefore?.map((f) => f.income) },
{ name: "Money out", color: "var(--chart)", values: d.flow.map((f) => f.spend), faint: d.flowBefore?.map((f) => f.spend) },
];
// Stacked from the biggest up; each block knows its category, so a click opens that category (Other: all of them).
const catDefs = [...d.cats.order.map((c) => ({ id: c.id as string | undefined, name: c.label, color: slot(c.slot), values: d.cats.values.map((v) => v[c.id] ?? 0) })), { id: undefined, name: "Other", color: slot(0), values: d.cats.values.map((v) => v.other ?? 0) }].filter((s) => s.values.some((v) => v));
const catSeries: Series[] = catDefs;
const mtdDays = d.mtd.average.map((_, i) => String(i + 1));
const bal = d.balance;
return (
<div className="space-y-4">
{d.otherCurrency > 0 && <p className="text-xs text-muted px-1">{d.otherCurrency} transactions in another currency are left out of these charts.</p>}
<div className="grid grid-cols-3 gap-3">
{([["Money in", d.totals.income, d.totalsBefore?.income], ["Money out", d.totals.spend, d.totalsBefore?.spend], ["Kept", d.totals.net, d.totalsBefore?.net]] as const).map(([k, v, b]) => (
<div key={k} className="card px-5 py-4">
<div className="text-xs text-muted">{k}</div>
<div className={`text-xl font-semibold tabular ${k === "Kept" && v < 0 ? "text-bad" : ""}`}>{money0(v)}</div>
{d.compare && change(v, b)}
</div>
))}
</div>
<div className="grid gap-4 @4xl:grid-cols-2">
<Card title="Cash flow" note={d.compare ? "Dashed outlines: the period before." : "Money in and out per period. Click a bar to see the transactions."} legend={flowSeries}
table={tableOf(["Period", "In", "Out", "Kept"], [d.flow.map((f) => money0(f.income)), d.flow.map((f) => money0(f.spend)), d.flow.map((f) => money0(f.net))])}>
<Bars labels={labels} series={flowSeries} fmt={money0} hrefs={(i) => inPeriod(i)} />
</Card>
<Card title="Savings rate" note="Share of what came in that you kept, per month. Empty where nothing came in." legend={d.compare ? [{ name: "This period", color: "var(--good)" }, { name: "Before", color: "var(--good)", dashed: true }] : undefined}
table={{ head: ["Month", "Kept", ...(d.rateBefore ? ["Before"] : [])], rows: d.rate.periods.map((p, i) => [p.label, d.rate.values[i] === null ? "–" : pct(d.rate.values[i]!), ...(d.rateBefore ? [d.rateBefore[i] === null ? "–" : pct(d.rateBefore[i]!)] : [])]) }}>
<Lines labels={d.rate.periods.map((p) => p.label)} series={[{ name: "Kept", color: "var(--good)", values: d.rate.values, faint: d.rateBefore ?? undefined }]} fmt={pct}
hrefs={(i) => activity({ from: d.rate.periods[i].from, to: d.rate.periods[i].to })} />
</Card>
<Card title="Spending by category" note="Your biggest categories; the rest is Other. Click a block to see it." legend={catSeries}
table={tableOf(["Period", ...catSeries.map((s) => s.name)], catSeries.map((s) => s.values.map((v) => money0(v ?? 0))))}>
<Bars labels={labels} series={catSeries} stacked fmt={money0}
hrefs={(i, s) => inPeriod(i, s !== undefined ? { category: catDefs[s]?.id } : {})} />
</Card>
<Card title="This month so far" note={`Spending added up day by day: ${monthName(d.mtd.thisMonth)} against ${monthName(d.mtd.lastMonth)} and the average of the 3 months before.`}
legend={[{ name: "This month", color: "var(--chart)" }, { name: "Last month", color: "var(--muted)", dashed: true }, { name: "3-month average", color: "var(--series-other)" }]}
table={{ head: ["Day", "This month", "Last month", "Average"], rows: mtdDays.map((l, i) => [l, d.mtd.current[i] !== undefined ? money0(d.mtd.current[i]) : "–", d.mtd.last[i] !== undefined ? money0(d.mtd.last[i]) : "–", money0(d.mtd.average[i])]) }}>
<Lines labels={mtdDays} fmt={money0} hrefs={(i) => activity({ from: `${d.mtd.thisMonth}-01`, to: `${d.mtd.thisMonth}-${String(i + 1).padStart(2, "0")}` })} series={[
{ name: "3-month average", color: "var(--series-other)", values: d.mtd.average, width: 1.5 },
{ name: "Last month", color: "var(--muted)", values: mtdDays.map((_, i) => d.mtd.last[i] ?? null), dashed: true, width: 1.5 },
{ name: "This month", color: "var(--chart)", values: mtdDays.map((_, i) => d.mtd.current[i] ?? null), width: 2.5 },
]} />
</Card>
<Card title="Balance over time" note="Worked back from today's balances. Cards and loans count as owed. Click a name to show or hide it."
table={{ head: ["Day", "Total", ...bal.series.map((s) => s.name)], rows: bal.days.map((dd, i) => [day(dd), money0(bal.total[i]), ...bal.series.map((s) => money0(s.values[i]))]) }}>
<div className="flex flex-wrap gap-x-3 gap-y-1 text-xs">
<span className="flex items-center gap-1.5 font-medium"><span className="w-3 rounded" style={{ background: "var(--ink)", height: 3 }} />Total</span>
{bal.series.map((s) => (
<button key={s.id} type="button" onClick={() => toggle(s.id)} aria-pressed={!hidden.has(s.id)} className={`flex items-center gap-1.5 ${hidden.has(s.id) ? "text-muted line-through" : "text-muted hover:text-ink"}`}>
<span className="w-3 rounded" style={{ background: slot(s.slot), height: 3 }} />{s.name}{s.owed ? " (owed)" : ""}
</button>
))}
</div>
<Lines labels={bal.days.map(day)} fmt={money0} zero={false} series={[
...bal.series.filter((s) => !hidden.has(s.id)).map((s) => ({ name: s.name, color: slot(s.slot), values: s.values, width: 1.25 })),
{ name: "Total", color: "var(--ink)", values: bal.total, width: 2.5 },
]} />
</Card>
<Card title="Top merchants" note="Your biggest merchants in this period, spending per period." legend={d.merchants.map((m) => ({ name: m.name, color: slot(m.slot) }))}
table={tableOf(["Period", ...d.merchants.map((m) => m.name)], d.merchants.map((m) => m.values.map((v) => money0(v))))}>
{d.merchants.length ? <Lines labels={labels} fmt={money0} hrefs={(i) => inPeriod(i)} series={d.merchants.map((m) => ({ name: m.name, color: slot(m.slot), values: m.values }))} /> : <p className="text-sm text-muted">No spending in this period.</p>}
</Card>
<Card title="Spending by weekday" note={d.compare ? "Average per weekday. Dashed outlines: the period before." : "Average spent on each day of the week in this period."}
table={{ head: ["Day", "Average", ...(d.weekdayBefore ? ["Before"] : [])], rows: WEEKDAYS.map((w, i) => [w, money0(d.weekday[i]), ...(d.weekdayBefore ? [money0(d.weekdayBefore[i])] : [])]) }}>
<Bars labels={WEEKDAYS} series={[{ name: "Average spent", color: "var(--chart)", values: d.weekday, faint: d.weekdayBefore ?? undefined }]} fmt={money0} />
</Card>
<Card title="Biggest changes" note="Compared with the same length of time just before.">
{d.changes ? (
<div className="grid grid-cols-2 gap-4 text-sm">
{([["Categories", d.changes.categories, (c: Change & { label?: string }) => c.label ?? c.id, (c: Change) => activity({ category: c.id, from: d.periods[0]?.from, to: d.periods.at(-1)?.to })],
["Merchants", d.changes.merchants, (c: Change) => c.id, (c: Change) => activity({ q: c.id, from: d.periods[0]?.from, to: d.periods.at(-1)?.to })]] as const).map(([title, ch, name, href]) => (
<div key={title} className="space-y-1 min-w-0">
<div className="text-xs font-medium text-muted">{title}</div>
{!ch.up.length && !ch.down.length && <p className="text-xs text-muted">No real changes.</p>}
{[...ch.up, ...ch.down].map((c) => (
<Link key={c.id} href={href(c)} className="row-hover flex justify-between gap-2 rounded-lg px-2 py-1 -mx-2">
<span className="truncate">{name(c)}</span>
<span className={`tabular shrink-0 ${c.delta > 0 ? "text-bad" : "text-good"}`}>{c.delta > 0 ? "+" : "−"}{money0(Math.abs(c.delta))}</span>
</Link>
))}
</div>
))}
</div>
) : <p className="text-sm text-muted">Pick a time range to compare.</p>}
</Card>
</div>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
// node src/lib/charts.test.ts
import assert from "node:assert/strict";
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periodKey, periods, previousRange, rankBySpend, savingsRate, totals, type Row } from "./charts.ts";
const r = (date: string, amount: number, extra: Partial<Row> = {}): Row => ({
date, amount, spend: amount > 0, income: amount < 0, categoryId: "food", merchant: "AH", accountId: "chk", ...extra,
});
// Periods: weeks start on Monday, months cover the whole month, empty periods still listed.
assert.equal(periodKey("2026-11-19", "week"), "2026-11-16"); // a Thursday -> Monday 16 Nov
assert.equal(periodKey("2026-11-16", "week"), "2026-11-16");
assert.equal(periodKey("2026-11-22", "week"), "2026-11-16"); // Sunday belongs to the week before
assert.deepEqual(periods("2026-10-15", "2026-12-02", "month").map((p) => [p.key, p.from, p.to]), [["2026-10", "2026-10-01", "2026-10-31"], ["2026-11", "2026-11-01", "2026-11-30"], ["2026-12", "2026-12-01", "2026-12-31"]]);
assert.equal(periods("2026-12-20", "2027-01-05", "month")[1].label, "Jan '27");
assert.equal(periods("2026-11-01", "2026-11-03", "day").length, 3);
assert.deepEqual(previousRange("2026-11-01", "2026-11-30"), { from: "2026-10-02", to: "2026-10-31" });
// Cash flow and savings rate.
const rows = [r("2026-10-01", -2500, { categoryId: "pay", merchant: "Werkgever" }), r("2026-10-03", 40), r("2026-10-20", 60, { categoryId: "fun", merchant: "Cinema" }), r("2026-11-02", 30)];
const ps = periods("2026-10-01", "2026-11-30", "month");
const flow = cashFlow(rows, ps, "month");
assert.deepEqual(flow, [{ key: "2026-10", income: 2500, spend: 100, net: 2400 }, { key: "2026-11", income: 0, spend: 30, net: -30 }]);
assert.deepEqual(savingsRate(flow), [{ key: "2026-10", rate: 96 }, { key: "2026-11", rate: null }]);
// A transfer (neither spend nor income) counts nowhere.
assert.deepEqual(cashFlow([r("2026-10-05", 1000, { spend: false, income: false })], ps, "month")[0], { key: "2026-10", income: 0, spend: 0, net: 0 });
assert.deepEqual(totals(rows), { spend: 130, income: 2500, net: 2370 });
// Categories over time with "other", and the stable spend ranking.
assert.deepEqual(categoriesOver(rows, ps, "month", ["food"]).map((x) => x.values), [{ food: 40, other: 60 }, { food: 30, other: 0 }]);
assert.deepEqual(rankBySpend(rows, (x) => x.categoryId), ["food", "fun"]);
assert.deepEqual(merchantsOver(rows, ps, "month", ["AH"]), [{ name: "AH", values: [40, 30] }]);
// Month to date: running totals, cut at today for this month.
const mtd = monthToDate([r("2026-11-01", 10), r("2026-11-03", 5), r("2026-10-02", 20), r("2026-11-25", 99)], "2026-11-03");
assert.deepEqual(mtd.current, [10, 10, 15]);
assert.equal(mtd.last.length, 31);
assert.equal(mtd.last[1], 20);
assert.equal(mtd.average.length, 30);
assert.equal(mtd.average[30 - 1], round(20 / 3));
function round(n: number) { return Math.round(n * 100) / 100; }
// Balances worked back from today: spending lowers a bank balance and raises what's owed on a card.
const b = balances(
[{ id: "chk", name: "Checking", balance: 1000, owed: false }, { id: "card", name: "Card", balance: 50, owed: true }],
[r("2026-11-02", 100), r("2026-11-03", -40), r("2026-11-02", 50, { accountId: "card" })],
"2026-11-01", "2026-11-03", "day",
);
assert.deepEqual(b.days, ["2026-11-01", "2026-11-02", "2026-11-03"]);
assert.deepEqual(b.series[0].values, [1060, 960, 1000]); // before the €100 out and the €40 in
assert.deepEqual(b.series[1].values, [0, 50, 50]);
assert.deepEqual(b.total, [1060, 910, 950]);
assert.deepEqual(balances([{ id: "chk", name: "C", balance: 1, owed: false }], [], "2026-11-01", "2026-11-30", "week").days, ["2026-11-01", "2026-11-08", "2026-11-15", "2026-11-22", "2026-11-29", "2026-11-30"]);
// Weekday averages: Mon 2 Nov and Mon 9 Nov in range, €30 spent on one of them -> €15 a Monday.
assert.equal(byWeekday([r("2026-11-02", 30)], "2026-11-02", "2026-11-15")[0], 15);
// Biggest changes.
const ch = biggestChanges([r("2026-11-02", 300, { categoryId: "fun" }), r("2026-11-03", 20)], [r("2026-10-02", 100, { categoryId: "fun" }), r("2026-10-03", 90)], (x) => x.categoryId);
assert.deepEqual(ch.up, [{ id: "fun", now: 300, before: 100, delta: 200 }]);
assert.deepEqual(ch.down, [{ id: "food", now: 20, before: 90, delta: -70 }]);
console.log("charts ok");
+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) };
}