Merge pull request 'feat(coupons): add per-user limit and fully redeemed status' (#47) from fix/issue-57-coupon-per-user-limit into main
Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-api/pulls/47 Reviewed-by: Amit Salunke <amit@noreply.localhost>
This commit is contained in:
commit
aa7ec0c679
|
|
@ -0,0 +1,85 @@
|
||||||
|
"""add per_user_limit on coupons and allow multi-use coupon redemptions
|
||||||
|
|
||||||
|
Revision ID: 0006_coupon_per_user_limit
|
||||||
|
Revises: 0005_builder_modules_table
|
||||||
|
Create Date: 2026-12-01
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0006_coupon_per_user_limit"
|
||||||
|
down_revision: str | None = "0005_builder_modules_table"
|
||||||
|
branch_labels: Sequence[str] | None = None
|
||||||
|
depends_on: Sequence[str] | None = None
|
||||||
|
|
||||||
|
COMMERCE_SCHEMA = "commerce"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
bind = op.get_bind()
|
||||||
|
inspector = sa.inspect(bind)
|
||||||
|
|
||||||
|
coupon_columns = {
|
||||||
|
col["name"] for col in inspector.get_columns("coupons", schema=COMMERCE_SCHEMA)
|
||||||
|
}
|
||||||
|
if "per_user_limit" not in coupon_columns:
|
||||||
|
op.add_column(
|
||||||
|
"coupons",
|
||||||
|
sa.Column("per_user_limit", sa.Integer(), nullable=True),
|
||||||
|
schema=COMMERCE_SCHEMA,
|
||||||
|
)
|
||||||
|
|
||||||
|
unique_names = {
|
||||||
|
uc["name"]
|
||||||
|
for uc in inspector.get_unique_constraints(
|
||||||
|
"coupon_redemptions", schema=COMMERCE_SCHEMA
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if "uq_coupon_user" in unique_names:
|
||||||
|
op.drop_constraint(
|
||||||
|
"uq_coupon_user",
|
||||||
|
"coupon_redemptions",
|
||||||
|
schema=COMMERCE_SCHEMA,
|
||||||
|
type_="unique",
|
||||||
|
)
|
||||||
|
|
||||||
|
index_names = {
|
||||||
|
idx["name"]
|
||||||
|
for idx in inspector.get_indexes("coupon_redemptions", schema=COMMERCE_SCHEMA)
|
||||||
|
}
|
||||||
|
if "idx_coupon_redemptions_coupon_user" not in index_names:
|
||||||
|
op.create_index(
|
||||||
|
"idx_coupon_redemptions_coupon_user",
|
||||||
|
"coupon_redemptions",
|
||||||
|
["coupon_id", "user_id"],
|
||||||
|
unique=False,
|
||||||
|
schema=COMMERCE_SCHEMA,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
bind = op.get_bind()
|
||||||
|
inspector = sa.inspect(bind)
|
||||||
|
|
||||||
|
index_names = {
|
||||||
|
idx["name"]
|
||||||
|
for idx in inspector.get_indexes("coupon_redemptions", schema=COMMERCE_SCHEMA)
|
||||||
|
}
|
||||||
|
if "idx_coupon_redemptions_coupon_user" in index_names:
|
||||||
|
op.drop_index(
|
||||||
|
"idx_coupon_redemptions_coupon_user",
|
||||||
|
table_name="coupon_redemptions",
|
||||||
|
schema=COMMERCE_SCHEMA,
|
||||||
|
)
|
||||||
|
|
||||||
|
coupon_columns = {
|
||||||
|
col["name"] for col in inspector.get_columns("coupons", schema=COMMERCE_SCHEMA)
|
||||||
|
}
|
||||||
|
if "per_user_limit" in coupon_columns:
|
||||||
|
op.drop_column("coupons", "per_user_limit", schema=COMMERCE_SCHEMA)
|
||||||
|
|
@ -216,6 +216,7 @@ class Coupon(Base):
|
||||||
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
end_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
end_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
usage_limit: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
usage_limit: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||||
|
per_user_limit: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
usage_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
usage_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
|
||||||
applicable_plan_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
|
applicable_plan_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
|
||||||
applicable_module_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
|
applicable_module_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
|
||||||
|
|
@ -291,7 +292,10 @@ class InvoiceMonthlySequence(Base):
|
||||||
|
|
||||||
class CouponRedemption(Base):
|
class CouponRedemption(Base):
|
||||||
__tablename__ = "coupon_redemptions"
|
__tablename__ = "coupon_redemptions"
|
||||||
__table_args__ = (UniqueConstraint("coupon_id", "user_id", name="uq_coupon_user"), {"schema": COMMERCE_SCHEMA})
|
__table_args__ = (
|
||||||
|
Index("idx_coupon_redemptions_coupon_user", "coupon_id", "user_id"),
|
||||||
|
{"schema": COMMERCE_SCHEMA},
|
||||||
|
)
|
||||||
|
|
||||||
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
||||||
coupon_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{COMMERCE_SCHEMA}.coupons.id", ondelete="CASCADE"), nullable=False)
|
coupon_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{COMMERCE_SCHEMA}.coupons.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
|
|
||||||
|
|
@ -97,6 +97,7 @@ class CreateCouponRequest(BaseModel):
|
||||||
start_date: str | None = None
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int = 0
|
usage_limit: int = 0
|
||||||
|
per_user_limit: int | None = None
|
||||||
min_purchase_amount: float = 0.0
|
min_purchase_amount: float = 0.0
|
||||||
min_purchase_inr: float | None = None
|
min_purchase_inr: float | None = None
|
||||||
min_purchase_usd: float | None = None
|
min_purchase_usd: float | None = None
|
||||||
|
|
@ -122,6 +123,7 @@ class UpdateCouponRequest(BaseModel):
|
||||||
start_date: str | None = None
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int | None = None
|
usage_limit: int | None = None
|
||||||
|
per_user_limit: int | None = None
|
||||||
min_purchase_amount: float | None = None
|
min_purchase_amount: float | None = None
|
||||||
min_purchase_inr: float | None = None
|
min_purchase_inr: float | None = None
|
||||||
min_purchase_usd: float | None = None
|
min_purchase_usd: float | None = None
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ class AdminCouponService:
|
||||||
if not c.is_active:
|
if not c.is_active:
|
||||||
status = "inactive"
|
status = "inactive"
|
||||||
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
|
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
|
||||||
status = "expired"
|
status = "fully_redeemed"
|
||||||
elif now < s_date:
|
elif now < s_date:
|
||||||
status = "scheduled"
|
status = "scheduled"
|
||||||
elif now > e_date:
|
elif now > e_date:
|
||||||
|
|
@ -164,6 +164,11 @@ class AdminCouponService:
|
||||||
"start_date": s_date.isoformat(),
|
"start_date": s_date.isoformat(),
|
||||||
"end_date": e_date.isoformat(),
|
"end_date": e_date.isoformat(),
|
||||||
"usage_limit": c.usage_limit,
|
"usage_limit": c.usage_limit,
|
||||||
|
"per_user_limit": (
|
||||||
|
c.per_user_limit
|
||||||
|
if isinstance(c.per_user_limit, int) and not isinstance(c.per_user_limit, bool)
|
||||||
|
else None
|
||||||
|
),
|
||||||
"usage_count": usage_count,
|
"usage_count": usage_count,
|
||||||
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
||||||
"min_purchase_inr": min_inr,
|
"min_purchase_inr": min_inr,
|
||||||
|
|
@ -198,6 +203,10 @@ class AdminCouponService:
|
||||||
|
|
||||||
if end <= start:
|
if end <= start:
|
||||||
raise ValueError("Invalid date range: End date must be later than start date.")
|
raise ValueError("Invalid date range: End date must be later than start date.")
|
||||||
|
if payload.usage_limit < 0:
|
||||||
|
raise ValueError("Global usage limit must be 0 or greater.")
|
||||||
|
if payload.per_user_limit is None or payload.per_user_limit < 0:
|
||||||
|
raise ValueError("Per-user limit is required and must be 0 or greater.")
|
||||||
|
|
||||||
expanded_plan_uuids = await self._expand_plan_ids(payload.applicable_plan_ids)
|
expanded_plan_uuids = await self._expand_plan_ids(payload.applicable_plan_ids)
|
||||||
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
||||||
|
|
@ -216,6 +225,7 @@ class AdminCouponService:
|
||||||
start_date=start,
|
start_date=start,
|
||||||
end_date=end,
|
end_date=end,
|
||||||
usage_limit=payload.usage_limit,
|
usage_limit=payload.usage_limit,
|
||||||
|
per_user_limit=payload.per_user_limit,
|
||||||
usage_count=0,
|
usage_count=0,
|
||||||
min_purchase_amount=Decimal(str(base_min)),
|
min_purchase_amount=Decimal(str(base_min)),
|
||||||
is_first_purchase_only=payload.is_first_purchase_only,
|
is_first_purchase_only=payload.is_first_purchase_only,
|
||||||
|
|
@ -262,7 +272,13 @@ class AdminCouponService:
|
||||||
if payload.end_date is not None:
|
if payload.end_date is not None:
|
||||||
coupon.end_date = new_end
|
coupon.end_date = new_end
|
||||||
if payload.usage_limit is not None:
|
if payload.usage_limit is not None:
|
||||||
|
if payload.usage_limit < 0:
|
||||||
|
raise ValueError("Global usage limit must be 0 or greater.")
|
||||||
coupon.usage_limit = payload.usage_limit
|
coupon.usage_limit = payload.usage_limit
|
||||||
|
if "per_user_limit" in payload.model_fields_set:
|
||||||
|
if payload.per_user_limit is None or payload.per_user_limit < 0:
|
||||||
|
raise ValueError("Per-user limit is required and must be 0 or greater.")
|
||||||
|
coupon.per_user_limit = payload.per_user_limit
|
||||||
if payload.min_purchase_inr is not None:
|
if payload.min_purchase_inr is not None:
|
||||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
|
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
|
||||||
elif payload.min_purchase_amount is not None:
|
elif payload.min_purchase_amount is not None:
|
||||||
|
|
|
||||||
|
|
@ -356,7 +356,7 @@ class AdminReportService:
|
||||||
elif c.end_date and c.end_date < now:
|
elif c.end_date and c.end_date < now:
|
||||||
schedule_status = "Expired"
|
schedule_status = "Expired"
|
||||||
elif c.usage_limit and usage_count >= c.usage_limit:
|
elif c.usage_limit and usage_count >= c.usage_limit:
|
||||||
schedule_status = "Exhausted"
|
schedule_status = "Fully Redeemed"
|
||||||
|
|
||||||
start_str = c.start_date.strftime("%Y-%m-%d") if c.start_date else "Immediate"
|
start_str = c.start_date.strftime("%Y-%m-%d") if c.start_date else "Immediate"
|
||||||
end_str = c.end_date.strftime("%Y-%m-%d") if c.end_date else "No Expiry"
|
end_str = c.end_date.strftime("%Y-%m-%d") if c.end_date else "No Expiry"
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,10 @@ from __future__ import annotations
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
||||||
from app.db.models import AccessPlan, AccessPlanModule, Coupon, Module, UserEntitlement, UserSubscription
|
from app.db.models import AccessPlan, AccessPlanModule, Coupon, CouponRedemption, Module, UserEntitlement, UserSubscription
|
||||||
from app.features.payments.pricing import PricingCoupon, PricingItem
|
from app.features.payments.pricing import PricingCoupon, PricingItem
|
||||||
|
|
||||||
class CartRepository:
|
class CartRepository:
|
||||||
|
|
@ -151,7 +151,7 @@ class CartRepository:
|
||||||
))
|
))
|
||||||
return items
|
return items
|
||||||
|
|
||||||
async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
|
async def get_coupon(self, code: str | None, currency: str, user_id: UUID | None = None) -> tuple[PricingCoupon | None, str | None]:
|
||||||
if not code or not code.strip():
|
if not code or not code.strip():
|
||||||
return None, None
|
return None, None
|
||||||
clean_code = code.strip().upper()
|
clean_code = code.strip().upper()
|
||||||
|
|
@ -169,6 +169,21 @@ class CartRepository:
|
||||||
return None, "This coupon code has expired."
|
return None, "This coupon code has expired."
|
||||||
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
|
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
|
||||||
return None, "Coupon usage limit reached."
|
return None, "Coupon usage limit reached."
|
||||||
|
per_user_limit = getattr(coupon, "per_user_limit", None)
|
||||||
|
if isinstance(per_user_limit, int) and not isinstance(per_user_limit, bool):
|
||||||
|
if per_user_limit <= 0:
|
||||||
|
return None, "This coupon is currently not available for redemption."
|
||||||
|
if user_id is not None:
|
||||||
|
user_redemptions = (
|
||||||
|
await self.session.execute(
|
||||||
|
select(func.count(CouponRedemption.id)).where(
|
||||||
|
CouponRedemption.coupon_id == coupon.id,
|
||||||
|
CouponRedemption.user_id == user_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalar() or 0
|
||||||
|
if user_redemptions >= per_user_limit:
|
||||||
|
return None, "You have already reached the usage limit for this coupon."
|
||||||
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
|
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
|
||||||
value = Decimal(coupon.value)
|
value = Decimal(coupon.value)
|
||||||
if coupon.discount_type in {"flat", "flat_amount"}:
|
if coupon.discount_type in {"flat", "flat_amount"}:
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ class CartService:
|
||||||
resolved = {i.code.upper() for i in items}
|
resolved = {i.code.upper() for i in items}
|
||||||
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
|
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
|
||||||
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
|
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
|
||||||
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency)
|
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency, user_id=user_id)
|
||||||
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
||||||
if request.owned_category_names:
|
if request.owned_category_names:
|
||||||
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,8 @@ class CheckoutService:
|
||||||
async def create_order(self, user: AppUser, request: CheckoutOrderRequest) -> CheckoutOrderResponse:
|
async def create_order(self, user: AppUser, request: CheckoutOrderRequest) -> CheckoutOrderResponse:
|
||||||
validate_user_country_currency(user.country, request.currency)
|
validate_user_country_currency(user.country, request.currency)
|
||||||
calc = await self.cart_service.calculate(CartCalculationRequest(cart_item_codes=request.cart_item_codes, coupon_code=request.coupon_code, currency=request.currency), user_id=user.id)
|
calc = await self.cart_service.calculate(CartCalculationRequest(cart_item_codes=request.cart_item_codes, coupon_code=request.coupon_code, currency=request.currency), user_id=user.id)
|
||||||
|
if request.coupon_code and request.coupon_code.strip() and calc.coupon_error:
|
||||||
|
raise ValueError(calc.coupon_error)
|
||||||
if calc.grand_total <= 0:
|
if calc.grand_total <= 0:
|
||||||
raise ValueError("Grand total must be greater than zero to checkout.")
|
raise ValueError("Grand total must be greater than zero to checkout.")
|
||||||
rzp = get_razorpay_service()
|
rzp = get_razorpay_service()
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import select
|
from sqlalchemy import or_, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.models import Coupon, CouponRedemption
|
from app.db.models import Coupon, CouponRedemption
|
||||||
|
|
||||||
|
|
@ -15,7 +15,7 @@ async def record_coupon_redemption(
|
||||||
user_id: UUID,
|
user_id: UUID,
|
||||||
invoice_id: UUID | None = None,
|
invoice_id: UUID | None = None,
|
||||||
) -> Coupon | None:
|
) -> Coupon | None:
|
||||||
"""Increment coupon usage_count and record CouponRedemption entry."""
|
"""Increment coupon usage_count and record a per-invoice CouponRedemption entry."""
|
||||||
if coupon is None:
|
if coupon is None:
|
||||||
if not coupon_code or not str(coupon_code).strip():
|
if not coupon_code or not str(coupon_code).strip():
|
||||||
return None
|
return None
|
||||||
|
|
@ -27,24 +27,38 @@ async def record_coupon_redemption(
|
||||||
if not coupon:
|
if not coupon:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
coupon.usage_count = (coupon.usage_count or 0) + 1
|
if invoice_id is not None:
|
||||||
|
existing_filter = or_(
|
||||||
|
CouponRedemption.invoice_id == invoice_id,
|
||||||
|
CouponRedemption.invoice_id.is_(None),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
existing_filter = CouponRedemption.invoice_id.is_(None)
|
||||||
|
|
||||||
existing = (await session.execute(
|
existing = (await session.execute(
|
||||||
select(CouponRedemption).where(
|
select(CouponRedemption)
|
||||||
|
.where(
|
||||||
CouponRedemption.coupon_id == coupon.id,
|
CouponRedemption.coupon_id == coupon.id,
|
||||||
CouponRedemption.user_id == user_id,
|
CouponRedemption.user_id == user_id,
|
||||||
|
existing_filter,
|
||||||
)
|
)
|
||||||
|
.limit(1)
|
||||||
)).scalar_one_or_none()
|
)).scalar_one_or_none()
|
||||||
|
|
||||||
if not existing:
|
if existing:
|
||||||
session.add(CouponRedemption(
|
if invoice_id is not None and existing.invoice_id == invoice_id:
|
||||||
coupon_id=coupon.id,
|
return coupon
|
||||||
user_id=user_id,
|
coupon.usage_count = (coupon.usage_count or 0) + 1
|
||||||
invoice_id=invoice_id,
|
if invoice_id and not existing.invoice_id:
|
||||||
redeemed_at=datetime.now(timezone.utc),
|
existing.invoice_id = invoice_id
|
||||||
))
|
return coupon
|
||||||
elif invoice_id and not existing.invoice_id:
|
|
||||||
existing.invoice_id = invoice_id
|
|
||||||
|
|
||||||
|
coupon.usage_count = (coupon.usage_count or 0) + 1
|
||||||
|
session.add(CouponRedemption(
|
||||||
|
coupon_id=coupon.id,
|
||||||
|
user_id=user_id,
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
redeemed_at=datetime.now(timezone.utc),
|
||||||
|
))
|
||||||
return coupon
|
return coupon
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -173,5 +173,56 @@ async def test_list_coupons_exhausted_marked_expired():
|
||||||
|
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result[0]["usage_count"] == 5
|
assert result[0]["usage_count"] == 5
|
||||||
# Since usage_count (5) >= usage_limit (5), status should be expired
|
# Since usage_count (5) >= usage_limit (5), status should be fully_redeemed
|
||||||
assert result[0]["schedule_status"] == "expired"
|
assert result[0]["schedule_status"] == "fully_redeemed"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_record_coupon_redemption_allows_repeat_purchase_across_distinct_invoices():
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = MagicMock(spec=Coupon)
|
||||||
|
coupon.id = uuid4()
|
||||||
|
coupon.usage_count = 1
|
||||||
|
user_id = uuid4()
|
||||||
|
invoice_id = uuid4()
|
||||||
|
|
||||||
|
exec_redemption = MagicMock()
|
||||||
|
exec_redemption.scalar_one_or_none.return_value = None
|
||||||
|
session.execute.return_value = exec_redemption
|
||||||
|
|
||||||
|
await record_coupon_redemption(
|
||||||
|
session,
|
||||||
|
coupon=coupon,
|
||||||
|
user_id=user_id,
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert coupon.usage_count == 2
|
||||||
|
session.add.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_record_coupon_redemption_is_idempotent_for_same_invoice():
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = MagicMock(spec=Coupon)
|
||||||
|
coupon.id = uuid4()
|
||||||
|
coupon.usage_count = 2
|
||||||
|
user_id = uuid4()
|
||||||
|
invoice_id = uuid4()
|
||||||
|
|
||||||
|
existing_redemption = MagicMock(spec=CouponRedemption)
|
||||||
|
existing_redemption.invoice_id = invoice_id
|
||||||
|
|
||||||
|
exec_redemption = MagicMock()
|
||||||
|
exec_redemption.scalar_one_or_none.return_value = existing_redemption
|
||||||
|
session.execute.return_value = exec_redemption
|
||||||
|
|
||||||
|
await record_coupon_redemption(
|
||||||
|
session,
|
||||||
|
coupon=coupon,
|
||||||
|
user_id=user_id,
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert coupon.usage_count == 2
|
||||||
|
session.add.assert_not_called()
|
||||||
|
|
|
||||||
|
|
@ -92,6 +92,7 @@ async def test_create_coupon_valid_date_range():
|
||||||
code="TESTVALID",
|
code="TESTVALID",
|
||||||
discount_type="percentage",
|
discount_type="percentage",
|
||||||
value=10.0,
|
value=10.0,
|
||||||
|
per_user_limit=1,
|
||||||
start_date="2026-12-01T00:00:00Z",
|
start_date="2026-12-01T00:00:00Z",
|
||||||
end_date="2026-12-31T00:00:00Z",
|
end_date="2026-12-31T00:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,201 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.db.models import AppUser, Coupon
|
||||||
|
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
|
||||||
|
from app.features.admin.services.coupon_service import AdminCouponService
|
||||||
|
from app.features.cart.repository import CartRepository
|
||||||
|
from app.features.checkout.schema import CheckoutOrderRequest
|
||||||
|
from app.features.checkout.service import CheckoutService
|
||||||
|
|
||||||
|
|
||||||
|
def _make_active_coupon(*, usage_limit: int = 0, per_user_limit: int | None = None, usage_count: int = 0) -> MagicMock:
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
coupon = MagicMock(spec=Coupon)
|
||||||
|
coupon.id = uuid4()
|
||||||
|
coupon.code = "PROMO20"
|
||||||
|
coupon.discount_type = "percentage"
|
||||||
|
coupon.value = Decimal("20.00")
|
||||||
|
coupon.max_discount_limit = Decimal("0.00")
|
||||||
|
coupon.min_purchase_amount = Decimal("0.00")
|
||||||
|
coupon.start_date = now - timedelta(days=1)
|
||||||
|
coupon.end_date = now + timedelta(days=10)
|
||||||
|
coupon.usage_limit = usage_limit
|
||||||
|
coupon.per_user_limit = per_user_limit
|
||||||
|
coupon.usage_count = usage_count
|
||||||
|
coupon.applicable_plan_ids = []
|
||||||
|
coupon.applicable_module_ids = []
|
||||||
|
coupon.is_first_purchase_only = False
|
||||||
|
coupon.is_active = True
|
||||||
|
coupon.metadata_json = {}
|
||||||
|
return coupon
|
||||||
|
|
||||||
|
|
||||||
|
class TestPerUserCouponValidation:
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_per_user_limit_zero_blocks_every_user(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = _make_active_coupon(usage_limit=0, per_user_limit=0)
|
||||||
|
res_coupon = MagicMock()
|
||||||
|
res_coupon.scalar_one_or_none.return_value = coupon
|
||||||
|
session.execute.return_value = res_coupon
|
||||||
|
|
||||||
|
repo = CartRepository(session)
|
||||||
|
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
|
||||||
|
|
||||||
|
assert resolved is None
|
||||||
|
assert error == "This coupon is currently not available for redemption."
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_per_user_limit_none_allows_unlimited_user_redemptions(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = _make_active_coupon(usage_limit=0, per_user_limit=None, usage_count=5)
|
||||||
|
res_coupon = MagicMock()
|
||||||
|
res_coupon.scalar_one_or_none.return_value = coupon
|
||||||
|
session.execute.return_value = res_coupon
|
||||||
|
|
||||||
|
repo = CartRepository(session)
|
||||||
|
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
|
||||||
|
|
||||||
|
assert resolved is not None
|
||||||
|
assert error is None
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_per_user_limit_enforces_user_redemption_cap(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = _make_active_coupon(usage_limit=10, per_user_limit=1, usage_count=1)
|
||||||
|
res_coupon = MagicMock()
|
||||||
|
res_coupon.scalar_one_or_none.return_value = coupon
|
||||||
|
|
||||||
|
res_count = MagicMock()
|
||||||
|
res_count.scalar.return_value = 1
|
||||||
|
session.execute.side_effect = [res_coupon, res_count]
|
||||||
|
|
||||||
|
repo = CartRepository(session)
|
||||||
|
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
|
||||||
|
|
||||||
|
assert resolved is None
|
||||||
|
assert error == "You have already reached the usage limit for this coupon."
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_per_user_limit_allows_user_below_limit(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = _make_active_coupon(usage_limit=10, per_user_limit=2, usage_count=1)
|
||||||
|
res_coupon = MagicMock()
|
||||||
|
res_coupon.scalar_one_or_none.return_value = coupon
|
||||||
|
|
||||||
|
res_count = MagicMock()
|
||||||
|
res_count.scalar.return_value = 1
|
||||||
|
session.execute.side_effect = [res_coupon, res_count]
|
||||||
|
|
||||||
|
repo = CartRepository(session)
|
||||||
|
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
|
||||||
|
|
||||||
|
assert resolved is not None
|
||||||
|
assert error is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestAdminCouponPerUserLimitLifecycle:
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_create_coupon_accepts_zero_and_none_per_user_limit(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
res_existing = MagicMock()
|
||||||
|
res_existing.scalar_one_or_none.return_value = None
|
||||||
|
session.execute.return_value = res_existing
|
||||||
|
|
||||||
|
svc = AdminCouponService(session)
|
||||||
|
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||||
|
|
||||||
|
payload = CreateCouponRequest(
|
||||||
|
code="ZEROUSER",
|
||||||
|
discount_type="percentage",
|
||||||
|
value=10.0,
|
||||||
|
per_user_limit=0,
|
||||||
|
)
|
||||||
|
await svc.create_coupon(payload, admin)
|
||||||
|
|
||||||
|
added_coupon = session.add.call_args[0][0]
|
||||||
|
assert added_coupon.per_user_limit == 0
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_create_coupon_requires_per_user_limit(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
res_existing = MagicMock()
|
||||||
|
res_existing.scalar_one_or_none.return_value = None
|
||||||
|
session.execute.return_value = res_existing
|
||||||
|
|
||||||
|
svc = AdminCouponService(session)
|
||||||
|
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||||
|
|
||||||
|
payload = CreateCouponRequest(
|
||||||
|
code="BLANKUSER",
|
||||||
|
discount_type="percentage",
|
||||||
|
value=10.0,
|
||||||
|
per_user_limit=None,
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="Per-user limit is required"):
|
||||||
|
await svc.create_coupon(payload, admin)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_create_coupon_rejects_negative_per_user_limit(self) -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
res_existing = MagicMock()
|
||||||
|
res_existing.scalar_one_or_none.return_value = None
|
||||||
|
session.execute.return_value = res_existing
|
||||||
|
|
||||||
|
svc = AdminCouponService(session)
|
||||||
|
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||||
|
|
||||||
|
payload = CreateCouponRequest(
|
||||||
|
code="NEGUSER",
|
||||||
|
discount_type="percentage",
|
||||||
|
value=10.0,
|
||||||
|
per_user_limit=-1,
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="Per-user limit is required and must be 0 or greater"):
|
||||||
|
await svc.create_coupon(payload, admin)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_update_coupon_rejects_blank_per_user_limit_and_preserves_when_omitted(self) -> None:
|
||||||
|
coupon = _make_active_coupon(per_user_limit=1)
|
||||||
|
session = AsyncMock()
|
||||||
|
res_coupon = MagicMock()
|
||||||
|
res_coupon.scalar_one_or_none.return_value = coupon
|
||||||
|
session.execute.return_value = res_coupon
|
||||||
|
|
||||||
|
svc = AdminCouponService(session)
|
||||||
|
|
||||||
|
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(description="Unchanged limit"))
|
||||||
|
assert coupon.per_user_limit == 1
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="Per-user limit is required"):
|
||||||
|
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(per_user_limit=None))
|
||||||
|
|
||||||
|
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(per_user_limit=3))
|
||||||
|
assert coupon.per_user_limit == 3
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_checkout_create_order_rejects_invalid_coupon() -> None:
|
||||||
|
session = AsyncMock()
|
||||||
|
cart_repo = MagicMock(spec=CartRepository)
|
||||||
|
service = CheckoutService(session=session, cart_repository=cart_repo)
|
||||||
|
service.cart_service.calculate = AsyncMock(
|
||||||
|
return_value=MagicMock(
|
||||||
|
grand_total=1000.0,
|
||||||
|
coupon_error="You have already reached the usage limit for this coupon.",
|
||||||
|
coupon_applied="None",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
user = AppUser(id=uuid4(), email="user@acupedia.test", country="India")
|
||||||
|
req = CheckoutOrderRequest(cart_item_codes=["LIFETIME_ALL"], coupon_code="PROMO20", currency="INR")
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="usage limit for this coupon"):
|
||||||
|
await service.create_order(user, req)
|
||||||
|
|
||||||
Loading…
Reference in New Issue