diff --git a/backend/app.py b/backend/app.py index 93a0098..3394beb 100644 --- a/backend/app.py +++ b/backend/app.py @@ -1006,12 +1006,35 @@ def recalc_invoice_totals(invoice_id): conn.close() return - cursor.execute(""" - SELECT COALESCE(SUM(payment_amount), 0) AS total_paid - FROM payments - WHERE invoice_id = %s - AND payment_status = 'confirmed' - """, (invoice_id,)) + invoice_currency = str(invoice.get("currency_code") or "CAD").upper() + + if invoice_currency == "CAD": + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = 'CAD' + THEN payment_amount + ELSE COALESCE(cad_value_at_payment, 0) + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_id,)) + else: + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = %s + THEN payment_amount + ELSE 0 + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_currency, invoice_id)) + row = cursor.fetchone() total_paid = to_decimal(row["total_paid"])