One clear money plan, and paste the Supabase page address for the Project URL
- Money plan is one card: your AI's two-sentence summary, then numbered next steps, then context and chat - Removed the next-move card, plan summary, payoff chart, timeline and bills list from the page - Setup accepts the dashboard address or project ref and works out the Project URL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f2d7f36017
commit
febd77e105
10 files changed
+78
-648
No files matched your search
+52
-134
@@ -1,15 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { Bell, CalendarDays, Check, ChevronDown, Copy, LoaderCircle, Mail, MessageSquare, Phone, TriangleAlert } from "lucide-react";
|
||||
import { Bell, CalendarDays, ChevronDown, Copy, LoaderCircle, Mail, MessageSquare, Phone } 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 { sectionOf, stepOf, type Kind, type Section, type Status } from "@/lib/plan";
|
||||
import type { PMove } from "@/lib/projection";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
type Message = { to: string; channel: "email" | "sms" | "call"; subject?: string; body: string; phone?: string };
|
||||
@@ -29,7 +28,6 @@ export type PlanState = {
|
||||
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)}`;
|
||||
@@ -80,24 +78,9 @@ const SECTION_COLOR: Record<Section, string> = { spending: "#b07a2a", tax: "var(
|
||||
// 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 } }) {
|
||||
export function MoneyPlan({ initial, today, name }: { initial: PlanState; today: string; name: string }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const [state, setState] = useState(initial);
|
||||
const [moves, setMoves] = useState(initial.moves);
|
||||
@@ -113,9 +96,7 @@ export function MoneyPlan({ initial, today, name, payoff }: { initial: PlanState
|
||||
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 ?? []);
|
||||
|
||||
@@ -133,7 +114,7 @@ export function MoneyPlan({ initial, today, name, payoff }: { initial: PlanState
|
||||
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
|
||||
router.refresh();
|
||||
}, 2000);
|
||||
};
|
||||
useEffect(() => {
|
||||
@@ -173,133 +154,70 @@ export function MoneyPlan({ initial, today, name, payoff }: { initial: PlanState
|
||||
} 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)} />
|
||||
const [all, setAll] = useState(false);
|
||||
const shown = all ? live : live.slice(0, 5);
|
||||
const row = (m: PlanMove, i: number, n?: number) => (
|
||||
<MoveRow key={m.id} m={m} n={n} 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.ref ?? "")} />
|
||||
);
|
||||
|
||||
// The plan in one card: Claude's summary of where you stand, then the next steps in order. Open a step for how to do it.
|
||||
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">
|
||||
<section className="card overflow-hidden">
|
||||
<div className="p-6 md:p-7 space-y-3">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<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 className="text-sm text-muted">
|
||||
{p ? `${p.provider ? `Written by ${PROVIDER[p.provider] ?? p.provider}` : "Built from your accounts"} on ${dateLabel(p.created_at, { month: "short", day: "numeric" })}` : "Your plan"}
|
||||
</div>
|
||||
<p className="text-xl font-semibold tracking-[-0.01em] leading-snug">
|
||||
{p?.summary ?? (p ? first?.title ?? "Nothing left to do." : "Get a plan for your money: what to do first, then what comes next.")}
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={run} disabled={state.running || !state.ready} className="btn-primary disabled:opacity-60 flex items-center gap-2">
|
||||
<button onClick={run} disabled={state.running || !state.ready} className={`${p ? "btn" : "btn-primary"} disabled:opacity-60 flex items-center gap-2 shrink-0`}>
|
||||
{state.running && <LoaderCircle size={16} className="animate-spin" />}
|
||||
{state.running ? "Auditing..." : p ? "Run again" : "Run my money audit"}
|
||||
{state.running ? "Writing..." : p ? "Redo my plan" : "Write my plan"}
|
||||
</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.stale && !state.running && <p className="text-sm text-bad">{state.stale} Redo it 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?.note && !state.running && <p className="text-sm text-muted">{p.note} Steps built on those numbers aren't counted.</p>}
|
||||
</div>
|
||||
|
||||
{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>
|
||||
)}
|
||||
{p && live.length > 0 && (
|
||||
<>
|
||||
<div className="px-6 md:px-7 pb-2 flex items-baseline justify-between gap-3">
|
||||
<span className="section-label">Next steps</span>
|
||||
{yearly >= 100 && <span className="text-sm text-muted tabular">About {money0(yearly)} a year when they're done{once > 0 ? `, plus ${money0(once)} once` : ""}</span>}
|
||||
</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>
|
||||
<ol className="border-t border-line">{shown.map((m, i) => row(m, i, i + 1))}</ol>
|
||||
{live.length > 5 && (
|
||||
<button onClick={() => setAll(!all)} className="w-full border-t border-line px-6 py-3 text-sm text-muted hover:text-ink text-left">
|
||||
{all ? "Show fewer" : `Show ${live.length - 5} more`}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{p && !live.length && <p className="px-6 md:px-7 pb-6 text-sm text-muted">{moves.length ? "Nothing left to do. Redo your plan after your next statement." : "Your plan found nothing to change."}</p>}
|
||||
|
||||
{closed.length > 0 && (
|
||||
<div className="border-t border-line">
|
||||
<button onClick={() => setShowDone(!showDone)} aria-expanded={showDone} className="w-full flex items-center justify-between gap-3 px-6 md:px-7 py-3 text-left text-sm text-muted hover:text-ink">
|
||||
<span className="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>
|
||||
{saved > 0 && <span className="tabular">Saved {money0(saved)} a year</span>}
|
||||
</button>
|
||||
{showDone && <div className="border-t border-line">{closed.map((m, i) => row(m, i))}</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>
|
||||
<p className="px-6 md:px-7 py-3 border-t border-line text-xs text-muted">General education, not financial advice. Amounts are estimates from your own transactions.</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
function MoveRow({ m, n, first, open, toggle, setStatus, setSteps, short, today, name, looksDone }: {
|
||||
m: PlanMove; n?: number; 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();
|
||||
@@ -320,9 +238,10 @@ function MoveRow({ m, first, open, toggle, setStatus, setSteps, short, today, na
|
||||
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" : ""}`}>
|
||||
<li id={`move-${m.id}`} className={`list-none 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} />
|
||||
{n ? <span className={`grid place-items-center size-7 rounded-full text-sm tabular shrink-0 ${n === 1 ? "bg-ink text-on-ink" : "border border-line text-muted"}`}>{n}</span>
|
||||
: <CategoryIcon icon={SECTION_ICON[sectionOf(m)]} color={SECTION_COLOR[sectionOf(m)]} size={28} />}
|
||||
<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>
|
||||
@@ -334,7 +253,6 @@ function MoveRow({ m, first, open, toggle, setStatus, setSteps, short, today, na
|
||||
<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>}
|
||||
@@ -406,6 +324,6 @@ function MoveRow({ m, first, open, toggle, setStatus, setSteps, short, today, na
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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} />;
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user