acupedia-api/app/features/payments/pricing.py

79 lines
3.3 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
from typing import Any
def q(value: Decimal) -> Decimal:
return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
@dataclass(frozen=True)
class PricingItem:
code: str
name: str
category: str
price: Decimal
is_renewal: bool = False
@dataclass(frozen=True)
class PricingCoupon:
code: str
category: str
discount_type: str
value: Decimal
description: str | None = None
max_discount_limit: Decimal = Decimal("0")
min_purchase_amount: Decimal = Decimal("0")
class PricingEngine:
"""Calculates checkout totals with Policy 5.1 Early Renewal Discount (20%) and coupon discounts."""
def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool, coupon_error: str | None = None) -> dict[str, Any]:
curr = currency.upper()
base = sum((item.price for item in items), Decimal("0"))
# Policy 5.1: 20% Early Renewal Discount for modules renewed within validity
renewal_discount = sum(
(q(item.price * Decimal("0.20")) for item in items if item.is_renewal),
Decimal("0")
)
bundle = Decimal("0")
policy = "Early Renewal (20% Off)" if renewal_discount > Decimal("0") else "None"
after_renewal = max(Decimal("0"), base - renewal_discount)
coupon_discount = Decimal("0")
coupon_text = "None"
if coupon:
if coupon.min_purchase_amount > 0 and after_renewal < coupon.min_purchase_amount:
coupon_error = f"Minimum cart spend of {curr} {coupon.min_purchase_amount} required to use coupon {coupon.code}."
coupon_text = "None"
coupon_discount = Decimal("0")
else:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type in {"flat", "flat_amount"}:
coupon_discount = min(coupon.value, after_renewal)
elif coupon.discount_type in {"percentage", "percent"}:
coupon_discount = after_renewal * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
net = max(Decimal("0"), after_renewal - coupon_discount)
grand = q(net)
return {
"currency": curr,
"base_subtotal": float(q(base)),
"discount_policy": policy,
"bundle_discount_amount": float(q(bundle)),
"renewal_discount_amount": float(q(renewal_discount)),
"coupon_applied": coupon_text,
"coupon_discount_amount": float(q(coupon_discount)),
"coupon_error": coupon_error,
"total_discounts": float(q(renewal_discount + coupon_discount)),
"convenience_fee_rate": 0.0,
"convenience_fee": 0.0,
"taxable_amount": 0.0,
"gst_amount": 0.0,
"grand_total": float(grand),
"cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price)), "is_renewal": i.is_renewal} for i in items],
}