fix: sync billing profile and invoices with updated user phone and country
This commit is contained in:
parent
a4d37fcf1a
commit
7b65c5bd38
|
|
@ -374,9 +374,9 @@ class AdminPaymentService:
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
cust_name = (invoice.billing_name if invoice else None) or (profile.billing_name if profile else None) or (user.display_name if user else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
|
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 = (invoice.billing_email if invoice else None) or (profile.billing_email if profile else None) or (user.email if user else None) or rzp_payment.get("email") or "customer@example.com"
|
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 = (profile.billing_phone if profile else None) or (user.phone_number if user else None) or rzp_payment.get("contact") or ""
|
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
|
# Clean address string
|
||||||
clean_addr_parts = []
|
clean_addr_parts = []
|
||||||
|
|
@ -384,7 +384,7 @@ class AdminPaymentService:
|
||||||
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
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"]:
|
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
|
||||||
clean_addr_parts.append(p.strip())
|
clean_addr_parts.append(p.strip())
|
||||||
c = profile.country or (user.country if user else None)
|
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"]:
|
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
clean_addr_parts.append(c.strip())
|
clean_addr_parts.append(c.strip())
|
||||||
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
|
|
|
||||||
|
|
@ -238,6 +238,24 @@ class AuthService:
|
||||||
if user is None:
|
if user is None:
|
||||||
raise UserNotFoundError("User not found.")
|
raise UserNotFoundError("User not found.")
|
||||||
|
|
||||||
|
# Keep default user billing profile in sync with updated contact info
|
||||||
|
from app.db.models import UserBillingProfile
|
||||||
|
from sqlalchemy import update
|
||||||
|
bp_values: dict[str, object] = {}
|
||||||
|
if full_name:
|
||||||
|
bp_values["billing_name"] = full_name
|
||||||
|
if phone:
|
||||||
|
bp_values["billing_phone"] = phone
|
||||||
|
if country:
|
||||||
|
bp_values["country"] = country
|
||||||
|
if bp_values:
|
||||||
|
await self.session.execute(
|
||||||
|
update(UserBillingProfile)
|
||||||
|
.where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
||||||
|
.values(**bp_values)
|
||||||
|
)
|
||||||
|
await self.session.flush()
|
||||||
|
|
||||||
roles = await self.repository.get_user_roles(user.id)
|
roles = await self.repository.get_user_roles(user.id)
|
||||||
if not roles:
|
if not roles:
|
||||||
roles = [PRACTITIONER_ROLE]
|
roles = [PRACTITIONER_ROLE]
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,14 @@ class CheckoutService:
|
||||||
await self.session.flush()
|
await self.session.flush()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
edit_data: dict[str, Any] = {"name": user.display_name or user.email, "email": user.email}
|
||||||
|
if user.phone_number:
|
||||||
|
edit_data["contact"] = user.phone_number
|
||||||
|
rzp.client.customer.edit(user.external_ref, data=edit_data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
||||||
applied_coupon_code = (
|
applied_coupon_code = (
|
||||||
request.coupon_code.strip().upper()
|
request.coupon_code.strip().upper()
|
||||||
|
|
@ -185,6 +193,19 @@ class CheckoutService:
|
||||||
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
||||||
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
||||||
if profile:
|
if profile:
|
||||||
|
# Synchronize default/auto-generated profile with user's latest verified contact details
|
||||||
|
updated = False
|
||||||
|
if user.phone_number and profile.billing_phone != user.phone_number:
|
||||||
|
profile.billing_phone = user.phone_number
|
||||||
|
updated = True
|
||||||
|
if user.country and profile.country != user.country:
|
||||||
|
profile.country = user.country
|
||||||
|
updated = True
|
||||||
|
if user.display_name and profile.billing_name != user.display_name:
|
||||||
|
profile.billing_name = user.display_name
|
||||||
|
updated = True
|
||||||
|
if updated:
|
||||||
|
await self.session.flush()
|
||||||
return profile
|
return profile
|
||||||
profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True)
|
profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True)
|
||||||
self.session.add(profile)
|
self.session.add(profile)
|
||||||
|
|
@ -203,8 +224,31 @@ class CheckoutService:
|
||||||
) -> tuple[Invoice, str | None]:
|
) -> tuple[Invoice, str | None]:
|
||||||
currency = tx.currency.upper()
|
currency = tx.currency.upper()
|
||||||
inv_number = await generate_next_invoice_number(self.session)
|
inv_number = await generate_next_invoice_number(self.session)
|
||||||
|
|
||||||
|
# Prioritize current verified user phone and country
|
||||||
|
phone_to_use = profile.billing_phone or payment.get("contact")
|
||||||
|
country_to_use = profile.country or "India"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
rzp.client.invoice.create(data={"type":"invoice","customer":{"name":profile.billing_name,"email":profile.billing_email, **({"contact": profile.billing_phone} if profile.billing_phone else {})},"line_items":[{"name": (", ".join(plan_names) or "Access Subscription")[:250],"amount": int(Decimal(tx.amount)*100),"currency":currency,"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":tx.gateway_transaction_id}})
|
cust_data: dict[str, Any] = {
|
||||||
|
"name": profile.billing_name,
|
||||||
|
"email": profile.billing_email,
|
||||||
|
}
|
||||||
|
if phone_to_use:
|
||||||
|
cust_data["contact"] = phone_to_use
|
||||||
|
rzp.client.invoice.create(data={
|
||||||
|
"type": "invoice",
|
||||||
|
"customer": cust_data,
|
||||||
|
"line_items": [{
|
||||||
|
"name": (", ".join(plan_names) or "Access Subscription")[:250],
|
||||||
|
"amount": int(Decimal(tx.amount) * 100),
|
||||||
|
"currency": currency,
|
||||||
|
"quantity": 1,
|
||||||
|
}],
|
||||||
|
"email_notify": False,
|
||||||
|
"sms_notify": False,
|
||||||
|
"notes": {"payment_id": tx.gateway_transaction_id},
|
||||||
|
})
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
# Always use internal branded Acupedia Tax Invoice view URL
|
# Always use internal branded Acupedia Tax Invoice view URL
|
||||||
|
|
@ -213,12 +257,20 @@ class CheckoutService:
|
||||||
discount = Decimal(str(meta.get("total_discounts", 0)))
|
discount = Decimal(str(meta.get("total_discounts", 0)))
|
||||||
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
||||||
gst = Decimal(str(meta.get("gst_amount", 0)))
|
gst = Decimal(str(meta.get("gst_amount", 0)))
|
||||||
|
|
||||||
|
# Build clean address with current country
|
||||||
|
addr_parts = [profile.address_line1, profile.city, profile.state, profile.postal_code]
|
||||||
|
clean_parts = [p.strip() for p in addr_parts if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]]
|
||||||
|
if country_to_use and country_to_use.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
|
clean_parts.append(country_to_use.strip())
|
||||||
|
final_billing_address = ", ".join(clean_parts) if clean_parts else (country_to_use or "Digital Access")
|
||||||
|
|
||||||
invoice = Invoice(
|
invoice = Invoice(
|
||||||
payment_transaction_id=tx.id,
|
payment_transaction_id=tx.id,
|
||||||
invoice_number=inv_number,
|
invoice_number=inv_number,
|
||||||
billing_name=profile.billing_name,
|
billing_name=profile.billing_name,
|
||||||
billing_email=profile.billing_email,
|
billing_email=profile.billing_email,
|
||||||
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}",
|
billing_address=final_billing_address,
|
||||||
gstin=profile.gstin,
|
gstin=profile.gstin,
|
||||||
billing_profile_id=profile.id,
|
billing_profile_id=profile.id,
|
||||||
applied_coupon_id=applied_coupon_id,
|
applied_coupon_id=applied_coupon_id,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,111 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
from uuid import uuid4
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.db.models import AppUser, UserBillingProfile, PaymentTransaction, Invoice
|
||||||
|
from app.features.checkout.service import CheckoutService
|
||||||
|
from app.features.admin.services.payment_service import AdminPaymentService
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_checkout_billing_profile_syncs_updated_user_details() -> None:
|
||||||
|
uid = uuid4()
|
||||||
|
mock_user = MagicMock(spec=AppUser)
|
||||||
|
mock_user.id = uid
|
||||||
|
mock_user.display_name = "Updated User"
|
||||||
|
mock_user.email = "user@example.com"
|
||||||
|
mock_user.phone_number = "+491512345678" # New phone number
|
||||||
|
mock_user.country = "Germany" # New country
|
||||||
|
|
||||||
|
# Existing profile with OLD phone and country
|
||||||
|
existing_profile = UserBillingProfile(
|
||||||
|
id=uuid4(),
|
||||||
|
user_id=uid,
|
||||||
|
label="Default Auto-Generated",
|
||||||
|
billing_name="Initial Name",
|
||||||
|
billing_email="user@example.com",
|
||||||
|
billing_phone="+919876543210", # Old phone number
|
||||||
|
country="India", # Old country
|
||||||
|
address_line1="Not Configured",
|
||||||
|
city="Not Configured",
|
||||||
|
state="Not Configured",
|
||||||
|
postal_code="000000",
|
||||||
|
is_default=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_exec_res = MagicMock()
|
||||||
|
mock_exec_res.scalar_one_or_none.return_value = existing_profile
|
||||||
|
mock_session.execute.return_value = mock_exec_res
|
||||||
|
|
||||||
|
mock_cart_repo = MagicMock()
|
||||||
|
service = CheckoutService(session=mock_session, cart_repository=mock_cart_repo)
|
||||||
|
|
||||||
|
profile = await service._billing_profile(mock_user, None)
|
||||||
|
|
||||||
|
assert profile.billing_phone == "+491512345678"
|
||||||
|
assert profile.country == "Germany"
|
||||||
|
assert profile.billing_name == "Updated User"
|
||||||
|
assert mock_session.flush.called
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_render_invoice_html_uses_updated_phone_and_country() -> None:
|
||||||
|
tx_id = uuid4()
|
||||||
|
mock_tx = MagicMock(spec=PaymentTransaction)
|
||||||
|
mock_tx.id = tx_id
|
||||||
|
mock_tx.user_id = uuid4()
|
||||||
|
mock_tx.gateway_transaction_id = "pay_test123"
|
||||||
|
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_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
|
||||||
|
|
||||||
|
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.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
|
||||||
|
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.address_line1 = "Not Configured"
|
||||||
|
mock_profile.city = "Not Configured"
|
||||||
|
mock_profile.state = "Not Configured"
|
||||||
|
mock_profile.postal_code = "000000"
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
r_tx = MagicMock()
|
||||||
|
r_tx.scalar_one_or_none.return_value = mock_tx
|
||||||
|
r_user = MagicMock()
|
||||||
|
r_user.scalar_one_or_none.return_value = mock_user
|
||||||
|
r_inv = MagicMock()
|
||||||
|
r_inv.scalar_one_or_none.return_value = mock_invoice
|
||||||
|
r_prof = MagicMock()
|
||||||
|
r_prof.scalar_one_or_none.return_value = mock_profile
|
||||||
|
|
||||||
|
mock_session.execute.side_effect = [r_tx, r_user, r_inv, r_prof]
|
||||||
|
|
||||||
|
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
|
||||||
Loading…
Reference in New Issue