Initial commit: FPT Financial Planning Tool
Deploy App / deploy (push) Successful in 3m3s

This commit is contained in:
2026-07-08 19:19:39 +02:00
commit 4f990c9686
60 changed files with 12436 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from "next/server";
import { createSessionToken, SESSION_COOKIE_NAME } from "@/lib/auth";
import { getAppCredential, verifyAppPassword } from "@/lib/credentials";
export async function POST(request: NextRequest) {
const { password } = await request.json();
const credential = await getAppCredential();
if (!credential) {
return NextResponse.json(
{ error: "Es ist noch kein Passwort gesetzt. Bitte zuerst ein Passwort festlegen." },
{ status: 409 }
);
}
if (typeof password !== "string" || password.length === 0 || !(await verifyAppPassword(password))) {
return NextResponse.json({ error: "Falsches Passwort." }, { status: 401 });
}
const token = await createSessionToken();
const response = NextResponse.json({ ok: true });
response.cookies.set(SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
});
return response;
}
+8
View File
@@ -0,0 +1,8 @@
import { NextResponse } from "next/server";
import { SESSION_COOKIE_NAME } from "@/lib/auth";
export async function POST() {
const response = NextResponse.json({ ok: true });
response.cookies.delete(SESSION_COOKIE_NAME);
return response;
}
+37
View File
@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { createSessionToken, SESSION_COOKIE_NAME } from "@/lib/auth";
import { getAppCredential, setAppPassword } from "@/lib/credentials";
const setupSchema = z.object({
password: z.string().min(4, "Das Passwort muss mindestens 4 Zeichen lang sein."),
});
// Legt das Login-Passwort einmalig fest. Nur solange noch keine AppCredential-Zeile
// existiert (d. h. beim allerersten Login) erreichbar -- danach ausschliesslich
// ueber /api/auth/login.
export async function POST(request: NextRequest) {
const existing = await getAppCredential();
if (existing) {
return NextResponse.json({ error: "Es ist bereits ein Passwort gesetzt." }, { status: 409 });
}
const body = await request.json();
const parsed = setupSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
await setAppPassword(parsed.data.password);
const token = await createSessionToken();
const response = NextResponse.json({ ok: true });
response.cookies.set(SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30,
});
return response;
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getAppCredential } from "@/lib/credentials";
export async function GET() {
const credential = await getAppCredential();
return NextResponse.json({ passwordSet: credential != null });
}
+94
View File
@@ -0,0 +1,94 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getHouseholdOrNull, toHouseholdInput } from "@/lib/queries";
const personSchema = z.object({
role: z.enum(["PERSON_A", "PERSON_B"]),
age: z.number().int().min(0).max(120),
retirementAge: z.number().int().min(0).max(120),
});
const householdSchema = z.object({
householdType: z.enum(["SINGLE", "COUPLE"]),
inflationRateDefault: z.number().min(-20).max(50),
persons: z.array(personSchema).min(1).max(2),
});
function validatePersonsForType(data: z.infer<typeof householdSchema>) {
if (data.householdType === "SINGLE" && data.persons.length !== 1) {
return "Einzelperson-Haushalt benoetigt genau eine Person.";
}
if (data.householdType === "COUPLE" && data.persons.length !== 2) {
return "Paar-Haushalt benoetigt genau zwei Personen (Person A und Person B).";
}
return null;
}
export async function GET() {
const household = await getHouseholdOrNull();
return NextResponse.json({ household: household ? toHouseholdInput(household) : null });
}
export async function POST(request: NextRequest) {
const existing = await getHouseholdOrNull();
if (existing) {
return NextResponse.json(
{ error: "Es existiert bereits ein Haushalt. Bitte PATCH verwenden, um ihn zu bearbeiten." },
{ status: 409 }
);
}
const body = await request.json();
const parsed = householdSchema.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 household = await prisma.household.create({
data: {
householdType: parsed.data.householdType,
inflationRateDefault: parsed.data.inflationRateDefault,
persons: { create: parsed.data.persons },
},
include: { persons: true },
});
return NextResponse.json({ household: toHouseholdInput(household) }, { status: 201 });
}
export async function PATCH(request: NextRequest) {
const existing = await getHouseholdOrNull();
if (!existing) {
return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 404 });
}
const body = await request.json();
const parsed = householdSchema.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 household = await prisma.$transaction(async (tx) => {
await tx.person.deleteMany({ where: { householdId: existing.id } });
return tx.household.update({
where: { id: existing.id },
data: {
householdType: parsed.data.householdType,
inflationRateDefault: parsed.data.inflationRateDefault,
persons: { create: parsed.data.persons },
},
include: { persons: true },
});
});
return NextResponse.json({ household: toHouseholdInput(household) });
}
+133
View File
@@ -0,0 +1,133 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { phaseInclude } from "@/lib/queries";
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),
});
const realEstateSchema = z.object({
name: z.string().min(1),
marketValue: z.number(),
mortgage: z.number(),
valueGrowth: z.number(),
amortization: z.number(),
salePrice: z.number().nullable().optional(),
saleTaxRate: z.number().min(0).max(100),
});
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),
});
const updatePhaseSchema = 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"]),
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 { 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 prisma.phase.findUnique({ where: { id: phaseId } });
if (!existing) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
}
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.map((re) => ({ ...re, salePrice: re.salePrice ?? null })) },
oneTimeEvents: { create: data.oneTimeEvents.map((e) => ({ ...e, description: e.description ?? null })) },
retirementInfos: { create: data.retirementInfos },
},
include: phaseInclude,
});
});
return NextResponse.json({ phase });
}
// Eine Phase kann nur geloescht werden, wenn sie die letzte in der Kette ist -- so
// bleibt die Verkettung (Schlussvermoegen = Startvermoegen der Folgephase) immer intakt.
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ phaseId: string }> }
) {
const { phaseId } = await params;
const phase = await prisma.phase.findUnique({ where: { id: phaseId } });
if (!phase) {
return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 });
}
const laterPhase = 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 }
);
}
await prisma.phase.delete({ where: { id: phaseId } });
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,118 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
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(),
});
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 { phaseId } = await params;
const phase = await prisma.phase.findUnique({
where: { id: phaseId },
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) fuer jede Position der Vorphase.
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ phaseId: string }> }
) {
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.findUnique({
where: { id: phaseId },
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 oder Verkaufen gewaehlt werden." },
{ status: 400 }
);
}
const transition = await prisma.$transaction(async (tx) => {
await tx.phaseTransition.deleteMany({ where: { fromPhaseId: phaseId } });
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,
})),
},
},
include: { items: true },
});
});
return NextResponse.json({ transition });
}
@@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { planInclude, toHouseholdInput, toPlanInput, getHouseholdOrNull } from "@/lib/queries";
import { computePlan, planToCsv } from "@/lib/calculations";
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
const { planId } = await params;
const household = await getHouseholdOrNull();
if (!household) {
return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
}
const plan = await prisma.plan.findUnique({ where: { id: planId }, include: planInclude });
if (!plan) {
return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
}
const planInput = toPlanInput(plan);
const computed = computePlan(planInput, toHouseholdInput(household));
const csv = planToCsv(planInput, computed);
return new NextResponse(csv, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="${plan.name.replace(/[^a-z0-9]+/gi, "_")}.csv"`,
},
});
}
@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { phaseInclude } from "@/lib/queries";
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"),
});
// Fuegt eine neue Lebensabschnittsphase am Ende der Phasenkette eines Plans an
// (TDD Kapitel 3: Phasen werden chronologisch aneinandergereiht).
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
const { planId } = await params;
const body = await request.json();
const parsed = createPhaseSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const plan = await prisma.plan.findUnique({ where: { id: planId } });
if (!plan) {
return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
}
const lastPhase = await prisma.phase.findFirst({
where: { planId },
orderBy: { sequenceNumber: "desc" },
});
const nextSequence = (lastPhase?.sequenceNumber ?? 0) + 1;
const phase = await prisma.phase.create({
data: {
planId,
sequenceNumber: nextSequence,
name: parsed.data.name,
durationYears: parsed.data.durationYears,
inflationRate: parsed.data.inflationRate ?? null,
incomeMode: parsed.data.incomeMode,
},
include: phaseInclude,
});
return NextResponse.json({ phase }, { status: 201 });
}
+35
View File
@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { planInclude, toHouseholdInput, toPlanInput, getHouseholdOrNull } from "@/lib/queries";
import { computePlan } from "@/lib/calculations";
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
const { planId } = await params;
const household = await getHouseholdOrNull();
if (!household) {
return NextResponse.json({ error: "Kein Haushalt vorhanden." }, { status: 400 });
}
const plan = await prisma.plan.findUnique({ where: { id: planId }, include: planInclude });
if (!plan) {
return NextResponse.json({ error: "Plan nicht gefunden." }, { status: 404 });
}
const householdInput = toHouseholdInput(household);
const planInput = toPlanInput(plan);
const computed = computePlan(planInput, householdInput);
return NextResponse.json({ plan: planInput, computed });
}
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
const { planId } = await params;
await prisma.plan.delete({ where: { id: planId } });
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,120 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { phaseInclude, planInclude } from "@/lib/queries";
const scenarioSchema = z.object({
name: z.string().min(1).max(120),
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).
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ planId: string }> }
) {
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 });
}
const sourcePlan = await prisma.plan.findUnique({ where: { id: planId }, include: planInclude });
if (!sourcePlan) {
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 phasesToCopy = sourcePlan.phases
.filter((p) => p.sequenceNumber <= branchPhase.sequenceNumber)
.sort((a, b) => a.sequenceNumber - b.sequenceNumber);
const newPlanId = await prisma.$transaction(async (tx) => {
const newPlan = await tx.plan.create({
data: {
householdId: sourcePlan.householdId,
name: parsed.data.name,
parentPlanId: sourcePlan.id,
},
});
let lastNewPhaseId = "";
for (const phase of phasesToCopy) {
const newPhase = await tx.phase.create({
data: {
planId: newPlan.id,
sequenceNumber: phase.sequenceNumber,
name: phase.name,
durationYears: phase.durationYears,
inflationRate: phase.inflationRate,
incomeMode: phase.incomeMode,
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,
})),
},
realEstates: {
create: phase.realEstates.map((re) => ({
name: re.name,
marketValue: re.marketValue,
mortgage: re.mortgage,
valueGrowth: re.valueGrowth,
amortization: re.amortization,
salePrice: re.salePrice,
saleTaxRate: re.saleTaxRate,
})),
},
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;
}
await tx.plan.update({
where: { id: newPlan.id },
data: { branchFromPhaseId: lastNewPhaseId },
});
return newPlan.id;
});
return NextResponse.json({ planId: newPlanId }, { status: 201 });
}
+53
View File
@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { getHouseholdOrNull } from "@/lib/queries";
const createPlanSchema = z.object({
name: z.string().min(1).max(120),
});
export async function GET() {
const household = await getHouseholdOrNull();
if (!household) {
return NextResponse.json({ plans: [] });
}
const plans = await prisma.plan.findMany({
where: { householdId: household.id },
orderBy: { createdAt: "asc" },
select: {
id: true,
name: true,
parentPlanId: true,
branchFromPhaseId: true,
createdAt: true,
phases: {
select: { id: true, name: true, sequenceNumber: true },
orderBy: { sequenceNumber: "asc" },
},
},
});
return NextResponse.json({ plans });
}
export async function POST(request: NextRequest) {
const household = await getHouseholdOrNull();
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 plan = await prisma.plan.create({
data: { householdId: household.id, name: parsed.data.name },
});
return NextResponse.json({ plan }, { status: 201 });
}