From a353b80a15d5bec8b807242c96ee7c0849346b4e Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 23 Jul 2026 07:40:44 +0330 Subject: [PATCH] add demo data for Swagger --- README.md | 4 ++ src/warehouse_allocation/api.py | 31 +++++++++- src/warehouse_allocation/api_examples.py | 76 ++++++++++++++++++++++++ tests/integration/test_api.py | 23 +++++++ 4 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 src/warehouse_allocation/api_examples.py diff --git a/README.md b/README.md index 59f6f61..6e22527 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ docker compose up --build پس از healthy شدن سرویس، مستندات تعاملی در `http://localhost:8080/docs` و متریک‌ها در `http://localhost:8080/metrics` در دسترس‌اند. +در استقرار عمومی، نمونه `Runnable demo quote` داخل Swagger با موجودی نمایشی +هماهنگ شده و `reserveInventory: false` دارد؛ بنابراین می‌توان آن را چند بار بدون +کاهش موجودی اجرا کرد. + ابتدا موجودی projection را ثبت کنید: ```bash diff --git a/src/warehouse_allocation/api.py b/src/warehouse_allocation/api.py index 93b21d1..e510dab 100644 --- a/src/warehouse_allocation/api.py +++ b/src/warehouse_allocation/api.py @@ -4,12 +4,16 @@ from collections.abc import AsyncIterator from contextlib import asynccontextmanager from typing import Annotated, cast -from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status +from fastapi import Body, Depends, FastAPI, Header, HTTPException, Request, Response, status from fastapi.responses import JSONResponse from prometheus_client import CONTENT_TYPE_LATEST, generate_latest from redis.asyncio import Redis from starlette.middleware.base import RequestResponseEndpoint +from warehouse_allocation.api_examples import ( + DEMO_ALLOCATION_REQUEST, + DEMO_ALLOCATION_RESPONSE, +) from warehouse_allocation.application import AllocationService from warehouse_allocation.config import Settings, get_settings from warehouse_allocation.domain.exceptions import ( @@ -122,13 +126,36 @@ def create_app( "/v1/allocations", response_model=AllocationResponse, responses={ + 200: { + "description": "Warehouse selected successfully.", + "content": { + "application/json": { + "example": DEMO_ALLOCATION_RESPONSE, + } + }, + }, 400: {"model": ErrorResponse}, 409: {"model": ErrorResponse}, 503: {"model": ErrorResponse}, }, ) async def allocate( - payload: AllocationRequest, + payload: Annotated[ + AllocationRequest, + Body( + openapi_examples={ + "demoQuote": { + "summary": "Runnable demo quote", + "description": ( + "Uses inventory pre-seeded in the public demo. " + "It does not reserve or decrement stock, " + "so it is safe to run repeatedly." + ), + "value": DEMO_ALLOCATION_REQUEST, + } + } + ), + ], service: Annotated[AllocationService, Depends(get_service)], ) -> AllocationResponse: started = time.perf_counter() diff --git a/src/warehouse_allocation/api_examples.py b/src/warehouse_allocation/api_examples.py new file mode 100644 index 0000000..7b1d779 --- /dev/null +++ b/src/warehouse_allocation/api_examples.py @@ -0,0 +1,76 @@ +from typing import Final + +DEMO_SKU: Final = "DEMO-SKU-001" +DEMO_WAREHOUSE_IDS: Final = ("demo-tehran", "demo-karaj") + +DEMO_ALLOCATION_REQUEST: Final[dict[str, object]] = { + "requestId": "swagger-demo-quote", + "customerLocation": { + "latitude": 35.7219, + "longitude": 51.3347, + }, + "items": [ + { + "sku": DEMO_SKU, + "quantity": 1, + } + ], + "transportationCosts": [ + { + "warehouseId": "demo-tehran", + "fixedCost": 180000, + "distanceKm": 12, + "costPerKm": 3500, + "baseDeliveryMinutes": 55, + "surcharge": 0, + }, + { + "warehouseId": "demo-karaj", + "fixedCost": 60000, + "distanceKm": 48, + "costPerKm": 2500, + "baseDeliveryMinutes": 105, + "surcharge": 0, + }, + ], + "logisticsConstraints": [ + { + "warehouseId": "demo-tehran", + "trafficMultiplier": 1.25, + "fleetPriority": 1.1, + "handlingMinutes": 8, + "available": True, + }, + { + "warehouseId": "demo-karaj", + "trafficMultiplier": 1.05, + "fleetPriority": 1, + "handlingMinutes": 12, + "available": True, + }, + ], + "weights": { + "cost": 0.7, + "deliveryTime": 0.3, + }, + "promisedDeliveryMinutes": 180, + # A Swagger demo should remain repeatable and must not consume shared stock. + "reserveInventory": False, +} + +DEMO_ALLOCATION_RESPONSE: Final[dict[str, object]] = { + "requestId": "swagger-demo-quote", + "warehouseId": "demo-karaj", + "estimatedDeliveryTime": 122, + "totalCost": 181350, + "routeOptimizationScore": 70, + "inventoryReserved": False, + "scoreBreakdown": { + "transportCost": 181350, + "normalizedCost": 0, + "normalizedDeliveryTime": 1, + "slaPenalty": 0, + "feasibleWarehouseCount": 2, + }, + "calculatedAt": "2026-07-23T04:00:00Z", +} diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py index 35cda88..72c4843 100644 --- a/tests/integration/test_api.py +++ b/tests/integration/test_api.py @@ -1,5 +1,6 @@ import httpx +from warehouse_allocation.api_examples import DEMO_SKU, DEMO_WAREHOUSE_IDS from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository @@ -83,3 +84,25 @@ async def test_validation_error_is_structured( assert response.status_code == 422 assert response.json()["detail"] + + +async def test_openapi_demo_example_is_runnable_and_non_reserving( + client: httpx.AsyncClient, + inventory: InMemoryInventoryRepository, +) -> None: + for warehouse_id in DEMO_WAREHOUSE_IDS: + await inventory.set_levels(warehouse_id, {DEMO_SKU: 10}) + + openapi = (await client.get("/openapi.json")).json() + media_type = openapi["paths"]["/v1/allocations"]["post"]["requestBody"]["content"][ + "application/json" + ] + example = media_type["examples"]["demoQuote"]["value"] + + first = await client.post("/v1/allocations", json=example) + second = await client.post("/v1/allocations", json=example) + + assert first.status_code == 200 + assert second.status_code == 200 + assert first.json()["inventoryReserved"] is False + assert first.json()["warehouseId"] in DEMO_WAREHOUSE_IDS