broke: a private money app that runs on your own accounts and your own AI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minimus7andClaude Opus 5.5 committed 2026-11-04 10:53:45 -06:00
commit f550865e93
359 files changed
+34290

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
import Link from "next/link";
import { AddAccounts } from "@/components/AddAccounts";
import { LinkedNow } from "@/components/LinkedNow";
import { countryOf, wantsAkahu } from "@/lib/countries";
import { getUser } from "@/lib/data";
import { addChoices } from "@/lib/providers";
// A page, not a modal: Plaid Link draws its own overlay, and an open <dialog> would make it inert.
export default async function AddAccountsPage({ searchParams }: { searchParams: Promise<{ connect?: string }> }) {
const { supabase, user } = await getUser();
const { connect } = await searchParams;
const country = countryOf(user?.user_metadata?.profile?.country);
const choices = addChoices(country.code, wantsAkahu(user?.user_metadata?.profile));
const { data: manual } = await supabase.from("accounts").select("id, name, custom_name, mask").eq("manual", true).eq("user_id", user!.id);
const accounts = (manual ?? []).map((a) => ({ id: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}` }));
return (
<div className="space-y-6 max-w-4xl">
<Link href="/accounts" className="inline-block text-sm text-muted hover:text-ink px-1">Back to accounts</Link>
<LinkedNow userId={user!.id} profile={user?.user_metadata?.profile} />
{connect === "done" && <p className="card px-5 py-3 text-sm" role="status">Your bank is connected. Its transactions are on the way.</p>}
{connect === "cancelled" && <p className="card px-5 py-3 text-sm" role="status">The connection was cancelled. Nothing changed.</p>}
{connect === "failed" && <p className="card px-5 py-3 text-sm text-bad" role="alert">That bank didn&apos;t connect. Try again, or import a statement instead.</p>}
{!choices.bank && !choices.feeds.length && !choices.akahuMissing && !choices.alsoAkahu && <p className="text-sm text-muted px-1">Automatic bank linking isn&apos;t available in {country.name} yet. Import a statement from your bank instead: it takes a minute and works with any bank.</p>}
<AddAccounts choices={choices} accounts={accounts} locale={country.locale} currency={country.currency} country={country.code} />
{choices.akahuMissing && (
<p className="text-sm text-muted px-1">To sync NZ banks automatically, add Akahu keys on the <a href="/setup" className="underline underline-offset-2">Setup page</a>. Until then, import a statement from your bank.</p>
)}
</div>
);
}
+185
View File
@@ -0,0 +1,185 @@
import { Banknote, BarChart3, Bitcoin, Car, CreditCard, Gem, HandCoins, House, Landmark, type LucideIcon } from "lucide-react";
import Link from "next/link";
import { AccountToggle } from "@/components/AccountToggle";
import { HoldingFee } from "@/components/HoldingFee";
import { CardArt } from "@/components/CardArt";
import { Merchant } from "@/components/Merchant";
import { ownedCards } from "@/lib/cards";
import { ConnectionActions, SyncButton } from "@/components/PlaidButtons";
import { getUser } from "@/lib/data";
import { money, money0, plural } from "@/lib/format";
type Holding = { id: string; name: string | null; ticker: string | null; type: string | null; quantity: number | null; value: number | null; cost_basis: number | null };
type Account = { id: string; name: string; official_name?: string | null; custom_name: string | null; mask: string | null; type: string; subtype: string | null; current_balance: number | null; currency: string | null; home: number | null; included: boolean; holdings: Holding[] };
type Item = {
id: string;
institution_name: string | null;
institution_logo: string | null;
institution_color: string | null;
last_synced_at: string | null;
status?: string;
error?: string | null;
provider?: string;
accounts: Account[];
};
const GROUPS: { type: string; label: string; icon: LucideIcon; debt: boolean }[] = [
{ type: "depository", label: "Cash", icon: Landmark, debt: false },
{ type: "investment", label: "Investments", icon: BarChart3, debt: false },
{ type: "other", label: "Property and other", icon: Gem, debt: false }, // manual cars, homes, valuables (Add accounts)
{ type: "credit", label: "Credit cards", icon: CreditCard, debt: true },
{ type: "loan", label: "Loans", icon: HandCoins, debt: true },
];
// Plaid subtypes are lowercase codes ("hsa", "401k", "roth"); everything else just gets capitalised.
const SUBTYPES: Record<string, string> = { hsa: "HSA", "401k": "401(k)", "403b": "403(b)", "457b": "457(b)", ira: "IRA", roth: "Roth IRA", "roth 401k": "Roth 401(k)", "529": "529", sep: "SEP IRA", "simple ira": "SIMPLE IRA", brokerage: "Brokerage", cd: "CD" };
// Manual accounts keep the kind picked on Add accounts as their subtype.
const MANUAL_ICON: Record<string, LucideIcon> = { vehicle: Car, property: House, crypto: Bitcoin, cash: Banknote, other: Gem };
// Plaid's cash position inside a brokerage ("CUR:USD U S Dollar").
const isCash = (h: Holding) => h.type === "cash" || /^(CASH|CUR:)/.test(h.ticker ?? "");
// What a connection holds, so two from the same bank read apart: "Cash, credit cards and loans".
const holds = (accounts: Account[]) => {
const ls = GROUPS.filter((g) => accounts.some((a) => a.type === g.type)).map((g, i) => (i ? g.label.toLowerCase() : g.label));
return ls.length > 1 ? `${ls.slice(0, -1).join(", ")} and ${ls.at(-1)}` : ls[0] ?? "";
};
const subtypeLabel = (s: string) => SUBTYPES[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
const ago = (iso: string) => {
const m = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
return m < 1 ? "just now" : m < 60 ? `${m} min ago` : m < 1440 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} d ago`;
};
export default async function Accounts() {
const { supabase, user } = await getUser();
// Manual accounts (from "Add transaction") have no Plaid item; balance (migration 0014) is the starting balance less what went out.
const [{ data }, { data: manual }] = await Promise.all([
supabase
.from("plaid_items")
.select("id, institution_name, institution_logo, institution_color, last_synced_at, status, error, provider, accounts(id, name, official_name, custom_name, mask, type, subtype, current_balance, currency, home:home_balance, included, holdings(id, name, ticker, type, quantity, value, cost_basis))")
.order("created_at"),
supabase.from("accounts").select("id, name, custom_name, mask, type, subtype, current_balance:balance, currency, home:home_balance, included").eq("manual", true).eq("user_id", user!.id),
]);
const items = (data ?? []) as unknown as Item[];
const manualItem = { id: "manual", institution_name: "Added by you", institution_logo: null, institution_color: null, last_synced_at: null, accounts: [] };
const all = [
...items.flatMap((i) => i.accounts.map((a) => ({ ...a, item: i }))),
...((manual ?? []) as unknown as Account[]).map((a) => ({ ...a, holdings: [], item: manualItem })),
];
const sum = (debt: boolean) =>
all.filter((a) => a.included && GROUPS.find((g) => g.type === a.type)?.debt === debt).reduce((s, a) => s + Number(a.home ?? 0), 0);
const assets = sum(false);
const debts = sum(true);
return (
<div className="space-y-6 max-w-4xl">
<div className="flex gap-2 items-start flex-wrap">
<Link href="/accounts/add" className="btn-primary">Add account</Link>
{!!items.length && <SyncButton />}
</div>
{!!all.length && (
<section className="card grid grid-cols-1 @md:grid-cols-3 divide-y @md:divide-y-0 @md:divide-x divide-line">
{[
["Assets", assets, ""],
["Debts", debts, "text-bad"],
["Net worth", assets - debts, ""],
].map(([label, v, cls]) => (
<div key={label as string} className="px-6 py-4 @md:py-6">
<div className="section-label">{label}</div>
<div className={`text-2xl font-semibold tracking-[-0.02em] tabular mt-1 ${cls}`}>{money0(v as number)}</div>
</div>
))}
</section>
)}
{GROUPS.map(({ type, label, icon: Icon, debt }) => {
const rows = all.filter((a) => a.type === type);
if (!rows.length) return null;
const total = rows.filter((a) => a.included).reduce((s, a) => s + Number(a.home ?? 0), 0);
return (
<div key={type} className="space-y-3">
<div className="flex justify-between px-1">
<span className="section-label">{label}</span>
<span className={`text-sm tabular font-medium ${debt ? "text-bad" : ""}`}>{money(total)}</span>
</div>
<section className="card overflow-hidden">
{rows.map((a) => (
<div key={a.id} className={`border-b border-line last:border-0 ${a.included ? "" : "opacity-50"}`}>
<div className="row-hover flex items-center gap-4 px-6 py-4">
{(() => {
const card = a.type === "credit" ? ownedCards([a])[0] : undefined;
if (card) return <CardArt card={card} w="w-14" />;
const RowIcon = (a.item.id === "manual" && a.subtype && MANUAL_ICON[a.subtype]) || Icon;
return <span className="size-9 rounded-full bg-canvas grid place-items-center shrink-0"><RowIcon size={17} strokeWidth={1.6} aria-hidden /></span>;
})()}
<div className="flex-1 min-w-0">
<div className="truncate">{a.custom_name || a.name} <span className="text-muted">{a.mask ? `··${a.mask}` : ""}</span></div>
<div className="text-xs text-muted">{a.item.institution_name}{a.subtype ? ` · ${subtypeLabel(a.subtype)}` : ""}</div>
</div>
<span className="tabular font-medium">{money(a.current_balance, a.currency)}</span>
<AccountToggle id={a.id} included={a.included} name={a.custom_name || a.name} />
</div>
{!!a.holdings?.length && (
<ul className="pl-6 @md:pl-[4.75rem] pr-6 pb-3 space-y-2.5">
{[...a.holdings].sort((x, y) => Number(y.value ?? 0) - Number(x.value ?? 0)).map((h) => {
const cash = isCash(h);
const gain = !cash && h.cost_basis != null && h.value != null ? Number(h.value) - Number(h.cost_basis) : null;
return (
<li key={h.id} className="text-sm">
<div className="flex items-baseline gap-3">
<span className="w-14 shrink-0 text-xs font-medium tabular text-muted truncate">{cash ? "" : h.ticker ?? ""}</span>
<span className="flex-1 min-w-0 truncate">{cash ? "Cash" : h.name}</span>
<span className="shrink-0 text-right tabular">{money(h.value, a.currency)}</span>
</div>
{!cash && (
<div className="pl-[4.25rem] flex flex-wrap gap-x-3 text-xs text-muted tabular">
{gain != null && <span className={gain < 0 ? "text-bad" : ""}>{gain < 0 ? "down " : "up "}{money0(Math.abs(gain), a.currency)}</span>}
<HoldingFee ticker={h.ticker} type={h.type} value={h.value} />
</div>
)}
</li>
);
})}
</ul>
)}
</div>
))}
</section>
</div>
);
})}
{!!items.length && (
<div className="space-y-3">
<div className="section-label px-1">Connections</div>
<section className="card overflow-hidden">
{items.map((item) => (
<div key={item.id} className="flex flex-wrap items-center gap-4 px-6 py-4 border-b border-line last:border-0">
<Merchant name={item.institution_name ?? "Bank"} logo={item.institution_logo} color={item.institution_color} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
{item.institution_name ?? "Bank"}
{item.status && item.status !== "ok" && <span className="text-xs font-medium text-bad border border-bad rounded-full px-2 py-0.5">Needs attention</span>}
</div>
<div className="text-xs text-muted">
{item.status && item.status !== "ok"
? item.status === "ITEM_LOGIN_REQUIRED" ? "Sign in to your bank again to keep syncing." : (item.error ?? "This connection stopped syncing.")
: `${holds(item.accounts) ? `${holds(item.accounts)} · ` : ""}${plural(item.accounts.length, "account")} · synced ${item.last_synced_at ? ago(item.last_synced_at) : "never"}`}
</div>
</div>
<ConnectionActions itemId={item.id} broken={item.provider === "plaid" && !!item.status && item.status !== "ok"} name={item.institution_name ?? "this bank"} />
</div>
))}
</section>
</div>
)}
{!all.length && (
<section className="card p-10 text-center space-y-2">
<div className="card-title">No accounts yet</div>
<p className="text-sm text-muted">Link a bank to see balances, transactions and recurring charges, and a brokerage, 401(k) or HSA to see what you hold.</p>
</section>
)}
</div>
);
}
+116
View File
@@ -0,0 +1,116 @@
import { Check, CircleHelp, X } from "lucide-react";
import Link from "next/link";
import { Merchant } from "@/components/Merchant";
import { KIND_LABEL, type Match, type OfferKind, type Verdict } from "@/lib/bonuses";
import { myBonuses } from "@/lib/bonuses-data";
const MARK: Record<Verdict, { icon: typeof Check; label: string; tone: string }> = {
yes: { icon: Check, label: "You qualify", tone: "text-good" },
maybe: { icon: CircleHelp, label: "Check first", tone: "text-muted" },
no: { icon: X, label: "Not for you now", tone: "text-muted" },
};
function Row({ name, by, logo, bonus, net, verdict, why, notes, need, href, cta }: { name: string; by: string; logo?: string; bonus: string; net: string; verdict: Verdict; why: string[]; notes: string[]; need: string; href: string; cta: string }) {
const m = MARK[verdict], Icon = m.icon;
return (
<li className={`p-5 flex flex-col @md:flex-row gap-4 @md:items-start ${verdict === "no" ? "opacity-60" : ""}`}>
<Merchant name={logo ?? by} />
<div className="flex-1 min-w-0 space-y-1.5">
<div className="flex flex-wrap items-baseline gap-x-2">
<span className="font-medium">{name}</span>
<span className="text-sm text-muted">{by}</span>
</div>
<p className="text-sm">{need}</p>
<p className={`text-sm flex items-center gap-1.5 ${m.tone}`}><Icon size={14} className="shrink-0" />{m.label}</p>
<ul className="text-sm text-muted space-y-0.5">{why.map((w) => <li key={w}>{w}</li>)}</ul>
{!!notes.length && (
<details className="text-sm text-muted">
<summary className="cursor-pointer hover:text-ink w-fit">Fees and fine print</summary>
<ul className="space-y-0.5 pt-1">{notes.map((w) => <li key={w}>{w}</li>)}</ul>
</details>
)}
</div>
<div className="flex @md:flex-col items-center @md:items-end justify-between gap-3 shrink-0">
<div className="@md:text-right">
<div className="text-lg font-semibold tabular">{bonus}</div>
{net !== bonus && <div className="text-xs text-muted tabular">You keep about {net}</div>}
</div>
<a href={href} target="_blank" rel="noopener noreferrer" className={verdict === "yes" ? "btn-primary" : "btn"}>{cta}</a>
</div>
</li>
);
}
// Offers that fit (or might) first; the ones that don't fold away under one line.
function Section({ title, sub, fits, rest, empty }: { title: string; sub: string; fits: React.ReactNode[]; rest: React.ReactNode[]; empty: string }) {
return (
<section className="card overflow-hidden">
<div className="p-5 pb-3">
<div className="card-title">{title}</div>
<p className="text-sm text-muted mt-0.5">{sub}</p>
</div>
{fits.length ? <ul className="divide-y divide-line border-t border-line">{fits}</ul> : <p className="px-5 pb-4 text-sm text-muted">{empty}</p>}
{!!rest.length && (
<details className="border-t border-line">
<summary className="px-5 py-3.5 text-sm text-muted cursor-pointer hover:text-ink">{rest.length} more that don&apos;t fit you now</summary>
<ul className="divide-y divide-line border-t border-line">{rest}</ul>
</details>
)}
</section>
);
}
const split = <T extends { verdict: Verdict }>(rows: T[], row: (r: T) => React.ReactNode) => ({ fits: rows.filter((r) => r.verdict !== "no").map(row), rest: rows.filter((r) => r.verdict === "no").map(row) });
export default async function Bonuses() {
const b = await myBonuses();
const count = (ms: { verdict: Verdict }[]) => ms.filter((m) => m.verdict === "yes").length;
const kinds = (["checking", "savings", "brokerage"] as OfferKind[]).map((k) => ({ k, rows: b.accounts.filter((m) => m.offer.kind === k) }));
const accountRow = (m: Match) => (
<Row key={m.offer.id} name={m.offer.product} by={m.offer.institution} bonus={b.money(m.bonus)} net={b.money(m.net)} verdict={m.verdict} why={m.why} notes={m.notes}
need={`${m.offer.requirement}${m.offer.expires ? ` Ends ${new Date(m.offer.expires + "T12:00:00Z").toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" })}.` : ""}`}
href={m.offer.url} cta="See the offer" />
);
const noOffers = !b.accounts.length && !b.cards?.length;
return (
<div className="space-y-6 max-w-4xl">
<section className="card p-6 space-y-2">
<div className="text-sm text-muted">Sign-up bonuses you could get now</div>
<div className="figure">{b.money(b.total)}</div>
<p className="text-sm text-muted">
{noOffers
? `broke has no bonus list for ${b.country.name} yet.`
: `From ${count(b.accounts) + count(b.cards ?? [])} offers you qualify for today, after fees${b.country.code === "US" ? " and federal tax" : ""}. Open one at a time and finish its steps before the next.`}
</p>
{b.later > b.total && <p className="text-sm">Up to <span className="font-semibold tabular">{b.money(b.later)}</span> once the first steps of your plan are done.</p>}
{(b.who.carrying || !b.who.cushion) && !noOffers && (
<p className="text-sm">
{b.who.carrying ? "You're paying card interest, so bonuses wait until that's paid off." : "Bonuses wait until your starter emergency fund is built."}{" "}
<Link href="/plan" className="underline underline-offset-2">See your plan</Link>
</p>
)}
</section>
{b.cards && (
<Section title="Credit cards" sub="Bonuses for spending you already do. Only cards inside your credit range." empty="No card bonuses fit you right now."
{...split(b.cards, (c) => (
<Row key={c.fit.card.id} name={c.fit.card.name} by={c.fit.card.issuer} bonus={b.money(c.fit.bonus!)} net={b.money(c.net)} verdict={c.verdict} why={c.why} notes={c.notes}
need={`Spend ${b.money(c.fit.card.bonus!.minSpend)} in the first ${c.fit.card.bonus!.months} months.`} href={c.fit.card.referral ?? c.fit.card.url} cta="Apply" />
))} />
)}
{kinds.filter((x) => x.rows.length).map(({ k, rows }) => (
<Section key={k} title={KIND_LABEL[k]} sub={k === "brokerage" ? "Bonuses for opening or moving investments. Moving money in may have its own fees." : "Bonuses for opening an account and moving money or your pay into it."}
empty="None of these fit you right now." {...split(rows, accountRow)} />
))}
<div className="text-xs text-muted px-1 leading-relaxed space-y-2">
<p>
broke checks each offer on the bank&apos;s own page and shows the date it did. Offers change often: read the terms on their page before you open anything.
{b.country.code === "US" ? " US bank and investing bonuses count as taxable income. Opening many bank accounts can show up on your ChexSystems report." : ""} This is not financial advice.
</p>
{b.cards?.some((c) => c.fit.card.referral) && <p>Some Apply buttons are referral links. The person who shared them may earn points or cash.</p>}
</div>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
import { SlidersHorizontal } from "lucide-react";
import { AskButton } from "@/components/Assistant";
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
import { EmptyBank } from "@/components/EmptyBank";
import { budgetContext, suggest, type MonthSpend } from "@/lib/budget";
import { categories, getUser, isSpend, moneyByMonth, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
import { monthStart, ymd } from "@/lib/format";
// Budgets: tracked against this month with a pace marker; suggestions come from the last 3 full months,
// never below this month's spending so far. Income is the typical month every page shows (typicalMonthly).
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const nextDay = (d: string) => new Date(Date.parse(`${d}T00:00:00Z`) + 864e5).toISOString().slice(0, 10);
export default async function Budgets({ searchParams }: { searchParams: Promise<{ from?: string; to?: string }> }) {
const sp = await searchParams;
const from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
const { supabase, user } = await getUser();
const now = await today();
const thisMonth = ymd(monthStart(now)).slice(0, 7);
const lastMonth = ymd(monthStart(now, -1)).slice(0, 7);
const [txns, cats, saved, typical] = await Promise.all([
moneyByMonth(supabase, ymd(monthStart(now, -Math.max(3, now.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
categories(),
supabase.from("budgets").select("category_id, amount"),
typicalMonthly(supabase, user!.id, ymd(now)),
]);
const threeMonthsAgo = ymd(monthStart(now, -3)).slice(0, 7);
const past = txns.filter((r) => !r.month.startsWith(thisMonth) && r.month.slice(0, 7) >= threeMonthsAgo);
const monthsOfData = Math.max(1, new Set(past.map((r) => r.month.slice(0, 7))).size);
const sum = (catId: string, month?: string) =>
sumOf((month ? txns : past).filter((r) => r.category_id === catId && (!month || r.month.startsWith(month))), (r) => r.spend);
const income = typical?.income ?? 0;
const rows: BudgetCat[] = cats
.filter((c) => c.kind === "spend")
.map((c) => {
const avg = sum(c.id) / monthsOfData;
const spent = sum(c.id, thisMonth);
return { id: c.id, label: c.label, icon: c.icon, color: c.color, spent, last: sum(c.id, lastMonth), avg, suggested: suggest(avg, spent), main: c.key !== "BANK_FEES" && Math.max(avg, spent) >= 10 };
});
// Each month of this year, spend by category, for the year view.
const year = String(now.getUTCFullYear());
const yearMonths: MonthSpend[] = Array.from({ length: now.getUTCMonth() + 1 }, (_, i) => {
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
const cats: Record<string, number> = {};
for (const r of txns) if (r.month.startsWith(month) && r.spend > 0) cats[r.category_id] = (cats[r.category_id] ?? 0) + r.spend;
return { month, cats };
});
// Custom dates: spend per category in the range, added up from the transactions. An open start begins at the first one.
const end = to || ymd(now);
const rangeTxns = from || to ? (await transactionsSince(from || "2000-01-01", nextDay(end))).filter(isSpend) : [];
const range = from || to ? {
from, to, start: from || rangeTxns.map((t) => t.date).sort()[0] || end, end,
spent: rangeTxns.reduce<Record<string, number>>((m, t) => (t.category_id ? { ...m, [t.category_id]: (m[t.category_id] ?? 0) + t.amount } : m), {}),
} : null;
const budgets = Object.fromEntries((saved.data ?? []).map((b) => [b.category_id, Number(b.amount)]));
if (!txns.length && !Object.keys(budgets).length)
return <EmptyBank title="A budget built from your real spending" body="Link a bank and broke suggests a monthly amount for each category from your last 3 months." />;
return (
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
<BudgetEditor key={JSON.stringify(budgets) + (range ? `${from}|${to}` : "")} cats={rows} initial={budgets} year={yearMonths} range={range} today={ymd(now)} income={Math.round(income)} now={now.toISOString()} tableMissing={!!saved.error} aside={
<AskButton
q={`Look at my budget, my income and my last 3 months of spending. Which categories should I lower, by how much, and what would that free up each month?${budgetContext(rows.filter((c) => c.id in budgets).map((c) => [c.label, budgets[c.id]]))}`}
className="card-link w-full p-5 text-left flex items-center gap-4"
>
<span className="size-10 rounded-2xl border border-line text-muted grid place-items-center shrink-0"><SlidersHorizontal size={18} strokeWidth={1.6} /></span>
<span>
<span className="block font-medium">Ask AI to tune my budget</span>
<span className="block text-sm text-muted">It compares your budget with what you really spend and suggests where to cut.</span>
</span>
</AskButton>
} />
);
}
+104
View File
@@ -0,0 +1,104 @@
import Link from "next/link";
import { CardArt } from "@/components/CardArt";
import { YourCards } from "@/components/YourCards";
import { ApplyButton, CardList, CreditPicker, type Row } from "@/components/CardList";
import { Merchant } from "@/components/Merchant";
import { bestFit, bonusText, CAT_LABEL, CHECKED, feeText } from "@/lib/cards";
import { bandLabel, creditOf } from "@/lib/credit";
import { cardMatches } from "@/lib/cards-data";
import { countryOf } from "@/lib/countries";
import { getUser } from "@/lib/data";
import { money0 } from "@/lib/format";
const checked = new Date(CHECKED + "T12:00:00").toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
export default async function Cards() {
const { supabase, user } = await getUser();
const profile = (user?.user_metadata?.profile ?? {}) as Record<string, unknown>;
const country = countryOf(profile.country as string | undefined);
if (!country.cards)
return (
<section className="card p-6 space-y-2 max-w-2xl">
<div className="card-title">Cards are US-only for now</div>
<p className="text-sm text-muted">This page compares US credit cards, so it doesn&apos;t fit {country.name === "Somewhere else" ? "where you live" : country.name} yet.</p>
</section>
);
const credit = creditOf(profile);
const band = credit && credit.band !== "unsure" ? credit.band : null;
const m = await cardMatches(supabase, user!.id, band);
// RegExp can't cross to the client.
const rows: Row[] = m.fits.map((f) => ({ ...f, card: { ...f.card, match: undefined } }));
const best = bestFit(rows);
return (
<div className="space-y-6 max-w-4xl">
<YourCards mine={m.mine} spend={m.spend} />
<section className="card p-6 space-y-4">
<div className="card-title">{m.mine.length ? "Best new card for your spending" : "Best card for your spending"}</div>
{band ? (
<p className="text-sm text-muted">
Picked from cards that fit your credit range: {bandLabel(band)}. <Link href="/optimize#profile" className="text-ink underline underline-offset-2 hover:opacity-70">Change</Link>
</p>
) : (
<CreditPicker profile={profile} />
)}
{!m.hasHistory ? (
<p className="text-sm text-muted">Link a bank with some spending to see which card fits. Until then the list below uses no spending.</p>
) : !best ? (
<p className="text-sm text-muted">None of the cards below fit your credit range yet.</p>
) : (
<>
<div className="flex flex-wrap items-start gap-4 justify-between">
<div className="flex flex-col @md:flex-row gap-4 @md:gap-5">
<CardArt card={best.card} w="w-40" />
<div>
<div className="text-sm text-muted flex items-center gap-1.5"><Merchant name={best.card.issuer} small />{best.card.issuer}</div>
<div className="text-lg font-semibold">{best.card.name}</div>
<div className="text-sm text-muted mt-3">You&apos;d earn about</div>
<div className="figure">{money0(best.ongoing)}<span className="text-base font-normal tracking-normal text-muted"> a year</span></div>
<p className="text-sm text-muted">
{best.card.currency === "cash back" ? "Cash back" : "Rewards, valued in dollars,"} on the {money0(best.byCat.reduce((s, x) => s + x.spend, 0))} you spend a year{best.card.fee || best.card.feeYear1 ? `, after the annual fee (${feeText(best.card).toLowerCase()})` : ""}.
</p>
<p className="text-sm text-muted">First year: {money0(best.yearOne)}. {bonusText(best).join(" ")}</p>
</div>
</div>
<ApplyButton card={best.card} primary />
</div>
<table className="w-full text-sm tabular">
<thead>
<tr className="text-left text-muted"><th className="font-normal py-1.5">Category</th><th className="font-normal text-right">Spend a year</th><th className="font-normal text-right">Rate</th><th className="font-normal text-right">You&apos;d earn</th></tr>
</thead>
<tbody>
{best.byCat.sort((a, b) => b.spend - a.spend).map((x) => (
<tr key={x.cat} className="border-t border-line">
<td className="py-1.5">{CAT_LABEL[x.cat]}</td>
<td className="text-right">{money0(x.spend)}</td>
<td className="text-right">{x.rate}{best.card.currency === "cash back" ? "%" : "x"}</td>
<td className="text-right">{money0(x.earn)}</td>
</tr>
))}
</tbody>
</table>
{m.ownedEarn != null && (
<p className="text-sm">Your current cards ({m.owned.map((c) => c.name).join(", ")}) earn about {money0(m.ownedEarn)} a year on this spending.</p>
)}
{m.creditAccounts > 0 && !m.owned.length && <p className="text-xs text-muted">We couldn&apos;t tell which cards your linked credit accounts are, so none are left out below.</p>}
</>
)}
</section>
<div className="section-label px-1">All cards</div>
<CardList rows={rows} />
<div className="text-xs text-muted px-1 leading-relaxed space-y-2">
{rows.some((r) => r.card.referral) && (
<p>Some Apply buttons are referral links. The person who shared them may earn points or cash. Your offer comes from the issuer and can differ from the public one.</p>
)}
<p>
Estimates use your spending from the last 12 months (scaled up if you have less) and treat 1 point as 1 cent. Bonus categories that only partly match how broke sorts spending are counted at the base rate.
This is not financial advice. Approval depends on your credit. Terms checked on the issuers&apos; pages on {checked}; offers change, so read the issuer&apos;s page before you apply.
</p>
</div>
</div>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { ConnectAI } from "@/components/ConnectAI";
import { getUser } from "@/lib/data";
import { savedChoice } from "@/lib/llm/gate";
import { isHosted, providersFor } from "@/lib/llm/providers";
export default async function ConnectAIPage({ searchParams }: { searchParams: Promise<{ connected?: string; error?: string }> }) {
const { user } = await getUser();
const [providers, q] = await Promise.all([providersFor(user!.id), searchParams]);
return <ConnectAI initial={JSON.parse(JSON.stringify(providers))} choice={savedChoice(user)} hosted={isHosted()} connected={!!q.connected} failed={!!q.error} />;
}
+154
View File
@@ -0,0 +1,154 @@
import Link from "next/link";
import { DebtFields } from "@/components/DebtFields";
import { PageDates } from "@/components/PageDates";
import { allRows, getUser, loanPayments, today } from "@/lib/data";
import { debtFacts, debtMonths, monthsAfter, payoff, type DebtRow } from "@/lib/debt";
import { dateLabel, money0, monthStart, plural, ymd } from "@/lib/format";
type Acct = { id: string; name: string; custom_name: string | null; type: string; subtype: string | null; balance: number | null; apr: number | null; debt_payment: number | null };
const KIND: Record<string, string> = { student: "Student loan", auto: "Car loan", mortgage: "Mortgage" };
const span = (months: number) => (months < 12 ? plural(months, "month") : `${plural(Math.floor(months / 12), "year")}${months % 12 ? `, ${plural(months % 12, "month")}` : ""}`);
// What you owe, what you've been paying and what it costs. Interest comes from the transactions; a loan's interest is
// usually inside its payment, so that part needs the rate the user types in. There's no balance history to chart yet.
const DAY = /^\d{4}-\d{2}-\d{2}$/;
export default async function Debt({ searchParams }: { searchParams: Promise<{ from?: string; to?: string }> }) {
const sp = await searchParams;
const from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
const { supabase, user } = await getUser();
const uid = user!.id;
const now = await today();
const yearAgo = ymd(monthStart(now, -11));
// The window for the totals and chart: the last 12 months, or the dates picked. Balances and payoffs are always as of today.
const custom = !!(from || to);
const start = from || yearAgo, end = to || ymd(now);
const [{ data }, loans] = await Promise.all([
supabase.from("accounts").select("id, name, custom_name, type, subtype, balance:home_balance, apr, debt_payment").eq("user_id", uid).in("type", ["credit", "loan"]),
loanPayments(supabase, uid, start, end),
]);
const accounts = (data ?? []) as Acct[];
const debts = accounts.map((a) => ({ ...a, owed: Math.abs(Number(a.balance ?? 0)) })).filter((a) => a.owed >= 1);
if (!debts.length)
return (
<div className="card p-8 max-w-xl space-y-3">
<h2 className="text-xl font-semibold">No debt to track</h2>
<p className="text-sm text-muted">Link a card or loan, or add one by hand, and this page shows what you owe, what you&apos;re paying and what it costs.</p>
<Link href="/accounts/add" className="btn-primary inline-block">Add a debt</Link>
</div>
);
const raw = await allRows<{ date: string; amount: number; name: string; plaid_category: string | null; account_id: string; category: { key: string } | null }>((a, b) =>
supabase.from("transactions").select("date, amount, name, plaid_category, account_id, category:categories(key)").eq("user_id", uid).eq("ignored", false).gte("date", from && from < yearAgo ? from : yearAgo).in("account_id", accounts.map((x) => x.id)).order("id").range(a, b));
const rows: DebtRow[] = raw.map((r) => ({ date: r.date, amount: Number(r.amount), name: r.name, plaid_category: r.plaid_category, account_id: r.account_id, key: r.category?.key ?? null }));
const inRange = rows.filter((r) => r.date >= start && r.date <= end);
const monthCount = (Number(end.slice(0, 4)) - Number(start.slice(0, 4))) * 12 + Number(end.slice(5, 7)) - Number(start.slice(5, 7)) + 1;
const months = Array.from({ length: Math.max(1, monthCount) }, (_, i) => monthsAfter(start, i));
const history = debtMonths(inRange, accounts, loans, months);
const firstUsed = history.findIndex((m) => m.paid > 0 || m.interest > 0);
const shown = firstUsed < 0 ? [] : history.slice(firstUsed);
const top = Math.max(1, ...shown.map((m) => m.paid));
const last12 = Array.from({ length: 12 }, (_, i) => monthsAfter(yearAgo, i));
const fullMonths = last12.slice(-4, -1); // the last 3 finished months, whatever dates are picked: "usual" means lately
const items = debts.map((d) => {
const f = debtFacts(rows, d.id, fullMonths);
const rangeInterest = debtFacts(inRange, d.id, []).interest;
// A card's payment often just clears new spending, so only what the user typed predicts its payoff.
const payment = d.debt_payment != null ? Number(d.debt_payment) : d.type === "loan" && f.usualPayment >= 1 ? f.usualPayment : null;
const apr = d.apr == null ? null : Number(d.apr);
const plan = payoff(d.owed, apr, payment);
const faster = plan && !plan.never ? payoff(d.owed, apr, payment! + 50) : null;
return { ...d, f, rangeInterest, payment, apr, plan, faster, monthlyInterest: apr == null ? null : (d.owed * apr) / 1200 };
}).sort((a, b) => (b.apr ?? -1) - (a.apr ?? -1) || b.owed - a.owed);
const owed = debts.reduce((s, d) => s + d.owed, 0);
const counted = history.slice(0, -1).slice(-3);
const monthly = counted.reduce((s, m) => s + m.paid, 0) / Math.max(1, counted.length);
const paidTotal = history.reduce((s, m) => s + m.paid, 0);
const label = (d: string) => dateLabel(d, { month: "short", day: "numeric", year: "numeric" });
const when = custom ? `${label(start)} to ${label(end)}` : "last 12 months";
const yearInterest = history.reduce((s, m) => s + m.interest, 0);
const toGo = items.reduce((s, d) => s + (d.plan && !d.plan.never ? d.plan.interest : 0), 0);
const known = items.filter((d) => d.plan && !d.plan.never).length;
const worst = items.find((d) => d.apr != null);
return (
<div className="max-w-4xl space-y-6">
<PageDates path="/debt" from={from} to={to} today={ymd(now)} />
<section className="card overflow-hidden">
{[
{ label: "You owe", value: money0(owed) },
custom ? { label: `Paid, ${when}`, value: money0(paidTotal) } : { label: "Paid each month, on average", value: money0(monthly) },
{ label: `Interest charged, ${when}`, value: money0(yearInterest), bad: yearInterest >= 1 },
...(known ? [{ label: `Interest still to pay on ${plural(known, "debt")}, at these payments`, value: money0(toGo), bad: toGo >= 1 }] : []),
].map((s) => (
<div key={s.label} className="flex items-center justify-between gap-4 px-6 py-4 border-b border-line last:border-0">
<span>{s.label}</span>
<span className={`tabular font-medium ${s.bad ? "text-bad" : ""}`}>{s.value}</span>
</div>
))}
</section>
{!!shown.length && (
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3 px-1">
<div className="section-label">What you paid each month{custom ? `, ${when}` : ""}</div>
<div className="flex gap-4 text-xs text-muted">
<span className="flex items-center gap-1.5"><span className="size-2.5 rounded-sm" style={{ background: "var(--chart)" }} />Payments</span>
<span className="flex items-center gap-1.5"><span className="size-2.5 rounded-sm" style={{ background: "var(--bad)" }} />Interest</span>
</div>
</div>
<section className="card p-5 md:p-6">
<div className="flex items-end gap-1.5 @lg:gap-3 h-40" role="img" aria-label={shown.map((m) => `${m.month}: paid ${money0(m.paid)}, interest ${money0(m.interest)}`).join("; ")}>
{shown.map((m) => (
<div key={m.month} className="flex-1 min-w-0 h-full flex flex-col items-center justify-end gap-1.5">
<span className="text-[10px] tabular text-muted truncate max-w-full">{m.paid >= 1 ? money0(m.paid) : ""}</span>
<div className="w-full max-w-10 flex-1 flex items-end justify-center gap-0.5">
<div className="flex-1 rounded-t" style={{ height: `${(m.paid / top) * 100}%`, minHeight: 2, background: "var(--chart)" }} />
{m.interest >= 1 && <div className="flex-1 rounded-t" style={{ height: `${Math.max(3, (m.interest / top) * 100)}%`, background: "var(--bad)" }} />}
</div>
<span className="text-[11px] text-muted">{dateLabel(`${m.month}-01`, { month: "short" })}</span>
</div>
))}
</div>
</section>
</div>
)}
<div className="space-y-3">
<div className="section-label px-1">Your debts</div>
{items.map((d) => (
<section key={d.id} className="card p-5 md:p-6 space-y-4">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<div className="font-medium truncate">{d.custom_name || d.name}</div>
<div className="text-sm text-muted">{d.type === "credit" ? "Credit card" : KIND[d.subtype ?? ""] ?? "Loan"}{d.id === worst?.id && items.filter((x) => x.apr != null).length > 1 ? " · highest rate, so extra money usually does most here" : ""}</div>
</div>
<div className="text-xl font-semibold tabular shrink-0">{money0(d.owed)}</div>
</div>
<div className="space-y-1 text-sm">
{d.type === "credit" && (d.f.carrying
? <p>You&apos;ve been charged interest lately, so you&apos;re <span className="text-bad font-medium">carrying a balance</span>.</p>
: <p>No interest in the last 3 months. Paying it in full each month costs you nothing.</p>)}
{d.rangeInterest >= 1 && <p>{money0(d.rangeInterest)} in interest, {when}.</p>}
{d.monthlyInterest != null && d.monthlyInterest >= 1 && <p>About {money0(d.monthlyInterest)} of interest a month at this balance.</p>}
{d.plan?.never && <p className="text-bad">This payment doesn&apos;t cover the interest, so the balance won&apos;t go down.</p>}
{d.plan && !d.plan.never && <p>Paid off in <span className="font-medium">{span(d.plan.months)}</span> ({dateLabel(`${monthsAfter(ymd(now), d.plan.months)}-01`, { month: "short", year: "numeric" })}), with <span className="font-medium">{money0(d.plan.interest)}</span> of interest still to pay.</p>}
{d.plan && !d.plan.never && d.faster && !d.faster.never && d.plan.months - d.faster.months >= 1 && <p className="text-muted">Paying {money0(50)} more a month: {span(d.plan.months - d.faster.months)} sooner, {money0(d.plan.interest - d.faster.interest)} less interest.</p>}
{d.apr == null && <p className="text-muted">Add the rate from your statement to see when this is paid off and what it will cost.</p>}
{d.apr != null && d.payment == null && <p className="text-muted">Add what you pay each month to see when this is paid off.</p>}
</div>
<DebtFields id={d.id} apr={d.apr} payment={d.debt_payment == null ? null : Number(d.debt_payment)} guess={d.f.usualPayment} />
</section>
))}
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<Link href="/accounts/add" className="btn">Add a debt</Link>
<p className="text-xs text-muted">Estimates from what you entered. A rate can change, and new spending on a card changes the date. Not financial advice.</p>
</div>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
"use client";
import { useEffect } from "react";
// Plain words only: the raw error (database text, codes) goes to the console, not the page.
export default function PageError({ error, reset }: { error: Error; reset: () => void }) {
useEffect(() => console.error(error), [error]);
return (
<div className="card p-10 max-w-lg mx-auto mt-10 text-center space-y-3">
<div className="card-title">This page didn&apos;t load</div>
<p className="text-sm text-muted">Something went wrong loading it. Your data is safe.</p>
<button onClick={reset} className="btn-primary">Try again</button>
</div>
);
}
+245
View File
@@ -0,0 +1,245 @@
"use client";
import { Check, ExternalLink, Lock, ShieldCheck } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useLinkBank } from "@/components/PlaidButtons";
import { ClearTestData } from "@/components/ClearTestData";
const PLAID = {
home: "https://dashboard.plaid.com/overview",
profile: "https://dashboard.plaid.com/settings/company/compliance?tab=companyProfile",
oauth: "https://dashboard.plaid.com/settings/compliance/us-oauth-institutions",
launch: "https://dashboard.plaid.com/developers/launch-center",
useCase: "https://dashboard.plaid.com/link/data-transparency-v5",
keys: "https://dashboard.plaid.com/developers/keys",
trial: "https://plaid.com/docs/account/billing/#trial-plans",
};
const STEPS = ["Before you start", "Turn on real banks", "Add your real key", "Clear the test data", "Link your bank", "Done"];
const SAVED = "broke:go-live-step"; // so someone waiting days on Plaid comes back to the same step
function Ext({ href, children }: { href: string; children: React.ReactNode }) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 underline underline-offset-2 hover:opacity-70">
{children}
<ExternalLink size={12} />
</a>
);
}
type Props = { live: boolean; canWrite: { ok: boolean; reason?: string }; testItems: { id: string; name: string }[]; realLinked: number; plaidCountry: boolean };
export function GoLive({ live, canWrite, testItems, realLinked, plaidCountry }: Props) {
// Already on real banks: skip to what's left.
const start = live ? (realLinked ? 5 : testItems.length ? 3 : 4) : 0;
const [step, setStep] = useState(start);
useEffect(() => {
if (live) return;
try {
const n = Number(localStorage.getItem(SAVED));
if (n > 0 && n < 3) setStep(n);
} catch {}
}, [live]);
const go = (n: number) => {
setStep(n);
try {
localStorage.setItem(SAVED, String(n));
} catch {}
window.scrollTo({ top: 0 });
};
if (!plaidCountry)
return (
<section className="card p-6 max-w-2xl space-y-2">
<div className="card-title">Real banks through Plaid aren&apos;t used where you live</div>
<p className="text-sm text-muted">Plaid links US, Canadian and some European banks. Add your accounts another way on <Link href="/accounts/add" className="underline underline-offset-2">Add accounts</Link>.</p>
</section>
);
return (
<div className="max-w-2xl space-y-5">
<ol className="flex flex-wrap gap-x-4 gap-y-1 text-sm px-1" aria-label="Steps">
{STEPS.map((s, i) => (
<li key={s} aria-current={i === step ? "step" : undefined} className={`flex items-center gap-1.5 ${i === step ? "text-ink font-medium" : "text-muted"}`}>
{i < step ? <Check size={14} className="text-good" /> : <span className="tabular">{i + 1}.</span>}
{s}
</li>
))}
</ol>
<section className="card p-6 space-y-5">
{step === 0 && <Intro next={() => go(1)} />}
{step === 1 && <Approval back={() => go(0)} next={() => go(2)} />}
{step === 2 && <Secret canWrite={canWrite} back={() => go(1)} next={() => go(3)} />}
{step === 3 && <Clear items={testItems} next={() => go(4)} />}
{step === 4 && <LinkReal next={() => go(5)} />}
{step === 5 && <Done />}
</section>
</div>
);
}
function Nav({ back, next, label = "Continue", disabled }: { back?: () => void; next: () => void; label?: string; disabled?: boolean }) {
return (
<div className="flex items-center gap-3 pt-1">
<button className="btn-primary" onClick={next} disabled={disabled}>{label}</button>
{back && <button className="text-sm text-muted hover:text-ink" onClick={back}>Back</button>}
</div>
);
}
function Intro({ next }: { next: () => void }) {
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">Use your real bank</h2>
<p className="text-muted">broke is in test mode. The bank window only shows Plaid&apos;s made-up banks, so a real bank login won&apos;t work yet.</p>
</div>
<ul className="space-y-3 text-sm">
<li><span className="font-medium">About 10 minutes.</span> Older Plaid accounts may wait a few days for Plaid to review them.</li>
<li><span className="font-medium">The first 10 real banks are free</span> on Plaid&apos;s <Ext href={PLAID.trial}>Trial plan</Ext> (US and Canada). After that Plaid charges per bank. Unlinking a bank doesn&apos;t give a free one back, so link the ones you mean to keep.</li>
<li><span className="font-medium">Your test data gets cleared</span> at step 4, so fake numbers don&apos;t mix with real ones.</li>
</ul>
<Nav next={next} label="Start" />
</>
);
}
function Approval({ back, next }: { back: () => void; next: () => void }) {
const [done, setDone] = useState(false);
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">Turn on real banks in Plaid</h2>
<p className="text-muted">Real bank data only comes through Plaid&apos;s Production mode, which needs its own key. Test mode can&apos;t reach a real bank.</p>
</div>
<ol className="space-y-3 text-sm list-decimal pl-5">
<li>Open the <Ext href={PLAID.home}>Plaid Dashboard</Ext>. If it offers the free Trial plan, fill in that form. It&apos;s for Plaid accounts made since April 15, 2026.</li>
<li>Older Plaid account: open the <Ext href={PLAID.launch}>Launch Center</Ext> and request Production access instead. Plaid may take a few days to review it.</li>
<li>Asked what the data is for? Say it&apos;s a personal budgeting app for your own money. For US and Canadian banks, also <Ext href={PLAID.useCase}>pick a use case</Ext>.</li>
<li>You can close broke while you wait. This page remembers where you were.</li>
</ol>
<label className="flex items-center gap-2.5 text-sm cursor-pointer">
<input type="checkbox" checked={done} onChange={(e) => setDone(e.target.checked)} className="size-4 accent-[var(--ink)]" />
Plaid shows a Production secret on my Keys page
</label>
<Nav back={back} next={next} disabled={!done} />
</>
);
}
// The same check Settings uses: Plaid tests the secret first, and it's only saved if Plaid accepts it.
function Secret({ canWrite, back, next }: { canWrite: Props["canWrite"]; back: () => void; next: () => void }) {
const router = useRouter();
const [secret, setSecret] = useState("");
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string; restart?: boolean } | null>(null);
async function check() {
setBusy(true);
setMsg(null);
const values = { PLAID_ENV: "production", PLAID_SECRET: secret.trim() };
type Reply = { error?: string; errors?: Record<string, string>; checks?: { plaid?: { ok: boolean; message: string } }; restart?: boolean };
const post = (test: boolean) =>
fetch("/api/setup/env", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ values, test }) })
.then(async (r) => ({ ok: r.ok, body: (await r.json().catch(() => ({}))) as Reply }));
try {
const t = await post(true);
const plaid = t.body.checks?.plaid;
const fail = t.body.errors ? Object.values(t.body.errors)[0] : !t.ok ? t.body.error ?? "Couldn't check." : !plaid ? "Add your Plaid client ID in Settings first." : !plaid.ok ? `${plaid.message} Nothing was changed.` : null;
if (fail) return setMsg({ ok: false, text: fail });
const r = await post(false);
if (!r.ok || !r.body.checks?.plaid?.ok) return setMsg({ ok: false, text: r.body.error ?? r.body.checks?.plaid?.message ?? "Couldn't save." });
setSecret("");
setMsg({ ok: true, text: "Plaid accepted it. broke now uses real banks.", restart: r.body.restart });
router.refresh();
} catch {
setMsg({ ok: false, text: "Couldn't reach broke. Is it still running?" });
} finally {
setBusy(false);
}
}
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">Add your real key</h2>
<p className="text-muted">
In the Plaid Dashboard, open <Ext href={PLAID.keys}>Developers → Keys</Ext> and copy the secret under Production. It&apos;s a different secret from the test one; your client ID stays the same.
</p>
</div>
{!canWrite.ok ? (
<p className="text-sm text-muted">{canWrite.reason}</p>
) : msg?.ok ? (
<div className="space-y-3 text-sm">
<p className="text-good flex items-center gap-1.5"><Check size={15} />{msg.text}</p>
{msg.restart && <p>Restart broke to finish: close the window it&apos;s running in and open it again.</p>}
<Nav next={next} />
</div>
) : (
<>
<input
type="password" autoComplete="off" spellCheck={false} value={secret} onChange={(e) => setSecret(e.target.value)}
placeholder="Production secret (30 letters and numbers)" aria-label="Production secret" className="select font-mono !text-[13px]"
/>
<p className="text-xs text-muted flex items-center gap-1.5"><Lock size={12} />Saved only on this computer, in broke&apos;s .env.local file. broke checks it with Plaid before saving.</p>
{msg && <p className="text-sm text-bad">{msg.text}</p>}
<Nav back={back} next={check} label={busy ? "Checking with Plaid…" : "Check and save"} disabled={busy || !secret.trim()} />
</>
)}
</>
);
}
function Clear({ items, next }: { items: { id: string; name: string }[]; next: () => void }) {
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">Clear the test data</h2>
<p className="text-muted">So nothing worked out from fake spending carries over to your real money.</p>
</div>
<ClearTestData items={items} />
<Nav next={next} label="Continue" />
</>
);
}
function LinkReal({ next }: { next: () => void }) {
const { start, busy, error, result } = useLinkBank(undefined, { quiet: true });
useEffect(() => {
if (result) next();
}, [result, next]);
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">Link your bank</h2>
<p className="text-muted">Plaid opens a window where you pick your bank and sign in.</p>
</div>
<ul className="space-y-3 text-sm">
<li className="flex gap-2.5"><ShieldCheck size={18} className="shrink-0 text-muted" /><span><span className="font-medium">broke never sees your bank login.</span> You sign in with your bank inside Plaid&apos;s window.</span></li>
<li className="flex gap-2.5"><Lock size={18} className="shrink-0 text-muted" /><span><span className="font-medium">You&apos;re in control.</span> Unlink any bank on the Accounts page and broke stops reading it.</span></li>
</ul>
<p className="text-sm text-muted">
Plaid says &ldquo;Connectivity not supported&rdquo;? Banks that sign you in on their own site (Chase, Bank of America, Wise and others) first need to approve broke. In the Plaid Dashboard, fill in the{" "}
<Ext href={PLAID.profile}>compliance center</Ext> (company profile, app profile, security questions), then check <Ext href={PLAID.oauth}>OAuth institutions</Ext>. Most banks approve within hours.
</p>
{error && <p className="text-sm text-bad">{error}</p>}
<Nav next={() => start(false, "bank")} label={busy ? "Opening Plaid…" : "Link my bank"} disabled={busy} />
</>
);
}
function Done() {
return (
<>
<div className="space-y-1.5">
<h2 className="text-xl font-semibold tracking-tight">You&apos;re on real banks</h2>
<p className="text-muted">The first sync can take a few minutes. Once your transactions are in, build your money plan from them.</p>
</div>
<div className="flex flex-wrap gap-3">
<Link href="/plan" className="btn-primary">Build my money plan</Link>
<Link href="/accounts/add" className="btn">Add another account</Link>
</div>
</>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { getUser } from "@/lib/data";
import { addChoices } from "@/lib/providers";
import { canWriteEnv, currentEnv, setupAccess, supabaseReady } from "@/lib/setup";
import { createAdminClient } from "@/utils/supabase/admin";
import { GoLive } from "./GoLive";
export const dynamic = "force-dynamic";
// "Use your real bank": the steps from Plaid's test banks to real ones, in order, one at a time.
export default async function GoLivePage() {
const [{ user }, access] = await Promise.all([getUser(), setupAccess()]);
const live = currentEnv().PLAID_ENV === "production";
const { data: items } = user && supabaseReady()
? await createAdminClient().from("plaid_items").select("id, institution_name, access_token").eq("user_id", user.id).eq("provider", "plaid")
: { data: [] };
const rows = (items ?? []) as { id: string; institution_name: string | null; access_token: string | null }[];
const test = rows.filter((i) => i.access_token?.startsWith("access-sandbox-")).map((i) => ({ id: i.id, name: i.institution_name ?? "Test bank" }));
return (
<GoLive
live={live}
canWrite={canWriteEnv()}
testItems={test}
realLinked={rows.length - test.length}
plaidCountry={addChoices(user?.user_metadata?.profile?.country).bank === "plaid"}
/>
);
}
+7
View File
@@ -0,0 +1,7 @@
import { redirect } from "next/navigation";
// For you folded into Plan (2026-10-23): its fee, interest, subscription, spike and idle cash checks are plan moves,
// its profile nudge is on Home, and its savings rate is a line on the plan. Old links land on the plan.
export default function Insights() {
redirect("/plan");
}
+61
View File
@@ -0,0 +1,61 @@
import { Settings } from "lucide-react";
import { AutoSync } from "@/components/AutoSync";
import { headers } from "next/headers";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AssistantProvider } from "@/components/Assistant";
import { Logo } from "@/components/Logo";
import { MoneyProvider } from "@/components/Money";
import { Nav, PageTitle, SectionTabs, ThemeToggle, TimeZoneCookie } from "@/components/Nav";
import { countryOf } from "@/lib/countries";
import { getUser, userTz } from "@/lib/data";
import { fmtFor, todayIn } from "@/lib/format";
import { modeOf } from "@/lib/privacy";
import { createClient } from "@/utils/supabase/server";
// Accounts made before country support are treated as US (countryOf default) and get a dashboard nudge instead.
const FIRST_RUN_SINCE = "2026-10-22";
export default async function AppLayout({ children }: { children: React.ReactNode }) {
const [{ user }, tz] = await Promise.all([getUser(), userTz()]);
const profile = user?.user_metadata?.profile;
// created_at isn't in the token, so only users with no country pay for the full user record.
// If that lookup fails (a dropped call, a dev recompile), treat the user as new: the picker is harmless, skipping it is not.
if (user && !profile?.country && ((await (await createClient()).auth.getUser()).data.user?.created_at ?? FIRST_RUN_SINCE) >= FIRST_RUN_SINCE) redirect("/welcome");
// Onboarding left halfway resumes where it stopped. Its "Add accounts another way" link opens /accounts/add.
if (user && profile?.onboarding && profile.onboarding !== "done" && !(await headers()).get("x-path")?.startsWith("/accounts/add")) redirect("/welcome");
const today = todayIn(tz);
// A bank is due a sync when it hasn't synced in 6 hours, or when its last sync came within 4 hours of linking
// (Plaid fetches older history in the background after a link) and wasn't in the last 10 minutes.
const { data: items } = user ? await (await createClient()).from("plaid_items").select("created_at, last_synced_at").eq("user_id", user.id) : { data: [] };
const now = Date.now();
const due = (items ?? []).some((i) => {
const synced = i.last_synced_at ? Date.parse(i.last_synced_at) : 0;
return now - synced > 6 * 3600e3 || (synced - Date.parse(i.created_at) < 4 * 3600e3 && now - synced > 10 * 60e3);
});
const cards = countryOf(profile?.country).cards;
return (
<MoneyProvider fmt={{ ...fmtFor(profile), tz }}>
<AssistantProvider aiMode={modeOf(user?.user_metadata)}>
<TimeZoneCookie />
<AutoSync due={due} />
<aside className="md:w-60 md:h-screen md:sticky md:top-0 px-3 pt-4 md:pb-4 flex md:flex-col gap-4 md:gap-6">
<div className="flex-1 md:flex-none flex items-center justify-between px-2">
<Logo />
{/* Settings lives on the gear, on the phone too (the phone bar has no room for it). */}
<Link href="/settings" prefetch aria-label="Settings" className="text-muted hover:text-ink"><Settings size={18} strokeWidth={1.6} /></Link>
</div>
<Nav />
<div className="hidden md:block mt-auto px-3 space-y-3">
<ThemeToggle />
<p className="text-[11px] text-muted leading-relaxed">broke is a personal project. Bank data comes from Plaid.</p>
</div>
</aside>
<div className="flex-1 min-w-0 md:py-3 md:pr-3">
<header className="px-4 md:px-6 py-4 md:pt-2"><PageTitle today={today} /></header>
<main className="@container bg-canvas md:rounded-3xl px-4 md:px-6 pt-6 pb-24 md:pb-6 min-h-[calc(100vh-80px)]"><SectionTabs cards={cards} />{children}</main>
</div>
</AssistantProvider>
</MoneyProvider>
);
}
+21
View File
@@ -0,0 +1,21 @@
// Shown instantly on navigation while the server loads the next page.
export default function Loading() {
const bar = "bg-line/70 rounded-full animate-pulse";
return (
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.4fr_1fr] items-start" aria-busy="true" aria-label="Loading">
{[0, 1].map((col) => (
<div key={col} className="space-y-6">
{[0, 1].map((i) => (
<div key={i} className="card p-6 space-y-4">
<div className={`${bar} h-4 w-32`} />
<div className={`${bar} h-8 w-24`} />
<div className={`${bar} h-3 w-full`} />
<div className={`${bar} h-3 w-5/6`} />
<div className={`${bar} h-3 w-2/3`} />
</div>
))}
</div>
))}
</div>
);
}
+35
View File
@@ -0,0 +1,35 @@
import { ChevronRight, Sparkles } from "lucide-react";
import Link from "next/link";
import { countryOf } from "@/lib/countries";
import { getUser } from "@/lib/data";
const PAGES = [
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
{ href: "/plan", label: "Money plan", what: "Every move broke found for you, in order." },
{ href: "/optimize", label: "Optimize", what: "Tax and savings ideas for your country." },
{ href: "/bonuses", label: "Bonuses", what: "Sign-up bonuses from banks and cards." },
{ href: "/cards", label: "Cards", what: "Your cards and which one to use." },
];
// Everything that isn't part of the three steps on Home.
export default async function More() {
const { user } = await getUser();
const cards = countryOf(user?.user_metadata?.profile?.country).cards;
return (
<div className="max-w-2xl space-y-4">
<section className="card overflow-hidden">
{PAGES.filter((p) => cards || p.href !== "/cards").map((p) => (
<Link key={p.href} href={p.href} prefetch className="row-hover flex items-center gap-3 px-6 py-4 border-b border-line last:border-0">
<span className="flex-1 min-w-0"><span className="block font-medium">{p.label}</span><span className="block text-sm text-muted">{p.what}</span></span>
<ChevronRight size={18} className="text-muted shrink-0" />
</Link>
))}
</section>
<Link href="/connect-ai" className="card-link flex items-center gap-3 px-6 py-4">
<Sparkles size={18} className="text-muted shrink-0" />
<span className="flex-1 font-medium">Connect your AI</span>
<ChevronRight size={18} className="text-muted shrink-0" />
</Link>
</div>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { HeartPulse, Landmark, PiggyBank, Receipt } from "lucide-react";
import { AskButton } from "@/components/Assistant";
import { Contributions } from "@/components/Contributions";
import { IdleCash } from "@/components/IdleCash";
import { MatchCheck } from "@/components/MatchCheck";
import { ProfileForm, type Profile } from "@/components/ProfileForm";
import { countryOf, type Country } from "@/lib/countries";
import { getUser } from "@/lib/data";
const SAVINGS = { icon: PiggyBank, title: "Savings", q: "How big should my emergency fund be given my spending, and where should I keep it?" };
const US_TOPICS = [
{ icon: Receipt, title: "Taxes", q: "Based on my profile and state, what are the biggest ways I could lower my taxes this year?" },
{ icon: HeartPulse, title: "HSA", q: "Am I eligible for an HSA, how much can I put in this year, and is it worth it for me?" },
{ icon: Landmark, title: "Retirement", q: "Am I getting my full 401(k) match, and should I be using a Roth IRA or traditional IRA?" },
SAVINGS,
];
// The local tax-advantaged accounts, by tax module.
const ACCOUNTS: Record<string, string> = { nz: "KiwiSaver", au: "super", uk: "ISA and pension", ca: "RRSP and TFSA", in: "PPF and NPS", ie: "pension" };
const topics = (c: Country) =>
c.tax === "us" ? US_TOPICS : [
{ icon: Receipt, title: "Taxes", q: `Based on my profile, what are the biggest ways I could lower my taxes in ${c.name} this year?` },
{ icon: Landmark, title: "Retirement", q: ACCOUNTS[c.tax]
? `How much should I put into my ${ACCOUNTS[c.tax]} this year, and am I getting everything my employer and the government add?`
: `Which tax-advantaged retirement or savings accounts can I use in ${c.name}, and how much should I put in?` },
SAVINGS,
];
export default async function Optimize() {
const { user } = await getUser();
const profile = (user?.user_metadata?.profile ?? {}) as Profile & { country?: string };
const country = countryOf(profile.country);
return (
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
<ProfileForm initial={profile} />
<div className="space-y-3">
<Contributions profile={profile} />
{country.tax === "us" && <MatchCheck />}
<IdleCash />
<div className="section-label px-1">Ask about one thing</div>
<section className="card overflow-hidden">
{topics(country).map(({ icon: Icon, title, q }) => (
<AskButton key={title} q={q} className="w-full flex items-start gap-4 px-5 py-4 border-b border-line last:border-0 text-left row-hover">
<span className="size-9 rounded-full bg-brand-soft text-brand grid place-items-center shrink-0"><Icon size={17} /></span>
<span>
<span className="block font-medium">{title}</span>
<span className="block text-sm text-muted">{q}</span>
</span>
</AskButton>
))}
</section>
<p className="text-xs text-muted px-1 leading-relaxed">
General education, not financial or tax advice. The AI checks current limits on the web, but confirm big decisions with a tax professional.
</p>
</div>
</div>
);
}
+150
View File
@@ -0,0 +1,150 @@
import { ChevronRight } from "lucide-react";
import Link from "next/link";
import { Suspense } from "react";
import { CategoryCheck, type Checks } from "@/components/CategoryCheck";
import { CountryBanner } from "@/components/CountryPicker";
import { EmptyBank } from "@/components/EmptyBank";
import { GoLiveCard } from "@/components/GoLiveCard";
import { Merchant } from "@/components/Merchant";
import { PayQuestion } from "@/components/PayQuestion";
import { SyncButton } from "@/components/PlaidButtons";
import { TxnList } from "@/components/TxnList";
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
import { deterministicMoves, ladder } from "@/lib/plan";
import { myPlanFacts } from "@/lib/plan-facts";
import { moneyPicture } from "@/lib/steps";
import { fetchChecks } from "@/lib/unsure";
// "Is this right?", collapsed to one line, only when a category waits to be checked. It streams, so it never holds the page.
async function HomeCheck({ checks }: { checks: Promise<Checks> }) {
const c = await checks;
return c.total > 0 ? <CategoryCheck initial={c} closed /> : null;
}
// One line pointing at the plan, or the one question broke needs answered. Streams in: the plan facts are the slow part.
async function NextStep({ profile }: { profile: Record<string, unknown> }) {
const facts = await myPlanFacts();
if (ladder(facts).spare == null) return <section className="card p-5 space-y-3"><p className="font-medium">What do you get paid?</p><PayQuestion profile={profile} /></section>;
const next = deterministicMoves(facts, money0)[0];
if (!next) return null;
return (
<Link href="/plan" className="card-link px-5 py-3.5 flex items-center gap-3">
<span className="text-sm text-muted shrink-0">Next</span>
<span className="flex-1 min-w-0 truncate">{next.title}</span>
<ChevronRight size={18} className="text-muted shrink-0" />
</Link>
);
}
// Home is for a glance: what you have, what went out this month, what's coming up, what you spent last.
// The working pages (Spending, Budgets, Money plan) are one click away.
export default async function Dashboard() {
const { supabase, user } = await getUser();
const uid = user!.id;
const profile = user?.user_metadata?.profile;
const now = await today(); // the user's date at UTC midnight: read it with getUTC* and ymd
const day = ymd(now), soon = ymd(new Date(now.getTime() + 14 * 864e5));
const checks = (fetchChecks(supabase, uid, day) as Promise<Checks>).catch(() => ({ rows: [], total: 0 })); // starts now, beside the queries below
// Own rows only: an account a partner shares is on the Accounts page, not in your totals.
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([
supabase.from("transactions").select(TXN_SELECT).eq("user_id", uid).order("date", { ascending: false }).order("id").limit(5),
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
supabase.rpc("fx_missing"),
supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4),
moneyByMonth(supabase, ymd(monthStart(now))),
categories(),
]);
if (!accounts?.length) return <EmptyBank />;
const txns = withAccountNames((recent ?? []) as unknown as Txn[]);
type Acct = { type: string; subtype: string | null };
const bal = (pred: (a: Acct) => boolean) => {
const list = accounts.filter((a) => a.included && pred(a));
return list.length ? list.reduce((s, a) => s + Number(a.current_balance ?? 0), 0) : null;
};
const owed = bal((a) => a.type === "credit" || a.type === "loan");
const tiles = [
{ label: "In your bank", value: bal((a) => a.type === "depository" && a.subtype !== "savings"), href: "/accounts" },
{ label: "Savings", value: bal((a) => a.type === "depository" && a.subtype === "savings"), href: "/accounts" },
{ label: "Investments", value: bal((a) => a.type === "investment"), href: "/accounts" },
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
].filter((t) => t.value != null);
const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
const monthName = dateLabel(day, { month: "long" });
return (
<div className="space-y-4 max-w-4xl">
<GoLiveCard country={profile?.country} userId={user?.id} />
{!profile?.country && <CountryBanner profile={profile ?? {}} />}
{!!noRate?.length && <p className="card px-5 py-3 text-sm text-muted">Totals leave out money in {(noRate as string[]).join(", ")}. No exchange rate is available for it.</p>}
<section className={`card overflow-hidden grid grid-cols-2 ${tiles.length >= 4 ? "@3xl:grid-cols-4" : tiles.length === 3 ? "@3xl:grid-cols-3" : ""}`}>
{tiles.map((t) => (
<Link key={t.label} href={t.href} className="row-hover p-5 space-y-1">
<span className="block text-sm text-muted">{t.label}</span>
<span className="block text-2xl font-semibold tabular tracking-[-0.02em]">{money0(t.value!)}</span>
</Link>
))}
</section>
<Suspense fallback={null}><NextStep profile={profile ?? {}} /></Suspense>
<Suspense fallback={null}><HomeCheck checks={checks} /></Suspense>
<div className="grid grid-cols-1 gap-4 @3xl:grid-cols-2 items-start">
<section className="card p-5 space-y-3">
<div className="flex items-baseline justify-between gap-3">
<span className="text-sm text-muted">Spent in {monthName}</span>
<Link href="/spending" className="text-sm text-muted hover:text-ink">See all</Link>
</div>
<p className="text-2xl font-semibold tabular tracking-[-0.02em]">{money0(pic.spent)}</p>
{pic.spent > 0 ? (
<>
<div className="flex h-2 gap-0.5 rounded-full overflow-hidden" aria-hidden>
{pic.slices.map((s) => <div key={s.label} style={{ width: `${(s.amount / pic.spent) * 100}%`, background: s.color }} />)}
</div>
<ul className="space-y-1.5 text-sm">
{pic.slices.slice(0, 3).map((s) => (
<li key={s.label} className="flex justify-between gap-3">
<span className="flex items-center gap-2 min-w-0"><span className="size-2 rounded-full shrink-0" style={{ background: s.color }} /><span className="truncate">{s.label}</span></span>
<span className="tabular text-muted">{money0(s.amount)}</span>
</li>
))}
</ul>
</>
) : <p className="text-sm text-muted">Nothing yet this month.</p>}
</section>
<section className="card p-5 space-y-3">
<div className="flex items-baseline justify-between gap-3">
<span className="text-sm text-muted">Coming up</span>
<Link href="/recurring" className="text-sm text-muted hover:text-ink">See all</Link>
</div>
{bills?.length ? (
<ul className="space-y-2.5">
{bills.map((b) => (
<li key={b.id as string} className="flex items-center gap-3 text-sm">
<Merchant name={b.merchant_name as string} logo={b.logo_url as string | null} />
<span className="flex-1 min-w-0 truncate">{(b.merchant_name as string).replace(/\s*\(\s*\)\s*$/, "")}</span>
<span className="text-muted shrink-0">{dateLabel(b.next_date as string, { month: "short", day: "numeric" })}</span>
<span className="tabular shrink-0 w-16 text-right">{money0(Number(b.average_amount))}</span>
</li>
))}
</ul>
) : <p className="text-sm text-muted">Nothing due in the next 2 weeks.</p>}
</section>
</div>
<section className="card overflow-hidden">
<div className="flex items-center justify-between gap-3 px-5 pt-5 pb-2">
<span className="text-sm text-muted">Latest spending</span>
<span className="flex items-center gap-4"><SyncButton subtle /><Link href="/transactions" className="text-sm text-muted hover:text-ink">See all</Link></span>
</div>
{txns.length ? <TxnList txns={txns} today={day} /> : <p className="px-5 pb-5 text-sm text-muted">No transactions yet. Press sync in a minute.</p>}
</section>
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { ChevronDown } from "lucide-react";
import { EmptyBank } from "@/components/EmptyBank";
import { NextMove } from "@/components/NextMove";
import { MoneyPlan, type PlanState } from "@/components/MoneyPlan";
import { PlanChat } from "@/components/PlanChat";
import { PlanContext } from "@/components/PlanContext";
import { PlanSummary } from "@/components/PlanSummary";
import { BillsOnCards } from "@/components/BillsOnCards";
import { Suspense } from "react";
import { countryOf } from "@/lib/countries";
import { getUser, today, typicalMonthly } from "@/lib/data";
import { money0, ymd } from "@/lib/format";
import { loadPlan, planFacts } from "@/lib/plan-facts";
import { laterOf, type Later } from "@/lib/projection";
import { marginalRate } from "@/lib/tax";
export default async function Plan() {
const { supabase, user } = await getUser();
const now = await today(); // the tz cookie, no database call
const [state, { count }, typical] = await Promise.all([
loadPlan(supabase, user!.id),
supabase.from("accounts").select("id", { count: "exact", head: true }).eq("user_id", user!.id),
typicalMonthly(supabase, user!.id, ymd(now)),
]);
if (!count) return <EmptyBank title="Your money plan" body="Link a bank and broke ai audits your bills, subscriptions, cards and cash for moves that save or earn money." />;
// The name drafts sign off with: the account's own name, else the start of the email ("sam.k@" -> "Sam").
const meta = user!.user_metadata ?? {};
const word = (user!.email ?? "").split("@")[0].match(/[a-z]+/i)?.[0] ?? "";
const name = (meta.full_name || meta.name || (word && word[0].toUpperCase() + word.slice(1)) || "[Your name]") as string;
// The payoff chart: the tax rate turns a contribution's tax saving back into the contribution (US only, like the tax moves).
// Possible later needs the full facts, so they load only when a live move is gated or a fund is still to build.
const profile = meta.profile ?? {};
const taxRate = countryOf(profile.country).code === "US" ? marginalRate(profile).rate : null;
const live = state.moves.filter((m) => m.status === "todo" || m.status === "doing");
let later: Later | null = null;
if (live.some((m) => m.gate || m.ref?.startsWith("fund:")))
later = await planFacts(supabase, user!.id, profile, ymd(now)).then((f) => laterOf(f, live), (e) => { console.error("[broke] payoff facts:", e); return null; });
// The savings rate, from the old For you page: the one thing on it the plan didn't already say.
const rate = typical && typical.income > 0 ? (typical.income - typical.spend) / typical.income : null;
return (
<>
{rate != null && (
<p className="text-sm text-muted mb-5 max-w-3xl">
In a typical month {money0(typical!.income)} comes in and {money0(typical!.spend)} goes out.{" "}
{rate >= 0 ? <>You save {Math.round(rate * 100)}% of it.</> : <span className="text-bad">That&apos;s {money0(typical!.spend - typical!.income)} more out than in.</span>}
</p>
)}
{/* One next move and a chat. The full plan is a click away for anyone who wants it. */}
<Suspense fallback={<section className="card p-6 h-72 mb-6" aria-busy="true" />}><div className="mb-6"><NextMove /></div></Suspense>
<div className="mb-6"><PlanChat /></div>
<details className="group">
<summary className="flex items-center gap-2 px-1 py-2 cursor-pointer list-none [&::-webkit-details-marker]:hidden font-medium">
<ChevronDown size={18} className="text-muted transition-transform group-open:rotate-180" /> See the full plan
</summary>
<div className="pt-4">
<Suspense fallback={<section className="card p-6 h-48 mb-6" aria-busy="true" />}><PlanSummary today={ymd(now)} /></Suspense>
<PlanContext initial={typeof profile.notes === "string" ? profile.notes : ""} />
<MoneyPlan initial={JSON.parse(JSON.stringify(state)) as PlanState} today={ymd(now)} name={name} payoff={{ rate: taxRate, later }} />
<Suspense fallback={<section className="card p-6 h-40 mt-6" aria-busy="true" />}><div className="mt-6"><BillsOnCards /></div></Suspense>
</div>
</details>
</>
);
}
+138
View File
@@ -0,0 +1,138 @@
import { EmptyBank } from "@/components/EmptyBank";
import Link from "next/link";
import { AskButton } from "@/components/Assistant";
import { BillAdvice, billName, CARD_NOTE, loadBills } from "@/components/BillsOnCards";
import { Merchant } from "@/components/Merchant";
import { CancelActions } from "@/components/CancelActions";
import { RecurringToggle } from "@/components/RecurringToggle";
import { SubscriptionAlerts } from "@/components/SubscriptionAlerts";
import { allRows, getUser, today as userToday } from "@/lib/data";
import { dayLabel, FREQ_LABEL, FREQ_PER_MONTH, money, plural, ymd } from "@/lib/format";
import { categoryOf, negotiable, subscriptionAlerts, type Charge } from "@/lib/subscriptions";
type Stream = {
id: string;
merchant_name: string;
frequency: string;
average_amount: number;
last_date: string | null;
next_date: string | null;
is_income: boolean;
active: boolean;
category: { key: string; label: string; color: string; icon: string } | null;
};
export default async function Recurring({ searchParams }: { searchParams: Promise<{ tab?: string }> }) {
const { tab } = await searchParams;
const all = tab === "all";
const { supabase, user } = await getUser();
const uid = user!.id;
const now = await userToday();
const today = ymd(now);
// Own streams and charges only; a partner's shared recurring charges are not yours to pay or cancel.
const { data, error } = await supabase
.from("recurring")
.select("id, merchant_name, frequency, average_amount:home_average, last_date, next_date, is_income, active, category:categories(key, label, color, icon)")
.eq("user_id", uid)
.neq("status", "TOMBSTONED")
.order("next_date", { ascending: true, nullsFirst: false });
if (error) throw new Error(error.message);
const streams = (data ?? []) as unknown as Stream[];
if (!streams.length) {
const { count } = await supabase.from("accounts").select("id", { count: "exact", head: true }).eq("user_id", uid).neq("type", "investment");
if (!count) return <EmptyBank title="See your subscriptions and bills" body="Link a bank and broke finds charges that repeat, what they cost a month and when each is due." />;
}
const since = ymd(new Date(now.getTime() - 400 * 864e5));
const [cardBills, logoRows, txns] = await Promise.all([
loadBills(),
streams.length
? allRows<{ merchant_name: string | null; logo_url: string }>((f, t) =>
supabase.from("transactions").select("merchant_name, logo_url").eq("user_id", uid).in("merchant_name", [...new Set(streams.map((s) => s.merchant_name))]).not("logo_url", "is", null).order("id").range(f, t))
: [],
allRows<Charge>((f, t) => supabase.from("transactions").select("merchant_name, name, amount, date, plaid_category").eq("user_id", uid).gt("amount", 0).gte("date", since).order("id").range(f, t)),
]);
const logos = new Map(logoRows.map((r) => [r.merchant_name, r.logo_url]));
const alerts = subscriptionAlerts(streams, txns);
const advice = new Map(cardBills.items.map((x) => [x.r.id, x]));
const switchable = cardBills.items.filter((x) => x.gainMine >= 1);
const cardGain = switchable.reduce((t, x) => t + x.gainMine, 0);
const ctx: RowCtx = { logos, txns, state: user?.user_metadata?.profile?.state, advice, money: cardBills.money };
const visible = streams.filter((s) => (all ? true : s.active && !s.is_income && (!s.next_date || s.next_date >= today)));
const isBill = (s: Stream) => s.category?.key === "RENT_AND_UTILITIES" || s.category?.key === "LOAN_PAYMENTS";
const subs = visible.filter((s) => !s.is_income && !isBill(s));
const bills = visible.filter((s) => !s.is_income && isBill(s));
const income = visible.filter((s) => s.is_income);
const monthly = streams.filter((s) => s.active && !s.is_income).reduce((t, b) => t + b.average_amount * (FREQ_PER_MONTH[b.frequency] ?? 0), 0);
return (
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
<div className="space-y-6">
<div className="pill-tabs">
<Link scroll={false} href="/recurring" className={`pill-tab !py-1 !px-3 ${all ? "" : "pill-tab-active"}`}>Upcoming</Link>
<Link scroll={false} href="/recurring?tab=all" className={`pill-tab !py-1 !px-3 ${all ? "pill-tab-active" : ""}`}>All recurring</Link>
</div>
<SubscriptionAlerts alerts={alerts} />
<Section ctx={ctx} title="Subscriptions" rows={subs} empty="You have no subscriptions yet. broke spots them after a charge repeats a few times." />
<Section ctx={ctx} title="Bills & Utilities" rows={bills} empty="You have no bills & utilities yet." />
{all && <Section ctx={ctx} title="Income" rows={income} empty="No recurring income found yet." />}
</div>
<div className="space-y-6">
<section className="card p-6">
<div className="section-label">Per month</div>
<div className="figure mt-2">{money(monthly)}</div>
<p className="text-sm text-muted mt-1">across {plural(streams.filter((s) => s.active && !s.is_income).length, "recurring charge")}</p>
</section>
{cardBills.country.cards && !!cardBills.items.length && (
<section className="card p-6 space-y-2">
<div className="section-label">Earn more on these</div>
{cardGain >= 1
? <p>Paying {switchable.length === 1 ? "one of these" : `${switchable.length} of these`} with a card you already have earns about <span className="font-medium tabular">{cardBills.money(cardGain)} a year</span> back.</p>
: <p>Nothing to switch to a card you already have.</p>}
<p className="text-xs text-muted">{CARD_NOTE}</p>
</section>
)}
<section className="rounded-3xl bg-plum text-white border border-white/10 p-6 space-y-3">
<div className="text-lg font-semibold">Looking to cancel a subscription?</div>
<p className="text-sm text-white/75">Ask broke AI which ones you barely use and how to cancel each one.</p>
<AskButton q="Which of my subscriptions should I cancel, and how do I cancel each one?" className="inline-block bg-white text-plum rounded-full px-5 py-2 text-sm font-medium">Ask broke AI</AskButton>
</section>
</div>
</div>
);
}
type RowCtx = { logos: Map<string | null, string>; txns: Charge[]; state?: string; advice: Map<string, Parameters<typeof BillAdvice>[0]["item"]>; money: (n: number) => string };
function Section({ title, rows, empty, ctx: { logos, txns, state, advice, money: money0 } }: { title: string; rows: Stream[]; empty: string; ctx: RowCtx }) {
return (
<div className="space-y-3">
<div className="section-label px-1">{title}</div>
<section className="card overflow-hidden">
{rows.length ? (
rows.map((s) => (
<div key={s.id} className={`row-hover flex flex-wrap items-center gap-x-4 gap-y-2 px-6 py-4 border-b border-line last:border-0 ${s.active ? "" : "opacity-50"}`}>
<Merchant name={s.merchant_name} logo={logos.get(s.merchant_name)} color={s.category?.color} icon={s.category?.icon} />
<div className="flex-1 min-w-0">
<div className="truncate font-medium">{billName(s.merchant_name)}</div>
<div className="text-xs text-muted">
{FREQ_LABEL[s.frequency] ?? s.frequency}
{s.next_date ? ` · next ${dayLabel(s.next_date)}` : s.last_date ? ` · last ${dayLabel(s.last_date)}` : ""}
</div>
{advice.has(s.id) && <div className="mt-1"><BillAdvice item={advice.get(s.id)!} money={money0} /></div>}
</div>
<span className={`tabular font-medium ${s.is_income ? "text-good" : ""}`}>{money(s.average_amount)}</span>
<div className="flex gap-2 justify-end basis-full @xl:basis-auto">
{!s.is_income && <CancelActions stream={s} kind={negotiable(s.merchant_name, categoryOf(s, txns))} state={state} />}
<RecurringToggle id={s.id} active={s.active} />
</div>
</div>
))
) : (
<p className="px-6 py-5 text-sm text-muted">{empty}</p>
)}
</section>
</div>
);
}
+637
View File
@@ -0,0 +1,637 @@
"use client";
import { Wrench, Bot, Check, CircleAlert, X, Database, Landmark, Link2, Palette, RefreshCw, SlidersHorizontal, User, type LucideIcon } from "lucide-react";
import Link from "next/link";
import { ClearTestData, RemoveTest } from "@/components/ClearTestData";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { modelOptions, saveChoice } from "@/components/Assistant";
import { CountryField } from "@/components/CountryPicker";
import { Dropdown } from "@/components/Dropdown";
import { Modal } from "@/components/Modal";
import { ThemeToggle } from "@/components/Nav";
import { SignOut } from "@/components/SignOut";
import { countryOf } from "@/lib/countries";
import { bandLabel, creditOf, monthText } from "@/lib/credit";
import { decode, encode, isSmall, QUALITY_NOTE, type ModelChoice } from "@/lib/llm/models";
import { AI_MODES, type AiMode } from "@/lib/privacy";
import type { Section, SetupStatus } from "@/lib/setup";
import { createClient, updateMeta } from "@/utils/supabase/client";
import { Body, ExtLink } from "../../setup/SetupChecklist";
import { Segmented } from "../../setup/SetupActions";
type Group = "profile" | "banks" | "database" | "ai" | "referrals" | "appearance" | "advanced" | "improve";
type Mode = "sandbox" | "production";
type Profile = Record<string, unknown> & { country?: string; currency?: string };
const NAV: { id: Group; label: string; icon: LucideIcon; what: string }[] = [
{ id: "profile", label: "Profile", icon: User, what: "Your account, country and money profile." },
{ id: "banks", label: "Banks", icon: Landmark, what: "Where broke reads your accounts and transactions from." },
{ id: "database", label: "Database", icon: Database, what: "Supabase stores sign-ins and keeps each person's data private." },
{ id: "ai", label: "AI assistant", icon: Bot, what: "What answers when you ask broke about your money." },
{ id: "referrals", label: "Referral links", icon: Link2, what: "Your own links for the Cards page." },
{ id: "appearance", label: "Appearance", icon: Palette, what: "How broke looks on this device." },
{ id: "advanced", label: "Advanced", icon: SlidersHorizontal, what: "Local model, Claude Code and testing shortcuts." },
{ id: "improve", label: "Improve broke", icon: Wrench, what: "broke is yours to change. Your AI app can do the coding." },
];
// Which settings page each /setup section belongs on. Sections added later land by what they're about.
const PLACE: Record<string, Group> = { supabase: "database", database: "database", plaid: "banks", akahu: "banks", enablebanking: "banks", basiq: "banks", belvo: "banks", ai: "ai", referrals: "referrals", local: "advanced", mcp: "advanced", devlogin: "advanced" };
const groupOf = (s: Section): Group => PLACE[s.id] ?? (/bank/i.test(`${s.title} ${s.what}`) ? "banks" : "advanced");
// Server setup (keys, database, model, testing shortcuts). Only shown on the machine that runs broke.
const SERVER: Group[] = ["banks", "database", "referrals", "advanced"];
const attention = (s: Section) => s.status === "error" || (s.status === "todo" && s.kind !== "more");
export function Settings({ signedIn, local, folder, repo, email, profile, mode, testItems, message, aiMode }: { signedIn: boolean; local: boolean; folder: string; repo: string | null; email: string; profile: Profile; mode: Mode; testItems: { id: string; name: string }[]; message?: string; aiMode: AiMode }) {
const [group, setGroup] = useState<Group>("profile");
const [data, setData] = useState<SetupStatus | null>(null);
const [failed, setFailed] = useState(false);
const [checking, setChecking] = useState(true);
const load = useCallback(async () => {
setChecking(true);
try {
const res = await fetch("/api/setup/status", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
setData((await res.json()) as SetupStatus);
setFailed(false);
} catch {
setFailed(true);
}
setChecking(false);
}, []);
useEffect(() => {
if (local) load();
else setChecking(false);
const fromHash = () => {
const h = location.hash.slice(1) as Group;
if (NAV.some((n) => n.id === h) && (local || !SERVER.includes(h) || h === "banks")) setGroup(h);
};
fromHash();
addEventListener("hashchange", fromHash);
return () => removeEventListener("hashchange", fromHash);
}, [load, local]);
// Which bank options show depends on the profile, so opening Banks after saving it picks up the change.
useEffect(() => {
if (local && group === "banks") load();
}, [group, local, load]);
const nav = local ? NAV : NAV.filter((n) => !SERVER.includes(n.id) || n.id === "banks");
const sections = (data?.sections ?? []).filter((s) => groupOf(s) === group);
const flagged = (g: Group) => (data?.sections ?? []).some((s) => groupOf(s) === g && attention(s));
const here = NAV.find((n) => n.id === group)!;
const pick = (g: Group) => {
setGroup(g);
history.replaceState(null, "", `#${g}`);
};
return (
<div className="md:grid md:grid-cols-[200px_minmax(0,1fr)] md:gap-8 max-w-5xl">
<nav aria-label="Settings" className="-mx-4 px-4 md:mx-0 md:px-0 mb-5 md:mb-0 flex md:flex-col gap-1 overflow-x-auto md:overflow-visible md:sticky md:top-6 md:self-start [scrollbar-width:none]">
{nav.map(({ id, label, icon: Icon }) => (
<button
key={id}
onClick={() => pick(id)}
aria-current={group === id ? "page" : undefined}
className={`shrink-0 flex items-center gap-2.5 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap transition-colors ${group === id ? "bg-surface text-ink font-medium shadow-[var(--shadow-card)]" : "text-ink/70 hover:text-ink hover:bg-[var(--hover)]"}`}
>
<Icon size={17} strokeWidth={group === id ? 2 : 1.6} className="hidden md:block" />
<span className="md:flex-1 text-left">{label}</span>
{flagged(id) && <span className="size-1.5 rounded-full bg-bad" aria-label="Needs attention" />}
</button>
))}
</nav>
<div className="space-y-4 min-w-0">
<div className="flex items-start justify-between gap-4">
<div>
<h2 className="text-lg font-semibold tracking-[-0.01em]">{here.label}</h2>
<p className="text-sm text-muted">{here.what}</p>
</div>
{local && (
<button className="text-sm text-muted hover:text-ink inline-flex items-center gap-1.5 shrink-0 pt-1" disabled={checking} onClick={load}>
<RefreshCw size={14} className={checking ? "animate-spin" : ""} /> {checking ? "Checking" : "Check again"}
</button>
)}
</div>
{message && <p role="status" className="text-sm">{message}</p>}
{failed && <p className="text-sm text-bad">Couldn&apos;t check what&apos;s connected. Is broke still running?</p>}
{group === "profile" && <ProfileCards email={email} profile={profile} />}
{group === "appearance" && (
<Card title="Theme" what="System follows your device. Saved in this browser.">
<ThemeToggle />
</Card>
)}
{group === "improve" && <ImproveCard folder={folder} repo={repo} />}
{group === "ai" && <AiDataCard initial={aiMode} />}
{group === "ai" && <ModelCard />}
{!local && (SERVER.includes(group) || group === "ai") && (
<Card title="Managed by the server owner" what="Bank keys, the database and the AI model are set up on the computer that runs broke. Open broke there to change them." />
)}
{local && !data && !failed && !["profile", "appearance", "improve"].includes(group) && <div className="card h-40 animate-pulse" aria-busy="true" />}
{group === "banks" && testItems.length > 0 && (
<div id="test-data">
<Card title="Test data" what="Plaid's made-up banks and everything worked out from them. Delete them before you rely on your real numbers.">
<ClearTestData items={testItems} />
</Card>
</div>
)}
{data && sections.map((s) =>
s.id === "plaid" ? (
<PlaidCard key={s.id} s={s} data={data} signedIn={signedIn} reload={load} initialMode={mode} testItems={testItems} />
) : (
<Card key={s.id} title={s.title} what={s.what} s={s}>
<Body s={s} data={data} signedIn={signedIn} reload={load} />
</Card>
),
)}
</div>
</div>
);
}
function StatusPill({ s }: { s: Section }) {
if (s.status === "done") return <span className="text-xs font-medium text-good inline-flex items-center gap-1 shrink-0"><Check size={13} /> {s.kind === "more" ? "On" : "Connected"}</span>;
if (s.status === "error") return <span className="text-xs font-medium text-bad inline-flex items-center gap-1 shrink-0"><CircleAlert size={13} /> Needs attention</span>;
return <span className="text-xs text-muted shrink-0">{s.status === "optional" ? "Optional" : "Not set up"}</span>;
}
function Card({ title, what, s, children }: { title: string; what?: string; s?: Section; children?: React.ReactNode }) {
const note = s && (s.status === "done" || s.status === "error") && s.kind !== "more" ? s.note : undefined;
return (
<section className="card p-6 space-y-4">
<div className="space-y-1">
<div className="flex items-center justify-between gap-3">
<h3 className="font-semibold">{title}</h3>
{s && <StatusPill s={s} />}
</div>
{what && <p className="text-sm text-muted">{what}</p>}
{note && <p className={`text-sm ${s?.status === "error" ? "text-bad" : ""}`}>{note}</p>}
</div>
{children}
</section>
);
}
function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
const router = useRouter();
const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency };
const [c, setC] = useState(start);
const [msg, setMsg] = useState("");
const dirty = c.country !== start.country || c.currency !== start.currency;
const credit = creditOf(profile);
async function save() {
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, ...c } } });
setMsg(error ? "Couldn't save that. Try again." : "Saved.");
if (!error) router.refresh();
}
return (
<>
<Card title="Account">
<div className="flex items-center justify-between gap-3">
<span className="text-sm truncate">{email}</span>
<SignOut />
</div>
</Card>
<Card title="Country and currency" what="Sets your currency, which banks you can link and which tax tips apply.">
<div className="max-w-sm">
<CountryField country={c.country} currency={c.currency} onChange={(country, currency) => (setC({ country, currency }), setMsg(""))} />
</div>
<div className="flex items-center gap-3">
<button className="btn-primary" disabled={!dirty} onClick={save}>Save</button>
{msg && <span className="text-sm text-muted">{msg}</span>}
</div>
</Card>
<Card title="Money profile" what="Filing status, income, goals and more. Ask broke and Optimize use it to tailor advice.">
<Link href="/optimize#profile" className="btn inline-block">Edit money profile</Link>
</Card>
<Card title="Credit range" what="Picks which cards fit you on the Cards page. You choose it; broke doesn't pull your credit.">
<p className="text-sm">
{bandLabel(credit?.band) ?? "Not set"}
{credit?.asOf && <span className="text-muted"> · Last checked {monthText(credit.asOf)}</span>}
</p>
<Link href="/optimize#profile" className="btn inline-block">Edit in money profile</Link>
</Card>
<Card title="Transaction rules" what="Change categories, names and more on matching transactions.">
<Link href="/transactions/rules" className="btn inline-block">Manage rules</Link>
</Card>
</>
);
}
type ModelsReply = { providers: Parameters<typeof modelOptions>[0]; choice: ModelChoice | null };
// "Model": which model answers chat, check-ins and the money plan. The same saved choice as the chat header's picker.
function ModelCard() {
const [data, setData] = useState<ModelsReply | null>(null);
const [choice, setChoice] = useState<ModelChoice>({ provider: "claude", model: null });
const [msg, setMsg] = useState("");
useEffect(() => {
fetch("/api/models")
.then((r) => (r.ok ? r.json() : { providers: [], choice: null }))
.then((b: ModelsReply) => {
setData(b);
if (b.choice) setChoice(b.choice);
})
.catch(() => setData({ providers: [], choice: null }));
}, []);
async function pick(v: string) {
const before = choice, c = decode(v);
setChoice(c);
setMsg("");
const { error } = await saveChoice(c);
if (error) {
setChoice(before);
return setMsg("Couldn't save that. Try again.");
}
setMsg("Saved.");
}
const current = data?.providers.find((p) => p.id === choice.provider);
return (
<Card title="Model" what="Which model answers in chat, weekly check-ins and the money plan. Cloud models still get a summary only.">
{!data ? (
<div className="h-10 max-w-sm rounded-xl bg-canvas animate-pulse" aria-busy="true" />
) : (
<div className="max-w-sm">
<Dropdown label="Model" value={encode(choice)} onChange={pick} options={modelOptions(data.providers)} />
<Link href="/connect-ai" className="text-sm underline underline-offset-4">Connect your AI</Link>
</div>
)}
{current && !current.ready && <p className="text-sm text-muted">{(current.reason ?? `${current.label} isn't set up`).replace(/[.!]?$/, ".")} Until it is, broke uses the first model that is ready.</p>}
{current?.ready && isSmall(choice.provider, choice.model) && <p className="text-sm">{QUALITY_NOTE}</p>}
{msg && <p role="status" className="text-sm text-muted">{msg}</p>}
</Card>
);
}
// "AI and your data": Off, Summary only (default) or On this Mac only. Saved to the user's metadata as ai_mode.
function AiDataCard({ initial }: { initial: AiMode }) {
const router = useRouter();
const [mode, setMode] = useState(initial);
const [msg, setMsg] = useState("");
const [localReady, setLocalReady] = useState<boolean | null>(null);
const [seeing, setSeeing] = useState(false);
useEffect(() => {
fetch("/api/models")
.then((r) => (r.ok ? r.json() : { providers: [] }))
.then((b: { providers?: { id: string; ready: boolean }[] }) => setLocalReady(!!b.providers?.find((p) => p.id === "local")?.ready))
.catch(() => setLocalReady(false));
}, []);
async function pick(m: AiMode) {
if (m === mode) return;
const before = mode;
setMode(m);
setMsg("");
const { error } = await updateMeta(createClient(), { data: { ai_mode: m } });
if (error) {
setMode(before);
return setMsg("Couldn't save that. Try again.");
}
setMsg("Saved.");
router.refresh();
}
return (
<Card title="AI and your data" what="Choose what broke ai can see. This covers chat, weekly check-ins and the money plan.">
<div role="radiogroup" aria-label="AI and your data" className="space-y-2">
{AI_MODES.map((o) => {
const blocked = o.value === "local" && localReady === false && mode !== "local";
const on = mode === o.value;
return (
<button
key={o.value}
type="button"
role="radio"
aria-checked={on}
disabled={blocked}
onClick={() => pick(o.value)}
className={`w-full flex items-start gap-3 text-left rounded-2xl border px-4 py-3 transition-colors disabled:cursor-not-allowed ${on ? "border-ink bg-canvas" : "border-line hover:bg-[var(--hover)]"} ${blocked ? "opacity-60 hover:bg-transparent" : ""}`}
>
<span className={`mt-0.5 size-4 rounded-full border shrink-0 grid place-items-center ${on ? "border-ink" : "border-muted/60"}`}>{on && <span className="size-2 rounded-full bg-ink" />}</span>
<span className="min-w-0 space-y-0.5">
<span className="block text-sm font-medium">{o.label}{o.value === "summary" && <span className="font-normal text-muted"> (default)</span>}</span>
<span className="block text-sm text-muted">{o.what}</span>
</span>
</button>
);
})}
</div>
{localReady === false && (
<p className="text-sm text-muted">On this Mac only needs a local model, and none is set up. <a href="#advanced" className="underline underline-offset-2 text-ink">Set up a local model</a></p>
)}
<p className="text-sm text-muted">In a summary, amounts are rounded: to the nearest 5 under 100, the nearest 10 up to 1,000, and the nearest 100 above that. Dates show the month only.</p>
<div className="flex flex-wrap items-center gap-3">
<button type="button" className="btn" onClick={() => setSeeing(true)}>What the AI sees</button>
{msg && <span role="status" className="text-sm text-muted">{msg}</span>}
</div>
{seeing && <SeesModal onClose={() => setSeeing(false)} />}
</Card>
);
}
type Seen = { tool: string; input: Record<string, unknown>; result: unknown };
const SEEN_LABEL: Record<string, string> = {
get_profile: "Money profile", spending_summary: "Spending, last 3 months", list_recurring: "Recurring charges", list_accounts: "Accounts",
list_holdings: "Investments", safe_to_spend: "Safe to spend", subscription_alerts: "Price rises and overlaps",
};
type Obj = Record<string, unknown>;
const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v);
const words = (k: string) => (k.replace(/_/g, " ").replace(/^./, (c) => c.toUpperCase()));
// The exact summary a cloud model gets for this user right now, from /api/privacy (real data, summarised).
// Shown as readable sections; "Show raw" gives the JSON the model reads.
function SeesModal({ onClose }: { onClose: () => void }) {
const [seen, setSeen] = useState<Seen[] | null>(null);
const [failed, setFailed] = useState(false);
const [raw, setRaw] = useState(false);
useEffect(() => {
fetch("/api/privacy", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : Promise.reject()))
.then((b: { tools: Seen[] }) => setSeen(b.tools))
.catch(() => setFailed(true));
}, []);
const profile = seen?.find((s) => s.tool === "get_profile")?.result;
const currency = (typeof profile === "string" && /currency ([A-Z]{3})/.exec(profile)?.[1]) || "USD";
const money = (n: unknown) => (typeof n === "number" ? `about ${new Intl.NumberFormat("en-US", { style: "currency", currency, maximumFractionDigits: 0 }).format(n)}` : "none");
return (
<Modal label="What the AI sees" onClose={onClose} className="md:!max-w-2xl space-y-5">
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
<h3 className="card-title">What the AI sees</h3>
<p className="text-sm text-muted">This is what a cloud model gets when it looks up your money, built from your data right now. Placeholders like ⟨M1⟩ stay on this Mac, and broke puts the real names back in the reply.</p>
</div>
<button type="button" onClick={onClose} aria-label="Close" className="grid place-items-center size-8 rounded-full text-muted hover:text-ink hover:bg-[var(--hover)] shrink-0" data-autofocus>
<X size={17} />
</button>
</div>
{failed && <p className="text-sm text-bad">Couldn&apos;t build the summary. Try again.</p>}
{!seen && !failed && <div className="h-40 rounded-2xl bg-canvas animate-pulse" aria-busy="true" />}
{seen && (
<div className="flex">
<button type="button" className="btn !py-1.5 text-sm" aria-pressed={raw} onClick={() => setRaw((r) => !r)}>{raw ? "Show summary" : "Show raw"}</button>
</div>
)}
{seen?.map((s) => (
<section key={s.tool} className="space-y-2">
<h4 className="section-label">{SEEN_LABEL[s.tool] ?? words(s.tool)}</h4>
{raw ? (
<pre className="rounded-2xl bg-canvas p-3 text-xs font-mono whitespace-pre-wrap break-words max-h-64 overflow-y-auto">{typeof s.result === "string" ? s.result : JSON.stringify(s.result, null, 2)}</pre>
) : (
<SeenPart tool={s.tool} result={s.result} money={money} />
)}
</section>
))}
</Modal>
);
}
const Rows = ({ rows }: { rows: [React.ReactNode, React.ReactNode][] }) =>
rows.length ? (
<ul className="rounded-2xl bg-canvas divide-y divide-line text-sm">
{rows.map(([a, b], i) => (
<li key={i} className="flex items-baseline justify-between gap-3 px-3 py-2">
<span className="min-w-0 break-words">{a}</span>
<span className="text-muted text-right shrink-0 tabular">{b}</span>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted">Nothing here yet.</p>
);
function SeenPart({ tool, result, money }: { tool: string; result: unknown; money: (n: unknown) => string }) {
if (typeof result === "string") return <p className="rounded-2xl bg-canvas p-3 text-sm whitespace-pre-wrap">{result.replace(/^- /gm, "")}</p>;
if (isObj(result) && typeof result.error === "string") return <p className="text-sm text-bad">{result.error}</p>;
if (tool === "spending_summary" && isObj(result)) {
const months = (result.months as Obj[]) ?? [];
const cats = [...new Set(months.flatMap((m) => Object.keys((m.by_category as Obj) ?? {})))];
const merchants = (result.top_merchants as Obj[]) ?? [];
return (
<div className="space-y-3">
<p className="text-sm font-medium">Months</p>
<Rows rows={months.map((m) => [String(m.month), `spent ${money(m.spent)}, received ${money(m.received)}, ${m.purchases} purchases`])} />
<p className="text-sm font-medium">Categories</p>
<div className="rounded-2xl bg-canvas overflow-x-auto">
<table className="w-full text-sm">
<thead><tr className="text-muted text-left"><th className="font-normal px-3 py-2">Category</th>{months.map((m) => <th key={String(m.month)} className="font-normal px-3 py-2 text-right tabular">{String(m.month)}</th>)}</tr></thead>
<tbody className="divide-y divide-line">
{cats.map((c) => (
<tr key={c}><td className="px-3 py-2">{c}</td>{months.map((m) => <td key={String(m.month)} className="px-3 py-2 text-right text-muted tabular whitespace-nowrap">{(m.by_category as Obj)?.[c] == null ? "" : money((m.by_category as Obj)[c])}</td>)}</tr>
))}
</tbody>
</table>
</div>
<p className="text-sm font-medium">Top merchants, as placeholders</p>
<Rows rows={merchants.map((m) => [m.bank_event ? <>{String(m.bank_event)} <span className="text-muted">(bank event)</span></> : <span className="font-mono">{String(m.merchant)}</span>, `${money(m.total)} · ${m.count}x`])} />
</div>
);
}
if (tool === "list_recurring" && Array.isArray(result))
return <Rows rows={(result as Obj[]).map((r) => [<><span className="font-mono">{String(r.name)}</span> <span className="text-muted">{String(r.what ?? "")}</span></>, r.next_month ? `next ${r.next_month}` : r.active === false ? "stopped" : ""])} />;
if (tool === "list_accounts" && Array.isArray(result))
return <Rows rows={(result as Obj[]).map((a) => [<><span className="font-mono">{String(a.account)}</span> <span className="text-muted">{String(a.subtype ?? a.type ?? "")}</span></>, [`balance ${money(a.balance)}`, a.available != null && `available ${money(a.available)}`, a.credit_limit != null && `limit ${money(a.credit_limit)}`].filter(Boolean).join(", ")])} />;
if (tool === "list_holdings" && Array.isArray(result))
return <Rows rows={(result as Obj[]).map((h) => [String(h.group), `${h.holdings} holdings, ${money(h.value)}, gain ${money(h.gain)}`])} />;
return <Generic v={result} money={money} />;
}
// Anything else: one row per field, lists one row per item. Numbers are rounded money unless the name says otherwise.
function Generic({ v, money }: { v: unknown; money: (n: unknown) => string }) {
const show = (k: string, x: unknown): string =>
x == null ? "none" : typeof x === "number" ? (/pct|apy|ratio|rate|count|year|months|days/i.test(k) ? String(x) : money(x)) : typeof x === "boolean" ? (x ? "yes" : "no")
: Array.isArray(x) ? (x.length ? x.map((y) => (isObj(y) ? Object.entries(y).map(([a, b]) => `${words(a).toLowerCase()} ${show(a, b)}`).join(", ") : show(k, y))).join("; ") : "none")
: isObj(x) ? Object.entries(x).map(([a, b]) => `${words(a).toLowerCase()} ${show(a, b)}`).join(", ") : String(x);
if (Array.isArray(v)) return <Rows rows={v.map((x, i) => [show("", x), String(i + 1)])} />;
if (!isObj(v)) return <p className="text-sm">{show("", v)}</p>;
return <Rows rows={Object.entries(v).map(([k, x]) => [words(k), show(k, x)])} />;
}
type Check = { ok: boolean; message: string } | null;
// Plaid, with the mode up front: test (sandbox) or live (production), and the steps to go live.
function PlaidCard({ s, data, signedIn, reload, initialMode, testItems }: { s: Section; data: SetupStatus; signedIn: boolean; reload: () => void; initialMode: Mode; testItems: { id: string; name: string }[] }) {
const [mode, setMode] = useState<Mode>(initialMode);
const [want, setWant] = useState<Mode>(initialMode);
const live = mode === "production";
const keys: Section = { ...s, fields: s.fields?.filter((f) => f.key !== "PLAID_ENV"), steps: live ? undefined : s.steps };
return (
<Card title="Plaid" what="Links US and Canadian banks so broke can read balances and transactions." s={s}>
<div className="rounded-2xl bg-canvas p-4 space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5">
<span className={`size-2.5 rounded-full ${live ? "bg-good" : "bg-brand"}`} />
<span className="font-medium">{live ? "Live: real banks" : "Test mode: sandbox banks only"}</span>
</div>
<Segmented label="Bank mode" value={want} onChange={(v) => setWant(v as Mode)} options={[{ value: "sandbox", label: "Test banks" }, { value: "production", label: "Real banks" }]} />
</div>
<p className="text-sm text-muted">
{live ? "Plaid connects to your real bank accounts." : <>Plaid only shows made-up test banks. Nothing here touches a real account. <Link href="/go-live" className="text-ink underline underline-offset-2">Step by step to real banks</Link></>}
</p>
</div>
{want !== mode && (
<SwitchMode
to={want}
canWrite={data.canWrite}
writeNote={data.writeNote}
testItems={testItems}
onCancel={() => setWant(mode)}
onSwitched={() => {
setMode(want);
reload();
}}
/>
)}
<div className="space-y-3 pt-1">
<h4 className="text-sm font-medium">Keys</h4>
<Body s={keys} data={data} signedIn={signedIn} reload={reload} />
</div>
</Card>
);
}
const PLAID = {
launch: "https://dashboard.plaid.com/developers/launch-center",
request: "https://dashboard.plaid.com/overview/request-products",
useCase: "https://dashboard.plaid.com/link/data-transparency-v5",
keys: "https://dashboard.plaid.com/developers/keys",
billing: "https://plaid.com/docs/account/billing/",
trial: "https://plaid.com/docs/account/billing/#trial-plans",
};
function SwitchMode({ to, canWrite, writeNote, testItems, onCancel, onSwitched }: { to: Mode; canWrite: boolean; writeNote?: string; testItems: { id: string; name: string }[]; onCancel: () => void; onSwitched: () => void }) {
const router = useRouter();
const [secret, setSecret] = useState("");
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<{ ok: boolean; text: string } | null>(null);
const live = to === "production";
const name = live ? "Production" : "Sandbox";
// Test first, save only if Plaid accepts: a wrong secret never replaces a working one.
async function go() {
setBusy(true);
setResult(null);
const values: Record<string, string> = { PLAID_ENV: to, ...(secret.trim() ? { PLAID_SECRET: secret.trim() } : {}) };
const post = (test: boolean) => fetch("/api/setup/env", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ values, test }) }).then(async (r) => ({ ok: r.ok, body: (await r.json().catch(() => ({}))) as { error?: string; errors?: Record<string, string>; checks?: { plaid?: Check }; restart?: boolean } }));
try {
const t = await post(true);
const fail = t.body.errors ? Object.values(t.body.errors)[0] : !t.ok ? t.body.error ?? "Couldn't check." : !t.body.checks?.plaid ? "Add your client ID first." : !t.body.checks.plaid.ok ? `${t.body.checks.plaid.message} Nothing was changed.` : null;
if (fail) return setResult({ ok: false, text: fail });
const r = await post(false);
const check = r.body.checks?.plaid;
if (!r.ok || !check?.ok) return setResult({ ok: false, text: r.body.error ?? check?.message ?? "Couldn't save." });
setResult({ ok: true, text: r.body.restart ? `${check.message} Restart broke to finish.` : check.message });
setSecret("");
router.refresh();
onSwitched();
} catch {
setResult({ ok: false, text: "Couldn't reach broke. Is it still running?" });
} finally {
setBusy(false);
}
}
const steps: { title: string; body: React.ReactNode }[] = live
? [
{
title: "Get Plaid's approval for real banks",
body: (
<>
In the Plaid Dashboard, open the <ExtLink href={PLAID.launch}>Launch Center</ExtLink> and request Production access. Plaid asks about your company and how you use the data, and reviews it before Production turns on. US and Canadian banks also need a <ExtLink href={PLAID.useCase}>use case picked</ExtLink>.
<span className="block mt-1.5 text-muted">
Real banks are billed by Plaid: Transactions and Investments are a monthly fee per connected bank, and test mode is always free. New US and Canadian teams can start on the free <ExtLink href={PLAID.trial}>Trial plan</ExtLink> (up to 10 real connections). <ExtLink href={PLAID.billing}>How Plaid bills</ExtLink>
</span>
</>
),
},
{
title: "Paste your Production secret",
body: <>It&apos;s under Production on <ExtLink href={PLAID.keys}>Developers → Keys</ExtLink>. It&apos;s a different secret from Sandbox. Your client ID stays the same.</>,
},
{
title: "Remove test connections",
body: testItems.length ? <RemoveTest items={testItems} intro="Test connections stop working in live mode." /> : <span className="text-muted">No test connections to remove.</span>,
},
]
: [
{ title: "Real connections pause", body: "Real banks stop syncing in test mode. They pick up again when you switch back." },
{ title: "Paste your Sandbox secret", body: <>Under Sandbox on <ExtLink href={PLAID.keys}>Developers → Keys</ExtLink>. Leave it empty to try the saved secret.</> },
];
return (
<div className="rounded-2xl border border-line p-4 md:p-5 space-y-4">
<h4 className="font-medium">{live ? "Switch to real banks" : "Switch back to test banks"}</h4>
<ol className="space-y-4">
{steps.map((st, i) => (
<li key={i} className="flex gap-3 text-sm">
<span className="size-6 rounded-full border border-line text-xs text-muted grid place-items-center shrink-0 tabular">{i + 1}</span>
<div className="flex-1 min-w-0 space-y-2 pt-0.5">
<div className="font-medium">{st.title}</div>
<div>{st.body}</div>
{i === 1 && canWrite && (
<input
type="password"
autoComplete="off"
spellCheck={false}
value={secret}
onChange={(e) => setSecret(e.target.value)}
placeholder={`${name} secret (30 letters and numbers)`}
aria-label={`${name} secret`}
className="select font-mono !text-[13px] max-w-md"
/>
)}
</div>
</li>
))}
</ol>
{canWrite ? (
<div className="flex flex-wrap items-center gap-3">
<button className="btn-primary" disabled={busy || (live && !secret.trim())} onClick={go}>
{busy ? "Checking with Plaid…" : live ? "Check and switch to real banks" : "Check and switch to test banks"}
</button>
<button className="text-sm text-muted hover:text-ink" onClick={onCancel}>Cancel</button>
{result && <span className={`text-sm ${result.ok ? "text-good" : "text-bad"}`}>{result.text}</span>}
</div>
) : (
<p className="text-sm text-muted">{writeNote}</p>
)}
</div>
);
}
function ImproveCard({ folder, repo }: { folder: string; repo: string | null }) {
const line = "block font-mono text-[13px] rounded-lg border border-line px-3 py-2 break-all";
const github = repo ? `https://github.com/${repo}` : null;
if (!folder) return (
<>
<Card title="Get the latest broke" what="No Terminal needed. Your changes stay, and your site rebuilds by itself.">
<ol className="space-y-2 text-sm list-decimal pl-5">
<li>{github ? <a className="underline underline-offset-2" href={`${github}/actions/workflows/update-broke.yml`}>Open Update broke in your GitHub</a> : "In your GitHub repo, open Actions, then Update broke"}.</li>
<li>Press Run workflow, then Run workflow again.</li>
<li>Your site updates a couple of minutes later.</li>
</ol>
</Card>
<Card title="Change anything" what="Claude Code, Codex or opencode can make the change. The repo's CLAUDE.md tells them broke's privacy rules.">
<ol className="space-y-3 text-sm list-decimal pl-5">
<li className="space-y-1.5">Copy your code to your computer and start your AI app.<code className={line}>git clone {github ?? "<your repo>"} broke &amp;&amp; cd broke &amp;&amp; claude</code></li>
<li>Say what you want, like &quot;add a chart of my spending by weekday&quot;.</li>
<li className="space-y-1.5">Publish it. Vercel rebuilds your site.<code className={line}>git add -A &amp;&amp; git commit -m &quot;My change&quot; &amp;&amp; git push</code></li>
</ol>
</Card>
</>
);
return (
<Card title="Change anything" what="Claude Code, Codex or opencode can make the change. The repo's CLAUDE.md tells them broke's privacy rules.">
<ol className="space-y-3 text-sm list-decimal pl-5">
<li className="space-y-1.5">Open Terminal in your broke folder and start your AI app.<code className={line}>cd &quot;{folder}&quot; &amp;&amp; claude</code></li>
<li>Say what you want, like &quot;add a chart of my spending by weekday&quot;.</li>
<li className="space-y-1.5">See it change as it works. Stop broke if it&apos;s running, then run this in a second Terminal window.<code className={line}>npm run dev</code></li>
<li className="space-y-1.5">Get the latest broke at any time. Your changes stay.<code className={line}>npm run update</code></li>
<li>Made something others would want? <a className="underline underline-offset-2" href="https://github.com/nextwork-projects/broke/pulls">Send it back as a pull request</a>.</li>
</ol>
</Card>
);
}
+33
View File
@@ -0,0 +1,33 @@
import { getUser } from "@/lib/data";
import { isHosted } from "@/lib/llm/providers";
import { modeOf } from "@/lib/privacy";
import { currentEnv, fromLocalhost, setupAccess, supabaseReady } from "@/lib/setup";
import { createAdminClient } from "@/utils/supabase/admin";
import { DB_MESSAGES } from "../../setup/messages";
import { Settings } from "./Settings";
export const dynamic = "force-dynamic";
// Keys and statuses load in the browser from /api/setup/status (same as /setup), so no key details land in this payload.
export default async function SettingsPage({ searchParams }: { searchParams: Promise<{ db?: string }> }) {
const [{ user }, access, { db }, local] = await Promise.all([getUser(), setupAccess(), searchParams, fromLocalhost()]);
const mode = currentEnv().PLAID_ENV === "production" ? "production" : "sandbox";
// Test connections: Plaid access tokens carry their environment ("access-sandbox-…").
const { data: testItems } = user && supabaseReady()
? await createAdminClient().from("plaid_items").select("id, institution_name").eq("user_id", user.id).eq("provider", "plaid").like("access_token", "access-sandbox-%")
: { data: [] };
return (
<Settings
signedIn={access.signedIn}
local={local}
folder={isHosted() ? "" : process.cwd()}
repo={process.env.VERCEL_GIT_REPO_OWNER && process.env.VERCEL_GIT_REPO_SLUG ? `${process.env.VERCEL_GIT_REPO_OWNER}/${process.env.VERCEL_GIT_REPO_SLUG}` : null}
email={user?.email ?? ""}
profile={user?.user_metadata?.profile ?? {}}
aiMode={modeOf(user?.user_metadata)}
mode={mode}
testItems={(testItems ?? []).map((i) => ({ id: i.id as string, name: (i.institution_name as string | null) ?? "Test bank" }))}
message={db && Object.hasOwn(DB_MESSAGES, db) ? DB_MESSAGES[db] : undefined}
/>
);
}
+347
View File
@@ -0,0 +1,347 @@
import { ChevronLeft, ChevronRight, CircleMinus, CirclePlus, Landmark, PiggyBank, ReceiptText, Scale, type LucideIcon } from "lucide-react";
import Link from "next/link";
import { Breakdown } from "@/components/Donut";
import { EmptyBank } from "@/components/EmptyBank";
import { MonthBars } from "@/components/MonthBars";
import { PageDates } from "@/components/PageDates";
import { Merchant } from "@/components/Merchant";
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
import { dateLabel, money, money0, monthLabel, monthStart, ymd } from "@/lib/format";
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const nextDay = (d: string) => new Date(Date.parse(`${d}T00:00:00Z`) + 864e5).toISOString().slice(0, 10);
type Row = { icon: LucideIcon; label: string; sub: string; v: number };
function Summary({ rows }: { rows: Row[] }) {
return (
<div className="space-y-3">
<div className="section-label px-1">Summary</div>
<section className="card overflow-hidden">
{rows.map(({ icon: Icon, label, sub, v }, i) => (
<div key={label} className={`flex items-center gap-4 px-5 py-4 ${i ? "border-t border-line" : ""}`}>
<Icon size={20} strokeWidth={1.6} className="text-chart" />
<div className="flex-1">
<div>{label}</div>
<div className="text-xs text-muted">{sub}</div>
</div>
<span className="tabular font-medium">{money(v)}</span>
</div>
))}
</section>
</div>
);
}
// Where the money came from: one row per source and currency (never add currencies together), biggest first.
function IncomeSources({ txns, range }: { txns: Txn[]; range: string }) {
const by = new Map<string, { v: number; n: number; t: Txn }>();
for (const t of txns.filter(isIncome)) {
const k = `${displayName(t)}|${t.currency ?? ""}`;
const f = by.get(k) ?? { v: 0, n: 0, t };
by.set(k, { v: f.v - t.amount, n: f.n + 1, t });
}
const rows = [...by].filter(([, f]) => f.v > 0).sort((a, b) => b[1].v - a[1].v);
return (
<div className="space-y-3">
<div className="section-label px-1">Income breakdown</div>
<section className="card overflow-hidden">
{rows.length ? rows.map(([k, f]) => (
<Link key={k} href={`/transactions?q=${encodeURIComponent(displayName(f.t))}${range}`} className="row-hover flex items-center gap-4 px-5 py-3 border-b border-line last:border-0">
<Merchant name={displayName(f.t)} logo={f.t.logo_url} color={f.t.category?.color} icon={f.t.category?.icon} />
<div className="flex-1 min-w-0">
<div className="truncate">{displayName(f.t)}</div>
<div className="text-xs text-muted">{f.n === 1 ? "1 payment" : `${f.n} payments`}</div>
</div>
<span className="tabular font-medium text-good">{money(f.v, f.t.currency)}</span>
</Link>
)) : <p className="px-5 py-5 text-sm text-muted">No income in these dates.</p>}
</section>
</div>
);
}
// Any dates the user picks: the same totals and breakdown, added up from the transactions themselves.
async function CustomRange({ from, to, today }: { from: string; to: string; today: string }) {
const { supabase, user } = await getUser();
const start = from || "2000-01-01", end = to || today;
const [txns, cats, savedMonths] = await Promise.all([transactionsSince(start, nextDay(end)), categories(), savedByMonth(supabase, user!.id, start, end)]);
const spend = txns.filter(isSpend);
const total = sumOf(spend, (t) => t.amount);
const income = -sumOf(txns.filter(isIncome), (t) => t.amount);
const loans = sumOf(txns.filter((t) => t.category?.key === "LOAN_PAYMENTS" && t.amount > 0 && !t.ignored), (t) => t.amount);
const saved = [...savedMonths.values()].reduce((s, n) => s + n, 0);
const by = new Map<string, number>();
for (const t of spend) if (t.category_id) by.set(t.category_id, (by.get(t.category_id) ?? 0) + t.amount);
const slices = [...by].flatMap(([id, v]) => {
const c = cats.find((x) => x.id === id);
return c ? [{ id, label: c.label, color: c.color, icon: c.icon, v, prev: 0 }] : [];
}).sort((a, b) => b.v - a.v);
const left = income - total - loans;
const label = (d: string) => dateLabel(d, { month: "short", day: "numeric", year: "numeric" });
return (
<div className="space-y-6">
<PageDates path="/spending" from={from} to={to} today={today} />
<p className="text-center font-medium">{from ? label(from) : "The start"} to {label(end)}</p>
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
<div className="space-y-6">
<div className="space-y-3">
<div className="section-label px-1">Spending breakdown</div>
<section className="card p-6">
{slices.length ? <Breakdown slices={slices} total={total} change={null} prevLabel="" monthParam={`&${new URLSearchParams(Object.entries({ from, to }).filter(([, v]) => v))}`} /> : <p className="text-sm text-muted text-center py-10">No spending in these dates.</p>}
</section>
</div>
<IncomeSources txns={txns} range={`&${new URLSearchParams(Object.entries({ from, to }).filter(([, v]) => v))}`} />
</div>
<Summary rows={[
{ icon: CirclePlus, label: "Income", sub: "Money that came in", v: income },
{ icon: CircleMinus, label: "Spending", sub: `${spend.length} purchases`, v: total },
...(loans >= 1 ? [{ icon: Landmark, label: "Loan payments", sub: "Paid toward loans", v: loans }] : []),
{ icon: Scale, label: left >= 0 ? "Left over" : "Spent more than came in", sub: "Income minus everything that went out", v: Math.abs(left) },
...(saved >= 1 ? [{ icon: PiggyBank, label: "Saved and invested", sub: "Into savings and investment accounts", v: saved }] : []),
]} />
</div>
</div>
);
}
export default async function Spending({ searchParams }: { searchParams: Promise<{ m?: string; bills?: string; from?: string; to?: string; span?: string }> }) {
const { m, bills, from: rawFrom, to: rawTo, span } = await searchParams;
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
const includeBills = bills !== "0";
const now = await today();
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
const { supabase, user } = await getUser();
// m = "YYYY-MM" (the arrows or a bar), "last" or "now"; anything else = this month. Up to 5 years back.
const ym = /^\d{4}-\d{2}$/.test(m ?? "") ? m!.split("-").map(Number) : null;
// The first days of a month open on last month: this one is still empty. m=now asks for this month anyway.
const offset = m === "last" || (!m && now.getUTCDate() <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
const month = monthStart(now, offset);
const prevMonth = monthStart(now, offset - 1);
// The chart and table: the picked month's whole year by default, or the last 12 or 6 months (the 6 or 12 ending at the
// picked month once it's older than that). A year stops at this month, so there are never empty months ahead.
const n = span === "6" ? 6 : span === "12" ? 12 : 0;
const end = n && offset <= -n ? offset : 0;
const year = month.getUTCFullYear();
const yearLen = year === now.getUTCFullYear() ? now.getUTCMonth() + 1 : 12;
const months = n ? Array.from({ length: n }, (_, i) => monthStart(now, end + i - n + 1)) : Array.from({ length: yearLen }, (_, i) => new Date(Date.UTC(year, i, 1)));
const first = months[0] < prevMonth ? months[0] : prevMonth;
// Totals come from SQL over every own row (migration 0014); only the month's own rows are fetched, for the lists.
const [rows, allCats, monthTxns, loans, savedMonths] = await Promise.all([
moneyByMonth(supabase, ymd(first)),
categories(),
transactionsSince(ymd(month), ymd(monthStart(now, offset + 1))),
loanPayments(supabase, user!.id, ymd(first)),
savedByMonth(supabase, user!.id, ymd(first)),
]);
// ponytail: "no transactions in 6 months" is treated as "no bank yet"; split the copy if linked-but-quiet accounts show up.
if (!rows.length) return <EmptyBank title="See where your money goes" body="Link a bank to get a monthly breakdown by category." />;
const catById = new Map(allCats.map((c) => [c.id, c]));
const BILLS = ["RENT_AND_UTILITIES", "LOAN_PAYMENTS"];
const isBillCat = (id: string | null) => BILLS.includes(catById.get(id ?? "")?.key ?? "");
const inMonth = (r: MonthRow, d: Date) => r.month.startsWith(ymd(d).slice(0, 7));
const countedRow = (r: MonthRow) => includeBills || !isBillCat(r.category_id);
const counted = (t: Txn) => isSpend(t) && (includeBills || !isBillCat(t.category_id));
const loansIn = (d: Date) => loans.get(ymd(d).slice(0, 7)) ?? 0;
// Everything that went out, whatever the Include bills switch says: loan payments too, since the money is gone.
const bars = months.map((d) => ({ d, v: sumOf(rows.filter((r) => inMonth(r, d)), (r) => r.spend) + loansIn(d), income: sumOf(rows.filter((r) => inMonth(r, d)), (r) => r.income) }));
const of = (d: Date, f: (r: MonthRow) => number, keep: (r: MonthRow) => boolean = () => true) => sumOf(rows.filter((r) => inMonth(r, d) && keep(r)), f);
const total = of(month, (r) => r.spend, countedRow);
const prevTotal = of(prevMonth, (r) => r.spend, countedRow);
const income = of(month, (r) => r.income);
const prevIncome = of(prevMonth, (r) => r.income);
const billTotal = of(month, (r) => r.spend, (r) => isBillCat(r.category_id));
const prevBills = of(prevMonth, (r) => r.spend, (r) => isBillCat(r.category_id));
const spend = monthTxns.filter(counted);
const allOut = of(month, (r) => r.spend) + loansIn(month);
const savedIn = (d: Date) => savedMonths.get(ymd(d).slice(0, 7)) ?? 0;
const anySaved = months.some((d) => savedIn(d) >= 1);
const active = Math.max(1, bars.filter((b) => b.v > 0 || b.income > 0).length); // months before the first data don't drag the average down
const byCat = new Map<string, { id: string; label: string; color: string; icon: string; v: number; prev: number }>();
for (const [d, field] of [[month, "v"], [prevMonth, "prev"]] as const) {
for (const r of rows.filter((r) => inMonth(r, d) && countedRow(r) && r.spend)) {
const c = catById.get(r.category_id);
if (!c) continue;
const row = byCat.get(c.id) ?? { id: c.id, label: c.label, color: c.color, icon: c.icon, v: 0, prev: 0 };
row[field] += r.spend;
byCat.set(c.id, row);
}
}
const cats = [...byCat.values()].filter((c) => c.v > 0).sort((a, b) => b.v - a.v);
const largest = [...spend].sort((a, b) => b.amount - a.amount).slice(0, 3);
const freq = new Map<string, { n: number; v: number; t: Txn }>();
for (const t of spend) {
const k = `${displayName(t)}|${t.currency ?? ""}`; // one row per merchant and currency: never add currencies together
const f = freq.get(k) ?? { n: 0, v: 0, t };
freq.set(k, { n: f.n + 1, v: f.v + t.amount, t });
}
const frequent = [...freq].filter(([, f]) => f.n > 1).sort((a, b) => b[1].n - a[1].n).slice(0, 3);
const change = prevTotal ? Math.round(((total - prevTotal) / prevTotal) * 100) : null;
const vs = (a: number, b: number) => (Math.abs(a - b) < 1 ? `Same as ${monthLabel(prevMonth)}` : `${money0(Math.abs(a - b))} ${a > b ? "more" : "less"} than ${monthLabel(prevMonth)}`);
const qs = (o: Record<string, string | undefined>) => "/spending?" + new URLSearchParams(Object.entries({ m, bills, span, ...o }).filter(([, v]) => v) as [string, string][]);
return (
<div className="space-y-6">
<div className="flex items-center justify-center gap-2">
{offset > -59 ? (
<Link scroll={false} href={qs({ m: ymd(prevMonth).slice(0, 7) })} aria-label="Earlier month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronLeft size={18} /></Link>
) : <span className="size-9" />}
<span className="min-w-36 text-center font-medium tabular-nums">{dateLabel(month, { month: "long", year: "numeric" })}</span>
{offset < 0 ? (
<Link scroll={false} href={qs({ m: offset === -1 ? "now" : ymd(monthStart(now, offset + 1)).slice(0, 7) })} aria-label="Later month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronRight size={18} /></Link>
) : <span className="size-9" />}
{offset < -1 && <Link scroll={false} href={qs({ m: "now" })} className="text-sm text-muted hover:text-ink underline underline-offset-4 ml-1">This month</Link>}
</div>
<PageDates path="/spending" from="" to="" today={ymd(now)} />
<nav aria-label="How much to show" className="pill-tabs max-w-full overflow-x-auto">
{[
{ label: String(now.getUTCFullYear()), on: !n && year === now.getUTCFullYear(), href: qs({ span: undefined, m: "now" }) },
{ label: String(now.getUTCFullYear() - 1), on: !n && year === now.getUTCFullYear() - 1, href: qs({ span: undefined, m: `${now.getUTCFullYear() - 1}-12` }) },
{ label: "Last 12 months", on: n === 12, href: qs({ span: "12" }) },
{ label: "Last 6 months", on: n === 6, href: qs({ span: "6" }) },
].map((t) => <Link key={t.label} scroll={false} href={t.href} aria-current={t.on ? "true" : undefined} className={`pill-tab !py-1 !px-3 whitespace-nowrap ${t.on ? "pill-tab-active" : ""}`}>{t.label}</Link>)}
</nav>
<section className="card px-4 @lg:px-8 pt-6 pb-5">
<MonthBars
bars={bars.map((b) => ({
key: ymd(b.d),
label: monthLabel(b.d),
v: b.v,
income: b.income,
active: ymd(b.d) === ymd(month),
href: qs({ m: ymd(b.d).slice(0, 7) }),
}))}
/>
</section>
<div className="space-y-3">
<div className="section-label px-1">Month by month</div>
<section className="card overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-muted border-b border-line">
<th className="font-normal text-left pl-5 py-2.5">Month</th>
<th className="font-normal text-right px-3">Income</th>
<th className="font-normal text-right px-3">Expenses</th>
<th className="font-normal text-right px-3">Left over</th>
{anySaved && <th className="font-normal text-right pr-5 pl-3">Saved and invested</th>}
</tr>
</thead>
<tbody>
{bars.map((b) => {
const left = b.income - b.v;
return (
<tr key={ymd(b.d)} className="border-b border-line last:border-0 tabular">
<td className="pl-5 py-3"><Link scroll={false} href={qs({ m: ymd(b.d).slice(0, 7) })} className="hover:underline underline-offset-2">{monthLabel(b.d)}</Link></td>
<td className="text-right px-3">{money0(b.income)}</td>
<td className="text-right px-3">{money0(b.v)}</td>
<td className={`text-right px-3 font-medium ${left < 0 ? "text-bad" : ""}`}>{left < 0 ? "-" : ""}{money0(Math.abs(left))}</td>
{anySaved && <td className="text-right pr-5 pl-3">{money0(savedIn(b.d))}</td>}
</tr>
);
})}
</tbody>
<tfoot>
<tr className="tabular font-medium border-t border-line">
<td className="pl-5 py-3">Total</td>
<td className="text-right px-3">{money0(sumOf(bars, (b) => b.income))}</td>
<td className="text-right px-3">{money0(sumOf(bars, (b) => b.v))}</td>
<td className={`text-right px-3 ${sumOf(bars, (b) => b.income - b.v) < 0 ? "text-bad" : ""}`}>{sumOf(bars, (b) => b.income - b.v) < 0 ? "-" : ""}{money0(Math.abs(sumOf(bars, (b) => b.income - b.v)))}</td>
{anySaved && <td className="text-right pr-5 pl-3">{money0(sumOf(bars, (b) => savedIn(b.d)))}</td>}
</tr>
<tr className="tabular text-muted border-t border-line">
<td className="pl-5 py-3">Average a month</td>
<td className="text-right px-3">{money0(sumOf(bars, (b) => b.income) / active)}</td>
<td className="text-right px-3">{money0(sumOf(bars, (b) => b.v) / active)}</td>
<td className="text-right px-3">{sumOf(bars, (b) => b.income - b.v) < 0 ? "-" : ""}{money0(Math.abs(sumOf(bars, (b) => b.income - b.v)) / active)}</td>
{anySaved && <td className="text-right pr-5 pl-3">{money0(sumOf(bars, (b) => savedIn(b.d)) / active)}</td>}
</tr>
</tfoot>
</table>
</section>
</div>
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
<div className="space-y-6">
<div className="space-y-3">
<div className="section-label px-1">Spending breakdown</div>
<section className="card p-6 space-y-6">
<div className="flex justify-end">
<Link scroll={false} href={qs({ bills: includeBills ? "0" : undefined })} className="flex items-center gap-2 text-sm">
Include bills
<span className={`w-10 h-6 rounded-full p-0.5 transition ${includeBills ? "bg-good" : "bg-line"}`}>
<span className={`block size-5 rounded-full bg-white shadow transition ${includeBills ? "translate-x-4" : ""}`} />
</span>
</Link>
</div>
{cats.length ? (
<Breakdown slices={cats} total={total} change={change} prevLabel={monthLabel(prevMonth)} monthParam="" />
) : (
<p className="text-sm text-muted text-center py-10">No spending in {monthLabel(month)} yet.</p>
)}
</section>
</div>
<IncomeSources txns={monthTxns} range={`&from=${ymd(month)}&to=${ymd(new Date(monthStart(now, offset + 1).getTime() - 864e5))}`} />
</div>
<div className="space-y-6">
<Summary rows={[
{ icon: CirclePlus, label: "Income", sub: vs(income, prevIncome), v: income },
{ icon: ReceiptText, label: "Bills", sub: vs(billTotal, prevBills), v: billTotal },
{ icon: CircleMinus, label: "Spending", sub: vs(total, prevTotal), v: total },
...(loansIn(month) >= 1 || loansIn(prevMonth) >= 1 ? [{ icon: Landmark, label: "Loan payments", sub: vs(loansIn(month), loansIn(prevMonth)), v: loansIn(month) }] : []),
{ icon: Scale, label: income - allOut >= 0 ? "Left over" : "Spent more than came in", sub: "Income minus everything that went out", v: Math.abs(income - allOut) },
...(savedIn(month) >= 1 || savedIn(prevMonth) >= 1 ? [{ icon: PiggyBank, label: "Saved and invested", sub: vs(savedIn(month), savedIn(prevMonth)), v: savedIn(month) }] : []),
]} />
{!!frequent.length && (
<div className="space-y-3">
<div className="section-label px-1">Frequent Spend</div>
<section className="card overflow-hidden">
<p className="px-5 py-4 text-sm text-muted border-b border-line">
You&apos;ve spent at {displayName(frequent[0][1].t)} {frequent[0][1].n} times {offset ? `in ${dateLabel(month, { month: "long" })}` : "this month"}.
</p>
{frequent.map(([k, f]) => (
<div key={k} className="flex items-center gap-4 px-5 py-3 border-b border-line last:border-0">
<span className="size-9 rounded-full bg-canvas grid place-items-center text-xs font-semibold">{f.n}x</span>
<div className="flex-1 min-w-0">
<div className="truncate">{displayName(f.t)}</div>
<div className="text-xs text-muted">Average {money(f.v / f.n, f.t.currency)}</div>
</div>
<span className="tabular font-medium">{money(f.v, f.t.currency)}</span>
</div>
))}
</section>
</div>
)}
{!!largest.length && (
<div className="space-y-3">
<div className="section-label px-1">Largest Purchases</div>
<section className="card overflow-hidden">
{largest.map((t) => (
<div key={t.id} className="flex items-center gap-4 px-5 py-3 border-b border-line last:border-0">
<Merchant name={displayName(t)} logo={t.logo_url} color={t.category?.color} icon={t.category?.icon} />
<div className="flex-1 min-w-0">
<div className="truncate">{displayName(t)}</div>
<div className="text-xs text-muted">{Math.round((t.amount / total) * 100)}% of spend</div>
</div>
<span className="tabular font-medium">{money(t.amount, t.currency)}</span>
</div>
))}
</section>
</div>
)}
</div>
</div>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { Reveal } from "@/components/motion";
import { Toaster } from "@/components/Toast";
// A template re-mounts on every navigation (a layout does not), so each page gets its entrance.
export default function Template({ children }: { children: React.ReactNode }) {
return (
<>
<Reveal>{children}</Reveal>
<Toaster />
</>
);
}
+123
View File
@@ -0,0 +1,123 @@
import Link from "next/link";
import { EmptyBank } from "@/components/EmptyBank";
import { Filters } from "@/components/Filters";
import { ImportStatement } from "@/components/ImportStatement";
import { CategoryCheck, type Checks } from "@/components/CategoryCheck";
import { AddTransaction } from "@/components/ManualTxn";
import { TxnRow } from "@/components/TxnRow";
import { pairTransfers } from "@/lib/transfers";
import { countryOf } from "@/lib/countries";
import { accountName, allTags, categories, getUser, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { money, plural, ymd } from "@/lib/format";
import { fetchChecks } from "@/lib/unsure";
type Search = { q?: string; category?: string; account?: string; range?: string; from?: string; to?: string; tag?: string; limit?: string };
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const PAGE = 50;
const MAX = 1000; // ponytail: PostgREST returns 1000 rows per request; past that the list stops growing, page with .range() offsets if anyone scrolls that far.
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export default async function Transactions({ searchParams }: { searchParams: Promise<Search> }) {
const sp = await searchParams;
// Hand-edited or stale links: a bad param is dropped, never sent to the database.
const q = sp.q?.replace(/[%,()"\\]/g, " ").trim() || undefined;
const category = UUID.test(sp.category ?? "") ? sp.category : undefined;
const account = UUID.test(sp.account ?? "") ? sp.account : undefined;
const tag = sp.tag && sp.tag.length <= 100 && !/[,{}"\\]/.test(sp.tag) ? sp.tag : undefined;
const range = /^\d{1,5}$/.test(sp.range ?? "") && Number(sp.range) > 0 ? sp.range : undefined;
const n = Number.parseInt(sp.limit ?? "", 10);
const limit = n > 0 ? Math.min(n, MAX) : PAGE;
const now = await today();
// Custom dates win over the Last 30 days style presets. Either end can be left open.
const from = DAY.test(sp.from ?? "") ? sp.from : undefined;
const to = DAY.test(sp.to ?? "") ? sp.to : undefined;
const since = from ?? (range && !to ? ymd(new Date(now.getTime() - Number(range) * 864e5)) : undefined);
const { supabase, user } = await getUser();
const country = countryOf(user?.user_metadata?.profile?.country);
let query = supabase.from("transactions").select(TXN_SELECT, { count: "exact" }).order("date", { ascending: false }).order("id").limit(limit);
if (q) query = query.or(`name.ilike.%${q}%,merchant_name.ilike.%${q}%,custom_name.ilike.%${q}%`);
if (category) query = query.eq("category_id", category);
if (account) query = query.eq("account_id", account);
if (tag) query = query.contains("tags", [tag]);
if (since) query = query.gte("date", since);
if (to) query = query.lte("date", to);
const [{ data, count, error }, cats, { data: accounts, error: acctError }, tags, totals, checks] = await Promise.all([
query,
categories(),
supabase.from("accounts").select("id, name, custom_name, mask, owner_label, manual").order("name"),
allTags(),
// Out and in over the whole filter, not just the loaded page: own rows, no transfers, no ignored (migration 0014).
supabase.rpc("txn_totals", { q: q ?? null, cat: category ?? null, acct: account ?? null, tag: tag ?? null, start_date: since ?? null, end_date: to ?? null }).single<{ money_out: number; money_in: number }>(),
// "Is this right?" rows at the top, own rows from the last 90 days (lib/unsure.ts).
fetchChecks(supabase, user!.id, ymd(now)),
]);
if (error || acctError || totals.error) throw new Error((error ?? acctError ?? totals.error)!.message);
const txns = withAccountNames((data ?? []) as unknown as Txn[]);
const pairs = pairTransfers(txns); // a card payment shows once, on the account it left
const out = Number(totals.data?.money_out ?? 0);
const inn = Number(totals.data?.money_in ?? 0);
const shared = (accounts ?? []).some((a) => a.owner_label);
const own = (accounts ?? []).filter((a) => !a.owner_label).map((a) => ({ id: a.id, label: `${accountName(a)}${a.mask ? ` ··${a.mask}` : ""}` }));
const ownManual = (accounts ?? []).filter((a) => !a.owner_label && a.manual).map((a) => ({ id: a.id, label: accountName(a) }));
const more = new URLSearchParams(Object.entries({ q: sp.q, category, account, range, from, to, tag, limit: String(limit + PAGE) }).filter(([, v]) => v) as [string, string][]);
if (!count && !q && !category && !account && !range && !from && !to && !tag)
return (
<EmptyBank title="No transactions yet" body="Link a bank and every purchase shows up here, cleaned up and categorised.">
<AddTransaction accounts={own} cats={cats} allTags={tags} />
<ImportStatement link accounts={ownManual} locale={country.locale} currency={country.currency} />
</EmptyBank>
);
return (
<div className="space-y-5">
{checks.total > 0 && <CategoryCheck initial={checks as Checks} cats={cats} closed />}
<Filters
today={ymd(now)}
categories={cats.map((c) => ({ id: c.id, label: c.label, icon: c.icon, color: c.color }))}
accounts={(accounts ?? []).map((a) => ({ id: a.id, label: `${accountName(a)}${a.mask ? ` ··${a.mask}` : ""}${a.owner_label ? ` (${a.owner_label})` : ""}` }))}
tags={tags}
/>
<div className="flex flex-wrap justify-between gap-2 px-1 text-sm text-muted">
<span>{plural(count ?? 0, "transaction")}{count && count > txns.length ? `, showing ${txns.length}` : ""}</span>
<span className="flex items-center gap-4">
{!!txns.length && <span className="tabular" title="Your own accounts, without transfers and hidden transactions">{shared ? "Yours: " : ""}{money(out)} out · <span className="text-good">{money(inn)} in</span></span>}
<AddTransaction accounts={own} cats={cats} allTags={tags} />
<ImportStatement link accounts={ownManual} locale={country.locale} currency={country.currency} />
<Link href="/transactions/rules" className="text-ink underline underline-offset-2 hover:opacity-70">Rules</Link>
</span>
</div>
<div className="card overflow-clip">
<table className="w-full text-[15px]">
<thead className="sticky top-0 bg-surface z-10">
<tr className="text-left text-xs text-muted border-b border-line">
<th className="pl-4 @2xl:pl-6 pr-2 py-4 font-medium w-16">Date</th>
<th className="px-2 py-4 font-medium">Name</th>
<th className="px-2 py-4 font-medium hidden @2xl:table-cell">Category</th>
<th className="px-2 py-4 font-medium hidden @2xl:table-cell">Actions</th>
<th className="pl-2 pr-4 @2xl:pr-6 py-4 font-medium text-right">Amount</th>
</tr>
</thead>
<tbody>
{txns.filter((t) => !pairs.hidden.has(t.id)).map((t) => <TxnRow key={t.id} t={t} cats={cats} allTags={tags} to={pairs.to.get(t.id)} />)}
</tbody>
</table>
{!txns.length && (
<div className="p-10 text-center space-y-1">
<div className="font-medium">No transactions match</div>
<p className="text-sm text-muted">Try a different search or clear the filters.</p>
</div>
)}
{!!count && count > txns.length && limit < MAX && (
<div className="p-4 border-t border-line text-center">
<Link href={`/transactions?${more}`} scroll={false} className="btn">Show {Math.min(PAGE, count - txns.length)} more</Link>
</div>
)}
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { ArrowLeft } from "lucide-react";
import Link from "next/link";
import { RulesManager } from "@/components/RulesManager";
import { accountName, allRows, allTags, categories, getUser } from "@/lib/data";
import { matches, RULE_COLS, type Rule } from "@/lib/rules";
type Row = { name: string; merchant_name: string | null; amount: number; account_id: string; date: string };
export default async function Rules() {
const { supabase, user } = await getUser();
const [{ data, error }, cats, tags, { data: accts }, txns] = await Promise.all([
supabase.from("rules").select(RULE_COLS).order("created_at", { ascending: false }),
categories(),
allTags(),
supabase.from("accounts").select("id, name, custom_name, mask").eq("user_id", user!.id).order("name"),
// Own rows only, paged past the 1000-row cap, so each count is every transaction the rule matches.
// ponytail: counts in JS over every own row; move to SQL if a user reaches 100k+ transactions.
allRows<Row>((from, to) => supabase.from("transactions").select("name, merchant_name, amount, account_id, date").eq("user_id", user!.id).order("id").range(from, to)),
]);
const rules = (data ?? []) as Rule[];
const counts = Object.fromEntries(rules.map((r) => [r.id, txns.filter((t) => matches(r, t)).length]));
const accounts = (accts ?? []).map((a) => ({ id: a.id as string, label: `${accountName(a)}${a.mask ? ` ··${a.mask}` : ""}` }));
return (
<div className="space-y-5 max-w-3xl">
<Link href="/transactions" className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink"><ArrowLeft size={15} /> Transactions</Link>
<RulesManager rules={rules} counts={counts} cats={cats} allTags={tags} accounts={accounts} missing={!!error} />
</div>
);
}