diff --git a/src/app/api/transactions/bulk/route.ts b/src/app/api/transactions/bulk/route.ts index 5257809..5ca66b3 100644 --- a/src/app/api/transactions/bulk/route.ts +++ b/src/app/api/transactions/bulk/route.ts @@ -34,14 +34,32 @@ export async function POST(req: Request) { // Verify all transaction IDs belong to this user const owned = await prisma.transaction.findMany({ where: { id: { in: ids }, account: { userId } }, - select: { id: true }, + select: { id: true, accountId: true }, }) if (owned.length !== ids.length) { return NextResponse.json({ error: 'One or more transactions not found' }, { status: 404 }) } if (action === 'delete') { + const accountIds = [...new Set(owned.map((t) => t.accountId))] + await prisma.transaction.deleteMany({ where: { id: { in: ids } } }) + + // Recompute currentBalanceCents for each affected account + for (const accountId of accountIds) { + const [balRow] = await prisma.$queryRaw<[{ balance: bigint }]>` + SELECT COALESCE(SUM( + CASE WHEN type = 'CREDIT' THEN "amountCents" ELSE -"amountCents" END + ), 0)::bigint AS balance + FROM "Transaction" + WHERE "accountId" = ${accountId} + ` + await prisma.account.update({ + where: { id: accountId }, + data: { currentBalanceCents: Number(balRow.balance) }, + }) + } + return NextResponse.json({ deleted: ids.length }) }