80 lines
2.1 KiB
TypeScript
80 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/db";
|
|
import { queryRaw } from "@/lib/db";
|
|
|
|
interface SplitInput {
|
|
participant_id: number;
|
|
share_percent: number;
|
|
}
|
|
|
|
interface SplitRow {
|
|
id: number;
|
|
transaction_id: number;
|
|
participant_id: number;
|
|
name: string;
|
|
share_percent: number;
|
|
settled: boolean;
|
|
settled_at: string | null;
|
|
created_at: string;
|
|
}
|
|
|
|
export async function GET(
|
|
_req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params;
|
|
const splits = await queryRaw<SplitRow>(
|
|
`SELECT ts.*, p.name
|
|
FROM transaction_splits ts
|
|
JOIN participants p ON p.id = ts.participant_id
|
|
WHERE ts.transaction_id = $1
|
|
ORDER BY p.name`,
|
|
[Number(id)]
|
|
);
|
|
return NextResponse.json(splits);
|
|
}
|
|
|
|
export async function POST(
|
|
req: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params;
|
|
const transactionId = Number(id);
|
|
const { splits } = (await req.json()) as { splits: SplitInput[] };
|
|
|
|
if (!splits || !Array.isArray(splits) || splits.length === 0) {
|
|
return NextResponse.json({ error: "splits array required" }, { status: 400 });
|
|
}
|
|
|
|
const total = splits.reduce((sum, s) => sum + Number(s.share_percent), 0);
|
|
if (Math.abs(total - 100) > 0.01) {
|
|
return NextResponse.json(
|
|
{ error: `Shares must sum to 100%, got ${total}%` },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Replace all splits for this transaction atomically
|
|
await prisma.$transaction([
|
|
prisma.transaction_splits.deleteMany({ where: { transaction_id: transactionId } }),
|
|
...splits.map((s) =>
|
|
prisma.transaction_splits.create({
|
|
data: {
|
|
transaction_id: transactionId,
|
|
participant_id: s.participant_id,
|
|
share_percent: s.share_percent,
|
|
},
|
|
})
|
|
),
|
|
]);
|
|
|
|
const result = await queryRaw<SplitRow>(
|
|
`SELECT ts.*, p.name FROM transaction_splits ts
|
|
JOIN participants p ON p.id = ts.participant_id
|
|
WHERE ts.transaction_id = $1 ORDER BY p.name`,
|
|
[transactionId]
|
|
);
|
|
|
|
return NextResponse.json(result);
|
|
}
|