@@ -105,12 +105,33 @@ exports.settleDebt = async (request, response) => {
105105
106106// Delete a debt between a lender and borrower.
107107exports . 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