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
+41 -105
View File
@@ -1,139 +1,75 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { phaseInclude, getOwnedPhase } from "@/lib/queries";
import { getHouseholdOrNull, getOwnedPhase, getOwnedPlan, toPlanInput } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
const incomeEntrySchema = z.object({
personId: z.string().nullable().optional(),
label: z.string().nullable().optional(),
amount: z.number(),
});
const expenseEntrySchema = z.object({
label: z.string().nullable().optional(),
amount: z.number(),
});
const securitySchema = z.object({
name: z.string().min(1),
startValue: z.number(),
expectedReturn: z.number(),
annualContribution: z.number(),
ownerTag: z.enum(["PERSON_A", "PERSON_B", "HOUSEHOLD"]),
saleTaxRate: z.number().min(0).max(100),
carriedBaseValue: z.number().default(0),
});
const realEstateSchema = z.object({
name: z.string().min(1),
// Muss zwingend angegeben werden (siehe Anforderung: Kaufpreis ist Pflichtfeld).
purchasePrice: z.number().positive("Kaufpreis muss groesser als 0 sein."),
mortgage: z.number(),
amortization: z.number(),
});
const oneTimeEventSchema = z.object({
type: z.enum(["INCOME", "EXPENSE"]),
amount: z.number(),
description: z.string().nullable().optional(),
});
const retirementInfoSchema = z.object({
personId: z.string().min(1),
ahvAmount: z.number().min(0),
pkPensionAmount: z.number().min(0),
lumpSumAmount: z.number().min(0),
lumpSumTaxRate: z.number().min(0).max(100),
});
import { maxPhaseDuration } from "@/lib/calculations";
const updatePhaseSchema = z.object({
name: z.string().min(1).max(120),
durationYears: z.number().int().min(1).max(80),
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(),
incomeMode: z.enum(["PER_PERSON", "HOUSEHOLD"]),
incomeEntries: z.array(incomeEntrySchema).default([]),
expenseEntries: z.array(expenseEntrySchema).default([]),
securities: z.array(securitySchema).default([]),
realEstates: z.array(realEstateSchema).default([]),
oneTimeEvents: z.array(oneTimeEventSchema).default([]),
retirementInfos: z.array(retirementInfoSchema).default([]),
});
// Ersetzt eine Phase vollstaendig (Basisfelder + alle Unter-Sammlungen). Fuer ein
// Single-User-Tool ohne nennenswerte Nebenlaeufigkeit ist ein "delete + recreate" der
// Kindobjekte einfacher und robuster als granulares Diffing pro Zeile.
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ phaseId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) {
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { phaseId } = await params;
const body = await request.json();
const parsed = updatePhaseSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const data = parsed.data;
const existing = await getOwnedPhase(phaseId, userId);
if (!existing) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
if (!existing) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
const body = await request.json();
const parsed = updatePhaseSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
let duration = parsed.data.durationYears;
if (duration != null) {
// Dauer ans naechste Pensionsereignis kappen (Jahre vor dieser Phase).
const household = await getHouseholdOrNull(userId);
const plan = await getOwnedPlan(existing.planId, userId);
if (household && plan) {
const planInput = toPlanInput(plan);
const yearsBefore = planInput.phases
.filter((p) => p.sequenceNumber < existing.sequenceNumber)
.reduce((s, p) => s + p.durationYears, 0);
const cap = maxPhaseDuration(household.persons, planInput, yearsBefore);
if (cap != null) duration = Math.min(duration, cap);
duration = Math.max(1, duration);
}
}
const phase = await prisma.$transaction(async (tx) => {
await Promise.all([
tx.incomeEntry.deleteMany({ where: { phaseId } }),
tx.expenseEntry.deleteMany({ where: { phaseId } }),
tx.security.deleteMany({ where: { phaseId } }),
tx.realEstate.deleteMany({ where: { phaseId } }),
tx.oneTimeEvent.deleteMany({ where: { phaseId } }),
tx.retirementInfo.deleteMany({ where: { phaseId } }),
]);
return tx.phase.update({
where: { id: phaseId },
data: {
name: data.name,
durationYears: data.durationYears,
inflationRate: data.inflationRate ?? null,
incomeMode: data.incomeMode,
incomeEntries: { create: data.incomeEntries.map((e) => ({ ...e, label: e.label ?? null, personId: e.personId ?? null })) },
expenseEntries: { create: data.expenseEntries.map((e) => ({ ...e, label: e.label ?? null })) },
securities: { create: data.securities },
realEstates: { create: data.realEstates },
oneTimeEvents: { create: data.oneTimeEvents.map((e) => ({ ...e, description: e.description ?? null })) },
retirementInfos: { create: data.retirementInfos },
},
include: phaseInclude,
});
const phase = await prisma.phase.update({
where: { id: phaseId },
data: {
name: parsed.data.name ?? undefined,
durationYears: duration ?? undefined,
inflationRate: parsed.data.inflationRate === undefined ? undefined : parsed.data.inflationRate,
},
});
return NextResponse.json({ phase });
return NextResponse.json({ phase: { id: phase.id } });
}
// Eine Phase kann nur geloescht werden, wenn sie die letzte in der Kette ist -- so
// bleibt die Verkettung (Schlussvermoegen = Startvermoegen der Folgephase) immer intakt.
// Nur die letzte Phase kann geloescht werden (Verkettung bleibt intakt).
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ phaseId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) {
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { phaseId } = await params;
const phase = await getOwnedPhase(phaseId, userId);
if (!phase) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
}
const laterPhase = await prisma.phase.findFirst({
const phase = await getOwnedPhase(phaseId, userId);
if (!phase) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
const later = await prisma.phase.findFirst({
where: { planId: phase.planId, sequenceNumber: { gt: phase.sequenceNumber } },
});
if (laterPhase) {
return NextResponse.json(
{ error: "Nur die letzte Phase eines Plans kann geloescht werden." },
{ status: 400 }
);
if (later) {
return NextResponse.json({ error: "Nur die letzte Phase kann geloescht werden." }, { status: 400 });
}
await prisma.phase.delete({ where: { id: phaseId } });