210 lines
8.3 KiB
Python
210 lines
8.3 KiB
Python
"""
|
|
@service CouponService (Backend/app/services/CouponService.py)
|
|
@purpose Multi-point rule engine for promotional coupons, first-time buyer checks, catalog restrictions, and usage accounting.
|
|
"""
|
|
import ulid
|
|
from datetime import datetime, timezone
|
|
from typing import Dict, Any, List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from decimal import Decimal
|
|
|
|
from app.models.CouponModel import Coupon, CouponUsage
|
|
from app.models.OrderModel import Order
|
|
from app.models.ProductModel import ProductVariant, Product
|
|
|
|
|
|
class CouponService:
|
|
|
|
@staticmethod
|
|
def validate_coupon(
|
|
db: Session,
|
|
code: str,
|
|
customer_id: Optional[str],
|
|
items: List[Dict[str, Any]],
|
|
subtotal: float,
|
|
channel: str = "ONLINE",
|
|
shipping_cost: float = 0.0
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
Validates coupon against all configured business rules.
|
|
Returns validation status, calculated discount amount, or human-readable rejection reason.
|
|
"""
|
|
if not code or not code.strip():
|
|
return {"valid": False, "error": "Please enter a valid coupon code."}
|
|
|
|
clean_code = code.strip().upper()
|
|
coupon = db.query(Coupon).filter(Coupon.code == clean_code).first()
|
|
|
|
if not coupon:
|
|
return {"valid": False, "error": f"Coupon code '{clean_code}' is invalid."}
|
|
|
|
# 1. Active status check
|
|
if not coupon.is_active:
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' is currently inactive."}
|
|
|
|
# 2. Validity date range check
|
|
now = datetime.now()
|
|
if now < coupon.valid_from:
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' will be active starting {coupon.valid_from.strftime('%d %b %Y')}."}
|
|
|
|
if now > coupon.valid_to:
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' expired on {coupon.valid_to.strftime('%d %b %Y')}."}
|
|
|
|
# 3. Global usage cap check
|
|
if coupon.usage_limit_total and coupon.times_used >= coupon.usage_limit_total:
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' has reached its maximum global redemptions."}
|
|
|
|
# 4. Channel scope check (ONLINE_ONLY, POS_ONLY, OMNICHANNEL)
|
|
req_channel = channel.upper()
|
|
if coupon.channel_scope == "ONLINE_ONLY" and req_channel == "POS":
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' is exclusively valid for online store orders."}
|
|
if coupon.channel_scope == "POS_ONLY" and req_channel != "POS":
|
|
return {"valid": False, "error": f"Coupon '{clean_code}' is exclusively valid for in-store walk-in counter orders."}
|
|
|
|
# 5. First-Time Customer Rule check
|
|
if coupon.first_order_only:
|
|
if not customer_id:
|
|
return {
|
|
"valid": False,
|
|
"error": "Please sign in to your customer account to redeem this first-order welcome offer."
|
|
}
|
|
|
|
completed_prior_orders = db.query(Order).filter(
|
|
Order.customer_id == customer_id,
|
|
Order.status.notin_(["CANCELLED", "PAYMENT_FAILED"])
|
|
).count()
|
|
|
|
if completed_prior_orders > 0:
|
|
return {
|
|
"valid": False,
|
|
"error": f"Coupon '{clean_code}' is exclusively for first-time customers on their very first purchase."
|
|
}
|
|
|
|
# 6. Per-Customer usage limit check
|
|
if customer_id and coupon.usage_limit_per_customer:
|
|
customer_uses = db.query(CouponUsage).filter(
|
|
CouponUsage.coupon_id == coupon.coupon_id,
|
|
CouponUsage.customer_id == customer_id
|
|
).count()
|
|
|
|
if customer_uses >= coupon.usage_limit_per_customer:
|
|
return {
|
|
"valid": False,
|
|
"error": f"You have already redeemed coupon '{clean_code}' the maximum allowed times ({coupon.usage_limit_per_customer})."
|
|
}
|
|
|
|
# 7. Minimum order amount check
|
|
min_order = float(coupon.min_order_amount or 0.0)
|
|
if subtotal < min_order:
|
|
shortfall = min_order - subtotal
|
|
return {
|
|
"valid": False,
|
|
"error": f"Add ₹{shortfall:.2f} more to your cart to use coupon '{clean_code}' (Minimum spend: ₹{min_order:.2f})."
|
|
}
|
|
|
|
# 8. Maximum order amount check (excludes wholesale / bulk from consumer coupons)
|
|
if coupon.max_order_amount and subtotal > float(coupon.max_order_amount):
|
|
return {
|
|
"valid": False,
|
|
"error": f"Cart total exceeds the maximum eligible order limit of ₹{float(coupon.max_order_amount):.2f} for this coupon."
|
|
}
|
|
|
|
# 9. Catalog Target Restrictions (Categories, Brands, Models)
|
|
cat_ids = coupon.applicable_category_ids or []
|
|
brand_ids = coupon.applicable_brand_ids or []
|
|
model_ids = coupon.applicable_model_ids or []
|
|
has_catalog_filter = bool(cat_ids or brand_ids or model_ids)
|
|
|
|
qualifying_subtotal = 0.0
|
|
if has_catalog_filter and items:
|
|
for itm in items:
|
|
v_id = itm.get("variant_id")
|
|
qty = itm.get("qty") or itm.get("quantity") or 1
|
|
price = itm.get("unit_price")
|
|
|
|
variant = db.query(ProductVariant).filter(ProductVariant.variant_id == v_id).first()
|
|
if not variant:
|
|
continue
|
|
|
|
if price is None:
|
|
price = float(variant.price)
|
|
|
|
product = variant.product
|
|
if not product:
|
|
continue
|
|
|
|
# Category filter
|
|
if cat_ids and product.category_id not in cat_ids:
|
|
continue
|
|
# Brand filter
|
|
if brand_ids and product.brand_id not in brand_ids:
|
|
continue
|
|
# Model filter
|
|
if model_ids and product.device_model_id not in model_ids:
|
|
continue
|
|
|
|
qualifying_subtotal += float(price) * int(qty)
|
|
|
|
if qualifying_subtotal <= 0:
|
|
return {
|
|
"valid": False,
|
|
"error": f"Coupon '{clean_code}' is not applicable to the specific items currently in your cart."
|
|
}
|
|
else:
|
|
qualifying_subtotal = subtotal
|
|
|
|
# 10. Compute discount amount
|
|
base_calc_amount = qualifying_subtotal if has_catalog_filter else subtotal
|
|
discount_amount = 0.0
|
|
is_free_shipping = False
|
|
|
|
if coupon.discount_type == "PERCENTAGE":
|
|
discount_amount = round(base_calc_amount * (float(coupon.discount_value) / 100.0), 2)
|
|
if coupon.max_discount_cap:
|
|
discount_amount = min(discount_amount, float(coupon.max_discount_cap))
|
|
elif coupon.discount_type == "FIXED":
|
|
discount_amount = min(float(coupon.discount_value), base_calc_amount)
|
|
elif coupon.discount_type == "FREE_SHIPPING":
|
|
discount_amount = float(shipping_cost)
|
|
is_free_shipping = True
|
|
|
|
discount_amount = round(min(discount_amount, subtotal), 2)
|
|
|
|
return {
|
|
"valid": True,
|
|
"coupon_id": coupon.coupon_id,
|
|
"code": coupon.code,
|
|
"title": coupon.title,
|
|
"discount_type": coupon.discount_type,
|
|
"discount_value": float(coupon.discount_value),
|
|
"discount_amount": discount_amount,
|
|
"is_free_shipping": is_free_shipping,
|
|
"message": f"Coupon '{coupon.code}' applied! You saved ₹{discount_amount:.2f}."
|
|
}
|
|
|
|
@staticmethod
|
|
def record_usage(
|
|
db: Session,
|
|
coupon_id: str,
|
|
customer_id: str,
|
|
order_id: str,
|
|
discount_amount: float
|
|
) -> CouponUsage:
|
|
"""
|
|
Records verified redemption and increments usage counter atomically.
|
|
"""
|
|
coupon = db.query(Coupon).filter(Coupon.coupon_id == coupon_id).with_for_update().first()
|
|
if coupon:
|
|
coupon.times_used = (coupon.times_used or 0) + 1
|
|
|
|
usage = CouponUsage(
|
|
usage_id=str(ulid.ULID()),
|
|
coupon_id=coupon_id,
|
|
customer_id=customer_id,
|
|
order_id=order_id,
|
|
discount_amount=round(discount_amount, 2),
|
|
used_at=datetime.now(timezone.utc)
|
|
)
|
|
db.add(usage)
|
|
return usage
|
|
|