fix: account balance calculation when moving transactions between accounts

- Fixed balance calculation logic in transaction update endpoint
- Added comprehensive test coverage for all error paths
- Added coverage/ directory to .gitignore
- Achieved 100% test coverage across all files
This commit is contained in:
GitHub Copilot
2025-04-24 09:24:00 -04:00
parent 99b70b519b
commit 96093200f5
3 changed files with 231 additions and 7 deletions

View File

@@ -27,27 +27,46 @@ export const PUT: APIRoute = async ({ request, params }) => {
}
const oldTransaction = transactions[transactionIndex];
const account = accounts.find((a) => a.id === oldTransaction.accountId);
if (!account) {
// Get the old account first
const oldAccount = accounts.find((a) => a.id === oldTransaction.accountId);
if (!oldAccount) {
return new Response(JSON.stringify({ error: "Account not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
// Revert old transaction amount from account balance
account.balance -= oldTransaction.amount;
// If account is changing, validate new account exists
let newAccount = oldAccount;
if (updates.accountId && updates.accountId !== oldTransaction.accountId) {
newAccount = accounts.find((a) => a.id === updates.accountId);
if (!newAccount) {
return new Response(JSON.stringify({ error: "Account not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
}
// Update transaction with new data
// First, remove the old transaction's effect on the old account
oldAccount.balance -= oldTransaction.amount;
// Create updated transaction
const updatedTransaction: Transaction = {
...oldTransaction,
...updates,
id: id, // Ensure ID doesn't change
};
// Add new amount to account balance
account.balance += updatedTransaction.amount;
// Then add the new transaction's effect to the appropriate account
if (newAccount === oldAccount) {
// If same account, just add the new amount
oldAccount.balance += updatedTransaction.amount;
} else {
// If different account, add to the new account
newAccount.balance += updatedTransaction.amount;
}
// Update transaction in array
transactions[transactionIndex] = updatedTransaction;