diff --git a/components/payments/paymentService.js b/components/payments/paymentService.js index f676482..b17c1d0 100644 --- a/components/payments/paymentService.js +++ b/components/payments/paymentService.js @@ -74,7 +74,7 @@ const emitPaymentStatusChangedIfNeeded = (payment, previousStatus, actorId = nul }); }; -const reconcilePendingTransactions = async (payment) => { +const reconcilePendingTransactions = async (payment, { adjustAmount = true } = {}) => { const transactions = await Transaction.find({ payment: payment._id }).lean(); const remaining = getPayableAmount(payment) - sumPaidTransactions(transactions); const pending = await Transaction.find({ payment: payment._id, status: 'pending' }).sort({ dueDate: 1 }); @@ -85,10 +85,12 @@ const reconcilePendingTransactions = async (payment) => { } if (pending.length) { - const pendingTotal = pending.reduce((sum, row) => sum + row.amount, 0); - if (pendingTotal !== remaining) { - pending[0].amount = remaining; - await pending[0].save(); + if (adjustAmount) { + const pendingTotal = pending.reduce((sum, row) => sum + row.amount, 0); + if (pendingTotal !== remaining) { + pending[0].amount = remaining; + await pending[0].save(); + } } if (pending.length > 1) { await Transaction.deleteMany({ _id: { $in: pending.slice(1).map((row) => row._id) } }); @@ -363,7 +365,8 @@ const updateTransaction = async (transactionId, body, actorId = null) => { if (actorId) trx.recordedBy = actorId; await trx.save(); - await reconcilePendingTransactions(payment); + // Preserve admin-edited amounts; only reconcile balance when recording new payments. + await reconcilePendingTransactions(payment, { adjustAmount: false }); await refreshPaymentTotals(payment); emitPaymentStatusChangedIfNeeded(payment, previousStatus, actorId);