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
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getOwnedElement } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { phaseDataSchema } from "@/lib/elements";
// Speichert die Werte eines Elements innerhalb einer Lebensphase (Upsert).
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ elementId: string; phaseId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { elementId, phaseId } = await params;
const element = await getOwnedElement(elementId, userId);
if (!element) return NextResponse.json({ error: "Element nicht gefunden." }, { status: 404 });
const phase = await prisma.phase.findFirst({ where: { id: phaseId, planId: element.planId } });
if (!phase) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
const body = await request.json();
const parsed = phaseDataSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
await prisma.elementPhaseValue.upsert({
where: { elementId_phaseId: { elementId, phaseId } },
create: { elementId, phaseId, data: parsed.data },
update: { data: parsed.data },
});
return NextResponse.json({ ok: true });
}
+41
View File
@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getOwnedElement } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
const patchSchema = z.object({ name: z.string().min(1).max(120) });
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ elementId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { elementId } = await params;
const element = await getOwnedElement(elementId, userId);
if (!element) return NextResponse.json({ error: "Element 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 });
await prisma.financialElement.update({ where: { id: element.id }, data: { name: parsed.data.name } });
return NextResponse.json({ ok: true });
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ elementId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { elementId } = await params;
const element = await getOwnedElement(elementId, userId);
if (!element) return NextResponse.json({ error: "Element nicht gefunden." }, { status: 404 });
await prisma.financialElement.delete({ where: { id: element.id } });
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getOwnedElement } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { transitionDataSchema } from "@/lib/elements";
// Speichert den Uebergangs-Entscheid eines Elements nach der Phase fromPhase (Upsert).
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ elementId: string; fromPhaseId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
const { elementId, fromPhaseId } = await params;
const element = await getOwnedElement(elementId, userId);
if (!element) return NextResponse.json({ error: "Element nicht gefunden." }, { status: 404 });
const phase = await prisma.phase.findFirst({ where: { id: fromPhaseId, planId: element.planId } });
if (!phase) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
const body = await request.json();
const parsed = transitionDataSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
await prisma.elementTransitionValue.upsert({
where: { elementId_fromPhaseId: { elementId, fromPhaseId } },
create: { elementId, fromPhaseId, data: parsed.data },
update: { data: parsed.data },
});
return NextResponse.json({ ok: true });
}
+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 } });
@@ -1,237 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { computeMortgageYearly, computeSecurityYearlyValues } from "@/lib/calculations";
import { floorToThousand } from "@/lib/format";
import { getCurrentUserId } from "@/lib/session";
const transitionItemSchema = z.object({
positionType: z.enum(["SECURITY", "REAL_ESTATE"]),
securityId: z.string().nullable().optional(),
realEstateId: z.string().nullable().optional(),
decision: z.enum(["CARRY_OVER", "SELL"]),
salePrice: z.number().nullable().optional(),
// Nur bei Immobilien-Verkauf relevant (Grundstueckgewinnsteuer in %).
saleTaxRate: z.number().min(0).max(100).nullable().optional(),
});
const putTransitionSchema = z.object({
items: z.array(transitionItemSchema),
});
// Liefert die aktuellen Positionen der Phase (Wertschriften + Immobilien) sowie eine
// evtl. bereits vorhandene Entscheidung, damit die UI den Uebergangs-Screen (TDD 4.4)
// rendern kann.
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ phaseId: string }> }
) {
const userId = await getCurrentUserId();
if (!userId) {
return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 });
}
const { phaseId } = await params;
const phase = await prisma.phase.findFirst({
where: { id: phaseId, plan: { household: { userId } } },
include: { securities: true, realEstates: true },
});
if (!phase) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
}
const nextPhase = await prisma.phase.findFirst({
where: { planId: phase.planId, sequenceNumber: phase.sequenceNumber + 1 },
});
const transition = await prisma.phaseTransition.findUnique({
where: { fromPhaseId: phaseId },
include: { items: true },
});
return NextResponse.json({
positions: {
securities: phase.securities,
realEstates: phase.realEstates,
},
nextPhase,
transition,
});
}
// Speichert die Entscheidungen (Uebernehmen/Verkaufen bzw. Halten/Verkaufen) fuer jede
// Position der Vorphase. Uebernommene/gehaltene Positionen werden automatisch 1:1 (mit
// zurueckgesetztem Sparbeitrag/Amortisation) in der Folgephase angelegt. Verkaufte
// Positionen fliessen als "verfuegbares Startkapital" (Phase.incomingCapital) ein.
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 });
}
const { phaseId } = await params;
const body = await request.json();
const parsed = putTransitionSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const phase = await prisma.phase.findFirst({
where: { id: phaseId, plan: { household: { userId } } },
include: { securities: true, realEstates: true },
});
if (!phase) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
}
const nextPhase = await prisma.phase.findFirst({
where: { planId: phase.planId, sequenceNumber: phase.sequenceNumber + 1 },
});
if (!nextPhase) {
return NextResponse.json(
{ error: "Es existiert noch keine Folgephase fuer diesen Uebergang." },
{ status: 400 }
);
}
const requiredIds = new Set([
...phase.securities.map((s) => `SECURITY:${s.id}`),
...phase.realEstates.map((re) => `REAL_ESTATE:${re.id}`),
]);
const providedIds = new Set(
parsed.data.items.map((i) => `${i.positionType}:${i.securityId ?? i.realEstateId}`)
);
const missing = [...requiredIds].filter((id) => !providedIds.has(id));
if (missing.length > 0) {
return NextResponse.json(
{ error: "Fuer jede bestehende Position muss Uebernehmen/Halten oder Verkaufen gewaehlt werden." },
{ status: 400 }
);
}
const securityById = new Map(phase.securities.map((s) => [s.id, s]));
const realEstateById = new Map(phase.realEstates.map((re) => [re.id, re]));
let incomingCapital = 0;
const securitiesToCarry: { source: (typeof phase.securities)[number]; endValue: number }[] = [];
const realEstatesToCarry: { source: (typeof phase.realEstates)[number]; remainingMortgage: number }[] = [];
for (const item of parsed.data.items) {
if (item.positionType === "SECURITY" && item.securityId) {
const security = securityById.get(item.securityId);
if (!security) continue;
const endValue = computeSecurityYearlyValues(
security.startValue,
security.expectedReturn,
security.annualContribution,
phase.durationYears
)[phase.durationYears];
if (item.decision === "CARRY_OVER") {
securitiesToCarry.push({ source: security, endValue });
} else {
const gain = Math.max(0, endValue - security.startValue);
const tax = gain * (security.saleTaxRate / 100);
incomingCapital += endValue - tax;
}
} else if (item.positionType === "REAL_ESTATE" && item.realEstateId) {
const realEstate = realEstateById.get(item.realEstateId);
if (!realEstate) continue;
const remainingMortgage = computeMortgageYearly(
realEstate.mortgage,
realEstate.amortization,
phase.durationYears
)[phase.durationYears];
if (item.decision === "CARRY_OVER") {
realEstatesToCarry.push({ source: realEstate, remainingMortgage });
} else {
const salePrice = item.salePrice ?? 0;
const saleTaxRate = item.saleTaxRate ?? 0;
const gain = Math.max(0, salePrice - realEstate.purchasePrice);
const tax = gain * (saleTaxRate / 100);
incomingCapital += salePrice - remainingMortgage - tax;
}
}
}
// Auf ein Vielfaches von 1'000 abrunden, damit der Betrag ueber Wertschriften
// (die nur in 1'000er-Schritten Sparbeitraege/Startwerte annehmen) vollstaendig
// verteilbar bleibt.
incomingCapital = floorToThousand(incomingCapital);
const transition = await prisma.$transaction(async (tx) => {
await tx.phaseTransition.deleteMany({ where: { fromPhaseId: phaseId } });
// Vorherige automatisch uebernommene Positionen aus einem frueheren Speichern
// dieses Uebergangs entfernen, damit sie nicht dupliziert werden. Manuell vom
// Benutzer angelegte Positionen (carriedFrom...Id = null) bleiben unberuehrt.
await tx.security.deleteMany({
where: {
phaseId: nextPhase.id,
carriedFromSecurityId: { in: phase.securities.map((s) => s.id) },
},
});
await tx.realEstate.deleteMany({
where: {
phaseId: nextPhase.id,
carriedFromRealEstateId: { in: phase.realEstates.map((re) => re.id) },
},
});
for (const { source, endValue } of securitiesToCarry) {
await tx.security.create({
data: {
phaseId: nextPhase.id,
name: source.name,
startValue: endValue,
carriedBaseValue: endValue,
expectedReturn: source.expectedReturn,
annualContribution: 0,
ownerTag: source.ownerTag,
saleTaxRate: source.saleTaxRate,
carriedFromSecurityId: source.id,
},
});
}
for (const { source, remainingMortgage } of realEstatesToCarry) {
await tx.realEstate.create({
data: {
phaseId: nextPhase.id,
name: source.name,
purchasePrice: source.purchasePrice,
mortgage: remainingMortgage,
amortization: 0,
carriedFromRealEstateId: source.id,
},
});
}
await tx.phase.update({
where: { id: nextPhase.id },
data: { incomingCapital },
});
return tx.phaseTransition.create({
data: {
fromPhaseId: phaseId,
toPhaseId: nextPhase.id,
items: {
create: parsed.data.items.map((i) => ({
positionType: i.positionType,
securityId: i.securityId ?? null,
realEstateId: i.realEstateId ?? null,
decision: i.decision,
salePrice: i.salePrice ?? null,
saleTaxRate: i.saleTaxRate ?? null,
})),
},
},
include: { items: true },
});
});
return NextResponse.json({ transition, incomingCapital });
}
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getOwnedPlan } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
import { PERSON_ONLY_CATEGORIES } from "@/lib/elements";
const createSchema = z.object({
category: z.enum([
"INCOME",
"EXPENSE",
"AHV",
"PENSION_FUND",
"PILLAR_3A",
"REAL_ESTATE",
"OTHER_ASSET",
"OTHER_DEBT",
]),
name: z.string().min(1).max(120),
ownerRole: z.enum(["PERSON_A", "PERSON_B", "HOUSEHOLD"]).nullable().optional(),
});
// Legt ein neues finanzielles Element (plan-weit) an. Personen-Pflicht je Kategorie.
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 });
const { planId } = await params;
const plan = await getOwnedPlan(planId, userId);
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
const body = await request.json();
const parsed = createSchema.safeParse(body);
if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 });
const { category, name } = parsed.data;
let ownerRole = parsed.data.ownerRole ?? null;
if (PERSON_ONLY_CATEGORIES.includes(category)) {
if (ownerRole !== "PERSON_A" && ownerRole !== "PERSON_B") {
return NextResponse.json(
{ error: "Diese Kategorie muss einer Person zugeordnet werden." },
{ status: 400 }
);
}
} else if (ownerRole == null) {
ownerRole = "HOUSEHOLD";
}
const maxOrder = await prisma.financialElement.aggregate({
where: { planId: plan.id },
_max: { orderIndex: true },
});
const element = await prisma.financialElement.create({
data: {
planId: plan.id,
category,
name,
ownerRole,
orderIndex: (maxOrder._max.orderIndex ?? 0) + 1,
},
});
return NextResponse.json({ element: { id: element.id } }, { status: 201 });
}
+94 -50
View File
@@ -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 {};
}
}
+39 -15
View File
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { toHouseholdInput, toPlanInput, getHouseholdOrNull, getOwnedPlan } from "@/lib/queries";
import { getCurrentUserId } from "@/lib/session";
@@ -9,19 +10,14 @@ export async function GET(
{ 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 household = await getHouseholdOrNull(userId);
if (!household) {
return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
}
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 });
}
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
const householdInput = toHouseholdInput(household);
const planInput = toPlanInput(plan);
@@ -30,19 +26,47 @@ export async function GET(
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(),
});
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
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 } } });
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 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,
},
});
return NextResponse.json({ plan: { id: updated.id, name: updated.name } });
}
export async function DELETE(
_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 plan = await prisma.plan.findFirst({ where: { id: planId, household: { userId } } });
if (!plan) {
return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
}
if (!plan) return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
await prisma.plan.delete({ where: { id: plan.id } });
return NextResponse.json({ ok: true });
}
+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;
});