import { NextResponse } from 'next/server' import { db } from '@/lib/db' export const dynamic = 'force-dynamic' // POST /api/aos/accounting/bank/[id]/match — match a bank transaction to an invoice. // Body: { invoiceId } — marks the transaction matched + invoice paid. export async function POST( req: Request, { params }: { params: Promise<{ id: string }> } ) { try { const { id } = await params const { invoiceId } = (await req.json()) as { invoiceId: string } const tx = await db.bankTransaction.findUnique({ where: { id } }) if (!tx) return NextResponse.json({ error: 'transaction not found' }, { status: 404 }) const invoice = await db.invoice.findUnique({ where: { id: invoiceId } }) if (!invoice) return NextResponse.json({ error: 'invoice not found' }, { status: 404 }) const updated = await db.bankTransaction.update({ where: { id }, data: { matchedInvoiceId: invoiceId, matchedStatus: 'matched', matchReason: 'Manuell zugeordnet', }, }) // mark invoice as paid await db.invoice.update({ where: { id: invoiceId }, data: { status: 'paid', paidDate: tx.valueDate }, }) await db.auditLog.create({ data: { actor: 'nora@nordlicht.digital', action: 'bank.match:invoice', entity: 'BankTransaction', entityId: id, after: JSON.stringify({ invoiceId, invoiceNumber: invoice.number, status: 'matched', invoiceStatus: 'paid' }), hash: 'sha256:' + Math.random().toString(36).slice(2), }, }) return NextResponse.json({ transaction: updated, invoiceNumber: invoice.number }) } catch (err) { const msg = err instanceof Error ? err.message : 'internal server error' return NextResponse.json({ error: msg }, { status: 500 }) } }