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:
@@ -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 })
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user