192 lines
8.5 KiB
Python
192 lines
8.5 KiB
Python
from __future__ import annotations
|
|
from datetime import datetime, timedelta, timezone
|
|
from decimal import Decimal
|
|
from uuid import UUID
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from app.db.models import AccessPlan, AppUser, Coupon, Module
|
|
from ..schema import CreateCouponRequest, UpdateCouponRequest
|
|
|
|
|
|
def _parse_iso_datetime(value: str | datetime | None, default: datetime | None = None) -> datetime | None:
|
|
if value is None:
|
|
return default
|
|
if isinstance(value, datetime):
|
|
dt = value
|
|
else:
|
|
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
|
|
|
|
|
|
class AdminCouponService:
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
|
|
async def list_coupons(self) -> list[dict]:
|
|
coupons = (await self.session.execute(
|
|
select(Coupon).order_by(Coupon.created_at.desc())
|
|
)).scalars().all()
|
|
|
|
plans_q = await self.session.execute(select(AccessPlan))
|
|
all_plans = {str(p.id): (p.name or p.code) for p in plans_q.scalars().all()}
|
|
|
|
mods_q = await self.session.execute(select(Module))
|
|
all_mods = {str(m.id): m.name for m in mods_q.scalars().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
|
|
|
|
if not c.is_active:
|
|
status = "inactive"
|
|
elif now < s_date:
|
|
status = "scheduled"
|
|
elif now > e_date:
|
|
status = "expired"
|
|
else:
|
|
status = "active"
|
|
|
|
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
|
|
module_names = [all_mods.get(str(mid), str(mid)[:8]) for mid in (c.applicable_module_ids or [])]
|
|
|
|
result.append({
|
|
"id": str(c.id),
|
|
"code": c.code,
|
|
"discount_type": c.discount_type,
|
|
"coupon_category": c.coupon_category,
|
|
"value": float(c.value),
|
|
"max_discount_limit": float(c.max_discount_limit or 0.0),
|
|
"start_date": s_date.isoformat(),
|
|
"end_date": e_date.isoformat(),
|
|
"usage_limit": c.usage_limit,
|
|
"usage_count": c.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,
|
|
"description": c.description or "",
|
|
"schedule_status": status,
|
|
"applicable_plan_ids": [str(pid) for pid in (c.applicable_plan_ids or [])],
|
|
"applicable_module_ids": [str(mid) for mid in (c.applicable_module_ids or [])],
|
|
"plan_names": plan_names,
|
|
"module_names": module_names,
|
|
"created_at": c.created_at.isoformat() if c.created_at else None,
|
|
})
|
|
return result
|
|
|
|
async def create_coupon(self, payload: CreateCouponRequest, admin: AppUser) -> dict:
|
|
code = payload.code.strip().upper()
|
|
if not code:
|
|
raise ValueError("Coupon code cannot be empty.")
|
|
if (await self.session.execute(select(Coupon.id).where(Coupon.code == code))).scalar_one_or_none():
|
|
raise ValueError(f"Coupon code '{code}' already exists.")
|
|
|
|
now = datetime.now(timezone.utc)
|
|
start = _parse_iso_datetime(payload.start_date, default=now)
|
|
end = _parse_iso_datetime(payload.end_date, default=(now + timedelta(days=30)))
|
|
|
|
if end <= start:
|
|
raise ValueError("Invalid date range: End date must be later than start date.")
|
|
|
|
plan_uuids = [UUID(pid) for pid in payload.applicable_plan_ids] if payload.applicable_plan_ids else None
|
|
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
|
|
|
|
coupon = Coupon(
|
|
code=code,
|
|
discount_type=payload.discount_type,
|
|
coupon_category=payload.coupon_category,
|
|
value=Decimal(str(payload.value)),
|
|
max_discount_limit=Decimal(str(payload.max_discount_limit or 0)),
|
|
start_date=start,
|
|
end_date=end,
|
|
usage_limit=payload.usage_limit,
|
|
usage_count=0,
|
|
min_purchase_amount=Decimal(str(payload.min_purchase_amount or 0)),
|
|
is_first_purchase_only=payload.is_first_purchase_only,
|
|
applicable_plan_ids=plan_uuids,
|
|
applicable_module_ids=module_uuids,
|
|
is_active=payload.is_active,
|
|
description=payload.description,
|
|
)
|
|
self.session.add(coupon)
|
|
await self.session.commit()
|
|
await self.session.refresh(coupon)
|
|
return {"status": "success", "message": f"Coupon '{coupon.code}' created successfully.", "coupon_id": str(coupon.id)}
|
|
|
|
async def update_coupon(self, coupon_id: str, payload: UpdateCouponRequest) -> dict:
|
|
try:
|
|
cid = UUID(coupon_id)
|
|
except ValueError:
|
|
raise ValueError("Invalid coupon UUID.")
|
|
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
|
if not coupon:
|
|
raise LookupError("Coupon not found.")
|
|
|
|
new_start = _parse_iso_datetime(payload.start_date, default=coupon.start_date)
|
|
new_end = _parse_iso_datetime(payload.end_date, default=coupon.end_date)
|
|
if new_start is not None and new_end is not None:
|
|
if new_end <= new_start:
|
|
raise ValueError("Invalid date range: End date must be later than start date.")
|
|
|
|
if payload.discount_type is not None:
|
|
coupon.discount_type = payload.discount_type
|
|
if payload.coupon_category is not None:
|
|
coupon.coupon_category = payload.coupon_category
|
|
if payload.value is not None:
|
|
coupon.value = Decimal(str(payload.value))
|
|
if payload.max_discount_limit is not None:
|
|
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
|
if payload.start_date is not None:
|
|
coupon.start_date = new_start
|
|
if payload.end_date is not None:
|
|
coupon.end_date = new_end
|
|
if payload.usage_limit is not None:
|
|
coupon.usage_limit = payload.usage_limit
|
|
if payload.min_purchase_amount is not None:
|
|
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
|
if payload.is_first_purchase_only is not None:
|
|
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
|
if payload.applicable_plan_ids is not None:
|
|
coupon.applicable_plan_ids = [UUID(pid) for pid in payload.applicable_plan_ids]
|
|
if payload.applicable_module_ids is not None:
|
|
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
|
if payload.is_active is not None:
|
|
coupon.is_active = payload.is_active
|
|
if payload.description is not None:
|
|
coupon.description = payload.description
|
|
|
|
await self.session.commit()
|
|
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
|
|
|
async def toggle_status(self, coupon_id: str, is_active: bool) -> dict:
|
|
try:
|
|
cid = UUID(coupon_id)
|
|
except ValueError:
|
|
raise ValueError("Invalid coupon UUID.")
|
|
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
|
if not coupon:
|
|
raise LookupError("Coupon not found.")
|
|
|
|
coupon.is_active = is_active
|
|
await self.session.commit()
|
|
return {
|
|
"status": "success",
|
|
"message": f"Coupon '{coupon.code}' status toggled to {'Active' if is_active else 'Inactive'}.",
|
|
"is_active": is_active,
|
|
}
|
|
|
|
async def delete_coupon(self, coupon_id: str) -> dict:
|
|
try:
|
|
cid = UUID(coupon_id)
|
|
except ValueError:
|
|
raise ValueError("Invalid coupon UUID.")
|
|
coupon = (await self.session.execute(select(Coupon).where(Coupon.id == cid))).scalar_one_or_none()
|
|
if not coupon:
|
|
raise LookupError("Coupon not found.")
|
|
|
|
code = coupon.code
|
|
await self.session.delete(coupon)
|
|
await self.session.commit()
|
|
return {"status": "success", "message": f"Coupon '{code}' deleted successfully."}
|