mirror of
https://github.com/acedanger/finance.git
synced 2025-12-05 22:50:12 -08:00
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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user