import httpx from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository async def seed(repository: InMemoryInventoryRepository) -> None: await repository.set_levels("tehran-west", {"SKU-RED-42": 10}) await repository.set_levels("karaj", {"SKU-RED-42": 10}) async def test_allocation_contract_and_selection( client: httpx.AsyncClient, inventory: InMemoryInventoryRepository, allocation_payload: dict[str, object], ) -> None: await seed(inventory) response = await client.post("/v1/allocations", json=allocation_payload) assert response.status_code == 200, response.text assert response.headers["x-process-time-ms"] body = response.json() assert body["requestId"] == "order-1001" assert body["warehouseId"] == "tehran-west" assert body["estimatedDeliveryTime"] == 75 assert body["totalCost"] == 116.11 assert 0 <= body["routeOptimizationScore"] <= 100 assert body["scoreBreakdown"]["feasibleWarehouseCount"] == 2 async def test_reservation_decrements_inventory( client: httpx.AsyncClient, inventory: InMemoryInventoryRepository, allocation_payload: dict[str, object], ) -> None: await inventory.set_levels("tehran-west", {"SKU-RED-42": 2}) await inventory.set_levels("karaj", {"SKU-RED-42": 0}) allocation_payload["reserveInventory"] = True first = await client.post("/v1/allocations", json=allocation_payload) second = await client.post("/v1/allocations", json=allocation_payload) assert first.status_code == 200, first.text assert first.json()["inventoryReserved"] is True assert second.status_code == 409 assert second.json()["error"]["code"] == "NO_FEASIBLE_WAREHOUSE" async def test_no_single_warehouse_can_split_fulfillment( client: httpx.AsyncClient, inventory: InMemoryInventoryRepository, allocation_payload: dict[str, object], ) -> None: await inventory.set_levels("tehran-west", {"SKU-RED-42": 1}) await inventory.set_levels("karaj", {"SKU-RED-42": 1}) response = await client.post("/v1/allocations", json=allocation_payload) assert response.status_code == 409 async def test_inventory_upsert_and_health_endpoints(client: httpx.AsyncClient) -> None: upsert = await client.put( "/v1/inventory", json={"warehouseId": "w1", "levels": [{"sku": "A", "quantity": 5}]}, ) live = await client.get("/health/live") ready = await client.get("/health/ready") metrics = await client.get("/metrics") assert upsert.status_code == 204, upsert.text assert live.json()["status"] == "ok" assert ready.json()["inventory"] == "ok" assert "warehouse_allocation_requests_total" in metrics.text async def test_validation_error_is_structured( client: httpx.AsyncClient, allocation_payload: dict[str, object] ) -> None: allocation_payload["customerLocation"] = {"latitude": 200, "longitude": 51} response = await client.post("/v1/allocations", json=allocation_payload) assert response.status_code == 422 assert response.json()["detail"]