fix(coupons): validate coupon date range before database commit #26
|
|
@ -8,6 +8,16 @@ 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
|
||||
|
|
@ -73,8 +83,11 @@ class AdminCouponService:
|
|||
raise ValueError(f"Coupon code '{code}' already exists.")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
start = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00")) if payload.start_date else now
|
||||
end = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00")) if payload.end_date else (now + timedelta(days=30))
|
||||
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
|
||||
|
|
@ -110,6 +123,12 @@ class AdminCouponService:
|
|||
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:
|
||||
|
|
@ -119,9 +138,9 @@ class AdminCouponService:
|
|||
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 = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00"))
|
||||
coupon.start_date = new_start
|
||||
if payload.end_date is not None:
|
||||
coupon.end_date = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00"))
|
||||
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:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,102 @@
|
|||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from uuid import uuid4
|
||||
from datetime import datetime, timezone
|
||||
from app.features.admin.services.coupon_service import AdminCouponService
|
||||
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
|
||||
from app.db.models import AppUser, Coupon
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_coupon_invalid_date_range():
|
||||
session = AsyncMock()
|
||||
exec_result = MagicMock()
|
||||
exec_result.scalar_one_or_none.return_value = None
|
||||
session.execute.return_value = exec_result
|
||||
|
||||
service = AdminCouponService(session)
|
||||
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||
|
||||
# Start date later than end date
|
||||
payload = CreateCouponRequest(
|
||||
code="TESTCODE",
|
||||
discount_type="percentage",
|
||||
value=10.0,
|
||||
start_date="2026-12-31T00:00:00Z",
|
||||
end_date="2026-12-01T00:00:00Z",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
|
||||
await service.create_coupon(payload, admin)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_coupon_equal_start_and_end_date():
|
||||
session = AsyncMock()
|
||||
exec_result = MagicMock()
|
||||
exec_result.scalar_one_or_none.return_value = None
|
||||
session.execute.return_value = exec_result
|
||||
|
||||
service = AdminCouponService(session)
|
||||
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||
|
||||
# Start date equal to end date
|
||||
payload = CreateCouponRequest(
|
||||
code="TESTEQUAL",
|
||||
discount_type="percentage",
|
||||
value=10.0,
|
||||
start_date="2026-12-01T00:00:00Z",
|
||||
end_date="2026-12-01T00:00:00Z",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
|
||||
await service.create_coupon(payload, admin)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_coupon_invalid_date_range():
|
||||
coupon_id = uuid4()
|
||||
mock_coupon = MagicMock(spec=Coupon)
|
||||
mock_coupon.id = coupon_id
|
||||
mock_coupon.code = "TESTUP"
|
||||
mock_coupon.start_date = datetime(2026, 12, 10, tzinfo=timezone.utc)
|
||||
mock_coupon.end_date = datetime(2026, 12, 20, tzinfo=timezone.utc)
|
||||
|
||||
session = AsyncMock()
|
||||
exec_result = MagicMock()
|
||||
exec_result.scalar_one_or_none.return_value = mock_coupon
|
||||
session.execute.return_value = exec_result
|
||||
|
||||
service = AdminCouponService(session)
|
||||
|
||||
# Update end_date to be before start_date
|
||||
payload = UpdateCouponRequest(
|
||||
end_date="2026-12-05T00:00:00Z",
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
|
||||
await service.update_coupon(str(coupon_id), payload)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_coupon_valid_date_range():
|
||||
session = AsyncMock()
|
||||
exec_result = MagicMock()
|
||||
exec_result.scalar_one_or_none.return_value = None
|
||||
session.execute.return_value = exec_result
|
||||
|
||||
service = AdminCouponService(session)
|
||||
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
|
||||
|
||||
payload = CreateCouponRequest(
|
||||
code="TESTVALID",
|
||||
discount_type="percentage",
|
||||
value=10.0,
|
||||
start_date="2026-12-01T00:00:00Z",
|
||||
end_date="2026-12-31T00:00:00Z",
|
||||
)
|
||||
|
||||
result = await service.create_coupon(payload, admin)
|
||||
assert result["status"] == "success"
|
||||
session.add.assert_called_once()
|
||||
session.commit.assert_called_once()
|
||||
Loading…
Reference in New Issue