V3: 3 Farbschemata, Grundprofil auf Plan-Ebene, Erstellungs-Popups, integer-Zahlenfelder mit Beschleunigungs-Spinner, Carry-Forward des Zielwerts, gefuehrter Uebergang
Deploy App / deploy (push) Successful in 1m51s

- Theming: semantische CSS-Tokens + 3 waehlbare Schemata (Hell/Dunkel/Warm/Sunset), Umschalter im Profil-Menue, FOUC-frei via Inline-Script, localStorage; Klassen-Sweep aller Komponenten, Recharts aus Tokens
- Datenmodell: Household entfaellt; Plan traegt Haushaltsform/Personen/Inflation selbst (Person -> planId, Plan -> userId); destruktive Migration (TRUNCATE); Onboarding/HouseholdSettings entfernt; Plan-Erstellung & -Einstellungen mit Profilfeldern
- Popups: Element-Erstellung mit Inline-Feldern (geteilte ElementPhaseFields/ElementTransitionFields), Phase- und Plan-Popups mit Direkteingabe
- Zahlenfelder: 1'000er-Runden entfernt (floorToThousand/roundToHundred weg), integer MoneyInput mit beschleunigendem Press-and-Hold-Spinner, 0-Bug-Fix, harte Live-Caps
- Quote: Amortisation + Tilgung neu quotenwirksam; Restquote sichtbar (sinkt beim Verteilen); Invest-Deckel = verfuegbares Kapital + fortgeschriebener Zielwert
- Carry-Forward: Startwert der Folgephase = Zielwert der Vorphase minus Uebergangs-Bezug (live abgeleitet); optionale Zusatzinvestition aus verfuegbarem Kapital
- Matrix: Zelle zeigt Start -> Ziel; Uebergangs-Spaltenkopf mit "n offen"-Badge + gefuehrtem Pruef-Panel

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-13 14:49:42 +02:00
parent b775ab77cb
commit 32adfb4476
32 changed files with 1706 additions and 1290 deletions
+2 -6
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { toHouseholdInput, toPlanInput, getHouseholdOrNull, getOwnedPlan } from "@/lib/queries";
import { toPlanInput, getOwnedPlan } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { computePlan, planToCsv } from "@/lib/calculations";
@@ -12,10 +12,6 @@ export async function GET(
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
const { planId } = await params;
const household = await getHouseholdOrNull(userId);
if (!household) {
return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
}
const plan = await getOwnedPlan(planId, userId);
if (!plan) {
@@ -23,7 +19,7 @@ export async function GET(
}
const planInput = toPlanInput(plan);
const computed = computePlan(planInput, toHouseholdInput(household));
const computed = computePlan(planInput);
const csv = planToCsv(planInput, computed);
return new NextResponse(csv, {
+21 -33
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getHouseholdOrNull, getOwnedPlan, toHouseholdInput, toPlanInput } from "@/lib/queries";
import { getOwnedPlan, toPlanInput } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { Prisma } from "@/generated/prisma/client";
import { computePlan, maxPhaseDuration } from "@/lib/calculations";
@@ -10,11 +10,12 @@ import { num, type PhaseData } from "@/lib/elements";
const createPhaseSchema = z.object({
name: z.string().min(1).max(120).optional(),
durationYears: z.number().int().min(1).max(80).optional(),
inflationRate: z.number().min(-20).max(50).nullable().optional(),
});
// Legt eine neue Lebensphase am Ende der Kette an. Die Dauer wird ans naechste
// Pensionsereignis gekappt. Fuer bestehende Elemente werden die Werte 1:1 bzw. mit
// den fortgeschriebenen Endbestaenden aus der Vorphase vorbelegt.
// Pensionsereignis gekappt. Fuer bestehende Elemente werden die editierbaren Felder
// vorbelegt; die Startwerte werden in der Berechnung live aus der Vorphase fortgeschrieben.
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
@@ -23,8 +24,6 @@ export async function POST(
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { planId } = await params;
const household = await getHouseholdOrNull(userId);
if (!household) return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
const plan = await getOwnedPlan(planId, userId);
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
@@ -32,10 +31,9 @@ export async function POST(
const parsed = createPhaseSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
const householdInput = toHouseholdInput(household);
const planInput = toPlanInput(plan);
const yearsBefore = planInput.phases.reduce((s, p) => s + p.durationYears, 0);
const cap = maxPhaseDuration(household.persons, planInput, yearsBefore);
const cap = maxPhaseDuration(planInput.persons, yearsBefore);
let duration = parsed.data.durationYears ?? (cap ?? 10);
if (cap != null) duration = Math.min(duration, cap);
@@ -44,18 +42,15 @@ export async function POST(
const nextSequence = planInput.phases.length + 1;
// Phasentyp der neuen Phase fuer den Default-Namen bestimmen.
const anyRetiredAtStart = household.persons.some((p) => {
const ra = p.role === "PERSON_A" ? planInput.retirementAgeA ?? p.retirementAge : planInput.retirementAgeB ?? p.retirementAge;
return p.age + yearsBefore >= ra;
});
const anyRetiredAtStart = planInput.persons.some((p) => p.age + yearsBefore >= p.retirementAge);
const defaultName =
parsed.data.name ?? (nextSequence === 1 ? "Erste Lebensphase" : anyRetiredAtStart ? "Pensionsphase" : "Erwerbsphase");
// Endbestaende der bisher letzten Phase (fuer Carry-Vorbelegung).
const prevComputed = planInput.phases.length > 0 ? computePlan(planInput, householdInput) : null;
// Status der Elemente in der bisher letzten Phase (verkauft/getilgt nicht fortfuehren).
const prevComputed = planInput.phases.length > 0 ? computePlan(planInput) : null;
const lastPhaseId = planInput.phases.at(-1)?.id;
const prevPhase = prevComputed?.phases.find((p) => p.id === lastPhaseId) ?? null;
const prevElemById = new Map((prevPhase?.elements ?? []).map((e) => [e.elementId, e]));
const prevStatusById = new Map((prevPhase?.elements ?? []).map((e) => [e.elementId, e.status]));
const phase = await prisma.$transaction(async (tx) => {
const created = await tx.phase.create({
@@ -64,15 +59,15 @@ export async function POST(
sequenceNumber: nextSequence,
name: defaultName,
durationYears: duration,
inflationRate: parsed.data.inflationRate ?? undefined,
},
});
// Carry-Vorbelegung fuer bestehende Elemente.
// Vorbelegung der editierbaren Felder bestehender Elemente.
for (const e of planInput.elements) {
const prev = prevElemById.get(e.id);
if (prev && prev.status !== "ACTIVE") continue; // verkauft/getilgt -> nicht mehr fortfuehren
if ((prevStatusById.get(e.id) ?? "ACTIVE") !== "ACTIVE") continue; // verkauft/getilgt
const prevData: PhaseData = e.phaseValues[lastPhaseId ?? ""] ?? {};
const data: PhaseData = buildCarryData(e.category, prevData, prev?.endValue);
const data: PhaseData = buildCarryData(e.category, prevData);
await tx.elementPhaseValue.create({
data: { elementId: e.id, phaseId: created.id, data: data as Prisma.InputJsonValue },
});
@@ -84,12 +79,10 @@ export async function POST(
return NextResponse.json({ phase: { id: phase.id } }, { status: 201 });
}
function buildCarryData(
category: string,
prev: PhaseData,
prevEndValue: number | undefined
): PhaseData {
const endVal = Math.max(0, Math.round(prevEndValue ?? 0));
// Vorbelegung fuer eine neue Phase: nur die editierbaren Felder werden uebernommen. Start-
// bzw. Restwerte (PK/3a/Vermoegen/Hypothek/Schuld) werden in der Berechnung live aus der
// Vorphase fortgeschrieben und deshalb hier NICHT als Snapshot gespeichert.
function buildCarryData(category: string, prev: PhaseData): PhaseData {
switch (category) {
case "INCOME":
case "EXPENSE":
@@ -98,18 +91,13 @@ function buildCarryData(
return { gapYears: 0 };
case "PENSION_FUND":
case "PILLAR_3A":
return { currentValue: endVal, annualContribution: num(prev.annualContribution), expectedReturn: num(prev.expectedReturn) };
case "OTHER_ASSET":
return { startValue: endVal, annualContribution: num(prev.annualContribution), expectedReturn: num(prev.expectedReturn) };
return { annualContribution: num(prev.annualContribution), expectedReturn: num(prev.expectedReturn) };
case "REAL_ESTATE":
// endValue = purchase - mortgage; Hypothek fortschreiben ueber purchasePrice - endValue.
return {
purchasePrice: num(prev.purchasePrice),
mortgage: Math.max(0, num(prev.purchasePrice) - endVal),
amortization: num(prev.amortization),
};
// purchasePrice + amortization bleiben; die Resthypothek wird live fortgeschrieben.
return { purchasePrice: num(prev.purchasePrice), amortization: num(prev.amortization) };
case "OTHER_DEBT":
return { startValue: Math.abs(endVal), annualRepayment: num(prev.annualRepayment) };
return { annualRepayment: num(prev.annualRepayment) };
default:
return {};
}
+32 -18
View File
@@ -1,9 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { toHouseholdInput, toPlanInput, getHouseholdOrNull, getOwnedPlan } from "@/lib/queries";
import { toPlanInput, getOwnedPlan } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { computePlan } from "@/lib/calculations";
import { planProfileSchema, validatePersonsForType } from "@/app/api/plans/route";
export async function GET(
_request: NextRequest,
@@ -13,24 +14,20 @@ export async function GET(
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { planId } = await params;
const household = await getHouseholdOrNull(userId);
if (!household) return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
const plan = await getOwnedPlan(planId, userId);
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
const householdInput = toHouseholdInput(household);
const planInput = toPlanInput(plan);
const computed = computePlan(planInput, householdInput);
const computed = computePlan(planInput);
return NextResponse.json({ plan: planInput, computed });
}
const patchSchema = z.object({
name: z.string().min(1).max(120).optional(),
retirementAgeA: z.number().int().min(30).max(100).nullable().optional(),
retirementAgeB: z.number().int().min(30).max(100).nullable().optional(),
});
// Name allein aendern ODER das ganze Plan-Profil (Haushaltsform/Personen/Inflation).
const patchSchema = z.union([
z.object({ name: z.string().min(1).max(120) }),
planProfileSchema.extend({ name: z.string().min(1).max(120).optional() }),
]);
export async function PATCH(
request: NextRequest,
@@ -40,20 +37,37 @@ export async function PATCH(
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { planId } = await params;
const plan = await prisma.plan.findFirst({ where: { id: planId, household: { userId } } });
const plan = await prisma.plan.findFirst({ where: { id: planId, userId } });
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
const body = await request.json();
const parsed = patchSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
const data = parsed.data;
const hasProfile = "householdType" in data;
if (hasProfile) {
const error = validatePersonsForType(data);
if (error) return NextResponse.json({ error }, { status: 400 });
const updated = await prisma.$transaction(async (tx) => {
await tx.person.deleteMany({ where: { planId: plan.id } });
return tx.plan.update({
where: { id: plan.id },
data: {
name: data.name ?? undefined,
householdType: data.householdType,
inflationRateDefault: data.inflationRateDefault,
persons: { create: data.persons },
},
});
});
return NextResponse.json({ plan: { id: updated.id, name: updated.name } });
}
const updated = await prisma.plan.update({
where: { id: plan.id },
data: {
name: parsed.data.name ?? undefined,
retirementAgeA: parsed.data.retirementAgeA === undefined ? undefined : parsed.data.retirementAgeA,
retirementAgeB: parsed.data.retirementAgeB === undefined ? undefined : parsed.data.retirementAgeB,
},
data: { name: data.name },
});
return NextResponse.json({ plan: { id: updated.id, name: updated.name } });
}
@@ -65,7 +79,7 @@ export async function DELETE(
const userId = await getCurrentUserId();
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { planId } = await params;
const plan = await prisma.plan.findFirst({ where: { id: planId, household: { userId } } });
const plan = await prisma.plan.findFirst({ where: { id: planId, userId } });
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
await prisma.plan.delete({ where: { id: plan.id } });
return NextResponse.json({ ok: true });
+6 -3
View File
@@ -36,11 +36,14 @@ export async function POST(
const newPlanId = await prisma.$transaction(async (tx) => {
const newPlan = await tx.plan.create({
data: {
householdId: source.householdId,
userId,
name: parsed.data.name,
retirementAgeA: source.retirementAgeA,
retirementAgeB: source.retirementAgeB,
householdType: source.householdType,
inflationRateDefault: source.inflationRateDefault,
parentPlanId: source.id,
persons: {
create: source.persons.map((p) => ({ role: p.role, age: p.age, retirementAge: p.retirementAge })),
},
},
});
+36 -17
View File
@@ -1,24 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getHouseholdOrNull } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
const createPlanSchema = z.object({
name: z.string().min(1).max(120),
const personSchema = z.object({
role: z.enum(["PERSON_A", "PERSON_B"]),
age: z.number().int().min(0).max(120),
retirementAge: z.number().int().min(30).max(100),
});
// Ein Plan traegt sein eigenes Grundprofil (Haushaltsform, Personen, Inflation).
export const planProfileSchema = z.object({
householdType: z.enum(["SINGLE", "COUPLE"]),
inflationRateDefault: z.number().min(-20).max(50),
persons: z.array(personSchema).min(1).max(2),
});
const createPlanSchema = z
.object({ name: z.string().min(1).max(120) })
.and(planProfileSchema);
export function validatePersonsForType(data: z.infer<typeof planProfileSchema>): string | null {
if (data.householdType === "SINGLE" && data.persons.length !== 1) {
return "Einzelperson-Plan benoetigt genau eine Person.";
}
if (data.householdType === "COUPLE" && data.persons.length !== 2) {
return "Paar-Plan benoetigt genau zwei Personen (Person A und Person B).";
}
return null;
}
export async function GET() {
const userId = await getCurrentUserId();
if (!userId) {
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
const household = await getHouseholdOrNull(userId);
if (!household) {
return NextResponse.json({ plans: [] });
}
const plans = await prisma.plan.findMany({
where: { householdId: household.id },
where: { userId },
orderBy: { createdAt: "asc" },
select: {
id: true,
@@ -40,23 +58,24 @@ export async function POST(request: NextRequest) {
if (!userId) {
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
const household = await getHouseholdOrNull(userId);
if (!household) {
return NextResponse.json(
{ error: "Bitte zuerst das Grundprofil (Onboarding) anlegen." },
{ status: 400 }
);
}
const body = await request.json();
const parsed = createPlanSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const error = validatePersonsForType(parsed.data);
if (error) return NextResponse.json({ error }, { status: 400 });
const plan = await prisma.plan.create({
data: { householdId: household.id, name: parsed.data.name },
data: {
userId,
name: parsed.data.name,
householdType: parsed.data.householdType,
inflationRateDefault: parsed.data.inflationRateDefault,
persons: { create: parsed.data.persons },
},
});
return NextResponse.json({ plan }, { status: 201 });
return NextResponse.json({ plan: { id: plan.id } }, { status: 201 });
}