fix(invoice): preserve purchase-time phone and address snapshot on historical invoices #44
|
|
@ -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
|
invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None
|
||||||
|
|
||||||
profile = 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(
|
profile = (await self.session.execute(
|
||||||
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
||||||
)).scalar_one_or_none()
|
)).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 = {}
|
rzp_payment = {}
|
||||||
try:
|
try:
|
||||||
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
|
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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"
|
sub_meta = (sub.metadata_json or {}) if sub else {}
|
||||||
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 ""
|
|
||||||
|
|
||||||
# Clean address string
|
# Prioritize the frozen invoice/purchase snapshot so historical invoices never mutate on profile edits
|
||||||
clean_addr_parts = []
|
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"
|
||||||
if profile:
|
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"
|
||||||
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
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 ""
|
||||||
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())
|
|
||||||
|
|
||||||
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)
|
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"
|
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 description
|
||||||
item_desc = rzp_payment.get("description") if rzp_payment else None
|
item_desc = rzp_payment.get("description") if rzp_payment else None
|
||||||
if not item_desc and tx:
|
if not item_desc and tx:
|
||||||
if tx.subscription_id:
|
if sub:
|
||||||
sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.id == tx.subscription_id))).scalar_one_or_none()
|
ref = sub.payment_reference
|
||||||
if sub:
|
subs = (await self.session.execute(
|
||||||
ref = sub.payment_reference
|
select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref)
|
||||||
subs = (await self.session.execute(
|
)).scalars().all() if ref else [sub]
|
||||||
select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref)
|
p_names = []
|
||||||
)).scalars().all() if ref else [sub]
|
for s in subs:
|
||||||
p_names = []
|
p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none()
|
||||||
for s in subs:
|
if p and p.name not in p_names:
|
||||||
p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none()
|
p_names.append(p.name)
|
||||||
if p and p.name not in p_names:
|
if p_names:
|
||||||
p_names.append(p.name)
|
item_desc = ", ".join(p_names)
|
||||||
if p_names:
|
|
||||||
item_desc = ", ".join(p_names)
|
|
||||||
if not item_desc:
|
if not item_desc:
|
||||||
item_desc = "Clinical Access Plan Subscription"
|
item_desc = "Clinical Access Plan Subscription"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -172,6 +172,12 @@ class CheckoutService:
|
||||||
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
||||||
)).scalar_one_or_none() if coupon_code else None
|
)).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(
|
invoice, invoice_url = await self._create_invoice(
|
||||||
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
|
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -102,6 +102,12 @@ class RazorpayWebhookService:
|
||||||
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
||||||
)).scalar_one_or_none() if coupon_code else None
|
)).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(
|
invoice = Invoice(
|
||||||
payment_transaction_id=transaction.id,
|
payment_transaction_id=transaction.id,
|
||||||
invoice_number=invoice_number,
|
invoice_number=invoice_number,
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
import pytest
|
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.checkout.service import CheckoutService
|
||||||
from app.features.admin.services.payment_service import AdminPaymentService
|
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
|
@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()
|
tx_id = uuid4()
|
||||||
|
sub_id = uuid4()
|
||||||
mock_tx = MagicMock(spec=PaymentTransaction)
|
mock_tx = MagicMock(spec=PaymentTransaction)
|
||||||
mock_tx.id = tx_id
|
mock_tx.id = tx_id
|
||||||
mock_tx.user_id = uuid4()
|
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.amount = Decimal("15.00")
|
||||||
mock_tx.currency = "EUR"
|
mock_tx.currency = "EUR"
|
||||||
mock_tx.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
|
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 = MagicMock(spec=AppUser)
|
||||||
mock_user.display_name = "Hans Schmidt"
|
mock_user.display_name = "Hans Schmidt"
|
||||||
mock_user.email = "hans@example.de"
|
mock_user.email = "hans@example.de"
|
||||||
mock_user.phone_number = "+491701122334" # Updated phone
|
mock_user.phone_number = "+491701122334" # Updated phone
|
||||||
mock_user.country = "Germany" # Updated country
|
mock_user.country = "Germany" # Updated country
|
||||||
|
|
||||||
|
# Historical invoice snapshot from time of purchase
|
||||||
mock_invoice = MagicMock(spec=Invoice)
|
mock_invoice = MagicMock(spec=Invoice)
|
||||||
mock_invoice.invoice_number = "INV-2026-0001"
|
mock_invoice.invoice_number = "INV-2026-0001"
|
||||||
mock_invoice.billing_name = "Hans Schmidt"
|
mock_invoice.billing_name = "Hans Schmidt"
|
||||||
mock_invoice.billing_email = "hans@example.de"
|
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.currency_code = "EUR"
|
||||||
mock_invoice.total_amount = Decimal("15.00")
|
mock_invoice.total_amount = Decimal("15.00")
|
||||||
mock_invoice.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
|
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 = MagicMock(spec=UserBillingProfile)
|
||||||
mock_profile.billing_name = "Hans Schmidt"
|
mock_profile.billing_name = "Hans Schmidt"
|
||||||
mock_profile.billing_email = "hans@example.de"
|
mock_profile.billing_email = "hans@example.de"
|
||||||
mock_profile.billing_phone = "+919999988888"
|
mock_profile.billing_phone = "+491701122334"
|
||||||
mock_profile.country = "India"
|
mock_profile.country = "Germany"
|
||||||
mock_profile.address_line1 = "Not Configured"
|
mock_profile.address_line1 = "Not Configured"
|
||||||
mock_profile.city = "Not Configured"
|
mock_profile.city = "Not Configured"
|
||||||
mock_profile.state = "Not Configured"
|
mock_profile.state = "Not Configured"
|
||||||
mock_profile.postal_code = "000000"
|
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()
|
mock_session = AsyncMock()
|
||||||
r_tx = MagicMock()
|
r_tx = MagicMock()
|
||||||
r_tx.scalar_one_or_none.return_value = mock_tx
|
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_inv.scalar_one_or_none.return_value = mock_invoice
|
||||||
r_prof = MagicMock()
|
r_prof = MagicMock()
|
||||||
r_prof.scalar_one_or_none.return_value = mock_profile
|
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)
|
svc = AdminPaymentService(mock_session)
|
||||||
response = await svc.render_invoice_html("pay_test123")
|
response = await svc.render_invoice_html("pay_test123")
|
||||||
|
|
||||||
html = response.body.decode("utf-8")
|
html = response.body.decode("utf-8")
|
||||||
assert "+491701122334" in html
|
assert "+919999988888" in html
|
||||||
assert "+919999988888" not in html
|
assert "+491701122334" not in html
|
||||||
assert "Germany" in html
|
assert "India" in html
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue