fire-planner: Wave 2 chart-first — flex spending, categorised life
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
events, interactive Visx Gantt + spending-profile chart
Charts are now the primary editor for life events. The Plan-tab body
re-orders to make charts ~80% of viewport real-estate; legacy form
sections are collapsed into a drawer.
Backend:
- alembic 0004: life_event.category enum (essential / discretionary /
not_spending). Defaults to essential so existing rows keep their
full spending impact.
- Simulator gains discretionary_outflows + flex_rules params. Tracks
per-path running ATH, applies the deepest applicable cut to
discretionary outflows when portfolio drops vs ATH (PLab-style flex
spending). Cut amount stays in the portfolio (refund pattern).
- New flex_spending module with FlexRule + applicable_cut +
cuts_per_year (vectorised). Sortable rules; "deepest cut wins" so
users specify cumulative cuts at each tier.
- New /scenarios/{id}/spending-profile endpoint returning per-year
base / essential / discretionary / flex_cut / total breakdown.
- SimulateRequest gains flex_rules + life_event.category roundtrip.
- 8 new tests; 246 total pytest pass; mypy + ruff clean.
Frontend (Visx + ECharts):
- Installed @visx/{scale,shape,group,axis,event,responsive,tooltip}
for native SVG drag interactions.
- New <SpendingProfileChart> — Visx stacked-area of base/essential/
discretionary with red flex-cut overlay, hover tooltip, click-to-
scrub-year.
- New <EventGantt> — interactive Visx Gantt:
* Click empty space → popover create at that year (default
essential spending event)
* Click a bar → inline edit popover (name, kind, range, £/y,
category) with delete button
* Drag bar middle → moves the whole event (year-resolution snap)
* Drag bar edges → resizes year_start / year_end
* All gestures persist via PATCH /life-events/{id}
- New <FlexRulesEditor> — list of {from_ath_pct, cut} tiers, save-on-
change to scenario.config_json.flex_rules.
- Plan-tab redesign: NW fan dominant top with floating stat badges
(Year/Age/NW/Δ NW/Spending/Eff. tax) over the chart; spending-
profile chart middle; Gantt bottom; flex-rules editor; legacy form
sections in a collapsed <details> drawer.
- Frontend typecheck + 7 vitest tests + production build all clean.
This commit is contained in:
parent
9cc781a8d6
commit
64eb90c3dc
19 changed files with 2581 additions and 88 deletions
|
|
@ -50,6 +50,8 @@ export const api = {
|
|||
progress: (id: number) => request<ProgressResponse>(`/scenarios/${id}/progress`),
|
||||
cashflow: (id: number, year: number) =>
|
||||
request<CashflowResponse>(`/scenarios/${id}/cashflow?year=${year}`),
|
||||
spendingProfile: (id: number) =>
|
||||
request<SpendingProfileResponse>(`/scenarios/${id}/spending-profile`),
|
||||
networth: {
|
||||
current: () =>
|
||||
request<{
|
||||
|
|
@ -128,6 +130,8 @@ export interface ScenarioCreateBody {
|
|||
|
||||
// ── life events ──────────────────────────────────────────────────────
|
||||
|
||||
export type SpendingCategory = 'essential' | 'discretionary' | 'not_spending';
|
||||
|
||||
export interface LifeEvent {
|
||||
id: number;
|
||||
scenario_id: number;
|
||||
|
|
@ -137,6 +141,7 @@ export interface LifeEvent {
|
|||
year_end: number | null;
|
||||
delta_gbp_per_year: string;
|
||||
one_time_amount_gbp: string | null;
|
||||
category: SpendingCategory;
|
||||
enabled: boolean;
|
||||
payload: Record<string, unknown> | null;
|
||||
created_at: string;
|
||||
|
|
@ -149,10 +154,22 @@ export interface LifeEventCreateBody {
|
|||
year_end?: number | null;
|
||||
delta_gbp_per_year?: string;
|
||||
one_time_amount_gbp?: string | null;
|
||||
category?: SpendingCategory;
|
||||
enabled?: boolean;
|
||||
payload?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface LifeEventPatchBody {
|
||||
kind?: string;
|
||||
name?: string;
|
||||
year_start?: number;
|
||||
year_end?: number | null;
|
||||
delta_gbp_per_year?: string;
|
||||
one_time_amount_gbp?: string | null;
|
||||
category?: SpendingCategory;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export const lifeEventsApi = {
|
||||
list: (scenarioId: number) =>
|
||||
request<LifeEvent[]>(`/scenarios/${scenarioId}/life-events`),
|
||||
|
|
@ -161,10 +178,38 @@ export const lifeEventsApi = {
|
|||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
patch: (eventId: number, body: LifeEventPatchBody) =>
|
||||
request<LifeEvent>(`/life-events/${eventId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
delete: (eventId: number) =>
|
||||
request<void>(`/life-events/${eventId}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
// ── flex spending + spending profile ─────────────────────────────────
|
||||
|
||||
export interface FlexRule {
|
||||
from_ath_pct: string;
|
||||
cut_discretionary_pct: string;
|
||||
}
|
||||
|
||||
export interface SpendingProfilePoint {
|
||||
year_idx: number;
|
||||
base_gbp: string;
|
||||
essential_gbp: string;
|
||||
discretionary_gbp: string;
|
||||
not_spending_gbp: string;
|
||||
flex_cut_gbp: string;
|
||||
total_gbp: string;
|
||||
}
|
||||
|
||||
export interface SpendingProfileResponse {
|
||||
scenario_id: number;
|
||||
horizon_years: number;
|
||||
points: SpendingProfilePoint[];
|
||||
}
|
||||
|
||||
// ── goals ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Goal {
|
||||
|
|
@ -374,6 +419,7 @@ export interface SimulateRequest {
|
|||
year_end?: number | null;
|
||||
delta_gbp_per_year?: string;
|
||||
one_time_amount_gbp?: string | null;
|
||||
category?: SpendingCategory;
|
||||
enabled?: boolean;
|
||||
}>;
|
||||
returns_mode?: 'shiller' | 'manual' | 'wealthfolio';
|
||||
|
|
@ -391,6 +437,7 @@ export interface SimulateRequest {
|
|||
tax_treatment?: string;
|
||||
enabled?: boolean;
|
||||
}>;
|
||||
flex_rules?: FlexRule[];
|
||||
goals?: Array<{
|
||||
kind: string;
|
||||
name: string;
|
||||
|
|
|
|||
622
frontend/src/components/EventGantt.tsx
Normal file
622
frontend/src/components/EventGantt.tsx
Normal file
|
|
@ -0,0 +1,622 @@
|
|||
/**
|
||||
* Interactive Gantt of life events (Wave 2 chart-first redesign).
|
||||
*
|
||||
* Visualises every life event as a horizontal bar over the scenario
|
||||
* horizon. Bar color encodes spending category. Drag the middle to slide
|
||||
* the whole event. Drag the left/right edge handles to resize. Click an
|
||||
* empty slot to create a new event at that year. Click an existing bar
|
||||
* to edit it inline via a popover. Persists every interaction through
|
||||
* the existing life-events CRUD endpoints (PATCH for moves/resizes,
|
||||
* POST for create, DELETE from the popover).
|
||||
*
|
||||
* Source-of-truth pattern: this chart IS the editor. The list-form
|
||||
* fallback under the drawer remains for bulk edits and accessibility.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ParentSize } from '@visx/responsive';
|
||||
import { scaleBand, scaleLinear } from '@visx/scale';
|
||||
import { Group } from '@visx/group';
|
||||
import { AxisBottom } from '@visx/axis';
|
||||
import { localPoint } from '@visx/event';
|
||||
|
||||
import {
|
||||
lifeEventsApi,
|
||||
type LifeEvent,
|
||||
type LifeEventCreateBody,
|
||||
type LifeEventPatchBody,
|
||||
type SpendingCategory,
|
||||
} from '@/api/client';
|
||||
import { gbp } from '@/lib/format';
|
||||
import { emojiFor } from '@/lib/milestone';
|
||||
|
||||
interface Props {
|
||||
scenarioId: number;
|
||||
events: LifeEvent[];
|
||||
horizonYears: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
const CATEGORY_FILL: Record<SpendingCategory, string> = {
|
||||
essential: 'rgb(16, 185, 129)', // emerald-500
|
||||
discretionary: 'rgb(245, 158, 11)', // amber-500
|
||||
not_spending: 'rgb(100, 116, 139)', // slate-500
|
||||
};
|
||||
|
||||
const CATEGORY_BORDER: Record<SpendingCategory, string> = {
|
||||
essential: 'rgb(5, 150, 105)',
|
||||
discretionary: 'rgb(217, 119, 6)',
|
||||
not_spending: 'rgb(71, 85, 105)',
|
||||
};
|
||||
|
||||
type DragMode = 'move' | 'left' | 'right';
|
||||
|
||||
interface DragState {
|
||||
eventId: number;
|
||||
mode: DragMode;
|
||||
startMouseX: number;
|
||||
origYearStart: number;
|
||||
origYearEnd: number;
|
||||
}
|
||||
|
||||
interface PopoverState {
|
||||
// Either editing an existing event, or creating one at year_start=N
|
||||
kind: 'edit' | 'create';
|
||||
x: number;
|
||||
y: number;
|
||||
event?: LifeEvent;
|
||||
createYear?: number;
|
||||
}
|
||||
|
||||
export function EventGantt(props: Props) {
|
||||
return (
|
||||
<ParentSize>
|
||||
{({ width }) => (width > 0 ? <Inner {...props} width={width} /> : null)}
|
||||
</ParentSize>
|
||||
);
|
||||
}
|
||||
|
||||
function Inner({
|
||||
scenarioId,
|
||||
events,
|
||||
horizonYears,
|
||||
width,
|
||||
height = 220,
|
||||
}: Props & { width: number }) {
|
||||
const margin = { top: 12, right: 24, bottom: 28, left: 96 };
|
||||
const innerW = Math.max(0, width - margin.left - margin.right);
|
||||
const sortedEvents = useMemo(
|
||||
() => [...events].sort((a, b) => a.year_start - b.year_start || a.id - b.id),
|
||||
[events],
|
||||
);
|
||||
const rowHeight = 22;
|
||||
const minRows = Math.max(sortedEvents.length, 1);
|
||||
const innerH = Math.max(rowHeight * minRows + 32, height - margin.top - margin.bottom);
|
||||
|
||||
const xScale = useMemo(
|
||||
() =>
|
||||
scaleLinear<number>({
|
||||
domain: [0, Math.max(1, horizonYears - 1)],
|
||||
range: [0, innerW],
|
||||
}),
|
||||
[horizonYears, innerW],
|
||||
);
|
||||
|
||||
const yScale = useMemo(
|
||||
() =>
|
||||
scaleBand<number>({
|
||||
domain: sortedEvents.map((e) => e.id),
|
||||
range: [0, rowHeight * sortedEvents.length],
|
||||
padding: 0.2,
|
||||
}),
|
||||
[sortedEvents],
|
||||
);
|
||||
|
||||
const qc = useQueryClient();
|
||||
const invalidate = () =>
|
||||
qc.invalidateQueries({
|
||||
queryKey: ['scenarios', scenarioId, 'life-events'],
|
||||
});
|
||||
const invalidateProfile = () =>
|
||||
qc.invalidateQueries({
|
||||
queryKey: ['spending-profile', scenarioId],
|
||||
});
|
||||
|
||||
const patchMut = useMutation({
|
||||
mutationFn: ({ id, body }: { id: number; body: LifeEventPatchBody }) =>
|
||||
lifeEventsApi.patch(id, body),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
invalidateProfile();
|
||||
},
|
||||
});
|
||||
const createMut = useMutation({
|
||||
mutationFn: (body: LifeEventCreateBody) =>
|
||||
lifeEventsApi.create(scenarioId, body),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
invalidateProfile();
|
||||
},
|
||||
});
|
||||
const deleteMut = useMutation({
|
||||
mutationFn: (id: number) => lifeEventsApi.delete(id),
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
invalidateProfile();
|
||||
},
|
||||
});
|
||||
|
||||
// Drag state lives in a ref so mousemove handlers don't re-render.
|
||||
const drag = useRef<DragState | null>(null);
|
||||
// Pixel-level offset applied during drag (without committing).
|
||||
const [dragOffset, setDragOffset] = useState<{ id: number; dx: number; mode: DragMode } | null>(null);
|
||||
const [popover, setPopover] = useState<PopoverState | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => {
|
||||
if (!drag.current) return;
|
||||
setDragOffset({
|
||||
id: drag.current.eventId,
|
||||
dx: e.clientX - drag.current.startMouseX,
|
||||
mode: drag.current.mode,
|
||||
});
|
||||
};
|
||||
const onUp = (e: MouseEvent) => {
|
||||
if (!drag.current) return;
|
||||
const dx = e.clientX - drag.current.startMouseX;
|
||||
const dyears = pxToYears(dx, xScale, horizonYears);
|
||||
const { eventId, mode, origYearStart, origYearEnd } = drag.current;
|
||||
drag.current = null;
|
||||
setDragOffset(null);
|
||||
if (Math.abs(dyears) < 1) return; // sub-year drag = ignore
|
||||
let body: LifeEventPatchBody = {};
|
||||
if (mode === 'move') {
|
||||
const newStart = clamp(origYearStart + dyears, 0, horizonYears - 1);
|
||||
const span = origYearEnd - origYearStart;
|
||||
body = {
|
||||
year_start: newStart,
|
||||
year_end: clamp(newStart + span, newStart, horizonYears - 1),
|
||||
};
|
||||
} else if (mode === 'left') {
|
||||
body = {
|
||||
year_start: clamp(origYearStart + dyears, 0, origYearEnd),
|
||||
};
|
||||
} else if (mode === 'right') {
|
||||
body = {
|
||||
year_end: clamp(origYearEnd + dyears, origYearStart, horizonYears - 1),
|
||||
};
|
||||
}
|
||||
patchMut.mutate({ id: eventId, body });
|
||||
};
|
||||
window.addEventListener('mousemove', onMove);
|
||||
window.addEventListener('mouseup', onUp);
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', onMove);
|
||||
window.removeEventListener('mouseup', onUp);
|
||||
};
|
||||
}, [horizonYears, patchMut, xScale]);
|
||||
|
||||
const startDrag = (e: React.MouseEvent, ev: LifeEvent, mode: DragMode) => {
|
||||
e.stopPropagation();
|
||||
const yearEnd = ev.year_end ?? ev.year_start;
|
||||
drag.current = {
|
||||
eventId: ev.id,
|
||||
mode,
|
||||
startMouseX: e.clientX,
|
||||
origYearStart: ev.year_start,
|
||||
origYearEnd: yearEnd,
|
||||
};
|
||||
setDragOffset({ id: ev.id, dx: 0, mode });
|
||||
};
|
||||
|
||||
const onBackgroundClick = (e: React.MouseEvent<SVGRectElement>) => {
|
||||
const point = localPoint(e);
|
||||
if (!point) return;
|
||||
const x = point.x - margin.left;
|
||||
const year = Math.round(xScale.invert(Math.max(0, Math.min(innerW, x))));
|
||||
setPopover({
|
||||
kind: 'create',
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
createYear: year,
|
||||
});
|
||||
};
|
||||
|
||||
const onBarClick = (e: React.MouseEvent, ev: LifeEvent) => {
|
||||
e.stopPropagation();
|
||||
const point = localPoint(e);
|
||||
if (!point) return;
|
||||
setPopover({ kind: 'edit', x: point.x, y: point.y, event: ev });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<svg width={width} height={Math.max(height, innerH + margin.top + margin.bottom)}>
|
||||
<Group left={margin.left} top={margin.top}>
|
||||
{/* Faint year gridlines */}
|
||||
{Array.from({ length: horizonYears }).map((_, i) => {
|
||||
const x = xScale(i) ?? 0;
|
||||
return (
|
||||
<line
|
||||
key={i}
|
||||
x1={x}
|
||||
x2={x}
|
||||
y1={0}
|
||||
y2={innerH}
|
||||
stroke={i % 5 === 0 ? '#cbd5e1' : '#e2e8f0'}
|
||||
strokeWidth={1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{/* Background click capture (must be drawn before bars) */}
|
||||
<rect
|
||||
x={0}
|
||||
y={0}
|
||||
width={innerW}
|
||||
height={innerH}
|
||||
fill="transparent"
|
||||
onClick={onBackgroundClick}
|
||||
style={{ cursor: 'crosshair' }}
|
||||
/>
|
||||
{/* Bars */}
|
||||
{sortedEvents.map((ev) => {
|
||||
const yearEnd = ev.year_end ?? ev.year_start;
|
||||
const offsetDx =
|
||||
dragOffset && dragOffset.id === ev.id ? dragOffset.dx : 0;
|
||||
const dyears = pxToYears(offsetDx, xScale, horizonYears);
|
||||
const isMove = dragOffset?.id === ev.id && dragOffset.mode === 'move';
|
||||
const isLeft = dragOffset?.id === ev.id && dragOffset.mode === 'left';
|
||||
const isRight = dragOffset?.id === ev.id && dragOffset.mode === 'right';
|
||||
const startY = isMove
|
||||
? ev.year_start + dyears
|
||||
: isLeft
|
||||
? ev.year_start + dyears
|
||||
: ev.year_start;
|
||||
const endY = isMove
|
||||
? yearEnd + dyears
|
||||
: isRight
|
||||
? yearEnd + dyears
|
||||
: yearEnd;
|
||||
const x = xScale(Math.max(0, startY)) ?? 0;
|
||||
const w = Math.max(8, (xScale(Math.max(startY + 0.5, endY)) ?? 0) - x);
|
||||
const y = yScale(ev.id) ?? 0;
|
||||
const h = yScale.bandwidth();
|
||||
const fill = CATEGORY_FILL[ev.category] ?? CATEGORY_FILL.essential;
|
||||
const border =
|
||||
CATEGORY_BORDER[ev.category] ?? CATEGORY_BORDER.essential;
|
||||
return (
|
||||
<g
|
||||
key={ev.id}
|
||||
opacity={ev.enabled ? 1 : 0.4}
|
||||
onClick={(e) => onBarClick(e, ev)}
|
||||
style={{ cursor: 'grab' }}
|
||||
>
|
||||
<rect
|
||||
x={x}
|
||||
y={y}
|
||||
width={w}
|
||||
height={h}
|
||||
fill={fill}
|
||||
stroke={border}
|
||||
strokeWidth={1}
|
||||
rx={3}
|
||||
onMouseDown={(e) => startDrag(e, ev, 'move')}
|
||||
/>
|
||||
{/* Left handle */}
|
||||
<rect
|
||||
x={x - 1}
|
||||
y={y}
|
||||
width={6}
|
||||
height={h}
|
||||
fill="rgba(0,0,0,0.25)"
|
||||
rx={3}
|
||||
onMouseDown={(e) => startDrag(e, ev, 'left')}
|
||||
style={{ cursor: 'ew-resize' }}
|
||||
/>
|
||||
{/* Right handle */}
|
||||
<rect
|
||||
x={x + w - 5}
|
||||
y={y}
|
||||
width={6}
|
||||
height={h}
|
||||
fill="rgba(0,0,0,0.25)"
|
||||
rx={3}
|
||||
onMouseDown={(e) => startDrag(e, ev, 'right')}
|
||||
style={{ cursor: 'ew-resize' }}
|
||||
/>
|
||||
<text
|
||||
x={x + 6}
|
||||
y={y + h / 2}
|
||||
fill="#fff"
|
||||
fontSize={11}
|
||||
dominantBaseline="middle"
|
||||
pointerEvents="none"
|
||||
style={{ userSelect: 'none' }}
|
||||
>
|
||||
{emojiFor(ev.kind)} {ev.name}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<AxisBottom
|
||||
top={innerH}
|
||||
scale={xScale}
|
||||
numTicks={Math.min(10, horizonYears)}
|
||||
tickFormat={(v) => `y${Math.round(Number(v))}`}
|
||||
tickStroke="#94a3b8"
|
||||
stroke="#94a3b8"
|
||||
tickLabelProps={{ fill: '#64748b', fontSize: 10, textAnchor: 'middle' }}
|
||||
/>
|
||||
</Group>
|
||||
{/* Row labels */}
|
||||
<Group left={0} top={margin.top}>
|
||||
{sortedEvents.map((ev) => {
|
||||
const y = (yScale(ev.id) ?? 0) + yScale.bandwidth() / 2;
|
||||
return (
|
||||
<text
|
||||
key={ev.id}
|
||||
x={margin.left - 8}
|
||||
y={y}
|
||||
fill="#475569"
|
||||
fontSize={11}
|
||||
textAnchor="end"
|
||||
dominantBaseline="middle"
|
||||
>
|
||||
{ev.kind}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</Group>
|
||||
</svg>
|
||||
|
||||
{sortedEvents.length === 0 && (
|
||||
<div className="absolute top-12 left-0 right-0 text-center text-xs text-slate-500 pointer-events-none">
|
||||
Click anywhere on the timeline to add a life event.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{popover && (
|
||||
<EventPopover
|
||||
state={popover}
|
||||
onClose={() => setPopover(null)}
|
||||
onCreate={(body) => {
|
||||
createMut.mutate(body);
|
||||
setPopover(null);
|
||||
}}
|
||||
onPatch={(id, body) => {
|
||||
patchMut.mutate({ id, body });
|
||||
setPopover(null);
|
||||
}}
|
||||
onDelete={(id) => {
|
||||
deleteMut.mutate(id);
|
||||
setPopover(null);
|
||||
}}
|
||||
horizonYears={horizonYears}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function pxToYears(
|
||||
px: number,
|
||||
scale: { invert: (n: number) => number },
|
||||
_horizon: number,
|
||||
): number {
|
||||
const yearsAtZero = scale.invert(0);
|
||||
const yearsAtPx = scale.invert(px);
|
||||
return Math.round(yearsAtPx - yearsAtZero);
|
||||
}
|
||||
|
||||
function clamp(n: number, lo: number, hi: number): number {
|
||||
return Math.max(lo, Math.min(hi, n));
|
||||
}
|
||||
|
||||
interface PopoverProps {
|
||||
state: PopoverState;
|
||||
horizonYears: number;
|
||||
onClose: () => void;
|
||||
onCreate: (body: LifeEventCreateBody) => void;
|
||||
onPatch: (id: number, body: LifeEventPatchBody) => void;
|
||||
onDelete: (id: number) => void;
|
||||
}
|
||||
|
||||
const KIND_OPTIONS = [
|
||||
'kid_at_home',
|
||||
'kid_born',
|
||||
'kids_leave_home',
|
||||
'mortgage_payoff',
|
||||
'home_purchase',
|
||||
'sabbatical',
|
||||
'inheritance',
|
||||
'travel',
|
||||
'expense_range',
|
||||
'one_time_income',
|
||||
];
|
||||
|
||||
function EventPopover({
|
||||
state,
|
||||
horizonYears,
|
||||
onClose,
|
||||
onCreate,
|
||||
onPatch,
|
||||
onDelete,
|
||||
}: PopoverProps) {
|
||||
const isEdit = state.kind === 'edit' && state.event;
|
||||
const [name, setName] = useState(isEdit ? state.event!.name : '');
|
||||
const [kind, setKind] = useState(isEdit ? state.event!.kind : 'kid_at_home');
|
||||
const [yearStart, setYearStart] = useState(
|
||||
isEdit ? state.event!.year_start : state.createYear ?? 0,
|
||||
);
|
||||
const [yearEnd, setYearEnd] = useState<number | null>(
|
||||
isEdit ? state.event!.year_end : null,
|
||||
);
|
||||
const [delta, setDelta] = useState(
|
||||
isEdit ? Number(state.event!.delta_gbp_per_year) : -10000,
|
||||
);
|
||||
const [category, setCategory] = useState<SpendingCategory>(
|
||||
isEdit ? state.event!.category : 'essential',
|
||||
);
|
||||
|
||||
const submit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (isEdit) {
|
||||
onPatch(state.event!.id, {
|
||||
name,
|
||||
kind,
|
||||
year_start: yearStart,
|
||||
year_end: yearEnd,
|
||||
delta_gbp_per_year: String(delta),
|
||||
category,
|
||||
});
|
||||
} else {
|
||||
onCreate({
|
||||
kind,
|
||||
name: name || titleize(kind),
|
||||
year_start: yearStart,
|
||||
year_end: yearEnd,
|
||||
delta_gbp_per_year: String(delta),
|
||||
category,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute z-50 rounded-lg border border-slate-200 bg-white shadow-lg p-3 w-72 text-sm"
|
||||
style={{
|
||||
left: Math.min(state.x + 8, window.innerWidth - 290),
|
||||
top: state.y + 8,
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<form onSubmit={submit} className="space-y-2">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h3 className="font-semibold text-slate-900">
|
||||
{isEdit ? 'Edit event' : `Add event @ y${state.createYear}`}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-slate-400 hover:text-slate-700"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<label className="block text-xs">
|
||||
<span className="uppercase tracking-wide text-slate-500">Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={titleize(kind)}
|
||||
className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1 text-sm"
|
||||
autoFocus
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs">
|
||||
<span className="uppercase tracking-wide text-slate-500">Kind</span>
|
||||
<select
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value)}
|
||||
className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1 text-sm"
|
||||
>
|
||||
{KIND_OPTIONS.map((k) => (
|
||||
<option key={k} value={k}>
|
||||
{emojiFor(k)} {k}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block text-xs">
|
||||
<span className="uppercase tracking-wide text-slate-500">Year start</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={horizonYears - 1}
|
||||
value={yearStart}
|
||||
onChange={(e) => setYearStart(clamp(Number(e.target.value), 0, horizonYears - 1))}
|
||||
className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1 text-sm tabular-nums"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs">
|
||||
<span className="uppercase tracking-wide text-slate-500">Year end</span>
|
||||
<input
|
||||
type="number"
|
||||
min={yearStart}
|
||||
max={horizonYears - 1}
|
||||
value={yearEnd ?? ''}
|
||||
placeholder="—"
|
||||
onChange={(e) =>
|
||||
setYearEnd(e.target.value === '' ? null : Number(e.target.value))
|
||||
}
|
||||
className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1 text-sm tabular-nums"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block text-xs">
|
||||
<span className="uppercase tracking-wide text-slate-500">
|
||||
£ per year ({delta < 0 ? 'expense' : 'income'})
|
||||
</span>
|
||||
<input
|
||||
type="number"
|
||||
value={delta}
|
||||
step={1000}
|
||||
onChange={(e) => setDelta(Number(e.target.value))}
|
||||
className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1 text-sm tabular-nums"
|
||||
/>
|
||||
<div className="text-xs text-slate-500 mt-0.5">
|
||||
{delta !== 0 && `${delta < 0 ? '−' : '+'}${gbp(Math.abs(delta))}/y`}
|
||||
</div>
|
||||
</label>
|
||||
<fieldset className="text-xs">
|
||||
<legend className="uppercase tracking-wide text-slate-500 mb-1">Category</legend>
|
||||
<div className="flex gap-1">
|
||||
{(['essential', 'discretionary', 'not_spending'] as const).map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
onClick={() => setCategory(c)}
|
||||
className={[
|
||||
'flex-1 rounded-md px-2 py-1 text-xs border',
|
||||
category === c
|
||||
? 'border-slate-900 bg-slate-900 text-white'
|
||||
: 'border-slate-300 text-slate-600 hover:bg-slate-50',
|
||||
].join(' ')}
|
||||
>
|
||||
{c.replace('_', ' ')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="flex items-center justify-between pt-1">
|
||||
{isEdit && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDelete(state.event!.id)}
|
||||
className="text-xs text-red-700 hover:underline"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-md bg-slate-900 text-white text-xs font-medium px-3 py-1.5 hover:bg-slate-800"
|
||||
>
|
||||
{isEdit ? 'Save' : 'Create'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function titleize(kind: string): string {
|
||||
return kind
|
||||
.split('_')
|
||||
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
165
frontend/src/components/FlexRulesEditor.tsx
Normal file
165
frontend/src/components/FlexRulesEditor.tsx
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
/**
|
||||
* Flex-rules editor — list of {from_ath_pct, cut_discretionary_pct}
|
||||
* tiers stored on `scenario.config_json.flex_rules`. Saves on blur via
|
||||
* the existing PATCH /scenarios/:id (config_json is a free-form blob).
|
||||
*/
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { api, type Scenario } from '@/api/client';
|
||||
|
||||
interface Rule {
|
||||
from_ath_pct: number;
|
||||
cut_discretionary_pct: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
scenario: Scenario;
|
||||
}
|
||||
|
||||
const DEFAULT_RULES: Rule[] = [
|
||||
{ from_ath_pct: 0.10, cut_discretionary_pct: 0.20 },
|
||||
{ from_ath_pct: 0.30, cut_discretionary_pct: 0.60 },
|
||||
];
|
||||
|
||||
function readRules(scen: Scenario): Rule[] {
|
||||
const blob = scen.config_json as Record<string, unknown>;
|
||||
const raw = blob?.flex_rules;
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.filter((r): r is { from_ath_pct: unknown; cut_discretionary_pct: unknown } =>
|
||||
typeof r === 'object' && r !== null,
|
||||
)
|
||||
.map((r) => ({
|
||||
from_ath_pct: Number((r as { from_ath_pct: unknown }).from_ath_pct ?? 0),
|
||||
cut_discretionary_pct: Number(
|
||||
(r as { cut_discretionary_pct: unknown }).cut_discretionary_pct ?? 0,
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
export function FlexRulesEditor({ scenario }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const [rules, setRules] = useState<Rule[]>(() => readRules(scenario));
|
||||
|
||||
useEffect(() => {
|
||||
setRules(readRules(scenario));
|
||||
}, [scenario.id, scenario.config_json]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (next: Rule[]) =>
|
||||
api.scenarios.patch(scenario.id, {
|
||||
config_json: {
|
||||
...((scenario.config_json as Record<string, unknown>) ?? {}),
|
||||
flex_rules: next,
|
||||
},
|
||||
} as never),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['scenarios', scenario.id] });
|
||||
qc.invalidateQueries({
|
||||
queryKey: ['spending-profile', scenario.id],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const persist = (next: Rule[]) => {
|
||||
setRules(next);
|
||||
save.mutate(next);
|
||||
};
|
||||
|
||||
const update = (idx: number, patch: Partial<Rule>) => {
|
||||
persist(rules.map((r, i) => (i === idx ? { ...r, ...patch } : r)));
|
||||
};
|
||||
|
||||
const remove = (idx: number) => persist(rules.filter((_, i) => i !== idx));
|
||||
const add = () => persist([...rules, { from_ath_pct: 0.20, cut_discretionary_pct: 0.40 }]);
|
||||
const seedDefaults = () => persist(DEFAULT_RULES);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-4">
|
||||
<div className="flex items-baseline justify-between mb-3">
|
||||
<h2 className="text-base font-semibold">Flex spending rules</h2>
|
||||
<span className="text-xs text-slate-500">
|
||||
When portfolio drops vs ATH, cut discretionary by …
|
||||
</span>
|
||||
</div>
|
||||
{rules.length === 0 ? (
|
||||
<div className="text-sm text-slate-500 mb-3 flex items-center gap-3">
|
||||
<span>No flex rules — discretionary spending stays flat.</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={seedDefaults}
|
||||
className="text-xs text-slate-700 underline hover:text-slate-900"
|
||||
>
|
||||
Seed sensible defaults
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-2 mb-3">
|
||||
{rules.map((r, idx) => (
|
||||
<li key={idx} className="flex items-center gap-3 text-sm">
|
||||
<span className="text-slate-500">If down</span>
|
||||
<PctInput
|
||||
value={r.from_ath_pct}
|
||||
onChange={(v) => update(idx, { from_ath_pct: v })}
|
||||
aria="Drawdown threshold"
|
||||
/>
|
||||
<span className="text-slate-500">from ATH, cut discretionary by</span>
|
||||
<PctInput
|
||||
value={r.cut_discretionary_pct}
|
||||
onChange={(v) => update(idx, { cut_discretionary_pct: v })}
|
||||
aria="Cut percent"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove(idx)}
|
||||
className="ml-auto text-xs text-slate-500 hover:text-red-700"
|
||||
aria-label="Delete rule"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={add}
|
||||
className="text-xs text-slate-700 hover:text-slate-900 hover:underline"
|
||||
>
|
||||
+ Add tier
|
||||
</button>
|
||||
{save.isError && (
|
||||
<p className="text-xs text-red-700 mt-2">
|
||||
{String((save.error as Error)?.message ?? save.error)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PctInput({
|
||||
value,
|
||||
onChange,
|
||||
aria,
|
||||
}: {
|
||||
value: number;
|
||||
onChange: (v: number) => void;
|
||||
aria: string;
|
||||
}) {
|
||||
return (
|
||||
<span className="inline-flex items-center">
|
||||
<input
|
||||
type="number"
|
||||
value={Math.round(value * 100)}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
onChange={(e) => onChange(Math.max(0, Math.min(100, Number(e.target.value))) / 100)}
|
||||
className="w-14 rounded-md border border-slate-300 px-2 py-0.5 text-sm tabular-nums"
|
||||
aria-label={aria}
|
||||
/>
|
||||
<span className="ml-0.5 text-slate-500">%</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
300
frontend/src/components/SpendingProfileChart.tsx
Normal file
300
frontend/src/components/SpendingProfileChart.tsx
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
/**
|
||||
* Stacked-area spending profile per year (Wave 2 chart-first redesign).
|
||||
*
|
||||
* Stacks (bottom to top):
|
||||
* - base spending (slate)
|
||||
* - essential events (emerald)
|
||||
* - discretionary events (amber)
|
||||
* - flex_cut overlay (red, drawn as a hatched ribbon eaten from the
|
||||
* discretionary band)
|
||||
*
|
||||
* Hover shows the full breakdown for that year. Click forwards a
|
||||
* `year_idx` callback so the parent can sync the year-scrubber.
|
||||
*/
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ParentSize } from '@visx/responsive';
|
||||
import { scaleLinear } from '@visx/scale';
|
||||
import { AreaStack, Bar, Line } from '@visx/shape';
|
||||
import { Group } from '@visx/group';
|
||||
import { AxisBottom, AxisLeft } from '@visx/axis';
|
||||
import { localPoint } from '@visx/event';
|
||||
|
||||
import type { SpendingProfilePoint } from '@/api/client';
|
||||
import { gbpCompact, gbp } from '@/lib/format';
|
||||
|
||||
interface Props {
|
||||
points: SpendingProfilePoint[];
|
||||
height?: number;
|
||||
selectedYear?: number | null;
|
||||
onSelectYear?: (year: number) => void;
|
||||
}
|
||||
|
||||
const BAND_KEYS = ['base', 'essential', 'discretionary'] as const;
|
||||
type BandKey = (typeof BAND_KEYS)[number];
|
||||
|
||||
const COLORS: Record<BandKey, string> = {
|
||||
base: 'rgb(100, 116, 139)', // slate-500
|
||||
essential: 'rgb(16, 185, 129)', // emerald-500
|
||||
discretionary: 'rgb(245, 158, 11)', // amber-500
|
||||
};
|
||||
|
||||
const FLEX_CUT_COLOR = 'rgba(239, 68, 68, 0.55)'; // red-500 @ 55%
|
||||
|
||||
interface BandRow {
|
||||
year_idx: number;
|
||||
base: number;
|
||||
essential: number;
|
||||
discretionary: number;
|
||||
}
|
||||
|
||||
export function SpendingProfileChart(props: Props) {
|
||||
return (
|
||||
<ParentSize>
|
||||
{({ width }) => (width > 0 ? <Inner {...props} width={width} /> : null)}
|
||||
</ParentSize>
|
||||
);
|
||||
}
|
||||
|
||||
function Inner({
|
||||
points,
|
||||
width,
|
||||
height = 220,
|
||||
selectedYear,
|
||||
onSelectYear,
|
||||
}: Props & { width: number }) {
|
||||
const [hover, setHover] = useState<{ x: number; year: number } | null>(null);
|
||||
const margin = { top: 12, right: 24, bottom: 32, left: 64 };
|
||||
const innerW = Math.max(0, width - margin.left - margin.right);
|
||||
const innerH = Math.max(0, height - margin.top - margin.bottom);
|
||||
|
||||
const rows = useMemo<BandRow[]>(
|
||||
() =>
|
||||
points.map((p) => ({
|
||||
year_idx: p.year_idx,
|
||||
base: Number(p.base_gbp),
|
||||
essential: Number(p.essential_gbp),
|
||||
discretionary: Math.max(0, Number(p.discretionary_gbp) - Number(p.flex_cut_gbp)),
|
||||
})),
|
||||
[points],
|
||||
);
|
||||
|
||||
const maxTotal = useMemo(() => {
|
||||
if (points.length === 0) return 1;
|
||||
return Math.max(...points.map((p) => Number(p.total_gbp))) * 1.1;
|
||||
}, [points]);
|
||||
|
||||
const xScale = useMemo(
|
||||
() =>
|
||||
scaleLinear<number>({
|
||||
domain: [0, Math.max(0, points.length - 1)],
|
||||
range: [0, innerW],
|
||||
}),
|
||||
[innerW, points.length],
|
||||
);
|
||||
|
||||
const yScale = useMemo(
|
||||
() =>
|
||||
scaleLinear<number>({
|
||||
domain: [0, maxTotal],
|
||||
range: [innerH, 0],
|
||||
nice: true,
|
||||
}),
|
||||
[innerH, maxTotal],
|
||||
);
|
||||
|
||||
if (points.length === 0) {
|
||||
return (
|
||||
<div className="text-sm text-slate-500 px-4 py-8">
|
||||
No spending data — add a life event to populate the chart.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleMove = (e: React.MouseEvent<SVGRectElement>) => {
|
||||
const point = localPoint(e);
|
||||
if (!point) return;
|
||||
const x = point.x - margin.left;
|
||||
const idx = Math.round(xScale.invert(Math.max(0, Math.min(innerW, x))));
|
||||
setHover({ x: xScale(idx) ?? 0, year: idx });
|
||||
};
|
||||
|
||||
const handleLeave = () => setHover(null);
|
||||
const handleClick = (e: React.MouseEvent<SVGRectElement>) => {
|
||||
if (!onSelectYear) return;
|
||||
const point = localPoint(e);
|
||||
if (!point) return;
|
||||
const x = point.x - margin.left;
|
||||
const idx = Math.round(xScale.invert(Math.max(0, Math.min(innerW, x))));
|
||||
onSelectYear(idx);
|
||||
};
|
||||
|
||||
const hoverPoint = hover ? points[hover.year] : null;
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<svg width={width} height={height} className="select-none">
|
||||
<Group left={margin.left} top={margin.top}>
|
||||
<AreaStack<BandRow>
|
||||
data={rows}
|
||||
keys={BAND_KEYS as unknown as BandKey[]}
|
||||
x={(d) => xScale(d.data.year_idx) ?? 0}
|
||||
y0={(d) => yScale(d[0]) ?? 0}
|
||||
y1={(d) => yScale(d[1]) ?? 0}
|
||||
>
|
||||
{({ stacks, path }) =>
|
||||
stacks.map((stack) => (
|
||||
<path
|
||||
key={stack.key}
|
||||
d={path(stack) || ''}
|
||||
fill={COLORS[stack.key as BandKey]}
|
||||
fillOpacity={0.85}
|
||||
/>
|
||||
))
|
||||
}
|
||||
</AreaStack>
|
||||
|
||||
{/* Flex-cut overlay: drawn as a thin red ribbon at the top of the
|
||||
discretionary band so the user sees what was trimmed. */}
|
||||
{points.some((p) => Number(p.flex_cut_gbp) > 0) && (
|
||||
<FlexCutOverlay
|
||||
points={points}
|
||||
xScale={xScale}
|
||||
yScale={yScale}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedYear != null && selectedYear >= 0 && selectedYear < points.length && (
|
||||
<Line
|
||||
from={{ x: xScale(selectedYear) ?? 0, y: 0 }}
|
||||
to={{ x: xScale(selectedYear) ?? 0, y: innerH }}
|
||||
stroke="rgba(15, 23, 42, 0.7)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
)}
|
||||
|
||||
{hover && (
|
||||
<Line
|
||||
from={{ x: hover.x, y: 0 }}
|
||||
to={{ x: hover.x, y: innerH }}
|
||||
stroke="rgba(15, 23, 42, 0.4)"
|
||||
strokeWidth={1}
|
||||
strokeDasharray="3,3"
|
||||
pointerEvents="none"
|
||||
/>
|
||||
)}
|
||||
|
||||
<AxisBottom
|
||||
top={innerH}
|
||||
scale={xScale}
|
||||
numTicks={Math.min(10, points.length)}
|
||||
tickFormat={(v) => String(Math.round(Number(v)))}
|
||||
tickStroke="#94a3b8"
|
||||
stroke="#94a3b8"
|
||||
tickLabelProps={{ fill: '#64748b', fontSize: 10, textAnchor: 'middle' }}
|
||||
/>
|
||||
<AxisLeft
|
||||
scale={yScale}
|
||||
numTicks={4}
|
||||
tickFormat={(v) => gbpCompact(Number(v))}
|
||||
tickStroke="#94a3b8"
|
||||
stroke="#94a3b8"
|
||||
tickLabelProps={{ fill: '#64748b', fontSize: 10, textAnchor: 'end', dx: -4 }}
|
||||
/>
|
||||
|
||||
{/* Capture mouse + clicks. Last so it sits above the bands. */}
|
||||
<Bar
|
||||
x={0}
|
||||
y={0}
|
||||
width={innerW}
|
||||
height={innerH}
|
||||
fill="transparent"
|
||||
onMouseMove={handleMove}
|
||||
onMouseLeave={handleLeave}
|
||||
onClick={handleClick}
|
||||
style={{ cursor: onSelectYear ? 'pointer' : 'default' }}
|
||||
/>
|
||||
</Group>
|
||||
</svg>
|
||||
|
||||
{hoverPoint && hover && (
|
||||
<div
|
||||
className="absolute pointer-events-none rounded-md border border-slate-200 bg-white shadow-md text-xs px-3 py-2 tabular-nums"
|
||||
style={{
|
||||
left: Math.min(width - 180, hover.x + margin.left + 12),
|
||||
top: 8,
|
||||
}}
|
||||
>
|
||||
<div className="font-semibold text-slate-900 mb-1">Year {hover.year}</div>
|
||||
<Row dot={COLORS.base} label="Base" value={gbp(hoverPoint.base_gbp)} />
|
||||
<Row dot={COLORS.essential} label="Essential" value={gbp(hoverPoint.essential_gbp)} />
|
||||
<Row dot={COLORS.discretionary} label="Discretionary" value={gbp(hoverPoint.discretionary_gbp)} />
|
||||
{Number(hoverPoint.flex_cut_gbp) > 0 && (
|
||||
<Row dot={FLEX_CUT_COLOR} label="Flex cut" value={`−${gbp(hoverPoint.flex_cut_gbp)}`} />
|
||||
)}
|
||||
<hr className="my-1 border-slate-200" />
|
||||
<Row dot="" label="Total" value={gbp(hoverPoint.total_gbp)} bold />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FlexCutOverlay({
|
||||
points,
|
||||
xScale,
|
||||
yScale,
|
||||
}: {
|
||||
points: SpendingProfilePoint[];
|
||||
xScale: (n: number) => number;
|
||||
yScale: (n: number) => number;
|
||||
}) {
|
||||
// Marker tick at the top of each year that has a cut, with height
|
||||
// proportional to the cut amount. Keeps the area chart readable while
|
||||
// surfacing where flex was trimmed.
|
||||
return (
|
||||
<g>
|
||||
{points.map((p) => {
|
||||
const cut = Number(p.flex_cut_gbp);
|
||||
if (cut <= 0) return null;
|
||||
const total = Number(p.total_gbp) + cut;
|
||||
const top = yScale(total);
|
||||
const bottom = yScale(total - cut);
|
||||
const x = xScale(p.year_idx);
|
||||
return (
|
||||
<rect
|
||||
key={p.year_idx}
|
||||
x={x - 4}
|
||||
y={top}
|
||||
width={8}
|
||||
height={Math.max(2, bottom - top)}
|
||||
fill={FLEX_CUT_COLOR}
|
||||
stroke="rgba(220, 38, 38, 0.9)"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({
|
||||
dot,
|
||||
label,
|
||||
value,
|
||||
bold,
|
||||
}: {
|
||||
dot: string;
|
||||
label: string;
|
||||
value: string;
|
||||
bold?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={`flex items-baseline justify-between gap-3 ${bold ? 'font-semibold' : ''}`}>
|
||||
<span className="flex items-center gap-1.5">
|
||||
{dot && <span className="inline-block w-2.5 h-2.5 rounded-sm" style={{ background: dot }} />}
|
||||
<span className="text-slate-600">{label}</span>
|
||||
</span>
|
||||
<span className="text-slate-900">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,13 +1,19 @@
|
|||
/**
|
||||
* Plan-tab body for a scenario — Wave 1.A.x.
|
||||
* Plan-tab body — Wave 2 chart-first redesign.
|
||||
*
|
||||
* Layout:
|
||||
* ┌──────────────────────────────────────────┬──────────────┐
|
||||
* │ header + summary cards │ │
|
||||
* │ FanChart with milestone markers │ Year stats │
|
||||
* │ Year scrubber │ panel │
|
||||
* │ Income streams · Goals · Life events │ │
|
||||
* └──────────────────────────────────────────┴──────────────┘
|
||||
* Layout (chart is the SoT for editing life events):
|
||||
* ┌────────────────────────────────────────┐
|
||||
* │ NW fan + floating stats badges (top-R) │
|
||||
* │ year-scrubber along the bottom │
|
||||
* ├────────────────────────────────────────┤
|
||||
* │ Spending profile (stacked area) │
|
||||
* ├────────────────────────────────────────┤
|
||||
* │ Event Gantt (drag/click to edit) │
|
||||
* ├────────────────────────────────────────┤
|
||||
* │ Flex rules editor │
|
||||
* ├────────────────────────────────────────┤
|
||||
* │ Drawer: legacy form sections (collapsed)│
|
||||
* └────────────────────────────────────────┘
|
||||
*/
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
|
@ -15,12 +21,14 @@ import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
|||
|
||||
import { api, lifeEventsApi, type Scenario, type SimulateRequest } from '@/api/client';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { EventGantt } from '@/components/EventGantt';
|
||||
import { FanChart } from '@/components/FanChart';
|
||||
import { FlexRulesEditor } from '@/components/FlexRulesEditor';
|
||||
import { GoalsSection } from '@/components/GoalsSection';
|
||||
import { IncomeStreamsSection } from '@/components/IncomeStreamsSection';
|
||||
import { LifeEventsSection } from '@/components/LifeEventsSection';
|
||||
import { SpendingProfileChart } from '@/components/SpendingProfileChart';
|
||||
import { YearScrubber } from '@/components/YearScrubber';
|
||||
import { YearStatsPanel } from '@/components/YearStatsPanel';
|
||||
import { gbp, pct } from '@/lib/format';
|
||||
import { emojiFor } from '@/lib/milestone';
|
||||
|
||||
|
|
@ -52,6 +60,21 @@ export function ScenarioDetail() {
|
|||
enabled: Number.isFinite(id),
|
||||
});
|
||||
|
||||
const profile = useQuery({
|
||||
queryKey: ['spending-profile', id],
|
||||
queryFn: () => api.spendingProfile(id),
|
||||
enabled: Number.isFinite(id),
|
||||
staleTime: 0,
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
|
||||
const yearStats = useQuery({
|
||||
queryKey: ['year-stats', id, parseInt(searchParams.get('year') ?? '0', 10)],
|
||||
queryFn: () => api.yearStats(id, parseInt(searchParams.get('year') ?? '0', 10)),
|
||||
enabled: Number.isFinite(id) && proj.isSuccess,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const del = useMutation({
|
||||
mutationFn: () => api.scenarios.delete(id),
|
||||
onSuccess: () => {
|
||||
|
|
@ -103,6 +126,7 @@ export function ScenarioDetail() {
|
|||
|
||||
const onRunNow = async (s: Scenario) => {
|
||||
const fresh = await lifeEventsApi.list(s.id);
|
||||
const flexRules = readFlexRules(s);
|
||||
sim.mutate({
|
||||
jurisdiction: s.jurisdiction,
|
||||
strategy: s.strategy,
|
||||
|
|
@ -118,14 +142,14 @@ export function ScenarioDetail() {
|
|||
year_end: e.year_end,
|
||||
delta_gbp_per_year: e.delta_gbp_per_year,
|
||||
one_time_amount_gbp: e.one_time_amount_gbp,
|
||||
category: e.category,
|
||||
enabled: e.enabled,
|
||||
})),
|
||||
flex_rules: flexRules,
|
||||
});
|
||||
};
|
||||
|
||||
if (!Number.isFinite(id)) {
|
||||
return <p className="text-red-700">Invalid scenario id.</p>;
|
||||
}
|
||||
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 (
|
||||
|
|
@ -163,7 +187,7 @@ export function ScenarioDetail() {
|
|||
onClick={() => void onRunNow(s)}
|
||||
disabled={sim.isPending}
|
||||
className="rounded-md border border-slate-300 bg-white text-sm px-3 py-1.5 hover:bg-slate-50 disabled:opacity-60"
|
||||
title="Run a fresh MC including this scenario's life events"
|
||||
title="Run a fresh MC including this scenario's life events + flex rules"
|
||||
>
|
||||
{sim.isPending ? 'Running…' : 'Run now'}
|
||||
</button>
|
||||
|
|
@ -193,39 +217,76 @@ export function ScenarioDetail() {
|
|||
</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-1 lg:grid-cols-[1fr_280px] gap-6">
|
||||
<div className="space-y-4">
|
||||
<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)} />
|
||||
<>
|
||||
{/* NW fan with floating stat badges */}
|
||||
<div className="relative rounded-lg border border-slate-200 bg-white p-5">
|
||||
<div className="flex items-baseline justify-between mb-2">
|
||||
<h2 className="text-lg font-semibold">Portfolio fan</h2>
|
||||
<span className="text-xs text-slate-500">
|
||||
p10/p50/p90 over {projection.yearly.length}y · {projection.n_paths.toLocaleString()} paths
|
||||
</span>
|
||||
</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
|
||||
milestones={milestones}
|
||||
<FanChart
|
||||
yearly={projection.yearly}
|
||||
height={460}
|
||||
showWithdrawal
|
||||
milestones={milestones}
|
||||
selectedYear={year}
|
||||
onSelectYear={setYearAndUrl}
|
||||
/>
|
||||
<div className="mt-3">
|
||||
<YearScrubber value={year} min={0} max={maxYear} onChange={setYearAndUrl} />
|
||||
</div>
|
||||
<FloatingStats
|
||||
year={year}
|
||||
maxYear={maxYear}
|
||||
successRate={projection.success_rate}
|
||||
p50End={projection.p50_ending_gbp}
|
||||
netWorth={yearStats.data?.net_worth_p50}
|
||||
changeNw={yearStats.data?.change_in_nw}
|
||||
spending={yearStats.data?.spending}
|
||||
taxes={yearStats.data?.taxes}
|
||||
effectiveRate={yearStats.data?.effective_tax_rate}
|
||||
age={yearStats.data?.age ?? null}
|
||||
calendarYear={yearStats.data?.calendar_year}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Spending profile */}
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-5">
|
||||
<div className="flex items-baseline justify-between mb-2">
|
||||
<h2 className="text-lg font-semibold">Spending profile</h2>
|
||||
<Legend />
|
||||
</div>
|
||||
{profile.data ? (
|
||||
<SpendingProfileChart
|
||||
points={profile.data.points}
|
||||
selectedYear={year}
|
||||
onSelectYear={setYearAndUrl}
|
||||
/>
|
||||
<div className="mt-3">
|
||||
<YearScrubber value={year} min={0} max={maxYear} onChange={setYearAndUrl} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-slate-500">Loading…</p>
|
||||
)}
|
||||
</div>
|
||||
<YearStatsPanel scenarioId={id} year={year} />
|
||||
</div>
|
||||
|
||||
{/* Interactive Gantt */}
|
||||
<div className="rounded-lg border border-slate-200 bg-white p-5">
|
||||
<div className="flex items-baseline justify-between mb-2">
|
||||
<h2 className="text-lg font-semibold">Life events</h2>
|
||||
<span className="text-xs text-slate-500">
|
||||
Click empty space to add · drag bars to move · drag edges to resize
|
||||
</span>
|
||||
</div>
|
||||
<EventGantt
|
||||
scenarioId={id}
|
||||
events={events.data ?? []}
|
||||
horizonYears={horizonYears}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FlexRulesEditor scenario={s} />
|
||||
</>
|
||||
) : 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>
|
||||
|
|
@ -259,32 +320,105 @@ export function ScenarioDetail() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
<IncomeStreamsSection scenarioId={id} />
|
||||
<GoalsSection scenarioId={id} probabilities={projection?.goals_probability} />
|
||||
<LifeEventsSection scenarioId={id} />
|
||||
{/* Legacy form sections — collapsed by default. The chart UI above
|
||||
is the primary editor; these stay for bulk edit + accessibility. */}
|
||||
<details className="rounded-lg border border-slate-200 bg-white">
|
||||
<summary className="cursor-pointer select-none px-5 py-3 text-sm font-medium text-slate-700">
|
||||
Form-based editors (income streams · goals · life events table)
|
||||
</summary>
|
||||
<div className="p-5 space-y-5 border-t border-slate-100">
|
||||
<IncomeStreamsSection scenarioId={id} />
|
||||
<GoalsSection scenarioId={id} probabilities={projection?.goals_probability} />
|
||||
<LifeEventsSection scenarioId={id} />
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Stat({
|
||||
label,
|
||||
value,
|
||||
accent,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | number;
|
||||
accent?: boolean;
|
||||
function FloatingStats(props: {
|
||||
year: number;
|
||||
maxYear: number;
|
||||
successRate: string;
|
||||
p50End: string;
|
||||
netWorth?: string;
|
||||
changeNw?: string;
|
||||
spending?: string;
|
||||
taxes?: string;
|
||||
effectiveRate?: string;
|
||||
age: number | null;
|
||||
calendarYear?: number;
|
||||
}) {
|
||||
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 className="absolute top-3 right-3 grid grid-cols-2 gap-2 max-w-xs pointer-events-none">
|
||||
<Badge label="Year" value={String(props.calendarYear ?? `y${props.year}`)} />
|
||||
<Badge label="Age" value={props.age != null ? String(props.age) : '—'} />
|
||||
<Badge label="Net Worth" value={props.netWorth ? gbp(props.netWorth) : '—'} accent />
|
||||
<Badge
|
||||
label="Δ NW"
|
||||
value={props.changeNw ? gbp(props.changeNw) : '—'}
|
||||
signed={props.changeNw}
|
||||
/>
|
||||
<Badge label="Spending" value={props.spending ? gbp(props.spending) : '—'} />
|
||||
<Badge label="Eff. tax" value={props.effectiveRate ? pct(props.effectiveRate) : '—'} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Badge({
|
||||
label,
|
||||
value,
|
||||
accent,
|
||||
signed,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
accent?: boolean;
|
||||
signed?: string;
|
||||
}) {
|
||||
let cls = 'text-slate-700';
|
||||
if (accent) cls = 'text-emerald-700';
|
||||
if (signed != null) {
|
||||
const n = Number(signed);
|
||||
if (n > 0) cls = 'text-emerald-700';
|
||||
else if (n < 0) cls = 'text-red-600';
|
||||
}
|
||||
return (
|
||||
<div className="rounded-md border border-slate-200 bg-white/90 backdrop-blur px-2 py-1 shadow-sm pointer-events-auto">
|
||||
<div className="text-[9px] uppercase tracking-wide text-slate-500">{label}</div>
|
||||
<div className={`text-xs font-semibold tabular-nums ${cls}`}>{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Legend() {
|
||||
return (
|
||||
<div className="flex items-center gap-3 text-xs">
|
||||
<Swatch color="rgb(100, 116, 139)" label="Base" />
|
||||
<Swatch color="rgb(16, 185, 129)" label="Essential" />
|
||||
<Swatch color="rgb(245, 158, 11)" label="Discretionary" />
|
||||
<Swatch color="rgb(239, 68, 68)" label="Flex cut" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Swatch({ color, label }: { color: string; label: string }) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="inline-block w-2.5 h-2.5 rounded-sm" style={{ background: color }} />
|
||||
<span className="text-slate-600">{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function readFlexRules(s: Scenario): { from_ath_pct: string; cut_discretionary_pct: string }[] {
|
||||
const blob = s.config_json as Record<string, unknown>;
|
||||
const raw = blob?.flex_rules;
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.filter((r): r is Record<string, unknown> => typeof r === 'object' && r !== null)
|
||||
.map((r) => ({
|
||||
from_ath_pct: String(r.from_ath_pct ?? 0),
|
||||
cut_discretionary_pct: String(r.cut_discretionary_pct ?? 0),
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue