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
+49 -76
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { phaseInclude, getOwnedPlan } from "@/lib/queries";
import { getOwnedPlan } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
const scenarioSchema = z.object({
@@ -9,114 +9,87 @@ const scenarioSchema = z.object({
branchFromPhaseId: z.string().min(1),
});
// Erstellt ein neues Szenario als Kopie eines bestehenden Plans ab einer gewaehlten
// Phase (inklusive). Die Phasenkette bis zu diesem Punkt wird per Deep-Copy dupliziert;
// ab dort kann der Benutzer die Kette unabhaengig weiterentwickeln (TDD Kapitel 13).
// Erstellt ein Szenario als Deep-Copy eines Plans bis zur Verzweigungsphase (inkl.).
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ planId: 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 { planId } = await params;
const body = await request.json();
const parsed = scenarioSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
const sourcePlan = await getOwnedPlan(planId, userId);
if (!sourcePlan) {
return NextResponse.json({ error: "Ursprungsplan nicht gefunden." }, { status: 404 });
}
const source = await getOwnedPlan(planId, userId);
if (!source) return NextResponse.json({ error: "Ursprungsplan nicht gefunden." }, { status: 404 });
const branchPhase = sourcePlan.phases.find((p) => p.id === parsed.data.branchFromPhaseId);
if (!branchPhase) {
return NextResponse.json({ error: "Verzweigungsphase nicht gefunden." }, { status: 404 });
}
const branchPhase = source.phases.find((p) => p.id === parsed.data.branchFromPhaseId);
if (!branchPhase) return NextResponse.json({ error: "Verzweigungsphase nicht gefunden." }, { status: 404 });
const phasesToCopy = sourcePlan.phases
const copiedPhases = source.phases
.filter((p) => p.sequenceNumber <= branchPhase.sequenceNumber)
.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
const copiedPhaseIds = new Set(copiedPhases.map((p) => p.id));
const newPlanId = await prisma.$transaction(async (tx) => {
const newPlan = await tx.plan.create({
data: {
householdId: sourcePlan.householdId,
householdId: source.householdId,
name: parsed.data.name,
parentPlanId: sourcePlan.id,
retirementAgeA: source.retirementAgeA,
retirementAgeB: source.retirementAgeB,
parentPlanId: source.id,
},
});
// Phasen kopieren (alte -> neue Id).
const phaseIdMap = new Map<string, string>();
let lastNewPhaseId = "";
for (const phase of phasesToCopy) {
const newPhase = await tx.phase.create({
for (const phase of copiedPhases) {
const created = await tx.phase.create({
data: {
planId: newPlan.id,
sequenceNumber: phase.sequenceNumber,
name: phase.name,
durationYears: phase.durationYears,
inflationRate: phase.inflationRate,
incomeMode: phase.incomeMode,
incomingCapital: phase.incomingCapital,
incomeEntries: {
create: phase.incomeEntries.map((e) => ({
personId: e.personId,
label: e.label,
amount: e.amount,
})),
},
expenseEntries: {
create: phase.expenseEntries.map((e) => ({ label: e.label, amount: e.amount })),
},
securities: {
create: phase.securities.map((s) => ({
name: s.name,
startValue: s.startValue,
expectedReturn: s.expectedReturn,
annualContribution: s.annualContribution,
ownerTag: s.ownerTag,
saleTaxRate: s.saleTaxRate,
carriedBaseValue: s.carriedBaseValue,
})),
},
realEstates: {
create: phase.realEstates.map((re) => ({
name: re.name,
purchasePrice: re.purchasePrice,
mortgage: re.mortgage,
amortization: re.amortization,
})),
},
oneTimeEvents: {
create: phase.oneTimeEvents.map((e) => ({
type: e.type,
amount: e.amount,
description: e.description,
})),
},
retirementInfos: {
create: phase.retirementInfos.map((r) => ({
personId: r.personId,
ahvAmount: r.ahvAmount,
pkPensionAmount: r.pkPensionAmount,
lumpSumAmount: r.lumpSumAmount,
lumpSumTaxRate: r.lumpSumTaxRate,
})),
},
},
include: phaseInclude,
});
lastNewPhaseId = newPhase.id;
phaseIdMap.set(phase.id, created.id);
lastNewPhaseId = created.id;
}
await tx.plan.update({
where: { id: newPlan.id },
data: { branchFromPhaseId: lastNewPhaseId },
});
// Elemente + deren Phasen-/Uebergangswerte kopieren.
for (const el of source.elements) {
const newEl = await tx.financialElement.create({
data: {
planId: newPlan.id,
category: el.category,
name: el.name,
ownerRole: el.ownerRole,
orderIndex: el.orderIndex,
},
});
for (const pv of el.phaseValues) {
const newPhaseId = phaseIdMap.get(pv.phaseId);
if (!newPhaseId) continue;
await tx.elementPhaseValue.create({
data: { elementId: newEl.id, phaseId: newPhaseId, data: pv.data as object },
});
}
for (const tv of el.transitionValues) {
if (!copiedPhaseIds.has(tv.fromPhaseId)) continue;
const newFromId = phaseIdMap.get(tv.fromPhaseId);
if (!newFromId) continue;
await tx.elementTransitionValue.create({
data: { elementId: newEl.id, fromPhaseId: newFromId, data: tv.data as object },
});
}
}
await tx.plan.update({ where: { id: newPlan.id }, data: { branchFromPhaseId: lastNewPhaseId } });
return newPlan.id;
});