from __future__ import annotations from warehouse_allocation.config import Settings from warehouse_allocation.domain.exceptions import ( CandidateLimitExceededError, NoFeasibleWarehouseError, ) from warehouse_allocation.domain.models import AllocationRequest, AllocationResponse from warehouse_allocation.domain.optimizer import rank_warehouses from warehouse_allocation.infrastructure.inventory import InventoryRepository class AllocationService: def __init__(self, inventory: InventoryRepository, settings: Settings) -> None: self._inventory = inventory self._settings = settings async def allocate(self, request: AllocationRequest) -> AllocationResponse: warehouse_ids = [item.warehouse_id for item in request.transportation_costs] if len(warehouse_ids) > self._settings.max_candidate_warehouses: limit = self._settings.max_candidate_warehouses raise CandidateLimitExceededError(f"at most {limit} candidate warehouses are allowed") required = {item.sku: item.quantity for item in request.items} feasible = await self._inventory.feasible_warehouses(warehouse_ids, required) ranked = rank_warehouses(request, feasible) if not ranked: raise NoFeasibleWarehouseError("no warehouse can fulfill the complete order") selected = ranked[0] reserved = False if request.reserve_inventory: # A concurrent order can consume the first choice after the read. Try the remaining # ranked candidates; each reservation itself is atomic in the repository. for candidate in ranked: if await self._inventory.reserve(candidate.warehouse_id, required): selected = candidate reserved = True break if not reserved: raise NoFeasibleWarehouseError( "inventory changed before reservation; no candidate can fulfill the order" ) return AllocationResponse( request_id=request.request_id, warehouse_id=selected.warehouse_id, estimated_delivery_time=round(selected.delivery_minutes), total_cost=round(selected.total_cost, 2), route_optimization_score=round(selected.score, 2), inventory_reserved=reserved, score_breakdown=selected.breakdown, )