70 lines
2.1 KiB
TypeScript
70 lines
2.1 KiB
TypeScript
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 });
|
|
}
|