From 60dabb6264fe2fb4492f5027b8bd563c5d6822c0 Mon Sep 17 00:00:00 2001 From: jerick Date: Tue, 21 Apr 2026 16:24:59 -0400 Subject: [PATCH] Recompute account balance after bulk transaction delete After deleting transactions, recalculate currentBalanceCents for each affected account so the account card and net worth dashboard stay accurate. Co-Authored-By: Claude Sonnet 4.6 --- src/app/api/transactions/bulk/route.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) 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 }) }