fix(coupons): record coupon redemptions and increment usage count on purchase #27

Merged
amit merged 1 commits from fix/coupon-redemption-count into main 2026-11-04 04:47:54 +00:00
8 changed files with 385 additions and 35 deletions
Showing only changes of commit 52356da055 - Show all commits

View File

@ -2,9 +2,9 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from uuid import UUID
from sqlalchemy import select
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import AccessPlan, AppUser, Coupon, Module
from app.db.models import AccessPlan, AppUser, Coupon, CouponRedemption, Module
from ..schema import CreateCouponRequest, UpdateCouponRequest
@ -23,14 +23,24 @@ class AdminCouponService:
mods_q = await self.session.execute(select(Module))
all_mods = {str(m.id): m.name for m in mods_q.scalars().all()}
redemptions_q = await self.session.execute(
select(CouponRedemption.coupon_id, func.count(CouponRedemption.id))
.group_by(CouponRedemption.coupon_id)
)
redemption_counts = {cid: cnt for cid, cnt in redemptions_q.all()}
now = datetime.now(timezone.utc)
result: list[dict] = []
for c in coupons:
s_date = c.start_date.replace(tzinfo=timezone.utc) if c.start_date.tzinfo is None else c.start_date
e_date = c.end_date.replace(tzinfo=timezone.utc) if c.end_date.tzinfo is None else c.end_date
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
if not c.is_active:
status = "inactive"
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
status = "expired"
elif now < s_date:
status = "scheduled"
elif now > e_date:
@ -51,7 +61,7 @@ class AdminCouponService:
"start_date": s_date.isoformat(),
"end_date": e_date.isoformat(),
"usage_limit": c.usage_limit,
"usage_count": c.usage_count,
"usage_count": usage_count,
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
"is_first_purchase_only": c.is_first_purchase_only,
"is_active": c.is_active,

View File

