57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from collections.abc import Iterable
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from .loader import DEFAULT_PLANS_PATH, load_access_plans
|
|
from .models import AccessPlanSeed, CouponSeed
|
|
from .repository import CommerceSeedRepository
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class CommerceBootstrapResult:
|
|
plans: int
|
|
plan_module_mappings: int
|
|
coupons: int
|
|
|
|
|
|
class CommerceBootstrapSeeder:
|
|
"""Idempotent, configuration-driven commerce bootstrap."""
|
|
|
|
def __init__(self, session: AsyncSession) -> None:
|
|
self.session = session
|
|
self.repo = CommerceSeedRepository(session)
|
|
|
|
async def seed(
|
|
self,
|
|
*,
|
|
plans_path: Path = DEFAULT_PLANS_PATH,
|
|
plans: Iterable[AccessPlanSeed] | None = None,
|
|
coupons: Iterable[CouponSeed] = (),
|
|
) -> CommerceBootstrapResult:
|
|
resolved_plans = tuple(plans) if plans is not None else load_access_plans(plans_path)
|
|
|
|
plan_count = 0
|
|
mapping_count = 0
|
|
for seed in resolved_plans:
|
|
plan = await self.repo.upsert_plan(seed)
|
|
mapping_count += await self.repo.reconcile_plan_modules(
|
|
plan=plan,
|
|
module_codes=seed.module_codes,
|
|
)
|
|
plan_count += 1
|
|
|
|
coupon_count = 0
|
|
for seed in coupons:
|
|
await self.repo.upsert_coupon(seed)
|
|
coupon_count += 1
|
|
|
|
return CommerceBootstrapResult(
|
|
plans=plan_count,
|
|
plan_module_mappings=mapping_count,
|
|
coupons=coupon_count,
|
|
)
|