123 lines
8.0 KiB
TypeScript
123 lines
8.0 KiB
TypeScript
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>
|
||
|
|
);
|
||
|
|
}
|