@ -10,6 +10,7 @@ from app.db.models import (
AccessPlan,
AccessPlanModule,
AppUser,
Coupon,
Invoice,
PaymentTransaction,
RefundDecision,
@ -19,7 +20,7 @@ from app.db.models import (
)
from ..schema import AdminRefundRequest, AdminRefundResponse, AdminSyncResponse
from app.features.email import send_invoice_email
from app.features.payments import generate_next_invoice_number, get_razorpay_service
from app.features.payments import generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
class AdminPaymentService:
@ -173,24 +174,38 @@ class AdminPaymentService:
discount = Decimal(str(meta.get("total_discounts", 0)))
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
invoice_number = await generate_next_invoice_number(self.session, dt=now)
self.session.add(
Invoice(
payment_transaction_id=tx.id,
invoice_number=invoice_number,
billing_name=user.display_name or user.email,
billing_email=user.email,
billing_address="Synced from Razorpay",
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=amount,
currency_code=curr,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if curr == "INR" else None,
)
invoice = Invoice(
payment_transaction_id=tx.id,
invoice_number=invoice_number,
billing_name=user.display_name or user.email,
billing_email=user.email,
billing_address="Synced from Razorpay",
applied_coupon_id=coupon.id if coupon else None,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=amount,
currency_code=curr,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if curr == "INR" else None,
)
self.session.add(invoice)
await self.session.flush()
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=sub.user_id,
invoice_id=invoice.id,
)
module_ids = (await self.session.execute(
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id)

View File

@ -10,6 +10,7 @@ from app.db.models import (
AccessPlan,
AppUser,
Coupon,
CouponRedemption,
Invoice,
PaymentTransaction,
Role,
@ -239,6 +240,12 @@ class AdminReportService:
q = q.where(Coupon.created_at <= e_dt)
coupons = (await self.session.execute(q)).scalars().all()
redemptions_q = await self.session.execute(
select(CouponRedemption.coupon_id, func.count(CouponRedemption.id))
.group_by(CouponRedemption.coupon_id)
)
redemption_counts = {cid: cnt for cid, cnt in redemptions_q.all()}
writer.writerow([
"Coupon Code",
"Category",
@ -259,7 +266,7 @@ class AdminReportService:
disc_val = f"{val:.2f}%" if c.discount_type == "percentage" else f"{val:.2f}"
max_cap = f"{float(c.max_discount_limit):.2f}" if c.max_discount_limit else "None"
min_spend = f"{float(c.min_purchase_amount):.2f}" if c.min_purchase_amount else "0.00"
usage_count = c.usage_count or 0
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
remaining_str = "Unlimited"

View File

@ -6,11 +6,11 @@ from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Invoice, PaymentTransaction, UserBillingProfile, UserEntitlement, UserSubscription
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Coupon, Invoice, PaymentTransaction, UserBillingProfile, UserEntitlement, UserSubscription
from app.features.cart.repository import CartRepository
from app.features.cart.schema import CartCalculationRequest
from app.features.cart.service import CartService
from app.features.payments import generate_next_invoice_number, get_razorpay_service
from app.features.payments import generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
class CheckoutService:
@ -31,7 +31,21 @@ class CheckoutService:
except Exception:
pass
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""})
applied_coupon_code = (
request.coupon_code.strip().upper()
if request.coupon_code and calc.coupon_applied and calc.coupon_applied != "None"
else None
)
order = rzp.create_order(
amount=calc.grand_total,
currency=calc.currency,
receipt=receipt,
notes={
"user_id": str(user.id),
"cart_item_codes": ",".join(request.cart_item_codes),
"coupon_code": applied_coupon_code or "",
},
)
plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency)
seen_plan_ids = set()
plans: list[AccessPlan] = []
@ -40,7 +54,16 @@ class CheckoutService:
seen_plan_ids.add(plan.id)
plans.append(plan)
now = datetime.now(timezone.utc)
pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency}
pricing_meta = {
"base_subtotal": calc.base_subtotal,
"total_discounts": calc.total_discounts,
"grand_total": calc.grand_total,
"taxable_amount": calc.taxable_amount,
"gst_amount": calc.gst_amount,
"currency": calc.currency,
"coupon_code": applied_coupon_code,
"coupon_discount_amount": calc.coupon_discount_amount,
}
for plan in plans:
self.session.add(UserSubscription(user_id=user.id, plan_id=plan.id, status=SubscriptionStatus.PENDING, started_at=now, auto_renew=False, payment_provider="razorpay", payment_reference=order["id"], metadata_json=dict(pricing_meta)))
await self.session.commit()
@ -109,9 +132,23 @@ class CheckoutService:
active_ent.expires_at = sub.expires_at
else:
self.session.add(UserEntitlement(user_id=user.id, module_id=module_id, source_subscription_id=sub.id, source_plan_id=sub.plan_id, status=EntitlementStatus.ACTIVE, granted_at=now, grant_reason="subscription_purchase", expires_at=sub.expires_at))
invoice_number, invoice_url = await self._create_invoice(rzp, transaction, profile, payment, plan_names, meta)
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
invoice, invoice_url = await self._create_invoice(
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
)
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=user.id,
invoice_id=invoice.id,
)
await self.session.commit()
return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice_number, "invoice_url": invoice_url}
return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice.invoice_number, "invoice_url": invoice_url}
async def _billing_profile(self, user: AppUser, billing_profile_id: UUID | None) -> UserBillingProfile:
stmt = select(UserBillingProfile).where(UserBillingProfile.user_id == user.id)
@ -127,7 +164,16 @@ class CheckoutService:
await self.session.flush()
return profile
async def _create_invoice(self, rzp, tx: PaymentTransaction, profile: UserBillingProfile, payment: dict, plan_names: list[str], meta: dict) -> tuple[str, str | None]:
async def _create_invoice(
self,
rzp,
tx: PaymentTransaction,
profile: UserBillingProfile,
payment: dict,
plan_names: list[str],
meta: dict,
applied_coupon_id: UUID | None = None,
) -> tuple[Invoice, str | None]:
currency = tx.currency.upper()
inv_number = await generate_next_invoice_number(self.session)
try:
@ -140,5 +186,24 @@ class CheckoutService:
discount = Decimal(str(meta.get("total_discounts", 0)))
taxable = Decimal(str(meta.get("taxable_amount", 0)))
gst = Decimal(str(meta.get("gst_amount", 0)))
self.session.add(Invoice(payment_transaction_id=tx.id, invoice_number=inv_number, billing_name=profile.billing_name, billing_email=profile.billing_email, billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}", gstin=profile.gstin, billing_profile_id=profile.id, base_amount=base, discount_amount=discount, taxable_amount=taxable, gst_amount=gst, total_amount=Decimal(tx.amount), currency_code=currency, exchange_rate_to_inr=Decimal("1"), total_amount_inr=Decimal(tx.amount) if currency == "INR" else None))
return inv_number, inv_url
invoice = Invoice(
payment_transaction_id=tx.id,
invoice_number=inv_number,
billing_name=profile.billing_name,
billing_email=profile.billing_email,
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}",
gstin=profile.gstin,
billing_profile_id=profile.id,
applied_coupon_id=applied_coupon_id,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=Decimal(tx.amount),
currency_code=currency,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=Decimal(tx.amount) if currency == "INR" else None,
)
self.session.add(invoice)
await self.session.flush()
return invoice, inv_url

