Rework core model: financial elements as plan-wide entities across phases; derived phase types (Erwerb/Pension/Misch) with retirement-capped durations and per-plan retirement age; AHV (gap years + couple ceiling), PK payout/annuity, 3a, real estate, other assets/debts; horizontal timeline with retirement markers; phase x element matrix with detail panel; savings/consumption quota + available-capital key figures with red status
Deploy App / deploy (push) Successful in 1m57s

This commit is contained in:
2026-07-13 07:55:58 +02:00
parent b3a3b565ac
commit b775ab77cb
27 changed files with 2407 additions and 2166 deletions
+581
View File
@@ -0,0 +1,581 @@
"use client";
import { useMemo, useState } from "react";
import {
AlertCircle,
Building2,
CheckCircle2,
ChevronDown,
ChevronRight,
CreditCard,
Home,
Landmark,
PiggyBank,
Plus,
ShoppingCart,
TrendingUp,
Wallet,
} from "lucide-react";
import { Timeline } from "@/components/Timeline";
import { ElementDetail, type CellContext } from "@/components/ElementDetail";
import { PhaseDetail } from "@/components/PhaseDetail";
import { api } from "@/lib/api-client";
import { formatChf } from "@/lib/format";
import {
CATEGORY_LABELS,
CATEGORY_ORDER,
PERSON_ONLY_CATEGORIES,
num,
type ElementCategory,
} from "@/lib/elements";
import { resolveRetirementAge, type PhaseComputed, type PlanComputed } from "@/lib/calculations";
import type { ElementInput, HouseholdInput, PlanInput } from "@/lib/types";
const PERSON_A_COLOR = "#4f46e5";
const PERSON_B_COLOR = "#0ea5e9";
const CATEGORY_ICON: Record<ElementCategory, React.ReactNode> = {
INCOME: <Wallet className="h-4 w-4" />,
EXPENSE: <ShoppingCart className="h-4 w-4" />,
AHV: <Landmark className="h-4 w-4" />,
PENSION_FUND: <Building2 className="h-4 w-4" />,
PILLAR_3A: <PiggyBank className="h-4 w-4" />,
REAL_ESTATE: <Home className="h-4 w-4" />,
OTHER_ASSET: <TrendingUp className="h-4 w-4" />,
OTHER_DEBT: <CreditCard className="h-4 w-4" />,
};
const TRANSITION_CATEGORIES: ElementCategory[] = [
"PENSION_FUND",
"PILLAR_3A",
"REAL_ESTATE",
"OTHER_ASSET",
"OTHER_DEBT",
];
type Column =
| { kind: "phase"; phase: PhaseComputed }
| { kind: "transition"; fromPhase: PhaseComputed; toPhase: PhaseComputed };
type Selection =
| { type: "phaseCell"; elementId: string; phaseId: string }
| { type: "transitionCell"; elementId: string; fromPhaseId: string }
| { type: "phase"; phaseId: string };
export function PlanView({
plan,
household,
computed,
onChanged,
}: {
plan: PlanInput;
household: HouseholdInput;
computed: PlanComputed;
onChanged: () => void;
}) {
const [selected, setSelected] = useState<Selection | null>(null);
const [collapsedCats, setCollapsedCats] = useState<Set<ElementCategory>>(new Set());
const [showAdd, setShowAdd] = useState(false);
const columns = useMemo<Column[]>(() => {
const cols: Column[] = [];
computed.phases.forEach((p, i) => {
cols.push({ kind: "phase", phase: p });
if (i < computed.phases.length - 1) {
cols.push({ kind: "transition", fromPhase: p, toPhase: computed.phases[i + 1] });
}
});
return cols;
}, [computed.phases]);
const personAxes = household.persons.map((p) => ({
role: p.role,
label: p.role === "PERSON_A" ? "Person A" : "Person B",
currentAge: p.age,
retirementAge: resolveRetirementAge(p.role, plan, p.retirementAge),
color: p.role === "PERSON_A" ? PERSON_A_COLOR : PERSON_B_COLOR,
}));
const elementsByCategory = useMemo(() => {
const map = new Map<ElementCategory, ElementInput[]>();
for (const cat of CATEGORY_ORDER) map.set(cat, []);
for (const e of [...plan.elements].sort((a, b) => a.orderIndex - b.orderIndex)) {
map.get(e.category)!.push(e);
}
return map;
}, [plan.elements]);
function computedElement(phaseId: string, elementId: string) {
return computed.phases.find((p) => p.id === phaseId)?.elements.find((e) => e.elementId === elementId);
}
function isRetirementTransition(element: ElementInput, fromPhase: PhaseComputed, toPhase: PhaseComputed): boolean {
if (!element.ownerRole || element.ownerRole === "HOUSEHOLD") return false;
const before = fromPhase.persons.find((p) => p.role === element.ownerRole);
const after = toPhase.persons.find((p) => p.role === element.ownerRole);
return !!before?.working && !!after && !after.working;
}
async function handleAddPhase() {
await api.post(`/api/plans/${plan.id}/phases`, {});
onChanged();
}
const hasPhases = computed.phases.length > 0;
return (
<div className="flex flex-col gap-5">
<Timeline phases={computed.phases} persons={personAxes} />
{/* Pensionsalter-Overrides */}
<div className="flex flex-wrap items-center gap-3 rounded-xl border border-zinc-200/70 bg-white px-4 py-3 text-sm shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<span className="text-xs font-semibold uppercase tracking-wide text-zinc-400">Pensionsalter (Plan)</span>
{household.persons.map((p) => (
<label key={p.role} className="flex items-center gap-1.5 text-xs text-zinc-600 dark:text-zinc-300">
{p.role === "PERSON_A" ? "Person A" : "Person B"}:
<input
type="number"
defaultValue={resolveRetirementAge(p.role, plan, p.retirementAge)}
className="w-16 rounded-lg border border-zinc-300 px-2 py-1 text-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-zinc-700 dark:bg-zinc-800"
onBlur={async (e) => {
const val = parseInt(e.target.value, 10);
if (!Number.isFinite(val)) return;
await api.patch(`/api/plans/${plan.id}`, {
[p.role === "PERSON_A" ? "retirementAgeA" : "retirementAgeB"]: val,
});
onChanged();
}}
/>
</label>
))}
<span className="text-[11px] text-zinc-400">Standard aus Grundprofil, hier pro Plan uebersteuerbar.</span>
</div>
{!hasPhases && (
<div className="rounded-xl border border-dashed border-zinc-300 bg-white p-8 text-center dark:border-zinc-700 dark:bg-zinc-900">
<p className="text-sm text-zinc-500">Dieser Plan hat noch keine Lebensphasen.</p>
<button
type="button"
onClick={handleAddPhase}
className="mt-3 inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500 dark:bg-indigo-500"
>
<Plus className="h-4 w-4" /> Erste Lebensphase
</button>
</div>
)}
{hasPhases && (
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setShowAdd(true)}
className="flex items-center gap-1.5 rounded-lg bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white shadow-sm hover:bg-indigo-500 dark:bg-indigo-500 dark:hover:bg-indigo-400"
>
<Plus className="h-4 w-4" /> Finanzielles Element
</button>
<button
type="button"
onClick={handleAddPhase}
className="flex items-center gap-1.5 rounded-lg border border-dashed border-indigo-300 bg-indigo-50/50 px-3 py-1.5 text-sm font-medium text-indigo-700 hover:bg-indigo-50 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-300"
>
<Plus className="h-4 w-4" /> Lebensphase
</button>
</div>
)}
{/* Matrix */}
{hasPhases && (
<div className="overflow-x-auto rounded-xl border border-zinc-200/70 bg-white shadow-sm dark:border-zinc-800 dark:bg-zinc-900">
<table className="w-full border-collapse text-sm">
<thead>
<tr>
<th className="sticky left-0 z-20 min-w-44 border-b border-r border-zinc-200 bg-zinc-50 px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:border-zinc-800 dark:bg-zinc-800/60">
Finanzielle Elemente
</th>
{columns.map((col) =>
col.kind === "phase" ? (
<PhaseHeader
key={col.phase.id}
phase={col.phase}
onClick={() => setSelected({ type: "phase", phaseId: col.phase.id })}
active={selected?.type === "phase" && selected.phaseId === col.phase.id}
/>
) : (
<th
key={`t-${col.fromPhase.id}`}
className="border-b border-r border-zinc-200 bg-indigo-50/40 px-2 py-2 text-center text-[11px] font-medium text-indigo-500 dark:border-zinc-800 dark:bg-indigo-500/5"
>
Uebergang
</th>
)
)}
</tr>
</thead>
<tbody>
{CATEGORY_ORDER.map((cat) => {
const els = elementsByCategory.get(cat)!;
if (els.length === 0) return null;
const collapsed = collapsedCats.has(cat);
return (
<FragmentRows key={cat}>
<tr className="bg-zinc-50/60 dark:bg-zinc-800/30">
<td
className="sticky left-0 z-10 cursor-pointer border-b border-r border-zinc-200 bg-zinc-50/90 px-3 py-1.5 dark:border-zinc-800 dark:bg-zinc-800/60"
onClick={() =>
setCollapsedCats((prev) => {
const next = new Set(prev);
if (next.has(cat)) next.delete(cat);
else next.add(cat);
return next;
})
}
>
<span className="flex items-center gap-1.5 text-xs font-semibold text-zinc-600 dark:text-zinc-300">
{collapsed ? <ChevronRight className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
<span className="text-indigo-500 dark:text-indigo-400">{CATEGORY_ICON[cat]}</span>
{CATEGORY_LABELS[cat]}
</span>
</td>
<td colSpan={columns.length} className="border-b border-zinc-200 dark:border-zinc-800" />
</tr>
{!collapsed &&
els.map((el) => (
<tr key={el.id} className="hover:bg-zinc-50/50 dark:hover:bg-zinc-800/20">
<td className="sticky left-0 z-10 border-b border-r border-zinc-200 bg-white px-3 py-1.5 dark:border-zinc-800 dark:bg-zinc-900">
<div className="truncate text-xs font-medium text-zinc-800 dark:text-zinc-200">{el.name}</div>
{el.ownerRole && el.ownerRole !== "HOUSEHOLD" && (
<div className="text-[10px] text-zinc-400">
{el.ownerRole === "PERSON_A" ? "Person A" : "Person B"}
</div>
)}
</td>
{columns.map((col) => {
if (col.kind === "phase") {
const ce = computedElement(col.phase.id, el.id);
const isSel =
selected?.type === "phaseCell" &&
selected.elementId === el.id &&
selected.phaseId === col.phase.id;
return (
<td
key={col.phase.id}
onClick={() => setSelected({ type: "phaseCell", elementId: el.id, phaseId: col.phase.id })}
className={`cursor-pointer border-b border-r border-zinc-200 px-2 py-1.5 text-center text-xs dark:border-zinc-800 ${
isSel ? "bg-indigo-100 dark:bg-indigo-500/20" : ""
} ${ce?.locked ? "text-zinc-400" : "text-zinc-700 dark:text-zinc-200"}`}
>
{ce?.summary ?? ""}
</td>
);
}
const canTransition = TRANSITION_CATEGORIES.includes(el.category);
const isSel =
selected?.type === "transitionCell" &&
selected.elementId === el.id &&
selected.fromPhaseId === col.fromPhase.id;
return (
<td
key={`t-${col.fromPhase.id}`}
onClick={() =>
canTransition &&
setSelected({ type: "transitionCell", elementId: el.id, fromPhaseId: col.fromPhase.id })
}
className={`border-b border-r border-zinc-200 px-2 py-1.5 text-center text-[11px] dark:border-zinc-800 ${
canTransition ? "cursor-pointer text-indigo-500" : "text-zinc-300 dark:text-zinc-600"
} ${isSel ? "bg-indigo-100 dark:bg-indigo-500/20" : "bg-indigo-50/30 dark:bg-indigo-500/5"}`}
>
{canTransition ? transitionSummary(el, col.fromPhase, col.toPhase) : "→"}
</td>
);
})}
</tr>
))}
</FragmentRows>
);
})}
{plan.elements.length === 0 && (
<tr>
<td className="sticky left-0 bg-white px-3 py-4 text-xs text-zinc-400 dark:bg-zinc-900" colSpan={columns.length + 1}>
Noch keine finanziellen Elemente. Fuegen Sie oben Ihr erstes Element hinzu.
</td>
</tr>
)}
</tbody>
</table>
</div>
)}
{/* Detail-Panel */}
{selected && (
<div className="rounded-xl border border-indigo-200 bg-white p-4 shadow-sm dark:border-indigo-500/30 dark:bg-zinc-900">
{renderDetail()}
</div>
)}
{showAdd && (
<AddElementDialog
household={household}
onClose={() => setShowAdd(false)}
onCreate={async (payload) => {
await api.post(`/api/plans/${plan.id}/elements`, payload);
setShowAdd(false);
onChanged();
}}
/>
)}
</div>
);
function renderDetail() {
if (!selected) return null;
if (selected.type === "phase") {
const phase = computed.phases.find((p) => p.id === selected.phaseId);
const phaseInput = plan.phases.find((p) => p.id === selected.phaseId);
if (!phase || !phaseInput) return null;
const isLast = phase.sequenceNumber === computed.phases.length;
return (
<PhaseDetail
phase={phaseInput}
maxDurationYears={phase.maxDurationYears}
isLast={isLast}
household={household}
onSaved={onChanged}
onDeleted={() => {
setSelected(null);
onChanged();
}}
/>
);
}
const element = plan.elements.find((e) => e.id === selected.elementId);
if (!element) return null;
if (selected.type === "phaseCell") {
const phase = computed.phases.find((p) => p.id === selected.phaseId)!;
const ownerWorking = element.ownerRole && element.ownerRole !== "HOUSEHOLD"
? phase.persons.find((p) => p.role === element.ownerRole)?.working ?? false
: phase.type !== "PENSION";
const ce = computedElement(phase.id, element.id);
const context: CellContext = {
kind: "phase",
phaseId: phase.id,
ownerWorking,
isConsumption: phase.isConsumption,
durationYears: phase.durationYears,
isRetirementTransition: false,
carriedEndValue: ce?.endValue ?? 0,
};
return (
<ElementDetail
element={element}
context={context}
phaseData={element.phaseValues[phase.id] ?? {}}
transitionData={{}}
onSaved={onChanged}
onDeleteElement={() => deleteElement(element.id)}
/>
);
}
// transitionCell
const fromPhase = computed.phases.find((p) => p.id === selected.fromPhaseId)!;
const toIndex = computed.phases.findIndex((p) => p.id === fromPhase.id) + 1;
const toPhase = computed.phases[toIndex];
const ce = computedElement(fromPhase.id, element.id);
const context: CellContext = {
kind: "transition",
phaseId: fromPhase.id,
ownerWorking: true,
isConsumption: fromPhase.isConsumption,
durationYears: fromPhase.durationYears,
isRetirementTransition: toPhase ? isRetirementTransition(element, fromPhase, toPhase) : false,
carriedEndValue: ce?.endValue ?? 0,
};
return (
<ElementDetail
element={element}
context={context}
phaseData={{}}
transitionData={element.transitionValues[fromPhase.id] ?? {}}
onSaved={onChanged}
onDeleteElement={() => deleteElement(element.id)}
/>
);
}
async function deleteElement(id: string) {
if (!confirm("Dieses Element wirklich loeschen (aus allen Phasen)?")) return;
await api.delete(`/api/elements/${id}`);
setSelected(null);
onChanged();
}
function transitionSummary(el: ElementInput, fromPhase: PhaseComputed, toPhase: PhaseComputed): string {
const td = el.transitionValues[fromPhase.id] ?? {};
switch (el.category) {
case "REAL_ESTATE":
case "OTHER_ASSET":
return td.decision === "SELL" ? "Verkauf" : "Halten";
case "PENSION_FUND":
if (isRetirementTransition(el, fromPhase, toPhase)) {
return td.payoutMode === "CAPITAL" ? "Kapital" : td.payoutMode === "COMBI" ? "Kombi" : "Rente";
}
return num(td.withdrawal) > 0 ? `${formatChf(num(td.withdrawal))}` : "→";
case "PILLAR_3A":
if (isRetirementTransition(el, fromPhase, toPhase)) return "Bezug";
return num(td.withdrawal) > 0 ? `${formatChf(num(td.withdrawal))}` : "→";
case "OTHER_DEBT":
return num(td.immediateRepayment) > 0 ? "Tilgung" : "→";
default:
return "→";
}
}
}
function PhaseHeader({ phase, onClick, active }: { phase: PhaseComputed; onClick: () => void; active: boolean }) {
const quotaLabel = phase.isConsumption ? "Verzehr" : "Sparquote";
return (
<th
onClick={onClick}
className={`min-w-40 cursor-pointer border-b border-r border-zinc-200 px-2 py-2 text-left align-top dark:border-zinc-800 ${
active ? "bg-indigo-100 dark:bg-indigo-500/20" : "bg-white dark:bg-zinc-900"
}`}
>
<div className="flex items-center gap-1">
<span className="truncate text-xs font-semibold text-zinc-800 dark:text-zinc-100">{phase.name}</span>
{phase.incomplete ? (
<AlertCircle className="h-3.5 w-3.5 shrink-0 text-red-500" />
) : (
<CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-emerald-500" />
)}
</div>
<div className="mt-0.5 flex flex-wrap gap-1">
<span className="rounded bg-zinc-100 px-1 text-[10px] text-zinc-500 dark:bg-zinc-800">
{phase.type === "ERWERB" ? "Erwerb" : phase.type === "PENSION" ? "Pension" : "Misch"}
</span>
<span className="text-[10px] text-zinc-400">{phase.durationYears} J.</span>
<span className="text-[10px] text-zinc-400">Alter {phase.persons.map((p) => p.startAge).join("/")}</span>
</div>
<div className="mt-1 space-y-0.5 text-[10px] leading-tight text-zinc-500 dark:text-zinc-400">
<div>Einkommen {formatChf(phase.incomeTotal)}</div>
<div>Ausgaben {formatChf(phase.expenseTotal)}</div>
<div className={phase.quotaComplete ? "text-emerald-600 dark:text-emerald-400" : "text-red-600 dark:text-red-400"}>
{quotaLabel} {formatChf(Math.abs(phase.quota))}
</div>
<div className={phase.availableCapitalComplete ? "" : "text-red-600 dark:text-red-400"}>
Kapital {phase.availableCapital === null ? "n.a." : formatChf(phase.availableCapital)}
</div>
</div>
</th>
);
}
function FragmentRows({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
function AddElementDialog({
household,
onClose,
onCreate,
}: {
household: HouseholdInput;
onClose: () => void;
onCreate: (payload: { category: ElementCategory; name: string; ownerRole: string | null }) => void;
}) {
const [category, setCategory] = useState<ElementCategory>("INCOME");
const [name, setName] = useState("");
const [ownerRole, setOwnerRole] = useState<string>(household.householdType === "COUPLE" ? "PERSON_A" : "PERSON_A");
const needsPerson = PERSON_ONLY_CATEGORIES.includes(category);
const isCouple = household.householdType === "COUPLE";
const ownerOptions = needsPerson
? isCouple
? [
{ value: "PERSON_A", label: "Person A" },
{ value: "PERSON_B", label: "Person B" },
]
: [{ value: "PERSON_A", label: "Person A" }]
: isCouple
? [
{ value: "HOUSEHOLD", label: "Gemeinsam" },
{ value: "PERSON_A", label: "Person A" },
{ value: "PERSON_B", label: "Person B" },
]
: [
{ value: "HOUSEHOLD", label: "Gemeinsam" },
{ value: "PERSON_A", label: "Person A" },
];
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/40 px-4" onClick={onClose}>
<div
onClick={(e) => e.stopPropagation()}
className="flex w-full max-w-md flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-6 shadow-xl dark:border-zinc-700 dark:bg-zinc-900"
>
<h2 className="text-base font-semibold text-zinc-900 dark:text-zinc-50">Finanzielles Element</h2>
<div>
<label className="mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400">Kategorie</label>
<select
value={category}
onChange={(e) => {
const c = e.target.value as ElementCategory;
setCategory(c);
if (PERSON_ONLY_CATEGORIES.includes(c) && ownerRole === "HOUSEHOLD") setOwnerRole("PERSON_A");
if (!name) setName(CATEGORY_LABELS[c]);
}}
className="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-zinc-600 dark:bg-zinc-950"
>
{CATEGORY_ORDER.map((c) => (
<option key={c} value={c}>
{CATEGORY_LABELS[c]}
</option>
))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400">Bezeichnung</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={CATEGORY_LABELS[category]}
className="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-zinc-600 dark:bg-zinc-950"
/>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-zinc-600 dark:text-zinc-400">Zuordnung</label>
<select
value={ownerRole}
onChange={(e) => setOwnerRole(e.target.value)}
className="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 dark:border-zinc-600 dark:bg-zinc-950"
>
{ownerOptions.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={() => onCreate({ category, name: name.trim() || CATEGORY_LABELS[category], ownerRole })}
className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-500 dark:bg-indigo-500 dark:hover:bg-indigo-400"
>
Erstellen
</button>
<button
type="button"
onClick={onClose}
className="rounded-lg border border-zinc-300 px-4 py-2 text-sm font-medium text-zinc-700 hover:bg-zinc-50 dark:border-zinc-700 dark:text-zinc-200 dark:hover:bg-zinc-800"
>
Abbrechen
</button>
</div>
</div>
</div>
);
}