Skip to content

Commit 4a9b065

Browse files
committed
Fix data consistency between the Debt and UserDebt collections when debts are deleted
1 parent cf443db commit 4a9b065

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

server/controllers/debt_controller.js

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,33 @@ exports.settleDebt = async (request, response) => {
105105

106106
// Delete a debt between a lender and borrower.
107107
exports.deleteDebtBetweenUsers = async (request, response) => {
108+
// Find the debt first so we know the amount to adjust balances.
109+
const debt = await debtModel.findOne({
110+
from: request.params.from,
111+
to: request.params.to,
112+
});
113+
114+
if (!debt) {
115+
return response.status(404).send("Debt not found.");
116+
}
117+
118+
// Delete the debt.
108119
await debtModel.deleteOne({
109120
from: request.params.from,
110121
to: request.params.to,
111122
});
112-
// Now that we've deleted the debt, there may be a better way of allocating
113-
// the debt, so recalculate debts to minimise the number of transactions.
123+
124+
// Update userDebt balances: the borrower owes less, the lender is owed less.
125+
await userDebtModel.findOneAndUpdate(
126+
{ username: request.params.from },
127+
{ $inc: { netDebt: -debt.amount } },
128+
);
129+
await userDebtModel.findOneAndUpdate(
130+
{ username: request.params.to },
131+
{ $inc: { netDebt: debt.amount } },
132+
);
133+
134+
// Recalculate optimised debts.
114135
await helpers.simplifyDebts();
115136
response.send(
116137
`Debt from '${request.params.from}' to '${request.params.to}' deleted\

0 commit comments

Comments
 (0)