This commit is contained in:
Meghdad committed 2026-07-23 06:40:30 +03:30
1 parent 26d41cd03f
commit db57e0e4a2
30 files changed
+1757

No files matched your search

@@ -0,0 +1 @@
"""Domain models and allocation logic."""
@@ -0,0 +1,14 @@
class AllocationError(Exception):
"""Base class for expected allocation failures."""
class NoFeasibleWarehouseError(AllocationError):
"""No candidate can fulfill every item in the order."""
class InventoryUnavailableError(AllocationError):
"""Inventory storage could not be reached within its latency budget."""
class CandidateLimitExceededError(AllocationError):
"""The request would exceed the configured latency guardrail."""
+137
View File
@@ -0,0 +1,137 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
Sku = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)]
WarehouseId = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)]
def to_camel(value: str) -> str:
head, *tail = value.split("_")
return head + "".join(word.capitalize() for word in tail)
class ApiModel(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True,
extra="forbid",
str_strip_whitespace=True,
)
class CustomerLocation(ApiModel):
latitude: float = Field(ge=-90, le=90)
longitude: float = Field(ge=-180, le=180)
class OrderItem(ApiModel):
sku: Sku
quantity: int = Field(gt=0, le=100_000)
class TransportationCost(ApiModel):
warehouse_id: WarehouseId
fixed_cost: float = Field(ge=0)
distance_km: float = Field(ge=0)
cost_per_km: float = Field(default=0, ge=0)
base_delivery_minutes: float = Field(gt=0, le=43_200)
surcharge: float = Field(default=0, ge=0)
class LogisticsConstraint(ApiModel):
warehouse_id: WarehouseId
traffic_multiplier: float = Field(default=1, ge=0.1, le=10)
fleet_priority: float = Field(
default=1,
ge=0.1,
le=5,
description="Values above one represent preferred/faster fleet capacity.",
)
handling_minutes: float = Field(default=0, ge=0, le=1_440)
available: bool = True
class OptimizationWeights(ApiModel):
cost: float = Field(default=0.7, ge=0, le=1)
delivery_time: float = Field(default=0.3, ge=0, le=1)
@model_validator(mode="after")
def weights_must_sum_to_one(self) -> OptimizationWeights:
if abs((self.cost + self.delivery_time) - 1) > 1e-6:
raise ValueError("cost and deliveryTime weights must sum to 1")
return self
class AllocationRequest(ApiModel):
request_id: Annotated[str, StringConstraints(min_length=1, max_length=128)]
customer_location: CustomerLocation
items: list[OrderItem] = Field(min_length=1, max_length=100)
transportation_costs: list[TransportationCost] = Field(min_length=1, max_length=500)
logistics_constraints: list[LogisticsConstraint] = Field(default_factory=list, max_length=500)
weights: OptimizationWeights = Field(default_factory=OptimizationWeights)
promised_delivery_minutes: float | None = Field(default=None, gt=0, le=43_200)
reserve_inventory: bool = False
@model_validator(mode="after")
def identifiers_must_be_unique(self) -> AllocationRequest:
skus = [item.sku for item in self.items]
if len(skus) != len(set(skus)):
raise ValueError("items must contain unique SKUs")
warehouse_ids = [cost.warehouse_id for cost in self.transportation_costs]
if len(warehouse_ids) != len(set(warehouse_ids)):
raise ValueError("transportationCosts must contain unique warehouse IDs")
constraint_ids = [constraint.warehouse_id for constraint in self.logistics_constraints]
if len(constraint_ids) != len(set(constraint_ids)):
raise ValueError("logisticsConstraints must contain unique warehouse IDs")
unknown = set(constraint_ids) - set(warehouse_ids)
if unknown:
raise ValueError(f"constraints reference unknown warehouses: {sorted(unknown)}")
return self
class ScoreBreakdown(ApiModel):
transport_cost: float
normalized_cost: float
normalized_delivery_time: float
sla_penalty: float
feasible_warehouse_count: int
class AllocationResponse(ApiModel):
request_id: str
warehouse_id: str
estimated_delivery_time: int
total_cost: float
route_optimization_score: float
inventory_reserved: bool
score_breakdown: ScoreBreakdown
calculated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class InventoryLevel(ApiModel):
sku: Sku
quantity: int = Field(ge=0, le=2_147_483_647)
class InventoryUpsertRequest(ApiModel):
warehouse_id: WarehouseId
levels: list[InventoryLevel] = Field(min_length=1, max_length=10_000)
class HealthResponse(ApiModel):
status: str
service: str
inventory: str | None = None
class ErrorDetail(ApiModel):
code: str
message: str
class ErrorResponse(ApiModel):
error: ErrorDetail
@@ -0,0 +1,106 @@
from __future__ import annotations
from dataclasses import dataclass
from warehouse_allocation.domain.models import (
AllocationRequest,
LogisticsConstraint,
ScoreBreakdown,
TransportationCost,
)
@dataclass(frozen=True, slots=True)
class RankedWarehouse:
warehouse_id: str
delivery_minutes: float
total_cost: float
objective: float
score: float
breakdown: ScoreBreakdown
def _min_max(value: float, values: list[float]) -> float:
low, high = min(values), max(values)
if high == low:
return 0.0
return (value - low) / (high - low)
def _effective_values(
cost: TransportationCost, constraint: LogisticsConstraint
) -> tuple[float, float]:
raw_cost = cost.fixed_cost + (cost.distance_km * cost.cost_per_km) + cost.surcharge
# Congestion consumes fuel/driver time, while preferred fleet capacity lowers that overhead.
congestion_cost_factor = 1 + max(0.0, constraint.traffic_multiplier - 1) * 0.15
total_cost = raw_cost * congestion_cost_factor / constraint.fleet_priority
delivery_minutes = (
cost.base_delivery_minutes * constraint.traffic_multiplier + constraint.handling_minutes
) / constraint.fleet_priority
return total_cost, delivery_minutes
def rank_warehouses(request: AllocationRequest, feasible_ids: set[str]) -> list[RankedWarehouse]:
constraints = {item.warehouse_id: item for item in request.logistics_constraints}
candidates: list[tuple[str, float, float]] = []
for cost in request.transportation_costs:
constraint = constraints.get(cost.warehouse_id) or LogisticsConstraint(
warehouse_id=cost.warehouse_id
)
if cost.warehouse_id not in feasible_ids or not constraint.available:
continue
total_cost, delivery_minutes = _effective_values(cost, constraint)
candidates.append((cost.warehouse_id, total_cost, delivery_minutes))
if not candidates:
return []
costs = [candidate[1] for candidate in candidates]
delivery_times = [candidate[2] for candidate in candidates]
ranked: list[RankedWarehouse] = []
for warehouse_id, total_cost, delivery_minutes in candidates:
normalized_cost = _min_max(total_cost, costs)
normalized_time = _min_max(delivery_minutes, delivery_times)
sla_penalty = 0.0
if (
request.promised_delivery_minutes
and delivery_minutes > request.promised_delivery_minutes
):
overrun_ratio = (
delivery_minutes - request.promised_delivery_minutes
) / request.promised_delivery_minutes
sla_penalty = min(0.25, overrun_ratio * 0.25)
objective = min(
1.0,
request.weights.cost * normalized_cost
+ request.weights.delivery_time * normalized_time
+ sla_penalty,
)
ranked.append(
RankedWarehouse(
warehouse_id=warehouse_id,
delivery_minutes=delivery_minutes,
total_cost=total_cost,
objective=objective,
score=(1 - objective) * 100,
breakdown=ScoreBreakdown(
transport_cost=round(total_cost, 2),
normalized_cost=round(normalized_cost, 6),
normalized_delivery_time=round(normalized_time, 6),
sla_penalty=round(sla_penalty, 6),
feasible_warehouse_count=len(candidates),
),
)
)
return sorted(
ranked,
key=lambda candidate: (
candidate.objective,
candidate.total_cost,
candidate.delivery_minutes,
candidate.warehouse_id,
),
)