diff --git a/README.md b/README.md index 171c74b..a3b2819 100644 --- a/README.md +++ b/README.md @@ -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 | | 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. | +| 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`) | | Next.js and React | 15.5.4 and 19.1.0 (critical advisory) | 15.5.29 and 19.1.10 | diff --git a/src/app/(app)/charts/page.tsx b/src/app/(app)/charts/page.tsx new file mode 100644 index 0000000..ab215aa --- /dev/null +++ b/src/app/(app)/charts/page.tsx @@ -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 }) { + 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 ; + + // 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 = (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 ( +
+ ({ 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 }))} + /> + +
+ ); +} diff --git a/src/app/globals.css b/src/app/globals.css index 1657913..ca763af 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -26,6 +26,10 @@ --shadow-card: 0 1px 2px #0000000a, 0 6px 20px -8px #00000014; --shadow-pop: 0 1px 3px #0000000f, 0 18px 44px -14px #00000038; --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; } @@ -37,6 +41,7 @@ /* 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; --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. */ --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. */ --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; + --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; } diff --git a/src/components/Nav.tsx b/src/components/Nav.tsx index e96487f..17d29aa 100644 --- a/src/components/Nav.tsx +++ b/src/components/Nav.tsx @@ -19,7 +19,7 @@ const LINKS: { href: string; label: string; icon: Icon }[] = [ { href: "/accounts", label: "Accounts", icon: Landmark }, { 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 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))); diff --git a/src/components/charts/ChartFilters.tsx b/src/components/charts/ChartFilters.tsx new file mode 100644 index 0000000..1b80c70 --- /dev/null +++ b/src/components/charts/ChartFilters.tsx @@ -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(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 ( +
+ + {open && ( +
+ + {options.map((o) => ( + + ))} +
+ )} +
+ ); +} + +export function ChartFilters({ accounts, categories, tags }: { accounts: Opt[]; categories: Opt[]; tags: Opt[] }) { + const router = useRouter(), path = usePathname(), params = useSearchParams(); + const set = (patch: Record) => { + 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 ( +
+
+ set({ range: v === "12m" ? null : v, from: null, to: null })} /> + + set({ g: v || null })} /> + +
+
+ set({ acct: v.join(",") || null })} /> + set({ cat: v.join(",") || null })} /> + {!!tags.length && set({ tag: v.join(",") || null })} />} + set({ dir: v || null })} /> + + {any && } +
+
+ ); +} diff --git a/src/components/charts/ChartKit.tsx b/src/components/charts/ChartKit.tsx new file mode 100644 index 0000000..c328244 --- /dev/null +++ b/src/components/charts/ChartKit.tsx @@ -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(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 ( +
+
+
+
{title}
+ {note &&

{note}

} +
+ {table && } +
+ {legend && legend.length > 1 && !asTable && ( +
+ {legend.map((l) => ( + + {l.name} + + ))} +
+ )} + {asTable && table ? ( +
+ + {table.head.map((h, i) => )} + {table.rows.map((r, i) => {r.map((c, j) => )})} +
{h}
{c}
+
+ ) : children} +
+ ); +} + +function Tip({ x, w, children }: { x: number; w: number; children: ReactNode }) { + const left = Math.min(Math.max(x, 90), w - 90); + return
{children}
; +} + +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(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 ( +
setHover(null)}> + {hover !== null && ( + +
{labels[hover]}
+ {series.map((s) =>
{s.name}: {fmt(s.values[hover] ?? 0)}{s.faint ? (before: {fmt(s.faint[hover] ?? 0)}) : null}
)} +
+ )} + s.name).join(", ")} per period`}> + {tk.map((t) => ( + + + {fmt(t)} + + ))} + {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 ( + setHover(i)} onClick={() => go()}> + + {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 { e.stopPropagation(); go(j); }} />; + } + const bx = x0 + j * (per + 2); + const f = s.faint?.[i]; + return ( + + {f ? : null} + { e.stopPropagation(); go(j); }} /> + + ); + })} + {i % every === 0 && {l}} + + ); + })} + +
+ ); +} + +/** 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(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 ( +
setHover(null)}> + {hover !== null && ( + +
{labels[hover]}
+ {series.filter((s) => s.values[hover] !== null).map((s) =>
{s.name}: {fmt(s.values[hover]!)}{s.faint?.[hover] != null ? (before: {fmt(s.faint[hover]!)}) : null}
)} +
+ )} + 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) => ( + + + {fmt(t)} + + ))} + {labels.map((l, i) => (i % every === 0 ? {l} : null))} + {series.map((s) => s.faint && )} + {series.map((s) => )} + {/* 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 + ? : null))} + {hover !== null && ( + + + {series.map((s) => s.values[hover] !== null && )} + + )} + +
+ ); +} diff --git a/src/components/charts/ChartsView.tsx b/src/components/charts/ChartsView.tsx new file mode 100644 index 0000000..1835a58 --- /dev/null +++ b/src/components/charts/ChartsView.tsx @@ -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[] }; + 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; // 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) => { + 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 = {}) => 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 {p >= 0 ? "+" : ""}{Math.round(p)}% vs before; + }; + const [hidden, setHidden] = useState>(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 ( +
+ {d.otherCurrency > 0 &&

{d.otherCurrency} transactions in another currency are left out of these charts.

} +
+ {([["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]) => ( +
+
{k}
+
{money0(v)}
+ {d.compare && change(v, b)} +
+ ))} +
+ +
+ money0(f.income)), d.flow.map((f) => money0(f.spend)), d.flow.map((f) => money0(f.net))])}> + inPeriod(i)} /> + + + [p.label, d.rate.values[i] === null ? "–" : pct(d.rate.values[i]!), ...(d.rateBefore ? [d.rateBefore[i] === null ? "–" : pct(d.rateBefore[i]!)] : [])]) }}> + 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 })} /> + + + s.name)], catSeries.map((s) => s.values.map((v) => money0(v ?? 0))))}> + inPeriod(i, s !== undefined ? { category: catDefs[s]?.id } : {})} /> + + + [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])]) }}> + 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 }, + ]} /> + + + s.name)], rows: bal.days.map((dd, i) => [day(dd), money0(bal.total[i]), ...bal.series.map((s) => money0(s.values[i]))]) }}> +
+ Total + {bal.series.map((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 }, + ]} /> +
+ + ({ 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 ? inPeriod(i)} series={d.merchants.map((m) => ({ name: m.name, color: slot(m.slot), values: m.values }))} /> :

No spending in this period.

} +
+ + [w, money0(d.weekday[i]), ...(d.weekdayBefore ? [money0(d.weekdayBefore[i])] : [])]) }}> + + + + + {d.changes ? ( +
+ {([["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]) => ( +
+
{title}
+ {!ch.up.length && !ch.down.length &&

No real changes.

} + {[...ch.up, ...ch.down].map((c) => ( + + {name(c)} + 0 ? "text-bad" : "text-good"}`}>{c.delta > 0 ? "+" : "−"}{money0(Math.abs(c.delta))} + + ))} +
+ ))} +
+ ) :

Pick a time range to compare.

} +
+
+
+ ); +} diff --git a/src/lib/charts.test.ts b/src/lib/charts.test.ts new file mode 100644 index 0000000..b4d50ed --- /dev/null +++ b/src/lib/charts.test.ts @@ -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 => ({ + 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"); diff --git a/src/lib/charts.ts b/src/lib/charts.ts new file mode 100644 index 0000000..2cfc15e --- /dev/null +++ b/src/lib/charts.ts @@ -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])); + 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(); + 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(); + 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) }; +}