From 717f4010a761a3872098c509728fcb8c77bb83bb Mon Sep 17 00:00:00 2001 From: def Date: Mon, 16 Mar 2026 01:13:26 +0000 Subject: [PATCH] Use CAD payment value for crypto invoice reconciliation --- backend/app.py | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) 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"])