fire-planner/frontend/src/pages/ScenarioDetail.tsx
Viktor Barzin 60c275cd05
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was canceled
frontend: scenario create + delete (CRUD loop closes)
/scenarios/new — form posts to POST /scenarios with name, description,
jurisdiction, strategy, glide path, leave-UK year, spending, NW seed,
savings, horizon. Required-name validation; on success invalidates the
scenarios query and navigates to the new detail page.

/scenarios/:id — Delete button (user scenarios only; cartesian are
backend-protected). Browser confirm prompt + DELETE /scenarios/{id} +
invalidate + redirect to list.

api.scenarios gains create() and delete(). New ScenarioCreateBody type.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:11:54 +00:00

169 lines
5.9 KiB
TypeScript

/**
* Scenario detail — params + the latest persisted MC projection.
*
* Reuses FanChart from the What-If page. If the scenario has no MC run
* yet, prompts the user to run /recompute.
*/
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { api } from '@/api/client';
import { ApiError } from '@/api/client';
import { FanChart } from '@/components/FanChart';
import { gbp, pct } from '@/lib/format';
export function ScenarioDetail() {
const params = useParams<{ id: string }>();
const id = Number(params.id);
const navigate = useNavigate();
const qc = useQueryClient();
const scen = useQuery({
queryKey: ['scenarios', id],
queryFn: () => api.scenarios.get(id),
enabled: Number.isFinite(id),
});
const proj = useQuery({
queryKey: ['scenarios', id, 'projection'],
queryFn: () => api.scenarios.projection(id),
enabled: Number.isFinite(id),
retry: (count, err) => {
// Don't retry the 404 — it's the "no run yet" empty state.
if (err instanceof ApiError && err.status === 404) return false;
return count < 2;
},
});
const del = useMutation({
mutationFn: () => api.scenarios.delete(id),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['scenarios'] });
navigate('/scenarios');
},
});
const onDelete = () => {
if (!confirm(`Delete scenario "${scen.data?.name ?? id}"? This can't be undone.`)) return;
del.mutate();
};
if (!Number.isFinite(id)) {
return <p className="text-red-700">Invalid scenario id.</p>;
}
if (scen.isLoading) return <p className="text-slate-500">Loading</p>;
if (scen.isError || !scen.data) {
return (
<div className="rounded-md border border-red-200 bg-red-50 p-4 text-red-800 text-sm">
Couldn&apos;t load scenario {id}.
</div>
);
}
const s = scen.data;
const projection = proj.data;
const projection404 = proj.isError && proj.error instanceof ApiError && proj.error.status === 404;
return (
<section className="space-y-6">
<div className="text-sm">
<Link to="/scenarios" className="text-slate-500 hover:text-slate-900">
Scenarios
</Link>
</div>
<header className="flex items-start justify-between gap-4">
<div>
<h1 className="text-3xl font-semibold tracking-tight">{s.name ?? s.external_id}</h1>
<p className="text-sm text-slate-500 mt-1">
{s.kind} · {s.jurisdiction} · {s.strategy} · leave UK y{s.leave_uk_year} ·{' '}
{s.glide_path} glide · {s.horizon_years}y horizon
</p>
{s.description && <p className="text-sm text-slate-600 mt-2">{s.description}</p>}
</div>
{s.kind === 'user' && (
<button
type="button"
onClick={onDelete}
disabled={del.isPending}
className="rounded-md border border-red-300 text-red-700 text-sm px-3 py-1.5 hover:bg-red-50 disabled:opacity-60"
>
{del.isPending ? 'Deleting…' : 'Delete'}
</button>
)}
</header>
{del.isError && (
<div className="rounded-md border border-red-200 bg-red-50 p-3 text-red-800 text-sm">
{String((del.error as Error)?.message ?? del.error)}
</div>
)}
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Stat label="Spending" value={gbp(s.spending_gbp)} />
<Stat label="NW seed" value={gbp(s.nw_seed_gbp)} />
<Stat label="Annual savings" value={gbp(s.savings_per_year_gbp)} />
<Stat label="Horizon" value={`${s.horizon_years}y`} />
</div>
{projection ? (
<>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Stat label="Success rate" value={pct(projection.success_rate)} accent />
<Stat label="Median ending NW" value={gbp(projection.p50_ending_gbp)} />
<Stat label="P10 ending" value={gbp(projection.p10_ending_gbp)} />
<Stat label="P90 ending" value={gbp(projection.p90_ending_gbp)} />
<Stat label="Median lifetime tax" value={gbp(projection.median_lifetime_tax_gbp)} />
<Stat
label="Median years to ruin"
value={projection.median_years_to_ruin ?? 'never'}
/>
<Stat label="MC paths" value={projection.n_paths.toLocaleString()} />
<Stat label="Run at" value={new Date(projection.run_at).toLocaleString()} />
</div>
<div className="rounded-lg border border-slate-200 bg-white p-5">
<h2 className="text-lg font-semibold mb-2">Portfolio fan</h2>
<FanChart yearly={projection.yearly} height={420} showWithdrawal />
</div>
</>
) : projection404 ? (
<div className="rounded-lg border border-slate-200 bg-white p-8 text-center text-slate-500">
<p className="font-medium text-slate-700">No projection yet.</p>
<p className="text-sm mt-2">
Run <code className="px-1">python -m fire_planner recompute-all</code> or{' '}
<code>POST /recompute</code> to fill in MC projections for all scenarios.
</p>
</div>
) : proj.isLoading ? (
<p className="text-slate-500">Loading projection</p>
) : (
<div className="rounded-md border border-red-200 bg-red-50 p-4 text-red-800 text-sm">
{String((proj.error as Error)?.message ?? proj.error)}
</div>
)}
</section>
);
}
function Stat({
label,
value,
accent,
}: {
label: string;
value: string | number;
accent?: boolean;
}) {
return (
<div className="rounded-md border border-slate-200 bg-white p-3">
<div className="text-xs uppercase tracking-wide text-slate-500">{label}</div>
<div
className={`text-xl font-semibold tabular-nums mt-1 ${
accent ? 'text-emerald-700' : ''
}`}
>
{value}
</div>
</div>
);
}