From febd77e1056296ca791552e7544e0754b1778b5b Mon Sep 17 00:00:00 2001 From: minimus7 Date: Wed, 4 Nov 2026 15:10:45 -0600 Subject: [PATCH] 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 --- src/app/(app)/plan/page.tsx | 37 +--- src/components/MoneyPlan.tsx | 186 ++++++--------------- src/components/NextMove.tsx | 27 --- src/components/NextMoveCard.tsx | 91 ---------- src/components/PayoffChart.tsx | 287 -------------------------------- src/components/PlanSummary.tsx | 75 --------- src/lib/envfile.test.ts | 7 + src/lib/envfile.ts | 8 + src/lib/plan.ts | 2 +- src/lib/setup.ts | 6 +- 10 files changed, 78 insertions(+), 648 deletions(-) delete mode 100644 src/components/NextMove.tsx delete mode 100644 src/components/NextMoveCard.tsx delete mode 100644 src/components/PayoffChart.tsx delete mode 100644 src/components/PlanSummary.tsx diff --git a/src/app/(app)/plan/page.tsx b/src/app/(app)/plan/page.tsx index 22b8955..6c110df 100644 --- a/src/app/(app)/plan/page.tsx +++ b/src/app/(app)/plan/page.tsx @@ -1,18 +1,10 @@ -import { ChevronDown } from "lucide-react"; import { EmptyBank } from "@/components/EmptyBank"; -import { NextMove } from "@/components/NextMove"; import { MoneyPlan, type PlanState } from "@/components/MoneyPlan"; import { PlanChat } from "@/components/PlanChat"; import { PlanContext } from "@/components/PlanContext"; -import { PlanSummary } from "@/components/PlanSummary"; -import { BillsOnCards } from "@/components/BillsOnCards"; -import { Suspense } from "react"; -import { countryOf } from "@/lib/countries"; import { getUser, today, typicalMonthly } from "@/lib/data"; import { money0, ymd } from "@/lib/format"; -import { loadPlan, planFacts } from "@/lib/plan-facts"; -import { laterOf, type Later } from "@/lib/projection"; -import { marginalRate } from "@/lib/tax"; +import { loadPlan } from "@/lib/plan-facts"; export default async function Plan() { const { supabase, user } = await getUser(); @@ -27,14 +19,7 @@ export default async function Plan() { const meta = user!.user_metadata ?? {}; const word = (user!.email ?? "").split("@")[0].match(/[a-z]+/i)?.[0] ?? ""; const name = (meta.full_name || meta.name || (word && word[0].toUpperCase() + word.slice(1)) || "[Your name]") as string; - // The payoff chart: the tax rate turns a contribution's tax saving back into the contribution (US only, like the tax moves). - // Possible later needs the full facts, so they load only when a live move is gated or a fund is still to build. const profile = meta.profile ?? {}; - const taxRate = countryOf(profile.country).code === "US" ? marginalRate(profile).rate : null; - const live = state.moves.filter((m) => m.status === "todo" || m.status === "doing"); - let later: Later | null = null; - if (live.some((m) => m.gate || m.ref?.startsWith("fund:"))) - later = await planFacts(supabase, user!.id, profile, ymd(now)).then((f) => laterOf(f, live), (e) => { console.error("[broke] payoff facts:", e); return null; }); // The savings rate, from the old For you page: the one thing on it the plan didn't already say. const rate = typical && typical.income > 0 ? (typical.income - typical.spend) / typical.income : null; return ( @@ -45,20 +30,12 @@ export default async function Plan() { {rate >= 0 ? <>You save {Math.round(rate * 100)}% of it. : That's {money0(typical!.spend - typical!.income)} more out than in.}

)} - {/* One next move and a chat. The full plan is a click away for anyone who wants it. */} - }>
-
-
- - See the full plan - -
- }> - - - }>
-
-
+ {/* The plan, written by your AI from your accounts, then a place to talk it through. */} +
+ + + +
); } diff --git a/src/components/MoneyPlan.tsx b/src/components/MoneyPlan.tsx index 3217e7e..8cbc8a4 100644 --- a/src/components/MoneyPlan.tsx +++ b/src/components/MoneyPlan.tsx @@ -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 = { 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 = { spending: "#b07a2a", tax: "var( // The same Phosphor duotone glyphs the category icons use. const SECTION_ICON: Record = { 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 = { 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) => ( - 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) => ( + 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 ( -
-
-
+
+
+
-
{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"}
-
- {money0(yearly)} a year on the table -
-
- {once > 0 && <>Plus {money0(once)} one-time. }Saved so far: {money0(saved)} a year +
+ {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"}
+

+ {p?.summary ?? (p ? first?.title ?? "Nothing left to do." : "Get a plan for your money: what to do first, then what comes next.")} +

-
{state.running &&

{STAGES[stage]}. This takes a minute or two; you can leave the page.

} {state.error &&

{state.error}

} - {state.stale && !state.running &&

{state.stale} Run it again to use your current accounts.

} + {state.stale && !state.running &&

{state.stale} Redo it to use your current accounts.

} {!state.ready &&

The money plan needs a database update. Open Setup to apply it.

} - {p?.note && !state.running && ( -

- - {p.note} Moves built on those numbers are marked low confidence and not counted. -

- )} - {p?.summary && !state.running &&

{p.summary}

} -
+ {p?.note && !state.running &&

{p.note} Steps built on those numbers aren't counted.

} +
- {p && moves.length > 0 && !moves.some((m) => m.id === d.id)), ...moves]} today={today} rate={payoff.rate} later={payoff.later} note={p.note ?? null} />} - - {!p ? ( -
-
What the audit looks at
-
    - {LOOKS_AT.map((l) => ( -
  • {l}
  • - ))} -
-

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.

-
- ) : ( -
-
- {first && ( -
-
-
Do this first
-
Step {stepOf(first)}: {STEP_LABEL[stepOf(first)]}
-
-
{row(first, 0)}
-
- )} - {ladder.map((x) => ( -
-
-
{x.k}. {STEP_LABEL[x.k]}
- -
-
{x.ms.map(row)}
-
- ))} - {!live.length &&

{moves.length ? "Nothing left to do. Run the audit again after your next statement." : "This audit found no moves."}

} - {closed.length > 0 && ( -
- - {showDone &&
{closed.map(row)}
} -
- )} + {p && live.length > 0 && ( + <> +
+ Next steps + {yearly >= 100 && About {money0(yearly)} a year when they're done{once > 0 ? `, plus ${money0(once)} once` : ""}}
- - {timeline.length > 0 && ( -
-
Timeline
-
- {timeline.map(({ w, ms }) => ( -
-
{WHEN_LABEL[w]}
-
    - {ms.map((m) => ( -
  • - -
  • - ))} -
-
- ))} -
-
+
    {shown.map((m, i) => row(m, i, i + 1))}
+ {live.length > 5 && ( + )} + + )} + {p && !live.length &&

{moves.length ? "Nothing left to do. Redo your plan after your next statement." : "Your plan found nothing to change."}

} + + {closed.length > 0 && ( +
+ + {showDone &&
{closed.map((m, i) => row(m, i))}
}
)} -

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."}

-
+

General education, not financial advice. Amounts are estimates from your own transactions.

+
); } -function Total({ ms }: { ms: PlanMove[] }) { - const { money0 } = useMoney(); - const y = value(ms, false), o = value(ms, true); - if (!y && !o) return null; - return
{[y ? `${money0(y)} a year` : "", o ? `${money0(o)} once` : ""].filter(Boolean).join(" + ")}
; -} - -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 ( -
+
  • )} - + ); } diff --git a/src/components/NextMove.tsx b/src/components/NextMove.tsx deleted file mode 100644 index 18d16b4..0000000 --- a/src/components/NextMove.tsx +++ /dev/null @@ -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 & { 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 ( - - Your next move - Nothing left in your plan. Run the audit again after your next statement. - - ); - return ; -} diff --git a/src/components/NextMoveCard.tsx b/src/components/NextMoveCard.tsx deleted file mode 100644 index ce35cf5..0000000 --- a/src/components/NextMoveCard.tsx +++ /dev/null @@ -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> & { done_at?: string | null }; - -export function NextMoveCard({ items, looks }: { items: NextItem[]; looks: Record }) { - 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 ( -
    - Your next move - All done for now. Ask below if you want something new to work on. -
    - ); - 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 ( -
    -
    -
    Your next move
    -
    Step {m.step}: {STEP_LABEL[m.step as Step]}
    -
    -
    -

    {m.title}

    -

    {m.line}

    - {m.gate &&

    {m.gate}

    } -
    - {note && ( -
    - Looks done. {note} - -
    - )} -
      - {m.steps.map((s, i) => ( -
    1. - -
    2. - ))} -
    -
    - - {live.length > 1 && } - -
    -
    - ); -} diff --git a/src/components/PayoffChart.tsx b/src/components/PayoffChart.tsx deleted file mode 100644 index 3a1c816..0000000 --- a/src/components/PayoffChart.tsx +++ /dev/null @@ -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(5); - const [growth, setGrowth] = useState(DEFAULT_RETURN); - const [hover, setHover] = useState(null); - const svg = useRef(null); - const box = useRef(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("[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) { - 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(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 ( -
    -
    -
    What following your plan could be worth
    -
    - {HORIZONS.map((yr) => ( - - ))} -
    -
    - -
    -
    -
    {money0(end.total)} in {YEARS_LABEL(years)}
    -
    - {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.} -
    -
    - {progress.total >= 1 && since && ( -
    -
    Your progress so far
    -
    {money0(progress.total)}
    -
    Kept and invested from {doneMoves.length} done move{doneMoves.length === 1 ? "" : "s"} since {dateLabel(since, { month: "short", day: "numeric" })}
    -
    - )} -
    - -
    - setHover(null)} - onKeyDown={onKey} - onBlur={() => setHover(null)} - > - {grid.map((t) => ( - - - {compact(t)} - - ))} - {hasLater && } - {hasLater && } - - - - {h !== null && ( - - - {hasLater && } - - - )} - {tickYears.map((m, k) => ( - {tickLabel(m)} - ))} - - - {h !== null && ( -
    -
    {h === 0 ? "Today" : monthOf(h)}
    -
    Following your plan{money0(cTop[h])}
    - {hasLater &&
    Possible later+{money0(possible[h].total)}
    } -
    If nothing changes{money0(0)}
    - {growth > 0 && counted[h].growth >= 1 &&
    Of which {money0(counted[h].growth)} is growth
    } -
    - )} - -
    - Following your plan - {hasLater && Possible later} - If nothing changes -
    -
    - -
    -
    -
    In {YEARS_LABEL(years)}, by what it is
    - {hasLater &&
    Including possible later
    } -
    - -
    - -
    - {hasInvested && ( -
    - Growth on invested money -
    - {RETURNS.map((r) => ( - - ))} -
    -
    - )} -
      - {hasInvested &&
    • {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."}
    • } - {fs.some((f) => f.bucket === "savings") &&
    • Savings and your emergency fund earn {pctLabel(SAVINGS_RATE)} a year, a typical high-yield savings rate.
    • } -
    • Kept money and tax saved are counted as cash, with no growth. Invested counts the money you put in and any employer match.
    • - {hasLater && later &&
    • {laterText(later, money0)}
    • } -
    • Each value comes from a move in your plan. Moves with no dollar figure are left out.
    • -
    - {note && ( -

    - - {note} Moves built on those numbers are not counted here. -

    - )} -
    - -
    - See the numbers - - - {hasLater && } - - - {tickYears.map((m) => ( - - - - {hasLater && } - - - ))} - -
    WhenFollowing your planPossible laterOf which growth
    {tickLabel(m)}{money0(counted[m].total)}+{money0(possible[m].total)}{money0(counted[m].growth)}
    -
    -
    - ); -} - -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 ( -
    - {total >= 1 && ( -
    - {shown.map((x, i) => ( - - ))} -
    - )} -
      - {parts.map((x) => ( -
    • - - {x.label} - {money0(x.v)} -
    • - ))} -
    -
    - ); -} diff --git a/src/components/PlanSummary.tsx b/src/components/PlanSummary.tsx deleted file mode 100644 index 8264b07..0000000 --- a/src/components/PlanSummary.tsx +++ /dev/null @@ -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; - 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(); - 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 ( -
    -
    -
    Your plan
    -

    From your accounts as they are today. The full plan, with steps for each, is below.

    -
    - {groups.map((g, gi) => ( -
    -
    - {gi + 1} - {g.title} -
    -
      - {g.lines.slice(0, 5).map((l) => ( -
    • - {l.text} - {l.note && · {l.note}} -
    • - ))} -
    -
    - ))} -
    - ); -} diff --git a/src/lib/envfile.test.ts b/src/lib/envfile.test.ts index e37cd3b..588a1bc 100644 --- a/src/lib/envfile.test.ts +++ b/src/lib/envfile.test.ts @@ -41,3 +41,10 @@ assert.equal(updateEnvText("", { SUPABASE_DB_URL: "postgresql://u:p$ss#1@h:5432/ assert.equal(parseEnv(updateEnvText("", { SUPABASE_DB_URL: "postgresql://u:p$ss#1@h:5432/db" })).SUPABASE_DB_URL, "postgresql://u:p$ss#1@h:5432/db"); assert.ok(validate({ SUPABASE_DB_URL: 'postgresql://u:a"b@h/db' }).errors.SUPABASE_DB_URL); console.log("envfile: ok"); + +// The Project URL from the dashboard address, the bare ref, or the URL itself. +const REF = "macoucuuhxtmvihabcde"; +assert.equal(validate({ NEXT_PUBLIC_SUPABASE_URL: `https://supabase.com/dashboard/project/${REF}/settings/api-keys` }).clean.NEXT_PUBLIC_SUPABASE_URL, `https://${REF}.supabase.co`); +assert.equal(validate({ NEXT_PUBLIC_SUPABASE_URL: REF }).clean.NEXT_PUBLIC_SUPABASE_URL, `https://${REF}.supabase.co`); +assert.equal(validate({ NEXT_PUBLIC_SUPABASE_URL: `https://${REF}.supabase.co/` }).clean.NEXT_PUBLIC_SUPABASE_URL, `https://${REF}.supabase.co`); +assert.equal(validate({ NEXT_PUBLIC_SUPABASE_URL: "http://127.0.0.1:54321" }).clean.NEXT_PUBLIC_SUPABASE_URL, "http://127.0.0.1:54321"); diff --git a/src/lib/envfile.ts b/src/lib/envfile.ts index 53274c2..59f2d66 100644 --- a/src/lib/envfile.ts +++ b/src/lib/envfile.ts @@ -79,6 +79,13 @@ export function updateEnvText(text: string, updates: Record): st const quote = (v: string) => (/[\s#$]/.test(v) ? `"${v.replace(/\$/g, "\\$")}"` : v); // Every value is checked before anything touches the disk. Returns per-key errors. +// The Project URL is https://.supabase.co, and the ref is also in the browser's address bar on any page of the +// project in Supabase's dashboard. So that address, or the bare ref, is accepted and turned into the Project URL. +export function supabaseUrl(v: string) { + const ref = v.match(/supabase\.com\/dashboard\/project\/([a-z0-9]{20})\b/)?.[1] ?? v.match(/^([a-z0-9]{20})$/)?.[1]; + return ref ? `https://${ref}.supabase.co` : v.replace(/\/+$/, ""); +} + export function validate(updates: Record): { clean: Record; errors: Record } { const clean: Record = {}; const errors: Record = {}; @@ -89,6 +96,7 @@ export function validate(updates: Record): { clean: Record { note: sb?.ok ? (ref ? `Project ${ref}` : sb.message) : sb?.message, steps: [ ["Make a free account and project at ", { href: "https://supabase.com/dashboard/new", label: "supabase.com" }, ". Any name works. Save the database password it gives you."], - ["Copy your Project URL from ", { href: dash("/settings/api"), label: "Project Settings → Data API" }, "."], - ["Copy the publishable and secret keys from ", { href: dash("/settings/api-keys"), label: "Project Settings → API Keys" }, "."], + ["Open ", { href: dash("/settings/api-keys"), label: "Project Settings → API Keys" }, " and copy the publishable and secret keys."], + ["For the Project URL, copy the address from your browser's address bar on that page. broke works out the rest."], ["Paste all three below and press Save."], ], fields: fields(env, ["NEXT_PUBLIC_SUPABASE_URL", "NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SERVICE_ROLE_KEY"], { - NEXT_PUBLIC_SUPABASE_URL: { placeholder: "https://xxxx.supabase.co" }, + NEXT_PUBLIC_SUPABASE_URL: { placeholder: "https://supabase.com/dashboard/project/… or https://xxxx.supabase.co" }, NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: { placeholder: "sb_publishable_…" }, SUPABASE_SERVICE_ROLE_KEY: { placeholder: "sb_secret_…" }, }),