28 lines
1.7 KiB
Python
28 lines
1.7 KiB
Python
from __future__ import annotations
|
|
from uuid import UUID
|
|
from app.features.payments.pricing import PricingEngine
|
|
from .repository import CartRepository
|
|
from .schema import CartCalculationRequest, CartCalculationResponse
|
|
|
|
class CartService:
|
|
def __init__(self, repository: CartRepository) -> None:
|
|
self.repository = repository
|
|
self.engine = PricingEngine()
|
|
|
|
async def calculate(self, request: CartCalculationRequest, user_id: UUID | None = None) -> CartCalculationResponse:
|
|
currency = request.currency.upper()
|
|
renewable_codes = await self.repository.get_renewable_plan_codes(user_id) if user_id else set()
|
|
items = await self.repository.get_items(request.cart_item_codes, currency, renewable_codes=renewable_codes)
|
|
if len(items) != len({c.strip().upper() for c in request.cart_item_codes if c.strip()}):
|
|
resolved = {i.code.upper() for i in items}
|
|
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)}")
|
|
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 []
|
|
if request.owned_category_names:
|
|
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
|
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
|
|
if owned:
|
|
first = False
|
|
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))
|