import { useEffect, useState } from 'react' import { createFileRoute } from '@tanstack/react-router' import { colToLetter, formatValue } from '@tanstack/spreadsheet-core' import { useRevision } from '@tanstack/react-spreadsheet' import { cellValueFacade } from '@tanstack/spreadsheet-store' import { BUDGET, CATEGORY_NAMES, MODEL, MODEL_CELLS, TXN, modelVal, ref, } from '../budget/model' import { approveReallocation, pullForwardHardware } from '../budget/scenario' import { auditLog, budgetWorkbook, recordAudit, resetBudget, } from '../budget/store' import { isError, isPendingValue } from '../seed' import type { CellValue, Workbook } from '@tanstack/spreadsheet-core' export const Route = createFileRoute('/budget/')({ component: BudgetPageRoute, }) function BudgetPageRoute() { const [wb, setWb] = useState(null) const [resetN, setResetN] = useState(0) useEffect(() => setWb(budgetWorkbook()), []) if (!wb) return
Loading budget…
return ( { setWb(resetBudget()) setResetN((n) => n + 1) }} /> ) } const num = (v: CellValue): number => (typeof v === 'number' ? v : NaN) /** One living workbook: spreadsheet + data on the left, the guardrail graph on the right (60/40). */ function BudgetPage({ wb, onReset }: { wb: Workbook; onReset: () => void }) { const rev = useRevision(wb) return (

Dashboard

Spreadsheet

Every number here is live. The{' '} underlined blue cells are editable raw inputs (category anchors, transaction amounts, cash/payroll/one-off) — click one, type a value, press Enter, and watch the graph and runway react. Everything else (Actual, Lower, Upper, Total, burn, runway) is a{' '} computed formula and is read-only — hover to read its equation.

Review queue

) } /* ---------------- Dashboard ---------------- */ function readCats(wb: Workbook) { return CATEGORY_NAMES.map((name, i) => { const r = i + 1 return { name, anchor: num(wb.getCell(ref(BUDGET, r, 1))?.value ?? null), actual: wb.getCell(ref(BUDGET, r, 2))?.value ?? null, lower: num(wb.getCell(ref(BUDGET, r, 3))?.value ?? null), upper: num(wb.getCell(ref(BUDGET, r, 4))?.value ?? null), status: wb.getCell(ref(BUDGET, r, 5))?.value ?? null, } }) } /** KPIs + feed status (the "data", left column). */ function KpiRow({ wb, onReset }: { wb: Workbook; onReset: () => void }) { const classifying = readCats(wb).some((c) => isPendingValue(c.actual)) const trueRunway = modelVal(wb, MODEL_CELLS.trueRunway) const builtinRunway = modelVal(wb, MODEL_CELLS.builtinRunway) const burn = modelVal(wb, MODEL_CELLS.burn) return ( <>
{classifying ? 'classifying feed…' : 'settled'}
) } /** Category spend vs guardrail band — the graph (right column). */ function BarsChart({ wb }: { wb: Workbook }) { const cats = readCats(wb) const scaleMax = Math.max(...cats.map((c) => (Number.isFinite(c.upper) ? c.upper : 0)), 1) * 1.25 return ( <>
Category spend vs guardrail band (anchor ±20%):
{cats.map((c) => { const actual = isPendingValue(c.actual) ? null : num(c.actual) const pct = (v: number) => `${Math.min(100, (v / scaleMax) * 100)}%` const status = String(c.status ?? '') return (
{c.name}
{actual !== null && (
)}
{isPendingValue(c.actual) ? '…' : `${formatValue(c.actual)} · ${status}`}
) })}
) } function Kpi({ label, value, highlight, pending, }: { label: string value: string highlight?: boolean pending?: boolean }) { return (
{pending ? '…' : value} {label}
) } /* ---------------- Editable spreadsheet ---------------- */ const SHEETS = [ { id: BUDGET, label: 'Budget', rows: 7, cols: 6 }, { id: TXN, label: 'Transactions', rows: 10, cols: 5 }, { id: MODEL, label: 'Model', rows: 9, cols: 2 }, ] function SheetStack({ wb }: { wb: Workbook }) { // key of the cell being edited: `${sheet}:${row}:${col}` const [editing, setEditing] = useState(null) const [draft, setDraft] = useState('') const display = (v: CellValue, fmt?: string) => isPendingValue(v) ? '…' : formatValue(v, fmt) const commit = (sheet: string, row: number, col: number) => { wb.applyPatches(wb.setInput({ sheet, row, col }, draft)) setEditing(null) } return (
{SHEETS.map((sheet) => (
{sheet.label}
))} {Array.from({ length: sheet.rows }, (_, r) => ( {Array.from({ length: sheet.cols }, (_, c) => { const cl = wb.getCell({ sheet: sheet.id, row: r, col: c }) const v = cl?.value ?? null const fmt = wb.getFormat({ sheet: sheet.id, row: r, col: c, }) const isFormula = cl?.kind === 'formula' // A number that isn't computed by a formula is a raw input: editable. const editable = !isFormula && typeof v === 'number' const key = `${sheet.id}:${r}:${c}` if (editing === key) { return ( ) } return ( ) })} ))}
{Array.from({ length: sheet.cols }, (_, c) => ( {colToLetter(c)}
{r + 1} setDraft(e.target.value)} onBlur={() => commit(sheet.id, r, c)} onKeyDown={(e) => { if (e.key === 'Enter') commit(sheet.id, r, c) else if (e.key === 'Escape') setEditing(null) }} /> { setDraft(cl?.input ?? String(v)) setEditing(key) } : undefined } > {display(v, fmt)}
))}
) } /* ---------------- Review queue ---------------- */ /** Rewrite the guardrail band formulas to a tighter/looser percentage. */ function setBands(wb: Workbook, pct: number) { const lo = (1 - pct).toFixed(2) const hi = (1 + pct).toFixed(2) const patches = [] for (let i = 0; i < 5; i++) { const r = i + 1 const a = r + 1 patches.push(...wb.setInput(ref(BUDGET, r, 3), `=B${a}*${lo}`)) patches.push(...wb.setInput(ref(BUDGET, r, 4), `=B${a}*${hi}`)) } wb.applyPatches(patches) } function Review({ wb }: { wb: Workbook }) { const [applied, setApplied] = useState(false) const realloc = pullForwardHardware(wb) const gate = cellValueFacade(wb, ref(MODEL, MODEL_CELLS.gate, 1)) // the gate IS a cell const gateOpen = gate.get() === true const log = auditLog() const approve = () => { const entry = approveReallocation(wb, realloc, 'CFO') recordAudit(entry) setApplied(true) } return ( <> {/* --- staged reallocation diff --- */}
{realloc.label} {realloc.rationale}
{realloc.diff.map((d) => ( ))}
Cell What Before After
{d.a1} {d.label} {d.before || '(blank)'} {d.after}
Runway {formatValue(modelVal(wb, MODEL_CELLS.trueRunway))} months → preview after approval.
{/* --- state-manager proof: the button's enabled state IS a cell --- */}
Approval gate model!B9 = {formatValue(gate.get())}
The Approve button is enabled by a cell ( =COUNTIF(budget!F2:F6,"OK")=5), read through a §6.1 Store facade. Change the guardrail equation and the button's behaviour changes — no code edited.
{/* --- audit trail --- */}
Audit trail
{log.length === 0 &&
(no approvals yet)
} {log.map((e, i) => (
{e.label} — approved by {e.approver} runway {formatValue(e.runwayBefore)} →{' '} {formatValue(e.runwayAfter)}
            {e.diff
              .map((d) => `${d.a1}: ${d.before || '∅'} → ${d.after}`)
              .join('\n')}
            {'\n'}functions:{' '}
            {e.functions.map((f) => `${f.name}@${f.version}`).join(', ')}
          
))} ) }