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 <noreply@anthropic.com>
This commit is contained in:
2026-04-21 16:24:59 -04:00
parent da938c1fcf
commit 60dabb6264

View File

@@ -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 })
}