from __future__ import annotations import json from decimal import Decimal, InvalidOperation from pathlib import Path from typing import Any from app.db.enums import BillingPeriod, PlanType from .models import AccessPlanSeed DEFAULT_PLANS_PATH = Path(__file__).with_name("plans.json") class CommerceSeedConfigError(ValueError): pass def load_access_plans(path: Path = DEFAULT_PLANS_PATH) -> tuple[AccessPlanSeed, ...]: try: payload = json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError as exc: raise CommerceSeedConfigError(f"Commerce plans file not found: {path}") from exc except json.JSONDecodeError as exc: raise CommerceSeedConfigError( f"Invalid JSON in commerce plans file {path}: {exc}" ) from exc if not isinstance(payload, dict): raise CommerceSeedConfigError("plans.json root must be a JSON object") if payload.get("version") != 1: raise CommerceSeedConfigError("plans.json version must be 1") raw_plans = payload.get("plans") if not isinstance(raw_plans, list): raise CommerceSeedConfigError("plans.json 'plans' must be an array") seen_codes: set[str] = set() plans: list[AccessPlanSeed] = [] for index, raw in enumerate(raw_plans): if not isinstance(raw, dict): raise CommerceSeedConfigError(f"plans[{index}] must be an object") code = _required_text(raw, "code", index).upper() if code in seen_codes: raise CommerceSeedConfigError(f"Duplicate plan code in plans.json: {code}") seen_codes.add(code) plan_type = _required_text(raw, "plan_type", index).lower() billing_period = _required_text(raw, "billing_period", index).lower() try: PlanType(plan_type) except ValueError as exc: raise CommerceSeedConfigError( f"plans[{index}].plan_type is invalid: {plan_type}" ) from exc try: BillingPeriod(billing_period) except ValueError as exc: raise CommerceSeedConfigError( f"plans[{index}].billing_period is invalid: {billing_period}" ) from exc modules = raw.get("modules", []) if not isinstance(modules, list): raise CommerceSeedConfigError(f"plans[{index}].modules must be an array") module_codes: list[str] = [] seen_modules: set[str] = set() for module_index, module in enumerate(modules): if not isinstance(module, dict): raise CommerceSeedConfigError( f"plans[{index}].modules[{module_index}] must be an object" ) module_code = _required_text( module, "module_code", index, prefix=f"modules[{module_index}]." ).upper() if module_code in seen_modules: raise CommerceSeedConfigError( f"Duplicate module {module_code} in plan {code}" ) seen_modules.add(module_code) module_codes.append(module_code) metadata = raw.get("metadata", {}) if not isinstance(metadata, dict): raise CommerceSeedConfigError(f"plans[{index}].metadata must be an object") plans.append( AccessPlanSeed( code=code, name=_required_text(raw, "name", index), description=_optional_text(raw.get("description")), plan_type=plan_type, billing_period=billing_period, member_fee=_decimal(raw.get("member_fee", "0.00"), index, "member_fee"), module_fee=_decimal(raw.get("module_fee", "0.00"), index, "module_fee"), currency_code=_required_text(raw, "currency_code", index).upper(), country=_required_text(raw, "country", index), trial_days=_nonnegative_int(raw.get("trial_days", 0), index, "trial_days"), is_active=_boolean(raw.get("is_active", True), index, "is_active"), sort_order=_nonnegative_int(raw.get("sort_order", 0), index, "sort_order"), metadata=dict(metadata), module_codes=tuple(module_codes), ) ) return tuple(plans) def _required_text(raw: dict[str, Any], key: str, index: int, *, prefix: str = "") -> str: value = raw.get(key) if not isinstance(value, str) or not value.strip(): raise CommerceSeedConfigError(f"plans[{index}].{prefix}{key} is required") return value.strip() def _optional_text(value: Any) -> str | None: if value is None: return None if not isinstance(value, str): raise CommerceSeedConfigError("description must be a string or null") value = value.strip() return value or None def _decimal(value: Any, index: int, key: str) -> Decimal: try: result = Decimal(str(value)) except (InvalidOperation, ValueError) as exc: raise CommerceSeedConfigError(f"plans[{index}].{key} must be numeric") from exc if result < 0: raise CommerceSeedConfigError(f"plans[{index}].{key} must be >= 0") return result def _nonnegative_int(value: Any, index: int, key: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise CommerceSeedConfigError(f"plans[{index}].{key} must be an integer >= 0") return value def _boolean(value: Any, index: int, key: str) -> bool: if not isinstance(value, bool): raise CommerceSeedConfigError(f"plans[{index}].{key} must be boolean") return value