View File

@ -1,6 +1,15 @@
from .razorpay import RazorpayService, get_razorpay_service
from .pricing import PricingEngine, PricingItem, PricingCoupon
from .invoice_service import generate_next_invoice_number
from .coupon_redemption import record_coupon_redemption
__all__ = ["RazorpayService", "get_razorpay_service", "PricingEngine", "PricingItem", "PricingCoupon", "generate_next_invoice_number"]
__all__ = [
"RazorpayService",
"get_razorpay_service",
"PricingEngine",
"PricingItem",
"PricingCoupon",
"generate_next_invoice_number",
"record_coupon_redemption",
]

View File

@ -0,0 +1,50 @@
from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import Coupon, CouponRedemption
async def record_coupon_redemption(
session: AsyncSession,
*,
coupon: Coupon | None = None,
coupon_code: str | None = None,
user_id: UUID,
invoice_id: UUID | None = None,
) -> Coupon | None:
"""Increment coupon usage_count and record CouponRedemption entry."""
if coupon is None:
if not coupon_code or not str(coupon_code).strip():
return None
code = str(coupon_code).strip().upper()
coupon = (await session.execute(
select(Coupon).where(Coupon.code == code)
)).scalar_one_or_none()
if not coupon:
return None
coupon.usage_count = (coupon.usage_count or 0) + 1
existing = (await session.execute(
select(CouponRedemption).where(
CouponRedemption.coupon_id == coupon.id,
CouponRedemption.user_id == user_id,
)
)).scalar_one_or_none()
if not existing:
session.add(CouponRedemption(
coupon_id=coupon.id,
user_id=user_id,
invoice_id=invoice_id,
redeemed_at=datetime.now(timezone.utc),
))
elif invoice_id and not existing.invoice_id:
existing.invoice_id = invoice_id
return coupon

View File

@ -6,8 +6,8 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, Invoice, PaymentTransaction, UserEntitlement, UserSubscription
from app.features.payments import generate_next_invoice_number
from app.db.models import AccessPlan, AccessPlanModule, Coupon, Invoice, PaymentTransaction, UserEntitlement, UserSubscription
from app.features.payments import generate_next_invoice_number, record_coupon_redemption
class RazorpayWebhookService:
@ -96,12 +96,19 @@ class RazorpayWebhookService:
base = Decimal(str(meta.get("base_subtotal", amount)))
discount = Decimal(str(meta.get("total_discounts", "0")))
invoice_number = await generate_next_invoice_number(self.session, dt=now)
self.session.add(Invoice(
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
invoice = Invoice(
payment_transaction_id=transaction.id,
invoice_number=invoice_number,
billing_name=((payment.get("card") or {}).get("name") or payment.get("email") or "Customer"),
billing_email=payment.get("email") or "unknown@example.invalid",
billing_address="Recorded from Gateway Webhook",
applied_coupon_id=coupon.id if coupon else None,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
@ -110,7 +117,17 @@ class RazorpayWebhookService:
currency_code=currency,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if currency == "INR" else None,
))
)
self.session.add(invoice)
await self.session.flush()
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=main.user_id,
invoice_id=invoice.id,
)
await self.session.commit()
return {"status": "accepted"}

View File

