fire-planner: Wave 2 chart-first — flex spending, categorised life
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:
Viktor Barzin 2026-05-10 16:49:04 +00:00
parent 9cc781a8d6
commit 64eb90c3dc
19 changed files with 2581 additions and 88 deletions

View file

@ -9,6 +9,13 @@
"version": "0.0.1",
"dependencies": {
"@tanstack/react-query": "^5.62.0",
"@visx/axis": "^3.12.0",
"@visx/event": "^3.12.0",
"@visx/group": "^3.12.0",
"@visx/responsive": "^3.12.0",
"@visx/scale": "^3.12.0",
"@visx/shape": "^3.12.0",
"@visx/tooltip": "^3.12.0",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.2",
"react": "^19.0.0",
@ -19,6 +26,7 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.0",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.0",
@ -1897,7 +1905,6 @@
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
@ -1986,8 +1993,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
@ -2057,12 +2063,33 @@
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
"license": "MIT"
},
"node_modules/@types/d3-delaunay": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz",
"integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==",
"license": "MIT"
},
"node_modules/@types/d3-ease": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
"license": "MIT"
},
"node_modules/@types/d3-format": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz",
"integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==",
"license": "MIT"
},
"node_modules/@types/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
@ -2102,6 +2129,12 @@
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
},
"node_modules/@types/d3-time-format": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz",
"integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
@ -2122,6 +2155,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@ -2129,6 +2168,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/lodash": {
"version": "4.17.24",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.24.tgz",
"integrity": "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "22.19.18",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.18.tgz",
@ -2143,7 +2188,6 @@
"version": "19.2.14",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@ -2153,7 +2197,6 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
@ -2460,6 +2503,305 @@
"url": "https://opencollective.com/eslint"
}
},
"node_modules/@visx/axis": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/axis/-/axis-3.12.0.tgz",
"integrity": "sha512-8MoWpfuaJkhm2Yg+HwyytK8nk+zDugCqTT/tRmQX7gW4LYrHYLXFUXOzbDyyBakCVaUbUaAhVFxpMASJiQKf7A==",
"license": "MIT",
"dependencies": {
"@types/react": "*",
"@visx/group": "3.12.0",
"@visx/point": "3.12.0",
"@visx/scale": "3.12.0",
"@visx/shape": "3.12.0",
"@visx/text": "3.12.0",
"classnames": "^2.3.1",
"prop-types": "^15.6.0"
},
"peerDependencies": {
"react": "^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/bounds": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/bounds/-/bounds-3.12.0.tgz",
"integrity": "sha512-peAlNCUbYaaZ0IO6c1lDdEAnZv2iGPDiLIM8a6gu7CaMhtXZJkqrTh+AjidNcIqITktrICpGxJE/Qo9D099dvQ==",
"license": "MIT",
"dependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"prop-types": "^15.5.10"
},
"peerDependencies": {
"react": "^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0",
"react-dom": "^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/curve": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-3.12.0.tgz",
"integrity": "sha512-Ng1mefXIzoIoAivw7dJ+ZZYYUbfuwXgZCgQynShr6ZIVw7P4q4HeQfJP3W24ON+1uCSrzoycHSXRelhR9SBPcw==",
"license": "MIT",
"dependencies": {
"@types/d3-shape": "^1.3.1",
"d3-shape": "^1.0.6"
}
},
"node_modules/@visx/curve/node_modules/@types/d3-path": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.11.tgz",
"integrity": "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw==",
"license": "MIT"
},
"node_modules/@visx/curve/node_modules/@types/d3-shape": {
"version": "1.3.12",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.12.tgz",
"integrity": "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "^1"
}
},
"node_modules/@visx/curve/node_modules/d3-path": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
"integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
"license": "BSD-3-Clause"
},
"node_modules/@visx/curve/node_modules/d3-shape": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
"integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
"license": "BSD-3-Clause",
"dependencies": {
"d3-path": "1"
}
},
"node_modules/@visx/event": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/event/-/event-3.12.0.tgz",
"integrity": "sha512-9Lvw6qJ0Fi+y1vsC1WspfdIKCxHTb7oy59Uql1uBdPGT8zChP0vuxW0jQNQRDbKgoefj4pCXAFi8+MF1mEtVTw==",
"license": "MIT",
"dependencies": {
"@types/react": "*",
"@visx/point": "3.12.0"
}
},
"node_modules/@visx/group": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/group/-/group-3.12.0.tgz",
"integrity": "sha512-Dye8iS1alVXPv7nj/7M37gJe6sSKqJLH7x6sEWAsRQ9clI0kFvjbKcKgF+U3aAVQr0NCohheFV+DtR8trfK/Ag==",
"license": "MIT",
"dependencies": {
"@types/react": "*",
"classnames": "^2.3.1",
"prop-types": "^15.6.2"
},
"peerDependencies": {
"react": "^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/point": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/point/-/point-3.12.0.tgz",
"integrity": "sha512-I6UrHoJAEVbx3RORQNupgTiX5EzjuZpiwLPxn8L2mI5nfERotPKi1Yus12Cq2WtXqEBR/WgqTnoImlqOXBykcA==",
"license": "MIT"
},
"node_modules/@visx/responsive": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/responsive/-/responsive-3.12.0.tgz",
"integrity": "sha512-GV1BTYwAGlk/K5c9vH8lS2syPnTuIqEacI7L6LRPbsuaLscXMNi+i9fZyzo0BWvAdtRV8v6Urzglo++lvAXT1Q==",
"license": "MIT",
"dependencies": {
"@types/lodash": "^4.14.172",
"@types/react": "*",
"lodash": "^4.17.21",
"prop-types": "^15.6.1"
},
"peerDependencies": {
"react": "^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/scale": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/scale/-/scale-3.12.0.tgz",
"integrity": "sha512-+ubijrZ2AwWCsNey0HGLJ0YKNeC/XImEFsr9rM+Uef1CM3PNM43NDdNTrdBejSlzRq0lcfQPWYMYQFSlkLcPOg==",
"license": "MIT",
"dependencies": {
"@visx/vendor": "3.12.0"
}
},
"node_modules/@visx/shape": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/shape/-/shape-3.12.0.tgz",
"integrity": "sha512-/1l0lrpX9tPic6SJEalryBKWjP/ilDRnQA+BGJTI1tj7i23mJ/J0t4nJHyA1GrL4QA/bM/qTJ35eyz5dEhJc4g==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "^1.0.8",
"@types/d3-shape": "^1.3.1",
"@types/lodash": "^4.14.172",
"@types/react": "*",
"@visx/curve": "3.12.0",
"@visx/group": "3.12.0",
"@visx/scale": "3.12.0",
"classnames": "^2.3.1",
"d3-path": "^1.0.5",
"d3-shape": "^1.2.0",
"lodash": "^4.17.21",
"prop-types": "^15.5.10"
},
"peerDependencies": {
"react": "^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/shape/node_modules/@types/d3-path": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.11.tgz",
"integrity": "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw==",
"license": "MIT"
},
"node_modules/@visx/shape/node_modules/@types/d3-shape": {
"version": "1.3.12",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.12.tgz",
"integrity": "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "^1"
}
},
"node_modules/@visx/shape/node_modules/d3-path": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
"integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
"license": "BSD-3-Clause"
},
"node_modules/@visx/shape/node_modules/d3-shape": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
"integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
"license": "BSD-3-Clause",
"dependencies": {
"d3-path": "1"
}
},
"node_modules/@visx/text": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/text/-/text-3.12.0.tgz",
"integrity": "sha512-0rbDYQlbuKPhBqXkkGYKFec1gQo05YxV45DORzr6hCyaizdJk1G+n9VkuKSHKBy1vVQhBA0W3u/WXd7tiODQPA==",
"license": "MIT",
"dependencies": {
"@types/lodash": "^4.14.172",
"@types/react": "*",
"classnames": "^2.3.1",
"lodash": "^4.17.21",
"prop-types": "^15.7.2",
"reduce-css-calc": "^1.3.0"
},
"peerDependencies": {
"react": "^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/tooltip": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/tooltip/-/tooltip-3.12.0.tgz",
"integrity": "sha512-pWhsYhgl0Shbeqf80qy4QCB6zpq6tQtMQQxKlh3UiKxzkkfl+Metaf9p0/S0HexNi4vewOPOo89xWx93hBeh3A==",
"license": "MIT",
"dependencies": {
"@types/react": "*",
"@visx/bounds": "3.12.0",
"classnames": "^2.3.1",
"prop-types": "^15.5.10",
"react-use-measure": "^2.0.4"
},
"peerDependencies": {
"react": "^16.8.0-0 || ^17.0.0-0 || ^18.0.0-0",
"react-dom": "^16.8.0-0 || ^17.0.0-0 || ^18.0.0-0"
}
},
"node_modules/@visx/vendor": {
"version": "3.12.0",
"resolved": "https://registry.npmjs.org/@visx/vendor/-/vendor-3.12.0.tgz",
"integrity": "sha512-SVO+G0xtnL9dsNpGDcjCgoiCnlB3iLSM9KLz1sLbSrV7RaVXwY3/BTm2X9OWN1jH2a9M+eHt6DJ6sE6CXm4cUg==",
"license": "MIT and ISC",
"dependencies": {
"@types/d3-array": "3.0.3",
"@types/d3-color": "3.1.0",
"@types/d3-delaunay": "6.0.1",
"@types/d3-format": "3.0.1",
"@types/d3-geo": "3.1.0",
"@types/d3-interpolate": "3.0.1",
"@types/d3-scale": "4.0.2",
"@types/d3-time": "3.0.0",
"@types/d3-time-format": "2.1.0",
"d3-array": "3.2.1",
"d3-color": "3.1.0",
"d3-delaunay": "6.0.2",
"d3-format": "3.1.0",
"d3-geo": "3.1.0",
"d3-interpolate": "3.0.1",
"d3-scale": "4.0.2",
"d3-time": "3.1.0",
"d3-time-format": "4.1.0",
"internmap": "2.0.3"
}
},
"node_modules/@visx/vendor/node_modules/@types/d3-array": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz",
"integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==",
"license": "MIT"
},
"node_modules/@visx/vendor/node_modules/@types/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==",
"license": "MIT"
},
"node_modules/@visx/vendor/node_modules/@types/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@visx/vendor/node_modules/@types/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@visx/vendor/node_modules/@types/d3-time": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz",
"integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==",
"license": "MIT"
},
"node_modules/@visx/vendor/node_modules/d3-array": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz",
"integrity": "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@visx/vendor/node_modules/d3-format": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
"integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/@vitejs/plugin-react": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
@ -2652,7 +2994,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@ -2704,7 +3045,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
@ -2850,6 +3190,12 @@
"node": ">= 16"
}
},
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
"integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
"license": "MIT"
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@ -2946,7 +3292,6 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
@ -2970,6 +3315,18 @@
"node": ">=12"
}
},
"node_modules/d3-delaunay": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz",
"integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==",
"license": "ISC",
"dependencies": {
"delaunator": "5"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-ease": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@ -2988,6 +3345,18 @@
"node": ">=12"
}
},
"node_modules/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==",
"license": "ISC",
"dependencies": {
"d3-array": "2.5.0 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
@ -3132,6 +3501,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/delaunator": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
"integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
"license": "ISC",
"dependencies": {
"robust-predicates": "^3.0.2"
}
},
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@ -3157,8 +3535,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/echarts": {
"version": "6.0.0",
@ -3831,7 +4208,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@ -4235,6 +4611,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@ -4242,6 +4624,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@ -4265,7 +4659,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@ -4280,6 +4673,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/math-expression-evaluator": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.4.0.tgz",
"integrity": "sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==",
"license": "MIT"
},
"node_modules/min-indent": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
@ -4350,6 +4749,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@ -4528,7 +4936,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@ -4544,7 +4951,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@ -4552,13 +4958,22 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/pretty-format/node_modules/react-is": {
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"license": "MIT",
"peer": true
"dependencies": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"node_modules/prop-types/node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/punycode": {
"version": "2.3.1",
@ -4592,11 +5007,11 @@
}
},
"node_modules/react-is": {
"version": "19.2.6",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.6.tgz",
"integrity": "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw==",
"license": "MIT",
"peer": true
"version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT"
},
"node_modules/react-redux": {
"version": "9.2.0",
@ -4669,6 +5084,21 @@
"react-dom": ">=18"
}
},
"node_modules/react-use-measure": {
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",
"integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.13",
"react-dom": ">=16.13"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/recharts": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.8.1.tgz",
@ -4713,6 +5143,32 @@
"node": ">=8"
}
},
"node_modules/reduce-css-calc": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz",
"integrity": "sha512-0dVfwYVOlf/LBA2ec4OwQ6p3X9mYxn/wOl2xTcLwjnPYrkgEfPx3VI4eGCH3rQLlPISG5v9I9bkZosKsNRTRKA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^0.4.2",
"math-expression-evaluator": "^1.2.14",
"reduce-function-call": "^1.0.1"
}
},
"node_modules/reduce-css-calc/node_modules/balanced-match": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz",
"integrity": "sha512-STw03mQKnGUYtoNjmowo4F2cRmIIxYEGiMsjjwla/u5P1lxadj/05WkNaFjNiKTgJkj8KiXbgAiRTmcQRwQNtg==",
"license": "MIT"
},
"node_modules/reduce-function-call": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.3.tgz",
"integrity": "sha512-Hl/tuV2VDgWgCSEeWMLwxLZqX7OK59eU1guxXsRKTAyeYimivsKdtcV4fu3r710tpG5GmDKDhQ0HSZLExnNmyQ==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
@ -4744,6 +5200,12 @@
"node": ">=4"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rollup": {
"version": "4.60.3",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.3.tgz",

View file

@ -14,6 +14,13 @@
},
"dependencies": {
"@tanstack/react-query": "^5.62.0",
"@visx/axis": "^3.12.0",
"@visx/event": "^3.12.0",
"@visx/group": "^3.12.0",
"@visx/responsive": "^3.12.0",
"@visx/scale": "^3.12.0",
"@visx/shape": "^3.12.0",
"@visx/tooltip": "^3.12.0",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.2",
"react": "^19.0.0",
@ -24,6 +31,7 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.6.0",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.0",

View file

@ -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;

View 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(' ');
}

View 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>
);
}

View 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>
);
}

View file

@ -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),
}));
}