/** * Donations are never mutated once created — their remaining balance is the original * amount minus every "leg" (a Payment row with isDonation:false and originalPaymentId * pointing back at this donation) already allocated from it. A refund of the donation * itself also creates a leg, with a negative amount — Math.abs() so a refund reduces * the remaining balance (money that's left the building) instead of increasing it * (which a raw signed sum would do, since subtracting a negative adds). * * @param {number} originalAmount - the donation payment's own amount * @param {Array<{amount: number}>} legs - Payment rows with originalPaymentId === donation.id * @returns {number} */ function computeDonationRemaining(originalAmount, legs) { const alreadyUsed = (legs || []).reduce((sum, leg) => sum + Math.abs(leg.amount), 0); return Number(originalAmount || 0) - alreadyUsed; } module.exports = { computeDonationRemaining };