From c5a052b43255c2a2571363ce227b06b3bcb2fd9c Mon Sep 17 00:00:00 2001 From: Urvish Date: Thu, 26 Nov 2026 15:29:04 +0530 Subject: [PATCH] fix(invoice): preserve purchase-time phone and address snapshot on historical invoices --- .../admin/services/payment_service.py | 75 +++++++++++-------- app/features/checkout/service.py | 6 ++ app/features/webhooks/service.py | 6 ++ tests/test_invoice_profile_sync.py | 36 ++++++--- 4 files changed, 80 insertions(+), 43 deletions(-) diff --git a/app/features/admin/services/payment_service.py b/app/features/admin/services/payment_service.py index 1338ff3..7d2bfc8 100644 --- a/app/features/admin/services/payment_service.py +++ b/app/features/admin/services/payment_service.py @@ -363,36 +363,49 @@ class AdminPaymentService: invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None profile = None - if user: + if invoice and invoice.billing_profile_id: + profile = (await self.session.execute( + select(UserBillingProfile).where(UserBillingProfile.id == invoice.billing_profile_id) + )).scalar_one_or_none() + elif user: profile = (await self.session.execute( select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True)) )).scalar_one_or_none() + sub = None + if tx and tx.subscription_id: + sub = (await self.session.execute( + select(UserSubscription).where(UserSubscription.id == tx.subscription_id) + )).scalar_one_or_none() + rzp_payment = {} try: rzp_payment = get_razorpay_service().fetch_payment(payment_id) except Exception: pass - cust_name = (user.display_name if user and user.display_name else None) or (profile.billing_name if profile else None) or (invoice.billing_name if invoice else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer" - cust_email = (user.email if user and user.email else None) or (profile.billing_email if profile else None) or (invoice.billing_email if invoice else None) or rzp_payment.get("email") or "customer@example.com" - cust_phone = (user.phone_number if user and user.phone_number else None) or (profile.billing_phone if profile else None) or rzp_payment.get("contact") or "" + sub_meta = (sub.metadata_json or {}) if sub else {} - # Clean address string - clean_addr_parts = [] - if profile: - for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]: - if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]: - clean_addr_parts.append(p.strip()) - c = (user.country if user and user.country else None) or profile.country - if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]: - clean_addr_parts.append(c.strip()) - elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]: - clean_addr_parts.append(user.country.strip()) - elif invoice and invoice.billing_address and "not configured" not in invoice.billing_address.lower(): - clean_addr_parts.append(invoice.billing_address.strip()) + # Prioritize the frozen invoice/purchase snapshot so historical invoices never mutate on profile edits + cust_name = (invoice.billing_name if invoice and invoice.billing_name else None) or (profile.billing_name if profile else None) or (user.display_name if user and user.display_name else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer" + cust_email = (invoice.billing_email if invoice and invoice.billing_email else None) or (profile.billing_email if profile else None) or (user.email if user and user.email else None) or rzp_payment.get("email") or "customer@example.com" + cust_phone = sub_meta.get("billing_phone") or rzp_payment.get("contact") or (profile.billing_phone if profile else None) or (user.phone_number if user and user.phone_number else None) or "" - cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else (user.country if user and user.country else "Digital Access") + # Clean address string: prefer frozen invoice.billing_address when valid + if invoice and invoice.billing_address and invoice.billing_address.strip().lower() not in ["not configured", "none", "null", "recorded from gateway webhook"]: + cust_address = invoice.billing_address.strip() + else: + clean_addr_parts = [] + if profile: + for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]: + if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]: + clean_addr_parts.append(p.strip()) + c = profile.country or (user.country if user and user.country else None) + if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]: + clean_addr_parts.append(c.strip()) + elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]: + clean_addr_parts.append(user.country.strip()) + cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else ((user.country if user and user.country else None) or "Digital Access") now = datetime.now(timezone.utc) inv_number = (invoice.invoice_number if invoice else None) or f"INV-{now.strftime('%b').upper()}-{now.strftime('%Y')}-PREVIEW" @@ -407,20 +420,18 @@ class AdminPaymentService: # Item description item_desc = rzp_payment.get("description") if rzp_payment else None if not item_desc and tx: - if tx.subscription_id: - sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.id == tx.subscription_id))).scalar_one_or_none() - if sub: - ref = sub.payment_reference - subs = (await self.session.execute( - select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref) - )).scalars().all() if ref else [sub] - p_names = [] - for s in subs: - p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none() - if p and p.name not in p_names: - p_names.append(p.name) - if p_names: - item_desc = ", ".join(p_names) + if sub: + ref = sub.payment_reference + subs = (await self.session.execute( + select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref) + )).scalars().all() if ref else [sub] + p_names = [] + for s in subs: + p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none() + if p and p.name not in p_names: + p_names.append(p.name) + if p_names: + item_desc = ", ".join(p_names) if not item_desc: item_desc = "Clinical Access Plan Subscription" diff --git a/app/features/checkout/service.py b/app/features/checkout/service.py index e1a9c78..067d5da 100644 --- a/app/features/checkout/service.py +++ b/app/features/checkout/service.py @@ -172,6 +172,12 @@ class CheckoutService: select(Coupon).where(Coupon.code == str(coupon_code).strip().upper()) )).scalar_one_or_none() if coupon_code else None + phone_snapshot = profile.billing_phone or payment.get("contact") + if phone_snapshot and subs: + sub_meta = dict(subs[0].metadata_json or {}) + sub_meta["billing_phone"] = phone_snapshot + subs[0].metadata_json = sub_meta + invoice, invoice_url = await self._create_invoice( rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None ) diff --git a/app/features/webhooks/service.py b/app/features/webhooks/service.py index 77060ee..ebfbdab 100644 --- a/app/features/webhooks/service.py +++ b/app/features/webhooks/service.py @@ -102,6 +102,12 @@ class RazorpayWebhookService: select(Coupon).where(Coupon.code == str(coupon_code).strip().upper()) )).scalar_one_or_none() if coupon_code else None + if payment.get("contact") and subs: + sub_meta = dict(subs[0].metadata_json or {}) + if not sub_meta.get("billing_phone"): + sub_meta["billing_phone"] = payment.get("contact") + subs[0].metadata_json = sub_meta + invoice = Invoice( payment_transaction_id=transaction.id, invoice_number=invoice_number, diff --git a/tests/test_invoice_profile_sync.py b/tests/test_invoice_profile_sync.py index b5610ed..fb74b7c 100644 --- a/tests/test_invoice_profile_sync.py +++ b/tests/test_invoice_profile_sync.py @@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock from uuid import uuid4 import pytest -from app.db.models import AppUser, UserBillingProfile, PaymentTransaction, Invoice +from app.db.models import AppUser, UserBillingProfile, PaymentTransaction, Invoice, UserSubscription from app.features.checkout.service import CheckoutService from app.features.admin.services.payment_service import AdminPaymentService @@ -53,8 +53,9 @@ async def test_checkout_billing_profile_syncs_updated_user_details() -> None: @pytest.mark.asyncio -async def test_render_invoice_html_uses_updated_phone_and_country() -> None: +async def test_render_invoice_html_preserves_historical_snapshot() -> None: tx_id = uuid4() + sub_id = uuid4() mock_tx = MagicMock(spec=PaymentTransaction) mock_tx.id = tx_id mock_tx.user_id = uuid4() @@ -62,34 +63,43 @@ async def test_render_invoice_html_uses_updated_phone_and_country() -> None: mock_tx.amount = Decimal("15.00") mock_tx.currency = "EUR" mock_tx.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc) - mock_tx.subscription_id = None + mock_tx.subscription_id = sub_id + # User later updated their phone & country in User Profile mock_user = MagicMock(spec=AppUser) mock_user.display_name = "Hans Schmidt" mock_user.email = "hans@example.de" mock_user.phone_number = "+491701122334" # Updated phone mock_user.country = "Germany" # Updated country + # Historical invoice snapshot from time of purchase mock_invoice = MagicMock(spec=Invoice) mock_invoice.invoice_number = "INV-2026-0001" mock_invoice.billing_name = "Hans Schmidt" mock_invoice.billing_email = "hans@example.de" - mock_invoice.billing_address = "Germany" + mock_invoice.billing_address = "India" + mock_invoice.billing_profile_id = None mock_invoice.currency_code = "EUR" mock_invoice.total_amount = Decimal("15.00") mock_invoice.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc) - # Profile with older phone + # Profile also later synced to updated details mock_profile = MagicMock(spec=UserBillingProfile) mock_profile.billing_name = "Hans Schmidt" mock_profile.billing_email = "hans@example.de" - mock_profile.billing_phone = "+919999988888" - mock_profile.country = "India" + mock_profile.billing_phone = "+491701122334" + mock_profile.country = "Germany" mock_profile.address_line1 = "Not Configured" mock_profile.city = "Not Configured" mock_profile.state = "Not Configured" mock_profile.postal_code = "000000" + # Subscription stores the frozen billing_phone at time of purchase + mock_sub = MagicMock(spec=UserSubscription) + mock_sub.id = sub_id + mock_sub.payment_reference = None + mock_sub.metadata_json = {"billing_phone": "+919999988888"} + mock_session = AsyncMock() r_tx = MagicMock() r_tx.scalar_one_or_none.return_value = mock_tx @@ -99,13 +109,17 @@ async def test_render_invoice_html_uses_updated_phone_and_country() -> None: r_inv.scalar_one_or_none.return_value = mock_invoice r_prof = MagicMock() r_prof.scalar_one_or_none.return_value = mock_profile + r_sub = MagicMock() + r_sub.scalar_one_or_none.return_value = mock_sub + r_plan = MagicMock() + r_plan.scalar_one_or_none.return_value = None - mock_session.execute.side_effect = [r_tx, r_user, r_inv, r_prof] + mock_session.execute.side_effect = [r_tx, r_user, r_inv, r_prof, r_sub, r_plan] svc = AdminPaymentService(mock_session) response = await svc.render_invoice_html("pay_test123") html = response.body.decode("utf-8") - assert "+491701122334" in html - assert "+919999988888" not in html - assert "Germany" in html + assert "+919999988888" in html + assert "+491701122334" not in html + assert "India" in html