@ -0,0 +1,177 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
from datetime import datetime, timezone
import pytest
from app.db.models import AppUser, Coupon, CouponRedemption
from app.features.payments.coupon_redemption import record_coupon_redemption
from app.features.admin.services.coupon_service import AdminCouponService
@pytest.mark.asyncio
async def test_record_coupon_redemption_increments_count_and_adds_record():
session = AsyncMock()
coupon_id = uuid4()
user_id = uuid4()
invoice_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "PROMO50"
mock_coupon.usage_count = 3
# execute returns mock_coupon for coupon query, and None for existing redemption
exec_coupon = MagicMock()
exec_coupon.scalar_one_or_none.return_value = mock_coupon
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = None
session.execute.side_effect = [exec_coupon, exec_redemption]
result = await record_coupon_redemption(
session,
coupon_code="promo50",
user_id=user_id,
invoice_id=invoice_id,
)
assert result is mock_coupon
assert mock_coupon.usage_count == 4
session.add.assert_called_once()
added_obj = session.add.call_args[0][0]
assert isinstance(added_obj, CouponRedemption)
assert added_obj.coupon_id == coupon_id
assert added_obj.user_id == user_id
assert added_obj.invoice_id == invoice_id
@pytest.mark.asyncio
async def test_record_coupon_redemption_existing_user_updates_invoice():
session = AsyncMock()
coupon_id = uuid4()
user_id = uuid4()
invoice_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "WELCOME10"
mock_coupon.usage_count = 10
existing_redemption = MagicMock(spec=CouponRedemption)
existing_redemption.invoice_id = None
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = existing_redemption
session.execute.return_value = exec_redemption
result = await record_coupon_redemption(
session,
coupon=mock_coupon,
user_id=user_id,
invoice_id=invoice_id,
)
assert result is mock_coupon
assert mock_coupon.usage_count == 11
# Should update existing redemption's invoice_id rather than calling session.add
assert existing_redemption.invoice_id == invoice_id
session.add.assert_not_called()
@pytest.mark.asyncio
async def test_list_coupons_reports_accurate_usage_count():
session = AsyncMock()
coupon_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "ACTIVE10"
mock_coupon.discount_type = "percentage"
mock_coupon.coupon_category = "general"
mock_coupon.value = 10.0
mock_coupon.max_discount_limit = 0.0
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2027, 1, 1, tzinfo=timezone.utc)
mock_coupon.usage_limit = 100
mock_coupon.usage_count = 5
mock_coupon.min_purchase_amount = 0.0
mock_coupon.is_first_purchase_only = False
mock_coupon.is_active = True
mock_coupon.description = "Test coupon"
mock_coupon.applicable_plan_ids = []
mock_coupon.applicable_module_ids = []
mock_coupon.created_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
# Mock queries: 1. Coupon list, 2. Plans, 3. Modules, 4. Redemptions
exec_coupons = MagicMock()
exec_coupons.scalars.return_value.all.return_value = [mock_coupon]
exec_plans = MagicMock()
exec_plans.scalars.return_value.all.return_value = []
exec_mods = MagicMock()
exec_mods.scalars.return_value.all.return_value = []
exec_redemptions = MagicMock()
exec_redemptions.all.return_value = [(coupon_id, 7)] # 7 redemptions in ledger
session.execute.side_effect = [exec_coupons, exec_plans, exec_mods, exec_redemptions]
service = AdminCouponService(session)
result = await service.list_coupons()
assert len(result) == 1
# usage_count should be max(mock_coupon.usage_count (5), redemptions (7)) = 7
assert result[0]["usage_count"] == 7
assert result[0]["schedule_status"] == "active"
@pytest.mark.asyncio
async def test_list_coupons_exhausted_marked_expired():
session = AsyncMock()
coupon_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "LIMITED5"
mock_coupon.discount_type = "percentage"
mock_coupon.coupon_category = "general"
mock_coupon.value = 10.0
mock_coupon.max_discount_limit = 0.0
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2027, 1, 1, tzinfo=timezone.utc)
mock_coupon.usage_limit = 5
mock_coupon.usage_count = 5
mock_coupon.min_purchase_amount = 0.0
mock_coupon.is_first_purchase_only = False
mock_coupon.is_active = True
mock_coupon.description = "Limited coupon"
mock_coupon.applicable_plan_ids = []
mock_coupon.applicable_module_ids = []
mock_coupon.created_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
exec_coupons = MagicMock()
exec_coupons.scalars.return_value.all.return_value = [mock_coupon]
exec_plans = MagicMock()
exec_plans.scalars.return_value.all.return_value = []
exec_mods = MagicMock()
exec_mods.scalars.return_value.all.return_value = []
exec_redemptions = MagicMock()
exec_redemptions.all.return_value = []
session.execute.side_effect = [exec_coupons, exec_plans, exec_mods, exec_redemptions]
service = AdminCouponService(session)
result = await service.list_coupons()
assert len(result) == 1
assert result[0]["usage_count"] == 5
# Since usage_count (5) >= usage_limit (5), status should be expired
assert result[0]["schedule_status"] == "expired"