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
Deploy App / deploy (push) Successful in 1m57s
This commit is contained in:
@@ -1,72 +1,116 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { phaseInclude } from "@/lib/queries";
|
||||
import { getHouseholdOrNull, getOwnedPlan, toHouseholdInput, toPlanInput } from "@/lib/queries";
|
||||
import { getCurrentUserId } from "@/lib/session";
|
||||
import { Prisma } from "@/generated/prisma/client";
|
||||
import { computePlan, maxPhaseDuration } from "@/lib/calculations";
|
||||
import { num, type PhaseData } from "@/lib/elements";
|
||||
|
||||
const createPhaseSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
durationYears: z.number().int().min(1).max(80),
|
||||
inflationRate: z.number().min(-20).max(50).nullable().optional(),
|
||||
incomeMode: z.enum(["PER_PERSON", "HOUSEHOLD"]).default("HOUSEHOLD"),
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
durationYears: z.number().int().min(1).max(80).optional(),
|
||||
});
|
||||
|
||||
// Fuegt eine neue Lebensabschnittsphase am Ende der Phasenkette eines Plans an
|
||||
// (TDD Kapitel 3: Phasen werden chronologisch aneinandergereiht).
|
||||
// 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.
|
||||
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 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 body = await request.json().catch(() => ({}));
|
||||
const parsed = createPhaseSchema.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 plan = await prisma.plan.findFirst({ where: { id: planId, household: { userId } } });
|
||||
if (!plan) {
|
||||
return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
|
||||
}
|
||||
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 lastPhase = await prisma.phase.findFirst({
|
||||
where: { planId },
|
||||
orderBy: { sequenceNumber: "desc" },
|
||||
include: { incomeEntries: true, expenseEntries: true },
|
||||
let duration = parsed.data.durationYears ?? (cap ?? 10);
|
||||
if (cap != null) duration = Math.min(duration, cap);
|
||||
duration = Math.max(1, duration);
|
||||
|
||||
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 nextSequence = (lastPhase?.sequenceNumber ?? 0) + 1;
|
||||
const defaultName =
|
||||
parsed.data.name ?? (nextSequence === 1 ? "Erste Lebensphase" : anyRetiredAtStart ? "Pensionsphase" : "Erwerbsphase");
|
||||
|
||||
// Einkommen und Ausgaben werden 1:1 aus der letzten Phase uebernommen (manuell
|
||||
// anpassbar), damit man sie nicht bei jeder neuen Phase erneut eintippen muss.
|
||||
const phase = await prisma.phase.create({
|
||||
data: {
|
||||
planId,
|
||||
sequenceNumber: nextSequence,
|
||||
name: parsed.data.name,
|
||||
durationYears: parsed.data.durationYears,
|
||||
inflationRate: parsed.data.inflationRate ?? null,
|
||||
incomeMode: lastPhase?.incomeMode ?? parsed.data.incomeMode,
|
||||
incomeEntries: lastPhase
|
||||
? {
|
||||
create: lastPhase.incomeEntries.map((e) => ({
|
||||
personId: e.personId,
|
||||
label: e.label,
|
||||
amount: e.amount,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
expenseEntries: lastPhase
|
||||
? {
|
||||
create: lastPhase.expenseEntries.map((e) => ({ label: e.label, amount: e.amount })),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
include: phaseInclude,
|
||||
// Endbestaende der bisher letzten Phase (fuer Carry-Vorbelegung).
|
||||
const prevComputed = planInput.phases.length > 0 ? computePlan(planInput, householdInput) : 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 phase = await prisma.$transaction(async (tx) => {
|
||||
const created = await tx.phase.create({
|
||||
data: {
|
||||
planId: plan.id,
|
||||
sequenceNumber: nextSequence,
|
||||
name: defaultName,
|
||||
durationYears: duration,
|
||||
},
|
||||
});
|
||||
|
||||
// Carry-Vorbelegung fuer bestehende Elemente.
|
||||
for (const e of planInput.elements) {
|
||||
const prev = prevElemById.get(e.id);
|
||||
if (prev && prev.status !== "ACTIVE") continue; // verkauft/getilgt -> nicht mehr fortfuehren
|
||||
const prevData: PhaseData = e.phaseValues[lastPhaseId ?? ""] ?? {};
|
||||
const data: PhaseData = buildCarryData(e.category, prevData, prev?.endValue);
|
||||
await tx.elementPhaseValue.create({
|
||||
data: { elementId: e.id, phaseId: created.id, data: data as Prisma.InputJsonValue },
|
||||
});
|
||||
}
|
||||
|
||||
return created;
|
||||
});
|
||||
|
||||
return NextResponse.json({ phase }, { status: 201 });
|
||||
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));
|
||||
switch (category) {
|
||||
case "INCOME":
|
||||
case "EXPENSE":
|
||||
return { amount: num(prev.amount) };
|
||||
case "AHV":
|
||||
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) };
|
||||
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),
|
||||
};
|
||||
case "OTHER_DEBT":
|
||||
return { startValue: Math.abs(endVal), annualRepayment: num(prev.annualRepayment) };
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user