020 update city code resolving
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
from app.schemas.request import DeliveryRequest
|
||||
from app.schemas.request import DeliveryCalculationRequest
|
||||
from app.schemas.response import DeliveryPrice
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@ class DeliveryProvider(ABC):
|
||||
name: str
|
||||
|
||||
@abstractmethod
|
||||
async def get_prices(self, request: DeliveryRequest) -> list[DeliveryPrice]:
|
||||
async def get_prices(
|
||||
self, request: DeliveryCalculationRequest
|
||||
) -> list[DeliveryPrice]:
|
||||
"""Fetch provider tariffs for a delivery request."""
|
||||
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -15,9 +15,10 @@ from app.adapters.delivery_providers.cdek.order_mapper import (
|
||||
map_cdek_order_request,
|
||||
map_cdek_order_response,
|
||||
)
|
||||
from app.cities import cities_map
|
||||
from app.config import AdapterConfig
|
||||
from app.schemas.order import OrderCreateRequest, OrderCreateResponse
|
||||
from app.schemas.request import DeliveryRequest
|
||||
from app.schemas.request import DeliveryCalculationRequest
|
||||
from app.schemas.response import DeliveryPrice
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -45,16 +46,16 @@ class CDEKClient:
|
||||
self._http_client = http_client
|
||||
self._auth_client = auth_client
|
||||
normalized_base_url = base_url.rstrip("/")
|
||||
self._city_lookup_url = f"{normalized_base_url}/location/suggest/cities"
|
||||
self._tariff_url = f"{normalized_base_url}/calculator/tarifflist"
|
||||
self._orders_url = f"{normalized_base_url}/orders"
|
||||
self._timeout_seconds = timeout_seconds
|
||||
self._retry_attempts = retry_attempts
|
||||
self._retry_backoff_seconds = retry_backoff_seconds
|
||||
self._sleep = sleep
|
||||
self._city_code_cache: dict[str, int] = {}
|
||||
|
||||
async def get_raw_price(self, request: DeliveryRequest) -> dict[str, Any]:
|
||||
async def get_raw_price(
|
||||
self, request: DeliveryCalculationRequest
|
||||
) -> dict[str, Any]:
|
||||
payload = await self._build_payload(request)
|
||||
for attempt in range(self._retry_attempts + 1):
|
||||
try:
|
||||
@@ -89,7 +90,6 @@ class CDEKClient:
|
||||
|
||||
if not isinstance(raw_payload, dict):
|
||||
raise CDEKClientError("CDEK tariff payload must be a JSON object.")
|
||||
log.info(f"Founded {len(response.json())} tarrifs")
|
||||
return raw_payload
|
||||
|
||||
raise CDEKClientError("CDEK tariff request failed unexpectedly.")
|
||||
@@ -157,15 +157,11 @@ class CDEKClient:
|
||||
def _should_retry(status_code: int) -> bool:
|
||||
return status_code == 429 or status_code >= 500
|
||||
|
||||
async def _build_payload(self, request: DeliveryRequest) -> dict[str, Any]:
|
||||
from_city_code = await self._resolve_city_code(
|
||||
request.from_city,
|
||||
country_code=request.country_code,
|
||||
)
|
||||
to_city_code = await self._resolve_city_code(
|
||||
request.to_city,
|
||||
country_code=request.country_code,
|
||||
)
|
||||
async def _build_payload(
|
||||
self, request: DeliveryCalculationRequest
|
||||
) -> dict[str, Any]:
|
||||
from_city_code = self._get_cdek_city_code(request.from_city)
|
||||
to_city_code = self._get_cdek_city_code(request.to_city)
|
||||
return {
|
||||
"type": 2,
|
||||
"from_location": {"code": from_city_code},
|
||||
@@ -180,76 +176,32 @@ class CDEKClient:
|
||||
],
|
||||
}
|
||||
|
||||
async def _resolve_city_code(self, city: str, *, country_code: str | None) -> int:
|
||||
normalized_city = city.strip().casefold()
|
||||
normalized_country_code = (
|
||||
country_code.strip().upper() if country_code is not None else ""
|
||||
)
|
||||
cache_key = f"{normalized_country_code}:{normalized_city}"
|
||||
cached_code = self._city_code_cache.get(cache_key)
|
||||
if cached_code is not None:
|
||||
return cached_code
|
||||
|
||||
for attempt in range(self._retry_attempts + 1):
|
||||
try:
|
||||
token = await self._auth_client.get_access_token()
|
||||
params = {"name": city}
|
||||
if normalized_country_code:
|
||||
params["country_code"] = normalized_country_code
|
||||
response = await self._http_client.get(
|
||||
self._city_lookup_url,
|
||||
params=params,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=self._timeout_seconds,
|
||||
)
|
||||
log.info(f"Founded cities: {response.json()}")
|
||||
except (httpx.TimeoutException, httpx.TransportError) as exc:
|
||||
if attempt < self._retry_attempts:
|
||||
await self._sleep(self._retry_delay(attempt))
|
||||
continue
|
||||
raise CDEKClientError(
|
||||
"CDEK city lookup request failed after retry attempts."
|
||||
) from exc
|
||||
|
||||
if self._should_retry(response.status_code):
|
||||
if attempt < self._retry_attempts:
|
||||
await self._sleep(self._retry_delay(attempt))
|
||||
continue
|
||||
raise CDEKClientError(
|
||||
f"CDEK city lookup failed with status {response.status_code}."
|
||||
)
|
||||
try:
|
||||
response.raise_for_status()
|
||||
body = response.json()
|
||||
except (httpx.HTTPError, TypeError, ValueError) as exc:
|
||||
raise CDEKClientError("CDEK city lookup returned invalid payload.") from exc
|
||||
break
|
||||
else:
|
||||
raise CDEKClientError("CDEK city lookup failed unexpectedly.")
|
||||
|
||||
if isinstance(body, dict):
|
||||
first_item = body
|
||||
elif isinstance(body, list) and body:
|
||||
first_item = body[0]
|
||||
elif isinstance(body, list):
|
||||
@staticmethod
|
||||
def _get_cdek_city_code(city_id: int) -> int:
|
||||
city_entry = cities_map.get(str(city_id))
|
||||
if not isinstance(city_entry, dict):
|
||||
raise CDEKRequestError(
|
||||
f"CDEK city lookup returned no matches for '{city}'."
|
||||
f"CDEK city mapping is not configured for city id {city_id}."
|
||||
)
|
||||
|
||||
cdek_data = city_entry.get("cdek")
|
||||
if not isinstance(cdek_data, dict):
|
||||
raise CDEKRequestError(
|
||||
f"CDEK city mapping is not configured for city id {city_id}."
|
||||
)
|
||||
|
||||
raw_city_code = cdek_data.get("code")
|
||||
if raw_city_code is None or isinstance(raw_city_code, bool):
|
||||
raise CDEKRequestError(
|
||||
f"CDEK city code is invalid for city id {city_id}."
|
||||
)
|
||||
else:
|
||||
raise CDEKClientError("CDEK city lookup response must be an object or array.")
|
||||
|
||||
if not isinstance(first_item, dict):
|
||||
raise CDEKClientError("CDEK city lookup response entry must be an object.")
|
||||
raw_city_code = first_item.get("code")
|
||||
if raw_city_code is None:
|
||||
raise CDEKClientError("CDEK city lookup response has no city code.")
|
||||
try:
|
||||
city_code = int(raw_city_code)
|
||||
return int(raw_city_code)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CDEKClientError("CDEK city lookup response city code is invalid.") from exc
|
||||
|
||||
self._city_code_cache[cache_key] = city_code
|
||||
return city_code
|
||||
raise CDEKRequestError(
|
||||
f"CDEK city code is invalid for city id {city_id}."
|
||||
) from exc
|
||||
|
||||
|
||||
class CDEKProvider(DeliveryProvider):
|
||||
@@ -283,7 +235,9 @@ class CDEKProvider(DeliveryProvider):
|
||||
)
|
||||
return cls(client=client, cache_ttl_seconds=adapter_config.cdek_cache_ttl_seconds)
|
||||
|
||||
async def get_prices(self, request: DeliveryRequest) -> list[DeliveryPrice]:
|
||||
async def get_prices(
|
||||
self, request: DeliveryCalculationRequest
|
||||
) -> list[DeliveryPrice]:
|
||||
raw_payload = await self._client.get_raw_price(request)
|
||||
return map_cdek_response(raw_payload)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user