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:
commit
f550865e93
359 files changed
+34290
No files matched your search
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
export function AccountToggle({ id, included, name }: { id: string; included: boolean; name: string }) {
|
||||
const router = useRouter();
|
||||
const [on, setOn] = useState(included);
|
||||
return (
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
aria-label={`Include ${name} in totals`}
|
||||
title={on ? "Included in totals" : "Hidden from totals"}
|
||||
onClick={async () => {
|
||||
const next = !on;
|
||||
setOn(next);
|
||||
// RLS blocks with 0 rows, not an error.
|
||||
const { data, error } = await createClient().from("accounts").update({ included: next }).eq("id", id).select("id");
|
||||
if (error || !data?.length) return setOn(!next), toast("Couldn't save that. Try again.");
|
||||
router.refresh();
|
||||
}}
|
||||
className={`w-10 h-6 rounded-full p-0.5 shrink-0 transition ${on ? "bg-good" : "bg-line"}`}
|
||||
>
|
||||
<span className={`block size-5 rounded-full bg-white shadow transition ${on ? "translate-x-4" : ""}`} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
// One file per icon: the package barrel pulls in all ~1,500 icons and slowed every dev compile.
|
||||
import { BankIcon } from "@phosphor-icons/react/dist/ssr/Bank";
|
||||
import { CarIcon } from "@phosphor-icons/react/dist/ssr/Car";
|
||||
import { CheckIcon } from "@phosphor-icons/react/dist/ssr/Check";
|
||||
import { CaretRightIcon } from "@phosphor-icons/react/dist/ssr/CaretRight";
|
||||
import { ChartLineUpIcon } from "@phosphor-icons/react/dist/ssr/ChartLineUp";
|
||||
import { CreditCardIcon } from "@phosphor-icons/react/dist/ssr/CreditCard";
|
||||
import { CurrencyBtcIcon } from "@phosphor-icons/react/dist/ssr/CurrencyBtc";
|
||||
import { FileArrowUpIcon } from "@phosphor-icons/react/dist/ssr/FileArrowUp";
|
||||
import { HouseIcon } from "@phosphor-icons/react/dist/ssr/House";
|
||||
import { MagnifyingGlassIcon } from "@phosphor-icons/react/dist/ssr/MagnifyingGlass";
|
||||
import { MoneyIcon } from "@phosphor-icons/react/dist/ssr/Money";
|
||||
import { PiggyBankIcon } from "@phosphor-icons/react/dist/ssr/PiggyBank";
|
||||
import { WalletIcon } from "@phosphor-icons/react/dist/ssr/Wallet";
|
||||
import type { Icon } from "@phosphor-icons/react";
|
||||
import { X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { ImportStatement } from "@/components/ImportStatement";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { FeedConnect } from "@/components/FeedConnect";
|
||||
import { linkedText, TestModeNote, useAkahu, useLinkBank } from "@/components/PlaidButtons";
|
||||
import { toast } from "@/components/Toast";
|
||||
import type { AddChoices } from "@/lib/providers";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Acct = { id: string; label: string };
|
||||
|
||||
// Overlapping circles. Soft = brand tint, dark = ink with light icons.
|
||||
function Cluster({ icons, dark = false }: { icons: Icon[]; dark?: boolean }) {
|
||||
return (
|
||||
<span className="flex">
|
||||
{icons.map((I, i) => (
|
||||
<span key={i} className={`size-11 rounded-full grid place-items-center ring-[3px] ring-surface ${i ? "-ml-3" : ""} ${dark ? "bg-ink text-on-ink" : "bg-brand-soft text-brand"}`}>
|
||||
<I size={22} weight="duotone" />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({ icons, dark, title, body, onClick, busy, error }: { icons: Icon[]; dark?: boolean; title: string; body: string; onClick: () => void; busy?: string | false; error?: string }) {
|
||||
return (
|
||||
<button onClick={onClick} disabled={!!busy} className="card-link w-full text-left p-5 flex items-center gap-4 disabled:opacity-60">
|
||||
<span className="flex-1 min-w-0 space-y-4">
|
||||
<Cluster icons={icons} dark={dark} />
|
||||
<span className="block">
|
||||
<span className="block card-title">{title}</span>
|
||||
<span className="block text-sm text-muted mt-0.5">{busy || body}</span>
|
||||
{error && <span className="block text-xs text-bad mt-1">{error}</span>}
|
||||
</span>
|
||||
</span>
|
||||
<CaretRightIcon size={20} className="text-muted shrink-0" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type LinkState = ReturnType<typeof useLinkBank>;
|
||||
const importing = (l: LinkState) => (l.kind === "investments" ? "Importing holdings..." : "Importing transactions...");
|
||||
|
||||
function PlaidCard({ link }: { link: LinkState }) {
|
||||
return <Card icons={[BankIcon, CreditCardIcon, WalletIcon]} title="Link a bank or card" body="Checking, savings and credit cards" onClick={() => link.start()} busy={link.busy && link.kind === "bank" && importing(link)} />;
|
||||
}
|
||||
function AkahuCard() {
|
||||
const { start, busy, error } = useAkahu();
|
||||
return <Card icons={[BankIcon, CreditCardIcon, WalletIcon]} title="Link a bank or card" body="Every NZ bank on your Akahu login" onClick={start} busy={busy && "Importing transactions..."} error={error} />;
|
||||
}
|
||||
function InvestCard({ link }: { link: LinkState }) {
|
||||
return <Card icons={[ChartLineUpIcon, PiggyBankIcon]} title="Link investments or retirement" body="Brokerage, 401(k), IRA or HSA" onClick={() => link.start(false, "investments")} busy={link.busy && link.kind === "investments" && importing(link)} />;
|
||||
}
|
||||
|
||||
// Plaid Link has its own institution search. Its link token takes no search term (plaid.com/docs/api/link, read 2026-10-22), so this only opens Link.
|
||||
function Search({ link }: { link: LinkState }) {
|
||||
return (
|
||||
<button onClick={() => link.start()} disabled={link.busy} className="input w-full !py-3 flex items-center gap-3 text-left text-muted hover:border-ink">
|
||||
<MagnifyingGlassIcon size={18} />
|
||||
{link.busy ? importing(link) : "Search for your bank"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TestBanks({ link, investments }: { link: LinkState; investments: boolean }) {
|
||||
const cls = "underline underline-offset-2 hover:text-ink disabled:opacity-50";
|
||||
return (
|
||||
<div className="px-1 space-y-2">
|
||||
<TestModeNote />
|
||||
<p className="text-sm text-muted flex flex-wrap gap-x-3 gap-y-1">
|
||||
<span>Or add one straight away:</span>
|
||||
<button className={cls} disabled={link.busy} onClick={() => link.start(true)}>{link.busy && link.kind === "bank" ? "Importing..." : "Test bank"}</button>
|
||||
{investments && <button className={cls} disabled={link.busy} onClick={() => link.start(true, "investments")}>{link.busy && link.kind === "investments" ? "Importing..." : "Test investments"}</button>}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// While a link runs (about 20 s on a big bank), then what it brought in, or why it failed.
|
||||
function LinkStatus({ link }: { link: LinkState }) {
|
||||
const [secs, setSecs] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!link.busy) return;
|
||||
setSecs(0);
|
||||
const t = setInterval(() => setSecs((s) => s + 1), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, [link.busy]);
|
||||
if (link.busy)
|
||||
return (
|
||||
<section className="card p-5 space-y-3" role="status" aria-live="polite">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="card-title">{importing(link)}</span>
|
||||
<span className="text-sm text-muted tabular">{secs} s</span>
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full bg-line overflow-hidden"><div className="h-full w-1/3 rounded-full bg-brand animate-[slide_1.2s_ease-in-out_infinite]" /></div>
|
||||
<p className="text-sm text-muted">This can take up to 30 seconds. Keep this page open.</p>
|
||||
</section>
|
||||
);
|
||||
if (link.error) return <section className="card p-5 text-sm text-bad" role="status">{link.error}</section>;
|
||||
if (link.result)
|
||||
return (
|
||||
<section className="card p-5 flex flex-wrap items-center gap-4" role="status">
|
||||
<span className="size-9 rounded-full bg-brand-soft text-brand grid place-items-center shrink-0"><CheckIcon size={18} weight="bold" /></span>
|
||||
<span className="flex-1 min-w-0 font-medium">{linkedText(link.result)}</span>
|
||||
<span className="flex gap-2">
|
||||
<Link href="/accounts" className="btn">See accounts</Link>
|
||||
<Link href="/" className="btn-primary">Open dashboard</Link>
|
||||
</span>
|
||||
</section>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Manual accounts (migration 0012). type decides the Accounts group and whether it counts as a debt there.
|
||||
const KINDS = [
|
||||
{ value: "vehicle", label: "Car or other vehicle", type: "other", placeholder: "e.g. 2019 Corolla" },
|
||||
{ value: "property", label: "Home or property", type: "other", placeholder: "e.g. Our house" },
|
||||
{ value: "crypto", label: "Crypto", type: "investment", placeholder: "e.g. Bitcoin wallet" },
|
||||
{ value: "cash", label: "Cash", type: "depository", placeholder: "e.g. Cash at home" },
|
||||
{ value: "other", label: "Something else you own", type: "other", placeholder: "e.g. Watch" },
|
||||
{ value: "owed", label: "Something you owe", type: "loan", placeholder: "e.g. Car loan" },
|
||||
];
|
||||
|
||||
function AddAsset() {
|
||||
const router = useRouter();
|
||||
const { money, parseAmount } = useMoney();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [f, setF] = useState({ kind: KINDS[0].value, name: "", value: "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const kind = KINDS.find((k) => k.value === f.kind)!;
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const value = Math.abs(parseAmount(f.value));
|
||||
if (!f.name.trim()) return setErr("Add a name.");
|
||||
if (Number.isNaN(value)) return setErr("Add a value.");
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const { error } = await createClient().from("accounts").insert({
|
||||
name: f.name.trim(), type: kind.type, subtype: kind.value === "owed" ? "other" : kind.value, current_balance: value, manual: true,
|
||||
});
|
||||
setBusy(false);
|
||||
if (error) return setErr(/manual/.test(error.message) ? "Manual accounts need a database update. Open Setup to run it." : "Couldn't save that account.");
|
||||
setOpen(false);
|
||||
toast(`${f.name.trim()} added`);
|
||||
router.push("/accounts");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card icons={[MoneyIcon, CarIcon, HouseIcon, CurrencyBtcIcon]} dark title="Add something else" body="Cash, a car, a home, or crypto" onClick={() => setOpen(true)} />
|
||||
{open && (
|
||||
<Modal label="Add something else" onClose={() => setOpen(false)}>
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="card-title">Add something else</div>
|
||||
<button type="button" aria-label="Close" onClick={() => setOpen(false)} className="p-2 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Type</span>
|
||||
<Dropdown label="Type" value={f.kind} onChange={(k) => setF({ ...f, kind: k })} placeholder="Choose a type" options={KINDS.map(({ value, label }) => ({ value, label }))} />
|
||||
</div>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Name</span>
|
||||
<input data-autofocus value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder={kind.placeholder} className="select" />
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">{kind.type === "loan" ? "Amount owed" : "Value"}</span>
|
||||
<input inputMode="decimal" value={f.value} onChange={(e) => setF({ ...f, value: e.target.value })} placeholder={money(0)} className="select tabular" />
|
||||
</label>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
<button disabled={busy} className="btn-primary w-full !py-2.5">{busy ? "Saving..." : "Add account"}</button>
|
||||
</form>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddAccounts({ choices, accounts, locale, currency, country }: { choices: AddChoices; accounts: Acct[]; locale: string; currency: string; country: string }) {
|
||||
// One link at a time, so every button shares one hook and one status card.
|
||||
const link = useLinkBank(undefined, { quiet: true });
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<LinkStatus link={link} />
|
||||
{choices.bank === "plaid" && <Search link={link} />}
|
||||
{choices.feeds.map((f) => <FeedConnect key={f} id={f} country={country} />)}
|
||||
<div className="grid grid-cols-1 @xl:grid-cols-2 gap-4">
|
||||
{choices.bank === "plaid" && <PlaidCard link={link} />}
|
||||
{(choices.bank === "akahu" || choices.alsoAkahu) && <AkahuCard />}
|
||||
{choices.investments && <InvestCard link={link} />}
|
||||
<ImportStatement accounts={accounts} locale={locale} currency={currency} trigger={(open) => (
|
||||
<Card icons={[FileArrowUpIcon]} dark title="Import a statement" body="A CSV, OFX, QFX, QIF or PDF file from your bank" onClick={open} />
|
||||
)} />
|
||||
<AddAsset />
|
||||
</div>
|
||||
{choices.sandbox && <TestBanks link={link} investments={choices.investments} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
"use client";
|
||||
/* eslint-disable @next/next/no-img-element */ // attached images are data URLs; next/image has nothing to optimise
|
||||
|
||||
import { ArrowUp, Check, LoaderCircle, Paperclip, Plus, Receipt, Repeat, Target, TrendingUp, Wallet, X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { PhoneMark } from "@/components/Logo";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { toastHost } from "@/components/Toast";
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import { decode, encode, isSmall, QUALITY_NOTE, type ModelChoice, type ModelOption } from "@/lib/llm/models";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
import { BudgetOffer } from "@/components/BudgetOffer";
|
||||
import { RuleOffer } from "@/components/RuleOffer";
|
||||
import { validSave, type GoalPlan } from "@/lib/advice";
|
||||
import { BUDGET_CONTEXT } from "@/lib/budget";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
type Msg = { role: "user" | "assistant"; content: string; images?: string[] }; // images: data URLs the user attached
|
||||
type Ctx = { open: boolean; toggle: () => void; ask: (q: string) => void };
|
||||
type HowTo = { text: string; href?: string; command?: string };
|
||||
export type Provider = { id: string; label: string; model: string | null; models?: ModelOption[]; ready: boolean; reason?: string; howTo?: HowTo[]; found?: string; action?: string; helper?: boolean };
|
||||
export type AiMode = "off" | "summary" | "local";
|
||||
|
||||
// A no-op default, so a button rendered outside the panel's provider (an error page, a half-finished render)
|
||||
// does nothing instead of crashing the page.
|
||||
const AssistantCtx = createContext<Ctx>({ open: false, toggle: () => {}, ask: () => {} });
|
||||
export const useAssistant = () => useContext(AssistantCtx);
|
||||
|
||||
// The runners' signed-out line (claude-code.ts, cli-snapshot.ts), and which provider each name is.
|
||||
const SIGNED_OUT = /(Claude Code|ChatGPT|Gemini|opencode) isn't signed in/;
|
||||
const CLI_ID: Record<string, string> = { "Claude Code": "claude", ChatGPT: "codex", Gemini: "gemini", opencode: "opencode" };
|
||||
const CLI_NAME = Object.fromEntries(Object.entries(CLI_ID).map(([name, id]) => [id, name]));
|
||||
|
||||
// Sent with "Ask AI to sort these"; the chat bubble hides it (CategoryCheck.tsx).
|
||||
export const CHECK_CONTEXT = /\n\nThese need checking[\s\S]*$/;
|
||||
|
||||
const SUGGESTIONS = [
|
||||
{ icon: Wallet, q: "Where did most of my money go this month?" },
|
||||
{ icon: Repeat, q: "Which subscriptions should I cancel?" },
|
||||
{ icon: TrendingUp, q: "Am I spending more than last month?" },
|
||||
{ icon: Receipt, q: "What bills are coming up before payday?" },
|
||||
{ icon: Target, q: "Help me make a plan for my goals" },
|
||||
];
|
||||
|
||||
/** One row per model: "Claude", "Claude · Opus", ..., then a row per provider that isn't set up (picking it shows the steps). */
|
||||
export function modelOptions(providers: Provider[]) {
|
||||
return providers.flatMap((p) =>
|
||||
!p.ready
|
||||
? [{ value: encode({ provider: p.id as ModelChoice["provider"], model: null }), label: p.label, hint: p.found ? `${p.found}. Pick it to set it up.` : "Not set up yet. Pick it to set it up." }]
|
||||
: [
|
||||
...(p.id === "local" ? [] : [{ value: encode({ provider: p.id as ModelChoice["provider"], model: null }), label: p.label, hint: `Default${p.model ? ` · ${p.model}` : ""}` }]),
|
||||
...(p.models ?? []).map((m) => ({ value: encode({ provider: p.id as ModelChoice["provider"], model: m.id }), label: `${p.label} · ${m.label}`, hint: isSmall(p.id, m.id) ? "Smaller, faster" : undefined })),
|
||||
],
|
||||
);
|
||||
}
|
||||
/** Saves the choice for chat, check-ins and the money plan (user_metadata.ai_model). */
|
||||
export const saveChoice = (c: ModelChoice) => updateMeta(createClient(), { data: { ai_model: c } });
|
||||
|
||||
// Docked chat panel that lives in the app layout, so the conversation survives page changes.
|
||||
// Temporary chat: the conversation lives only in this panel's memory and is gone when it is cleared or the page reloads.
|
||||
// aiMode comes from Settings, AI assistant ("AI and your data"). Off: the panel only says so and sends nothing.
|
||||
export function AssistantProvider({ children, aiMode = "summary" }: { children: React.ReactNode; aiMode?: AiMode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [messages, setMessages] = useState<Msg[]>([]);
|
||||
// null until /api/models answers: the server then uses the saved choice itself.
|
||||
const [choice, setChoice] = useState<ModelChoice | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [forceSetup, setForceSetup] = useState(false); // a question hit an AI that isn't set up: keep its setup card up
|
||||
|
||||
const gen = useRef(0); // a new question or new chat stops any wait for a sign-in
|
||||
|
||||
async function send(text: string, images: string[] = []) {
|
||||
if ((!text.trim() && !images.length) || busy || aiMode === "off") return;
|
||||
const next: Msg[] = [...messages, { role: "user", content: text.trim() || "What does this show?", ...(images.length ? { images } : {}) }];
|
||||
await answer(next, ++gen.current);
|
||||
}
|
||||
|
||||
async function answer(next: Msg[], run: number, retried = false) {
|
||||
setMessages([...next, { role: "assistant", content: "" }]);
|
||||
setBusy(true);
|
||||
let reply = "";
|
||||
try {
|
||||
const res = await fetch("/api/assistant", { method: "POST", body: JSON.stringify({ messages: next.map((m, i) => (i === next.length - 1 ? m : { role: m.role, content: m.images ? `${m.content}\n[an image I sent earlier]` : m.content })), ...(choice ?? {}) }) });
|
||||
const notReady = res.headers.get("x-signin");
|
||||
if (notReady && !retried) {
|
||||
setBusy(false);
|
||||
return void signIn(next, run, notReady);
|
||||
}
|
||||
if (res.status === 400) {
|
||||
// Not set up and not a sign-in: the setup card above has the button.
|
||||
setForceSetup(true);
|
||||
setMessages([...next, { role: "assistant", content: "This AI isn't set up yet. Use the button above, or pick another." }]);
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
if (!res.ok || !res.body) throw new Error(await res.text());
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
reply += decoder.decode(value, { stream: true });
|
||||
setMessages([...next, { role: "assistant", content: reply }]);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[broke] assistant:", e);
|
||||
setMessages([...next, { role: "assistant", content: "That AI isn't connected yet, or it couldn't answer. Check it on [Connect your AI](/connect-ai), or pick another above." }]);
|
||||
}
|
||||
setBusy(false);
|
||||
const out = !retried && reply.match(SIGNED_OUT);
|
||||
if (out) signIn(next, run, CLI_ID[out[1]]);
|
||||
}
|
||||
|
||||
// Signed out of a CLI: open Terminal on its sign-in, then ask the question again by itself once it's signed in.
|
||||
async function signIn(next: Msg[], run: number, id: string) {
|
||||
const name = CLI_NAME[id];
|
||||
setMessages([...next, { role: "assistant", content: `${name} isn't signed in. Opening Terminal...` }]);
|
||||
const body = await fetch("/api/models/setup", { method: "POST", body: JSON.stringify({ id, force: true }) }).then((r) => r.json()).catch(() => ({}));
|
||||
if (gen.current !== run) return;
|
||||
if (!body.opened) return setMessages([...next, { role: "assistant", content: `${name} isn't signed in, and Terminal couldn't open from here. Follow the steps on [Connect your AI](/connect-ai).` }]);
|
||||
setMessages([...next, { role: "assistant", content: `Terminal just opened so you can sign in to ${name}. Finish there and broke asks again by itself.` }]);
|
||||
const ready = async () => {
|
||||
const b = await fetch("/api/models?fresh=1").then((r) => r.json()).catch(() => ({ providers: [] }));
|
||||
return !!(b.providers as Provider[]).find((p) => p.id === id)?.ready;
|
||||
};
|
||||
const stale = await ready(); // says signed in while the run said otherwise: nothing to wait for, so they ask again themselves
|
||||
if (stale) return setMessages([...next, { role: "assistant", content: `Terminal just opened so you can sign in to ${name}. Finish there, then ask again.` }]);
|
||||
for (let i = 0; i < 45 && gen.current === run; i++) {
|
||||
await new Promise((r) => setTimeout(r, 4000));
|
||||
if (gen.current === run && (await ready())) return void answer(next, run, true);
|
||||
}
|
||||
}
|
||||
|
||||
const ctx: Ctx = {
|
||||
open,
|
||||
toggle: () => setOpen((o) => !o),
|
||||
ask: (q) => {
|
||||
setOpen(true);
|
||||
send(q);
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<AssistantCtx.Provider value={ctx}>
|
||||
<div className="min-h-screen bg-surface md:flex">
|
||||
{children}
|
||||
{open && (
|
||||
<Panel
|
||||
messages={messages}
|
||||
busy={busy}
|
||||
send={send}
|
||||
close={() => setOpen(false)}
|
||||
choice={choice}
|
||||
setChoice={setChoice}
|
||||
aiMode={aiMode}
|
||||
forceSetup={forceSetup}
|
||||
newChat={() => { gen.current++; setMessages([]); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</AssistantCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function Panel(props: {
|
||||
messages: Msg[]; busy: boolean; send: (t: string, images?: string[]) => void; close: () => void;
|
||||
choice: ModelChoice | null; setChoice: (c: ModelChoice) => void; aiMode: AiMode; forceSetup: boolean; newChat: () => void;
|
||||
}) {
|
||||
const { messages, busy, send, close, choice, setChoice, aiMode, forceSetup, newChat } = props;
|
||||
const provider = choice?.provider ?? "openrouter";
|
||||
const off = aiMode === "off";
|
||||
const [input, setInput] = useState("");
|
||||
const [attached, setAttached] = useState<string[]>([]);
|
||||
const [attachErr, setAttachErr] = useState("");
|
||||
const [providers, setProviders] = useState<Provider[]>([]);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
// Pasted, dropped or picked images: PNG, JPEG, WebP or GIF, up to 4 a message and 5 MB each (the server checks again).
|
||||
async function attach(files: Iterable<File>) {
|
||||
setAttachErr("");
|
||||
const ok = [...files].filter((f) => /^image\/(png|jpeg|webp|gif)$/.test(f.type));
|
||||
if (ok.some((f) => f.size > 5e6)) setAttachErr("Images over 5 MB are left out.");
|
||||
const urls = await Promise.all(ok.filter((f) => f.size <= 5e6).map((f) => new Promise<string>((res, rej) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => res(String(r.result));
|
||||
r.onerror = rej;
|
||||
r.readAsDataURL(f);
|
||||
})));
|
||||
setAttached((a) => {
|
||||
const all = [...a, ...urls];
|
||||
if (all.length > 4) setAttachErr("Up to 4 images a message.");
|
||||
return all.slice(0, 4);
|
||||
});
|
||||
}
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const field = useRef<HTMLTextAreaElement>(null);
|
||||
const dialog = useRef<HTMLDialogElement>(null);
|
||||
const back = useRef<HTMLElement | null>(null);
|
||||
|
||||
// A modal sheet on phones (focus trap, inert page), a docked non-modal panel from md up. Focus goes back on close.
|
||||
useEffect(() => {
|
||||
const d = dialog.current!;
|
||||
let drop = () => {};
|
||||
if (!d.open) {
|
||||
back.current = document.activeElement as HTMLElement | null;
|
||||
if (matchMedia("(max-width: 767px)").matches) {
|
||||
d.showModal();
|
||||
drop = toastHost(d);
|
||||
} else d.show();
|
||||
}
|
||||
return () => {
|
||||
drop();
|
||||
back.current?.focus();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
// Only the chat scrolls. scrollIntoView would move the page behind it too.
|
||||
scroller.current?.scrollTo({ top: scroller.current.scrollHeight, behavior: "smooth" });
|
||||
}, [messages]);
|
||||
useEffect(() => {
|
||||
field.current?.focus({ preventScroll: true });
|
||||
}, [busy]);
|
||||
const loadModels = (fresh = false) =>
|
||||
fetch(`/api/models${fresh ? "?fresh=1" : ""}`)
|
||||
.then((r) => (r.ok ? r.json() : { providers: [] }))
|
||||
.then((b: { providers?: Provider[]; choice?: ModelChoice | null }) => {
|
||||
setProviders(b.providers ?? []);
|
||||
if (!choice) setChoice(b.choice ?? { provider: "openrouter", model: null });
|
||||
return b.providers ?? [];
|
||||
})
|
||||
.catch(() => (setProviders([]), [] as Provider[]));
|
||||
useEffect(() => void loadModels(), []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// Picking one that isn't ready brings up its setup right away, even mid-chat.
|
||||
const [picked, setPicked] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (picked) scroller.current?.scrollTo({ top: 0, behavior: "smooth" }); // the setup card sits at the top of the chat
|
||||
}, [picked]);
|
||||
const pickModel = (v: string) => {
|
||||
const c = decode(v);
|
||||
setChoice(c);
|
||||
setPicked(c.provider);
|
||||
saveChoice(c).then(({ error }) => error && console.error("[broke] model choice:", error.message));
|
||||
};
|
||||
|
||||
const current = providers.find((p) => p.id === provider);
|
||||
const icon = "grid place-items-center size-8 rounded-full text-muted hover:text-ink hover:bg-[var(--hover)] transition-colors";
|
||||
const submit = () => {
|
||||
if ((!input.trim() && !attached.length) || busy) return;
|
||||
send(input, attached);
|
||||
setInput("");
|
||||
setAttached([]);
|
||||
setAttachErr("");
|
||||
};
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialog}
|
||||
aria-label="broke ai chat"
|
||||
onKeyDown={(e) => e.key === "Escape" && !e.defaultPrevented && (e.preventDefault(), close())}
|
||||
onCancel={(e) => (e.preventDefault(), close())}
|
||||
className="fixed inset-0 z-40 size-full max-w-none max-h-none bg-transparent text-inherit md:static md:inset-auto md:w-[420px] md:shrink-0 md:h-screen md:sticky md:top-0 md:py-3 md:pr-3"
|
||||
>
|
||||
<div className="h-full bg-surface text-ink md:rounded-3xl md:border md:border-line md:shadow-[var(--shadow-card)] flex flex-col text-[14px] overflow-hidden">
|
||||
<header className="flex items-center gap-2 pl-4 pr-2 h-14 border-b border-line shrink-0">
|
||||
<PhoneMark size={22} />
|
||||
<span className="font-semibold tracking-tight shrink-0">broke ai</span>
|
||||
<div className="min-w-0 flex-1 flex">
|
||||
<Dropdown
|
||||
label="AI model"
|
||||
value={encode(choice ?? { provider: "openrouter", model: null })}
|
||||
onChange={pickModel}
|
||||
options={modelOptions(providers.length ? providers : [{ id: "openrouter", label: "OpenRouter", model: null, ready: true }])}
|
||||
/>
|
||||
</div>
|
||||
<button onClick={newChat} aria-label="New chat" title="New chat" className={icon}><Plus size={17} /></button>
|
||||
<button onClick={close} aria-label="Close" title="Close" className={icon}><X size={17} /></button>
|
||||
</header>
|
||||
|
||||
<div className="px-4 py-2 border-b border-line text-xs text-muted space-y-0.5 shrink-0">
|
||||
{off ? (
|
||||
<p>AI is off. Nothing goes to a model.</p>
|
||||
) : (
|
||||
<>
|
||||
<p>{aiMode === "local" && provider === "local" ? "Runs on this Mac" : aiMode === "local" ? "Sees a summary of your money. Full detail is for the local model only." : "Sees a summary of your money"}</p>
|
||||
<p>Temporary chat: not saved</p>
|
||||
{current?.ready && isSmall(provider, choice?.model ?? (provider === "local" ? current.model : null)) && <p className="text-ink">{QUALITY_NOTE}</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div ref={scroller} className="flex-1 overflow-y-auto px-4 py-5 space-y-5">
|
||||
{off && (
|
||||
<section className="rounded-2xl border border-line p-4 space-y-2">
|
||||
<p className="font-semibold">AI is off</p>
|
||||
<p className="text-sm text-muted">You turned off AI, so broke ai can't answer. Everything else in broke still works.</p>
|
||||
<Link href="/settings#ai" onClick={close} className="btn inline-block !py-1.5 text-sm">Change in Settings</Link>
|
||||
</section>
|
||||
)}
|
||||
{!off && current && !current.ready && (!messages.length || picked === provider || forceSetup) && <SetupCard p={current} recheck={() => loadModels(true)} />}
|
||||
{!off && !messages.length && current?.ready !== false && (
|
||||
<div className="pt-6 space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xl font-semibold tracking-tight">Ask anything about your money</p>
|
||||
<p className="text-muted">{aiMode === "local" && provider === "local" ? "I read your accounts, transactions and bills on this Mac." : "I see monthly totals and rounded amounts, not your transactions."} Keep using the app while we talk.</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
{SUGGESTIONS.map(({ icon: Icon, q }) => (
|
||||
<button key={q} onClick={() => send(q)} className="flex items-center gap-3 text-left rounded-2xl border border-line px-3.5 py-3 hover:bg-[var(--hover)] hover:border-muted/40 transition-colors">
|
||||
<span className="grid place-items-center size-8 rounded-full bg-canvas text-muted shrink-0"><Icon size={16} /></span>
|
||||
<span>{q}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{messages.map((m, i) =>
|
||||
m.role === "user" ? (
|
||||
<div key={i} className="flex justify-end">
|
||||
<div className="max-w-[85%] flex flex-col items-end gap-1.5">
|
||||
{m.images?.length ? <div className="flex flex-wrap justify-end gap-1.5">{m.images.map((src, j) => <img key={j} src={src} alt="" className="max-h-40 max-w-full rounded-2xl border border-line" />)}</div> : null}
|
||||
<p className="rounded-2xl rounded-br-md bg-ink text-on-ink px-4 py-2.5 whitespace-pre-wrap leading-relaxed">{m.content.replace(BUDGET_CONTEXT, "").replace(CHECK_CONTEXT, "")}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div key={i} className="leading-relaxed space-y-2.5">
|
||||
<Reply text={m.content} live={busy && i === messages.length - 1} onPick={!busy && i === messages.length - 1 ? send : undefined} />
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
onDragOver={(e) => e.dataTransfer.types.includes("Files") && e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
if (!e.dataTransfer.files.length) return;
|
||||
e.preventDefault();
|
||||
attach(e.dataTransfer.files);
|
||||
}}
|
||||
className="p-3 pt-0 shrink-0"
|
||||
>
|
||||
{attached.length > 0 && (
|
||||
<div className="pb-2 space-y-1.5">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{attached.map((src, i) => (
|
||||
<span key={i} className="relative">
|
||||
<img src={src} alt={`Attached image ${i + 1}`} className="size-16 rounded-xl object-cover border border-line" />
|
||||
<button type="button" aria-label={`Remove image ${i + 1}`} onClick={() => setAttached((a) => a.filter((_, j) => j !== i))} className="absolute -top-1.5 -right-1.5 size-5 rounded-full bg-ink text-on-ink grid place-items-center"><X size={12} /></button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{!(aiMode === "local" && provider === "local") && (
|
||||
<p className="text-xs text-muted">Images go to {current?.label ?? "the AI"} as they are, not as a summary. Crop out account numbers first.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{attachErr && <p className="text-xs text-bad pb-2">{attachErr}</p>}
|
||||
<div className="flex items-end gap-2 rounded-2xl border border-line bg-canvas/60 pl-2 pr-2 py-2 focus-within:border-muted/60 focus-within:bg-surface transition-colors">
|
||||
<input ref={fileInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple hidden onChange={(e) => { if (e.target.files) attach(e.target.files); e.target.value = ""; }} />
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Add an image"
|
||||
onClick={() => fileInput.current?.click()}
|
||||
disabled={busy || off || current?.ready === false}
|
||||
className="grid place-items-center size-8 rounded-full text-muted hover:text-ink hover:bg-[var(--hover)] shrink-0 disabled:opacity-40"
|
||||
>
|
||||
<Paperclip size={17} />
|
||||
</button>
|
||||
<textarea
|
||||
onPaste={(e) => {
|
||||
const files = [...e.clipboardData.files];
|
||||
if (files.length) {
|
||||
e.preventDefault();
|
||||
attach(files);
|
||||
}
|
||||
}}
|
||||
ref={field}
|
||||
rows={1}
|
||||
aria-label="Ask broke ai"
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
e.target.style.height = "auto";
|
||||
e.target.style.height = `${Math.min(e.target.scrollHeight, 140)}px`;
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}
|
||||
}}
|
||||
disabled={busy || off || current?.ready === false}
|
||||
placeholder={off ? "AI is off" : busy ? "Working on it..." : current?.ready === false ? `Set up ${current.label} to start` : "Ask about your spending"}
|
||||
className="flex-1 resize-none bg-transparent outline-none focus-visible:outline-none py-1.5 leading-6 placeholder:text-muted disabled:opacity-60"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
aria-label="Send"
|
||||
disabled={busy || (!input.trim() && !attached.length)}
|
||||
className="grid place-items-center size-8 rounded-full bg-ink text-on-ink shrink-0 transition-opacity disabled:opacity-25"
|
||||
>
|
||||
{busy ? <LoaderCircle size={16} className="animate-spin" /> : <ArrowUp size={16} strokeWidth={2.4} />}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted text-center mt-2">Runs on your own {current?.label ?? "AI"} {provider === "openrouter" ? "account" : "plan"}. Not financial advice.</p>
|
||||
</form>
|
||||
</div>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Shown in place of the chat when the picked model isn't ready, and on Connect your AI: its steps with copyable commands,
|
||||
// a button that opens Terminal with them typed in, and a re-check that keeps looking for a few minutes.
|
||||
export function SetupCard({ p, recheck, auto }: { p: Provider; recheck: () => Promise<Provider[]>; auto?: boolean }) {
|
||||
// Hosted, and their computer has gone offline: the command to reconnect is on Connect your AI.
|
||||
if (p.helper) return <section className="rounded-2xl border border-line p-4 space-y-3"><p className="text-sm">{p.reason}</p><Link href="/connect-ai" className="btn !py-2 text-sm inline-block">Connect your AI</Link></section>;
|
||||
if (p.id !== "openrouter") return <CliSetup p={p} recheck={recheck} auto={auto} />;
|
||||
// OpenRouter has nothing to install: its whole setup is one sign-in, and the Connect your AI page has every other way.
|
||||
return (
|
||||
<section className="rounded-2xl border border-line p-4 space-y-3">
|
||||
<p className="font-semibold">Connect an AI to ask questions</p>
|
||||
<p className="text-sm text-muted">Make a free OpenRouter account and approve broke. No install, no key to copy, and free models cost nothing.</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<a href="/api/ai/openrouter/start" className="btn-primary !py-2 text-sm">Connect OpenRouter</a>
|
||||
<Link href="/connect-ai" className="btn !py-2 text-sm">Other ways</Link>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// auto: opens Terminal as soon as it shows, because the user just pressed Sign in or Install.
|
||||
function CliSetup({ p, recheck, auto }: { p: Provider; recheck: () => Promise<Provider[]>; auto?: boolean }) {
|
||||
const [state, setState] = useState<"idle" | "opening" | "waiting" | "manual">("idle");
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const again = useRef(recheck);
|
||||
again.current = recheck;
|
||||
|
||||
// After Terminal opens, check every 4 s for up to 3 minutes; the card disappears once it's ready.
|
||||
useEffect(() => {
|
||||
if (state !== "waiting") return;
|
||||
let n = 0;
|
||||
const t = setInterval(async () => {
|
||||
const list = await again.current();
|
||||
if (list.find((x) => x.id === p.id)?.ready || ++n >= 45) clearInterval(t);
|
||||
}, 4000);
|
||||
return () => clearInterval(t);
|
||||
}, [state, p.id]);
|
||||
|
||||
async function openTerminal() {
|
||||
setState("opening");
|
||||
const res = await fetch("/api/models/setup", { method: "POST", body: JSON.stringify({ id: p.id }) });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (body.ready) return void recheck();
|
||||
setState(body.opened ? "waiting" : "manual");
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (auto) void openTerminal();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const copy = (cmd: string) => {
|
||||
navigator.clipboard?.writeText(cmd).then(() => { setCopied(cmd); setTimeout(() => setCopied(null), 1500); }).catch(() => {});
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="rounded-2xl border border-line p-4 space-y-4">
|
||||
<div className="space-y-1">
|
||||
<p className="font-semibold">{p.action === "Sign in" ? `Sign in to ${p.label}` : `${p.action ?? "Set up"} ${p.label}`}</p>
|
||||
<p className="text-sm text-muted">{(p.found ?? "It isn't ready on this computer yet").replace(/[.!]?$/, ".")} Press the button and Terminal opens for you. It runs on your own plan, so there's no API bill.</p>
|
||||
</div>
|
||||
{/* The steps are only needed when Terminal can't open by itself. */}
|
||||
{state === "manual" && <ol className="space-y-3">
|
||||
{(p.howTo ?? []).map((h, i) => (
|
||||
<li key={i} className="flex gap-3 text-sm">
|
||||
<span className="grid place-items-center size-5 rounded-full bg-canvas text-xs text-muted shrink-0 mt-0.5 tabular">{i + 1}</span>
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
<p>{h.href ? <a href={h.href} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">{h.text}</a> : h.text}</p>
|
||||
{h.command && (
|
||||
<button type="button" onClick={() => copy(h.command!)} className="w-full flex items-center justify-between gap-2 rounded-lg bg-canvas px-3 py-2 font-mono text-xs text-left hover:bg-[var(--hover)]">
|
||||
<span className="truncate">{h.command}</span>
|
||||
<span className="text-muted shrink-0">{copied === h.command ? "Copied" : "Copy"}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" onClick={openTerminal} disabled={state === "opening" || state === "waiting"} className="btn-primary !py-2 text-sm">
|
||||
{state === "opening" ? "Opening Terminal..." : state === "waiting" ? "Waiting for you to finish..." : p.action ?? "Set up in Terminal"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => { setChecking(true); await recheck(); setChecking(false); }}
|
||||
className="btn !py-2 text-sm"
|
||||
>
|
||||
{checking ? "Checking..." : "Check again"}
|
||||
</button>
|
||||
</div>
|
||||
{state === "waiting" && <p className="text-xs text-muted">Finish the steps in Terminal. This switches over by itself when {p.label} is ready.</p>}
|
||||
{state === "manual" && <p className="text-xs text-muted">Couldn't open Terminal from here. Copy the commands above into a terminal, then press Check again.</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function AskButton({ q, className, children }: { q?: string; className?: string; children: React.ReactNode }) {
|
||||
const { ask, toggle } = useAssistant();
|
||||
return (
|
||||
<button onClick={() => (q ? ask(q) : toggle())} className={className}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const TOOL_LABEL: Record<string, string> = {
|
||||
spending_summary: "Adding up your spending",
|
||||
search_transactions: "Searching your transactions",
|
||||
list_recurring: "Checking recurring charges",
|
||||
list_accounts: "Reading account balances",
|
||||
list_holdings: "Reading your investments",
|
||||
get_profile: "Reading your money profile",
|
||||
contribution_room: "Checking contribution room",
|
||||
fund_fees: "Checking fund fees",
|
||||
safe_to_spend: "Working out safe to spend",
|
||||
idle_cash: "Looking for idle cash",
|
||||
match_check: "Checking your employer match",
|
||||
subscription_alerts: "Looking for price hikes",
|
||||
cancel_info: "Finding how to cancel",
|
||||
card_recommendations: "Comparing credit cards",
|
||||
money_plan: "Reading your money plan",
|
||||
web_search: "Searching the web",
|
||||
WebSearch: "Searching the web",
|
||||
WebFetch: "Reading a web page",
|
||||
};
|
||||
// A tool without a label still reads as words: "mcp__x__new_tool" or "NewTool" becomes "New tool".
|
||||
const toolLabel = (name: string) => {
|
||||
if (TOOL_LABEL[name]) return TOOL_LABEL[name];
|
||||
const words = name.replace(/^mcp__\w+?__/, "").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().toLowerCase();
|
||||
return words ? words[0].toUpperCase() + words.slice(1) : "Working";
|
||||
};
|
||||
|
||||
const Dots = () => (
|
||||
<span className="inline-flex gap-1 py-2" aria-label="Thinking">
|
||||
{[0, 150, 300].map((d) => <span key={d} className="size-1.5 rounded-full bg-muted animate-bounce" style={{ animationDelay: `${d}ms` }} />)}
|
||||
</span>
|
||||
);
|
||||
|
||||
// Links in a reply: http(s) opens in a new tab, a path inside broke ("/recurring") is an in-app link. Anything else
|
||||
// (javascript:, mailto:, relative text) stays plain text.
|
||||
const APP_PATH = "(?:transactions|recurring|budgets|spending|plan|optimize|cards|accounts|settings|insights|setup)\\b[^\\s)<>,]*";
|
||||
const INLINE = new RegExp(`(\\*\\*[^*]+\\*\\*)|\\[([^\\]\\n]+)\\]\\(([^)\\n]+)\\)|(https?:\\/\\/[^\\s<>()\\]]+)|((?<![\\w/.])\\/${APP_PATH})`, "g");
|
||||
const linkCls = "underline underline-offset-2 decoration-muted/60 hover:decoration-ink";
|
||||
function ReplyLink({ href, children }: { href: string; children: React.ReactNode }) {
|
||||
const h = href.trim();
|
||||
if (/^https?:\/\/[^\s]+$/i.test(h)) return <a href={h} target="_blank" rel="noopener noreferrer" className={linkCls}>{children}</a>;
|
||||
if (/^\/(?![/\\])/.test(h)) return <Link href={h.replace(/ /g, "%20")} className={linkCls}>{children}</Link>;
|
||||
return <>{children}</>;
|
||||
}
|
||||
function inline(text: string): React.ReactNode[] {
|
||||
const out: React.ReactNode[] = [];
|
||||
let last = 0;
|
||||
for (const m of text.matchAll(INLINE)) {
|
||||
let [all] = m;
|
||||
const at = m.index!;
|
||||
// A bare link drops the full stop or comma that ends its sentence.
|
||||
const trail = m[4] || m[5] ? /[.,;:!?'"]+$/.exec(all)?.[0] ?? "" : "";
|
||||
if (trail) all = all.slice(0, -trail.length);
|
||||
out.push(text.slice(last, at));
|
||||
const k = out.length;
|
||||
if (m[1]) out.push(<strong key={k} className="font-semibold">{inline(m[1].slice(2, -2))}</strong>);
|
||||
else if (m[2]) out.push(<ReplyLink key={k} href={m[3]}>{m[2]}</ReplyLink>);
|
||||
else out.push(<ReplyLink key={k} href={all}>{all}</ReplyLink>);
|
||||
last = at + all.length;
|
||||
}
|
||||
out.push(text.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
// The model ends a reply with ```ask {"q", "options"}``` to ask a question as buttons, and ```save {...}``` to offer
|
||||
// a profile change. A block still streaming in is hidden until it closes. Returns the text without the blocks.
|
||||
export function replyBlocks(text: string) {
|
||||
let ask: { q: string; options: string[] } | null = null;
|
||||
let save: Record<string, unknown> | null = null;
|
||||
let budget: Record<string, unknown> | null = null;
|
||||
let rules: unknown[] | null = null;
|
||||
const body = text
|
||||
.replace(/```(ask|save|budget|rules)\s*\n([\s\S]*?)```/g, (_, kind: string, json: string) => {
|
||||
try {
|
||||
const v = JSON.parse(json);
|
||||
if (kind === "ask" && typeof v?.q === "string" && Array.isArray(v.options)) ask = { q: v.q, options: v.options.filter((o: unknown) => typeof o === "string").slice(0, 5) };
|
||||
if (kind === "save" && v && typeof v === "object") save = v;
|
||||
if (kind === "rules" && Array.isArray(v)) rules = v;
|
||||
if (kind === "budget" && v && typeof v === "object" && !Array.isArray(v)) budget = v;
|
||||
} catch {}
|
||||
return "";
|
||||
})
|
||||
.replace(/```(ask|save|budget|rules)[\s\S]*$/, "");
|
||||
return { body, ask: ask as { q: string; options: string[] } | null, save: save as Record<string, unknown> | null, budget: budget as Record<string, unknown> | null, rules: rules as unknown[] | null };
|
||||
}
|
||||
|
||||
// Saves only what this country's profile questions allow (validSave), merged into the existing profile.
|
||||
function SaveOffer({ proposed }: { proposed: Record<string, unknown> }) {
|
||||
const router = useRouter();
|
||||
const [state, setState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
async function save() {
|
||||
setState("saving");
|
||||
const sb = createClient();
|
||||
const { data } = await sb.auth.getUser();
|
||||
const profile = (data.user?.user_metadata?.profile ?? {}) as Record<string, unknown> & { goals?: string[]; goalPlans?: GoalPlan[] };
|
||||
const { fields, goals, goalPlans } = validSave(profile.country as string | undefined, proposed);
|
||||
// A new target replaces the old one for the same goal, and turns that goal on.
|
||||
const plans = [...(profile.goalPlans ?? []).filter((g) => !goalPlans.some((n) => n.goal === g.goal)), ...goalPlans];
|
||||
const next = { ...profile, ...fields, goals: [...new Set([...(profile.goals ?? []), ...goals, ...goalPlans.map((g) => g.goal)])], goalPlans: plans };
|
||||
const { error } = await updateMeta(sb, { data: { profile: next } });
|
||||
setState(error ? "failed" : "saved");
|
||||
if (!error) router.refresh();
|
||||
}
|
||||
return (
|
||||
<button onClick={save} disabled={state === "saving" || state === "saved"} className="btn !py-1 text-sm inline-flex items-center gap-1.5">
|
||||
{state === "saved" ? <><Check size={14} />Saved to your profile</> : state === "failed" ? "Couldn't save. Try again" : "Save to my profile"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Tiny markdown: status lines (\u001e) become a step list, "- " bullets, "### " headings, **bold** and links.
|
||||
function Reply({ text: raw, live, onPick }: { text: string; live: boolean; onPick?: (answer: string) => void }) {
|
||||
const { body: text, ask, save, budget, rules } = replyBlocks(raw);
|
||||
const lines = text.split("\n");
|
||||
// Each kind of step once, however many times the model repeats it. The latest stays last, so the spinner stays on it.
|
||||
const steps = [...new Set(lines.filter((l) => l.startsWith("\u001e")).map((l) => l.slice(1)).reverse())].reverse();
|
||||
const body = lines.filter((l) => !l.startsWith("\u001e"));
|
||||
const writing = body.some((l) => l.trim());
|
||||
const bold = inline;
|
||||
return (
|
||||
<>
|
||||
{!!steps.length && (
|
||||
<ul className="space-y-1.5 text-[13px] text-muted">
|
||||
{steps.map((name, i) => {
|
||||
const running = live && !writing && i === steps.length - 1;
|
||||
return (
|
||||
<li key={i} className="flex items-center gap-2">
|
||||
{running ? <LoaderCircle size={14} className="animate-spin shrink-0" /> : <Check size={14} className="text-good shrink-0" />}
|
||||
<span className={running ? "text-ink" : ""}>{toolLabel(name)}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{!writing && live && !steps.length && <Dots />}
|
||||
{body.map((line, i) => {
|
||||
if (!line.trim()) return null;
|
||||
if (/^#{1,4} /.test(line)) return <p key={i} className="font-semibold pt-1">{bold(line.replace(/^#+ /, ""))}</p>;
|
||||
const li = line.match(/^\s*([-*]|\d+\.) (.*)/);
|
||||
if (li)
|
||||
return (
|
||||
<p key={i} className="flex gap-2.5">
|
||||
<span className="text-muted tabular shrink-0 min-w-3">{/\d/.test(li[1]) ? li[1] : "•"}</span>
|
||||
<span>{bold(li[2])}</span>
|
||||
</p>
|
||||
);
|
||||
return <p key={i}>{bold(line)}</p>;
|
||||
})}
|
||||
{save && !live && <SaveOffer proposed={save} />}
|
||||
{budget && !live && <BudgetOffer proposed={budget} />}
|
||||
{rules && !live && <RuleOffer proposed={rules} />}
|
||||
{ask && !live && (
|
||||
<div className="space-y-2 pt-1">
|
||||
<p className="font-medium">{ask.q}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ask.options.map((o) => (
|
||||
<button key={o} onClick={() => onPick?.(o)} disabled={!onPick} className="rounded-full border border-line px-3.5 py-1.5 text-sm hover:bg-[var(--hover)] disabled:opacity-50 disabled:hover:bg-transparent">
|
||||
{o}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
// Opening broke syncs any bank that's due (the layout decides), in the background, once per 10 minutes per tab,
|
||||
// then refreshes the page with what came in. Without a deployed webhook this is how new and older history arrives.
|
||||
export function AutoSync({ due }: { due: boolean }) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (!due) return;
|
||||
try {
|
||||
const last = Number(sessionStorage.getItem("broke:autosync"));
|
||||
if (last && Date.now() - last < 10 * 60_000) return;
|
||||
sessionStorage.setItem("broke:autosync", String(Date.now()));
|
||||
} catch {}
|
||||
fetch("/api/plaid/sync", { method: "POST" }).then((r) => r.ok && router.refresh()).catch(() => {});
|
||||
}, [due, router]);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import Link from "next/link";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { billOnCards, CARDS, catOf, fitsCredit, ownedCards, withReferrals, type Card } from "@/lib/cards";
|
||||
import { referralLinks } from "@/lib/cards-data";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import { creditOf } from "@/lib/credit";
|
||||
import { getUser } from "@/lib/data";
|
||||
import { fmtFor, fmtWith } from "@/lib/format";
|
||||
|
||||
const PER_YEAR: Record<string, number> = { WEEKLY: 52, BIWEEKLY: 26, SEMI_MONTHLY: 24, MONTHLY: 12, ANNUALLY: 1 };
|
||||
// Payments that can't go on a card: loans, card payments, transfers. Rent usually costs a card fee, so it's left alone.
|
||||
const NOT_ON_A_CARD = new Set(["LOAN_PAYMENTS", "CREDIT_CARD_PAYMENT", "TRANSFER_IN", "TRANSFER_OUT"]);
|
||||
const RENT = /\b(rent|apartment|apartments|property|landlord|leasing)\b/i;
|
||||
// Bank feeds leave an empty "()" on some names ("Instacart ()").
|
||||
export const billName = (name: string) => name.replace(/\s*\(\s*\)\s*$/, "");
|
||||
|
||||
type Row = {
|
||||
id: string; merchant_name: string; logo_url: string | null; frequency: string; average_amount: number; next_date: string | null;
|
||||
category: { key: string } | null; account: { name: string; custom_name: string | null; official_name: string | null; mask: string | null; type: string } | null;
|
||||
};
|
||||
|
||||
// Every subscription and bill that repeats, which account pays it, and what moving it to a card would earn.
|
||||
// Cards only where the card catalogue applies (US); elsewhere the list on its own. Shared with the plan summary.
|
||||
export async function loadBills() {
|
||||
const { supabase, user } = await getUser();
|
||||
const profile = (user?.user_metadata?.profile ?? {}) as Record<string, unknown>;
|
||||
const country = countryOf(profile.country as string | undefined);
|
||||
const money = fmtWith(fmtFor(profile)).money0;
|
||||
const [{ data: rec }, { data: credit }] = await Promise.all([
|
||||
supabase.from("recurring")
|
||||
.select("id, merchant_name, logo_url, frequency, average_amount:home_average, next_date, category:categories(key), account:accounts(name, custom_name, official_name, mask, type)")
|
||||
.eq("user_id", user!.id).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED"),
|
||||
supabase.from("accounts").select("name, official_name").eq("user_id", user!.id).eq("type", "credit"),
|
||||
]);
|
||||
const rows = ((rec ?? []) as unknown as Row[]).filter((r) => !NOT_ON_A_CARD.has(r.category?.key ?? ""));
|
||||
if (!rows.length) return { items: [], money, country };
|
||||
|
||||
const catalogue = country.cards ? withReferrals(CARDS, referralLinks()) : [];
|
||||
const owned = ownedCards(credit ?? [], catalogue);
|
||||
const band = creditOf(profile)?.band;
|
||||
// Cards to suggest: not one they hold, inside their credit range, no yearly fee (a fee isn't worth it for one bill).
|
||||
const others = catalogue.filter((c) => !owned.includes(c) && fitsCredit(c, band && band !== "unsure" ? band : null) !== false && !(c.fee ?? 0) && !(c.feeYear1 ?? 0));
|
||||
|
||||
const items = rows.map((r) => {
|
||||
const yearly = Number(r.average_amount) * (PER_YEAR[r.frequency] ?? 12);
|
||||
const payingCard: Card | null = r.account?.type === "credit" ? ownedCards([r.account], catalogue)[0] ?? null : null;
|
||||
const rent = RENT.test(r.merchant_name);
|
||||
// On a card that isn't in the catalogue: its rewards are unknown, so no suggestion would be honest.
|
||||
const unknownCard = r.account?.type === "credit" && !payingCard;
|
||||
const o = catalogue.length && !rent && !unknownCard ? billOnCards({ yearly, cat: catOf(r.category?.key), payingCard }, owned, others) : null;
|
||||
const gainMine = o?.mine ? o.mine.earn - o.now : 0;
|
||||
const gainOther = o?.other ? o.other.earn - o.now : 0;
|
||||
return { r, yearly, rent, unknownCard, o, gainMine, gainOther };
|
||||
}).sort((a, b) => b.yearly - a.yearly);
|
||||
|
||||
return { items, money, country };
|
||||
}
|
||||
|
||||
export const CARD_NOTE = "Earnings use each card's rate for that kind of bill, with points valued as on the Cards page. Some billers charge a card fee, so check first. Pay the card in full every month, or the interest wipes out the points.";
|
||||
|
||||
type Item = Awaited<ReturnType<typeof loadBills>>["items"][number];
|
||||
|
||||
// The one line of card advice for a bill, or nothing to say. Also on the Recurring page.
|
||||
export function BillAdvice({ item: { r, rent, unknownCard, o, gainMine, gainOther }, money }: { item: Item; money: (n: number) => string }) {
|
||||
if (/\bbilt\b/i.test(r.merchant_name)) return <p className="text-sm text-muted">Paid through Bilt. Your Bilt account shows what it earns.</p>;
|
||||
if (unknownCard) return <p className="text-sm text-muted">Already on a card. broke doesn't know that card's rewards.</p>;
|
||||
if (rent) return <p className="text-sm text-muted">Rent on a card usually costs a fee bigger than the points, so it stays as it is.</p>;
|
||||
if (o && gainMine >= 1) return <p className="text-sm">Pay it with your {o.mine!.card.name}: about <span className="font-medium">{money(gainMine)} a year</span> back{o.now ? `, ${money(gainMine)} more than now` : ""}.</p>;
|
||||
if (o && o.now > 0) return <p className="text-sm text-muted">Already earning about {money(o.now)} a year on your {o.mine?.card.name ?? "card"}.</p>;
|
||||
if (o?.other && gainOther >= 5) return <p className="text-sm text-muted">A {o.other.card.issuer} {o.other.card.name} would earn about {money(gainOther)} a year on it. <Link href="/cards" className="text-ink underline underline-offset-2">Compare cards</Link></p>;
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function BillsOnCards() {
|
||||
const { items, money, country } = await loadBills();
|
||||
if (!items.length) return null;
|
||||
const total = items.reduce((s, x) => s + x.yearly, 0);
|
||||
const switchable = items.filter((x) => x.gainMine >= 1);
|
||||
const gain = switchable.reduce((s, x) => s + x.gainMine, 0);
|
||||
const from = (a: Row["account"]) => {
|
||||
if (!a) return "an account broke can't see";
|
||||
const n = a.custom_name || a.name;
|
||||
return a.mask && !n.includes(a.mask) ? `${n} ··${a.mask}` : n;
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="card overflow-hidden">
|
||||
<div className="p-6 pb-4 space-y-1">
|
||||
<div className="card-title">Your subscriptions and bills</div>
|
||||
<p className="text-sm text-muted">
|
||||
{items.length} that repeat, about {money(total)} a year.
|
||||
{gain >= 1 && <> Paying {switchable.length === 1 ? "one" : switchable.length} with a card you already have would earn about <span className="text-ink font-medium">{money(gain)} a year</span> back.</>}
|
||||
</p>
|
||||
</div>
|
||||
<ul className="divide-y divide-line border-t border-line">
|
||||
{items.map((item) => { const { r, yearly } = item; return (
|
||||
<li key={r.id} className="px-6 py-4 flex gap-3.5">
|
||||
<Merchant name={r.merchant_name} logo={r.logo_url} />
|
||||
<div className="flex-1 min-w-0 space-y-0.5">
|
||||
<div className="flex justify-between gap-3">
|
||||
<span className="font-medium truncate">{billName(r.merchant_name)}</span>
|
||||
<span className="tabular shrink-0">{money(yearly)}<span className="text-muted text-sm"> a year</span></span>
|
||||
</div>
|
||||
<p className="text-sm text-muted">Paid from {from(r.account)}{r.next_date ? `, next on ${new Date(r.next_date + "T12:00:00Z").toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" })}` : ""}</p>
|
||||
<BillAdvice item={item} money={money} />
|
||||
</div>
|
||||
</li>
|
||||
); })}
|
||||
</ul>
|
||||
{country.cards && (
|
||||
<p className="px-6 py-3.5 border-t border-line text-xs text-muted">
|
||||
{CARD_NOTE}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client";
|
||||
|
||||
import { Star, X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Bookmark = { id: string; href: string; label: string };
|
||||
const CHANGED = "broke:bookmarks";
|
||||
|
||||
// The current in-app URL, query string included, so a filtered view can be saved.
|
||||
function useHref() {
|
||||
const path = usePathname();
|
||||
const params = useSearchParams().toString();
|
||||
return params ? `${path}?${params}` : path;
|
||||
}
|
||||
|
||||
export function BookmarkButton({ title }: { title: string }) {
|
||||
const href = useHref();
|
||||
const params = useSearchParams();
|
||||
const [id, setId] = useState<string | null>(null);
|
||||
const [available, setAvailable] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
createClient()
|
||||
.from("bookmarks")
|
||||
.select("id")
|
||||
.eq("href", href)
|
||||
.maybeSingle()
|
||||
.then(({ data, error }) => {
|
||||
setAvailable(!error); // table missing until migration 0003 runs: hide the star
|
||||
setId((data?.id as string) ?? null);
|
||||
});
|
||||
}, [href]);
|
||||
|
||||
if (!available || !title) return null;
|
||||
|
||||
async function toggle() {
|
||||
const db = createClient();
|
||||
if (id) {
|
||||
await db.from("bookmarks").delete().eq("id", id);
|
||||
setId(null);
|
||||
} else {
|
||||
if (!/^\/(?![/\\])/.test(href)) return; // in-app paths only: "//host" and "/\\host" leave the site
|
||||
const q = params.get("q");
|
||||
const label = q ? `${title}: "${q}"` : params.size ? `${title} (filtered)` : title;
|
||||
const user = (await db.auth.getSession()).data.session?.user; // local; RLS checks the insert
|
||||
const { data } = await db.from("bookmarks").insert({ user_id: user!.id, href, label, kind: "page" }).select("id").single();
|
||||
setId((data?.id as string) ?? null);
|
||||
}
|
||||
window.dispatchEvent(new Event(CHANGED));
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={toggle}
|
||||
aria-pressed={!!id}
|
||||
aria-label={id ? "Remove bookmark" : "Bookmark this page"}
|
||||
title={id ? "Remove bookmark" : "Bookmark this page"}
|
||||
className={`p-1.5 rounded-lg hover:bg-canvas ${id ? "text-amber-500" : "text-muted hover:text-ink"}`}
|
||||
>
|
||||
<Star size={17} fill={id ? "currentColor" : "none"} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SavedList() {
|
||||
const current = useHref();
|
||||
const [items, setItems] = useState<Bookmark[]>([]);
|
||||
const load = useCallback(() => {
|
||||
createClient()
|
||||
.from("bookmarks")
|
||||
.select("id, href, label")
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(10)
|
||||
.then(({ data }) => setItems((data ?? []) as Bookmark[]));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
window.addEventListener(CHANGED, load);
|
||||
return () => window.removeEventListener(CHANGED, load);
|
||||
}, [load]);
|
||||
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<div className="pt-4 space-y-1">
|
||||
<div className="section-label px-3 pb-1">Saved</div>
|
||||
{items.map((b) => (
|
||||
<div key={b.id} className="group flex items-center rounded-xl hover:bg-canvas/60">
|
||||
<Link href={b.href} className={`flex-1 min-w-0 flex items-center gap-3 px-3 py-2 text-sm truncate ${b.href === current ? "font-medium" : "text-muted"}`}>
|
||||
<Star size={14} className="text-amber-500 shrink-0" fill="currentColor" />
|
||||
<span className="truncate">{b.label}</span>
|
||||
</Link>
|
||||
<button
|
||||
aria-label={`Remove ${b.label}`}
|
||||
onClick={async () => {
|
||||
await createClient().from("bookmarks").delete().eq("id", b.id);
|
||||
window.dispatchEvent(new Event(CHANGED));
|
||||
}}
|
||||
className="opacity-0 group-hover:opacity-100 focus:opacity-100 p-1.5 mr-1 text-muted hover:text-ink"
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import { CircleDashed, LayoutList, Minus, Plus, Sparkles, Table2, Trash2, X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { createCategory, SETUP, writeBudgets, type Changes } from "@/components/BudgetOffer";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { PageDates } from "@/components/PageDates";
|
||||
import { CATEGORY_ICON_KEYS, CategoryIcon } from "@/components/Icons";
|
||||
import { CountUp, EASE, firstVisit, reduced } from "@/components/motion";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { budgetContext, daysBetween, merge, month, perDay, scaleBudget, startPeriod, step, tone, yearView, type MonthSpend } from "@/lib/budget";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
export type BudgetRange = { from: string; to: string; start: string; end: string; spent: Record<string, number> };
|
||||
export type BudgetCat = { id: string; label: string; icon: string; color: string; spent: number; last: number; avg: number; suggested: number; main: boolean };
|
||||
|
||||
// Missing table (setup not finished) gets a friendly pointer (SETUP), never the technical cause.
|
||||
// Bars use the app's chart blue, like the rest of the app; only an overspend turns red.
|
||||
const TEXT = { ok: "text-muted", near: "text-ink", over: "text-bad" };
|
||||
|
||||
export function BudgetEditor({ cats: all, initial, year, range, today, income, now, tableMissing, aside }: { cats: BudgetCat[]; initial: Record<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [budgets, setBudgets] = useState(initial);
|
||||
const [error, setError] = useState(tableMissing ? SETUP : "");
|
||||
const [sheet, setSheet] = useState<"add" | "suggest" | null>(null);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
const [fresh, setFresh] = useState<string | null>(null);
|
||||
// List or table, remembered on this device. Read after mount so the server and first client render agree.
|
||||
const [view, setView] = useState<"list" | "table">("list");
|
||||
useEffect(() => {
|
||||
try { if (localStorage.getItem("budget-view") === "table") setView("table"); } catch {}
|
||||
}, []);
|
||||
const pickView = (v: "list" | "table") => {
|
||||
setView(v);
|
||||
try { localStorage.setItem("budget-view", v); } catch {}
|
||||
};
|
||||
|
||||
const m = month(new Date(now));
|
||||
const d = new Date(now);
|
||||
const lastMonth = dateLabel(new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 1, 1)).toISOString().slice(0, 10), { month: "long" });
|
||||
// This month or last: the same rows with "spent" swapped, so the list, table and summary all follow.
|
||||
const [period, setPeriod] = useState<"this" | "last" | "year" | "custom">(() => range ? "custom" : startPeriod(m.day, all.filter((c) => c.id in initial).reduce((s, c) => s + c.last, 0)));
|
||||
const past = period === "last";
|
||||
const cats = past ? all.map((c) => ({ ...c, spent: c.last, last: c.spent })) : all;
|
||||
const budgeted = cats.filter((c) => c.id in budgets).sort((a, b) => a.label.localeCompare(b.label));
|
||||
const open = cats.filter((c) => !(c.id in budgets)).sort((a, b) => b.avg - a.avg || a.label.localeCompare(b.label));
|
||||
const unbudgeted = open.filter((c) => c.spent > 0).sort((a, b) => b.spent - a.spent);
|
||||
const total = budgeted.reduce((s, c) => s + budgets[c.id], 0);
|
||||
const spent = budgeted.reduce((s, c) => s + c.spent, 0);
|
||||
const outside = unbudgeted.reduce((s, c) => s + c.spent, 0);
|
||||
const t = tone(spent, total);
|
||||
const hasBudget = budgeted.length > 0;
|
||||
|
||||
useGSAP(
|
||||
() => {
|
||||
if (reduced() || !firstVisit("budget-bars")) return;
|
||||
gsap.from("[data-fill]", { scaleX: 0, transformOrigin: "left", duration: 0.6, ease: "power3.out", stagger: 0.03, clearProps: "transform" });
|
||||
},
|
||||
{ scope: root, dependencies: [hasBudget] },
|
||||
);
|
||||
useGSAP(
|
||||
() => {
|
||||
if (fresh && !reduced()) gsap.from(`[data-row="${fresh}"]`, { opacity: 0, y: -8, duration: 0.3, ease: EASE, clearProps: "transform,opacity" });
|
||||
},
|
||||
{ scope: root, dependencies: [fresh] },
|
||||
);
|
||||
|
||||
// Optimistic: the screen changes first, the save runs after, and a failed save puts the old values back.
|
||||
// ponytail: rapid nudges send overlapping upserts, last-to-land wins; queue writes if that ever shows.
|
||||
async function apply(changes: Changes, done?: string) {
|
||||
const prev: Changes = Object.fromEntries(Object.keys(changes).map((k) => [k, budgets[k] ?? null]));
|
||||
setBudgets((b) => merge(b, changes));
|
||||
const err = await writeBudgets(changes);
|
||||
if (err) {
|
||||
setBudgets((b) => merge(b, prev));
|
||||
if (err === SETUP) setError(SETUP);
|
||||
else toast(err);
|
||||
} else if (done) toast(done, () => apply(prev));
|
||||
}
|
||||
|
||||
function add(c: BudgetCat) {
|
||||
setSheet(null);
|
||||
setFresh(c.id);
|
||||
if (!c.suggested) setEditing(c.id);
|
||||
apply({ [c.id]: c.suggested }, c.suggested ? `Added ${c.label} · ${money0(c.suggested)}` : undefined);
|
||||
}
|
||||
|
||||
// Fills main categories that have no budget yet; amounts you set stay.
|
||||
const suggestion = cats.filter((c) => c.main && !(c.id in budgets)).sort((a, b) => b.suggested - a.suggested);
|
||||
const useSuggested = () => {
|
||||
setSheet(null);
|
||||
apply(Object.fromEntries(suggestion.map((c) => [c.id, c.suggested])), `Added ${suggestion.length} budgets`);
|
||||
};
|
||||
|
||||
const sheets = (
|
||||
<>
|
||||
<Sheet open={sheet === "add"} onClose={() => setSheet(null)} title="Add a budget">
|
||||
{open.length ? (
|
||||
<ul>
|
||||
{open.map((c) => (
|
||||
<li key={c.id} className="flex items-center gap-3 px-5 md:px-6 py-3 border-t border-line">
|
||||
<CategoryIcon icon={c.icon} color={c.color} size={34} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium truncate">{c.label}</div>
|
||||
<div className="text-xs text-muted tabular">Last month {money0(c.last)} · 3-mo avg {money0(c.avg)}</div>
|
||||
</div>
|
||||
<button className="btn tabular shrink-0" onClick={() => add(c)}>
|
||||
{c.suggested ? <>+ {money0(c.suggested)}</> : "Set amount"}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="px-6 pb-6 text-sm text-muted">Every category has a budget.</p>
|
||||
)}
|
||||
<NewCategory taken={cats.map((c) => c.label)} onDone={(id, label, amount) => { setSheet(null); setBudgets((x) => ({ ...x, [id]: amount })); setFresh(id); toast(`Added ${label}`); }} />
|
||||
</Sheet>
|
||||
<Sheet open={sheet === "suggest"} onClose={() => setSheet(null)} title="Suggested budgets">
|
||||
<Suggest cats={suggestion} income={0} onUse={useSuggested} disabled={error === SETUP} sticky />
|
||||
</Sheet>
|
||||
</>
|
||||
);
|
||||
|
||||
if (!hasBudget)
|
||||
return (
|
||||
<div ref={root} className="space-y-6">
|
||||
<div className="card overflow-hidden">
|
||||
<div className="p-6 md:p-8 pb-4 md:pb-4 max-w-xl space-y-2">
|
||||
<h2 className="text-2xl font-semibold">Set a budget from how you really spend</h2>
|
||||
<p className="text-sm text-muted">These are your averages for the last 3 months, rounded up, and never less than you've spent this month. Use them as they are, or add one category at a time.</p>
|
||||
</div>
|
||||
<Suggest cats={suggestion} income={income} onUse={useSuggested} disabled={error === SETUP} alt={<button className="btn" onClick={() => setSheet("add")}>Add one at a time</button>} />
|
||||
{error && <div className="px-6 md:px-8 pb-6"><ErrorNote error={error} /></div>}
|
||||
{sheets}
|
||||
</div>
|
||||
<AskBudget cats={budgeted} budgets={budgets} />
|
||||
{aside}
|
||||
</div>
|
||||
);
|
||||
|
||||
const left = total - spent;
|
||||
return (
|
||||
<div ref={root} className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 px-1">
|
||||
<div className="section-label">Your budgets</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div className="flex rounded-full border border-line p-0.5" role="group" aria-label="View">
|
||||
{([["list", LayoutList, "List"], ["table", Table2, "Table"]] as const).map(([v, Icon, name]) => (
|
||||
<button key={v} aria-label={name} aria-pressed={view === v} title={name} onClick={() => pickView(v)} className={`size-7 grid place-items-center rounded-full ${view === v ? "bg-ink text-on-ink" : "text-muted hover:bg-[var(--hover)]"}`}><Icon size={15} /></button>
|
||||
))}
|
||||
</div>
|
||||
<button className="btn inline-flex items-center gap-1.5 whitespace-nowrap" onClick={() => setSheet("suggest")} disabled={error === SETUP}><Sparkles size={15} /> Suggest</button>
|
||||
<button className="btn-primary inline-flex items-center gap-1.5 whitespace-nowrap !py-1.5" onClick={() => setSheet("add")} disabled={error === SETUP}><Plus size={16} /> Add budget</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pill-tabs" role="group" aria-label="Month">
|
||||
{([["this", "This month"], ["last", "Last month"], ["year", "This year"], ["custom", "Custom dates"]] as const).map(([p, name]) => (
|
||||
<button key={p} aria-pressed={period === p} onClick={() => setPeriod(p)} className={`pill-tab !py-1 !px-3 ${period === p ? "pill-tab-active" : ""}`}>{name}</button>
|
||||
))}
|
||||
</div>
|
||||
<AskBudget cats={budgeted} budgets={budgets} />
|
||||
{period === "custom" ? (
|
||||
<div className="space-y-3">
|
||||
<PageDates path="/budgets" from={range?.from ?? ""} to={range?.to ?? ""} today={today} />
|
||||
{range && <RangeView range={range} cats={budgeted} budgets={budgets} />}
|
||||
</div>
|
||||
) : period === "year" ? (
|
||||
<YearView months={year} cats={budgeted} budgets={budgets} />
|
||||
) : view === "table" ? (
|
||||
<BudgetTable cats={budgeted} open={open} budgets={budgets} total={total} spent={spent} past={past} apply={apply} onAdd={(c, n) => { setFresh(c.id); apply({ [c.id]: n }, `Added ${c.label} · ${money0(n)}`); }} />
|
||||
) : (
|
||||
<section className="card overflow-hidden">
|
||||
<ul>
|
||||
{budgeted.map((c) => (
|
||||
<Row
|
||||
key={c.id}
|
||||
c={c}
|
||||
past={past}
|
||||
amount={budgets[c.id]}
|
||||
editing={editing === c.id}
|
||||
onEdit={() => setEditing(c.id)}
|
||||
onCancel={() => setEditing(null)}
|
||||
onSave={(n) => {
|
||||
setEditing(null);
|
||||
if (n !== budgets[c.id]) apply({ [c.id]: n });
|
||||
}}
|
||||
onDelete={() => {
|
||||
setEditing(null);
|
||||
apply({ [c.id]: null }, `Removed ${c.label} budget`);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{outside > 0 && (
|
||||
<li className="border-t border-line">
|
||||
<button onClick={() => setSheet("add")} className="row-hover w-full flex items-center gap-3 px-5 md:px-6 py-4 text-left">
|
||||
<span className="size-9 rounded-[30%] border border-dashed border-muted/50 text-muted grid place-items-center shrink-0"><CircleDashed size={16} /></span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block font-medium">Unbudgeted spending</span>
|
||||
<span className="block text-xs text-muted truncate tabular">{unbudgeted.slice(0, 3).map((c) => `${c.label} ${money0(c.spent)}`).join(" · ")}</span>
|
||||
</span>
|
||||
<span className="tabular font-medium">{money0(outside)}</span>
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-3">
|
||||
<div className="section-label px-1">Summary</div>
|
||||
<section className="card p-6 space-y-5">
|
||||
<div>
|
||||
<div className="card-title">{past ? lastMonth : dateLabel(now.slice(0, 10), { month: "long" })}</div>
|
||||
<div className="figure mt-1">
|
||||
{left >= 0 ? <CountUp value={left} format="money0" /> : money0(-left)}{" "}
|
||||
<span className={`text-base font-medium tracking-normal ${left >= 0 ? "text-muted" : "text-bad"}`}>{left >= 0 ? (past ? "under" : "left") : "over"}</span>
|
||||
</div>
|
||||
<div className="text-sm text-muted tabular">{money0(spent)} spent of {money0(total)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Bar used={total ? spent / total : 1} pace={past ? undefined : m.pace} tone={t} color="var(--chart)" thick />
|
||||
{!past && (
|
||||
<div className="relative h-4 mt-1.5 text-[11px] text-muted">
|
||||
<span className="absolute -translate-x-1/2 whitespace-nowrap" style={{ left: `${Math.min(90, Math.max(10, m.pace * 100))}%` }}>Today</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error && <ErrorNote error={error} />}
|
||||
</section>
|
||||
<section className="card overflow-hidden">
|
||||
{!past && <Stat label="Days left" value={String(m.left)} />}
|
||||
{!past && <Stat label="Left to spend per day" value={money0(perDay(total, spent, m.left))} />}
|
||||
<Stat label={past ? `Unbudgeted in ${lastMonth}` : "Unbudgeted this month"} value={money0(outside)} />
|
||||
{income > 0 && (
|
||||
<p className="px-5 py-4 border-t border-line text-sm text-muted">
|
||||
Income about <span className="text-ink tabular">{money0(income)}</span>/mo.{" "}
|
||||
{outside > 0 && <>Your budgets plus <span className="text-ink tabular">{money0(outside)}</span> of unbudgeted spending {past ? `in ${lastMonth}` : "this month"} </>}
|
||||
{outside > 0
|
||||
? income >= total + outside ? <>leave <span className="text-ink tabular">{money0(income - total - outside)}</span> to save.</> : <>come to <span className="text-ink tabular">{money0(total + outside - income)}</span> more than you earn.</>
|
||||
: income >= total ? <>Your budgets leave <span className="text-ink tabular">{money0(income - total)}</span> to save.</> : <>Your budgets are <span className="text-ink tabular">{money0(total - income)}</span> more than you earn.</>}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
{aside}
|
||||
</div>
|
||||
{sheets}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Any dates against the budget. Monthly amounts are scaled to the number of days, so 2 weeks gets about half a month's budget.
|
||||
function RangeView({ range, cats, budgets }: { range: BudgetRange; cats: BudgetCat[]; budgets: Record<string, number> }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const days = daysBetween(range.start, range.end);
|
||||
const rows = cats.map((c) => ({ c, budget: scaleBudget(budgets[c.id], days), spent: range.spent[c.id] ?? 0 }));
|
||||
const spent = rows.reduce((s, r) => s + r.spent, 0), budget = rows.reduce((s, r) => s + r.budget, 0);
|
||||
const diff = budget - spent;
|
||||
const label = (d: string) => dateLabel(d, { month: "short", day: "numeric", year: "numeric" });
|
||||
return (
|
||||
<section className="card p-5 md:p-6 space-y-4">
|
||||
<div>
|
||||
<div className="card-title">{money0(spent)} spent of {money0(budget)}</div>
|
||||
<p className={`text-sm ${diff < 0 ? "text-bad" : "text-muted"}`}>{money0(Math.abs(diff))} {diff < 0 ? "over" : "under"}, {label(range.start)} to {label(range.end)}</p>
|
||||
</div>
|
||||
<ul className="space-y-3">
|
||||
{rows.map(({ c, budget: b, spent: s }) => {
|
||||
const over = s - b;
|
||||
return (
|
||||
<li key={c.id}>
|
||||
<div className="flex justify-between gap-3 text-sm mb-1.5">
|
||||
<span className="flex items-center gap-2.5 min-w-0"><CategoryIcon icon={c.icon} color={c.color} size={24} /><span className="truncate">{c.label}</span></span>
|
||||
<span className="tabular text-right shrink-0"><span className={over >= 1 ? "text-bad" : "text-muted"}>{money0(Math.abs(over))} {over >= 1 ? "over" : "under"}</span><span className="text-muted"> · {money0(s)} / {money0(b)}</span></span>
|
||||
</div>
|
||||
<Bar used={b ? s / b : 1} tone={tone(s, b)} color="var(--chart)" />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="text-xs text-muted">Your monthly budgets scaled to {days === 1 ? "1 day" : `${days} days`}. To change an amount, go to This month.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Each month so far this year against the budget, for all budgets or one. Every month uses today's amounts: budgets keep no history.
|
||||
function YearView({ months, cats, budgets }: { months: MonthSpend[]; cats: BudgetCat[]; budgets: Record<string, number> }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const [only, setOnly] = useState("");
|
||||
const y = yearView(months, budgets, only || null);
|
||||
const diff = y.budget - y.spent;
|
||||
const options = [{ value: "", label: "All budgets" }, ...cats.map((c) => ({ value: c.id, label: c.label }))];
|
||||
return (
|
||||
<section className="card p-5 md:p-6 space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="card-title">{money0(y.spent)} spent of {money0(y.budget)}</div>
|
||||
{!!y.rows.length && <p className={`text-sm ${diff < 0 ? "text-bad" : "text-muted"}`}>{money0(Math.abs(diff))} {diff < 0 ? "over" : "under"} budget this year</p>}
|
||||
</div>
|
||||
<div className="w-48"><Dropdown label="Which budget" placeholder="All budgets" value={only} options={options} onChange={setOnly} searchable /></div>
|
||||
</div>
|
||||
{y.rows.length ? (
|
||||
<ul className="space-y-3">
|
||||
{y.rows.map((r) => {
|
||||
const over = r.spent - r.budget;
|
||||
return (
|
||||
<li key={r.month}>
|
||||
<div className="flex justify-between gap-3 text-sm mb-1.5">
|
||||
<span>{dateLabel(`${r.month}-01`, { month: "long" })}</span>
|
||||
<span className="tabular text-right"><span className={over > 0 ? "text-bad" : "text-muted"}>{money0(Math.abs(over))} {over > 0 ? "over" : "under"}</span><span className="text-muted"> · {money0(r.spent)} / {money0(r.budget)}</span></span>
|
||||
</div>
|
||||
<Bar used={r.budget ? r.spent / r.budget : 1} tone={tone(r.spent, r.budget)} color="var(--chart)" />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : <p className="text-sm text-muted">No spending in this budget this year.</p>}
|
||||
<p className="text-xs text-muted">Each month is compared with your budget as it is today.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Say the change in plain words. The AI answers with a budget block; nothing saves until Apply (BudgetOffer).
|
||||
// Only the category names and the user's own budget amounts go in the message; spending comes through the AI's own gated tools.
|
||||
function AskBudget({ cats, budgets }: { cats: BudgetCat[]; budgets: Record<string, number> }) {
|
||||
const { ask } = useAssistant();
|
||||
const [q, setQ] = useState("");
|
||||
function send(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!q.trim()) return;
|
||||
ask(`${q.trim()}${budgetContext(cats.map((c) => [c.label, budgets[c.id]]))}`);
|
||||
setQ("");
|
||||
}
|
||||
return (
|
||||
<form onSubmit={send} className="flex gap-2">
|
||||
<label className="flex-1 min-w-0 flex items-center gap-2 border border-line rounded-full px-3.5 h-10 bg-surface focus-within:border-ink">
|
||||
<Sparkles size={15} className="text-muted shrink-0" />
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} aria-label="Ask AI to change your budget" placeholder="Ask AI: cut eating out by 100 and add a Pets budget of 50" className="w-full text-sm outline-none bg-transparent" />
|
||||
</label>
|
||||
<button disabled={!q.trim()} className="btn shrink-0">Ask</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// The same budgets as a sheet: type an amount and press Enter or Tab away to save it, Esc puts it back.
|
||||
function BudgetTable({ cats, open, budgets, total, spent, past, apply, onAdd }: {
|
||||
cats: BudgetCat[]; open: BudgetCat[]; budgets: Record<string, number>; total: number; spent: number; past: boolean; apply: (c: Changes, done?: string) => void; onAdd: (c: BudgetCat, n: number) => void;
|
||||
}) {
|
||||
const { money0, symbol } = useMoney();
|
||||
const [pick, setPick] = useState("");
|
||||
const [amount, setAmount] = useState("");
|
||||
const chosen = open.find((c) => c.id === pick);
|
||||
const n = Math.round(Number(amount));
|
||||
const add = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!chosen || !amount.trim() || !(n >= 0)) return;
|
||||
onAdd(chosen, n);
|
||||
setPick(""); setAmount("");
|
||||
};
|
||||
const num = "px-3 py-2.5 text-right tabular whitespace-nowrap";
|
||||
const extra = "hidden @2xl:table-cell";
|
||||
const wide = "hidden @lg:table-cell"; // phones keep Budget and Left
|
||||
return (
|
||||
<section className="card">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-xs text-muted text-left border-b border-line">
|
||||
<th className="font-normal pl-5 pr-3 py-2.5">Category</th>
|
||||
<th className={`font-normal ${num}`}>Budget</th>
|
||||
<th className={`font-normal ${num} ${wide}`}>Spent</th>
|
||||
<th className={`font-normal ${num}`}>{past ? "Under" : "Left"}</th>
|
||||
<th className={`font-normal ${num} ${extra}`}>{past ? "This month" : "Last month"}</th>
|
||||
<th className={`font-normal ${num} ${extra}`}>3-mo avg</th>
|
||||
<th className="w-10" aria-label="Remove" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{cats.map((c) => {
|
||||
const left = budgets[c.id] - c.spent;
|
||||
return (
|
||||
<tr key={c.id} data-row={c.id} className="border-b border-line">
|
||||
<td className="pl-5 pr-3 py-1.5">
|
||||
<Link href={`/transactions?category=${c.id}&range=30`} className="flex items-center gap-2.5 min-w-0 font-medium hover:underline underline-offset-2">
|
||||
<CategoryIcon icon={c.icon} color={c.color} size={26} /><span className="truncate">{c.label}</span>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-1.5 py-1.5 text-right">
|
||||
<AmountCell key={budgets[c.id]} label={c.label} value={budgets[c.id]} symbol={symbol} onSave={(v) => apply({ [c.id]: v })} />
|
||||
</td>
|
||||
<td className={`${num} ${wide}`}>{money0(c.spent)}</td>
|
||||
<td className={`${num} ${left < 0 ? "text-bad" : ""}`}>{left < 0 ? `-${money0(-left)}` : money0(left)}</td>
|
||||
<td className={`${num} ${extra} text-muted`}>{money0(c.last)}</td>
|
||||
<td className={`${num} ${extra} text-muted`}>{money0(c.avg)}</td>
|
||||
<td className="pr-2 text-right">
|
||||
<button onClick={() => apply({ [c.id]: null }, `Removed ${c.label} budget`)} aria-label={`Remove ${c.label} budget`} className="size-8 inline-grid place-items-center rounded-full text-muted hover:text-bad hover:bg-[var(--hover-strong)]"><Trash2 size={15} /></button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="font-medium border-b border-line">
|
||||
<td className="pl-5 pr-3 py-2.5">Total</td>
|
||||
<td className={num}>{money0(total)}</td>
|
||||
<td className={`${num} ${wide}`}>{money0(spent)}</td>
|
||||
<td className={`${num} ${total - spent < 0 ? "text-bad" : ""}`}>{total - spent < 0 ? `-${money0(spent - total)}` : money0(total - spent)}</td>
|
||||
<td className={extra} /><td className={extra} /><td />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
{!!open.length && (
|
||||
<form onSubmit={add} className="flex flex-wrap items-center gap-2 px-5 py-3">
|
||||
<div className="basis-full @lg:basis-0 flex-1 min-w-0">
|
||||
<Dropdown label="Category to add" value={pick} placeholder="Add a category" searchable options={open.map((c) => ({ value: c.id, label: c.label }))}
|
||||
onChange={(id) => { setPick(id); setAmount(String(open.find((c) => c.id === id)?.suggested || "")); }} />
|
||||
</div>
|
||||
<label className="flex items-center border border-line rounded-xl px-3 h-10 bg-surface focus-within:border-ink w-28 shrink-0">
|
||||
<span className="text-sm text-muted">{symbol}</span>
|
||||
<input inputMode="numeric" value={amount} onChange={(e) => setAmount(e.target.value.replace(/[^\d.]/g, ""))} placeholder="0" aria-label="Monthly budget" className="w-full ml-1 text-sm tabular outline-none bg-transparent" />
|
||||
</label>
|
||||
<button disabled={!chosen || !amount.trim()} className="btn shrink-0 inline-flex items-center gap-1.5"><Plus size={15} /> Add</button>
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AmountCell({ label, value, symbol, onSave }: { label: string; value: number; symbol: string; onSave: (n: number) => void }) {
|
||||
const [v, setV] = useState(String(value));
|
||||
const commit = () => {
|
||||
const n = Math.round(Number(v));
|
||||
if (v.trim() === "" || !Number.isFinite(n) || n < 0) setV(String(value));
|
||||
else if (n !== value) onSave(n);
|
||||
};
|
||||
return (
|
||||
<label className="inline-flex items-center justify-end gap-0.5 rounded-lg border border-transparent hover:border-line focus-within:border-ink px-1.5 h-8">
|
||||
<span className="text-muted">{symbol}</span>
|
||||
<input inputMode="numeric" value={v} aria-label={`${label} budget`} onFocus={(e) => e.target.select()} onChange={(e) => setV(e.target.value.replace(/[^\d.]/g, ""))} onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") e.currentTarget.blur();
|
||||
if (e.key === "Escape") { setV(String(value)); requestAnimationFrame(() => (document.activeElement as HTMLElement)?.blur()); }
|
||||
}}
|
||||
style={{ width: `${Math.max(v.length, 2) + 1}ch` }} className="text-right tabular outline-none bg-transparent" />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4 px-5 py-4 border-b border-line last:border-0">
|
||||
<span>{label}</span>
|
||||
<span className="tabular font-medium">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Progress bar with a thin pace marker: where you'd be today if you spent evenly through the month.
|
||||
export function Bar({ used, pace, tone: t, color, thick }: { used: number; pace?: number; tone: "ok" | "near" | "over"; color: string; thick?: boolean }) {
|
||||
return (
|
||||
<div className={`relative ${thick ? "h-2.5" : "h-1.5"} rounded-full`} style={{ background: `color-mix(in srgb, ${color} 14%, var(--surface))` }}>
|
||||
<div className="absolute inset-0 rounded-full overflow-hidden">
|
||||
<div data-fill className="h-full rounded-full transition-[width] duration-300" style={{ width: `${Math.min(used, 1) * 100}%`, background: t === "over" ? "var(--bad)" : color }} />
|
||||
</div>
|
||||
{pace != null && <div className="absolute inset-y-0 w-[3px] -ml-[1.5px] bg-surface" style={{ left: `${pace * 100}%` }} title="Where you'd be at an even pace" />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ c, past, amount, editing, onEdit, onCancel, onSave, onDelete }: {
|
||||
c: BudgetCat; past: boolean; amount: number; editing: boolean; onEdit: () => void; onCancel: () => void; onSave: (n: number) => void; onDelete: () => void;
|
||||
}) {
|
||||
const { money0 } = useMoney();
|
||||
const t = tone(c.spent, amount);
|
||||
const status = t === "over" ? `${money0(c.spent - amount)} over` : `${money0(amount - c.spent)} ${past ? "under" : "left"}`;
|
||||
return (
|
||||
<li data-row={c.id} className="px-5 md:px-6 py-4 border-b border-line last:border-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<CategoryIcon icon={c.icon} color={c.color} size={36} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<Link href={`/transactions?category=${c.id}&range=30`} className="block font-medium truncate hover:underline underline-offset-2">{c.label}</Link>
|
||||
<div className="text-xs tabular">
|
||||
<span className={TEXT[t]}>{status}</span>
|
||||
<span className="text-muted"> · {past ? "this month" : "last month"} {money0(c.last)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{!editing && (
|
||||
<button onClick={onEdit} aria-label={`Edit ${c.label} budget`} className="tabular text-right rounded-xl px-2.5 py-1.5 -mr-2.5 hover:bg-[var(--hover-strong)] shrink-0">
|
||||
<span className="font-medium">{money0(c.spent)}</span>
|
||||
<span className="text-muted"> / {money0(amount)}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 pl-12">
|
||||
<Bar used={amount ? c.spent / amount : 1} tone={t} color="var(--chart)" />
|
||||
</div>
|
||||
{editing && <Editor key={amount} label={c.label} value={amount} onSave={onSave} onCancel={onCancel} onDelete={onDelete} />}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
// Inline amount editor: type, Enter saves, Esc cancels, -/+ step by a round amount.
|
||||
function Editor({ label, value, onSave, onCancel, onDelete }: { label: string; value: number; onSave: (n: number) => void; onCancel: () => void; onDelete: () => void }) {
|
||||
const { symbol } = useMoney();
|
||||
const [v, setV] = useState(String(value));
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => input.current?.select(), []);
|
||||
const n = Number(v);
|
||||
const commit = () => (v.trim() !== "" && Number.isFinite(n) && n >= 0 ? onSave(Math.round(n)) : onCancel());
|
||||
const nudge = (d: 1 | -1) => {
|
||||
const cur = Number.isFinite(n) ? n : value;
|
||||
setV(String(Math.max(0, Math.round(cur + d * step(d < 0 ? cur - 1 : cur)))));
|
||||
input.current?.focus();
|
||||
};
|
||||
const icon = "size-8 md:size-9 grid place-items-center rounded-full border border-line hover:bg-[var(--hover-strong)] shrink-0";
|
||||
return (
|
||||
<div className="mt-3 md:pl-12 flex items-center gap-1.5 md:gap-2">
|
||||
<button type="button" className={icon} onClick={() => nudge(-1)} aria-label="Less"><Minus size={15} /></button>
|
||||
<label className="flex items-center border border-line rounded-full px-3 h-8 md:h-9 bg-surface min-w-0 focus-within:border-ink">
|
||||
<span className="text-sm text-muted">{symbol}</span>
|
||||
<input
|
||||
ref={input}
|
||||
inputMode="numeric"
|
||||
value={v}
|
||||
onChange={(e) => setV(e.target.value.replace(/[^\d.]/g, ""))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") commit();
|
||||
if (e.key === "Escape") onCancel();
|
||||
}}
|
||||
aria-label={`${label} budget`}
|
||||
className="w-14 text-sm tabular outline-none bg-transparent"
|
||||
/>
|
||||
</label>
|
||||
<button type="button" className={icon} onClick={() => nudge(1)} aria-label="More"><Plus size={15} /></button>
|
||||
<button type="button" className="btn-primary px-4 py-1.5" onClick={commit}>Save</button>
|
||||
<span className="flex-1" />
|
||||
<button type="button" className={`${icon} text-muted hover:text-bad`} onClick={onDelete} aria-label={`Remove ${label} budget`}><Trash2 size={15} /></button>
|
||||
<button type="button" className={`${icon} text-muted`} onClick={onCancel} aria-label="Cancel"><X size={15} /></button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Preview of budgets from the 3-month average.
|
||||
function Suggest({ cats, income, onUse, disabled, alt, sticky }: { cats: BudgetCat[]; income: number; onUse: () => void; disabled: boolean; alt?: React.ReactNode; sticky?: boolean }) {
|
||||
const { money0 } = useMoney();
|
||||
const total = cats.reduce((s, c) => s + c.suggested, 0);
|
||||
if (!cats.length) return <div className="px-6 md:px-8 pb-6 space-y-4"><p className="text-sm text-muted">Nothing to suggest right now.</p>{alt}</div>;
|
||||
return (
|
||||
<>
|
||||
<ul className="grid @2xl:grid-cols-2 gap-x-8 px-5 md:px-8">
|
||||
{cats.map((c) => (
|
||||
<li key={c.id} className="flex items-center gap-3 py-2.5 border-b border-line">
|
||||
<CategoryIcon icon={c.icon} color={c.color} size={30} />
|
||||
<span className="flex-1 min-w-0 truncate">{c.label}</span>
|
||||
<span className="tabular text-sm">
|
||||
<span className="font-medium">{money0(c.suggested)}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className={`${sticky ? "sticky bottom-0" : ""} bg-surface px-5 md:px-8 py-5 space-y-3`}>
|
||||
<p className="text-xs text-muted">Each one is your 3-month average, rounded up, and never less than you've spent this month.</p>
|
||||
{income > 0 && <p className="text-sm text-muted">You bring in about {money0(income)} a month. {income >= total ? `This leaves ${money0(income - total)} to save.` : `You're spending ${money0(total - income)} more than you earn.`}</p>}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button className="btn-primary" onClick={onUse} disabled={disabled}>Use these · {money0(total)}/mo</button>
|
||||
{alt}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Native modal: Esc and a backdrop click close it. A bottom sheet on phones, centred above md.
|
||||
function Sheet({ open, onClose, title, children }: { open: boolean; onClose: () => void; title: string; children: React.ReactNode }) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
useEffect(() => {
|
||||
const d = ref.current!;
|
||||
if (open && !d.open) {
|
||||
d.showModal();
|
||||
if (!reduced()) gsap.from(d, { y: 24, opacity: 0, duration: 0.3, ease: EASE, clearProps: "transform,opacity" });
|
||||
} else if (!open && d.open) d.close();
|
||||
}, [open]);
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
onClose={onClose}
|
||||
onClick={(e) => e.target === ref.current && onClose()}
|
||||
className="@container w-full max-w-full md:max-w-[560px] max-h-[85vh] mx-auto mt-auto mb-0 md:my-auto rounded-t-3xl md:rounded-3xl border border-line bg-surface text-ink p-0 backdrop:bg-black/40"
|
||||
>
|
||||
<div className="sticky top-0 z-10 bg-surface flex items-center justify-between px-5 md:px-6 py-4">
|
||||
<h2 className="card-title">{title}</h2>
|
||||
<button onClick={onClose} aria-label="Close" className="size-8 grid place-items-center rounded-full text-muted hover:bg-[var(--hover-strong)]"><X size={16} /></button>
|
||||
</div>
|
||||
{children}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Your own spending category with a budget. Built-in categories stay as they are; this adds a row owned by you.
|
||||
// onDone puts the new budget in local state; router.refresh() then brings the category into `cats`.
|
||||
function NewCategory({ taken, onDone }: { taken: string[]; onDone: (id: string, label: string, amount: number) => void }) {
|
||||
const router = useRouter();
|
||||
const { symbol } = useMoney();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [label, setLabel] = useState("");
|
||||
const [icon, setIcon] = useState("other");
|
||||
const [amount, setAmount] = useState("");
|
||||
const [err, setErr] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const name = label.trim();
|
||||
const n = Math.round(Number(amount));
|
||||
if (!name) return setErr("Give it a name.");
|
||||
if (taken.some((t) => t.toLowerCase() === name.toLowerCase())) return setErr("You already have a category with that name.");
|
||||
if (!Number.isFinite(n) || n <= 0) return setErr("Add a monthly amount.");
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const id = await createCategory(name, icon);
|
||||
const failed = !id || (await writeBudgets({ [id]: n }));
|
||||
setBusy(false);
|
||||
if (failed) return setErr("Couldn't save that category.");
|
||||
onDone(id, name, n);
|
||||
setOpen(false);
|
||||
setLabel(""); setAmount(""); setIcon("other");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
if (!open)
|
||||
return (
|
||||
<div className="px-5 md:px-6 py-4 border-t border-line">
|
||||
<button className="btn inline-flex items-center gap-1.5" onClick={() => setOpen(true)}><Plus size={15} /> New category</button>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<form onSubmit={save} className="px-5 md:px-6 py-4 border-t border-line space-y-3">
|
||||
<div className="font-medium">New category</div>
|
||||
<input autoFocus value={label} onChange={(e) => setLabel(e.target.value)} placeholder="e.g. Pets" aria-label="Category name" maxLength={40} className="select" />
|
||||
<div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label="Icon">
|
||||
{CATEGORY_ICON_KEYS.map((k) => (
|
||||
<button key={k} type="button" role="radio" aria-checked={icon === k} aria-label={k.replace("_", " ")} onClick={() => setIcon(k)}
|
||||
className={`rounded-full p-0.5 ${icon === k ? "ring-2 ring-ink" : "hover:bg-[var(--hover)]"}`}>
|
||||
<CategoryIcon icon={k} color="#6f8cf2" size={32} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="flex items-center border border-line rounded-xl px-3.5 py-2.5 bg-surface focus-within:border-ink w-44">
|
||||
<span className="text-sm text-muted">{symbol}</span>
|
||||
<input inputMode="numeric" value={amount} onChange={(e) => setAmount(e.target.value.replace(/[^\d.]/g, ""))} placeholder="0" aria-label="Monthly budget" className="w-full ml-1 text-sm tabular outline-none bg-transparent" />
|
||||
<span className="text-sm text-muted">/mo</span>
|
||||
</label>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button disabled={busy} className="btn-primary">{busy ? "Saving..." : "Add category"}</button>
|
||||
<button type="button" className="btn" onClick={() => setOpen(false)}>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorNote({ error }: { error: string }) {
|
||||
return error === SETUP ? (
|
||||
<span className="text-sm text-muted">Budgets aren't switched on yet. <Link href="/setup" className="text-ink underline underline-offset-2">Finish setup</Link></span>
|
||||
) : (
|
||||
<span className="text-sm text-bad">{error}</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import { Check } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { budgetChanges, type BudgetChange } from "@/lib/budget";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
export type Changes = Record<string, number | null>;
|
||||
export const SETUP = "setup";
|
||||
|
||||
// Upserts amounts and deletes nulls. Returns an error message, or "" when saved.
|
||||
export async function writeBudgets(changes: Changes) {
|
||||
const db = createClient();
|
||||
const { data: { user } } = await db.auth.getUser();
|
||||
if (!user) return "Couldn't save that. Try again in a moment.";
|
||||
const now = new Date().toISOString();
|
||||
const up = Object.entries(changes).flatMap(([category_id, amount]) => (amount === null ? [] : [{ user_id: user.id, category_id, amount, updated_at: now }]));
|
||||
const del = Object.keys(changes).filter((k) => changes[k] === null);
|
||||
const res = await Promise.all([up.length ? db.from("budgets").upsert(up) : null, del.length ? db.from("budgets").delete().in("category_id", del) : null]);
|
||||
const error = res.map((r) => r?.error).find(Boolean);
|
||||
if (!error) return "";
|
||||
console.error("[broke] budgets:", error.code, error.message);
|
||||
return ["42P01", "PGRST205", "42501"].includes(error.code) ? SETUP : "Couldn't save that. Change undone.";
|
||||
}
|
||||
|
||||
// Your own spending category, with no budget yet. Returns its id, or null if it couldn't be saved.
|
||||
export async function createCategory(label: string, icon = "other") {
|
||||
const db = createClient();
|
||||
const { data: { user } } = await db.auth.getUser();
|
||||
if (!user) return null;
|
||||
const key = `custom_${label.toLowerCase().replace(/[^a-z0-9]+/g, "_").slice(0, 30)}_${Date.now().toString(36)}`;
|
||||
const { data, error } = await db.from("categories").insert({ user_id: user.id, key, label, icon, color: "#6f8cf2", kind: "spend" }).select("id").single();
|
||||
if (error) console.error("[broke] new category:", error.message);
|
||||
return (data?.id as string | undefined) ?? null;
|
||||
}
|
||||
|
||||
// The AI's ```budget block: lists what would change and saves nothing until the user presses Apply.
|
||||
export function BudgetOffer({ proposed }: { proposed: Record<string, unknown> }) {
|
||||
const router = useRouter();
|
||||
const { money0 } = useMoney();
|
||||
const [changes, setChanges] = useState<BudgetChange[] | null>(null);
|
||||
const [state, setState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
useEffect(() => {
|
||||
const db = createClient();
|
||||
Promise.all([db.from("categories").select("id, label").eq("kind", "spend"), db.from("budgets").select("category_id, amount")]).then(([c, b]) =>
|
||||
setChanges(budgetChanges(proposed, c.data ?? [], Object.fromEntries((b.data ?? []).map((x) => [x.category_id, Number(x.amount)])))));
|
||||
}, [proposed]);
|
||||
if (!changes?.length) return null;
|
||||
async function apply() {
|
||||
setState("saving");
|
||||
const write: Changes = {};
|
||||
for (const c of changes!) {
|
||||
const id = c.id ?? (await createCategory(c.label));
|
||||
if (!id) return setState("failed");
|
||||
write[id] = c.to;
|
||||
}
|
||||
if (await writeBudgets(write)) return setState("failed");
|
||||
setState("saved");
|
||||
router.refresh();
|
||||
}
|
||||
return (
|
||||
<div className="rounded-2xl border border-line p-3 space-y-2 text-sm">
|
||||
<ul className="space-y-1">
|
||||
{changes.map((c) => (
|
||||
<li key={c.label} className="flex justify-between gap-3">
|
||||
<span className="truncate">{c.label}{!c.id && <span className="text-muted"> · new</span>}</span>
|
||||
<span className="tabular shrink-0">{c.from !== null && <span className="text-muted">{money0(c.from)} → </span>}{c.to === null ? "removed" : money0(c.to)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button onClick={apply} disabled={state === "saving" || state === "saved"} className="btn !py-1 text-sm inline-flex items-center gap-1.5">
|
||||
{state === "saved" ? <><Check size={14} />Applied to your budget</> : state === "failed" ? "Couldn't save. Try again" : "Apply to my budget"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { useId } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { cancelPrompt, cancelUrl, negotiatePrompt, type Negotiable, type Stream } from "@/lib/subscriptions";
|
||||
|
||||
// "Cancel" opens a small native popover with the cancel page (when known) and a broke AI draft.
|
||||
// "Negotiate" shows only on internet, phone and insurance bills.
|
||||
export function CancelActions({ stream, kind, state }: { stream: Stream; kind: Negotiable | null; state?: string }) {
|
||||
const { ask } = useAssistant();
|
||||
const id = useId();
|
||||
const url = cancelUrl(stream.merchant_name);
|
||||
const close = () => (document.getElementById(id) as HTMLElement & { hidePopover?: () => void })?.hidePopover?.();
|
||||
return (
|
||||
<>
|
||||
{kind && (
|
||||
<button className="btn text-xs" onClick={() => ask(negotiatePrompt(stream, kind, state))}>
|
||||
Negotiate
|
||||
</button>
|
||||
)}
|
||||
<button className="btn text-xs" popoverTarget={id}>
|
||||
Cancel
|
||||
</button>
|
||||
<div id={id} popover="auto" className="card m-auto w-[min(380px,calc(100vw-32px))] p-6 space-y-4 backdrop:bg-black/30">
|
||||
<div className="card-title">Cancel {stream.merchant_name}</div>
|
||||
{url ? (
|
||||
<p className="text-sm">
|
||||
Cancel it yourself here:{" "}
|
||||
<a href={url} target="_blank" rel="noreferrer" className="underline break-all">
|
||||
{url.replace(/^https:\/\/(www\.)?/, "")}
|
||||
</a>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted">broke has no direct cancel link for {stream.merchant_name}. Check your account settings on their site, or send them a message.</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<button className="btn-primary" onClick={() => (close(), ask(cancelPrompt(stream)))}>
|
||||
Write my cancel message
|
||||
</button>
|
||||
<button className="btn" popoverTarget={id} popoverTargetAction="hide">
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { CARD_ART } from "@/lib/cards";
|
||||
|
||||
// The card's real art at card proportions, or the issuer's logo when there is none. w: Tailwind width class.
|
||||
export function CardArt({ card, w = "w-16" }: { card: { id: string; issuer: string; name: string }; w?: string }) {
|
||||
const art = CARD_ART[card.id];
|
||||
return (
|
||||
<span className={`${w} aspect-[1.586] shrink-0 self-start grid place-items-center`}>
|
||||
{art ? <img src={art.src} alt={`${card.issuer} ${card.name}`} className="size-full border border-line object-cover" style={{ borderRadius: "4.5% / 7%" }} /> : <Merchant name={card.issuer} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { CardArt } from "@/components/CardArt";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { bonusText, CAT_LABEL, creditFirst, creditNote, feeText, type Card, type Fit } from "@/lib/cards";
|
||||
import { BANDS } from "@/lib/credit";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
export type Row = Omit<Fit, "card"> & { card: Omit<Card, "match"> & { match?: undefined } };
|
||||
|
||||
const FILTERS = [["all", "All"], ["nofee", "No annual fee"], ["travel", "Travel"], ["cash", "Cash back"]] as const;
|
||||
// The best three rates, in "3x Dining" form, with "%" for cash back.
|
||||
const topRates = (c: Row["card"]) =>
|
||||
Object.entries(c.earn).sort((a, b) => b[1]!.rate - a[1]!.rate).slice(0, 3).map(([k, e]) => `${e!.rate}${c.currency === "cash back" ? "%" : "x"} ${CAT_LABEL[k as keyof typeof CAT_LABEL]}`);
|
||||
|
||||
export function ApplyButton({ card, primary }: { card: Row["card"]; primary?: boolean }) {
|
||||
return (
|
||||
<a href={card.referral ?? card.url} target="_blank" rel={card.referral ? "noopener noreferrer sponsored" : "noopener noreferrer"} className={`${primary ? "btn-primary" : "btn"} shrink-0 text-center`}>
|
||||
Apply
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
// The Cards page's one-line credit range question, shown while the profile has none (or "Not sure").
|
||||
export function CreditPicker({ profile }: { profile: Record<string, unknown> }) {
|
||||
const router = useRouter();
|
||||
const [err, setErr] = useState(false);
|
||||
async function pick(credit: string) {
|
||||
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, credit } } });
|
||||
setErr(!!error);
|
||||
if (!error) router.refresh();
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="text-sm">Add your credit range for better matches.</span>
|
||||
<Dropdown label="Credit range" value={(profile.credit as string) ?? ""} options={BANDS} onChange={pick} placeholder="Choose your credit range" />
|
||||
{err && <span className="text-sm text-muted">Couldn't save that. Try again.</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardList({ rows }: { rows: Row[] }) {
|
||||
const { money0 } = useMoney();
|
||||
const [filter, setFilter] = useState<(typeof FILTERS)[number][0]>("all");
|
||||
const [sort, setSort] = useState("ongoing");
|
||||
const shown = rows
|
||||
.filter((r) => filter === "all" || (filter === "nofee" ? r.card.fee === 0 : r.card.kind === filter))
|
||||
.sort((a, b) => creditFirst(a, b) || (sort === "yearOne" ? b.yearOne - a.yearOne : b.ongoing - a.ongoing));
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2 justify-between">
|
||||
<div className="pill-tabs overflow-x-auto max-w-full">
|
||||
{FILTERS.map(([v, label]) => (
|
||||
<button key={v} onClick={() => setFilter(v)} className={`pill-tab whitespace-nowrap ${filter === v ? "pill-tab-active" : ""}`}>{label}</button>
|
||||
))}
|
||||
</div>
|
||||
<Dropdown label="Sort" value={sort} onChange={setSort} options={[{ value: "ongoing", label: "Most earned every year" }, { value: "yearOne", label: "Most earned in year one" }]} />
|
||||
</div>
|
||||
<section className="card overflow-hidden">
|
||||
{shown.map((r) => (
|
||||
<div key={r.card.id} className="px-5 py-4 border-b border-line last:border-0 flex flex-col @2xl:flex-row gap-3 @2xl:items-center">
|
||||
<div className="flex-1 min-w-0 flex gap-4 items-start">
|
||||
<CardArt card={r.card} w="w-16 @md:w-20" />
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||
<span className="font-medium">{r.card.name}</span>
|
||||
<span className="text-sm text-muted inline-flex items-center gap-1.5 self-center"><Merchant name={r.card.issuer} small />{r.card.issuer}</span>
|
||||
{r.card.referral && <span className="text-xs text-muted border border-line rounded-full px-2">Referral link</span>}
|
||||
</div>
|
||||
<div className="text-sm">{feeText(r.card)} · {topRates(r.card).join(" · ")}</div>
|
||||
<div className="text-sm text-muted">{bonusText(r).join(" ")}</div>
|
||||
{r.card.credit === "building" && <div className="text-xs text-muted">For building or rebuilding credit.</div>}
|
||||
{r.fitsCredit === true && <div className="text-xs text-muted">Fits your credit range.</div>}
|
||||
{r.fitsCredit === false && <div className="text-xs font-medium">{creditNote(r.card)}</div>}
|
||||
{r.card.notes.length > 0 && <div className="text-xs text-muted leading-relaxed">{r.card.notes.join(" ")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 @2xl:w-56 @2xl:justify-end">
|
||||
<div className="flex-1 @2xl:flex-none @2xl:text-right">
|
||||
<div className="text-xs text-muted">You'd earn</div>
|
||||
<div className="font-semibold tabular">{money0(r.ongoing)}<span className="text-sm font-normal text-muted"> a year</span></div>
|
||||
<div className="text-xs text-muted tabular">{money0(r.yearOne)} in year one with the bonus</div>
|
||||
</div>
|
||||
<ApplyButton card={r.card} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!shown.length && <p className="px-5 py-4 text-sm text-muted">No cards in this group.</p>}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Sparkles } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { categoryOptions, emptyRule, saveRule } from "@/components/RuleForm";
|
||||
import { toast } from "@/components/Toast";
|
||||
import type { Category } from "@/lib/data";
|
||||
import { displayName, plural } from "@/lib/format";
|
||||
import { matches } from "@/lib/rules";
|
||||
import { fetchChecks, REASON_TEXT, type CheckRow, type Reason } from "@/lib/unsure";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Row = CheckRow & { reason: Reason; same: string[] };
|
||||
export type Checks = { rows: Row[]; total: number };
|
||||
|
||||
const db = () => createClient();
|
||||
const uid = async () => (await db().auth.getSession()).data.session?.user.id;
|
||||
// The bank's merchant when it gives one ("Uber"), else the raw name, as TxnRow's "Create a rule" does.
|
||||
const ruleName = (t: Row) => t.merchant_name ?? t.name;
|
||||
|
||||
// One transaction: Yes keeps its category, Change picks another. Either way it never comes back (checked_at, 0023).
|
||||
function CheckItem({ t, cats, onAnswer }: { t: Row; cats: Category[]; onAnswer: (t: Row, categoryId: string | null, always: boolean) => Promise<void> }) {
|
||||
const { signed, dayLabel } = useMoney();
|
||||
const [changing, setChanging] = useState(t.reason === "none");
|
||||
const [always, setAlways] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const name = displayName(t);
|
||||
const has = t.category && t.category.key !== "OTHER";
|
||||
const answer = async (id: string | null) => {
|
||||
setBusy(true);
|
||||
await onAnswer(t, id, always);
|
||||
setBusy(false);
|
||||
};
|
||||
return (
|
||||
<li className="py-4 border-b border-line last:border-0 space-y-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Merchant name={name} logo={t.logo_url} icon={t.category?.icon} color={t.category?.color} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium truncate">{name}</div>
|
||||
<div className="text-xs text-muted">{dayLabel(t.date)} · {REASON_TEXT[t.reason]}{t.same.length > 1 ? ` · ${plural(t.same.length, "transaction")} like this` : ""}</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<div className={`text-sm tabular ${t.amount < 0 ? "text-good" : ""}`}>{signed(t.amount, t.currency)}</div>
|
||||
<div className="text-xs text-muted">{has ? t.category!.label : "No category"}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 pl-11">
|
||||
{changing ? (
|
||||
<div className="w-full max-w-xs">
|
||||
<Dropdown label={`Category for ${name}`} value="" options={categoryOptions(cats)} onChange={(v) => v && answer(v)} placeholder="Pick a category" searchable />
|
||||
</div>
|
||||
) : (
|
||||
<span className="flex gap-2">
|
||||
<button type="button" disabled={busy} onClick={() => answer(t.category_id)} className="btn">Yes</button>
|
||||
<button type="button" disabled={busy} onClick={() => setChanging(true)} className="btn">Change</button>
|
||||
</span>
|
||||
)}
|
||||
<label className="flex items-center gap-2 text-sm text-muted cursor-pointer min-w-0">
|
||||
<input type="checkbox" checked={always} onChange={(e) => setAlways(e.target.checked)} className="size-4 shrink-0 accent-[var(--color-ink)]" />
|
||||
<span className="truncate">Always do this for {name}</span>
|
||||
</label>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Is this right?": unsure transactions, the biggest first, 5 at a time until they ask for more. Pass `initial` from the server, or it loads its own.
|
||||
* onEmpty: called once nothing is left to check (onboarding moves on). */
|
||||
export function CategoryCheck({ initial, cats: catsIn, onEmpty, title, closed = false }: { initial?: Checks; cats?: Category[]; onEmpty?: () => void; title?: string; closed?: boolean }) {
|
||||
const router = useRouter();
|
||||
const { ask } = useAssistant();
|
||||
const [open, setOpen] = useState(!closed);
|
||||
const [checks, setChecks] = useState<Checks | null>(initial ?? null);
|
||||
const [cats, setCats] = useState<Category[]>(catsIn ?? []);
|
||||
const [limit, setLimit] = useState(5);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initial) uid().then((id) => (id ? fetchChecks(db(), id) : { rows: [], total: 0 })).then((c) => setChecks(c as Checks));
|
||||
if (!catsIn) db().from("categories").select("id, key, label, icon, color, kind").order("label").then(({ data }) => setCats((data ?? []) as Category[]));
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// A rule applied from the chat: the page refreshes with a shorter list.
|
||||
useEffect(() => {
|
||||
if (initial) setChecks(initial);
|
||||
}, [initial]);
|
||||
|
||||
useEffect(() => {
|
||||
if (checks && !checks.total) onEmpty?.();
|
||||
}, [checks?.total]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
async function onAnswer(t: Row, categoryId: string | null, always: boolean) {
|
||||
const changed = categoryId !== t.category_id;
|
||||
const now = new Date().toISOString();
|
||||
const { error } = await db().from("transactions").update({ checked_at: now, ...(changed ? { category_id: categoryId } : {}) }).in("id", t.same);
|
||||
if (error) return void toast("Couldn't save that. Try again.");
|
||||
// "Always": a rule for this merchant, applied to past rows too. The other shown rows it covers are answered with it.
|
||||
let done = t.same;
|
||||
if (always && categoryId) {
|
||||
const r = await saveRule(emptyRule({ match: ruleName(t), category_id: categoryId }), true);
|
||||
if (r.error) toast(r.error);
|
||||
else {
|
||||
const draft = emptyRule({ match: ruleName(t) });
|
||||
const covered = checks!.rows.filter((x) => x.id !== t.id && matches(draft, x)).flatMap((x) => x.same);
|
||||
if (covered.length) await db().from("transactions").update({ checked_at: now }).in("id", covered);
|
||||
done = [...t.same, ...covered];
|
||||
toast(r.updated ? `Rule saved. Updated ${plural(r.updated, "past transaction")}.` : "Rule saved.");
|
||||
}
|
||||
}
|
||||
const left = checks!.rows.filter((x) => !done.includes(x.id));
|
||||
const total = Math.max(0, checks!.total - (checks!.rows.length - left.length));
|
||||
// The shown five are done but more wait: load the next ones.
|
||||
if (!left.length && total) {
|
||||
const id = await uid();
|
||||
setChecks(id ? ((await fetchChecks(db(), id, undefined, limit)) as Checks) : { rows: [], total: 0 });
|
||||
} else setChecks({ rows: left, total });
|
||||
if (changed || always) router.refresh();
|
||||
}
|
||||
|
||||
// Names, which way the money went and today's category, never amounts. A cloud model sees the names as placeholders.
|
||||
async function sortWithAI() {
|
||||
const id = await uid();
|
||||
const all = id ? ((await fetchChecks(db(), id, undefined, 60)) as Checks).rows : checks!.rows;
|
||||
const lines = all.map((t) => `${displayName(t)} (money ${t.amount < 0 ? "in" : "out"}, now ${t.category?.label ?? "no category"}${t.same.length > 1 ? `, ${t.same.length} like this` : ""})`);
|
||||
ask(`Help me sort these categories. Suggest rules for what you're confident about, and ask me about anything you're not sure of.\n\nThese need checking: ${lines.join("; ")}.`);
|
||||
}
|
||||
|
||||
// More of the same list, biggest first. Anything already answered is gone from it.
|
||||
async function showMore() {
|
||||
const id = await uid();
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
const n = checks!.rows.length + 20;
|
||||
setChecks((await fetchChecks(db(), id, undefined, n)) as Checks);
|
||||
setLimit(n);
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
if (!checks) return <div className="card p-6 space-y-3" aria-busy="true">{[0, 1, 2].map((i) => <div key={i} className="h-10 rounded-xl bg-line/70 animate-pulse" />)}</div>;
|
||||
if (!checks.total)
|
||||
return initial === undefined && !onEmpty ? null : (
|
||||
<section className="card p-6 flex items-center gap-3" role="status">
|
||||
<span className="size-8 rounded-full bg-brand-soft text-brand grid place-items-center shrink-0"><Check size={16} /></span>
|
||||
<span className="text-sm">Every category is checked.</span>
|
||||
</section>
|
||||
);
|
||||
const head = title ?? `${checks.total} to check`;
|
||||
// closed (the Transactions page): one line until they open it, so the list stays in view.
|
||||
if (!open)
|
||||
return (
|
||||
<section className="card px-5 md:px-6 py-4 flex flex-wrap items-center gap-x-4 gap-y-2" aria-labelledby="check-title">
|
||||
<div className="flex-1 min-w-48">
|
||||
<div id="check-title" className="card-title">{head}</div>
|
||||
<p className="text-sm text-muted">Is this right? Tips are only as good as your categories.</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => setOpen(true)} className="btn">Check them</button>
|
||||
</section>
|
||||
);
|
||||
return (
|
||||
<section className="card px-5 md:px-6 pt-5 pb-1" aria-labelledby="check-title">
|
||||
<div id="check-title" className="card-title">{head}</div>
|
||||
<p className="text-sm text-muted mt-1">Is this right? Tips are only as good as your categories.</p>
|
||||
<button type="button" onClick={sortWithAI} className="btn inline-flex items-center gap-1.5 mt-3"><Sparkles size={15} /> Ask AI to sort these</button>
|
||||
<ul className="mt-2">{checks.rows.map((t) => <CheckItem key={t.id} t={t} cats={cats} onAnswer={onAnswer} />)}</ul>
|
||||
{checks.rows.length < checks.total && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 py-4 border-t border-line">
|
||||
<span className="text-sm text-muted tabular">Showing {checks.rows.length} of {checks.total}</span>
|
||||
<button type="button" onClick={showMore} disabled={loading} className="btn">{loading ? "Loading..." : `Show ${Math.min(20, checks.total - checks.rows.length)} more`}</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { Check } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
// Removes each sandbox connection through /api/plaid/remove (it only removes the signed-in user's own).
|
||||
export function RemoveTest({ items, intro }: { items: { id: string; name: string }[]; intro: string }) {
|
||||
const router = useRouter();
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [left, setLeft] = useState(items);
|
||||
const [err, setErr] = useState("");
|
||||
if (!left.length) return <span className="text-sm text-good inline-flex items-center gap-1"><Check size={13} /> Test connections removed.</span>;
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const keep: typeof left = [];
|
||||
for (const it of left) {
|
||||
const res = await fetch("/api/plaid/remove", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ itemId: it.id }) }).catch(() => null);
|
||||
if (!res?.ok) keep.push(it);
|
||||
}
|
||||
setLeft(keep);
|
||||
setBusy(false);
|
||||
setConfirm(false);
|
||||
if (keep.length) setErr(`Couldn't remove ${keep.map((k) => k.name).join(", ")}. Try again.`);
|
||||
router.refresh();
|
||||
}
|
||||
const n = left.length;
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<p>{intro} You have {n}: {left.map((i) => i.name).join(", ")}.</p>
|
||||
{confirm ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-muted">Remove {n === 1 ? "it" : `all ${n}`} and {n === 1 ? "its" : "their"} test transactions?</span>
|
||||
<button className="btn text-bad" disabled={busy} onClick={remove}>{busy ? "Removing..." : "Remove"}</button>
|
||||
<button className="text-muted hover:text-ink" disabled={busy} onClick={() => setConfirm(false)}>Cancel</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn" onClick={() => setConfirm(true)}>Remove test connections</button>
|
||||
)}
|
||||
{err && <p className="text-bad">{err}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Everything that came from Plaid's test banks, in one go: the connections (their accounts and transactions go with
|
||||
// them), then what was worked out from them (/api/start-fresh). One action, because the page refreshes once the
|
||||
// connections are gone and a second button would vanish with them. Used by Settings and the go-live steps.
|
||||
export function ClearTestData({ items }: { items: { id: string; name: string }[] }) {
|
||||
const router = useRouter();
|
||||
const [budgets, setBudgets] = useState(false);
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [state, setState] = useState<"idle" | "busy" | "done" | "failed">("idle");
|
||||
const [left, setLeft] = useState(items);
|
||||
async function clear() {
|
||||
setState("busy");
|
||||
const keep: typeof left = [];
|
||||
for (const it of left) {
|
||||
const res = await fetch("/api/plaid/remove", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ itemId: it.id }) }).catch(() => null);
|
||||
if (!res?.ok) keep.push(it);
|
||||
}
|
||||
const fresh = await fetch("/api/start-fresh", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ budgets }) }).catch(() => null);
|
||||
setLeft(keep);
|
||||
setConfirm(false);
|
||||
setState(!keep.length && fresh?.ok ? "done" : "failed");
|
||||
router.refresh();
|
||||
}
|
||||
if (state === "done") return <p className="text-sm text-good flex items-center gap-1.5"><Check size={15} />Test data deleted. Your totals now only count real banks.</p>;
|
||||
const n = left.length;
|
||||
return (
|
||||
<div className="space-y-3 text-sm">
|
||||
<ul className="space-y-1">
|
||||
{n > 0 && <li>{n === 1 ? "1 test bank" : `${n} test banks`} ({left.map((i) => i.name).join(", ")}) with their accounts and transactions</li>}
|
||||
<li>Your money plan and weekly reviews. broke builds them again from your real banks.</li>
|
||||
</ul>
|
||||
<p className="text-muted">Your rules, categories and money profile stay.</p>
|
||||
<label className="flex items-center gap-2.5 cursor-pointer">
|
||||
<input type="checkbox" checked={budgets} onChange={(e) => setBudgets(e.target.checked)} className="size-4 accent-[var(--ink)]" />
|
||||
Also delete my budgets
|
||||
</label>
|
||||
{confirm ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-muted">This can't be undone.</span>
|
||||
<button className="btn text-bad" disabled={state === "busy"} onClick={clear}>{state === "busy" ? "Deleting…" : "Delete"}</button>
|
||||
<button className="text-muted hover:text-ink" disabled={state === "busy"} onClick={() => setConfirm(false)}>Cancel</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="btn" onClick={() => setConfirm(true)}>Delete test data</button>
|
||||
)}
|
||||
{state === "failed" && <p className="text-bad">{n ? `Couldn't remove ${left.map((k) => k.name).join(", ")}.` : "Couldn't clear the plan and reviews."} Try again.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
import { Check } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { saveChoice, SetupCard, type Provider } from "@/components/Assistant";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { OPENROUTER_FREE, type ModelChoice } from "@/lib/llm/models";
|
||||
|
||||
const PLANS = ["claude", "codex", "gemini"], HERE = ["local", "opencode"];
|
||||
|
||||
// The one place to connect an AI, easiest first. broke works without any of it: AI is only for asking questions.
|
||||
export function ConnectAI({ initial, choice: saved, hosted, connected, failed }: { initial: Provider[]; choice: ModelChoice | null; hosted: boolean; connected: boolean; failed: boolean }) {
|
||||
const router = useRouter();
|
||||
const [providers, setProviders] = useState(initial);
|
||||
const [choice, setChoice] = useState(saved);
|
||||
const [setting, setSetting] = useState<string | null>(null);
|
||||
const openRouter = providers.find((p) => p.id === "openrouter");
|
||||
const recheck = () => fetch("/api/models?fresh=1").then((r) => r.json()).then((b: { providers: Provider[] }) => (setProviders(b.providers), b.providers));
|
||||
const use = (c: ModelChoice) => {
|
||||
setChoice(c);
|
||||
setSetting(null);
|
||||
saveChoice(c).then(({ error }) => error && console.error("[broke] model choice:", error.message));
|
||||
};
|
||||
async function disconnect() {
|
||||
await fetch("/api/ai/openrouter/disconnect", { method: "POST" });
|
||||
if (choice?.provider === "openrouter") setChoice(null);
|
||||
await recheck();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
// Hosted: the command that connects the AI app on their own computer. The code in it works once, for 10 minutes.
|
||||
const [helperCmd, setHelperCmd] = useState<string | null>(null);
|
||||
async function connectComputer() {
|
||||
const res = await fetch("/api/ai/helper/pair", { method: "POST" });
|
||||
if (!res.ok) return setHelperCmd("");
|
||||
const { code } = (await res.json()) as { code: string };
|
||||
const site = window.location.origin;
|
||||
setHelperCmd(`curl -fsSL ${site}/broke-connect.cjs | node - ${site} ${code}`);
|
||||
}
|
||||
|
||||
const row = (p: Provider) => (
|
||||
<li key={p.id} className="border-t border-line py-3 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="min-w-0">
|
||||
<span className="block font-medium">{p.label}</span>
|
||||
{p.found && <span className={`block text-sm ${p.ready ? "text-good" : "text-muted"}`}>{p.found}</span>}
|
||||
</span>
|
||||
{p.helper && !p.ready ? null : !p.ready ? <button className="btn shrink-0" onClick={() => setSetting(setting === p.id ? null : p.id)}>{p.action ?? "Set up"}</button>
|
||||
: choice?.provider === p.id ? <span className="text-sm text-muted flex items-center gap-1.5"><Check size={15} /> In use</span>
|
||||
: <button className="btn" onClick={() => use({ provider: p.id as ModelChoice["provider"], model: null })}>Use this</button>}
|
||||
</div>
|
||||
{setting === p.id && !p.ready && <SetupCard p={p} recheck={recheck} auto />}
|
||||
</li>
|
||||
);
|
||||
const group = (ids: string[]) => providers.filter((p) => ids.includes(p.id)).sort((a, b) => Number(b.ready) - Number(a.ready)).map(row);
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl space-y-4">
|
||||
<p className="text-sm text-muted">Connect an AI to ask questions about your money. The rest of broke works without one.</p>
|
||||
{connected && <p className="card px-5 py-3 text-sm" role="status">OpenRouter is connected. Press Ask broke ai to try it.</p>}
|
||||
{failed && <p className="card px-5 py-3 text-sm text-bad" role="alert">That didn't connect. Try again.</p>}
|
||||
|
||||
<section className="card p-6 space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="card-title">OpenRouter</h2>
|
||||
<p className="text-sm text-muted">The easiest way if you don't have an AI yet. Make a free account, approve broke, and you're done. No install, no key to copy. Free models cost nothing. Paid ones use credits you add yourself.</p>
|
||||
</div>
|
||||
{openRouter?.ready ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="min-w-64">
|
||||
<Dropdown label="OpenRouter model" placeholder="Model" value={choice?.provider === "openrouter" ? choice.model ?? OPENROUTER_FREE : ""} options={(openRouter.models ?? []).map((m) => ({ value: m.id, label: m.label }))}
|
||||
onChange={(model) => use({ provider: "openrouter", model })} />
|
||||
</div>
|
||||
<button className="btn" onClick={disconnect}>Disconnect</button>
|
||||
</div>
|
||||
) : (
|
||||
// A full page visit: the route redirects to OpenRouter, and a client-side link can't follow that.
|
||||
<a href="/api/ai/openrouter/start" className="btn-primary inline-block">Connect OpenRouter</a>
|
||||
)}
|
||||
<p className="text-xs text-muted">Free models can keep what they're sent. They only get a summary of your money: rounded totals with names hidden, never single transactions or account numbers.</p>
|
||||
</section>
|
||||
|
||||
{hosted && (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="space-y-1">
|
||||
<h2 className="card-title">Already pay for Claude, or use opencode?</h2>
|
||||
<p className="text-sm text-muted">Use it from your own computer, at no extra cost. Run one command there and leave it open. Your AI login stays on your computer, and broke only sends it the same summary of your money.</p>
|
||||
</div>
|
||||
<ul>{providers.filter((p) => p.helper).map(row)}</ul>
|
||||
{helperCmd === null && <button className="btn" onClick={connectComputer}>Connect my computer</button>}
|
||||
{helperCmd === "" && <p className="text-sm text-bad" role="alert">That didn't work. Try again.</p>}
|
||||
{helperCmd && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm">Paste this in Terminal, then press Check again. The code in it works once, for 10 minutes.</p>
|
||||
<code className="block text-xs break-all rounded-lg border border-line p-3">{helperCmd}</code>
|
||||
<div className="flex gap-2">
|
||||
<button className="btn" onClick={() => navigator.clipboard.writeText(helperCmd)}>Copy</button>
|
||||
<button className="btn" onClick={recheck}>Check again</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted">AI only answers while that command is running. Claude and opencode run with every tool off. ChatGPT and Gemini only work when broke runs on your own computer.</p>
|
||||
</section>
|
||||
)}
|
||||
{!hosted && (
|
||||
<>
|
||||
<section className="card p-6 space-y-2">
|
||||
<h2 className="card-title">Already pay for Claude, ChatGPT or Gemini?</h2>
|
||||
<p className="text-sm text-muted">Use that plan, at no extra cost. broke checked this computer, and pressing a button opens Terminal for you.</p>
|
||||
<ul className="pt-1">{group(PLANS)}</ul>
|
||||
</section>
|
||||
<section className="card p-6 space-y-2">
|
||||
<h2 className="card-title">Run AI on this computer</h2>
|
||||
<p className="text-sm text-muted">The most private. A local model never sends anything out, but it's a few GB to download and can give weaker answers. opencode runs open-source models.</p>
|
||||
<ul className="pt-1">{group(HERE)}</ul>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
<Link href="/" className="btn inline-block">Back to home</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
// What the user has put in this tax year, when no linked account shows it. Saved to user_metadata.contributed["kind:year"].
|
||||
export function ContributionInput({ id, label, value }: { id: string; label: string; value: number | null }) {
|
||||
const router = useRouter();
|
||||
const [v, setV] = useState(value == null ? "" : String(value));
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const n = Number(v.replace(/[^\d.]/g, ""));
|
||||
if (v.trim() && !Number.isFinite(n)) return;
|
||||
setBusy(true);
|
||||
const sb = createClient();
|
||||
const { data } = await sb.auth.getUser(); // latest copy, so two rows saved in a row both stick
|
||||
const all = { ...(data.user?.user_metadata?.contributed ?? {}) } as Record<string, number>;
|
||||
if (v.trim()) all[id] = n;
|
||||
else delete all[id];
|
||||
await updateMeta(sb, { data: { contributed: all } });
|
||||
setBusy(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={save} className="flex flex-wrap items-center gap-2">
|
||||
<span className="w-full text-xs text-muted">Put in so far</span>
|
||||
<input
|
||||
inputMode="decimal"
|
||||
value={v}
|
||||
onChange={(e) => setV(e.target.value)}
|
||||
aria-label={`What you've put in your ${label} this year`}
|
||||
placeholder="Add what you've put in"
|
||||
className="w-48 bg-surface border border-line rounded-full px-3.5 py-1.5 text-sm outline-none focus:border-ink tabular"
|
||||
/>
|
||||
<button className="btn text-sm" disabled={busy}>{busy ? "Saving" : "Save"}</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ContributionInput } from "@/components/ContributionInput";
|
||||
import type { Profile } from "@/components/ProfileForm";
|
||||
import { countryOf, type Country } from "@/lib/countries";
|
||||
import { getUser, today } from "@/lib/data";
|
||||
import { money, money0, ymd } from "@/lib/format";
|
||||
import { contributionRoom, type Room } from "@/lib/invest";
|
||||
|
||||
// Employer rules that are one plain line. NZ: ird.govt.nz/kiwisaver-changes; UK: gov.uk/workplace-pensions (checked 2026-10-22).
|
||||
const AT_WORK: Record<string, string> = {
|
||||
nz: "At work, your employer must add 3.5% of your pay to KiwiSaver when you contribute.",
|
||||
uk: "At work, your employer must pay at least 3% into your workplace pension (8% in total with yours) on earnings between £6,240 and £50,270.",
|
||||
};
|
||||
|
||||
// This tax year's contributions to tax-advantaged accounts against the limits for the user's country.
|
||||
export async function Contributions({ profile }: { profile: Profile & { country?: string } }) {
|
||||
const { supabase, user } = await getUser();
|
||||
const country = countryOf(profile.country);
|
||||
const rows = await contributionRoom(supabase, profile, { tax: country.tax, today: ymd(await today()), locale: country.locale, mine: user?.user_metadata?.contributed });
|
||||
return <ContributionsCard rows={rows} profile={profile} country={country} />;
|
||||
}
|
||||
|
||||
export function ContributionsCard({ rows, profile, country }: { rows: Room[]; profile: Profile; country: Country }) {
|
||||
if (!rows.length) return null;
|
||||
const us = country.tax === "us";
|
||||
// Limits are set in the country's own currency. $1,042.86 keeps its cents, $20,000 shows none.
|
||||
const m = (n: number) => (Math.round(n * 100) % 100 ? money : money0)(n, country.currency);
|
||||
const noHsa = us && profile.health && !profile.health.startsWith("High-deductible");
|
||||
|
||||
return (
|
||||
<section className="card p-6 space-y-5">
|
||||
<div className="section-label">{us ? "Contributions this year" : "Contributions this tax year"}</div>
|
||||
{rows.map((r) => {
|
||||
const both = r.contributed != null && r.limit != null;
|
||||
return (
|
||||
<div key={r.kind} className="space-y-2">
|
||||
<div className="flex justify-between gap-3 text-sm">
|
||||
<span className="font-medium">{r.label}{!us && <span className="text-muted font-normal"> {r.year}</span>}</span>
|
||||
<span className="tabular text-muted text-right">
|
||||
{both ? `${m(r.contributed!)} of ${m(r.limit!)}` : r.contributed != null ? `${m(r.contributed)} put in` : r.limit != null ? `${r.goal ? "Target" : "Limit"} ${m(r.limit)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
{both && (
|
||||
<div className="h-2 rounded-full bg-canvas overflow-hidden">
|
||||
<div className="h-full rounded-full bg-chart" style={{ width: `${Math.min(1, r.contributed! / r.limit!) * 100}%` }} />
|
||||
</div>
|
||||
)}
|
||||
{r.left != null && (
|
||||
<p className="text-sm">
|
||||
{r.goal
|
||||
? r.left > 0 ? <>Put in <b className="tabular">{m(r.left)}</b> more by {r.deadline} to get the full government contribution.</> : "You'll get the full government contribution this year."
|
||||
: r.left > 0 ? <>You have <b className="tabular">{m(r.left)}</b> of {r.label} room left {r.kind === "k401" ? `through payroll by ${r.deadline}` : `before ${r.deadline}`}.</>
|
||||
: r.left < 0 ? <span className="text-bad">You're {m(-r.left)} over the {r.year} limit.{us ? " Ask your provider to return the extra." : ""}</span>
|
||||
: `You've maxed your ${r.label} for ${r.year}.`}
|
||||
</p>
|
||||
)}
|
||||
{(r.note || (r.kind === "hsa" && noHsa)) && (
|
||||
<p className="text-xs text-muted">{[r.note, r.kind === "hsa" && noHsa ? "your health plan may not allow HSA contributions" : ""].filter(Boolean).join(". ")}</p>
|
||||
)}
|
||||
{r.from !== "linked" && <ContributionInput id={`${r.kind}:${r.year}`} label={r.label} value={r.contributed} />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{AT_WORK[country.tax] && <p className="text-sm">{AT_WORK[country.tax]}</p>}
|
||||
<p className="text-xs text-muted">
|
||||
{us
|
||||
? "Counts deposits Plaid marks as contributions. A 401(k) employer match shows here too but doesn't count toward your limit."
|
||||
: `Counts deposits into linked accounts with ${rows.map((r) => r.label.split(" ")[0]).join(" or ").replace("Pension", "pension")} in the name, or what you add. Limits checked on government sites on 22 October 2026.`}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { COUNTRIES, countryOf, guessCountry, OTHER } from "@/lib/countries";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
type Profile = Record<string, unknown> & { country?: string; currency?: string };
|
||||
|
||||
const COUNTRY_OPTIONS = [...COUNTRIES, OTHER].map((c) => ({ value: c.code, label: c.name, hint: c.code === OTHER.code ? "Pick your currency" : c.currency }));
|
||||
|
||||
// Country, plus a currency pick when it isn't listed. currency is only kept for "Somewhere else".
|
||||
export function CountryField({ country, currency, onChange }: { country: string; currency?: string; onChange: (country: string, currency: string) => void }) {
|
||||
const other = country === OTHER.code;
|
||||
const currencies = useMemo(() => {
|
||||
const name = new Intl.DisplayNames(["en"], { type: "currency" });
|
||||
return Intl.supportedValuesOf("currency").map((c) => ({ value: c, label: `${name.of(c)} (${c})` }));
|
||||
}, []);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Dropdown label="Country" value={country} options={COUNTRY_OPTIONS} onChange={(c) => onChange(c, countryOf(c).currency)} placeholder="Choose a country" searchable />
|
||||
{other && <Dropdown label="Currency" value={currency ?? ""} options={currencies} onChange={(c) => onChange(country, c)} placeholder="Choose a currency" searchable />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Saves country and home currency into the money profile (user_metadata.profile), keeping the rest of it.
|
||||
async function saveCountry(profile: Profile, country: string, currency: string) {
|
||||
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, country, currency } } });
|
||||
return !error;
|
||||
}
|
||||
|
||||
// First run: pick a country before anything else, guessed from the browser. onDone: the next onboarding step,
|
||||
// which the saved profile resumes at (onboarding: "bank"); without it, the dashboard.
|
||||
export function Welcome({ profile, onDone }: { profile: Profile; onDone?: (p: Profile) => void }) {
|
||||
const router = useRouter();
|
||||
const [c, setC] = useState({ country: "", currency: "" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
useEffect(() => {
|
||||
const country = guessCountry(navigator.languages ?? [navigator.language], Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
setC((x) => (x.country ? x : { country, currency: countryOf(country).currency }));
|
||||
}, []);
|
||||
|
||||
async function go() {
|
||||
setBusy(true);
|
||||
const next = onDone ? { ...profile, onboarding: "bank" } : profile;
|
||||
if (await saveCountry(next, c.country, c.currency)) {
|
||||
if (onDone) onDone({ ...next, country: c.country, currency: c.currency });
|
||||
else router.replace("/");
|
||||
} else {
|
||||
setErr("Couldn't save that. Try again.");
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-[-0.02em]">Where do you live?</h1>
|
||||
<p className="text-sm text-muted mt-1">broke uses it for your currency, which banks you can link and which tax tips apply. You can change it later.</p>
|
||||
</div>
|
||||
<CountryField country={c.country} currency={c.currency} onChange={(country, currency) => setC({ country, currency })} />
|
||||
<button onClick={go} disabled={busy || !c.country || !c.currency} className="btn-primary w-full">{busy ? "Saving..." : "Continue"}</button>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Existing users without a country are treated as US. One small nudge until they pick one or say they're in the US.
|
||||
export function CountryBanner({ profile }: { profile: Profile }) {
|
||||
const router = useRouter();
|
||||
const [gone, setGone] = useState(false);
|
||||
if (gone) return null;
|
||||
return (
|
||||
<div className="card px-5 py-3 flex items-center gap-3 text-sm">
|
||||
<span className="flex-1">
|
||||
Using broke outside the US? <Link href="/optimize#profile" className="font-medium underline underline-offset-4">Set your country</Link>
|
||||
</span>
|
||||
<button
|
||||
onClick={async () => {
|
||||
setGone(true);
|
||||
if (await saveCountry(profile, "US", "USD")) router.refresh();
|
||||
}}
|
||||
className="text-muted hover:text-ink flex items-center gap-1"
|
||||
>
|
||||
I'm in the US <X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
// The rate and payment for one debt, which bank feeds don't give. Saves when you leave the box.
|
||||
export function DebtFields({ id, apr, payment, guess }: { id: string; apr: number | null; payment: number | null; guess: number }) {
|
||||
const router = useRouter();
|
||||
const { symbol } = useMoney();
|
||||
const [a, setA] = useState(apr?.toString() ?? "");
|
||||
const [p, setP] = useState(payment?.toString() ?? "");
|
||||
const [err, setErr] = useState("");
|
||||
async function save(field: "apr" | "debt_payment", raw: string, max: number) {
|
||||
const n = raw.trim() === "" ? null : Number(raw);
|
||||
if (n !== null && !(n >= 0 && n <= max)) return setErr(field === "apr" ? "A rate is between 0 and 100." : "That payment doesn't look right.");
|
||||
setErr("");
|
||||
const { error } = await createClient().from("accounts").update({ [field]: n }).eq("id", id);
|
||||
if (error) return setErr("Couldn't save that. Try again.");
|
||||
router.refresh();
|
||||
}
|
||||
const box = "flex items-center border border-line rounded-xl px-3 h-10 bg-surface focus-within:border-ink";
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-2 gap-3 max-w-md">
|
||||
<label className="space-y-1 text-xs text-muted block">Interest rate (APR)
|
||||
<span className={box}>
|
||||
<input inputMode="decimal" value={a} onChange={(e) => setA(e.target.value.replace(/[^\d.]/g, ""))} onBlur={() => save("apr", a, 100)} placeholder="24.99" aria-label="Interest rate" className="w-full text-sm text-ink tabular outline-none bg-transparent" />
|
||||
<span className="text-sm text-muted">%</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className="space-y-1 text-xs text-muted block">Monthly payment
|
||||
<span className={box}>
|
||||
<span className="text-sm text-muted mr-1">{symbol}</span>
|
||||
<input inputMode="decimal" value={p} onChange={(e) => setP(e.target.value.replace(/[^\d.]/g, ""))} onBlur={() => save("debt_payment", p, 1e7)} placeholder={guess >= 1 ? String(Math.round(guess)) : "0"} aria-label="Monthly payment" className="w-full text-sm text-ink tabular outline-none bg-transparent" />
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import { ArrowDown, ArrowUp } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRef, useState } from "react";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { EASE, firstVisit, reduced } from "@/components/motion";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
type Slice = { id: string; label: string; color: string; icon: string; v: number; prev: number };
|
||||
|
||||
// Donut + category list sharing one hover: hovering a slice or a row lifts that slice,
|
||||
// dims the others, and swaps the centre to that category's total.
|
||||
export function Breakdown({ slices, total, change, prevLabel, monthParam }: { slices: Slice[]; total: number; change: number | null; prevLabel: string; monthParam: string }) {
|
||||
const { money, money0 } = useMoney();
|
||||
const [hover, setHover] = useState<string | null>(null);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const sum = slices.reduce((s, x) => s + x.v, 0) || 1;
|
||||
const R = 100, r = 64, C = 120;
|
||||
|
||||
let a0 = -Math.PI / 2;
|
||||
const arcs = slices.map((s) => {
|
||||
const a1 = a0 + (s.v / sum) * Math.PI * 2;
|
||||
const mid = (a0 + a1) / 2;
|
||||
// Rounded: Math.cos/sin can differ in the last digit between Node and the browser, which breaks hydration.
|
||||
const p = (a: number, rad: number) => `${(C + rad * Math.cos(a)).toFixed(2)},${(C + rad * Math.sin(a)).toFixed(2)}`;
|
||||
const large = a1 - a0 > Math.PI ? 1 : 0;
|
||||
const d = slices.length === 1
|
||||
? `M${C},${C - R} A${R},${R} 0 1 1 ${C - 0.01},${C - R} L${C - 0.01},${C - r} A${r},${r} 0 1 0 ${C},${C - r} Z`
|
||||
: `M${p(a0, R)} A${R},${R} 0 ${large} 1 ${p(a1, R)} L${p(a1, r)} A${r},${r} 0 ${large} 0 ${p(a0, r)} Z`;
|
||||
const round = (n: number) => Math.round(n * 100) / 100;
|
||||
const out = { dx: round(Math.cos(mid) * 6), dy: round(Math.sin(mid) * 6) };
|
||||
const icon = { x: round(C + ((R + r) / 2) * Math.cos(mid)), y: round(C + ((R + r) / 2) * Math.sin(mid)) };
|
||||
a0 = a1;
|
||||
return { s, d, out, icon, big: s.v / sum > 0.06 };
|
||||
});
|
||||
|
||||
useGSAP(
|
||||
() => {
|
||||
if (reduced() || !firstVisit("breakdown")) return;
|
||||
const slices = gsap.utils.toArray<SVGElement>("[data-slice]");
|
||||
gsap.set(slices, { transition: "none" });
|
||||
gsap.from(slices, {
|
||||
scale: 0.6, opacity: 0, transformOrigin: "120px 120px", duration: 0.6, ease: "back.out(1.4)", stagger: 0.04,
|
||||
// Hand transform/opacity back to the hover styles once the intro is done.
|
||||
onComplete: () => void gsap.set(slices, { clearProps: "transform,opacity,transition" }),
|
||||
});
|
||||
gsap.from("[data-row]", { x: -8, opacity: 0, duration: 0.3, ease: EASE, stagger: 0.03, delay: 0.2, clearProps: "transform,opacity" });
|
||||
},
|
||||
{ scope: root },
|
||||
);
|
||||
|
||||
const h = slices.find((s) => s.id === hover);
|
||||
const pct = (v: number) => Math.round((v / total) * 100);
|
||||
|
||||
return (
|
||||
<div ref={root} className="space-y-6">
|
||||
<div className="relative w-full max-w-72 mx-auto aspect-square" onPointerLeave={() => setHover(null)}>
|
||||
<svg viewBox="0 0 240 240" className="w-full h-full overflow-visible">
|
||||
{arcs.map(({ s, d, out }) => (
|
||||
<path
|
||||
key={s.id}
|
||||
data-slice
|
||||
d={d}
|
||||
fill={s.color}
|
||||
stroke="var(--surface)"
|
||||
strokeWidth="2"
|
||||
onPointerEnter={() => setHover(s.id)}
|
||||
className="cursor-pointer transition-[transform,opacity] duration-300 ease-[cubic-bezier(.33,1,.68,1)]"
|
||||
style={{ transform: hover === s.id ? `translate(${out.dx}px, ${out.dy}px)` : undefined, opacity: hover && hover !== s.id ? 0.35 : 1 }}
|
||||
/>
|
||||
))}
|
||||
</svg>
|
||||
{arcs.filter((a) => a.big).map(({ s, icon }) => (
|
||||
<span key={s.id} className="absolute -translate-x-1/2 -translate-y-1/2 rounded-full bg-surface/90 pointer-events-none transition-opacity duration-300" style={{ left: `${(icon.x / 240) * 100}%`, top: `${(icon.y / 240) * 100}%`, opacity: hover && hover !== s.id ? 0.3 : 1 }}>
|
||||
<CategoryIcon icon={s.icon} color={s.color} size={26} />
|
||||
</span>
|
||||
))}
|
||||
<div className="absolute inset-0 grid place-items-center text-center pointer-events-none">
|
||||
{h ? (
|
||||
<div key={h.id}>
|
||||
<div className="text-xs" style={{ color: h.color }}>{h.label}</div>
|
||||
<div className="text-2xl font-semibold tabular">{money(h.v)}</div>
|
||||
<div className="text-xs text-muted mt-1">{pct(h.v)}% of spend</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<div className="text-xs text-muted">Total spend</div>
|
||||
<div className="text-2xl font-semibold tabular">{money(total)}</div>
|
||||
{change !== null && (
|
||||
<div className="text-xs text-muted flex items-center justify-center gap-1 mt-1">
|
||||
{change > 0 ? <ArrowUp size={12} /> : <ArrowDown size={12} />}{Math.abs(change)}% from {prevLabel}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul onPointerLeave={() => setHover(null)}>
|
||||
{slices.map((c) => {
|
||||
const delta = c.v - c.prev;
|
||||
return (
|
||||
<li key={c.id} data-row>
|
||||
<Link
|
||||
href={`/transactions?category=${c.id}${monthParam}`}
|
||||
onPointerEnter={() => setHover(c.id)}
|
||||
onFocus={() => setHover(c.id)}
|
||||
className={`row-hover flex items-center gap-4 py-3 px-3 -mx-3 border-t border-line ${hover === c.id ? "bg-[var(--hover)]" : ""}`}
|
||||
>
|
||||
<CategoryIcon icon={c.icon} color={c.color} size={36} />
|
||||
<div className="flex-1">
|
||||
<div className="font-medium">{c.label}</div>
|
||||
<div className="text-xs text-muted">{pct(c.v)}% of spend</div>
|
||||
</div>
|
||||
<span className={`hidden @md:inline text-xs tabular ${delta > 0 ? "text-bad" : "text-good"}`}>{delta > 0 ? "↑" : "↓"} {money0(Math.abs(delta))}</span>
|
||||
<span className="w-24 text-right tabular font-medium">{money(c.v)}</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import { Check, ChevronDown, Search } from "lucide-react";
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { reduced } from "@/components/motion";
|
||||
|
||||
export type Option = { value: string; label: string; icon?: React.ReactNode; hint?: string; disabled?: boolean };
|
||||
|
||||
// One select for the whole app: animated menu, check on the current value, optional search, keyboard
|
||||
// (arrows, Enter, Esc, a letter jumps to the first match), disabled rows. The menu renders in a portal at a
|
||||
// fixed position, so cards that clip their overflow (the transactions table) can't cut it off. Inside a modal
|
||||
// <dialog> it portals into the dialog, since everything outside it is inert.
|
||||
// A select-only combobox: focus stays on the trigger (or the search box), aria-activedescendant names the row.
|
||||
// variant: "pill" (filters), "field" (forms, needs a placeholder), "inline" (a table cell: icon + label only).
|
||||
export function Dropdown({
|
||||
label, value, options, onChange, searchable = false, placeholder, variant = placeholder !== undefined ? "field" : "pill", dark = false, footer,
|
||||
}: {
|
||||
label: string; value: string; options: Option[]; onChange: (v: string) => void; searchable?: boolean; placeholder?: string;
|
||||
variant?: "pill" | "field" | "inline"; dark?: boolean; footer?: React.ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [q, setQ] = useState("");
|
||||
const [active, setActive] = useState(0);
|
||||
const [pos, setPos] = useState<{ top?: number; bottom?: number; left: number; width?: number; maxH: number } | null>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
const menu = useRef<HTMLDivElement>(null);
|
||||
const foot = useRef<HTMLDivElement>(null);
|
||||
const id = useId();
|
||||
const current = options.find((o) => o.value === value) ?? (variant === "pill" ? options[0] : undefined);
|
||||
const shown = q ? options.filter((o) => o.label.toLowerCase().includes(q.toLowerCase())) : options;
|
||||
const optId = (i: number) => `${id}-${i}`;
|
||||
const activeId = open && pos && shown[active] ? optId(active) : undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (activeId) document.getElementById(activeId)?.scrollIntoView({ block: "nearest" });
|
||||
}, [activeId]);
|
||||
|
||||
// Below the button, or above when there isn't room. Closes on scroll/resize instead of chasing the button.
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !button.current) return;
|
||||
const r = button.current.getBoundingClientRect();
|
||||
const below = innerHeight - r.bottom - 16, above = r.top - 16;
|
||||
const up = below < 260 && above > below;
|
||||
const width = variant === "field" ? r.width : undefined;
|
||||
const left = Math.max(8, Math.min(r.left, innerWidth - Math.max(width ?? 240, 240) - 8));
|
||||
setPos(up ? { bottom: innerHeight - r.top + 8, left, width, maxH: Math.min(360, above) } : { top: r.bottom + 8, left, width, maxH: Math.min(360, below) });
|
||||
const close = (e: Event) => !(e.target instanceof Node && menu.current?.contains(e.target)) && setOpen(false); // a window resize has no Node target
|
||||
addEventListener("scroll", close, true);
|
||||
addEventListener("resize", close);
|
||||
return () => {
|
||||
removeEventListener("scroll", close, true);
|
||||
removeEventListener("resize", close);
|
||||
};
|
||||
}, [open, variant]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (e: PointerEvent) => !button.current?.contains(e.target as Node) && !menu.current?.contains(e.target as Node) && setOpen(false);
|
||||
document.addEventListener("pointerdown", close);
|
||||
return () => document.removeEventListener("pointerdown", close);
|
||||
}, [open]);
|
||||
|
||||
useGSAP(
|
||||
() => {
|
||||
if (open && pos && menu.current && !reduced()) gsap.fromTo(menu.current, { opacity: 0, y: pos.top ? -6 : 6, scale: 0.98 }, { opacity: 1, y: 0, scale: 1, duration: 0.18, ease: "power2.out" });
|
||||
},
|
||||
{ dependencies: [open, !!pos] },
|
||||
);
|
||||
|
||||
function show(next: boolean) {
|
||||
if (next) setActive(Math.max(0, options.findIndex((o) => o.value === value)));
|
||||
else setPos(null);
|
||||
setOpen(next);
|
||||
setQ("");
|
||||
}
|
||||
|
||||
function pick(o: Option) {
|
||||
if (o.disabled) return;
|
||||
onChange(o.value);
|
||||
show(false);
|
||||
button.current?.focus();
|
||||
}
|
||||
|
||||
// Next enabled row in a direction, or stay put.
|
||||
function step(from: number, dir: 1 | -1) {
|
||||
for (let i = from + dir; i >= 0 && i < shown.length; i += dir) if (!shown[i].disabled) return i;
|
||||
return from;
|
||||
}
|
||||
|
||||
// Typeahead: the next enabled row (after the active one, wrapping) whose label starts with the letter.
|
||||
function jump(key: string, from: number) {
|
||||
const k = key.toLowerCase();
|
||||
for (let n = 1; n <= options.length; n++) {
|
||||
const i = (from + n) % options.length;
|
||||
if (!options[i].disabled && options[i].label.toLowerCase().startsWith(k)) return setActive(i);
|
||||
}
|
||||
}
|
||||
|
||||
function onKey(e: React.KeyboardEvent) {
|
||||
// Keys on the footer action are its own (Enter clicks it), except leaving the menu.
|
||||
if (foot.current?.contains(e.target as Node) && e.key !== "Escape" && e.key !== "Tab") return;
|
||||
const letter = !searchable && e.key.length === 1 && e.key !== " " && !e.metaKey && !e.ctrlKey && !e.altKey;
|
||||
if (!open && (["ArrowDown", "ArrowUp", "Enter", " "].includes(e.key) || letter)) {
|
||||
e.preventDefault();
|
||||
show(true);
|
||||
if (letter) jump(e.key, options.findIndex((o) => o.value === value));
|
||||
return;
|
||||
}
|
||||
if (!open) return;
|
||||
// preventDefault on Escape also stops a surrounding <dialog> from closing.
|
||||
if (e.key === "Escape") { e.preventDefault(); show(false); button.current?.focus(); }
|
||||
// Focus the trigger first so Tab moves on from it, not from the menu at the end of the page.
|
||||
else if (e.key === "Tab") {
|
||||
// Tab from the search box goes on into the footer action; anywhere else it closes the menu.
|
||||
const intoFooter = footer && !e.shiftKey && menu.current?.contains(e.target as Node) && !foot.current?.contains(e.target as Node);
|
||||
if (!intoFooter) { show(false); button.current?.focus(); }
|
||||
}
|
||||
else if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => step(a, 1)); }
|
||||
else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => step(a, -1)); }
|
||||
else if ((e.key === "Enter" || (e.key === " " && !searchable)) && shown[active]) { e.preventDefault(); pick(shown[active]); }
|
||||
else if (letter) { e.preventDefault(); jump(e.key, active); }
|
||||
}
|
||||
|
||||
const changed = value !== options[0]?.value;
|
||||
const trigger = {
|
||||
pill: `flex items-center gap-2 text-sm pl-3.5 pr-3 py-1.5 rounded-full whitespace-nowrap ${open ? "bg-[var(--hover-strong)]" : changed ? "bg-ink text-on-ink hover:bg-ink/85" : "hover:bg-[var(--hover)]"}`,
|
||||
field: `w-full flex items-center gap-2.5 text-sm text-left bg-surface border rounded-xl px-3.5 py-2.5 transition-colors ${open ? "border-ink" : "border-line hover:border-muted/50"}`,
|
||||
inline: `group inline-flex items-center gap-2.5 rounded-full pr-2.5 text-left ${dark ? `hover:text-white ${open ? "text-white" : "text-white/50"}` : open ? "bg-[var(--hover)]" : "hover:bg-[var(--hover)]"}`,
|
||||
}[variant];
|
||||
const skin = dark
|
||||
? { menu: "bg-[#1a1a1d] text-[#e6e6e6] border-white/10 font-mono text-[13px]", row: "bg-white/10", line: "border-white/10", muted: "text-white/40", check: "text-[#8b9cff]" }
|
||||
: { menu: "bg-surface border-line text-sm", row: "bg-[var(--hover)]", line: "border-line", muted: "text-muted", check: "text-brand" };
|
||||
|
||||
return (
|
||||
<div className={variant === "field" ? "relative" : "relative inline-flex min-w-0 max-w-full"} onKeyDown={onKey}>
|
||||
<button
|
||||
ref={button}
|
||||
type="button"
|
||||
role="combobox"
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
aria-activedescendant={searchable ? undefined : activeId}
|
||||
aria-label={`${label}: ${current?.label ?? placeholder ?? "none"}`}
|
||||
onClick={() => show(!open)}
|
||||
className={`${trigger} max-w-full`}
|
||||
>
|
||||
{current?.icon}
|
||||
<span className={`truncate ${variant === "field" ? `flex-1 ${current ? "" : "text-muted"}` : ""}`}>{current?.label ?? placeholder}</span>
|
||||
<ChevronDown
|
||||
size={variant === "inline" ? 14 : 15}
|
||||
className={`shrink-0 transition-transform duration-150 ${open ? "rotate-180" : ""} ${variant === "field" ? "text-muted" : ""} ${variant === "inline" && !dark && !open ? "text-muted opacity-0 group-hover:opacity-100" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{open && pos && createPortal(
|
||||
<div
|
||||
ref={menu}
|
||||
style={{ top: pos.top, bottom: pos.bottom, left: pos.left, width: pos.width }}
|
||||
className={`fixed z-[60] ${pos.width ? "" : "min-w-60 max-w-80"} rounded-2xl border shadow-[var(--shadow-pop)] p-1.5 ${skin.menu}`}
|
||||
>
|
||||
{searchable && (
|
||||
<label className={`flex items-center gap-2 px-2.5 py-2 mb-1 border-b ${skin.line}`}>
|
||||
<Search size={14} className={skin.muted} />
|
||||
<input
|
||||
autoFocus
|
||||
role="combobox"
|
||||
aria-label={`Search ${label.toLowerCase()}`}
|
||||
aria-expanded
|
||||
aria-controls={id}
|
||||
aria-autocomplete="list"
|
||||
aria-activedescendant={activeId}
|
||||
value={q}
|
||||
onChange={(e) => { setQ(e.target.value); setActive(0); }}
|
||||
placeholder={`Search ${label.toLowerCase()}`}
|
||||
className="flex-1 outline-none focus-visible:outline-none bg-transparent"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<ul id={id} role="listbox" aria-label={label} tabIndex={-1} className="overflow-y-auto" style={{ maxHeight: pos.maxH - (searchable ? 48 : 0) - (footer ? 48 : 0) }}>
|
||||
{shown.map((o, i) => (
|
||||
<li
|
||||
key={o.value}
|
||||
id={optId(i)}
|
||||
role="option"
|
||||
aria-selected={o.value === value}
|
||||
aria-disabled={o.disabled}
|
||||
onPointerEnter={() => !o.disabled && setActive(i)}
|
||||
onClick={() => pick(o)}
|
||||
className={`flex items-center gap-2.5 px-2.5 py-2 rounded-xl ${o.disabled ? `${skin.muted} cursor-not-allowed` : "cursor-pointer"} ${i === active && !o.disabled ? skin.row : ""}`}
|
||||
>
|
||||
{o.icon}
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block truncate">{o.label}</span>
|
||||
{o.hint && <span className={`block text-xs truncate ${skin.muted}`}>{o.hint}</span>}
|
||||
</span>
|
||||
{o.value === value && <Check size={15} className={`shrink-0 ${skin.check}`} />}
|
||||
</li>
|
||||
))}
|
||||
{!shown.length && <li className={`px-2.5 py-3 ${skin.muted}`}>No matches</li>}
|
||||
</ul>
|
||||
{footer && <div ref={foot} className={`border-t mt-1 pt-1 ${skin.line}`} onClick={() => { show(false); button.current?.focus(); }}>{footer}</div>}
|
||||
</div>,
|
||||
button.current?.closest("dialog") ?? document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Link from "next/link";
|
||||
import { FeedConnect } from "@/components/FeedConnect";
|
||||
import { ImportStatement } from "@/components/ImportStatement";
|
||||
import { AkahuButton, LinkBankButton, TestModeNote } from "@/components/PlaidButtons";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import { getUser } from "@/lib/data";
|
||||
import { addChoices } from "@/lib/providers";
|
||||
|
||||
// The one empty state for "no bank data yet": says what the page will show and gives the next step.
|
||||
// Users with only investment accounts get copy that fits what they have.
|
||||
export async function EmptyBank({ title = "Link an account to get started", body = "broke reads your transactions through Plaid, with bank-level encryption.", children }: { title?: string; body?: string; children?: React.ReactNode }) {
|
||||
const { supabase, user } = await getUser();
|
||||
const { data } = await supabase.from("accounts").select("user_id, type");
|
||||
const own = (data ?? []).filter((a) => a.user_id === user?.id);
|
||||
const country = countryOf(user?.user_metadata?.profile?.country);
|
||||
const choices = addChoices(country.code); // the same choices as /accounts/add
|
||||
const investOnly = !!own.length && own.every((a) => a.type === "investment");
|
||||
return (
|
||||
<div className="card p-10 max-w-xl mx-auto mt-6 text-center space-y-5">
|
||||
<h2 className="text-2xl font-semibold">{title}</h2>
|
||||
<p className="text-sm text-muted">
|
||||
{investOnly ? "Your linked accounts are investments. Spending and budgets come from a bank or card, or from transactions you add by hand." : body}
|
||||
</p>
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
{choices.feeds.map((f) => <FeedConnect key={f} id={f} country={country.code} />)}
|
||||
{choices.bank === "akahu" && <AkahuButton primary />}
|
||||
{choices.bank === "plaid" && <LinkBankButton label={investOnly ? "Link a bank or card" : "Link a bank"} primary />}
|
||||
{choices.sandbox && <LinkBankButton sandbox label="Use a test bank (sandbox)" />}
|
||||
{choices.sandbox && <TestModeNote />}
|
||||
<ImportStatement accounts={[]} locale={country.locale} currency={country.currency} />
|
||||
{children ?? (investOnly && <Link href="/transactions" className="text-sm underline underline-offset-2">Add a transaction by hand</Link>)}
|
||||
<Link href="/accounts/add" className="text-sm text-muted underline underline-offset-2 hover:text-ink">More ways to add an account</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
|
||||
const TITLE: Record<string, { title: string; body: string }> = {
|
||||
enablebanking: { title: "Link your bank", body: "Pick your bank and approve on its own page. broke can only read, it can't move money." },
|
||||
basiq: { title: "Link your bank", body: "Approve on a secure page run by Basiq. broke can only read, it can't move money." },
|
||||
belvo: { title: "Conectar seu banco", body: "Open Finance needs your CPF and full name. They go to Belvo for your consent and broke doesn't keep them. broke can only read." },
|
||||
};
|
||||
|
||||
// One hosted-consent connection: asks what it needs, then sends the user to the vendor's or the bank's page.
|
||||
export function FeedConnect({ id, country }: { id: string; country: string }) {
|
||||
const [banks, setBanks] = useState<string[] | null>(null);
|
||||
const [bank, setBank] = useState("");
|
||||
const [cpf, setCpf] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
useEffect(() => {
|
||||
if (id !== "enablebanking") return;
|
||||
fetch(`/api/bank/connect/${id}/start?country=${country}`).then((r) => r.json()).then((b: { banks?: string[]; error?: string }) => {
|
||||
setBanks(b.banks ?? []);
|
||||
if (b.error) setErr(b.error);
|
||||
}).catch(() => setErr("Couldn't load the bank list."));
|
||||
}, [id, country]);
|
||||
async function go(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const res = await fetch(`/api/bank/connect/${id}/start`, { method: "POST", body: JSON.stringify({ bank, country, cpf, name }) }).catch(() => null);
|
||||
const body = await res?.json().catch(() => ({}));
|
||||
if (res?.ok && body?.url) return void (window.location.href = body.url);
|
||||
setErr(body?.error ?? "Couldn't start the connection.");
|
||||
setBusy(false);
|
||||
}
|
||||
const t = TITLE[id];
|
||||
const ready = id === "enablebanking" ? !!bank : id === "belvo" ? !!cpf && !!name : true;
|
||||
return (
|
||||
<form onSubmit={go} className="card p-5 space-y-3">
|
||||
<div>
|
||||
<div className="card-title">{t.title}</div>
|
||||
<p className="text-sm text-muted mt-0.5">{t.body}</p>
|
||||
</div>
|
||||
{id === "enablebanking" && <Dropdown label="Your bank" placeholder={banks ? "Choose your bank" : "Loading banks..."} searchable value={bank} options={(banks ?? []).map((b) => ({ value: b, label: b }))} onChange={setBank} />}
|
||||
{id === "belvo" && (
|
||||
<div className="grid gap-3 @lg:grid-cols-2">
|
||||
<input value={cpf} onChange={(e) => setCpf(e.target.value)} inputMode="numeric" autoComplete="off" placeholder="CPF" aria-label="CPF" className="select" />
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} autoComplete="name" placeholder="Nome completo" aria-label="Nome completo" className="select" />
|
||||
</div>
|
||||
)}
|
||||
<button disabled={!ready || busy} className="btn-primary">{busy ? "Opening..." : "Continue"}</button>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
"use client";
|
||||
|
||||
import { Search, X } from "lucide-react";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { RangePicker } from "@/components/RangePicker";
|
||||
|
||||
type Opt = { id: string; label: string; icon?: string; color?: string };
|
||||
|
||||
// Filters apply on change (search after a short pause), and the URL keeps them so back/refresh work.
|
||||
export function Filters({ categories, accounts, tags = [], today }: { categories: Opt[]; accounts: Opt[]; tags?: string[]; today: string }) {
|
||||
const router = useRouter();
|
||||
const path = usePathname();
|
||||
const params = useSearchParams();
|
||||
const [q, setQ] = useState(params.get("q") ?? "");
|
||||
const [pending, start] = useTransition();
|
||||
|
||||
const update = (key: string, value: string) => {
|
||||
const next = new URLSearchParams(params);
|
||||
if (value) next.set(key, value);
|
||||
else next.delete(key);
|
||||
next.delete("limit");
|
||||
start(() => router.replace(`${path}?${next}`, { scroll: false }));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (q === (params.get("q") ?? "")) return;
|
||||
const t = setTimeout(() => update("q", q), 300);
|
||||
return () => clearTimeout(t);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [q]);
|
||||
|
||||
const from = params.get("from") ?? "", to = params.get("to") ?? "";
|
||||
const [custom, setCustom] = useState(!!(from || to));
|
||||
const dates = (a: string, b: string, range = "") => {
|
||||
const next = new URLSearchParams(params);
|
||||
for (const [k, v] of [["from", a], ["to", b], ["range", range]]) {
|
||||
if (v) next.set(k, v);
|
||||
else next.delete(k);
|
||||
}
|
||||
next.delete("limit");
|
||||
start(() => router.replace(`${path}?${next}`, { scroll: false }));
|
||||
};
|
||||
|
||||
const active = ["q", "range", "from", "to", "category", "account", "tag"].some((k) => params.get(k));
|
||||
|
||||
return (
|
||||
<div className="space-y-3 relative z-20">
|
||||
<div className={`card @2xl:!rounded-full !overflow-visible relative z-20 flex flex-wrap items-center gap-1 px-3 py-2 transition-opacity ${pending ? "opacity-70" : ""}`}>
|
||||
<label className="flex items-center gap-2 flex-1 min-w-48 px-3 rounded-full focus-within:ring-2 focus-within:ring-brand/60">
|
||||
<Search size={16} className="text-muted" />
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search merchants" aria-label="Search transactions" className="flex-1 outline-none focus-visible:outline-none text-sm bg-transparent py-1.5" />
|
||||
</label>
|
||||
<Dropdown
|
||||
label="Date range"
|
||||
value={custom ? "custom" : params.get("range") ?? ""}
|
||||
onChange={(v) => {
|
||||
setCustom(v === "custom");
|
||||
if (v !== "custom") dates("", "", v);
|
||||
}}
|
||||
options={[
|
||||
{ value: "", label: "All dates" },
|
||||
{ value: "30", label: "Last 30 days" },
|
||||
{ value: "90", label: "Last 90 days" },
|
||||
{ value: "365", label: "Last year" },
|
||||
{ value: "custom", label: "Custom dates" },
|
||||
]}
|
||||
/>
|
||||
<Dropdown
|
||||
label="Categories"
|
||||
searchable
|
||||
value={params.get("category") ?? ""}
|
||||
onChange={(v) => update("category", v)}
|
||||
options={[{ value: "", label: "All categories" }, ...categories.map((c) => ({ value: c.id, label: c.label, icon: <CategoryIcon icon={c.icon} color={c.color} size={22} /> }))]}
|
||||
/>
|
||||
<Dropdown
|
||||
label="Accounts"
|
||||
value={params.get("account") ?? ""}
|
||||
onChange={(v) => update("account", v)}
|
||||
options={[{ value: "", label: "All accounts" }, ...accounts.map((a) => ({ value: a.id, label: a.label }))]}
|
||||
/>
|
||||
{!!tags.length && (
|
||||
<Dropdown
|
||||
label="Tags"
|
||||
searchable
|
||||
value={params.get("tag") ?? ""}
|
||||
onChange={(v) => update("tag", v)}
|
||||
options={[{ value: "", label: "All tags" }, ...tags.map((t) => ({ value: t, label: t }))]}
|
||||
/>
|
||||
)}
|
||||
{active && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setQ("");
|
||||
setCustom(false);
|
||||
start(() => router.replace(path, { scroll: false }));
|
||||
}}
|
||||
className="filter flex items-center gap-1 text-muted"
|
||||
>
|
||||
<X size={14} /> Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{custom && (
|
||||
<section className="card px-5 py-4">
|
||||
<RangePicker key={`${from}|${to}`} from={from} to={to} today={today} onApply={(a, b) => dates(a, b)} />
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Link from "next/link";
|
||||
import { duplicateItems } from "@/lib/links";
|
||||
import { addChoices } from "@/lib/providers";
|
||||
import { currentEnv, supabaseReady } from "@/lib/setup";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
// Home: on Plaid's test banks, the way to real ones; on real banks with test connections still there, the way to clear them.
|
||||
export async function GoLiveCard({ country, userId }: { country?: string | null; userId?: string }) {
|
||||
if (addChoices(country).sandbox) {
|
||||
return (
|
||||
<Link href="/go-live" className="card-link px-5 py-3.5 flex items-center justify-between gap-3">
|
||||
<span className="min-w-0 truncate">You're looking at test data</span>
|
||||
<span className="text-sm shrink-0 underline underline-offset-4">Use your real bank</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
if (!userId || !supabaseReady()) return null;
|
||||
// A bank linked twice doubles every transaction: say so first.
|
||||
const { data: items } = await createAdminClient().from("plaid_items").select("id, institution_id, institution_name, created_at, accounts(mask, type)").eq("user_id", userId);
|
||||
const copies = duplicateItems((items ?? []).map((i) => ({ id: i.id, institution_id: i.institution_id, created_at: i.created_at, accounts: (i.accounts ?? []) as { mask: string | null; type: string | null }[] })));
|
||||
if (copies.size) {
|
||||
const names = [...new Set((items ?? []).filter((i) => copies.has(i.id)).map((i) => i.institution_name ?? "A bank"))];
|
||||
return (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="card-title">{names.join(" and ")} {names.length === 1 ? "is" : "are"} linked twice</div>
|
||||
<p className="text-sm text-muted">Each copy brings in the same transactions, so they show up twice. Remove the extra copy and everything shows once.</p>
|
||||
<Link href="/accounts/add" className="btn-primary inline-block">Fix it</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (currentEnv().PLAID_ENV !== "production") return null;
|
||||
const { count } = await createAdminClient().from("plaid_items").select("id", { count: "exact", head: true }).eq("user_id", userId).like("access_token", "access-sandbox-%");
|
||||
if (!count) return null;
|
||||
return (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="card-title">Test data is still mixed in</div>
|
||||
<p className="text-sm text-muted">{count === 1 ? "A test bank from before" : `${count} test banks from before`} still {count === 1 ? "sits" : "sit"} next to your real money, and every total here counts {count === 1 ? "it" : "them"}.</p>
|
||||
<Link href="/settings#banks" className="btn-primary inline-block">Delete test data</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Plus, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { GOALS, hasTarget, type GoalPlan } from "@/lib/advice";
|
||||
|
||||
// A target being typed can be half filled; whoever saves keeps only whole ones (validGoalPlan).
|
||||
export type DraftPlan = { goal: string; amount?: number; by?: string; saved?: number };
|
||||
|
||||
// Pick from the list or type your own. Goals with a target (TARGET_GOALS and anything typed) open amount, date, saved.
|
||||
// The first goal picked is the main one. Onboarding and the money profile share this.
|
||||
export function GoalPicker({ goals, plans, onChange, showMain }: { goals: string[]; plans: (GoalPlan | DraftPlan)[]; onChange: (goals: string[], plans: DraftPlan[]) => void; showMain?: boolean }) {
|
||||
const { money0 } = useMoney();
|
||||
const [typed, setTyped] = useState("");
|
||||
const own = goals.filter((g) => !GOALS.includes(g));
|
||||
const plan = (goal: string) => plans.find((g) => g.goal === goal);
|
||||
const setPlan = (goal: string, k: "amount" | "by" | "saved", v: string) =>
|
||||
onChange(goals, [...plans.filter((g) => g.goal !== goal), { ...plan(goal), goal, [k]: k === "by" ? v : v === "" ? undefined : Number(v) }]);
|
||||
const toggle = (g: string) => onChange(goals.includes(g) ? goals.filter((x) => x !== g) : [...goals, g], plans);
|
||||
function add() {
|
||||
const name = typed.trim().slice(0, 60);
|
||||
setTyped("");
|
||||
if (!name) return;
|
||||
const known = [...GOALS, ...own].find((g) => g.toLowerCase() === name.toLowerCase());
|
||||
if (!goals.includes(known ?? name)) onChange([...goals, known ?? name], plans);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[...GOALS, ...own].map((g) => {
|
||||
const on = goals.includes(g);
|
||||
return (
|
||||
<button key={g} type="button" aria-pressed={on} onClick={() => toggle(g)}
|
||||
className={`text-sm rounded-full px-3.5 py-1.5 border flex items-center gap-1.5 ${on ? "bg-ink text-on-ink border-ink" : "border-line hover:bg-canvas"}`}>
|
||||
{on && (GOALS.includes(g) ? <Check size={14} /> : <X size={14} />)}{g}{showMain && goals[0] === g && <span className="opacity-70">· main</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<input value={typed} onChange={(e) => setTyped(e.target.value)} maxLength={60} aria-label="Add your own goal" placeholder="Add your own, e.g. Trip to Japan" className="select"
|
||||
onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
|
||||
<button type="button" onClick={add} disabled={!typed.trim()} className="btn shrink-0 inline-flex items-center gap-1.5"><Plus size={15} /> Add</button>
|
||||
</div>
|
||||
{goals.filter(hasTarget).map((g) => {
|
||||
const t = plan(g);
|
||||
return (
|
||||
<div key={g} className="grid gap-2 grid-cols-3 pt-1">
|
||||
<span className="col-span-3 text-sm font-medium">{g}: your target (optional)</span>
|
||||
<label className="space-y-1 text-xs text-muted">Amount
|
||||
<input type="number" min={0} inputMode="numeric" value={t?.amount ?? ""} onChange={(e) => setPlan(g, "amount", e.target.value)} placeholder={money0(g === "Buy a home" || g === "Save for kids' college" ? 40000 : 5000)} className="select text-ink" />
|
||||
</label>
|
||||
<label className="space-y-1 text-xs text-muted">By
|
||||
<input type="month" value={t?.by ?? ""} min={new Date().toISOString().slice(0, 7)} onChange={(e) => setPlan(g, "by", e.target.value)} className="select text-ink" />
|
||||
</label>
|
||||
<label className="space-y-1 text-xs text-muted">Saved so far
|
||||
<input type="number" min={0} inputMode="numeric" value={t?.saved ?? ""} onChange={(e) => setPlan(g, "saved", e.target.value)} placeholder={money0(0)} className="select text-ink" />
|
||||
</label>
|
||||
{!!t?.amount !== !!t?.by && <p className="col-span-3 text-xs text-muted">Add {t?.amount ? "a date" : "an amount"} and broke works out what to put aside each month.</p>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { money0 } from "@/lib/format";
|
||||
import { EXPENSE_RATIO, feeCost30, INDEX_RATIO } from "@/lib/invest";
|
||||
|
||||
// A holding's expense ratio and its 30-year cost against a 0.03% index fund. Cash and money market rows show nothing.
|
||||
export function HoldingFee({ ticker, type, value }: { ticker: string | null; type: string | null; value: number | null }) {
|
||||
if (type === "cash" || !ticker || /^(CASH|CUR:)/.test(ticker)) return null;
|
||||
const ratio = EXPENSE_RATIO[ticker.toUpperCase()];
|
||||
if (ratio == null) return <span>fee unknown</span>;
|
||||
const cost = feeCost30(Number(value ?? 0), ratio);
|
||||
return (
|
||||
<span title={`${ratio}% a year. Over 30 years at 7% growth, ${money0(cost)} more in fees than a ${INDEX_RATIO}% index fund on today's value.`}>
|
||||
fee {ratio}%{cost >= 1 && <> · <span className={cost >= 1000 ? "text-bad" : ""}>about {money0(cost)} more over 30 years</span></>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// One file per icon: the package barrel pulls in all ~1,500 icons and slowed every dev compile.
|
||||
import { AirplaneTiltIcon } from "@phosphor-icons/react/dist/ssr/AirplaneTilt";
|
||||
import { ArrowsLeftRightIcon } from "@phosphor-icons/react/dist/ssr/ArrowsLeftRight";
|
||||
import { BankIcon } from "@phosphor-icons/react/dist/ssr/Bank";
|
||||
import { CarIcon } from "@phosphor-icons/react/dist/ssr/Car";
|
||||
import { CreditCardIcon } from "@phosphor-icons/react/dist/ssr/CreditCard";
|
||||
import { DotsThreeCircleIcon } from "@phosphor-icons/react/dist/ssr/DotsThreeCircle";
|
||||
import { FilmSlateIcon } from "@phosphor-icons/react/dist/ssr/FilmSlate";
|
||||
import { ForkKnifeIcon } from "@phosphor-icons/react/dist/ssr/ForkKnife";
|
||||
import { HeartbeatIcon } from "@phosphor-icons/react/dist/ssr/Heartbeat";
|
||||
import { HouseIcon } from "@phosphor-icons/react/dist/ssr/House";
|
||||
import { LightningIcon } from "@phosphor-icons/react/dist/ssr/Lightning";
|
||||
import { MoneyIcon } from "@phosphor-icons/react/dist/ssr/Money";
|
||||
import { ReceiptIcon } from "@phosphor-icons/react/dist/ssr/Receipt";
|
||||
import { ScalesIcon } from "@phosphor-icons/react/dist/ssr/Scales";
|
||||
import { ShoppingBagIcon } from "@phosphor-icons/react/dist/ssr/ShoppingBag";
|
||||
import { ShoppingCartIcon } from "@phosphor-icons/react/dist/ssr/ShoppingCart";
|
||||
import { SparkleIcon } from "@phosphor-icons/react/dist/ssr/Sparkle";
|
||||
import { WrenchIcon } from "@phosphor-icons/react/dist/ssr/Wrench";
|
||||
|
||||
// Phosphor fill (MIT).
|
||||
// The ssr entry works in server and client components.
|
||||
const CATEGORY_ICONS: Record<string, typeof MoneyIcon> = {
|
||||
income: MoneyIcon,
|
||||
transfer: ArrowsLeftRightIcon,
|
||||
credit_card: CreditCardIcon,
|
||||
loan: BankIcon,
|
||||
fees: ReceiptIcon,
|
||||
entertainment: FilmSlateIcon,
|
||||
dining: ForkKnifeIcon,
|
||||
groceries: ShoppingCartIcon,
|
||||
shopping: ShoppingBagIcon,
|
||||
home: HouseIcon,
|
||||
health: HeartbeatIcon,
|
||||
personal_care: SparkleIcon,
|
||||
services: WrenchIcon,
|
||||
taxes: ScalesIcon,
|
||||
transport: CarIcon,
|
||||
travel: AirplaneTiltIcon,
|
||||
bills: LightningIcon,
|
||||
other: DotsThreeCircleIcon,
|
||||
};
|
||||
|
||||
export const CATEGORY_ICON_KEYS = Object.keys(CATEGORY_ICONS);
|
||||
|
||||
// Category icon: a solid tile in the category colour with a white glyph.
|
||||
export function CategoryIcon({ icon, color, size = 32 }: { icon?: string | null; color?: string | null; size?: number }) {
|
||||
const Glyph = CATEGORY_ICONS[icon ?? "other"] ?? DotsThreeCircleIcon;
|
||||
const c = color ?? "#78716c";
|
||||
return (
|
||||
<span className="grid place-items-center shrink-0 text-white" style={{ width: size, height: size, borderRadius: "30%", background: c }}>
|
||||
<Glyph size={Math.round(size * 0.56)} weight="fill" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoryLabel({ icon, color, label }: { icon?: string | null; color?: string | null; label: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-2.5 text-sm">
|
||||
<CategoryIcon icon={icon} color={color} size={28} />
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { myCashInsights } from "@/lib/cash";
|
||||
import { money0 } from "@/lib/format";
|
||||
import { BANK_APY, HYSA_APY } from "@/lib/insights";
|
||||
|
||||
const pct = (r: number) => `${+(r * 100).toFixed(1)}%`;
|
||||
|
||||
// Checking and savings above 3 months of spending, and what it would earn in a high-yield account.
|
||||
export async function IdleCash() {
|
||||
const { idle, monthlySpend } = await myCashInsights();
|
||||
return (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="card-title">Idle Cash</div>
|
||||
{!idle ? (
|
||||
<p className="text-sm text-muted">Not enough spending history yet to check this.</p>
|
||||
) : idle.excess > 0 ? (
|
||||
<>
|
||||
<div className="figure">{money0(idle.excess)}</div>
|
||||
<p className="text-sm">
|
||||
{money0(idle.excess)} sits above 3 months of spending. At {pct(HYSA_APY)} that's about {money0(idle.hysa)} a year.
|
||||
A typical bank pays about {pct(BANK_APY)}, or {money0(idle.bank)}.
|
||||
</p>
|
||||
<p className="text-xs text-muted leading-relaxed">
|
||||
You spend about {money0(monthlySpend)} a month, so 3 months is {money0(idle.cushion)}. {pct(HYSA_APY)} is a typical high-yield savings rate, not a quote. If your savings already earns that, skip this.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
Your {money0(idle.cash)} {idle.available ? "available " : ""}in {idle.where} is under 3 months of spending ({money0(idle.cushion)}). Nothing sits idle.
|
||||
{Math.round(idle.current) > Math.round(idle.cash) && <> The {idle.where} balance is {money0(idle.current)}.</>}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import { Upload, X } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { applyRules, RULE_COLS, type Rule } from "@/lib/rules";
|
||||
import { applyMapping, parseStatement, type DateOrder, type Mapping, type Parsed, type Row } from "@/lib/statement";
|
||||
import { pdfToTable, type PdfItem } from "@/lib/statement-pdf";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Acct = { id: string; label: string };
|
||||
const NEW = "__new";
|
||||
const ORDERS: { value: DateOrder; label: string }[] = [
|
||||
{ value: "dmy", label: "Day first (31/12/2026)" },
|
||||
{ value: "mdy", label: "Month first (12/31/2026)" },
|
||||
{ value: "ymd", label: "Year first (2026/12/31)" },
|
||||
];
|
||||
|
||||
// "Import a bank statement": CSV, OFX or QIF from any bank. Rows are manual, keyed so a second import of the
|
||||
// same file adds nothing (transactions.import_key, migration 0016). Goes into a manual account or a new one.
|
||||
// trigger: draw your own opener (the Add accounts card) instead of the button.
|
||||
export function ImportStatement({ accounts, locale, currency, link = false, trigger }: { accounts: Acct[]; locale: string; currency: string; link?: boolean; trigger?: (open: () => void) => React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [file, setFile] = useState("");
|
||||
const [parsed, setParsed] = useState<Parsed | null>(null);
|
||||
const [m, setM] = useState<Mapping | null>(null);
|
||||
const [account, setAccount] = useState(accounts[0]?.id ?? NEW);
|
||||
const [newName, setNewName] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const [pdfFile, setPdfFile] = useState<File | null>(null); // a locked PDF waiting for its password
|
||||
const [pdfPass, setPdfPass] = useState("");
|
||||
|
||||
const result = useMemo((): { rows: Row[]; skipped: number } => {
|
||||
if (!parsed) return { rows: [], skipped: 0 };
|
||||
if (parsed.kind !== "csv") return { rows: parsed.rows, skipped: 0 };
|
||||
return m ? applyMapping(parsed.table, m, locale) : { rows: [], skipped: 0 };
|
||||
}, [parsed, m, locale]);
|
||||
const fmt = useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency }), [locale, currency]);
|
||||
|
||||
function reset() {
|
||||
setOpen(false);
|
||||
setParsed(null);
|
||||
setM(null);
|
||||
setFile("");
|
||||
setErr("");
|
||||
setPdfFile(null);
|
||||
setPdfPass("");
|
||||
}
|
||||
|
||||
// Read here in the browser: a PDF statement never leaves this device.
|
||||
async function readPdf(f: File, pass?: string) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const pdfjs = await import("pdfjs-dist");
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
|
||||
const doc = await pdfjs.getDocument({ data: await f.arrayBuffer(), password: pass }).promise;
|
||||
const items: PdfItem[] = [];
|
||||
for (let page = 1; page <= doc.numPages; page++) {
|
||||
for (const it of (await (await doc.getPage(page)).getTextContent()).items) {
|
||||
if ("str" in it && it.str.trim()) items.push({ str: it.str, x: it.transform[4], right: it.transform[4] + it.width, y: it.transform[5], page });
|
||||
}
|
||||
}
|
||||
const t = pdfToTable(items, locale);
|
||||
if (!t) return setErr(items.length ? "No transactions found in that PDF. Is it a bank statement?" : "That PDF is a scanned picture with no text in it. Ask your bank for a CSV or a text PDF.");
|
||||
setPdfFile(null);
|
||||
setFile(f.name);
|
||||
setNewName(f.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").slice(0, 60) || "Imported account");
|
||||
setParsed({ kind: "csv", ...t });
|
||||
setM(t.mapping);
|
||||
} catch (e) {
|
||||
// Many banks lock statements with a password.
|
||||
if ((e as { name?: string }).name === "PasswordException") {
|
||||
setPdfFile(f);
|
||||
setErr(pass ? "That password didn't open it. Try again." : "");
|
||||
} else {
|
||||
console.error("[broke] pdf statement:", e);
|
||||
setErr("Couldn't read that PDF.");
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function choose(f: File | undefined) {
|
||||
if (!f) return;
|
||||
setErr("");
|
||||
const pdf = f.type === "application/pdf" || /\.pdf$/i.test(f.name);
|
||||
if (f.size > (pdf ? 25e6 : 5e6)) return setErr(`That file is over ${pdf ? 25 : 5} MB. Export a shorter date range.`);
|
||||
if (pdf) return readPdf(f);
|
||||
const p = parseStatement(await f.text(), f.name, locale);
|
||||
if (p.kind === "csv" && !p.table.rows.length) return setErr("No dated rows found. Is this a bank statement export?");
|
||||
setFile(f.name);
|
||||
setNewName(f.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").slice(0, 60) || "Imported account");
|
||||
setParsed(p);
|
||||
setM(p.kind === "csv" ? p.mapping : null);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!result.rows.length) return setErr("Nothing to import. Check the columns below.");
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const supabase = createClient();
|
||||
let acct = account;
|
||||
if (acct === NEW) {
|
||||
// Currency left empty: a manual account is in the home currency (migration 0015).
|
||||
const { data, error } = await supabase.from("accounts").insert({ name: newName.trim() || "Imported account", type: "depository", subtype: "checking", current_balance: 0, manual: true }).select("id").single();
|
||||
if (error) return setBusy(false), setErr("Couldn't create the account.");
|
||||
acct = data.id;
|
||||
}
|
||||
const { data: rules } = await supabase.from("rules").select(RULE_COLS).order("created_at", { ascending: false });
|
||||
const rows = result.rows.map((r) => {
|
||||
const p = applyRules((rules ?? []) as Rule[], { ...r, account_id: acct });
|
||||
return { account_id: acct, date: r.date, amount: r.amount, name: r.name, merchant_name: r.name, import_key: r.key, manual: true,
|
||||
category_id: p.category_id ?? null, custom_name: p.custom_name ?? null, ignored: p.ignored ?? false, tags: p.tags ?? [] };
|
||||
});
|
||||
let added = 0;
|
||||
for (let i = 0; i < rows.length; i += 500) {
|
||||
const { data, error } = await supabase.from("transactions").upsert(rows.slice(i, i + 500), { onConflict: "account_id,import_key", ignoreDuplicates: true }).select("id");
|
||||
if (error) {
|
||||
setBusy(false);
|
||||
return setErr(/import_key/.test(error.message) ? "Statement import needs a database update. Open Setup to run it." : `Couldn't save the transactions${added ? ` after ${added}` : ""}.`);
|
||||
}
|
||||
added += data?.length ?? 0;
|
||||
}
|
||||
setBusy(false);
|
||||
const dupes = rows.length - added;
|
||||
toast(`${added} added${dupes ? `, ${dupes} already there` : ""}`);
|
||||
reset();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
const cols = parsed?.kind === "csv" ? parsed.table.header.map((h, i) => ({ value: String(i), label: h })) : [];
|
||||
const none = { value: "-1", label: "Not used" };
|
||||
const pick = (label: string, key: "date" | "name" | "amount" | "debit" | "credit", optional = false) =>
|
||||
m && (
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">{label}</span>
|
||||
<Dropdown label={label} value={String(m[key])} onChange={(v) => setM({ ...m, [key]: Number(v) })} placeholder="Choose a column" options={optional ? [none, ...cols] : cols} />
|
||||
</div>
|
||||
);
|
||||
const split = !!m && m.amount < 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
{trigger ? trigger(() => setOpen(true)) : <button onClick={() => setOpen(true)} className={link ? "inline-flex items-center gap-1 text-ink underline underline-offset-2 hover:opacity-70" : "btn inline-flex items-center gap-1.5"}>
|
||||
<Upload size={14} /> Import a bank statement
|
||||
</button>}
|
||||
{open && (
|
||||
<Modal label="Import a bank statement" onClose={reset} className="md:!max-w-2xl">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="card-title">Import a bank statement</div>
|
||||
<button type="button" aria-label="Close" onClick={reset} className="p-2 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
||||
</div>
|
||||
<p className="text-sm text-muted">Log in to your bank on a computer, open the account and look for Statements or Download. CSV, OFX, QIF and PDF all work. A PDF stays on this device. Importing the same file again adds nothing new.</p>
|
||||
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Statement file</span>
|
||||
<input data-autofocus type="file" accept=".csv,.txt,.ofx,.qfx,.qif,.pdf,text/csv,application/pdf" onChange={(e) => choose(e.target.files?.[0])} className="select file:mr-3 file:rounded-full file:border-0 file:bg-canvas file:px-3 file:py-1 file:text-sm" />
|
||||
</label>
|
||||
{pdfFile && (
|
||||
<form onSubmit={(e) => { e.preventDefault(); readPdf(pdfFile, pdfPass); }} className="space-y-2">
|
||||
<p className="text-sm">This PDF is locked. Banks often use something like your date of birth or customer number: your statement email usually says which. It stays on this device.</p>
|
||||
<div className="flex gap-2">
|
||||
<input type="password" autoComplete="off" value={pdfPass} onChange={(e) => setPdfPass(e.target.value)} aria-label="PDF password" className="select flex-1" />
|
||||
<button disabled={!pdfPass || busy} className="btn-primary shrink-0">{busy ? "Opening..." : "Open"}</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{parsed && (
|
||||
<>
|
||||
<p className="text-sm text-muted">
|
||||
{file}: {/\.pdf$/i.test(file) ? "PDF" : parsed.kind.toUpperCase()}, {result.rows.length} transactions{result.skipped ? `, ${result.skipped} rows skipped (no date or amount)` : ""}.
|
||||
</p>
|
||||
|
||||
{m && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{pick("Date", "date")}
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Date format</span>
|
||||
<Dropdown label="Date format" value={m.order} onChange={(v) => setM({ ...m, order: v as DateOrder })} placeholder="Choose" options={ORDERS} />
|
||||
</div>
|
||||
{pick("Description", "name")}
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Amounts</span>
|
||||
<Dropdown
|
||||
label="Amounts" placeholder="Choose"
|
||||
value={split ? "split" : m.outPositive ? "pos" : "neg"}
|
||||
onChange={(v) => setM(v === "split"
|
||||
? { ...m, amount: -1, debit: m.debit >= 0 ? m.debit : 0, credit: m.credit >= 0 ? m.credit : 0 }
|
||||
: { ...m, amount: m.amount >= 0 ? m.amount : Math.max(0, m.debit), outPositive: v === "pos" })}
|
||||
options={[
|
||||
{ value: "neg", label: "One column, money out is negative" },
|
||||
{ value: "pos", label: "One column, money out is positive" },
|
||||
{ value: "split", label: "Separate money out and money in columns" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{split ? <>{pick("Money out", "debit", true)}{pick("Money in", "credit", true)}</> : pick("Amount", "amount")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border border-line rounded-xl overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead><tr className="text-left text-xs text-muted border-b border-line"><th className="px-3 py-2 font-medium">Date</th><th className="px-3 py-2 font-medium">Description</th><th className="px-3 py-2 font-medium text-right">Amount</th></tr></thead>
|
||||
<tbody>
|
||||
{result.rows.slice(0, 5).map((r) => (
|
||||
<tr key={r.key} className="border-b border-line last:border-0">
|
||||
<td className="px-3 py-2 tabular whitespace-nowrap">{r.date}</td>
|
||||
<td className="px-3 py-2 truncate max-w-0 w-full">{r.name}</td>
|
||||
<td className={`px-3 py-2 tabular text-right whitespace-nowrap ${r.amount < 0 ? "text-good" : ""}`}>{r.amount < 0 ? `+${fmt.format(-r.amount)}` : fmt.format(r.amount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!result.rows.length && <tr><td colSpan={3} className="px-3 py-4 text-center text-muted">No rows read with these columns.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Into account</span>
|
||||
<Dropdown label="Into account" value={account} onChange={setAccount} placeholder="Choose an account"
|
||||
options={[...accounts.map((a) => ({ value: a.id, label: a.label })), { value: NEW, label: "New account", hint: `In ${currency}` }]} />
|
||||
</div>
|
||||
{account === NEW && (
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Account name</span>
|
||||
<input value={newName} onChange={(e) => setNewName(e.target.value)} className="select" />
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
{parsed && <button onClick={submit} disabled={busy || !result.rows.length} className="btn-primary w-full !py-2.5">{busy ? "Importing..." : `Import ${result.rows.length} transactions`}</button>}
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import Link from "next/link";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { RemoveCopy } from "@/components/PlaidButtons";
|
||||
import { duplicateItems } from "@/lib/links";
|
||||
import { fmtFor, fmtWith } from "@/lib/format";
|
||||
import { historyPending } from "@/lib/sync";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
const ago = (iso: string | null) => {
|
||||
if (!iso) return "not synced yet";
|
||||
const m = Math.round((Date.now() - Date.parse(iso)) / 60_000);
|
||||
return m < 1 ? "synced just now" : m < 60 ? `synced ${m} min ago` : m < 1440 ? `synced ${Math.round(m / 60)} h ago` : `synced ${Math.round(m / 1440)} d ago`;
|
||||
};
|
||||
|
||||
// Every connection the user has, with its accounts, before the ways to add more. Own connections only
|
||||
// (a partner's shared accounts live on /accounts). Admin client: test vs real comes from the access token,
|
||||
// which the browser role can't read (0002); only that one fact leaves this component.
|
||||
export async function LinkedNow({ userId, profile }: { userId: string; profile?: { country?: string; currency?: string } }) {
|
||||
const db = createAdminClient();
|
||||
const [{ data: items }, { data: accts }] = await Promise.all([
|
||||
db.from("plaid_items").select("id, institution_id, institution_name, institution_logo, institution_color, provider, status, last_synced_at, created_at, access_token").eq("user_id", userId).order("created_at"),
|
||||
db.from("accounts").select("id, item_id, name, custom_name, mask, type, current_balance, manual").eq("user_id", userId).order("name"),
|
||||
]);
|
||||
const money = fmtWith(fmtFor(profile)).money0;
|
||||
const pending = new Set(historyPending());
|
||||
const conns = (items ?? []).map((i) => ({
|
||||
id: i.id as string, name: (i.institution_name as string | null) ?? "Bank", logo: i.institution_logo as string | null, color: i.institution_color as string | null,
|
||||
test: !!(i.access_token as string | null)?.startsWith("access-sandbox-"), broken: i.status !== "ok", synced: i.last_synced_at as string | null,
|
||||
institution_id: i.institution_id as string | null, created_at: i.created_at as string,
|
||||
accounts: (accts ?? []).filter((a) => a.item_id === i.id && !a.manual),
|
||||
}));
|
||||
const manual = (accts ?? []).filter((a) => a.manual);
|
||||
const copies = duplicateItems(conns.map((c) => ({ id: c.id, institution_id: c.institution_id, created_at: c.created_at, accounts: c.accounts.map((a) => ({ mask: a.mask as string | null, type: a.type as string | null })) })));
|
||||
if (!conns.length && !manual.length)
|
||||
return <section className="card p-5 text-sm text-muted">Nothing linked yet. Pick a way to add an account below.</section>;
|
||||
const label = (a: { custom_name: string | null; name: string; mask: string | null }) => `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}`;
|
||||
return (
|
||||
<section className="card overflow-hidden">
|
||||
<div className="p-5 pb-3 flex items-baseline justify-between gap-3">
|
||||
<div className="card-title">Linked now</div>
|
||||
<span className="text-sm text-muted">{conns.length} {conns.length === 1 ? "bank" : "banks"}, {(accts ?? []).length} accounts</span>
|
||||
</div>
|
||||
<ul className="divide-y divide-line border-t border-line">
|
||||
{conns.map((c) => (
|
||||
<li key={c.id} className="p-5 flex gap-3.5">
|
||||
<Merchant name={c.name} logo={c.logo} color={c.color} />
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||
<span className="font-medium">{c.name}</span>
|
||||
<span className={`text-sm ${c.test ? "text-bad" : c.broken ? "text-bad" : "text-muted"}`}>
|
||||
{c.test ? "Test bank, not real money" : c.broken ? "Needs you to sign in again" : ago(c.synced)}
|
||||
</span>
|
||||
</div>
|
||||
{copies.has(c.id) && (
|
||||
<div className="space-y-1.5 py-1">
|
||||
<p className="text-sm text-bad">Linked twice: these are the same accounts as the {c.name} above, so every transaction shows twice.</p>
|
||||
<RemoveCopy itemId={c.id} name={c.name} />
|
||||
</div>
|
||||
)}
|
||||
{pending.has(c.id) && <p className="text-sm text-muted">Older history is still coming in from the bank. broke checks again every 10 minutes.</p>}
|
||||
<ul className="text-sm text-muted">
|
||||
{c.accounts.map((a) => (
|
||||
<li key={a.id} className="flex justify-between gap-3 tabular"><span className="truncate">{label(a)}</span><span>{a.current_balance == null ? "" : money(Number(a.current_balance))}</span></li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
{manual.length > 0 && (
|
||||
<li className="p-5 space-y-1">
|
||||
<span className="font-medium">Added by hand</span>
|
||||
<ul className="text-sm text-muted">
|
||||
{manual.map((a) => <li key={a.id} className="flex justify-between gap-3 tabular"><span className="truncate">{label(a)}</span><span>{a.current_balance == null ? "" : money(Number(a.current_balance))}</span></li>)}
|
||||
</ul>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
{conns.some((c) => c.test) && (
|
||||
<p className="px-5 py-3.5 border-t border-line text-sm">Test banks count in your totals. <Link href="/settings#banks" className="underline underline-offset-2">Delete test data</Link></p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useId } from "react";
|
||||
|
||||
// broke's mark: a 2006 brick phone with "Credit: $0.00" on the screen (design/logo-2000s-2.html, G2).
|
||||
// The LCD text only reads at the large size; small, it's the silhouette and the green screen.
|
||||
export function PhoneMark({ size = 30 }: { size?: number }) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={(size * 120) / 210} height={size} viewBox="60 18 120 210" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}lcd`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#c8d89a" /><stop offset="1" stopColor="#9fb46a" /></linearGradient>
|
||||
<linearGradient id={`${id}body`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
</defs>
|
||||
<rect x="62" y="20" width="116" height="206" rx="26" fill={`url(#${id}body)`} stroke="#20242a" strokeWidth="3" />
|
||||
<rect x="78" y="44" width="84" height="74" rx="6" fill={`url(#${id}lcd)`} stroke="#222" strokeWidth="3" />
|
||||
{size >= 80 ? (
|
||||
<g fontFamily="Menlo, Courier New, monospace" fontWeight="700" fill="#2b3315">
|
||||
<text x="84" y="60" fontSize="9">▂▄▆ 1:37</text>
|
||||
<text x="120" y="84" textAnchor="middle" fontSize="18">broke</text>
|
||||
<text x="120" y="100" textAnchor="middle" fontSize="9">Credit: $0.00</text>
|
||||
<text x="84" y="113" fontSize="8">Menu</text>
|
||||
<text x="156" y="113" textAnchor="end" fontSize="8">Cry</text>
|
||||
</g>
|
||||
) : (
|
||||
<rect x="92" y="76" width="56" height="12" rx="2" fill="#2b3315" opacity=".75" />
|
||||
)}
|
||||
<rect x="104" y="128" width="32" height="14" rx="7" fill="#2a2e35" />
|
||||
<g fill="#2a2e35">
|
||||
{[152, 170, 188].flatMap((y) => [80, 109, 138].map((x) => <rect key={`${x}-${y}`} x={x} y={y} width="22" height="12" rx="5" />))}
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Logo() {
|
||||
return (
|
||||
<span className="flex items-center gap-2 font-semibold text-lg tracking-tight">
|
||||
<PhoneMark size={30} />
|
||||
broke
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { categoryOptions } from "@/components/RuleForm";
|
||||
import { TagEditor } from "@/components/Tags";
|
||||
import { toast } from "@/components/Toast";
|
||||
import type { Category } from "@/lib/data";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
type Acct = { id: string; label: string };
|
||||
const NEW_CASH = "__cash";
|
||||
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
|
||||
|
||||
// "Add transaction": cash, a bank Plaid can't reach, anything typed by hand. Saved with manual = true.
|
||||
export function AddTransaction({ accounts, cats, allTags }: { accounts: Acct[]; cats: Category[]; allTags: string[] }) {
|
||||
const { money, parseAmount } = useMoney();
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const empty = { date: today(), name: "", amount: "", out: true, account: accounts[0]?.id ?? NEW_CASH, category: "", note: "", tags: [] as string[] };
|
||||
const [f, setF] = useState(empty);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
const amount = Math.abs(parseAmount(f.amount));
|
||||
if (!f.name.trim()) return setErr("Add a name, like the shop or person.");
|
||||
if (!amount) return setErr("Add an amount.");
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const supabase = createClient();
|
||||
let account = f.account;
|
||||
if (account === NEW_CASH) {
|
||||
const { data, error } = await supabase.from("accounts").insert({ name: "Cash", type: "depository", subtype: "cash", current_balance: 0, manual: true }).select("id").single();
|
||||
if (error) return setBusy(false), setErr(/manual/.test(error.message) ? "Manual transactions need a database update. Open Setup to run it." : "Couldn't create the cash account.");
|
||||
account = data.id;
|
||||
}
|
||||
// Bank convention: positive = money out.
|
||||
const { error } = await supabase.from("transactions").insert({
|
||||
account_id: account, date: f.date, amount: f.out ? amount : -amount, name: f.name.trim(), merchant_name: f.name.trim(),
|
||||
category_id: f.category || null, note: f.note.trim() || null, tags: f.tags, manual: true,
|
||||
});
|
||||
setBusy(false);
|
||||
if (error) return setErr("Couldn't save that transaction.");
|
||||
setOpen(false);
|
||||
setF(empty);
|
||||
toast(`${f.name.trim()} added`);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setOpen(true)} className="inline-flex items-center gap-1 text-ink underline underline-offset-2 hover:opacity-70"><Plus size={14} /> Add transaction</button>
|
||||
{open && (
|
||||
<Modal label="Add transaction" onClose={() => setOpen(false)}>
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="card-title">Add transaction</div>
|
||||
<button type="button" aria-label="Close" onClick={() => setOpen(false)} className="p-2 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-1 p-1 bg-canvas rounded-full text-sm">
|
||||
{[true, false].map((out) => (
|
||||
<button key={String(out)} type="button" onClick={() => setF({ ...f, out })} className={`rounded-full py-1.5 ${f.out === out ? "bg-surface shadow-sm font-medium" : "text-muted"}`}>
|
||||
{out ? "Money out" : "Money in"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Name</span>
|
||||
<input data-autofocus value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder="e.g. Farmers market" className="select" />
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Amount</span>
|
||||
<input inputMode="decimal" value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} placeholder={money(0)} className="select tabular" />
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Date</span>
|
||||
<input type="date" value={f.date} max={today()} onChange={(e) => setF({ ...f, date: e.target.value })} className="select tabular" />
|
||||
</label>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Account</span>
|
||||
<Dropdown
|
||||
label="Account"
|
||||
value={f.account}
|
||||
onChange={(account) => setF({ ...f, account })}
|
||||
placeholder="Choose an account"
|
||||
options={[...accounts.map((a) => ({ value: a.id, label: a.label })), ...(accounts.some((a) => a.label === "Cash") ? [] : [{ value: NEW_CASH, label: "Cash", hint: "Creates a cash account" }])]}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Category</span>
|
||||
<Dropdown label="Category" value={f.category} onChange={(category) => setF({ ...f, category })} placeholder="Uncategorized" options={categoryOptions(cats)} searchable />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Tags <span className="text-muted font-normal">(optional)</span></span>
|
||||
<TagEditor value={f.tags} onChange={(tags) => setF({ ...f, tags })} all={allTags} />
|
||||
</div>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Note <span className="text-muted font-normal">(optional)</span></span>
|
||||
<input value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} className="select" />
|
||||
</label>
|
||||
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
<button disabled={busy} className="btn-primary w-full !py-2.5">{busy ? "Saving..." : "Add transaction"}</button>
|
||||
</form>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { myCashInsights } from "@/lib/cash";
|
||||
import { money0 } from "@/lib/format";
|
||||
import { TAKE_HOME } from "@/lib/insights";
|
||||
|
||||
const range = ([a, b]: [number, number]) => (Math.round(a) === Math.round(b) ? `about ${money0(b)}` : a < 1 ? `up to about ${money0(b)}` : `about ${money0(a)} to ${money0(b)}`);
|
||||
const ProfileLink = ({ children }: { children: string }) => <a href="#profile" className="underline underline-offset-4">{children}</a>;
|
||||
|
||||
// Employer 401(k) match vs what the user puts in, with pay estimated from their paychecks.
|
||||
export async function MatchCheck() {
|
||||
const { match: m } = await myCashInsights();
|
||||
const notes = {
|
||||
"no-profile": <p className="text-sm">Pick your employer 401(k) match in <ProfileLink>your money profile</ProfileLink> to check if you get all of it.</p>,
|
||||
"not-sure": <p className="text-sm">Your profile says you're not sure about your 401(k) match. Your benefits portal or HR lists it. Then update <ProfileLink>your money profile</ProfileLink>.</p>,
|
||||
"no-plan": <p className="text-sm text-muted">Your profile says you have no 401(k) at work, so there is no match to check.</p>,
|
||||
"no-match": <p className="text-sm text-muted">Your profile says your 401(k) has no employer match, so there is nothing to miss.</p>,
|
||||
"no-pay": <p className="text-sm">No paychecks found yet. Add your income range to <ProfileLink>your money profile</ProfileLink> to estimate this.</p>,
|
||||
};
|
||||
let body;
|
||||
if (m.status !== "ok") body = notes[m.status];
|
||||
else {
|
||||
const [lo, hi] = m.cap;
|
||||
const cap = lo === hi ? `${hi}%` : `${lo}-${hi}%`;
|
||||
const head = `Your employer matches up to ${cap}${hi === 6 && lo === 6 ? " or more" : ""} of pay.`;
|
||||
const g = m.gaps[0].gap;
|
||||
body = (
|
||||
<>
|
||||
{m.pct != null ? (
|
||||
<p className="text-sm">
|
||||
{head} You put in about {Math.round(m.pct)}%, so {g[1] > 0 ? <>you're leaving <b>{range(g)}</b> a year.</> : "you get the full match."}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm">{head} What you'd leave on the table each year:</p>
|
||||
<div className="space-y-2 text-sm">
|
||||
{m.gaps.map(({ pct, gap }) => (
|
||||
<div key={pct} className="flex justify-between">
|
||||
<span>If you put in {pct}%</span>
|
||||
<span className="tabular font-medium">{range(gap)}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex justify-between text-muted">
|
||||
<span>If you put in {hi}% or more</span>
|
||||
<span>full match</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<p className="text-xs text-muted leading-relaxed">
|
||||
{m.source === "profile"
|
||||
? `Pay is estimated at ${money0(m.gross)} from your household income range.`
|
||||
: `Pay is estimated at about ${money0(m.gross)} a year before tax. ${m.source === "income" ? `Your income is about ${money0((m.takeHome ?? 0) / 12)} a month, ${money0(m.takeHome)} a year` : `Your paychecks come to about ${money0(m.takeHome)} a year`}, and take-home is assumed to be ${TAKE_HOME * 100}% of pay.`}{" "}
|
||||
Assumes the match is dollar for dollar.
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="card-title">401(k) Match</div>
|
||||
{body}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { isGeneric, logoFor } from "@/lib/logos";
|
||||
|
||||
// Plaid's logo, else a local brand logo, else the category icon for money-moving rows, else the first letter.
|
||||
// icon: the row's category icon key. small: a 16px mark beside text (issuer names), not a row avatar.
|
||||
export function Merchant({ name, logo, color, icon, small }: { name: string; logo?: string | null; color?: string | null; icon?: string | null; small?: boolean }) {
|
||||
const src = logo || logoFor(name);
|
||||
const size = small ? "size-4" : "size-8";
|
||||
if (src) return <img src={src} alt="" className={`${size} rounded-full border border-line bg-white object-cover shrink-0`} />;
|
||||
if (small) return null;
|
||||
if (isGeneric(name, icon)) return <CategoryIcon icon={icon} color={color} />;
|
||||
return (
|
||||
<span
|
||||
className="size-8 rounded-full grid place-items-center text-xs font-semibold text-white shrink-0"
|
||||
style={{ background: color ?? "#78716c" }}
|
||||
>
|
||||
{name.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoryPill({ label, color }: { label: string; color: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 text-xs px-2 py-0.5 rounded-full border border-line">
|
||||
<span className="size-2 rounded-full" style={{ background: color }} />
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { toastHost } from "@/components/Toast";
|
||||
|
||||
// Native modal <dialog>: focus trap, Escape, inert page and the top layer come from the browser.
|
||||
// Bottom sheet on phones, centred card from md up (or always a sheet with `sheet`). Focus goes back to the trigger on close.
|
||||
export function Modal({ label, onClose, sheet = false, className = "", children }: { label: string; onClose: () => void; sheet?: boolean; className?: string; children: React.ReactNode }) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
const back = useRef<HTMLElement | null>(null);
|
||||
useEffect(() => {
|
||||
const d = ref.current!;
|
||||
if (!d.open) {
|
||||
back.current = document.activeElement as HTMLElement | null;
|
||||
d.showModal();
|
||||
// showModal focuses the first control; React's autoFocus ran while the dialog was still hidden.
|
||||
d.querySelector<HTMLElement>("[data-autofocus]")?.focus();
|
||||
}
|
||||
const drop = toastHost(d);
|
||||
return () => {
|
||||
drop();
|
||||
back.current?.focus();
|
||||
};
|
||||
}, []);
|
||||
return createPortal(
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={label}
|
||||
onClose={onClose}
|
||||
// A click on the dialog itself (not the panel) is a click on the dimmed backdrop.
|
||||
onClick={(e) => (e.stopPropagation(), e.target === e.currentTarget && onClose())}
|
||||
className={`fixed inset-0 m-0 p-0 size-full max-w-none max-h-none bg-transparent open:grid ${sheet ? "place-items-end" : "place-items-end md:place-items-center"} text-left font-normal whitespace-normal text-ink backdrop:bg-[var(--backdrop)] backdrop:animate-[fade_.15s_ease-out]`}
|
||||
>
|
||||
<div className={`relative w-full bg-surface ${sheet ? "rounded-t-3xl" : "md:max-w-md rounded-t-3xl md:rounded-3xl"} p-6 pb-[max(24px,env(safe-area-inset-bottom))] shadow-2xl max-h-[90vh] overflow-y-auto ${className}`}>
|
||||
{children}
|
||||
</div>
|
||||
</dialog>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import { fmtWith, US_FMT, type Fmt } from "@/lib/format";
|
||||
|
||||
// The user's currency and locale for client components; the app layout sets it from their profile.
|
||||
const Ctx = createContext<Fmt>(US_FMT);
|
||||
export const MoneyProvider = ({ fmt, children }: { fmt: Fmt; children: React.ReactNode }) => <Ctx.Provider value={fmt}>{children}</Ctx.Provider>;
|
||||
export function useMoney() {
|
||||
const f = useContext(Ctx);
|
||||
return useMemo(() => fmtWith(f), [f]);
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
"use client";
|
||||
|
||||
import { Bell, CalendarDays, Check, ChevronDown, Copy, LoaderCircle, Mail, MessageSquare, Phone, TriangleAlert } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { PayoffChart } from "@/components/PayoffChart";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { STEP_LABEL, STEPS, sectionOf, stepOf, type Kind, type Section, type Status } from "@/lib/plan";
|
||||
import type { Later, PMove } from "@/lib/projection";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Message = { to: string; channel: "email" | "sms" | "call"; subject?: string; body: string; phone?: string };
|
||||
export type PlanMove = {
|
||||
id: string; ref: string | null; kind: Kind; title: string; why: string; yearly_impact: number; effort: string; steps: string[];
|
||||
message: Message | null; links: { label: string; url: string }[]; confidence: string; status: Status; done_at: string | null;
|
||||
section: Section | null; deadline: string | null; step: number | null; once: boolean | null; gate: string | null; steps_done: number[] | null;
|
||||
};
|
||||
export type PlanState = {
|
||||
ready: boolean; running: boolean; error: string | null; saved: number; looksDone?: string[];
|
||||
stale?: string | null; // why the saved plan is out of date (loadPlan), or null
|
||||
done?: (PMove & { id: string })[]; // done moves across every run
|
||||
plan: { id: string; created_at: string; provider: string | null; summary: string | null; total_impact: number; note?: string | null } | null;
|
||||
moves: PlanMove[];
|
||||
};
|
||||
|
||||
const PROVIDER: Record<string, string> = { openrouter: "OpenRouter", claude: "Claude", codex: "ChatGPT", gemini: "Gemini", opencode: "opencode", local: "your local model" };
|
||||
// What the audit is doing, shown while it runs. Time-based: the CLI doesn't report its own progress.
|
||||
const STAGES = ["Reading your spending, bills and subscriptions", "Checking cash, debt, cards and your match", "Writing your plan", "Checking every number and link"];
|
||||
const LOOKS_AT = ["Spending above income, card interest and fees", "An emergency fund sized from your own essential spending", "Your employer match, then debt, then 401(k), HSA and IRA room you can afford", "Tax: your bracket, refunds, payments, losses to harvest and deductions", "Subscriptions, price rises and bills worth a call", "Messages worth sending, drafted for you"];
|
||||
|
||||
const enc = encodeURIComponent;
|
||||
const mailto = (m: Message) => `mailto:?${m.subject ? `subject=${enc(m.subject)}&` : ""}body=${enc(m.body)}`;
|
||||
const helpPrompt = (m: PlanMove) =>
|
||||
[
|
||||
`Help me do this move from my money plan: "${m.title}".`,
|
||||
`Why: ${m.why}`,
|
||||
m.gate ? `Note: ${m.gate}` : "",
|
||||
`Steps:\n${m.steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}`,
|
||||
m.message ? `Drafted ${m.message.channel === "call" ? "call script" : m.message.channel} for ${m.message.to}:\n${m.message.body}` : "",
|
||||
"Look up what you need from my accounts, then walk me through it with my real numbers: exactly what to say, click or compare. You can't do it for me, so give me the steps. Don't invent prices, phone numbers or links.",
|
||||
].filter(Boolean).join("\n\n");
|
||||
|
||||
// A calendar file for the move: at its deadline, or a week from today when it has none. Built in the browser.
|
||||
function remind(m: PlanMove, today: string) {
|
||||
const day = m.deadline ?? new Date(Date.parse(today) + 7 * 864e5).toISOString().slice(0, 10);
|
||||
const d = day.replace(/-/g, ""), next = new Date(Date.parse(day) + 864e5).toISOString().slice(0, 10).replace(/-/g, "");
|
||||
const esc = (s: string) => s.replace(/[\\;,]/g, (c) => `\\${c}`).replace(/\n/g, "\\n");
|
||||
const ics = [
|
||||
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//broke//money plan//EN", "BEGIN:VEVENT",
|
||||
`UID:${m.id}@broke`, `DTSTAMP:${new Date().toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`, `DTSTART;VALUE=DATE:${d}`, `DTEND;VALUE=DATE:${next}`,
|
||||
`SUMMARY:${esc(m.title)}`, `DESCRIPTION:${esc([m.why, ...m.steps.map((s, i) => `${i + 1}. ${s}`)].join("\n"))}`,
|
||||
"END:VEVENT", "END:VCALENDAR",
|
||||
].join("\r\n");
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(new Blob([ics], { type: "text/calendar" }));
|
||||
a.download = `${m.title.replace(/[^a-z0-9]+/gi, "-").toLowerCase().slice(0, 50)}.ics`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
|
||||
// "Set a $X budget" links: /budgets?set=<category id>&amount=<n>. Written like BudgetEditor does.
|
||||
const budgetLink = (url: string) => {
|
||||
const q = url.startsWith("/budgets?") ? new URLSearchParams(url.slice(9)) : null;
|
||||
const id = q?.get("set"), amount = Number(q?.get("amount"));
|
||||
return id && amount > 0 ? { id, amount } : null;
|
||||
};
|
||||
async function setBudget(category_id: string, amount: number) {
|
||||
const db = createClient();
|
||||
const { data: { user } } = await db.auth.getUser();
|
||||
if (!user) return false;
|
||||
const { error } = await db.from("budgets").upsert([{ user_id: user.id, category_id, amount, updated_at: new Date().toISOString() }]);
|
||||
return !error;
|
||||
}
|
||||
|
||||
// Section colours: var(--chart) and the muted category hues from migration 0017.
|
||||
const SECTION_COLOR: Record<Section, string> = { spending: "#b07a2a", tax: "var(--chart)", debt: "#9c4a3a", bills: "#2e7a8c", cards: "#a24f7c", saving: "#3f8a52" };
|
||||
// The same Phosphor duotone glyphs the category icons use.
|
||||
const SECTION_ICON: Record<Section, string> = { spending: "shopping", tax: "taxes", debt: "loan", bills: "bills", cards: "credit_card", saving: "income" };
|
||||
|
||||
// When to do a move: its deadline if it has one, else how long it takes.
|
||||
const WHEN = ["week", "month", "dec31", "taxday", "anytime"] as const;
|
||||
type When = (typeof WHEN)[number];
|
||||
const WHEN_LABEL: Record<When, string> = { week: "This week", month: "This month", dec31: "Before Dec 31", taxday: "By the tax deadline", anytime: "Anytime" };
|
||||
function whenOf(m: PlanMove, today: string): When {
|
||||
const year = Number(today.slice(0, 4));
|
||||
if (!m.deadline) return m.effort === "5 min" ? "week" : m.effort === "30 min" ? "month" : "anytime";
|
||||
const days = (Date.parse(m.deadline) - Date.parse(today)) / 864e5;
|
||||
if (days <= 7) return "week";
|
||||
if (days <= 31) return "month";
|
||||
if (m.deadline <= `${year}-12-31`) return "dec31";
|
||||
if (m.deadline <= `${year + 1}-04-15`) return "taxday";
|
||||
return "anytime";
|
||||
}
|
||||
|
||||
const value = (ms: PlanMove[], once: boolean) => ms.filter((m) => !!m.once === once).reduce((s, m) => s + Number(m.yearly_impact), 0);
|
||||
|
||||
export function MoneyPlan({ initial, today, name, payoff }: { initial: PlanState; today: string; name: string; payoff: { rate: number | null; later: Later | null } }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const [state, setState] = useState(initial);
|
||||
const [moves, setMoves] = useState(initial.moves);
|
||||
const [stage, setStage] = useState(0);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [showDone, setShowDone] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
// Saved across every run = the server's yearly total, adjusted for what changed on this page.
|
||||
const doneBefore = value(initial.moves.filter((m) => m.status === "done"), false);
|
||||
const saved = state.saved - doneBefore + value(moves.filter((m) => m.status === "done"), false);
|
||||
const live = moves.filter((m) => m.status === "todo" || m.status === "doing").sort((a, b) => stepOf(a) - stepOf(b));
|
||||
const yearly = value(live, false), once = value(live, true);
|
||||
const first = live[0];
|
||||
const ladder = STEPS.map((k) => ({ k, ms: live.filter((m) => stepOf(m) === k && m !== first) })).filter((x) => x.ms.length);
|
||||
const closed = moves.filter((m) => m.status === "done" || m.status === "dismissed");
|
||||
const timeline = WHEN.map((w) => ({ w, ms: live.filter((m) => whenOf(m, today) === w) })).filter((x) => x.ms.length);
|
||||
const short = (d: string) => dateLabel(d, { month: "short", day: "numeric" });
|
||||
const looks = new Set(state.looksDone ?? []);
|
||||
|
||||
const poll = () => {
|
||||
if (timer.current) return;
|
||||
const started = Date.now();
|
||||
timer.current = setInterval(async () => {
|
||||
setStage(Math.min(STAGES.length - 1, Math.floor((Date.now() - started) / 12000)));
|
||||
const r = await fetch("/api/plan").catch(() => null);
|
||||
if (!r?.ok) return;
|
||||
const s = (await r.json()) as PlanState;
|
||||
if (s.running) return;
|
||||
clearInterval(timer.current!);
|
||||
timer.current = null;
|
||||
setState(s);
|
||||
setMoves(s.moves);
|
||||
setOpen(null);
|
||||
router.refresh(); // the payoff chart's possible-later layer is worked out on the server from the new plan
|
||||
}, 2000);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (initial.running) poll();
|
||||
return () => { if (timer.current) clearInterval(timer.current); };
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const run = async () => {
|
||||
setState((s) => ({ ...s, running: true, error: null }));
|
||||
setStage(0);
|
||||
const r = await fetch("/api/plan", { method: "POST" }).catch(() => null);
|
||||
if (!r?.ok) return setState((s) => ({ ...s, running: false, error: "Couldn't start the audit. Try again." }));
|
||||
poll();
|
||||
};
|
||||
|
||||
const setStatus = async (m: PlanMove, status: Status, quiet = false) => {
|
||||
const before = m.status;
|
||||
const patch = { status, done_at: status === "done" ? new Date().toISOString() : null };
|
||||
setMoves((ms) => ms.map((x) => (x.id === m.id ? { ...x, ...patch } : x)));
|
||||
const { error } = await createClient().from("plan_moves").update(patch).eq("id", m.id);
|
||||
if (error) {
|
||||
setMoves((ms) => ms.map((x) => (x.id === m.id ? { ...x, status: before } : x)));
|
||||
return toast("Couldn't save that. Try again.");
|
||||
}
|
||||
if (!quiet) toast(status === "done" ? `Done: ${m.title}` : status === "dismissed" ? "Hidden from your plan" : "Moved back to to do", () => setStatus({ ...m, status }, before, true));
|
||||
};
|
||||
|
||||
// Ticked steps save to the move (0021 lets the browser update steps_done only).
|
||||
const setSteps = async (m: PlanMove, steps_done: number[]) => {
|
||||
const before = m.steps_done ?? [];
|
||||
setMoves((ms) => ms.map((x) => (x.id === m.id ? { ...x, steps_done } : x)));
|
||||
const { error } = await createClient().from("plan_moves").update({ steps_done }).eq("id", m.id);
|
||||
if (error) {
|
||||
setMoves((ms) => ms.map((x) => (x.id === m.id ? { ...x, steps_done: before } : x)));
|
||||
toast("Couldn't save that step. Try again.");
|
||||
} else if (m.status === "todo" && steps_done.length) setStatus(m, "doing", true);
|
||||
};
|
||||
|
||||
const jump = (id: string) => {
|
||||
setOpen(id);
|
||||
requestAnimationFrame(() => document.getElementById(`move-${id}`)?.scrollIntoView({ behavior: "smooth", block: "start" }));
|
||||
};
|
||||
const p = state.plan;
|
||||
const row = (m: PlanMove, i: number) => (
|
||||
<MoveRow key={m.id} m={m} first={i === 0} open={open === m.id} toggle={() => setOpen(open === m.id ? null : m.id)} setStatus={setStatus} setSteps={setSteps} short={short} today={today} name={name} looksDone={looks.has(m.id)} />
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section className="card p-6 md:p-7 space-y-5">
|
||||
<div className="flex flex-wrap items-end gap-6">
|
||||
<div className="flex-1 min-w-60 space-y-1.5">
|
||||
<div className="text-sm text-muted">{p ? `Last audit ${dateLabel(p.created_at, { month: "short", day: "numeric" })}, ${p.provider ? `written by ${PROVIDER[p.provider] ?? p.provider}` : "built from your numbers"}` : "No audit yet"}</div>
|
||||
<div className="figure">
|
||||
{money0(yearly)}<span className="text-base font-normal tracking-normal text-muted"> a year on the table</span>
|
||||
</div>
|
||||
<div className="text-sm text-muted tabular-nums">
|
||||
{once > 0 && <>Plus {money0(once)} one-time. </>}Saved so far: {money0(saved)} a year
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={run} disabled={state.running || !state.ready} className="btn-primary disabled:opacity-60 flex items-center gap-2">
|
||||
{state.running && <LoaderCircle size={16} className="animate-spin" />}
|
||||
{state.running ? "Auditing..." : p ? "Run again" : "Run my money audit"}
|
||||
</button>
|
||||
</div>
|
||||
{state.running && <p className="text-sm text-muted" aria-live="polite">{STAGES[stage]}. This takes a minute or two; you can leave the page.</p>}
|
||||
{state.error && <p className="text-sm text-bad" role="alert">{state.error}</p>}
|
||||
{state.stale && !state.running && <p className="text-sm text-bad">{state.stale} Run it again to use your current accounts.</p>}
|
||||
{!state.ready && <p className="text-sm text-muted">The money plan needs a database update. Open Setup to apply it.</p>}
|
||||
{p?.note && !state.running && (
|
||||
<p className="flex gap-2 items-start rounded-2xl bg-amber-50 text-amber-600 px-4 py-3 text-sm" role="note">
|
||||
<TriangleAlert size={16} className="mt-0.5 shrink-0" />
|
||||
<span><span className="font-medium">{p.note}</span> Moves built on those numbers are marked low confidence and not counted.</span>
|
||||
</p>
|
||||
)}
|
||||
{p?.summary && !state.running && <p className="text-sm">{p.summary}</p>}
|
||||
</section>
|
||||
|
||||
{p && moves.length > 0 && <PayoffChart moves={[...(state.done ?? []).filter((d) => !moves.some((m) => m.id === d.id)), ...moves]} today={today} rate={payoff.rate} later={payoff.later} note={p.note ?? null} />}
|
||||
|
||||
{!p ? (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="card-title">What the audit looks at</div>
|
||||
<ul className="text-sm space-y-2">
|
||||
{LOOKS_AT.map((l) => (
|
||||
<li key={l} className="flex gap-2.5"><Check size={16} className="mt-0.5 shrink-0 text-good" />{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-sm text-muted">Moves come in the usual order: stop the bleeding, a starter emergency fund, your match, debt, a full fund, tax-advantaged saving, then smaller wins. Each one has its value, the steps and any message to send. broke never acts for you: you choose what to do.</p>
|
||||
</section>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-6 @5xl:grid-cols-[1.6fr_1fr] items-start">
|
||||
<div className="space-y-6 min-w-0">
|
||||
{first && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-baseline justify-between gap-3 px-1">
|
||||
<div className="section-label">Do this first</div>
|
||||
<div className="text-sm text-muted">Step {stepOf(first)}: {STEP_LABEL[stepOf(first)]}</div>
|
||||
</div>
|
||||
<section className="card overflow-hidden ring-2 ring-brand/30">{row(first, 0)}</section>
|
||||
</div>
|
||||
)}
|
||||
{ladder.map((x) => (
|
||||
<div key={x.k} className="space-y-3">
|
||||
<div className="flex items-baseline justify-between gap-3 px-1">
|
||||
<div className="section-label">{x.k}. {STEP_LABEL[x.k]}</div>
|
||||
<Total ms={x.ms} />
|
||||
</div>
|
||||
<section className="card overflow-hidden">{x.ms.map(row)}</section>
|
||||
</div>
|
||||
))}
|
||||
{!live.length && <p className="card p-6 text-sm text-muted">{moves.length ? "Nothing left to do. Run the audit again after your next statement." : "This audit found no moves."}</p>}
|
||||
{closed.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<button onClick={() => setShowDone(!showDone)} aria-expanded={showDone} className="w-full flex items-baseline justify-between gap-3 px-1 text-left">
|
||||
<span className="section-label flex items-center gap-1.5">
|
||||
Done <span className="tabular">{closed.filter((m) => m.status === "done").length}</span>
|
||||
<ChevronDown size={14} className={`transition-transform ${showDone ? "rotate-180" : ""}`} />
|
||||
</span>
|
||||
<span className="text-sm text-muted tabular">Saved {money0(saved)} a year</span>
|
||||
</button>
|
||||
{showDone && <section className="card overflow-hidden">{closed.map(row)}</section>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{timeline.length > 0 && (
|
||||
<div className="space-y-3 @5xl:sticky @5xl:top-6">
|
||||
<div className="section-label px-1">Timeline</div>
|
||||
<section className="card p-5 space-y-5">
|
||||
{timeline.map(({ w, ms }) => (
|
||||
<div key={w} className="space-y-1">
|
||||
<div className="text-sm font-medium">{WHEN_LABEL[w]}</div>
|
||||
<ul>
|
||||
{ms.map((m) => (
|
||||
<li key={m.id}>
|
||||
<button onClick={() => jump(m.id)} className="w-full flex items-center gap-2.5 py-1.5 text-left text-sm group">
|
||||
<span className="size-2 rounded-full shrink-0" style={{ background: SECTION_COLOR[sectionOf(m)] }} />
|
||||
<span className="flex-1 min-w-0 truncate group-hover:underline underline-offset-4">{m.title}</span>
|
||||
<span className="text-xs text-muted tabular whitespace-nowrap">{m.deadline ? short(m.deadline) : m.effort}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted px-1">General education, not financial advice. Values are estimates from your own transactions and stated assumptions; a move only counts what your spare money can cover.{moves.some((m) => m.kind === "tax") && " Tax moves use 2026 US federal rules from irs.gov. broke never files or pays anything for you."}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Total({ ms }: { ms: PlanMove[] }) {
|
||||
const { money0 } = useMoney();
|
||||
const y = value(ms, false), o = value(ms, true);
|
||||
if (!y && !o) return null;
|
||||
return <div className="text-sm text-muted tabular">{[y ? `${money0(y)} a year` : "", o ? `${money0(o)} once` : ""].filter(Boolean).join(" + ")}</div>;
|
||||
}
|
||||
|
||||
function MoveRow({ m, first, open, toggle, setStatus, setSteps, short, today, name, looksDone }: {
|
||||
m: PlanMove; first: boolean; open: boolean; toggle: () => void; setStatus: (m: PlanMove, s: Status) => void; setSteps: (m: PlanMove, s: number[]) => void;
|
||||
short: (d: string) => string; today: string; name: string; looksDone: boolean;
|
||||
}) {
|
||||
const { money0 } = useMoney();
|
||||
const { ask } = useAssistant();
|
||||
const ticked = m.steps_done ?? [];
|
||||
const done = m.status === "done";
|
||||
const live = m.status === "todo" || m.status === "doing";
|
||||
const start = () => m.status === "todo" && setStatus(m, "doing");
|
||||
const msg = m.message ? { ...m.message, body: m.message.body.replace(/\[Your name\]/g, name) } : null;
|
||||
const copy = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast("Copied");
|
||||
} catch {
|
||||
toast("Couldn't copy. Select the text instead.");
|
||||
}
|
||||
};
|
||||
const chip = "rounded-full border border-line px-2 py-0.5";
|
||||
const amount = Number(m.yearly_impact);
|
||||
return (
|
||||
<div id={`move-${m.id}`} className={`scroll-mt-6 ${first ? "" : "border-t border-line"} ${m.status === "dismissed" ? "opacity-60" : ""}`}>
|
||||
<button onClick={toggle} aria-expanded={open} className="w-full text-left px-5 py-4 flex gap-3.5 items-start row-hover">
|
||||
<CategoryIcon icon={SECTION_ICON[sectionOf(m)]} color={SECTION_COLOR[sectionOf(m)]} size={36} />
|
||||
<span className="flex-1 min-w-0 space-y-1">
|
||||
<span className="flex items-start gap-3">
|
||||
<span className={`flex-1 min-w-0 font-medium ${done ? "line-through decoration-muted" : ""}`}>{m.title}</span>
|
||||
{amount > 0 && <span className="font-semibold tabular whitespace-nowrap">{money0(amount)}<span className="text-xs font-normal text-muted">{m.once ? " once" : "/yr"}</span></span>}
|
||||
</span>
|
||||
<span className={`text-sm text-muted ${open ? "block" : "line-clamp-1"}`}>{m.why}</span>
|
||||
{m.gate && <span className={`text-sm block ${open ? "" : "line-clamp-1"}`}>{m.gate}</span>}
|
||||
<span className="flex flex-wrap items-center gap-1.5 pt-0.5 text-xs text-muted">
|
||||
<span className={chip}>{m.effort}</span>
|
||||
{m.deadline && <span className={`${chip} flex items-center gap-1`}><CalendarDays size={12} />By {short(m.deadline)}</span>}
|
||||
{ticked.length > 0 && <span className={`${chip} tabular`}>{ticked.length} of {m.steps.length} steps</span>}
|
||||
{amount === 0 && <span className={chip}>Not counted in the total</span>}
|
||||
{m.status === "doing" && <span className="rounded-full bg-brand-soft text-brand px-2 py-0.5">Started</span>}
|
||||
{done && <span className="rounded-full bg-green-50 text-good px-2 py-0.5">Done</span>}
|
||||
{m.status === "dismissed" && <span className="rounded-full bg-canvas px-2 py-0.5">Not for me</span>}
|
||||
{looksDone && live && <span className="rounded-full bg-green-50 text-good px-2 py-0.5">Looks done, confirm?</span>}
|
||||
</span>
|
||||
</span>
|
||||
<ChevronDown size={18} className={`mt-0.5 text-muted shrink-0 transition-transform ${open ? "rotate-180" : ""}`} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="px-5 pb-5 @md:pl-[70px] space-y-4">
|
||||
{looksDone && live && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-2xl bg-green-50 px-4 py-3 text-sm">
|
||||
<span className="flex-1 min-w-48">Your latest transactions suggest this is done.</span>
|
||||
<button onClick={() => setStatus(m, "done")} className="btn">Yes, mark done</button>
|
||||
</div>
|
||||
)}
|
||||
<ol className="space-y-2">
|
||||
{m.steps.map((s, i) => (
|
||||
<li key={i}>
|
||||
<label className="flex gap-3 items-start text-sm cursor-pointer">
|
||||
<input type="checkbox" className="mt-0.5 size-4 accent-[var(--brand)] shrink-0" checked={ticked.includes(i)} onChange={() => setSteps(m, ticked.includes(i) ? ticked.filter((x) => x !== i) : [...ticked, i].sort())} />
|
||||
<span className={ticked.includes(i) ? "line-through text-muted" : ""}><span className="tabular text-muted">{i + 1}.</span> {s}</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{msg && (
|
||||
<div className="rounded-2xl bg-canvas border border-line p-4 space-y-2">
|
||||
<div className="text-xs text-muted">
|
||||
{msg.channel === "call" ? "What to say on the call" : msg.channel === "sms" ? "Text" : "Email"} to {msg.to}
|
||||
{msg.subject ? `, subject: ${msg.subject}` : ""}
|
||||
</div>
|
||||
<p className="text-sm whitespace-pre-wrap">{msg.body}</p>
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
<button onClick={() => copy(msg.body)} className="btn flex items-center gap-1.5"><Copy size={14} /> Copy</button>
|
||||
{msg.channel === "email" && <a href={mailto(msg)} onClick={start} className="btn flex items-center gap-1.5"><Mail size={14} /> Open in Mail</a>}
|
||||
{msg.channel === "sms" && <a href={`sms:?&body=${enc(msg.body)}`} onClick={start} className="btn flex items-center gap-1.5"><MessageSquare size={14} /> Text</a>}
|
||||
{msg.phone && <a href={`tel:${msg.phone.replace(/[^\d+]/g, "")}`} onClick={start} className="btn flex items-center gap-1.5"><Phone size={14} /> Call {msg.phone}</a>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{m.links.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
{m.links.map((l) => {
|
||||
const b = budgetLink(l.url);
|
||||
if (b)
|
||||
return (
|
||||
<button key={l.url} className="btn" onClick={async () => { start(); toast((await setBudget(b.id, b.amount)) ? `Budget set: ${money0(b.amount)} a month` : "Couldn't set the budget. Try it on Budgets."); }}>
|
||||
{l.label}
|
||||
</button>
|
||||
);
|
||||
return <a key={l.url} href={l.url} onClick={start} {...(l.url.startsWith("/") ? {} : { target: "_blank", rel: "noopener noreferrer" })} className="text-sm font-medium underline underline-offset-4">{l.label}</a>;
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-2 border-t border-line pt-4">
|
||||
<button onClick={() => { start(); ask(helpPrompt(m)); }} className="btn !border-brand/40 text-brand">Help me do this</button>
|
||||
{done ? (
|
||||
<button onClick={() => setStatus(m, "todo")} className="btn">Move back to to do</button>
|
||||
) : (
|
||||
<button onClick={() => setStatus(m, "done")} className="btn-primary">Mark done</button>
|
||||
)}
|
||||
{live && <button onClick={() => remind(m, today)} className="btn flex items-center gap-1.5"><Bell size={14} /> Remind me</button>}
|
||||
{m.status === "dismissed" ? (
|
||||
<button onClick={() => setStatus(m, "todo")} className="text-sm text-muted hover:text-ink px-2">Bring back</button>
|
||||
) : !done && (
|
||||
<button onClick={() => setStatus(m, "dismissed")} className="text-sm text-muted hover:text-ink px-2">Not for me</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import Link from "next/link";
|
||||
import { useRef, useState } from "react";
|
||||
import { firstVisit, reduced, withoutCssTransition } from "@/components/motion";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
// Heights from the last render, so a month switch (which remounts the page) tweens old -> new.
|
||||
const lastHeights = new Map<string, number>();
|
||||
|
||||
type Bar = { key: string; label: string; v: number; income: number; href: string; active: boolean };
|
||||
|
||||
// Six months of what came in beside what went out. Bars grow in; hovering one lifts it and dims the rest; clicking opens that month.
|
||||
export function MonthBars({ bars }: { bars: Bar[] }) {
|
||||
const { money, money0 } = useMoney();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [hover, setHover] = useState<string | null>(null);
|
||||
const max = Math.max(1, ...bars.map((b) => Math.max(b.v, b.income)));
|
||||
|
||||
useGSAP(
|
||||
() => {
|
||||
const els = gsap.utils.toArray<HTMLElement>("[data-bar]");
|
||||
const target = bars.map((b) => (b.v / max) * 100);
|
||||
if (!reduced()) {
|
||||
if (firstVisit("month-bars")) {
|
||||
gsap.set(els, { transition: "none" });
|
||||
gsap.from(els, { scaleY: 0, transformOrigin: "bottom", duration: 0.6, ease: "power3.out", stagger: 0.05, onComplete: () => void gsap.set(els, { clearProps: "transform,transition" }) });
|
||||
gsap.from("[data-in]", { scaleY: 0, transformOrigin: "bottom", duration: 0.6, ease: "power3.out", stagger: 0.05, clearProps: "transform" });
|
||||
gsap.from("[data-val]", { opacity: 0, y: 6, duration: 0.3, delay: 0.35, stagger: 0.05 });
|
||||
} else {
|
||||
els.forEach((el, i) => {
|
||||
const from = lastHeights.get(bars[i].key);
|
||||
if (from !== undefined && from !== target[i]) gsap.fromTo(el, { height: `${from}%` }, { height: `${target[i]}%`, duration: 0.3, ease: "power2.out", ...withoutCssTransition(el) });
|
||||
});
|
||||
}
|
||||
}
|
||||
bars.forEach((b, i) => lastHeights.set(b.key, target[i]));
|
||||
},
|
||||
{ scope: root, dependencies: [bars.map((b) => `${b.v}/${b.income}`).join()] },
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={root} className="space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="card-title">Income vs expenses</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(--good)" }} />Income</span>
|
||||
<span className="flex items-center gap-1.5"><span className="size-2.5 rounded-sm" style={{ background: "var(--chart)" }} />Expenses</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`flex items-end h-44 ${bars.length > 8 ? "gap-1 @lg:gap-2" : "gap-3 @lg:gap-6"}`} onPointerLeave={() => setHover(null)}>
|
||||
{bars.map((b) => {
|
||||
const lit = hover ? hover === b.key : b.active;
|
||||
const dim = hover && hover !== b.key;
|
||||
return (
|
||||
<Link
|
||||
key={b.key}
|
||||
href={b.href}
|
||||
scroll={false}
|
||||
onPointerEnter={() => setHover(b.key)}
|
||||
onFocus={() => setHover(b.key)}
|
||||
aria-label={`${b.label}: ${money(b.income)} in, ${money(b.v)} out`}
|
||||
className="group relative flex-1 flex flex-col items-center gap-2 h-full justify-end rounded-xl"
|
||||
>
|
||||
<span data-val className={`text-[10px] @lg:text-[11px] tabular whitespace-nowrap transition-colors duration-150 ${b.income - b.v < 0 ? "text-bad" : lit ? "text-ink font-medium" : "text-muted"}`}>{b.v || b.income ? `${b.income - b.v < 0 ? "-" : "+"}${money0(Math.abs(b.income - b.v))}` : ""}</span>
|
||||
<div className="w-full max-w-16 flex-1 flex items-end gap-0.5">
|
||||
<div
|
||||
data-in
|
||||
className="flex-1 rounded-t-lg transition-opacity duration-150"
|
||||
style={{ height: `${(b.income / max) * 100}%`, minHeight: b.income ? 2 : 0, background: "var(--good)", opacity: dim ? 0.3 : lit ? 1 : 0.55 }}
|
||||
/>
|
||||
<div
|
||||
data-bar
|
||||
className="flex-1 rounded-t-lg transition-[background-color,opacity,transform] duration-150 ease-[cubic-bezier(.33,1,.68,1)] group-hover:-translate-y-0.5"
|
||||
style={{
|
||||
height: `${(b.v / max) * 100}%`,
|
||||
minHeight: 2,
|
||||
background: lit ? "var(--chart)" : "var(--chart-mute)",
|
||||
opacity: dim ? 0.55 : 1,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-md transition-colors duration-150 ${b.active ? "bg-ink text-on-ink" : lit ? "bg-canvas text-ink" : "text-muted"}`}>{b.label}</span>
|
||||
{hover === b.key && (b.v > 0 || b.income > 0) && (
|
||||
<span className="absolute -top-9 left-1/2 -translate-x-1/2 whitespace-nowrap bg-ink text-on-ink text-[11px] rounded-lg px-2.5 py-1 shadow-lg pointer-events-none z-10">
|
||||
{money0(b.income)} in · {money0(b.v)} out
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeftRight, ChartPie, Ellipsis, House, Landmark, MessageCircle, Monitor, Moon, Sun } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import type { ComponentType } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { BookmarkButton, SavedList } from "@/components/Bookmarks";
|
||||
|
||||
// Home is the three steps. Spending holds Budgets and Recurring as tabs, More holds the rest; every page keeps its own URL.
|
||||
type Icon = ComponentType<{ size?: number; strokeWidth?: number }>;
|
||||
const LINKS: { href: string; label: string; icon: Icon }[] = [
|
||||
{ href: "/", label: "Home", icon: House },
|
||||
{ href: "/spending", label: "Spending", icon: ChartPie },
|
||||
{ href: "/transactions", label: "Activity", icon: ArrowLeftRight },
|
||||
{ href: "/accounts", label: "Accounts", icon: Landmark },
|
||||
{ href: "/more", label: "More", icon: Ellipsis },
|
||||
];
|
||||
const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/budgets", label: "Budgets" }, { href: "/recurring", label: "Recurring" }];
|
||||
const PLAN = [{ href: "/plan", label: "Money plan" }, { href: "/optimize", label: "Optimize" }, { href: "/bonuses", label: "Bonuses" }, { href: "/cards", label: "Cards" }];
|
||||
const under = (path: string, href: string) => (href === "/" ? path === "/" : path === href || path.startsWith(href + "/"));
|
||||
const tabsOf = (path: string) => [SPENDING, PLAN].find((g) => g.some((t) => under(path, t.href)));
|
||||
const sectionOf = (path: string) => (SPENDING.some((t) => under(path, t.href)) ? "/spending" : LINKS.find((l) => under(path, l.href))?.href ?? (tabsOf(path) || under(path, "/connect-ai") || under(path, "/debt") ? "/more" : undefined));
|
||||
|
||||
const TITLES: Record<string, string> = {
|
||||
"/": "Home", "/transactions": "Activity", "/spending": "Spending", "/budgets": "Budgets", "/recurring": "Recurring", "/plan": "Money plan",
|
||||
"/optimize": "Optimize", "/bonuses": "Bonuses", "/cards": "Cards", "/accounts": "Accounts", "/accounts/add": "Add accounts", "/settings": "Settings", "/more": "More", "/debt": "Debt", "/connect-ai": "Connect your AI", "/go-live": "Use your real bank",
|
||||
};
|
||||
|
||||
export function Nav() {
|
||||
const path = usePathname();
|
||||
const assistant = useAssistant();
|
||||
const section = sectionOf(path);
|
||||
return (
|
||||
<>
|
||||
<PhoneBar section={section} />
|
||||
<nav className="hidden md:flex flex-col gap-0.5" aria-label="Main">
|
||||
{LINKS.map(({ href, label, icon: Icon }) => {
|
||||
const active = href === section;
|
||||
return (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
prefetch // whole page, data included, so a click shows it at once (production only; dev never prefetches)
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap transition-colors ${active ? "bg-canvas text-ink font-medium" : "text-ink/70 hover:text-ink hover:bg-canvas/60"}`}
|
||||
>
|
||||
<Icon size={18} strokeWidth={active ? 2 : 1.6} />
|
||||
{label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
onClick={assistant.toggle}
|
||||
aria-pressed={assistant.open}
|
||||
className={`mt-5 flex items-center gap-3 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap border transition-colors ${assistant.open ? "bg-canvas border-line font-medium" : "border-line text-ink/80 hover:text-ink hover:bg-canvas/60"}`}
|
||||
>
|
||||
<MessageCircle size={18} strokeWidth={1.6} />
|
||||
<span className="flex-1 text-left">Ask broke ai</span>
|
||||
</button>
|
||||
<Suspense><SavedList /></Suspense>
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// The tab bar on top of Spending and Plan pages. Lives in the layout, so it stays put while a tab loads.
|
||||
// cards: the Cards tab applies in the user's country (countries.ts).
|
||||
export function SectionTabs({ cards = true }: { cards?: boolean }) {
|
||||
const path = usePathname();
|
||||
const tabs = tabsOf(path)?.filter((t) => cards || t.href !== "/cards");
|
||||
if (!tabs) return null;
|
||||
return (
|
||||
<nav data-tabs aria-label="Related pages" className="pill-tabs mb-6 max-w-full overflow-x-auto">
|
||||
{tabs.map((t) => (
|
||||
<Link key={t.href} href={t.href} prefetch aria-current={under(path, t.href) ? "page" : undefined} className={`pill-tab whitespace-nowrap ${under(path, t.href) ? "pill-tab-active" : ""}`}>
|
||||
{t.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
function PhoneBar({ section }: { section?: string }) {
|
||||
const assistant = useAssistant();
|
||||
const cell = "flex flex-col items-center gap-0.5 text-[11px] py-1.5 rounded-xl";
|
||||
return (
|
||||
<nav aria-label="Main" className="fixed bottom-0 inset-x-0 z-30 md:hidden bg-surface border-t border-line grid grid-cols-6 px-1 pt-1 pb-[max(6px,env(safe-area-inset-bottom))]">
|
||||
{LINKS.map(({ href, label, icon: Icon }) => (
|
||||
<Link key={href} href={href} prefetch aria-current={href === section ? "page" : undefined} className={`${cell} ${href === section ? "text-ink font-medium" : "text-muted"}`}>
|
||||
<Icon size={21} strokeWidth={href === section ? 2 : 1.6} />
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
<button onClick={assistant.toggle} className={`${cell} text-brand ${assistant.open ? "font-medium" : ""}`}>
|
||||
<MessageCircle size={21} strokeWidth={1.8} />
|
||||
Ask AI
|
||||
</button>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
// Tells the server the browser's time zone, so "today" and "this month" match the user's clock. Refreshes once when it changes.
|
||||
export function TimeZoneCookie() {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
if (!tz || document.cookie.split("; ").includes(`tz=${tz}`)) return;
|
||||
document.cookie = `tz=${tz}; path=/; max-age=31536000; samesite=lax`;
|
||||
router.refresh();
|
||||
}, [router]);
|
||||
return null;
|
||||
}
|
||||
|
||||
// today (YYYY-MM-DD) comes from the server (user's time zone) so Home's "October 2026" renders the same on server and client.
|
||||
export function PageTitle({ today }: { today: string }) {
|
||||
const path = usePathname();
|
||||
const key = "/" + (path.split("/")[1] ?? "");
|
||||
const title = TITLES[path] ?? TITLES[key] ?? "";
|
||||
const month = new Date(today + "T00:00:00Z").toLocaleDateString("en-US", { month: "long", timeZone: "UTC" });
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<h1 className="text-2xl font-semibold tracking-[-0.02em]">{key === "/" ? <>{month} <span className="text-muted font-normal">{today.slice(0, 4)}</span></> : title}</h1>
|
||||
<Suspense><BookmarkButton title={key === "/" ? "Home" : title} /></Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const THEMES = [["system", "System", Monitor], ["light", "Light", Sun], ["dark", "Dark", Moon]] as const;
|
||||
|
||||
// System / Light / Dark. Saved in localStorage; layout.tsx applies it before paint.
|
||||
export function ThemeToggle() {
|
||||
const [theme, setTheme] = useState("system");
|
||||
useEffect(() => setTheme(document.documentElement.dataset.theme ?? "system"), []);
|
||||
function pick(t: string) {
|
||||
setTheme(t);
|
||||
if (t === "system") delete document.documentElement.dataset.theme;
|
||||
else document.documentElement.dataset.theme = t;
|
||||
try {
|
||||
if (t === "system") localStorage.removeItem("theme");
|
||||
else localStorage.setItem("theme", t);
|
||||
} catch {}
|
||||
}
|
||||
return (
|
||||
<div role="radiogroup" aria-label="Theme" className="inline-flex gap-0.5 rounded-full border border-line p-0.5">
|
||||
{THEMES.map(([t, label, Icon]) => (
|
||||
<button
|
||||
key={t}
|
||||
role="radio"
|
||||
aria-checked={theme === t}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
onClick={() => pick(t)}
|
||||
className={`p-1.5 rounded-full ${theme === t ? "bg-canvas text-ink" : "text-muted hover:text-ink"}`}
|
||||
>
|
||||
<Icon size={14} strokeWidth={1.8} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Link from "next/link";
|
||||
import { NextMoveCard, type NextItem } from "@/components/NextMoveCard";
|
||||
import { money0 } from "@/lib/format";
|
||||
import { deterministicMoves, stepOf, whyLine, type Kind } from "@/lib/plan";
|
||||
import { myPlan, myPlanFacts } from "@/lib/plan-facts";
|
||||
|
||||
// The one move to make now: the first open move by the plan's ladder (the order /plan shows). With no plan yet,
|
||||
// the code-built moves, so a linked user always has one. Streams in: no plan means the full facts load first.
|
||||
export async function NextMove() {
|
||||
const state = await myPlan();
|
||||
const items: NextItem[] = state.plan && !state.stale
|
||||
? (state.moves as (Omit<NextItem, "line" | "step"> & { why: string; kind: Kind; step: number | null })[])
|
||||
.filter((m) => m.status === "todo" || m.status === "doing")
|
||||
.map((m) => ({ ...m, step: stepOf(m), line: whyLine(m.title, m.why) }))
|
||||
.sort((a, b) => a.step - b.step)
|
||||
: deterministicMoves(await myPlanFacts(), money0).map((m) => ({
|
||||
id: null, ref: m.ref, title: m.title, line: whyLine(m.title, m.why), gate: m.gate, steps: m.steps, steps_done: [], status: "todo", step: m.step,
|
||||
}));
|
||||
if (!items.length)
|
||||
return (
|
||||
<Link href="/plan" className="card-link p-6 block space-y-1">
|
||||
<span className="block section-label">Your next move</span>
|
||||
<span className="block text-sm text-muted">Nothing left in your plan. Run the audit again after your next statement.</span>
|
||||
</Link>
|
||||
);
|
||||
return <NextMoveCard items={items} looks={state.looksWhy} />;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { STEP_LABEL, type Status, type Step } from "@/lib/plan";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
// id null: a code-built move not saved yet (no plan).
|
||||
export type NextItem = { id: string | null; ref: string | null; title: string; line: string; gate: string | null; steps: string[]; steps_done: number[] | null; status: Status; step: number };
|
||||
type Patch = Partial<Pick<NextItem, "status" | "steps_done">> & { done_at?: string | null };
|
||||
|
||||
export function NextMoveCard({ items, looks }: { items: NextItem[]; looks: Record<string, string> }) {
|
||||
const { ask } = useAssistant();
|
||||
const [list, setList] = useState(items);
|
||||
const [skip, setSkip] = useState(0);
|
||||
const live = list.filter((m) => m.status === "todo" || m.status === "doing");
|
||||
const m = live[skip % Math.max(1, live.length)];
|
||||
|
||||
// A code-built move has no row yet: the first tick or Done saves the code-built plan (no AI), then updates its row.
|
||||
const idOf = async (x: NextItem) => {
|
||||
if (x.id) return x.id;
|
||||
const r = await fetch("/api/plan", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: true }) }).catch(() => null);
|
||||
if (!r?.ok) return null;
|
||||
const ids = new Map(((await r.json()) as { moves: { id: string; ref: string | null }[] }).moves.map((s) => [s.ref, s.id]));
|
||||
setList((l) => l.map((y) => ({ ...y, id: y.id ?? ids.get(y.ref) ?? null })));
|
||||
return ids.get(x.ref) ?? null;
|
||||
};
|
||||
// The same saving as /plan: the browser may update status, done_at and steps_done (0018, 0021).
|
||||
const save = async (x: NextItem, patch: Patch) => {
|
||||
setList((l) => l.map((y) => (y.ref === x.ref ? { ...y, ...patch } : y)));
|
||||
const id = await idOf(x);
|
||||
const { error } = id ? await createClient().from("plan_moves").update(patch).eq("id", id) : { error: true };
|
||||
if (!error) return true;
|
||||
setList((l) => l.map((y) => (y.ref === x.ref ? { ...y, status: x.status, steps_done: x.steps_done } : y)));
|
||||
toast("Couldn't save that. Try again.");
|
||||
return false;
|
||||
};
|
||||
const done = async (x: NextItem) => {
|
||||
if (await save(x, { status: "done", done_at: new Date().toISOString() })) toast(`Done: ${x.title}`, () => void save({ ...x, status: "done" }, { status: x.status, done_at: null }));
|
||||
};
|
||||
|
||||
if (!m)
|
||||
return (
|
||||
<section className="card p-6 space-y-1">
|
||||
<span className="block section-label">Your next move</span>
|
||||
<span className="block text-sm text-muted">All done for now. Ask below if you want something new to work on.</span>
|
||||
</section>
|
||||
);
|
||||
const ticked = m.steps_done ?? [];
|
||||
const note = m.id ? looks[m.id] : undefined;
|
||||
const tick = (i: number) => {
|
||||
const steps_done = ticked.includes(i) ? ticked.filter((x) => x !== i) : [...ticked, i].sort();
|
||||
save(m, m.status === "todo" && steps_done.length ? { steps_done, status: "doing" } : { steps_done });
|
||||
};
|
||||
return (
|
||||
<section className="card p-6 space-y-4" aria-labelledby="next-move-title">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<div className="section-label">Your next move</div>
|
||||
<div className="text-xs text-muted">Step {m.step}: {STEP_LABEL[m.step as Step]}</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h2 id="next-move-title" className="card-title">{m.title}</h2>
|
||||
<p className="text-sm text-muted">{m.line}</p>
|
||||
{m.gate && <p className="text-sm text-muted">{m.gate}</p>}
|
||||
</div>
|
||||
{note && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-2xl bg-green-50 px-4 py-3 text-sm">
|
||||
<span className="flex-1 min-w-48">Looks done. {note}</span>
|
||||
<button onClick={() => done(m)} className="btn">Yes, mark done</button>
|
||||
</div>
|
||||
)}
|
||||
<ol className="space-y-2">
|
||||
{m.steps.map((s, i) => (
|
||||
<li key={i}>
|
||||
<label className="flex gap-3 items-start text-sm cursor-pointer">
|
||||
<input type="checkbox" className="mt-0.5 size-4 accent-[var(--brand)] shrink-0" checked={ticked.includes(i)} onChange={() => tick(i)} />
|
||||
<span className={ticked.includes(i) ? "line-through text-muted" : ""}><span className="tabular text-muted">{i + 1}.</span> {s}</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
|
||||
<button onClick={() => done(m)} className="btn-primary">Done</button>
|
||||
{live.length > 1 && <button onClick={() => setSkip(skip + 1)} className="btn">Show me another</button>}
|
||||
<button onClick={() => ask(`Help me with this: ${m.title}. Use my real numbers and tell me what to do first.`)} className="btn inline-flex items-center gap-1.5 ml-auto"><Sparkles size={15} /> Help me with this</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
"use client";
|
||||
|
||||
import { Check } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Welcome } from "@/components/CountryPicker";
|
||||
import { GoalPicker, type DraftPlan } from "@/components/GoalPicker";
|
||||
import { FeedConnect } from "@/components/FeedConnect";
|
||||
import { Logo } from "@/components/Logo";
|
||||
import { linkedText, useAkahu, useLinkBank } from "@/components/PlaidButtons";
|
||||
import type { Profile } from "@/components/ProfileForm";
|
||||
import { validGoalPlan, type GoalPlan } from "@/lib/advice";
|
||||
import type { Fact } from "@/lib/first-fact";
|
||||
import { plural } from "@/lib/format";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import type { AddChoices } from "@/lib/providers";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
// The first run, about a minute: country, bank, goals, then one fact from their data. Pay comes from their deposits and
|
||||
// debts from linked accounts; Home asks about pay only if no paycheck shows up.
|
||||
// The step is saved in profile.onboarding before it shows, so leaving halfway resumes there (the app layout sends
|
||||
// them back to /welcome). Every step can be skipped. "done" (or no value, for accounts made before this) = finished.
|
||||
const STEPS = ["country", "bank", "goal", "result"] as const;
|
||||
export type Step = (typeof STEPS)[number];
|
||||
|
||||
type Info = {
|
||||
status: "none" | "importing" | "thin" | "ready";
|
||||
accounts: number;
|
||||
fact?: Fact | null;
|
||||
};
|
||||
const load = (): Promise<Info | null> => fetch("/api/onboarding").then((r) => (r.ok ? r.json() : null)).catch(() => null);
|
||||
|
||||
function Head({ title, body }: { title: string; body?: string }) {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-[-0.02em]">{title}</h1>
|
||||
{body && <p className="text-sm text-muted mt-1">{body}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const Skip = ({ onClick, label = "Skip for now" }: { onClick: () => void; label?: string }) => (
|
||||
<button type="button" onClick={onClick} className="text-sm text-muted underline underline-offset-4 hover:text-ink">{label}</button>
|
||||
);
|
||||
|
||||
function BankStep({ choices, country, info, next, reload }: { choices: AddChoices; country: string; info: Info | null; next: () => void; reload: () => void }) {
|
||||
const link = useLinkBank(undefined, { quiet: true });
|
||||
const akahu = useAkahu();
|
||||
const busy = link.busy || akahu.busy;
|
||||
// A link just finished: count what it brought in.
|
||||
const was = useRef(false);
|
||||
useEffect(() => {
|
||||
if (was.current && !busy) reload();
|
||||
was.current = busy;
|
||||
}, [busy]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [secs, setSecs] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!busy) return;
|
||||
setSecs(0);
|
||||
const t = setInterval(() => setSecs((s) => s + 1), 1000);
|
||||
return () => clearInterval(t);
|
||||
}, [busy]);
|
||||
const linked = info?.accounts ?? 0;
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Head title="Link your bank" body="broke reads your transactions through a secure link to find where your money goes. It can't move money." />
|
||||
{busy ? (
|
||||
<div className="space-y-3" role="status" aria-live="polite">
|
||||
<div className="flex justify-between text-sm"><span className="font-medium">Importing transactions...</span><span className="text-muted tabular">{secs} s</span></div>
|
||||
<div className="h-1.5 rounded-full bg-line overflow-hidden"><div className="h-full w-1/3 rounded-full bg-brand animate-[slide_1.2s_ease-in-out_infinite]" /></div>
|
||||
<p className="text-sm text-muted">This can take up to 30 seconds. Keep this page open.</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{(link.result || linked > 0) && (
|
||||
<p className="flex items-center gap-2 text-sm" role="status">
|
||||
<Check size={16} className="text-brand shrink-0" />
|
||||
{link.result ? linkedText(link.result) : `${plural(linked, "account")} linked`}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-col gap-3">
|
||||
{choices.feeds.map((f) => <FeedConnect key={f} id={f} country={country} />)}
|
||||
{choices.bank === "plaid" && <button onClick={() => link.start()} className={linked ? "btn" : "btn-primary"}>{linked ? "Link another bank" : "Link a bank or card"}</button>}
|
||||
{choices.bank === "akahu" && <button onClick={akahu.start} className={linked ? "btn" : "btn-primary"}>Link your NZ banks</button>}
|
||||
{choices.sandbox && <button onClick={() => link.start(true)} className="btn">Use a test bank</button>}
|
||||
{linked > 0 && <button onClick={next} className="btn-primary">Continue</button>}
|
||||
</div>
|
||||
{(link.error || akahu.error) && <p className="text-sm text-bad">{link.error || akahu.error}</p>}
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-wrap justify-between gap-3">
|
||||
<Link href="/accounts/add" className="text-sm text-muted underline underline-offset-4 hover:text-ink">Add accounts another way</Link>
|
||||
{!linked && !busy && <Skip onClick={next} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GoalStep({ profile, save }: { profile: Profile; save: (patch: Partial<Profile>) => void }) {
|
||||
const [goals, setGoals] = useState(profile.goals ?? []);
|
||||
const [plans, setPlans] = useState<DraftPlan[]>(profile.goalPlans ?? []);
|
||||
const done = () => save({ goals, goalPlans: plans.filter((g) => goals.includes(g.goal)).map(validGoalPlan).filter((g): g is GoalPlan => !!g) });
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Head title="What are you working toward?" body="Pick as many as you like, or type your own. broke puts tips for your first pick first." />
|
||||
<GoalPicker goals={goals} plans={plans} onChange={(g, p) => { setGoals(g); setPlans(p); }} showMain />
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Skip onClick={() => save({})} />
|
||||
<button disabled={!goals.length} onClick={done} className="btn-primary">Continue</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Waits while a connection is still sending rows (re-syncing every few seconds, up to 90 s): never a $0 fact.
|
||||
function ResultStep({ finish, back }: { finish: (href: string) => void; back: () => void }) {
|
||||
const [info, setInfo] = useState<Info | null>(null);
|
||||
const [waited, setWaited] = useState(0);
|
||||
const [going, setGoing] = useState("");
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
(async () => {
|
||||
const t0 = Date.now();
|
||||
for (;;) {
|
||||
const i = await load();
|
||||
if (!live) return;
|
||||
setInfo(i);
|
||||
setWaited(Math.round((Date.now() - t0) / 1000));
|
||||
if (!i || i.status !== "importing" || Date.now() - t0 > 90_000) return;
|
||||
await fetch("/api/plaid/sync", { method: "POST" }).catch(() => {});
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
if (!live) return;
|
||||
}
|
||||
})();
|
||||
return () => void (live = false);
|
||||
}, []);
|
||||
const go = (href: string) => (setGoing(href), finish(href));
|
||||
const dash = <button onClick={() => go("/")} disabled={!!going} className="btn">{going === "/" ? "Opening..." : "Go to your dashboard"}</button>;
|
||||
|
||||
if (!info || (info.status === "importing" && waited <= 90))
|
||||
return (
|
||||
<div className="space-y-5" role="status" aria-live="polite">
|
||||
<Head title="Reading your transactions" body="broke is looking for one useful fact in your money. If your bank is still sending transactions, this can take a minute." />
|
||||
<div className="h-1.5 rounded-full bg-line overflow-hidden"><div className="h-full w-1/3 rounded-full bg-brand animate-[slide_1.2s_ease-in-out_infinite]" /></div>
|
||||
</div>
|
||||
);
|
||||
if (info.status === "none")
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Head title="Link a bank to see your first result" body="broke finds one useful fact in your own transactions, like what your subscriptions cost a year." />
|
||||
<div className="flex flex-wrap gap-3"><button onClick={back} className="btn-primary">Link a bank</button>{dash}</div>
|
||||
</div>
|
||||
);
|
||||
if (info.status !== "ready" || !info.fact)
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Head
|
||||
title={info.status === "importing" ? "Your bank is still sending transactions" : "Not enough history yet"}
|
||||
body={info.status === "importing" ? "Your dashboard fills in as they arrive." : "broke needs at least 2 weeks of transactions to find a pattern. Your dashboard fills in as they arrive."}
|
||||
/>
|
||||
{dash}
|
||||
</div>
|
||||
);
|
||||
const f = info.fact;
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="section-label">Your first result</div>
|
||||
<p className="text-2xl font-semibold tracking-[-0.02em] leading-snug">{f.headline}.</p>
|
||||
<p className="text-sm text-muted">{f.detail}</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button onClick={() => go(f.cta.href)} disabled={!!going} className="btn-primary">{going === f.cta.href ? "Opening..." : f.cta.label}</button>
|
||||
{dash}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Onboarding({ profile: initial, start, choices }: { profile: Profile; start: Step; choices: AddChoices }) {
|
||||
const router = useRouter();
|
||||
const [profile, setProfile] = useState<Profile>(initial);
|
||||
const [step, setStep] = useState<Step>(STEPS.includes(start) ? start : "result");
|
||||
const [info, setInfo] = useState<Info | null>(null);
|
||||
// Writes run one after another so a later step never lands before an earlier one.
|
||||
const queue = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const write = (p: Profile) => (queue.current = queue.current.then(() => updateMeta(createClient(), { data: { profile: p } })));
|
||||
|
||||
useEffect(() => {
|
||||
if (step !== "country" && step !== "result") load().then(setInfo);
|
||||
}, [step === "country"]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Saves the answers and the next step together, and shows the next step at once.
|
||||
function save(patch: Partial<Profile> = {}) {
|
||||
const next = STEPS[STEPS.indexOf(step) + 1];
|
||||
const p = { ...profile, ...patch, onboarding: next };
|
||||
setProfile(p);
|
||||
setStep(next);
|
||||
write(p);
|
||||
}
|
||||
async function finish(href: string) {
|
||||
await write({ ...profile, onboarding: "done" });
|
||||
router.push(href);
|
||||
}
|
||||
|
||||
const i = STEPS.indexOf(step);
|
||||
return (
|
||||
<div className="w-full max-w-lg space-y-5">
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<Logo />
|
||||
{step !== "result" && <span className="text-xs text-muted tabular">Step {i + 1} of {STEPS.length - 1}</span>}
|
||||
</div>
|
||||
{step !== "result" && (
|
||||
<div className="h-1 bg-line rounded-full overflow-hidden mx-1"><div className="h-full bg-ink rounded-full transition-all" style={{ width: `${((i + 1) / (STEPS.length - 1)) * 100}%` }} /></div>
|
||||
)}
|
||||
<div className="card p-6 md:p-8">
|
||||
{step === "country" && <Welcome profile={profile} onDone={(p) => { setProfile(p); setStep("bank"); router.refresh(); }} />}
|
||||
{step === "bank" && <BankStep choices={choices} country={countryOf(profile.country).code} info={info} next={() => save()} reload={() => load().then(setInfo)} />}
|
||||
{step === "goal" && <GoalStep profile={profile} save={save} />}
|
||||
{step === "result" && <ResultStep finish={finish} back={() => { const p = { ...profile, onboarding: "bank" }; setProfile(p); setStep("bank"); write(p); }} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { RangePicker } from "@/components/RangePicker";
|
||||
|
||||
// "Custom dates" on a page. The URL keeps the range, so back and refresh work.
|
||||
export function PageDates({ path, from, to, today }: { path: string; from: string; to: string; today: string }) {
|
||||
const router = useRouter();
|
||||
const on = !!(from || to);
|
||||
const [open, setOpen] = useState(on);
|
||||
const go = (a: string, b: string) => router.push(`${path}?${new URLSearchParams(Object.entries({ from: a, to: b }).filter(([, v]) => v))}`, { scroll: false });
|
||||
if (!open) return <div className="text-center"><button onClick={() => setOpen(true)} className="text-sm text-muted underline underline-offset-4 hover:text-ink">Custom dates</button></div>;
|
||||
return (
|
||||
<section className="card p-4 flex justify-center">
|
||||
<RangePicker from={from} to={to} today={today} onApply={go} onClear={() => { setOpen(false); if (on) router.push(path, { scroll: false }); }} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import type { Profile } from "@/components/ProfileForm";
|
||||
import { FREQ_LABEL } from "@/lib/format";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
const PAY_EVERY = ["WEEKLY", "BIWEEKLY", "SEMI_MONTHLY", "MONTHLY"].map((v) => ({ value: v, label: FREQ_LABEL[v] }));
|
||||
|
||||
// Asked only when no paycheck shows up in their transactions. Saved as profile.pay, which the plan and Home read.
|
||||
export function PayQuestion({ profile }: { profile: Profile }) {
|
||||
const router = useRouter();
|
||||
const { parseAmount, symbol } = useMoney();
|
||||
const [amount, setAmount] = useState("");
|
||||
const [every, setEvery] = useState("");
|
||||
const [state, setState] = useState<"idle" | "saving" | "failed">("idle");
|
||||
const n = Math.abs(parseAmount(amount));
|
||||
async function save() {
|
||||
setState("saving");
|
||||
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, pay: { amount: n, every } } } });
|
||||
setState(error ? "failed" : "idle");
|
||||
if (!error) router.refresh();
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3 max-w-md">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-xs text-muted">Each payday, after tax</span>
|
||||
<input inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder={symbol} className="select tabular" />
|
||||
</label>
|
||||
<div className="space-y-1.5">
|
||||
<span className="text-xs text-muted block">How often</span>
|
||||
<Dropdown label="How often" value={every} options={PAY_EVERY} onChange={setEvery} placeholder="Choose one" />
|
||||
</div>
|
||||
</div>
|
||||
<button disabled={!(n > 0) || !every || state === "saving"} onClick={save} className="btn-primary">{state === "saving" ? "Saving..." : "Save my pay"}</button>
|
||||
{state === "failed" && <p className="text-sm text-bad">Couldn't save that. Try again.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { firstVisit, reduced } from "@/components/motion";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { at, DEFAULT_RETURN, flows, HORIZONS, project, RETURNS, SAVINGS_RATE, type Later, type PMove, type Point } from "@/lib/projection";
|
||||
|
||||
// The breakdown's three kinds, in a fixed order (validated: adjacent pairs pass CVD and normal-vision checks in light and dark).
|
||||
// Saving green and the tax blue are the plan's own section hues; kept is the cards hue.
|
||||
const KINDS = [
|
||||
{ key: "invested", label: "Invested and growth", color: "#3f8a52", of: (p: Point) => p.put + p.growth },
|
||||
{ key: "tax", label: "Tax saved", color: "#6f8cf2", of: (p: Point) => p.tax },
|
||||
{ key: "kept", label: "Kept", color: "#a24f7c", of: (p: Point) => p.kept },
|
||||
] as const;
|
||||
const YEARS_LABEL = (y: number) => (y === 1 ? "1 year" : `${y} years`);
|
||||
const pctLabel = (r: number) => `${Math.round(r * 100)}%`;
|
||||
|
||||
// Clean axis steps: 1, 2, 2.5 or 5 times a power of ten.
|
||||
function niceStep(max: number, n = 4) {
|
||||
const raw = Math.max(1, max / n), p = Math.pow(10, Math.floor(Math.log10(raw)));
|
||||
return ([1, 2, 2.5, 5, 10].find((s) => s * p >= raw) ?? 10) * p;
|
||||
}
|
||||
const sum = (p: Point, q: Point): Point => ({ kept: p.kept + q.kept, tax: p.tax + q.tax, put: p.put + q.put, growth: p.growth + q.growth, total: p.total + q.total });
|
||||
|
||||
export function PayoffChart({ moves, today, rate, later, note }: { moves: PMove[]; today: string; rate: number | null; later: Later | null; note: string | null }) {
|
||||
const { money0, dateLabel, locale, currency } = useMoney();
|
||||
const [years, setYears] = useState<number>(5);
|
||||
const [growth, setGrowth] = useState<number>(DEFAULT_RETURN);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const svg = useRef<SVGSVGElement>(null);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
// The viewBox follows the real width, so text stays 12px and the plot only stretches sideways.
|
||||
const [W, setW] = useState(560);
|
||||
useEffect(() => {
|
||||
const el = box.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver(([e]) => setW(Math.max(280, Math.round(e.contentRect.width) - 8)));
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const fs = useMemo(() => flows(moves, today, rate, later), [moves, today, rate, later]);
|
||||
const months = years * 12;
|
||||
const { counted, possible, progress } = useMemo(() => {
|
||||
const opts = { months: 360, growth };
|
||||
return {
|
||||
counted: project(fs.filter((f) => f.layer === "counted"), opts),
|
||||
possible: project(fs.filter((f) => f.layer === "later"), opts),
|
||||
progress: at(project(fs.filter((f) => f.layer === "counted" && f.done), { months: 0, growth }), 0),
|
||||
};
|
||||
}, [fs, growth]);
|
||||
const end = at(counted, months), endLater = at(possible, months);
|
||||
const hasLater = possible.some((p) => p.total >= 1);
|
||||
const hasInvested = fs.some((f) => f.bucket === "invested" || f.bucket === "savings");
|
||||
const doneMoves = moves.filter((m) => m.status === "done" && Number(m.yearly_impact) > 0);
|
||||
const since = doneMoves.map((m) => m.done_at).filter(Boolean).sort()[0] ?? null;
|
||||
|
||||
// Chart geometry, the same frame as SpendChart: values on the right, months along the bottom.
|
||||
const H = 170, R = 56;
|
||||
const top = Math.max(1, ...counted.slice(0, months + 1).map((p, i) => p.total + possible[i].total));
|
||||
const step = niceStep(top), max = Math.ceil(top / step) * step;
|
||||
const x = (i: number) => (i / months) * (W - R);
|
||||
const y = (v: number) => H - (v / max) * H;
|
||||
const pts = (vals: number[]) => vals.map((v, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
|
||||
const cTop = counted.slice(0, months + 1).map((p) => p.total);
|
||||
const lTop = cTop.map((v, i) => v + possible[i].total);
|
||||
const band = `${pts(lTop)} L${[...cTop].reverse().map((v, k) => `${x(months - k).toFixed(1)},${y(v).toFixed(1)}`).join(" L")} Z`;
|
||||
const grid = Array.from({ length: Math.round(max / step) }, (_, k) => (k + 1) * step);
|
||||
const tickYears = years === 1 ? [0, 3, 6, 9, 12] : years === 5 ? [0, 12, 24, 36, 48, 60] : years === 10 ? [0, 24, 48, 72, 96, 120] : [0, 60, 120, 180, 240, 300, 360];
|
||||
const tickLabel = (m: number) => (m === 0 ? (W < 420 ? "Now" : "Today") : years === 1 ? (m === 12 ? "1 yr" : `${m} mo`) : `${m / 12} yr${m === 12 ? "" : "s"}`);
|
||||
const compact = (n: number) => new Intl.NumberFormat(locale, { style: "currency", currency, notation: "compact", maximumFractionDigits: 1 }).format(n);
|
||||
const monthOf = (m: number) => dateLabel(new Date(Date.parse(today) + m * 30.44 * 864e5), { month: "short", year: "numeric" });
|
||||
|
||||
useGSAP(
|
||||
() => {
|
||||
if (reduced() || !firstVisit(`payoff-${years}`)) return;
|
||||
const path = svg.current!.querySelector<SVGPathElement>("[data-line]");
|
||||
if (!path) return;
|
||||
const len = path.getTotalLength();
|
||||
gsap.fromTo(path, { strokeDasharray: len, strokeDashoffset: len }, { strokeDashoffset: 0, duration: 1.1, ease: "power2.inOut", clearProps: "strokeDasharray,strokeDashoffset" });
|
||||
gsap.from("[data-band]", { opacity: 0, duration: 0.6, delay: 0.5, ease: "power2.out" });
|
||||
},
|
||||
{ scope: svg, dependencies: [years] },
|
||||
);
|
||||
|
||||
function onMove(e: React.PointerEvent<SVGSVGElement>) {
|
||||
const box = svg.current!.getBoundingClientRect();
|
||||
const px = ((e.clientX - box.left) / box.width) * (W + 8) - 4;
|
||||
setHover(Math.max(0, Math.min(months, Math.round((px / (W - R)) * months))));
|
||||
}
|
||||
function onKey(e: React.KeyboardEvent) {
|
||||
const d = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
|
||||
if (!d) return;
|
||||
e.preventDefault();
|
||||
setHover((h) => Math.max(0, Math.min(months, (h ?? (d > 0 ? -1 : months + 1)) + d * (years === 1 ? 1 : 12))));
|
||||
}
|
||||
const h = hover;
|
||||
// The tooltip sits beside the crosshair when it fits, else is clamped inside the chart: it never leaves the card.
|
||||
const tip = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (h === null || !tip.current) return;
|
||||
const tw = tip.current.offsetWidth, cx = x(h) + 4, room = W + 8;
|
||||
const left = cx + 12 + tw <= room ? cx + 12 : cx - 12 - tw >= 0 ? cx - 12 - tw : Math.max(0, Math.min(room - tw, cx - tw / 2));
|
||||
tip.current.style.left = `${left}px`;
|
||||
});
|
||||
const whole = sum(end, endLater);
|
||||
const chip = (active: boolean) => `pill-tab !py-1 !px-3 ${active ? "pill-tab-active" : ""}`;
|
||||
|
||||
return (
|
||||
<section className="card p-6 md:p-7 space-y-5" aria-labelledby="payoff-title">
|
||||
<div className="space-y-4">
|
||||
<div id="payoff-title" className="card-title">What following your plan could be worth</div>
|
||||
<div role="group" aria-label="How far ahead" className="pill-tabs">
|
||||
{HORIZONS.map((yr) => (
|
||||
<button key={yr} type="button" onClick={() => { setYears(yr); setHover(null); }} aria-pressed={yr === years} className={chip(yr === years)}>{YEARS_LABEL(yr)}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-end gap-x-8 gap-y-4">
|
||||
<div className="flex-1 min-w-56 space-y-1">
|
||||
<div className="figure">{money0(end.total)}<span className="text-base font-normal tracking-normal text-muted"> in {YEARS_LABEL(years)}</span></div>
|
||||
<div className="text-sm text-muted tabular-nums">
|
||||
{growth > 0 && end.growth >= 1 ? <>Of which {money0(end.growth)} is growth. </> : null}
|
||||
{hasLater && endLater.total >= 1 && <>Up to {money0(endLater.total)} more is possible later.</>}
|
||||
{end.total < 1 && !hasLater && <>Nothing in your plan adds money yet.</>}
|
||||
</div>
|
||||
</div>
|
||||
{progress.total >= 1 && since && (
|
||||
<div className="space-y-0.5 min-w-44">
|
||||
<div className="section-label">Your progress so far</div>
|
||||
<div className="text-xl font-semibold tracking-[-0.02em]">{money0(progress.total)}</div>
|
||||
<div className="text-xs text-muted">Kept and invested from {doneMoves.length} done move{doneMoves.length === 1 ? "" : "s"} since {dateLabel(since, { month: "short", day: "numeric" })}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div ref={box} className="relative">
|
||||
<svg
|
||||
ref={svg}
|
||||
viewBox={`-4 -8 ${W + 8} ${H + 38}`}
|
||||
className="w-full touch-none outline-none"
|
||||
role="img"
|
||||
tabIndex={0}
|
||||
aria-label={`Following your plan reaches ${money0(end.total)} in ${YEARS_LABEL(years)}${hasLater ? `, and up to ${money0(endLater.total)} more is possible later` : ""}. If nothing changes it stays at ${money0(0)}. Use the left and right arrow keys to read each point.`}
|
||||
onPointerMove={onMove}
|
||||
onPointerLeave={() => setHover(null)}
|
||||
onKeyDown={onKey}
|
||||
onBlur={() => setHover(null)}
|
||||
>
|
||||
{grid.map((t) => (
|
||||
<g key={t}>
|
||||
<line x1={0} x2={W - R} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeWidth="1" />
|
||||
<text x={W - R + 8} y={y(t) + 4} fontSize="12" fill="var(--muted)" className="tabular">{compact(t)}</text>
|
||||
</g>
|
||||
))}
|
||||
{hasLater && <path data-band d={band} fill="var(--chart-soft)" />}
|
||||
{hasLater && <path data-band d={pts(lTop)} fill="none" stroke="var(--chart-mute)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />}
|
||||
<line x1={0} x2={W - R} y1={H} y2={H} stroke="var(--muted)" strokeWidth="2" strokeLinecap="round" />
|
||||
<path data-line d={pts(cTop)} fill="none" stroke="var(--chart)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
|
||||
<circle cx={x(months)} cy={y(cTop[months])} r="5" fill="var(--chart)" stroke="var(--surface)" strokeWidth="2" />
|
||||
{h !== null && (
|
||||
<g pointerEvents="none">
|
||||
<line x1={x(h)} x2={x(h)} y1={0} y2={H} stroke="var(--ink)" strokeOpacity="0.25" />
|
||||
{hasLater && <circle cx={x(h)} cy={y(lTop[h])} r="4" fill="var(--chart-mute)" stroke="var(--surface)" strokeWidth="2" />}
|
||||
<circle cx={x(h)} cy={y(cTop[h])} r="4" fill="var(--chart)" stroke="var(--surface)" strokeWidth="2" />
|
||||
</g>
|
||||
)}
|
||||
{tickYears.map((m, k) => (
|
||||
<text key={m} x={x(m)} y={H + 22} fontSize="12" fill="var(--muted)" textAnchor={k === 0 ? "start" : k === tickYears.length - 1 ? "end" : "middle"}>{tickLabel(m)}</text>
|
||||
))}
|
||||
</svg>
|
||||
|
||||
{h !== null && (
|
||||
<div
|
||||
ref={tip}
|
||||
className="absolute -top-2 pointer-events-none bg-ink text-on-ink text-xs rounded-xl px-3 py-2 shadow-lg whitespace-nowrap"
|
||||
>
|
||||
<div className="text-on-ink/60 mb-0.5">{h === 0 ? "Today" : monthOf(h)}</div>
|
||||
<div className="flex justify-between gap-4"><span className="flex items-center gap-1.5"><span className="w-3 h-0.5 rounded-full bg-chart" />Following your plan</span><span className="tabular font-medium">{money0(cTop[h])}</span></div>
|
||||
{hasLater && <div className="flex justify-between gap-4 text-on-ink/80"><span className="flex items-center gap-1.5"><span className="w-3 h-0.5 rounded-full" style={{ background: "var(--chart-mute)" }} />Possible later</span><span className="tabular">+{money0(possible[h].total)}</span></div>}
|
||||
<div className="flex justify-between gap-4 text-on-ink/70"><span className="flex items-center gap-1.5"><span className="w-3 h-0.5 rounded-full" style={{ background: "var(--muted)" }} />If nothing changes</span><span className="tabular">{money0(0)}</span></div>
|
||||
{growth > 0 && counted[h].growth >= 1 && <div className="text-on-ink/60 mt-0.5">Of which {money0(counted[h].growth)} is growth</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1.5 text-xs text-muted mt-1">
|
||||
<span className="flex items-center gap-1.5"><span className="w-3 h-1 rounded-full bg-chart" />Following your plan</span>
|
||||
{hasLater && <span className="flex items-center gap-1.5"><span className="w-3 h-2.5 rounded-sm" style={{ background: "var(--chart-soft)", boxShadow: "inset 0 2px 0 var(--chart-mute)" }} />Possible later</span>}
|
||||
<span className="flex items-center gap-1.5"><span className="w-3 h-1 rounded-full" style={{ background: "var(--muted)" }} />If nothing changes</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<div className="section-label">In {YEARS_LABEL(years)}, by what it is</div>
|
||||
{hasLater && <div className="text-xs text-muted">Including possible later</div>}
|
||||
</div>
|
||||
<Breakdown p={hasLater ? whole : end} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 border-t border-line pt-4">
|
||||
{hasInvested && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="text-sm text-muted">Growth on invested money</span>
|
||||
<div role="group" aria-label="Return a year" className="pill-tabs">
|
||||
{RETURNS.map((r) => (
|
||||
<button key={r} type="button" onClick={() => setGrowth(r)} aria-pressed={r === growth} className={chip(r === growth)}>{r ? pctLabel(r) : "None"}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ul className="text-xs text-muted space-y-1">
|
||||
{hasInvested && <li>{growth > 0 ? `Assumes ${pctLabel(growth)} a year before inflation. Markets go up and down; this is not a promise.` : "No growth: invested money is counted as what goes in."}</li>}
|
||||
{fs.some((f) => f.bucket === "savings") && <li>Savings and your emergency fund earn {pctLabel(SAVINGS_RATE)} a year, a typical high-yield savings rate.</li>}
|
||||
<li>Kept money and tax saved are counted as cash, with no growth. Invested counts the money you put in and any employer match.</li>
|
||||
{hasLater && later && <li>{laterText(later, money0)}</li>}
|
||||
<li>Each value comes from a move in your plan. Moves with no dollar figure are left out.</li>
|
||||
</ul>
|
||||
{note && (
|
||||
<p className="flex gap-2 items-start rounded-2xl bg-canvas px-4 py-3 text-sm" role="note">
|
||||
<TriangleAlert size={16} className="mt-0.5 shrink-0 text-bad" />
|
||||
<span>{note} Moves built on those numbers are not counted here.</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<details className="text-sm">
|
||||
<summary className="cursor-pointer text-muted hover:text-ink">See the numbers</summary>
|
||||
<table className="mt-3 w-full text-left tabular">
|
||||
<thead className="text-xs text-muted">
|
||||
<tr><th className="font-normal py-1">When</th><th className="font-normal py-1 text-right">Following your plan</th>{hasLater && <th className="font-normal py-1 text-right">Possible later</th>}<th className="font-normal py-1 text-right">Of which growth</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tickYears.map((m) => (
|
||||
<tr key={m} className="border-t border-line">
|
||||
<td className="py-1.5">{tickLabel(m)}</td>
|
||||
<td className="py-1.5 text-right">{money0(counted[m].total)}</td>
|
||||
{hasLater && <td className="py-1.5 text-right">+{money0(possible[m].total)}</td>}
|
||||
<td className="py-1.5 text-right">{money0(counted[m].growth)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function laterText(l: Later, money0: (n: number) => string) {
|
||||
const what = l.first.map((x) => (x === "card" ? "card debt is paid off" : "the starter fund is built")).join(" and ");
|
||||
const start = l.delay === 0 ? "Possible later starts now: nothing in the steps above is in the way." : l.why === "spare"
|
||||
? `Possible later starts in ${l.delay} month${l.delay === 1 ? "" : "s"}, once ${what}, timed from your spare money a month.`
|
||||
: `Possible later starts in ${l.delay} months, once ${what}. You have no spare money a month yet, so ${l.delay} months is assumed.`;
|
||||
const fund = l.fund > 0 ? ` It includes your ${money0(l.fund)} emergency fund, built over ${l.fundMonths} months.` : "";
|
||||
return `${start}${fund} HSA, 401(k) and IRA moves count once, at this year's room left. Other gated moves count every year at their full value.`;
|
||||
}
|
||||
|
||||
function Breakdown({ p }: { p: Point }) {
|
||||
const { money0 } = useMoney();
|
||||
const parts = KINDS.map((k) => ({ ...k, v: Math.max(0, k.of(p)) }));
|
||||
const total = parts.reduce((s, x) => s + x.v, 0);
|
||||
const shown = parts.filter((x) => x.v >= 1);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{total >= 1 && (
|
||||
<div className="flex h-2.5 gap-0.5" aria-hidden>
|
||||
{shown.map((x, i) => (
|
||||
<span key={x.key} className={`h-full ${i === 0 ? "rounded-l" : ""} ${i === shown.length - 1 ? "rounded-r" : ""}`} style={{ width: `${(x.v / total) * 100}%`, minWidth: 4, background: x.color }} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<ul className="flex flex-col @md:flex-row @md:flex-wrap gap-x-8 gap-y-2 text-sm">
|
||||
{parts.map((x) => (
|
||||
<li key={x.key} className="flex items-center gap-2">
|
||||
<span className="size-2.5 rounded-sm shrink-0" style={{ background: x.color }} />
|
||||
<span className="flex-1 @md:flex-none text-muted">{x.label}</span>
|
||||
<span className="tabular font-medium">{money0(x.v)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
"use client";
|
||||
|
||||
import { CirclePlus } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { usePlaidLink } from "react-plaid-link";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { plural } from "@/lib/format";
|
||||
|
||||
export type LinkKind = "bank" | "investments";
|
||||
export type Linked = { institution: string | null; accounts: number; added: number; holdings: number; kind: LinkKind };
|
||||
|
||||
// "Linked First Platypus Bank: 7 accounts, 331 transactions". Investments count holdings instead.
|
||||
export const linkedText = (r: Linked) =>
|
||||
`Linked ${r.institution ?? "your bank"}: ${plural(r.accounts, "account")}, ${r.kind === "investments" ? plural(r.holdings, "holding") : plural(r.added, "transaction")}`;
|
||||
|
||||
const FAILED = "Couldn't reach broke. Check your connection and try again.";
|
||||
|
||||
// itemId: Link's update mode, to sign back in to that connection; success then just re-syncs it.
|
||||
// quiet: the caller shows `result` and `error` itself, so no toast.
|
||||
export function useLinkBank(itemId?: string, { quiet = false } = {}) {
|
||||
const router = useRouter();
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [kind, setKind] = useState<LinkKind>("bank");
|
||||
const [error, setError] = useState("");
|
||||
const [result, setResult] = useState<Linked | null>(null);
|
||||
|
||||
// Every request ends here: the button resets, success shows the counts, a failure (even a dropped connection) shows why.
|
||||
const run = useCallback(
|
||||
async (req: () => Promise<Response>, k: LinkKind) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setResult(null);
|
||||
try {
|
||||
const res = await req();
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error ?? "Linking failed. Try again in a moment.");
|
||||
if (!itemId) {
|
||||
const r: Linked = { institution: body.institution ?? null, accounts: body.accounts ?? 0, added: body.added ?? 0, holdings: body.holdings ?? 0, kind: k };
|
||||
setResult(r);
|
||||
if (!quiet) toast(linkedText(r), undefined, { label: "Open dashboard", run: () => router.push("/") });
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = e instanceof TypeError ? FAILED : e instanceof Error ? e.message : FAILED; // fetch throws TypeError "Failed to fetch"
|
||||
setError(msg);
|
||||
if (!quiet) toast(msg);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setToken(null);
|
||||
router.refresh();
|
||||
}
|
||||
},
|
||||
[router, itemId, quiet],
|
||||
);
|
||||
// The bank and accounts picked go along, so the server can refuse a bank that's already linked before saving a copy.
|
||||
const onSuccess = useCallback(
|
||||
(public_token: string, meta: { institution?: { institution_id?: string } | null; accounts?: { mask?: string | null; type?: string | null }[] }) =>
|
||||
run(() => (itemId ? fetch("/api/plaid/sync", { method: "POST" }) : fetch("/api/plaid/exchange", { method: "POST", body: JSON.stringify({
|
||||
public_token, institution_id: meta?.institution?.institution_id ?? null, accounts: (meta?.accounts ?? []).map((a) => ({ mask: a.mask ?? null, type: a.type ?? null })),
|
||||
}) })), kind),
|
||||
[run, itemId, kind],
|
||||
);
|
||||
const { open, ready } = usePlaidLink({ token, onSuccess, onExit: () => setToken(null) });
|
||||
|
||||
useEffect(() => {
|
||||
if (token && ready) open();
|
||||
}, [token, ready, open]);
|
||||
|
||||
async function start(sandbox = false, k: LinkKind = "bank") {
|
||||
setError("");
|
||||
setKind(k);
|
||||
const payload = JSON.stringify({ kind: k, itemId });
|
||||
if (sandbox) return run(() => fetch("/api/plaid/sandbox", { method: "POST", body: payload }), k);
|
||||
try {
|
||||
const res = await fetch("/api/plaid/link-token", { method: "POST", body: payload });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return setError(body.error ?? "Could not start Plaid");
|
||||
setToken(body.link_token);
|
||||
} catch {
|
||||
setError(FAILED);
|
||||
if (!quiet) toast(FAILED);
|
||||
}
|
||||
}
|
||||
return { start, busy, kind, error, result };
|
||||
}
|
||||
|
||||
export function LinkBankButton({ label = "Add account", primary = false, sandbox = false, kind = "bank" }: { label?: string; primary?: boolean; sandbox?: boolean; kind?: LinkKind }) {
|
||||
const { start, busy, error } = useLinkBank();
|
||||
return (
|
||||
<span className="inline-flex flex-col items-center gap-1">
|
||||
<button onClick={() => start(sandbox, kind)} disabled={busy} className={primary ? "btn-primary" : "btn"}>
|
||||
{busy ? (kind === "investments" ? "Importing holdings..." : "Importing transactions...") : label}
|
||||
</button>
|
||||
{error && <span className="text-xs text-bad">{error}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** New Zealand: links the server's Akahu personal app (every bank on that Akahu login). */
|
||||
export function useAkahu() {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
async function start() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
const res = await fetch("/api/bank/akahu", { method: "POST" });
|
||||
if (!res.ok) setError((await res.json().catch(() => ({}))).error ?? "Linking failed");
|
||||
setBusy(false);
|
||||
router.refresh();
|
||||
}
|
||||
return { start, busy, error };
|
||||
}
|
||||
|
||||
export function AkahuButton({ primary = false }: { primary?: boolean }) {
|
||||
const { start, busy, error } = useAkahu();
|
||||
return (
|
||||
<span className="inline-flex flex-col items-center gap-1">
|
||||
<button className={primary ? "btn-primary" : "btn"} disabled={busy} onClick={start}>
|
||||
{busy ? "Importing transactions..." : "+ Add NZ banks (Akahu)"}
|
||||
</button>
|
||||
{error && <span className="text-xs text-bad">{error}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddAccountLink() {
|
||||
const { start, busy } = useLinkBank();
|
||||
return (
|
||||
<button onClick={() => start()} disabled={busy} className="flex items-center gap-2 text-[15px] hover:opacity-70">
|
||||
{busy ? "Linking..." : "Add"} <CirclePlus size={20} strokeWidth={1.5} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Reconnect (when broken) and Remove, with a confirm step, for one bank connection. */
|
||||
export function ConnectionActions({ itemId, broken, name }: { itemId: string; broken: boolean; name: string }) {
|
||||
const router = useRouter();
|
||||
const { start, busy, error } = useLinkBank(itemId);
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
const [removeError, setRemoveError] = useState("");
|
||||
async function remove() {
|
||||
setRemoving(true);
|
||||
setRemoveError("");
|
||||
const res = await fetch("/api/plaid/remove", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ itemId }) });
|
||||
setRemoving(false);
|
||||
if (!res.ok) return setRemoveError((await res.json().catch(() => ({}))).error ?? "Couldn't remove it");
|
||||
setConfirm(false);
|
||||
router.refresh();
|
||||
}
|
||||
return (
|
||||
<span className="flex flex-col items-end gap-1">
|
||||
<span className="flex items-center gap-2">
|
||||
{confirm ? (
|
||||
<>
|
||||
<span className="text-xs text-muted">Remove {name} and its transactions?</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={removing}>{removing ? "Removing..." : "Remove"}</button>
|
||||
<button className="btn" onClick={() => setConfirm(false)} disabled={removing}>Cancel</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{broken && <button className="btn-primary" onClick={() => start()} disabled={busy}>{busy ? "Reconnecting..." : "Reconnect"}</button>}
|
||||
<button className="btn" onClick={() => setConfirm(true)}>Remove</button>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
{(error || removeError) && <span className="text-xs text-bad">{error || removeError}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function SyncButton({ subtle = false }: { subtle?: boolean }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [result, setResult] = useState("");
|
||||
useEffect(() => {
|
||||
if (!result) return;
|
||||
const t = setTimeout(() => setResult(""), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [result]);
|
||||
return (
|
||||
<button
|
||||
className={subtle ? "text-xs underline underline-offset-2 hover:opacity-70" : "btn"}
|
||||
disabled={busy}
|
||||
aria-live="polite"
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
const res = await fetch("/api/plaid/sync", { method: "POST" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
const added = (body.results ?? []).reduce((s: number, r: { added: number }) => s + r.added, 0);
|
||||
setResult(!res.ok ? "Sync failed" : added ? `${added} new` : "Up to date");
|
||||
setBusy(false);
|
||||
router.refresh();
|
||||
}}
|
||||
>
|
||||
{busy ? "Syncing..." : result || "Sync now"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// Test mode: Plaid's window only takes its made-up banks. Says how to sign in there, and where real banks start.
|
||||
export function TestModeNote() {
|
||||
return (
|
||||
<p className="text-sm text-muted max-w-md">
|
||||
Test mode: Plaid only shows made-up banks. Sign in with <code className="font-mono text-ink">user_good</code> and <code className="font-mono text-ink">pass_good</code>.{" "}
|
||||
<a href="/go-live" className="text-ink underline underline-offset-2 hover:opacity-70">Use your real bank</a>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
// Linked now: removes a second copy of a bank (the same accounts, linked again). /api/plaid/remove revokes it at Plaid.
|
||||
export function RemoveCopy({ itemId, name }: { itemId: string; name: string }) {
|
||||
const router = useRouter();
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const res = await fetch("/api/plaid/remove", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ itemId }) }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setErr("Couldn't remove it. Try again.");
|
||||
router.refresh();
|
||||
}
|
||||
return confirm ? (
|
||||
<span className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted">Remove this copy of {name}? The other one keeps all your transactions.</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={busy}>{busy ? "Removing..." : "Remove copy"}</button>
|
||||
<button className="text-muted hover:text-ink" onClick={() => setConfirm(false)} disabled={busy}>Cancel</button>
|
||||
{err && <span className="text-bad">{err}</span>}
|
||||
</span>
|
||||
) : (
|
||||
<button className="btn !py-1 text-sm" onClick={() => setConfirm(true)}>Remove this copy</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowUp } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
|
||||
const STARTERS = ["What should I do first with my money?", "How can I spend less without feeling it?", "Am I on track for my goals?"];
|
||||
|
||||
// The plan as a conversation: ask in plain words. The AI can look up your numbers and offer budget and category changes.
|
||||
export function PlanChat() {
|
||||
const { ask } = useAssistant();
|
||||
const [q, setQ] = useState("");
|
||||
function send(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!q.trim()) return;
|
||||
ask(q.trim());
|
||||
setQ("");
|
||||
}
|
||||
return (
|
||||
<section className="card p-6 space-y-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="card-title">Talk it through</h2>
|
||||
<p className="text-sm text-muted">Ask anything about your money. It can look at your numbers and suggest changes to your budget and categories.</p>
|
||||
</div>
|
||||
<form onSubmit={send} className="flex gap-2">
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} aria-label="Ask about your plan" placeholder="I want to save for a trip. Where do I start?" className="select flex-1 min-w-0" />
|
||||
<button aria-label="Ask" disabled={!q.trim()} className="btn-primary !px-3 shrink-0"><ArrowUp size={18} /></button>
|
||||
</form>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{STARTERS.map((s) => <button key={s} type="button" onClick={() => ask(s)} className="rounded-full border border-line px-3.5 py-1.5 text-sm hover:bg-[var(--hover)]">{s}</button>)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
// "What should your plan know?": the money profile's notes, on the plan page too. The plan and the chat read it;
|
||||
// a cloud model gets it with bank and merchant names swapped for placeholders.
|
||||
export function PlanContext({ initial }: { initial: string }) {
|
||||
const router = useRouter();
|
||||
const [text, setText] = useState(initial);
|
||||
const [state, setState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
async function save() {
|
||||
setState("saving");
|
||||
const sb = createClient();
|
||||
const { data } = await sb.auth.getUser();
|
||||
const profile = (data.user?.user_metadata?.profile ?? {}) as Record<string, unknown>;
|
||||
const { error } = await updateMeta(sb, { data: { profile: { ...profile, notes: text.trim().slice(0, 1000) } } });
|
||||
setState(error ? "failed" : "saved");
|
||||
if (!error) router.refresh();
|
||||
}
|
||||
return (
|
||||
<section className="card p-6 space-y-3 mb-6">
|
||||
<div>
|
||||
<div className="card-title">What should your plan know?</div>
|
||||
<p className="text-sm text-muted mt-0.5">Anything your bank data can't show. broke ai reads it when it builds your plan and when you chat.</p>
|
||||
</div>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => { setText(e.target.value); setState("idle"); }}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
aria-label="What should your plan know?"
|
||||
placeholder="e.g. I moved to the US in July, so my accounts are new. I get paid twice a month. I want to buy a car next year."
|
||||
className="w-full bg-surface border border-line rounded-2xl px-4 py-3 text-sm outline-none focus:border-ink"
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button className="btn" onClick={save} disabled={state === "saving" || text.trim() === initial.trim()}>{state === "saving" ? "Saving…" : state === "saved" ? "Saved" : "Save"}</button>
|
||||
{state === "saved" && <span className="text-sm text-muted">Run the audit again to use it.</span>}
|
||||
{state === "failed" && <span className="text-sm text-bad">Couldn't save. Try again.</span>}
|
||||
<span className="text-xs text-muted ml-auto">Names of banks and shops are swapped out before it goes to a cloud AI.</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { loadBills } from "@/components/BillsOnCards";
|
||||
import { getUser } from "@/lib/data";
|
||||
import { deterministicMoves, type Move } from "@/lib/plan";
|
||||
import { planFacts } from "@/lib/plan-facts";
|
||||
|
||||
type Line = { text: string; note?: string | null };
|
||||
|
||||
// The plan in a few plain lines, grouped the way people act on it: what to fix, what to move to a card, where to cut
|
||||
// back, what to save and invest. Worked out live from today's data on every load, so it's never out of date.
|
||||
// The full plan with steps and messages stays below it.
|
||||
export async function PlanSummary({ today }: { today: string }) {
|
||||
const { supabase, user } = await getUser();
|
||||
const profile = (user?.user_metadata?.profile ?? {}) as Record<string, unknown>;
|
||||
const [facts, bills] = await Promise.all([planFacts(supabase, user!.id, profile, today), loadBills()]);
|
||||
const { money } = bills;
|
||||
const moves = deterministicMoves(facts, money);
|
||||
const has = (m: Move, ...refs: string[]) => refs.some((r) => m.ref === r || m.ref.startsWith(`${r}:`));
|
||||
const line = (m: Move): Line => ({ text: m.title, note: m.gate });
|
||||
|
||||
const fix = moves.filter((m) => has(m, "interest", "fees", "overspend", "fund:starter") || m.ref === "goal:debt").map(line);
|
||||
|
||||
// Bills to move, grouped by the card to move them to.
|
||||
const byCard = new Map<string, { names: string[]; gain: number }>();
|
||||
for (const x of bills.items) {
|
||||
if (!x.o?.mine || x.gainMine < 1 || x.unknownCard || x.rent) continue;
|
||||
const k = x.o.mine.card.name;
|
||||
const g = byCard.get(k) ?? { names: [], gain: 0 };
|
||||
g.names.push(x.r.merchant_name);
|
||||
g.gain += x.gainMine;
|
||||
byCard.set(k, g);
|
||||
}
|
||||
const list = (xs: string[]) => (xs.length <= 2 ? xs.join(" and ") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)}`);
|
||||
const card: Line[] = [...byCard].map(([name, g]) => ({ text: `Pay ${list(g.names)} with your ${name}`, note: `About ${money(g.gain)} a year back.` }));
|
||||
|
||||
const cut: Line[] = [
|
||||
...(facts.spikes ?? []).map((s) => ({ text: `${s.label}: back to about ${money(s.avg)} a month`, note: `${money(s.now)} so far this month.` })),
|
||||
...moves.filter((m) => has(m, "duplicate", "hike")).map(line),
|
||||
...moves.filter((m) => m.ref === "subs").map((m) => ({ text: m.title, note: m.why.split(". ")[0] + "." })),
|
||||
];
|
||||
|
||||
const save = moves.filter((m) => has(m, "match", "fund:full", "room", "tax:ira", "hysa", "invest") || (m.ref.startsWith("goal:") && m.ref !== "goal:debt")).map(line);
|
||||
|
||||
const groups = [
|
||||
{ title: "Fix this first", lines: fix },
|
||||
{ title: "Move these to a card", lines: card },
|
||||
{ title: "Cut back", lines: cut },
|
||||
{ title: "Save and invest", lines: save },
|
||||
].filter((g) => g.lines.length);
|
||||
if (!groups.length) return null;
|
||||
|
||||
return (
|
||||
<section className="card p-6 space-y-5 mb-6">
|
||||
<div>
|
||||
<div className="card-title">Your plan</div>
|
||||
<p className="text-sm text-muted mt-0.5">From your accounts as they are today. The full plan, with steps for each, is below.</p>
|
||||
</div>
|
||||
{groups.map((g, gi) => (
|
||||
<div key={g.title} className="space-y-2">
|
||||
<div className="text-sm font-medium flex items-center gap-2">
|
||||
<span className="size-5 rounded-full border border-line text-xs text-muted grid place-items-center tabular">{gi + 1}</span>
|
||||
{g.title}
|
||||
</div>
|
||||
<ul className="space-y-1.5 pl-7">
|
||||
{g.lines.slice(0, 5).map((l) => (
|
||||
<li key={l.text} className="text-sm">
|
||||
{l.text}
|
||||
{l.note && <span className="text-muted"> · {l.note}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { CountryField } from "@/components/CountryPicker";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { GoalPicker } from "@/components/GoalPicker";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import { BANDS } from "@/lib/credit";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
import { profileFields, validGoalPlan, type GoalPlan } from "@/lib/advice";
|
||||
|
||||
export type Profile = {
|
||||
country?: string; currency?: string; // ISO codes; no country = US (countryOf)
|
||||
state?: string; // the country's region (regionLabel): a US state code, else what the user typed
|
||||
filing?: string; income?: string; age?: string; work?: string;
|
||||
match?: string; health?: string; hsaCover?: string; dependents?: string; risk?: string; goals?: string[]; notes?: string;
|
||||
goalPlans?: GoalPlan[]; // a target for each goal in TARGET_GOALS that has one
|
||||
alsoBanksIn?: string[]; // countries besides their own: only "NZ" changes anything today (wantsAkahu)
|
||||
credit?: string; creditAsOf?: string; // a credit.ts Band and a "YYYY-MM" month
|
||||
pay?: { amount: number; every: string }; // take-home pay per check; every: a Plaid frequency (WEEKLY ... MONTHLY)
|
||||
onboarding?: string; // the first-run step to resume at (Onboarding.tsx); absent or "done" = finished
|
||||
};
|
||||
|
||||
// Stored as the 2-letter code (what the model sees), shown as the full name so search works.
|
||||
const STATES = Object.entries({
|
||||
AL: "Alabama", AK: "Alaska", AZ: "Arizona", AR: "Arkansas", CA: "California", CO: "Colorado", CT: "Connecticut", DE: "Delaware",
|
||||
DC: "District of Columbia", FL: "Florida", GA: "Georgia", HI: "Hawaii", ID: "Idaho", IL: "Illinois", IN: "Indiana", IA: "Iowa",
|
||||
KS: "Kansas", KY: "Kentucky", LA: "Louisiana", ME: "Maine", MD: "Maryland", MA: "Massachusetts", MI: "Michigan", MN: "Minnesota",
|
||||
MS: "Mississippi", MO: "Missouri", MT: "Montana", NE: "Nebraska", NV: "Nevada", NH: "New Hampshire", NJ: "New Jersey",
|
||||
NM: "New Mexico", NY: "New York", NC: "North Carolina", ND: "North Dakota", OH: "Ohio", OK: "Oklahoma", OR: "Oregon",
|
||||
PA: "Pennsylvania", RI: "Rhode Island", SC: "South Carolina", SD: "South Dakota", TN: "Tennessee", TX: "Texas", UT: "Utah",
|
||||
VT: "Vermont", VA: "Virginia", WA: "Washington", WV: "West Virginia", WI: "Wisconsin", WY: "Wyoming",
|
||||
}).map(([value, label]) => ({ value, label }));
|
||||
export const PLAN_PROMPT =
|
||||
"Using my money profile and my last 90 days of transactions, give me my top 5 money moves to optimize taxes, tax-advantaged retirement accounts and savings under my country's rules. For each: what to do, why it fits me, and roughly how much it could save or grow.";
|
||||
|
||||
export function ProfileForm({ initial }: { initial: Profile }) {
|
||||
const router = useRouter();
|
||||
const { ask } = useAssistant();
|
||||
const { money0 } = useMoney();
|
||||
const [p, setP] = useState<Profile>(initial);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const set = (k: keyof Profile, v: string | string[]) => {
|
||||
setP({ ...p, [k]: v });
|
||||
setSaved(false);
|
||||
};
|
||||
|
||||
// Only whole targets are saved, and only for goals still picked.
|
||||
async function save() {
|
||||
const goalPlans = (p.goalPlans ?? []).filter((g) => p.goals?.includes(g.goal)).map(validGoalPlan).filter((g): g is GoalPlan => !!g);
|
||||
const { error } = await updateMeta(createClient(), { data: { profile: { ...p, goalPlans } } });
|
||||
if (!error) {
|
||||
setSaved(true);
|
||||
router.refresh();
|
||||
}
|
||||
return !error;
|
||||
}
|
||||
|
||||
const country = countryOf(p.country);
|
||||
const region = country.regionLabel;
|
||||
const FIELDS = profileFields(p.country); // only the questions that apply in this country
|
||||
const filled = [p.country, ...(region ? [p.state] : []), ...FIELDS.map((f) => p[f.key]), p.credit].filter(Boolean).length;
|
||||
const total = FIELDS.length + 2 + (region ? 1 : 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section id="profile" className="card p-6 space-y-5 scroll-mt-6">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="card-title">Your money profile</div>
|
||||
<p className="text-sm text-muted mt-1">broke AI uses this with your transactions to tailor ideas. Only you can see it.</p>
|
||||
</div>
|
||||
<span className="text-xs text-muted tabular whitespace-nowrap">{filled}/{total} answered</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-canvas rounded-full overflow-hidden">
|
||||
<div className="h-full bg-brand rounded-full transition-all" style={{ width: `${(filled / total) * 100}%` }} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 @2xl:grid-cols-2">
|
||||
<Field label="Country">
|
||||
<CountryField
|
||||
country={p.country ?? ""}
|
||||
currency={p.currency}
|
||||
// A US state code means nothing elsewhere, so the region clears when the country changes.
|
||||
onChange={(c, currency) => { setP({ ...p, country: c, currency, state: c === p.country ? p.state : undefined }); setSaved(false); }}
|
||||
/>
|
||||
{country.code !== "NZ" && (
|
||||
<label className="flex items-center gap-2.5 text-sm text-muted cursor-pointer pt-1">
|
||||
<input type="checkbox" checked={!!p.alsoBanksIn?.includes("NZ")} onChange={(e) => set("alsoBanksIn", e.target.checked ? ["NZ"] : [])} className="size-4 shrink-0 accent-[var(--color-ink)]" />
|
||||
I also have banks in New Zealand
|
||||
</label>
|
||||
)}
|
||||
</Field>
|
||||
{region && (
|
||||
<Field label={`${region} you live in`}>
|
||||
{country.code === "US" ? (
|
||||
<Dropdown label="State" value={p.state ?? ""} options={STATES} onChange={(v) => set("state", v)} placeholder="Choose a state" searchable />
|
||||
) : (
|
||||
<input value={p.state ?? ""} onChange={(e) => set("state", e.target.value)} aria-label={region} placeholder={`Your ${region.toLowerCase()}`} className="select" />
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
{FIELDS.map((f) => (
|
||||
<Field key={f.key} label={f.label}>
|
||||
<Dropdown label={f.label} value={(p[f.key] as string) ?? ""} options={f.options} onChange={(v) => set(f.key, v)} placeholder="Choose one" />
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Credit range">
|
||||
<Dropdown label="Credit range" value={p.credit ?? ""} options={BANDS} onChange={(v) => set("credit", v)} placeholder="Choose one" />
|
||||
</Field>
|
||||
<Field label="Last checked (optional)">
|
||||
<input type="month" value={p.creditAsOf ?? ""} max={new Date().toISOString().slice(0, 7)} onChange={(e) => set("creditAsOf", e.target.value)} aria-label="Credit range last checked" className="select" />
|
||||
</Field>
|
||||
</div>
|
||||
<p className="text-xs text-muted -mt-2">Your credit range picks which cards fit you on the Cards page.</p>
|
||||
|
||||
<Field label="Goals">
|
||||
<GoalPicker goals={p.goals ?? []} plans={p.goalPlans ?? []} onChange={(goals, goalPlans) => { setP({ ...p, goals, goalPlans: goalPlans as GoalPlan[] }); setSaved(false); }} />
|
||||
</Field>
|
||||
|
||||
<Field label="Anything else (optional)">
|
||||
<textarea
|
||||
value={p.notes ?? ""}
|
||||
onChange={(e) => set("notes", e.target.value)}
|
||||
rows={2}
|
||||
aria-label="Anything else"
|
||||
placeholder={`e.g. I have ${money0(8000)} in a savings account at 0.5% and freelance income on the side`}
|
||||
className="w-full bg-surface border border-line rounded-2xl px-4 py-3 text-sm outline-none focus:border-ink"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button onClick={save} className="btn">{saved ? "Saved" : "Save profile"}</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (await save()) ask(PLAN_PROMPT);
|
||||
}}
|
||||
className="btn-primary"
|
||||
>
|
||||
Get my money moves
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">{label}</span>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
// A custom date range: a start and an end, either can be left open. Dates are plain YYYY-MM-DD, the user's own days.
|
||||
export function RangePicker({ from, to, today, onApply, onClear }: { from: string; to: string; today: string; onApply: (from: string, to: string) => void; onClear?: () => void }) {
|
||||
const [a, setA] = useState(from);
|
||||
const [b, setB] = useState(to);
|
||||
const bad = !!a && !!b && a > b;
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); if (!bad) onApply(a, b); }} className="flex flex-wrap items-end gap-3">
|
||||
<label className="space-y-1 text-xs text-muted">From
|
||||
<input type="date" value={a} max={b || today} onChange={(e) => setA(e.target.value)} className="select text-ink block" />
|
||||
</label>
|
||||
<label className="space-y-1 text-xs text-muted">To
|
||||
<input type="date" value={b} min={a || undefined} max={today} onChange={(e) => setB(e.target.value)} className="select text-ink block" />
|
||||
</label>
|
||||
<button disabled={bad || (!a && !b)} className="btn-primary !py-2">Show</button>
|
||||
{onClear && <button type="button" onClick={onClear} className="btn !py-2">Clear dates</button>}
|
||||
{bad && <p className="w-full text-sm text-bad">The start has to be before the end.</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "@/components/Toast";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
// Optimistic: the label flips at once, a failed write (or 0 rows from RLS) puts it back.
|
||||
export function RecurringToggle({ id, active }: { id: string; active: boolean }) {
|
||||
const router = useRouter();
|
||||
const [on, setOn] = useState(active);
|
||||
return (
|
||||
<button
|
||||
className="btn text-xs"
|
||||
onClick={async () => {
|
||||
const next = !on;
|
||||
setOn(next);
|
||||
const { data, error } = await createClient().from("recurring").update({ active: next }).eq("id", id).select("id");
|
||||
if (error || !data?.length) return setOn(!next), toast("Couldn't save that. Try again.");
|
||||
router.refresh();
|
||||
}}
|
||||
>
|
||||
{on ? "Hide" : "Show"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeft, CalendarDays, DollarSign, EyeOff, Landmark, type LucideIcon, Pencil, Shapes, Tags, Type, X } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { TagEditor } from "@/components/Tags";
|
||||
import type { Category } from "@/lib/data";
|
||||
import { displayName, plural } from "@/lib/format";
|
||||
import { findsSomething, matches, mergeTags, type Rule } from "@/lib/rules";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
export type Draft = Omit<Rule, "id"> & { id?: string };
|
||||
export const emptyRule = (x: Partial<Draft> = {}): Draft => ({ match: "", amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, category_id: null, rename: null, ignore: null, add_tags: null, ...x });
|
||||
|
||||
type Match = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null };
|
||||
|
||||
// Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here.
|
||||
export async function pastMatches(d: Draft) {
|
||||
if (!findsSomething(d)) return [];
|
||||
const s = d.match.trim().replace(/[%,()]/g, " ");
|
||||
const db = createClient();
|
||||
const uid = (await db.auth.getSession()).data.session?.user.id;
|
||||
if (!uid) return [];
|
||||
// Own rows only (not a partner's shared ones), paged: Supabase returns at most 1000 rows per request.
|
||||
// ponytail: a rule with no name pages through every own row; fine for a personal ledger, an RPC if it gets slow.
|
||||
const rows: Match[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags").eq("user_id", uid);
|
||||
if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`);
|
||||
if (d.account_id) q = q.eq("account_id", d.account_id);
|
||||
const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999);
|
||||
rows.push(...((data ?? []) as Match[]));
|
||||
if (!data || data.length < 1000) break;
|
||||
}
|
||||
return rows.filter((t) => matches(d, t));
|
||||
}
|
||||
|
||||
/** Saves the rule and, if asked, rewrites the past transactions it matches. Returns how many changed, or an error. */
|
||||
export async function saveRule(d: Draft, applyPast: boolean): Promise<{ error?: string; updated: number }> {
|
||||
const supabase = createClient();
|
||||
const row = {
|
||||
match: d.match.trim(), amount_min: d.amount_min, amount_max: d.amount_max, account_id: d.account_id || null, day_from: d.day_from ?? null, day_to: d.day_to ?? null, direction: d.direction ?? null,
|
||||
category_id: d.category_id, rename: d.rename?.trim() || null, ignore: d.ignore, add_tags: d.add_tags?.length ? d.add_tags : null,
|
||||
};
|
||||
const { error } = d.id ? await supabase.from("rules").update(row).eq("id", d.id) : await supabase.from("rules").insert(row);
|
||||
if (error) return { error: /rules|column/.test(error.message) ? "Rules need a database update. Open Setup to run it." : "Couldn't save the rule.", updated: 0 };
|
||||
if (!applyPast) return { updated: 0 };
|
||||
const patch = { ...(row.category_id ? { category_id: row.category_id } : {}), ...(row.rename ? { custom_name: row.rename } : {}), ...(row.ignore != null ? { ignored: row.ignore } : {}) };
|
||||
const past = await pastMatches(d);
|
||||
const ids = past.map((t) => t.id);
|
||||
if (Object.keys(patch).length) for (let i = 0; i < ids.length; i += 200) await supabase.from("transactions").update(patch).in("id", ids.slice(i, i + 200));
|
||||
// Tags merge with what each row already has, so it's one write per row that gains a tag.
|
||||
// ponytail: per-row updates, 10 at a time; a Postgres function would do it in one call if rules grow to thousands of rows.
|
||||
const tagged = row.add_tags ? past.filter((t) => mergeTags(t.tags, row.add_tags).length > (t.tags ?? []).length) : [];
|
||||
for (let i = 0; i < tagged.length; i += 10)
|
||||
await Promise.all(tagged.slice(i, i + 10).map((t) => supabase.from("transactions").update({ tags: mergeTags(t.tags, row.add_tags) }).eq("id", t.id)));
|
||||
return { updated: ids.length };
|
||||
}
|
||||
|
||||
export const categoryOptions = (cats: Category[]) =>
|
||||
cats.map((c) => ({ value: c.id, label: c.label, icon: <CategoryIcon icon={c.icon} color={c.color} size={26} /> }));
|
||||
|
||||
// One option on the left pane: icon, label, checkbox. Checking it opens its inputs.
|
||||
function Option({ icon: Icon, label, on, set, children }: { icon: LucideIcon; label: string; on: boolean; set: (on: boolean) => void; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="rounded-2xl bg-surface border border-line">
|
||||
<label className="flex items-center gap-3 px-4 py-3.5 cursor-pointer">
|
||||
<Icon size={18} className="text-muted shrink-0" />
|
||||
<span className="flex-1 text-sm font-medium">{label}</span>
|
||||
<input type="checkbox" checked={on} onChange={(e) => set(e.target.checked)} className="size-4 accent-[var(--color-ink)]" />
|
||||
</label>
|
||||
{on && children && <div className="px-4 pb-4 space-y-3">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const day = (v: string) => (/^\d{1,2}$/.test(v.trim()) && +v >= 1 && +v <= 31 ? +v : null);
|
||||
|
||||
/** Create or edit a rule in two steps: how it finds transactions (with the live matches beside it), then what it does. */
|
||||
export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initial: Draft; cats: Category[]; allTags: string[]; onClose: () => void; onDone: (msg: string) => void }) {
|
||||
const { money0, parseAmount, signed, dayLabel } = useMoney();
|
||||
const num = (v: string) => (v.trim() === "" || isNaN(parseAmount(v)) ? null : Math.abs(parseAmount(v)));
|
||||
const [step, setStep] = useState<1 | 2>(1);
|
||||
const [d, setD] = useState(initial);
|
||||
const [on, setOn] = useState({
|
||||
name: !!initial.match.trim(), amount: initial.amount_min != null || initial.amount_max != null, account: !!initial.account_id, date: initial.day_from != null || initial.day_to != null,
|
||||
category: !!initial.category_id, rename: !!initial.rename, tags: !!initial.add_tags?.length, ignore: !!initial.ignore,
|
||||
});
|
||||
const turn = (k: keyof typeof on) => (v: boolean) => setOn({ ...on, [k]: v });
|
||||
const [min, setMin] = useState(initial.amount_min?.toString() ?? "");
|
||||
const [max, setMax] = useState(initial.amount_max?.toString() ?? "");
|
||||
const [dayFrom, setDayFrom] = useState(initial.day_from?.toString() ?? "");
|
||||
const [dayTo, setDayTo] = useState(initial.day_to?.toString() ?? "");
|
||||
const [accounts, setAccounts] = useState<{ value: string; label: string }[]>([]);
|
||||
const [found, setFound] = useState<Match[] | null>(null);
|
||||
const [foundKey, setFoundKey] = useState<string | null>(null); // which match settings `found` is for
|
||||
const [applyPast, setApplyPast] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
// Unchecked options don't count, so unchecking keeps what was typed without using it.
|
||||
const draft: Draft = {
|
||||
...d,
|
||||
match: on.name ? d.match : "",
|
||||
amount_min: on.amount ? num(min) : null, amount_max: on.amount ? num(max) : null,
|
||||
account_id: on.account ? d.account_id : null,
|
||||
day_from: on.date ? day(dayFrom) : null, day_to: on.date ? day(dayTo) : null,
|
||||
category_id: on.category ? d.category_id : null, rename: on.rename ? d.rename : null,
|
||||
add_tags: on.tags ? d.add_tags : null, ignore: on.ignore ? true : null,
|
||||
};
|
||||
const badAmount = draft.amount_min != null && draft.amount_max != null && draft.amount_min > draft.amount_max;
|
||||
const badDay = on.date && ((dayFrom.trim() !== "" && day(dayFrom) == null) || (dayTo.trim() !== "" && day(dayTo) == null));
|
||||
const canContinue = findsSomething(draft) && !badAmount && !badDay;
|
||||
const doesSomething = !!draft.category_id || !!draft.rename?.trim() || draft.ignore != null || !!draft.add_tags?.length;
|
||||
const key = JSON.stringify([draft.match, draft.amount_min, draft.amount_max, draft.account_id, draft.day_from, draft.day_to]);
|
||||
|
||||
// Own accounts, for "Filter by account".
|
||||
useEffect(() => {
|
||||
const db = createClient();
|
||||
db.auth.getSession().then(({ data }) => {
|
||||
const uid = data.session?.user.id;
|
||||
if (uid) db.from("accounts").select("id, name, custom_name, mask").eq("user_id", uid).order("name").then(({ data }) =>
|
||||
setAccounts((data ?? []).map((a) => ({ value: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}` }))));
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Live matches, after typing settles. A slower earlier answer never overwrites a newer one.
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const t = setTimeout(() => pastMatches(draft).then((r) => live && (setFound(r), setFoundKey(key))), 300);
|
||||
return () => {
|
||||
live = false;
|
||||
clearTimeout(t);
|
||||
};
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
async function save() {
|
||||
if (!doesSomething) return setErr("Pick at least one thing for the rule to do.");
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const r = await saveRule(draft, applyPast);
|
||||
setBusy(false);
|
||||
if (r.error) return setErr(r.error);
|
||||
onDone(r.updated ? `Rule saved. Updated ${plural(r.updated, "past transaction")}.` : "Rule saved.");
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const { error } = await createClient().from("rules").delete().eq("id", d.id!);
|
||||
if (error) return setErr("Couldn't delete the rule.");
|
||||
onDone("Rule deleted. Past transactions keep their changes.");
|
||||
}
|
||||
|
||||
// Until the count for these settings lands, say so instead of showing 0 (or the last count).
|
||||
const loading = findsSomething(draft) && foundKey !== key;
|
||||
const n = findsSomething(draft) ? found?.length ?? 0 : 0;
|
||||
const title = d.id ? "Edit rule" : "Create a rule";
|
||||
|
||||
return (
|
||||
<Modal label={title} onClose={onClose} className="md:max-w-4xl! p-0! md:h-[min(680px,88vh)] flex flex-col">
|
||||
<div className="flex items-center gap-2 px-5 md:px-6 py-4 border-b border-line">
|
||||
{step === 2 && <button type="button" aria-label="Back" onClick={() => (setStep(1), setErr(""))} className="p-2 -ml-2 rounded-full hover:bg-[var(--hover)]"><ArrowLeft size={18} /></button>}
|
||||
<div className="card-title flex-1 min-w-0 truncate">{title}</div>
|
||||
{step === 1
|
||||
? <button type="button" disabled={!canContinue} onClick={() => setStep(2)} className="btn-primary">Continue</button>
|
||||
: <button type="button" disabled={busy || !doesSomething} onClick={save} className="btn-primary">{busy ? "Saving..." : "Save rule"}</button>}
|
||||
<button type="button" aria-label="Close" onClick={onClose} className="p-2 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 md:min-h-0 grid md:grid-cols-2">
|
||||
<div className="bg-canvas p-5 md:p-6 space-y-3 md:overflow-y-auto">
|
||||
{step === 1 ? (
|
||||
<>
|
||||
<p className="text-sm text-muted pb-1">First, set up how your rule finds transactions. Pick one or more.</p>
|
||||
<Option icon={Pencil} label="Match on name" on={on.name} set={turn("name")}>
|
||||
<input autoFocus value={d.match} onChange={(e) => setD({ ...d, match: e.target.value })} placeholder="Name contains, e.g. uber" aria-label="Name contains" className="select" />
|
||||
</Option>
|
||||
<Option icon={DollarSign} label="Match on amount" on={on.amount} set={turn("amount")}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="block space-y-1.5"><span className="text-xs text-muted">From</span><input autoFocus inputMode="decimal" value={min} onChange={(e) => setMin(e.target.value)} placeholder={money0(0)} className="select tabular" /></label>
|
||||
<label className="block space-y-1.5"><span className="text-xs text-muted">To</span><input inputMode="decimal" value={max} onChange={(e) => setMax(e.target.value)} placeholder="Any" className="select tabular" /></label>
|
||||
</div>
|
||||
{badAmount && <p className="text-xs text-bad">The lowest amount is above the highest.</p>}
|
||||
</Option>
|
||||
<Option icon={Landmark} label="Filter by account" on={on.account} set={turn("account")}>
|
||||
{accounts.length
|
||||
? <Dropdown label="Account" value={d.account_id ?? ""} options={accounts} onChange={(v) => setD({ ...d, account_id: v || null })} placeholder="Pick an account" />
|
||||
: <p className="text-sm text-muted">No accounts yet.</p>}
|
||||
</Option>
|
||||
<Option icon={CalendarDays} label="Match on date" on={on.date} set={turn("date")}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="block space-y-1.5"><span className="text-xs text-muted">Day of the month</span><input autoFocus inputMode="numeric" value={dayFrom} onChange={(e) => setDayFrom(e.target.value)} placeholder="1" className="select tabular" /></label>
|
||||
<label className="block space-y-1.5"><span className="text-xs text-muted">To <span className="text-muted">(optional)</span></span><input inputMode="numeric" value={dayTo} onChange={(e) => setDayTo(e.target.value)} placeholder="Same day" className="select tabular" /></label>
|
||||
</div>
|
||||
{badDay && <p className="text-xs text-bad">Days run from 1 to 31.</p>}
|
||||
</Option>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted pb-1">Then, choose what the rule does to these transactions.</p>
|
||||
<Option icon={Shapes} label="Change category" on={on.category} set={turn("category")}>
|
||||
<Dropdown label="Category" value={d.category_id ?? ""} options={categoryOptions(cats)} onChange={(v) => setD({ ...d, category_id: v || null })} placeholder="Pick a category" searchable />
|
||||
</Option>
|
||||
<Option icon={Type} label="Rename" on={on.rename} set={turn("rename")}>
|
||||
<input autoFocus value={d.rename ?? ""} onChange={(e) => setD({ ...d, rename: e.target.value })} placeholder="New name, e.g. Uber" aria-label="New name" className="select" />
|
||||
</Option>
|
||||
<Option icon={Tags} label="Add tags" on={on.tags} set={turn("tags")}>
|
||||
<TagEditor value={d.add_tags ?? []} onChange={(add_tags) => setD({ ...d, add_tags })} all={allTags} autoFocus />
|
||||
</Option>
|
||||
<Option icon={EyeOff} label="Hide from totals" on={on.ignore} set={turn("ignore")} />
|
||||
<label className="flex items-center gap-3 text-sm cursor-pointer px-1 pt-2">
|
||||
<input type="checkbox" checked={applyPast} onChange={(e) => setApplyPast(e.target.checked)} className="size-4 accent-[var(--color-ink)]" />
|
||||
Also update {loading || found == null ? "past transactions" : plural(n, "past transaction")}
|
||||
</label>
|
||||
{err && <p className="text-sm text-bad px-1">{err}</p>}
|
||||
{d.id && (
|
||||
<div className="px-1 pt-2 text-sm">
|
||||
{confirmDelete
|
||||
? <span className="flex flex-wrap items-center gap-2"><span>Delete this rule? Past transactions keep their changes.</span><button type="button" onClick={remove} className="font-medium text-bad hover:opacity-70">Delete</button><button type="button" onClick={() => setConfirmDelete(false)} className="text-muted hover:text-ink">Cancel</button></span>
|
||||
: <button type="button" onClick={() => setConfirmDelete(true)} className="text-muted underline underline-offset-2 hover:text-bad">Delete rule</button>}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-5 md:p-6 pb-[max(20px,env(safe-area-inset-bottom))] md:overflow-y-auto">
|
||||
<div className="flex items-baseline justify-between gap-3 pb-3 border-b border-line">
|
||||
<span className="section-label text-ink">Transactions</span>
|
||||
<span className="text-sm text-muted tabular" aria-live="polite">{loading ? "Finding matches..." : `${n} matched`}</span>
|
||||
</div>
|
||||
{!findsSomething(draft) ? (
|
||||
<div className="flex flex-col items-center text-center gap-3 py-12 px-6 text-muted">
|
||||
<ArrowLeft size={22} className="max-md:rotate-90" />
|
||||
<p className="text-sm max-w-60"><span className="md:hidden">Pick a match above</span><span className="max-md:hidden">Pick a match on the left</span> to find transactions for your rule.</p>
|
||||
</div>
|
||||
) : loading && !found ? (
|
||||
<div className="space-y-3 py-3" aria-busy="true">{[0, 1, 2].map((i) => <div key={i} className="h-9 rounded-xl bg-line/70 animate-pulse" />)}</div>
|
||||
) : !loading && found && !found.length ? (
|
||||
<p className="text-sm text-muted py-12 text-center">No past transactions match yet.</p>
|
||||
) : (
|
||||
<ul className={loading ? "opacity-50" : ""}>
|
||||
{(found ?? []).slice(0, 100).map((t) => (
|
||||
<li key={t.id} className="flex items-center gap-3 py-2.5 border-b border-line last:border-0">
|
||||
<Merchant name={displayName(t)} logo={t.logo_url} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm truncate">{displayName(t)}</div>
|
||||
<div className="text-xs text-muted">{dayLabel(t.date)}</div>
|
||||
</div>
|
||||
<span className={`text-sm tabular ${t.amount < 0 ? "text-good" : ""}`}>{signed(t.amount, t.currency)}</span>
|
||||
</li>
|
||||
))}
|
||||
{(found?.length ?? 0) > 100 && <li className="text-xs text-muted pt-3">Showing the newest 100.</li>}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { Check } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { emptyRule, pastMatches, saveRule } from "@/components/RuleForm";
|
||||
import { plural } from "@/lib/format";
|
||||
import { validRules, type ProposedRule } from "@/lib/rules";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Row = ProposedRule & { ids: string[]; names: string[] };
|
||||
const draft = (r: ProposedRule) => emptyRule({ match: r.match, direction: r.direction, category_id: r.category_id });
|
||||
|
||||
// The AI's ```rules block: lists each rule and what it would change. Nothing saves until the user presses Apply.
|
||||
export function RuleOffer({ proposed }: { proposed: unknown[] }) {
|
||||
const router = useRouter();
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [state, setState] = useState<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
const [changed, setChanged] = useState(0);
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const { data } = await createClient().from("categories").select("id, label");
|
||||
const rules = validRules(proposed, data ?? []);
|
||||
setRows(await Promise.all(rules.map(async (r) => {
|
||||
const past = await pastMatches(draft(r));
|
||||
return { ...r, ids: past.map((t) => t.id), names: [...new Set(past.map((t) => t.custom_name || t.merchant_name || t.name))].slice(0, 3) };
|
||||
})));
|
||||
})().catch((e) => { console.error("[broke] rules:", e); setRows([]); });
|
||||
}, [proposed]);
|
||||
if (!rows?.length) return null;
|
||||
async function apply() {
|
||||
setState("saving");
|
||||
const db = createClient();
|
||||
let total = 0;
|
||||
for (const r of rows!) {
|
||||
const { error, updated } = await saveRule(draft(r), true);
|
||||
if (error) return setState("failed");
|
||||
total += updated;
|
||||
// Answered, so they leave the "to check" list.
|
||||
for (let i = 0; i < r.ids.length; i += 200) await db.from("transactions").update({ checked_at: new Date().toISOString() }).in("id", r.ids.slice(i, i + 200));
|
||||
}
|
||||
setChanged(total);
|
||||
setState("saved");
|
||||
router.refresh();
|
||||
}
|
||||
return (
|
||||
<div className="rounded-2xl border border-line p-3 space-y-3 text-sm">
|
||||
<ul className="space-y-2">
|
||||
{rows.map((r) => (
|
||||
<li key={`${r.match}-${r.direction}`}>
|
||||
<div>Name contains <span className="font-medium">"{r.match}"</span>{r.direction && <>, money {r.direction === "in" ? "coming in" : "going out"}</>} → <span className="font-medium">{r.category}</span></div>
|
||||
<div className="text-xs text-muted">{r.ids.length ? `${plural(r.ids.length, "transaction")}: ${r.names.join(", ")}${r.ids.length > r.names.length ? "..." : ""}` : "Nothing yet. It applies to new transactions."}</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button onClick={apply} disabled={state === "saving" || state === "saved"} className="btn !py-1 text-sm inline-flex items-center gap-1.5">
|
||||
{state === "saved" ? <><Check size={14} />Saved. {plural(changed, "transaction")} changed</> : state === "saving" ? "Saving..." : state === "failed" ? "Couldn't save. Try again" : rows.length > 1 ? `Apply ${rows.length} rules` : "Apply this rule"}
|
||||
</button>
|
||||
<p className="text-xs text-muted">New transactions follow these too. You can edit or remove rules in Settings.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronRight, EyeOff, Plus } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Fragment, useState } from "react";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { emptyRule, RuleDialog, type Draft } from "@/components/RuleForm";
|
||||
import { toast } from "@/components/Toast";
|
||||
import type { Category } from "@/lib/data";
|
||||
import { plural } from "@/lib/format";
|
||||
import { conditions, describeMatch, type Rule } from "@/lib/rules";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
const pill = "inline-flex items-center gap-1.5 rounded-full bg-canvas border border-line px-3 py-1 text-xs text-muted";
|
||||
|
||||
export function RulesManager({ rules, counts, cats, allTags, accounts, missing }: {
|
||||
rules: Rule[]; counts: Record<string, number>; cats: Category[]; allTags: string[]; accounts: { id: string; label: string }[]; missing: boolean;
|
||||
}) {
|
||||
const { money, money0 } = useMoney();
|
||||
const router = useRouter();
|
||||
const [editing, setEditing] = useState<Draft | null>(null);
|
||||
const [resetting, setResetting] = useState(false);
|
||||
const done = (msg: string) => {
|
||||
setEditing(null);
|
||||
toast(msg);
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
async function resetAll() {
|
||||
const db = createClient();
|
||||
const uid = (await db.auth.getSession()).data.session?.user.id;
|
||||
const { error } = uid ? await db.from("rules").delete().eq("user_id", uid) : { error: true };
|
||||
setResetting(false);
|
||||
if (error) return toast("Couldn't reset your rules.");
|
||||
toast("All rules deleted. Past transactions keep their changes.");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-start justify-between gap-4 px-1">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold tracking-[-0.02em]">Transaction rules</h2>
|
||||
<p className="text-sm text-muted mt-1">Change categories, names and more on matching transactions automatically. New ones from your bank follow these as they arrive.</p>
|
||||
</div>
|
||||
{!missing && <button onClick={() => setEditing(emptyRule())} className="btn-primary shrink-0 inline-flex items-center gap-1.5"><Plus size={16} /> Add rule</button>}
|
||||
</div>
|
||||
{missing && <p className="text-sm text-bad px-1">Rules need a database update. Open Setup to run it.</p>}
|
||||
|
||||
{!!rules.length && (
|
||||
<div className="space-y-3">
|
||||
{rules.map((r) => {
|
||||
const cat = cats.find((c) => c.id === r.category_id);
|
||||
const fmt = (n: number) => (Number.isInteger(n) ? money0(n) : money(n));
|
||||
const acct = accounts.find((a) => a.id === r.account_id)?.label;
|
||||
const conds = conditions(r, fmt, acct);
|
||||
return (
|
||||
<button key={r.id} onClick={() => setEditing({ ...r })} aria-label={`Edit rule: ${describeMatch(r, fmt, acct)}`}
|
||||
className="card-link w-full text-left flex items-center gap-4 px-5 py-4">
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div>
|
||||
<div className="text-[15px] leading-snug">
|
||||
{conds.map((c, i) => (
|
||||
<Fragment key={c.label}>
|
||||
{i ? `, ${c.label[0].toLowerCase()}${c.label.slice(1)} ` : `${c.label} `}
|
||||
<span className="font-semibold text-brand break-words">{c.value}</span>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-sm text-muted tabular mt-0.5">{plural(counts[r.id] ?? 0, "matching transaction")}</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{cat && <span className={pill}><CategoryIcon icon={cat.icon} color={cat.color} size={16} />Change category to <span className="text-ink font-medium">{cat.label}</span></span>}
|
||||
{r.rename && <span className={pill}>Rename to <span className="text-ink font-medium">{r.rename}</span></span>}
|
||||
{!!r.add_tags?.length && <span className={pill}>Add {r.add_tags.length === 1 ? "tag" : "tags"} <span className="text-ink font-medium">{r.add_tags.join(", ")}</span></span>}
|
||||
{r.ignore && <span className={pill}><EyeOff size={12} /> Hide from totals</span>}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight size={18} className="text-muted shrink-0" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!rules.length && !missing && (
|
||||
<section className="card p-10 text-center space-y-1">
|
||||
<div className="font-medium">No rules yet</div>
|
||||
<p className="text-sm text-muted">Change a transaction's category and press Always, or add one here.</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{!!rules.length && (
|
||||
<div className="px-1 text-sm text-muted" aria-live="polite">
|
||||
{resetting ? (
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span>Delete all {plural(rules.length, "rule")}? Past transactions keep their changes.</span>
|
||||
<button onClick={resetAll} className="font-medium text-bad hover:opacity-70">Delete all</button>
|
||||
<button onClick={() => setResetting(false)} className="hover:text-ink">Cancel</button>
|
||||
</span>
|
||||
) : (
|
||||
<>Looking to start over? <button onClick={() => setResetting(true)} className="text-ink underline underline-offset-2 hover:opacity-70">Reset all rules.</button></>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing && <RuleDialog initial={editing} cats={cats} allTags={allTags} onClose={() => setEditing(null)} onDone={done} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
export function SignOut() {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<button
|
||||
className="btn text-xs"
|
||||
onClick={async () => {
|
||||
await createClient().auth.signOut();
|
||||
router.push("/login");
|
||||
}}
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { dateLabel, money } from "@/lib/format";
|
||||
import type { Alert } from "@/lib/subscriptions";
|
||||
|
||||
const short = (iso: string) => dateLabel(iso, { month: "short", day: "numeric" });
|
||||
|
||||
// ["Spotify", "Apple Music", "Spotify"] -> "Spotify (2), Apple Music"
|
||||
const counted = (names: string[]) =>
|
||||
[...new Set(names)].map((n) => { const k = names.filter((x) => x === n).length; return k > 1 ? `${n} (${k})` : n; }).join(", ");
|
||||
|
||||
export function SubscriptionAlerts({ alerts }: { alerts: Alert[] }) {
|
||||
if (!alerts.length) return null;
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="section-label px-1">Heads up</div>
|
||||
<section className="card overflow-hidden">
|
||||
{alerts.map((a, i) => (
|
||||
<div key={i} className="flex items-start gap-3 px-6 py-4 border-b border-line last:border-0">
|
||||
<span className="mt-1.5 size-2 rounded-full bg-bad shrink-0" />
|
||||
{a.kind === "price_hike" ? (
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{a.merchant} went up</span> from <span className="tabular">{money(a.from)}</span> to{" "}
|
||||
<span className="tabular font-medium">{money(a.to)}</span> on {short(a.date)}. That is <span className="tabular">{money(a.to - a.from)}</span> more each charge.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">You pay for {a.merchants.length} {a.group} subscriptions</span>
|
||||
{a.same ? "" : `: ${counted(a.merchants)}`}. Together <span className="tabular font-medium">{money(a.monthly)}</span> a month.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { Tag as TagIcon, X } from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { mergeTags } from "@/lib/rules";
|
||||
|
||||
// Each tag keeps one colour, picked from its name.
|
||||
const DOTS = ["#4f6bed", "#0f9d76", "#d9822b", "#c2417e", "#7c5cd6", "#2b9bd9", "#b5523b", "#5b8a2b"];
|
||||
const dot = (t: string) => DOTS[[...t.toLowerCase()].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % DOTS.length];
|
||||
|
||||
export function TagChip({ tag, onRemove }: { tag: string; onRemove?: () => void }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full border border-line bg-surface pl-2 pr-2 py-0.5 text-xs text-ink whitespace-nowrap">
|
||||
<span className="size-1.5 rounded-full" style={{ background: dot(tag) }} />
|
||||
{tag}
|
||||
{onRemove && (
|
||||
<button type="button" aria-label={`Remove tag ${tag}`} onClick={onRemove} className="-mr-1 p-0.5 rounded-full text-muted hover:text-ink hover:bg-[var(--hover)]">
|
||||
<X size={11} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Chips plus an input: Enter or comma adds what's typed, suggestions add with one tap. */
|
||||
export function TagEditor({ value, onChange, all, autoFocus }: { value: string[]; onChange: (tags: string[]) => void; all: string[]; autoFocus?: boolean }) {
|
||||
const [text, setText] = useState("");
|
||||
const add = (t: string) => {
|
||||
onChange(mergeTags(value, [t]));
|
||||
setText("");
|
||||
};
|
||||
const has = (t: string) => value.some((v) => v.toLowerCase() === t.toLowerCase());
|
||||
const suggestions = all.filter((t) => !has(t) && t.toLowerCase().includes(text.trim().toLowerCase())).slice(0, 8);
|
||||
const typedIsNew = !!text.trim() && !has(text) && !all.some((t) => t.toLowerCase() === text.trim().toLowerCase());
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex flex-wrap items-center gap-1.5 bg-surface border border-line rounded-xl px-2.5 py-2 focus-within:border-ink">
|
||||
{value.map((t) => <TagChip key={t} tag={t} onRemove={() => onChange(value.filter((v) => v !== t))} />)}
|
||||
<input
|
||||
autoFocus={autoFocus}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value.replace(",", ""))}
|
||||
onKeyDown={(e) => {
|
||||
if ((e.key === "Enter" || e.key === ",") && text.trim()) {
|
||||
e.preventDefault();
|
||||
add(text);
|
||||
} else if (e.key === "Backspace" && !text && value.length) onChange(value.slice(0, -1));
|
||||
}}
|
||||
placeholder={value.length ? "" : "Add a tag"}
|
||||
aria-label="Add a tag"
|
||||
className="flex-1 min-w-24 bg-transparent text-sm outline-none focus-visible:outline-none py-0.5"
|
||||
/>
|
||||
</div>
|
||||
{(!!suggestions.length || typedIsNew) && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{typedIsNew && (
|
||||
<button type="button" onClick={() => add(text)} className="text-xs rounded-full px-2.5 py-1 bg-ink text-white hover:opacity-85">Create "{text.trim()}"</button>
|
||||
)}
|
||||
{suggestions.map((t) => (
|
||||
<button key={t} type="button" onClick={() => add(t)} className="rounded-full hover:opacity-70"><TagChip tag={t} /></button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A tag button that opens the editor in a popover. Saves when it closes, so one edit is one write. */
|
||||
export function TagButton({ tags, all, label, onSave }: { tags: string[]; all: string[]; label: string; onSave: (tags: string[]) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [draft, setDraft] = useState(tags);
|
||||
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
|
||||
const button = useRef<HTMLButtonElement>(null);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const draftRef = useRef(draft);
|
||||
draftRef.current = draft;
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
const next = draftRef.current;
|
||||
if (next.join("\u0000") !== tags.join("\u0000")) onSave(next);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !button.current) return;
|
||||
const r = button.current.getBoundingClientRect();
|
||||
setPos({ top: Math.min(r.bottom + 8, innerHeight - 220), left: Math.max(8, Math.min(r.right - 300, innerWidth - 308)) });
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const out = (e: PointerEvent) => !box.current?.contains(e.target as Node) && !button.current?.contains(e.target as Node) && close();
|
||||
const esc = (e: KeyboardEvent) => e.key === "Escape" && (close(), button.current?.focus());
|
||||
document.addEventListener("pointerdown", out);
|
||||
addEventListener("keydown", esc);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", out);
|
||||
removeEventListener("keydown", esc);
|
||||
};
|
||||
}); // re-binds each render so close() sees the latest tags
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={button}
|
||||
type="button"
|
||||
title="Tags"
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
onClick={() => (open ? close() : (setDraft(tags), setOpen(true)))}
|
||||
className={`p-2.5 rounded-lg hover:bg-[var(--hover)] ${tags.length ? "text-ink" : "hover:text-ink"}`}
|
||||
>
|
||||
<TagIcon size={17} />
|
||||
</button>
|
||||
{open && pos && createPortal(
|
||||
<div ref={box} style={pos} className="fixed z-[60] w-[300px] bg-surface border border-line rounded-2xl shadow-[0_16px_40px_-12px_#00000040] p-3 text-left font-normal text-ink">
|
||||
<TagEditor value={draft} onChange={setDraft} all={all} autoFocus />
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
type T = { id: number; text: string; undo?: () => void; action?: { label: string; run: () => void } };
|
||||
let push: (t: Omit<T, "id">) => void = () => {};
|
||||
|
||||
// Confirms an edit and offers Undo (and one more action) for 5 s. Call from anywhere on the client.
|
||||
export const toast = (text: string, undo?: () => void, action?: T["action"]) => push({ text, undo, action });
|
||||
|
||||
// An open modal dialog makes the rest of the page inert, so toasts render inside the top one.
|
||||
let hosts: HTMLElement[] = [];
|
||||
let setHost: (h: HTMLElement | null) => void = () => {};
|
||||
export function toastHost(el: HTMLElement) {
|
||||
hosts = [...hosts, el];
|
||||
setHost(el);
|
||||
return () => {
|
||||
hosts = hosts.filter((h) => h !== el);
|
||||
setHost(hosts.at(-1) ?? null);
|
||||
};
|
||||
}
|
||||
|
||||
export function Toaster() {
|
||||
const [items, setItems] = useState<T[]>([]);
|
||||
const [host, setH] = useState<HTMLElement | null>(null);
|
||||
useEffect(() => {
|
||||
let n = 0;
|
||||
const drop = (id: number) => setItems((xs) => xs.filter((x) => x.id !== id));
|
||||
// Stays while hovered or focused, so keyboard users and slow readers can reach Undo.
|
||||
const expire = (id: number): unknown => setTimeout(() => (document.querySelector(`[data-toast="${id}"]:is(:hover, :focus-within)`) ? expire(id) : drop(id)), 5000);
|
||||
push = (t) => {
|
||||
const id = ++n;
|
||||
setItems((xs) => [...xs.slice(-2), { ...t, id }]);
|
||||
expire(id);
|
||||
};
|
||||
setHost = setH;
|
||||
setH(hosts.at(-1) ?? null);
|
||||
return () => {
|
||||
push = () => {};
|
||||
setHost = () => {};
|
||||
};
|
||||
}, []);
|
||||
const done = (t: T, run: () => void) => {
|
||||
run();
|
||||
setItems((xs) => xs.filter((x) => x.id !== t.id));
|
||||
};
|
||||
const region = (
|
||||
<div role="status" aria-live="polite" className="fixed z-50 left-1/2 -translate-x-1/2 bottom-24 md:bottom-6 w-max max-w-[calc(100vw-32px)] flex flex-col items-center gap-2 pointer-events-none">
|
||||
{items.map((t) => (
|
||||
<div key={t.id} data-toast={t.id} className="pointer-events-auto flex items-center gap-4 bg-[#141414] text-white ring-1 ring-white/10 text-sm rounded-full pl-5 pr-2 py-2 shadow-[0_12px_30px_-10px_#00000066] animate-[fade_.15s_ease-out]">
|
||||
{t.text}
|
||||
{t.action && (
|
||||
<button type="button" onClick={() => done(t, t.action!.run)} className="rounded-full px-3 py-1 font-medium text-[#b9c6f8] hover:bg-white/10">
|
||||
{t.action.label}
|
||||
</button>
|
||||
)}
|
||||
{t.undo ? (
|
||||
<button type="button" onClick={() => done(t, t.undo!)} className="rounded-full px-3 py-1 font-medium text-[#b9c6f8] hover:bg-white/10">
|
||||
Undo
|
||||
</button>
|
||||
) : (
|
||||
<span className="w-2" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return host ? createPortal(region, host) : region;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { displayName, type Txn } from "@/lib/data";
|
||||
import { dateLabel, homeCurrency, money, signed } from "@/lib/format";
|
||||
import { pairTransfers } from "@/lib/transfers";
|
||||
|
||||
const fullDate = (iso: string) => dateLabel(iso, { month: "short", day: "numeric", year: "numeric" });
|
||||
|
||||
// Transactions grouped under a grey date band with that day's spend total (left out when the day mixes currencies).
|
||||
// today: the user's date. A row dated after it (Plaid dates in UTC) goes under today, never under a future day.
|
||||
export function TxnList({ txns, today }: { txns: Txn[]; today: string }) {
|
||||
const days = new Map<string, Txn[]>();
|
||||
const pairs = pairTransfers(txns); // a card payment shows once, on the account it left
|
||||
for (const t of txns.filter((x) => !pairs.hidden.has(x.id))) {
|
||||
const d = t.date > today ? today : t.date;
|
||||
days.set(d, [...(days.get(d) ?? []), t]);
|
||||
}
|
||||
const home = homeCurrency();
|
||||
const curOf = (list: Txn[]) => { const c = new Set(list.map((t) => t.currency ?? home)); return c.size === 1 ? [...c][0] : null; };
|
||||
return (
|
||||
<div>
|
||||
{[...days].map(([date, list]) => (
|
||||
<div key={date}>
|
||||
<div className="flex justify-between bg-canvas/70 px-6 py-2.5 text-xs text-muted">
|
||||
<span className="text-ink">{fullDate(date)}</span>
|
||||
{curOf(list) && <span className="tabular">{money(list.filter((t) => t.amount > 0).reduce((s, t) => s + t.amount, 0), curOf(list))}</span>}
|
||||
</div>
|
||||
{list.map((t) => (
|
||||
<Link key={t.id} href={`/transactions?q=${encodeURIComponent(displayName(t))}`} className="flex items-center gap-4 px-4 @lg:px-6 py-3 border-b border-line last:border-0 row-hover group">
|
||||
<Merchant name={displayName(t)} logo={t.logo_url} color={t.category?.color} icon={t.category?.icon} />
|
||||
<span className="flex-1 min-w-0 truncate">{displayName(t)}{t.pending && <span className="text-xs text-muted"> · Pending</span>}{pairs.to.has(t.id) && <span className="text-xs text-muted"> · To {pairs.to.get(t.id)}</span>}</span>
|
||||
<span className="hidden @lg:block"><CategoryIcon icon={t.category?.icon} color={t.category?.color} /></span>
|
||||
<span className={`w-24 text-right tabular font-medium ${t.amount < 0 ? "text-good" : ""}`}>{signed(t.amount, t.currency)}</span>
|
||||
<span className="size-8 rounded-full border border-line hidden @lg:grid place-items-center text-muted transition-all duration-150 group-hover:border-ink group-hover:text-ink group-hover:translate-x-0.5"><ChevronRight size={16} /></span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
"use client";
|
||||
|
||||
import { Ban, NotebookPen, Trash2, Wand2, X } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRef, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
import { CategoryIcon } from "@/components/Icons";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { Modal } from "@/components/Modal";
|
||||
import { categoryOptions, emptyRule, RuleDialog, type Draft } from "@/components/RuleForm";
|
||||
import { TagButton, TagChip, TagEditor } from "@/components/Tags";
|
||||
import { toast } from "@/components/Toast";
|
||||
import type { Category, Txn } from "@/lib/data";
|
||||
import { displayName } from "@/lib/format";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
type Patch = Partial<Pick<Txn, "category_id" | "note" | "ignored" | "tags">> & { checked_at?: string };
|
||||
|
||||
export function TxnRow({ t, cats, allTags = [], to }: { t: Txn; cats: Category[]; allTags?: string[]; to?: string }) {
|
||||
const { dayLabel, dateLabel, signed } = useMoney();
|
||||
const router = useRouter();
|
||||
const [ignored, setIgnored] = useState(t.ignored);
|
||||
const [noteOpen, setNoteOpen] = useState(!!t.note);
|
||||
const [catId, setCatId] = useState(t.category_id ?? "");
|
||||
const [sheet, setSheet] = useState(false);
|
||||
const [rule, setRule] = useState<Draft | null>(null);
|
||||
const [tags, setTags] = useState(t.tags ?? []);
|
||||
const actions = useRef<HTMLTableCellElement>(null);
|
||||
const name = displayName(t);
|
||||
// A partner's shared row is read-only here: RLS lets you see it, not change it.
|
||||
const mine = !t.account?.owner_label;
|
||||
const cat = cats.find((c) => c.id === catId);
|
||||
const label = (id: string) => cats.find((c) => c.id === id)?.label ?? "Uncategorized";
|
||||
const options = [{ value: "", label: "Uncategorized", icon: <CategoryIcon size={26} /> }, ...categoryOptions(cats)];
|
||||
// A new rule starts from this merchant ("Uber", not "UBER *TRIP 8812") and the category it has now.
|
||||
const newRule = (category_id = catId) => setRule(emptyRule({ match: t.merchant_name ?? t.name, category_id: category_id || null }));
|
||||
const ruleLink = (
|
||||
<button type="button" onClick={() => newRule()} className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm hover:bg-[var(--hover)]">
|
||||
<Wand2 size={16} className="text-muted" /> Create a rule for {t.merchant_name ?? name}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Optimistic: the screen and the toast change at once, the write runs behind it, and a failure puts it back.
|
||||
// Only edits that change totals re-render the page from the server. RLS blocks with 0 rows, not an error.
|
||||
function save(patch: Patch, rollback: () => void, refresh = false) {
|
||||
createClient().from("transactions").update(patch).eq("id", t.id).select("id").then(({ data, error }) => {
|
||||
if (error || !data?.length) {
|
||||
rollback();
|
||||
toast("Couldn't save that. Try again.");
|
||||
} else if (refresh) router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
function setCategory(next: string) {
|
||||
const prev = catId;
|
||||
setCatId(next);
|
||||
// A category picked by hand is a checked one: "Is this right?" stops asking about it (checked_at, 0023).
|
||||
save({ category_id: next || null, checked_at: new Date().toISOString() }, () => setCatId(prev));
|
||||
toast(
|
||||
`${name} moved to ${label(next)}`,
|
||||
() => {
|
||||
setCatId(prev);
|
||||
save({ category_id: prev || null }, () => setCatId(next));
|
||||
},
|
||||
next ? { label: "Always", run: () => newRule(next) } : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
function saveTags(next: string[]) {
|
||||
const prev = tags;
|
||||
setTags(next);
|
||||
save({ tags: next }, () => setTags(prev));
|
||||
toast(next.length ? `Tags saved for ${name}` : `Tags removed from ${name}`, () => {
|
||||
setTags(prev);
|
||||
save({ tags: prev }, () => setTags(next));
|
||||
});
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
const { data, error } = await createClient().from("transactions").delete().eq("id", t.id).select("id");
|
||||
if (error || !data?.length) return toast("Couldn't delete that.");
|
||||
setSheet(false);
|
||||
toast(`${name} deleted`);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
function toggleIgnore() {
|
||||
const next = !ignored;
|
||||
setIgnored(next);
|
||||
save({ ignored: next }, () => setIgnored(!next), true);
|
||||
toast(next ? `${name} hidden from totals` : `${name} counted again`, () => {
|
||||
setIgnored(!next);
|
||||
save({ ignored: !next }, () => setIgnored(next), true);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// On narrow layouts the category and action columns are hidden, so tapping the row opens a sheet instead.
|
||||
const narrow = () => !!actions.current && getComputedStyle(actions.current).display === "none";
|
||||
|
||||
return (
|
||||
<tr
|
||||
onClick={(e) => narrow() && !(e.target as HTMLElement).closest("input,button,select") && setSheet(true)}
|
||||
className={`row-hover border-b border-line last:border-0 ${ignored ? "text-muted" : ""}`}
|
||||
>
|
||||
<td className="pl-4 @2xl:pl-6 pr-2 py-3 tabular">{dateLabel(t.date, { month: "numeric", day: "numeric" })}</td>
|
||||
<td className="px-2 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Merchant name={name} logo={t.logo_url} color={cat?.color} icon={cat?.icon} />
|
||||
<div className="min-w-0">
|
||||
<div className="truncate max-w-28 @md:max-w-48 @2xl:max-w-72">{name}</div>
|
||||
{to && <div className="text-xs text-muted">To {to}</div>}
|
||||
{(t.pending || t.manual) && <div className="text-xs text-muted">{t.pending ? "Pending" : mine ? "Added by you" : `Added by ${t.account?.owner_label}`}</div>}
|
||||
{!!tags.length && <div className="flex flex-wrap gap-1 mt-1">{tags.map((g) => <TagChip key={g} tag={g} />)}</div>}
|
||||
{!mine && t.note && <div className="mt-1 text-xs text-muted">{t.note}</div>}
|
||||
{mine && noteOpen && (
|
||||
<input
|
||||
defaultValue={t.note ?? ""}
|
||||
autoFocus={!t.note}
|
||||
placeholder="Add a note"
|
||||
aria-label={`Note for ${name}`}
|
||||
onBlur={(e) => e.target.value !== (t.note ?? "") && (save({ note: e.target.value || null }, () => {}), toast("Note saved"))}
|
||||
className="mt-1 text-xs border-b border-line focus:border-ink w-56 bg-transparent"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-2 py-3 hidden @2xl:table-cell">
|
||||
{mine ? <Dropdown
|
||||
variant="inline"
|
||||
label={`Category for ${name}`}
|
||||
value={catId}
|
||||
options={options.map((o) => (o.value === catId ? { ...o, icon: <CategoryIcon icon={cat?.icon} color={cat?.color} size={30} /> } : o))}
|
||||
onChange={setCategory}
|
||||
searchable
|
||||
footer={ruleLink}
|
||||
/> : <span className="inline-flex items-center gap-2.5"><CategoryIcon icon={cat?.icon} color={cat?.color} size={30} />{label(catId)}</span>}
|
||||
{rule && <RuleDialog initial={rule} cats={cats} allTags={allTags} onClose={() => setRule(null)} onDone={(msg) => { setRule(null); toast(msg); router.refresh(); }} />}
|
||||
</td>
|
||||
<td ref={actions} className="px-2 py-3 hidden @2xl:table-cell">
|
||||
{mine && <div className="flex gap-1 text-muted">
|
||||
<TagButton tags={tags} all={allTags} label={`Tags for ${name}`} onSave={saveTags} />
|
||||
<button title="Add a note" aria-label={`Add a note to ${name}`} onClick={() => setNoteOpen(true)} className={`p-2.5 rounded-lg hover:bg-[var(--hover)] hover:text-ink ${t.note ? "text-ink" : ""}`}><NotebookPen size={17} /></button>
|
||||
<button
|
||||
title={ignored ? "Count in totals again" : "Hide from totals"}
|
||||
aria-label={ignored ? `Count ${name} in totals again` : `Hide ${name} from totals`}
|
||||
aria-pressed={ignored}
|
||||
onClick={toggleIgnore}
|
||||
className={`p-2.5 rounded-lg hover:bg-[var(--hover)] ${ignored ? "text-bad" : "hover:text-ink"}`}
|
||||
>
|
||||
<Ban size={17} />
|
||||
</button>
|
||||
{t.manual && <button title="Delete" aria-label={`Delete ${name}`} onClick={remove} className="p-2.5 rounded-lg hover:bg-[var(--hover)] hover:text-bad"><Trash2 size={17} /></button>}
|
||||
</div>}
|
||||
</td>
|
||||
<td className={`pl-2 pr-4 @2xl:pr-6 py-3 text-right tabular font-medium whitespace-nowrap ${t.amount < 0 ? "text-good" : ""} ${ignored ? "line-through text-muted" : ""}`}>
|
||||
{signed(t.amount, t.currency)}
|
||||
{sheet && renderSheet()}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
|
||||
// A plain render function, not a component, so the inputs keep focus across re-renders.
|
||||
function renderSheet() {
|
||||
return (
|
||||
<Modal label={name} onClose={() => setSheet(false)} sheet className="space-y-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Merchant name={name} logo={t.logo_url} color={cat?.color} icon={cat?.icon} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium truncate">{name}</div>
|
||||
<div className="text-xs text-muted">{dayLabel(t.date)}{t.account ? ` · ${t.account.name}${t.account.owner_label ? ` (${t.account.owner_label})` : ""}` : ""}</div>
|
||||
</div>
|
||||
<span className={`tabular font-semibold ${t.amount < 0 ? "text-good" : ""}`}>{signed(t.amount, t.currency)}</span>
|
||||
<button type="button" aria-label="Close" onClick={() => setSheet(false)} className="p-2.5 -mr-2 rounded-full hover:bg-[var(--hover)]"><X size={18} /></button>
|
||||
</div>
|
||||
{mine ? (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Category</span>
|
||||
<Dropdown label="Category" value={catId} options={options} onChange={setCategory} placeholder="Uncategorized" searchable footer={ruleLink} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="block text-sm font-medium">Tags</span>
|
||||
<TagEditor value={tags} onChange={saveTags} all={allTags} />
|
||||
</div>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">Note</span>
|
||||
<input
|
||||
defaultValue={t.note ?? ""}
|
||||
placeholder="Add a note"
|
||||
onBlur={(e) => e.target.value !== (t.note ?? "") && (save({ note: e.target.value || null }, () => {}), toast("Note saved"))}
|
||||
className="select"
|
||||
/>
|
||||
</label>
|
||||
<button onClick={toggleIgnore} className="btn w-full !py-2.5">{ignored ? "Count in totals again" : "Hide from totals"}</button>
|
||||
{t.manual && <button onClick={remove} className="btn w-full !py-2.5 text-bad">Delete transaction</button>}
|
||||
</>
|
||||
) : (
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="flex items-center gap-2.5"><CategoryIcon icon={cat?.icon} color={cat?.color} size={26} />{label(catId)}</div>
|
||||
{!!tags.length && <div className="flex flex-wrap gap-1">{tags.map((g) => <TagChip key={g} tag={g} />)}</div>}
|
||||
{t.note && <p className="text-muted">{t.note}</p>}
|
||||
<p className="text-xs text-muted">Shared by {t.account?.owner_label}. Only they can edit it.</p>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { CardArt } from "@/components/CardArt";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { CAT_LABEL, whichCard, type Card, type Cat } from "@/lib/cards";
|
||||
import { money0 } from "@/lib/format";
|
||||
|
||||
const rateText = (c: Card, rate: number) => (c.currency === "cash back" ? `${rate}%` : `${rate}x`);
|
||||
// "3x dining, travel and gas & transport; 1x everything else"
|
||||
const earnLine = (c: Card) => {
|
||||
const by = new Map<number, string[]>();
|
||||
for (const [cat, e] of Object.entries(c.earn) as [Cat, { rate: number }][]) if (cat !== "other") by.set(e.rate, [...(by.get(e.rate) ?? []), CAT_LABEL[cat].toLowerCase()]);
|
||||
const parts = [...by].sort((a, b) => b[0] - a[0]).map(([r, cats]) => `${rateText(c, r)} ${cats.join(", ")}`);
|
||||
return [...parts, `${rateText(c, c.earn.other.rate)} ${parts.length ? "everything else" : "on everything"}`].join(" · ");
|
||||
};
|
||||
|
||||
// The cards the user holds, and which one to pay with for each kind of spending. From their linked card accounts.
|
||||
export function YourCards({ mine, spend }: { mine: { name: string; mask: string | null; card: Card | null }[]; spend: Record<Cat, number> }) {
|
||||
if (!mine.length) return null;
|
||||
const known = [...new Map(mine.filter((m) => m.card).map((m) => [m.card!.id, m.card!])).values()];
|
||||
const pick = whichCard(known).filter((p) => spend[p.cat] > 0 || p.rate > 1).sort((a, b) => (spend[b.cat] ?? 0) - (spend[a.cat] ?? 0));
|
||||
const allSame = pick.length > 0 && pick.every((p) => !p.tie) && new Set(pick.map((p) => p.card.id)).size === 1;
|
||||
return (
|
||||
<section className="card p-6 space-y-5">
|
||||
<div className="card-title">Your cards</div>
|
||||
<ul className="space-y-4">
|
||||
{mine.map((m, i) => (
|
||||
<li key={i} className="flex items-center gap-4">
|
||||
{m.card ? <CardArt card={m.card} w="w-20" /> : <span className="w-20 grid place-items-center"><Merchant name={m.name} /></span>}
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium">{m.card ? (m.card.name.startsWith(m.card.issuer) ? m.card.name : `${m.card.issuer} ${m.card.name}`) : m.name}{m.mask && <span className="text-muted font-normal"> ··{m.mask}</span>}</div>
|
||||
<div className="text-sm text-muted">{m.card ? `${earnLine(m.card)}${m.card.fee ? ` · ${money0(m.card.fee)} a year` : " · No annual fee"}` : "broke doesn't know this card's rewards yet."}</div>
|
||||
{m.card?.notes[0] && <div className="text-xs text-muted">{m.card.notes[0].replace(/ Not counted[^.]*\./, "")}</div>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{pick.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="font-medium">Which card to use</div>
|
||||
{allSame ? (
|
||||
<p className="text-sm text-muted">Your {pick[0].card.name} earns the most on everything.</p>
|
||||
) : (
|
||||
<table className="w-full text-sm tabular">
|
||||
<thead><tr className="text-left text-muted"><th className="font-normal py-1.5">When you pay for</th><th className="font-normal">Use</th><th className="font-normal text-right">Earns</th><th className="font-normal text-right">On your spend a year</th></tr></thead>
|
||||
<tbody>
|
||||
{pick.map((p) => (
|
||||
<tr key={p.cat} className="border-t border-line">
|
||||
<td className="py-1.5">{CAT_LABEL[p.cat]}</td>
|
||||
<td>{p.tie ? "Either card" : p.card.name}</td>
|
||||
<td className="text-right">{p.tie ? "Same on both" : rateText(p.card, p.rate)}</td>
|
||||
<td className="text-right">{spend[p.cat] ? money0(spend[p.cat] * p.cents) : ""}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{known.some((c) => c.id === "discover-it") && (
|
||||
<p className="text-sm text-muted">Each quarter Discover names categories that earn 5% (up to $1,500). Activate them on Discover's site, and use the Discover for those while they last.</p>
|
||||
)}
|
||||
<p className="text-xs text-muted">Pay every card in full each month. Interest costs more than any of these earn.</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { useGSAP } from "@gsap/react";
|
||||
import gsap from "gsap";
|
||||
import { useRef } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
|
||||
gsap.registerPlugin(useGSAP);
|
||||
|
||||
// Motion tokens: 0.15 / 0.3 / 0.6 s, ease-out cubic-bezier(.33,1,.68,1) ~ power2.out.
|
||||
export const EASE = "power2.out";
|
||||
// Entrance animations play once per page, not again when only the query string changes
|
||||
// (switching month, toggling bills). Module state survives client navigations.
|
||||
const introduced = new Set<string>();
|
||||
// Marked a tick later: React's dev Strict Mode runs each effect twice in a row (run, undo, run), and marking
|
||||
// on the first run made the surviving second run skip, so charts snapped to their end state instead of animating.
|
||||
export function firstVisit(key: string) {
|
||||
if (introduced.has(key)) return false;
|
||||
setTimeout(() => introduced.add(key));
|
||||
return true;
|
||||
}
|
||||
let lastPath = "";
|
||||
export function pathChanged() {
|
||||
const p = typeof window === "undefined" ? "" : window.location.pathname;
|
||||
// Not on the first page load: the animation would change elements React is still hydrating, which it flags as an error.
|
||||
const changed = !!lastPath && p !== lastPath;
|
||||
setTimeout(() => (lastPath = p)); // same Strict Mode reason as firstVisit
|
||||
return changed;
|
||||
}
|
||||
|
||||
// GSAP intros on elements that also carry CSS hover transitions: the CSS transition re-eases every frame GSAP
|
||||
// writes, which stutters. Turn transitions off for the tween, then hand the element back to CSS.
|
||||
export const withoutCssTransition = (targets: gsap.TweenTarget) => ({
|
||||
onStart: () => void gsap.set(targets, { transition: "none" }),
|
||||
onComplete: () => void gsap.set(targets, { clearProps: "transition" }),
|
||||
});
|
||||
|
||||
export const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
// Cards fade in whenever a page mounts. Kept short: the content is already there, the fade only delays reading it.
|
||||
export function Reveal({ children }: { children: React.ReactNode }) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
useGSAP(
|
||||
() => {
|
||||
if (!pathChanged() || reduced()) return;
|
||||
gsap.from(root.current!.querySelectorAll(".card, .section-label, .pill-tabs"), {
|
||||
y: 4,
|
||||
opacity: 0,
|
||||
duration: 0.18,
|
||||
ease: EASE,
|
||||
stagger: { amount: 0.06 }, // the whole stagger, however many cards
|
||||
clearProps: "transform,opacity",
|
||||
});
|
||||
},
|
||||
{ scope: root },
|
||||
);
|
||||
return <div ref={root}>{children}</div>;
|
||||
}
|
||||
|
||||
// Tweens a money figure up from 0 the first time its page shows; later visits show the value at once.
|
||||
export function CountUp({ value, format }: { value: number; format: "money" | "money0" }) {
|
||||
const el = useRef<HTMLSpanElement>(null);
|
||||
const fmt = useMoney()[format];
|
||||
useGSAP(
|
||||
() => {
|
||||
if (reduced() || !firstVisit(`count:${location.pathname}`)) return;
|
||||
const o = { n: 0 };
|
||||
gsap.to(o, { n: value, duration: 0.5, ease: "power3.out", onUpdate: () => void (el.current!.textContent = fmt(o.n)) });
|
||||
},
|
||||
{ dependencies: [value] },
|
||||
);
|
||||
return <span ref={el} className="tabular">{fmt(value)}</span>;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useId } from "react";
|
||||
|
||||
type P = { size?: number; strokeWidth?: number };
|
||||
|
||||
// Dashboard: a chunky CRT monitor with three green-LCD bar-chart bars on its screen.
|
||||
export function RetroDashboard({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}body`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
<linearGradient id={`${id}lcd`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#c8d89a" /><stop offset="1" stopColor="#9fb46a" /></linearGradient>
|
||||
<linearGradient id={`${id}gloss`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
</defs>
|
||||
<path d="M8 18h8l1.5 4h-11z" fill={`url(#${id}body)`} stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<rect x="1.5" y="2.5" width="21" height="16" rx="3.5" fill={`url(#${id}body)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="4.5" y="5.5" width="15" height="10" rx="1.5" fill={`url(#${id}lcd)`} stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M6.5 10.5h2.5v3.5h-2.5zM10.75 8.5h2.5v5.5h-2.5zM15 7h2.5v7h-2.5z" fill="#2b3315" />
|
||||
<rect x="3" y="3.2" width="18" height="5.6" rx="2.6" fill={`url(#${id}gloss)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Transactions: two chunky glossy arrows, green pointing right (money in) above red pointing left (money out).
|
||||
export function RetroTransactions({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}in`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#7fbf8f" /><stop offset="1" stopColor="#3d8a55" /></linearGradient>
|
||||
<linearGradient id={`${id}gloss`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
</defs>
|
||||
<path d="M1.5 4.8h11.5V1.5l9.5 5.3-9.5 5.3V8.8H1.5z" fill={`url(#${id}in)`} stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<path d="M22.5 15.2H11v-3.3l-9.5 5.3 9.5 5.3v-3.3h11.5z" fill="#e2492f" stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<path d="M2.3 5.5h11.4V3l6.5 3.6H2.3zM21.7 15.9H10.3v-2.5l-6.5 3.6h17.9z" fill={`url(#${id}gloss)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Spending: a glossy pie chart, blue and light blue, with the gold slice pulled out.
|
||||
export function RetroSpending({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}blue`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#8b98ff" /><stop offset="1" stopColor="#5b6cf0" /></linearGradient>
|
||||
<linearGradient id={`${id}gold`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffe680" /><stop offset="1" stopColor="#e09a12" /></linearGradient>
|
||||
<linearGradient id={`${id}gloss`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
</defs>
|
||||
<path d="M10.5 13.5L19.5 13.5A9 9 0 0 1 2.7 18Z" fill="#5b6cf0" stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<path d="M10.5 13.5L2.7 18A9 9 0 0 1 10.5 4.5Z" fill="#8b98ff" stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<path d="M12.5 11.5V2.5A9 9 0 0 1 21.5 11.5Z" fill={`url(#${id}gold)`} stroke="#b07208" strokeWidth="1" strokeLinejoin="round" />
|
||||
<ellipse cx="10" cy="8.6" rx="6" ry="3.4" fill={`url(#${id}gloss)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Budgets: a glossy blue gel wallet with a gold clasp dot and a green note peeking out.
|
||||
export function RetroBudgets({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}blue`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#8b98ff" /><stop offset="1" stopColor="#5b6cf0" /></linearGradient>
|
||||
<linearGradient id={`${id}lcd`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#c8d89a" /><stop offset="1" stopColor="#9fb46a" /></linearGradient>
|
||||
<linearGradient id={`${id}gold`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffe680" /><stop offset="1" stopColor="#e09a12" /></linearGradient>
|
||||
<linearGradient id={`${id}gloss`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
</defs>
|
||||
<rect x="4.5" y="2.5" width="12" height="7" rx="1" fill={`url(#${id}lcd)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="1.5" y="6" width="19" height="15.5" rx="3.5" fill={`url(#${id}blue)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="13.5" y="10.5" width="9" height="7" rx="2.5" fill="#5b6cf0" stroke="#20242a" strokeWidth="1" />
|
||||
<circle cx="17.2" cy="14" r="2" fill={`url(#${id}gold)`} stroke="#b07208" strokeWidth="1" />
|
||||
<rect x="3" y="7" width="16" height="5.5" rx="2.5" fill={`url(#${id}gloss)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useId } from "react";
|
||||
|
||||
type P = { size?: number; strokeWidth?: number };
|
||||
|
||||
// Recurring: a desk calendar with two binder rings and a refresh arrow on the page.
|
||||
export function RetroRecurring({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
<linearGradient id={`${id}gm`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
</defs>
|
||||
<rect x="2.5" y="4.5" width="19" height="17" rx="2.5" fill="#fff" stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M2.5 9.5V7a2.5 2.5 0 0 1 2.5-2.5h14A2.5 2.5 0 0 1 21.5 7v2.5Z" fill="#e2492f" stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M3 9V7a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2Z" fill={`url(#${id}gl)`} />
|
||||
<g fill={`url(#${id}gm)`} stroke="#20242a" strokeWidth="1"><rect x="6" y="1.5" width="2.5" height="5.5" rx="1.25" /><rect x="15.5" y="1.5" width="2.5" height="5.5" rx="1.25" /></g>
|
||||
<path d="M9 14.4A3.2 3.2 0 1 0 12 12.3" fill="none" stroke="#5b6cf0" strokeWidth="2.2" strokeLinecap="round" />
|
||||
<path d="M9.9 12.3L12.9 10v4.6Z" fill="#5b6cf0" stroke="#5b6cf0" strokeWidth="1" strokeLinejoin="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Accounts: a bank with a gold pediment roof, three columns and a base step.
|
||||
export function RetroAccounts({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
<linearGradient id={`${id}au`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffe680" /><stop offset="1" stopColor="#e09a12" /></linearGradient>
|
||||
<linearGradient id={`${id}gm`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
</defs>
|
||||
<path d="M12 1.8L22 8.6H2Z" fill={`url(#${id}au)`} stroke="#b07208" strokeWidth="1" strokeLinejoin="round" />
|
||||
<path d="M12 3L18.5 7.4H5.5Z" fill={`url(#${id}gl)`} />
|
||||
<g fill="#fff" stroke="#20242a" strokeWidth="1"><rect x="4" y="9.6" width="3.4" height="8.4" rx=".6" /><rect x="10.3" y="9.6" width="3.4" height="8.4" rx=".6" /><rect x="16.6" y="9.6" width="3.4" height="8.4" rx=".6" /></g>
|
||||
<rect x="2" y="18" width="20" height="4" rx="1" fill={`url(#${id}gm)`} stroke="#20242a" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// For you: a glowing gold glass light bulb on a gunmetal screw base.
|
||||
export function RetroForYou({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
<linearGradient id={`${id}au`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffe680" /><stop offset="1" stopColor="#e09a12" /></linearGradient>
|
||||
<linearGradient id={`${id}gm`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
<radialGradient id={`${id}glow`}><stop offset=".55" stopColor="#ffe680" stopOpacity=".7" /><stop offset="1" stopColor="#ffe680" stopOpacity="0" /></radialGradient>
|
||||
</defs>
|
||||
<circle cx="12" cy="9.5" r="10.5" fill={`url(#${id}glow)`} />
|
||||
<path d="M8.5 15.5C6 14 4.6 12 4.6 9.4a7.4 7.4 0 0 1 14.8 0c0 2.6-1.4 4.6-3.9 6.1Z" fill={`url(#${id}au)`} stroke="#b07208" strokeWidth="1" strokeLinejoin="round" />
|
||||
<ellipse cx="10" cy="6.4" rx="3.8" ry="2.6" fill={`url(#${id}gl)`} />
|
||||
<rect x="8.2" y="15.5" width="7.6" height="5.2" rx="1.2" fill={`url(#${id}gm)`} stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M8.6 18.1h6.8M10.2 21.6h3.6" stroke="#20242a" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Money plan: a gold clipboard with a gunmetal clip, white paper and two green checks.
|
||||
export function RetroMoneyPlan({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}gl`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#fff" stopOpacity=".85" /><stop offset="1" stopColor="#fff" stopOpacity=".05" /></linearGradient>
|
||||
<linearGradient id={`${id}au`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#ffe680" /><stop offset="1" stopColor="#e09a12" /></linearGradient>
|
||||
<linearGradient id={`${id}gm`} x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3b4048" /><stop offset=".5" stopColor="#7a828e" /><stop offset="1" stopColor="#3b4048" /></linearGradient>
|
||||
</defs>
|
||||
<rect x="3.5" y="3.5" width="17" height="19" rx="2.2" fill={`url(#${id}au)`} stroke="#b07208" strokeWidth="1" />
|
||||
<rect x="5.6" y="6.6" width="12.8" height="14" rx="1" fill="#fff" stroke="#20242a" strokeWidth="1" />
|
||||
<g fill="none" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7.4 11l1.6 1.6 2.8-3.1M7.4 16.6l1.6 1.6 2.8-3.1" stroke="#3d8a55" /><path d="M13.6 11.4h3M13.6 17h3" stroke="#7a828e" strokeWidth="1.6" /></g>
|
||||
<rect x="7.5" y="1.5" width="9" height="4.5" rx="1.5" fill={`url(#${id}gm)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="8.2" y="2" width="7.6" height="1.9" rx=".9" fill={`url(#${id}gl)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useId } from "react";
|
||||
|
||||
type P = { size?: number; strokeWidth?: number };
|
||||
|
||||
// Optimize: a magic wand with a big gold sparkle star.
|
||||
export function RetroOptimize({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}m`} x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stopColor="#3b4048" />
|
||||
<stop offset=".5" stopColor="#7a828e" />
|
||||
<stop offset="1" stopColor="#3b4048" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}o`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#ffe680" />
|
||||
<stop offset="1" stopColor="#e09a12" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#fff" stopOpacity=".85" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="6.2" y="8.6" width="3.8" height="15" rx="1.3" transform="rotate(45 8.1 16.1)" fill={`url(#${id}m)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="6.2" y="8.6" width="3.8" height="4" rx="1.3" transform="rotate(45 8.1 16.1)" fill="#fff" stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M15.5 1 Q16.5 7.5 23 8.5 Q16.5 9.5 15.5 16 Q14.5 9.5 8 8.5 Q14.5 7.5 15.5 1Z" fill={`url(#${id}o)`} stroke="#b07208" strokeWidth="1" />
|
||||
<ellipse cx="15.5" cy="5.5" rx="1.2" ry="3.3" fill={`url(#${id}s)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Cards: a glossy blue credit card with a gold chip and a white stripe.
|
||||
export function RetroCards({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}b`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#8b98ff" />
|
||||
<stop offset="1" stopColor="#5b6cf0" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}o`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#ffe680" />
|
||||
<stop offset="1" stopColor="#e09a12" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#fff" stopOpacity=".85" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="2" y="4.5" width="20" height="15" rx="2.5" fill={`url(#${id}b)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="4.5" y="9.5" width="5.5" height="4.5" rx="1" fill={`url(#${id}o)`} stroke="#b07208" strokeWidth="1" />
|
||||
<rect x="11.5" y="15" width="8" height="2.2" rx="1.1" fill="#fff" />
|
||||
<rect x="3" y="5.3" width="18" height="5.6" rx="2" fill={`url(#${id}s)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Ask AI: a retro robot head with an LCD face and a red-ball antenna.
|
||||
export function RetroBot({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}m`} x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stopColor="#3b4048" />
|
||||
<stop offset=".5" stopColor="#7a828e" />
|
||||
<stop offset="1" stopColor="#3b4048" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}l`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#c8d89a" />
|
||||
<stop offset="1" stopColor="#9fb46a" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#fff" stopOpacity=".85" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M12 7V3.5" stroke="#7a828e" strokeWidth="2" strokeLinecap="round" />
|
||||
<circle cx="12" cy="3.2" r="2" fill="#e2492f" stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="3" y="7" width="18" height="15" rx="3" fill={`url(#${id}m)`} stroke="#20242a" strokeWidth="1" />
|
||||
<rect x="5.5" y="10" width="13" height="9.5" rx="1.5" fill={`url(#${id}l)`} stroke="#20242a" strokeWidth="1" />
|
||||
<path d="M8 12.5h2.6v3.2H8zM13.4 12.5H16v3.2h-2.6z" fill="#2b3315" />
|
||||
<rect x="4" y="7.8" width="16" height="5" rx="2.5" fill={`url(#${id}s)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Settings: a glossy gunmetal gear with a gold centre.
|
||||
export function RetroSettings({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}m`} x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stopColor="#3b4048" />
|
||||
<stop offset=".5" stopColor="#7a828e" />
|
||||
<stop offset="1" stopColor="#3b4048" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}o`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#ffe680" />
|
||||
<stop offset="1" stopColor="#e09a12" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#fff" stopOpacity=".85" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d="M9.58 4.17 L10.14 1.16 L13.86 1.16 L14.42 4.17 L15.83 4.75 L18.35 3.02 L20.98 5.65 L19.25 8.17 L19.83 9.58 L22.84 10.14 L22.84 13.86 L19.83 14.42 L19.25 15.83 L20.98 18.35 L18.35 20.98 L15.83 19.25 L14.42 19.83 L13.86 22.84 L10.14 22.84 L9.58 19.83 L8.17 19.25 L5.65 20.98 L3.02 18.35 L4.75 15.83 L4.17 14.42 L1.16 13.86 L1.16 10.14 L4.17 9.58 L4.75 8.17 L3.02 5.65 L5.65 3.02 L8.17 4.75Z" fill={`url(#${id}m)`} stroke="#20242a" strokeWidth="1" strokeLinejoin="round" />
|
||||
<circle cx="12" cy="12" r="4" fill={`url(#${id}o)`} stroke="#b07208" strokeWidth="1" />
|
||||
<ellipse cx="12" cy="7" rx="6.5" ry="3.6" fill={`url(#${id}s)`} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// More: three glossy gunmetal gel dots, an Aqua "..." button.
|
||||
export function RetroMore({ size = 18 }: P) {
|
||||
const id = useId();
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" aria-hidden className="shrink-0">
|
||||
<defs>
|
||||
<linearGradient id={`${id}m`} x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stopColor="#3b4048" />
|
||||
<stop offset=".5" stopColor="#7a828e" />
|
||||
<stop offset="1" stopColor="#3b4048" />
|
||||
</linearGradient>
|
||||
<linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stopColor="#fff" stopOpacity=".85" />
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g fill={`url(#${id}m)`} stroke="#20242a" strokeWidth="1">
|
||||
<circle cx="5" cy="12" r="3" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<circle cx="19" cy="12" r="3" />
|
||||
</g>
|
||||
<g fill={`url(#${id}s)`}>
|
||||
<ellipse cx="5" cy="10.4" rx="1.9" ry="1.2" />
|
||||
<ellipse cx="12" cy="10.4" rx="1.9" ry="1.2" />
|
||||
<ellipse cx="19" cy="10.4" rx="1.9" ry="1.2" />
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user