Добавлен POST /api/v1/delivery/suggest-address

This commit is contained in:
Раис Юсупалиев
2026-03-29 02:05:21 +03:00
parent 17772e5337
commit 4a3737999f
11 changed files with 666 additions and 23 deletions
+66 -3
View File
@@ -3,10 +3,15 @@
import asyncio
import hashlib
import json
from collections.abc import Iterable, Sequence
from collections.abc import Iterable, Mapping, Sequence
from decimal import Decimal
from typing import Protocol
from app.adapters.address_suggestions.base import (
AddressSuggestionClientError,
AddressSuggestionProvider,
AddressSuggestionRequestError,
)
from app.adapters.delivery_providers.base import DeliveryProvider, ProviderRequestError
from app.domain.price import (
DEFAULT_PROVIDER_PRICE_MULTIPLIER,
@@ -16,8 +21,8 @@ from app.domain.price import (
normalize_delivery_request,
)
from app.schemas.order import OrderCreateRequest, OrderCreateResponse
from app.schemas.request import DeliveryCalculationRequest
from app.schemas.response import DeliveryPrice
from app.schemas.request import AddressSuggestRequest, DeliveryCalculationRequest
from app.schemas.response import AddressSuggestion, DeliveryPrice
class AggregatorServiceError(RuntimeError):
@@ -28,6 +33,18 @@ class InvalidDeliveryRequestError(AggregatorServiceError):
"""Raised when provider rejects delivery request as invalid."""
class UnsupportedAddressSuggestionCountryError(AggregatorServiceError):
"""Raised when address suggestions are not configured for a country."""
class InvalidAddressSuggestRequestError(AggregatorServiceError):
"""Raised when provider rejects address suggestion payload."""
class AddressSuggestionsUnavailableError(AggregatorServiceError):
"""Raised when address suggestions cannot be completed."""
class InvalidOrderCreateRequestError(AggregatorServiceError):
"""Raised when provider rejects order creation payload as invalid."""
@@ -64,6 +81,8 @@ class AggregatorService:
providers: Sequence[DeliveryProvider],
cache: PriceCacheProtocol | None = None,
order_adapter: OrderRegistrationAdapterProtocol | None = None,
address_suggestion_providers: Sequence[AddressSuggestionProvider] = (),
address_suggestion_country_to_provider: Mapping[str, str] | None = None,
*,
weight_round_scale: int = DEFAULT_WEIGHT_ROUND_SCALE,
provider_price_multiplier: Decimal = DEFAULT_PROVIDER_PRICE_MULTIPLIER,
@@ -75,6 +94,12 @@ class AggregatorService:
self._weight_round_scale = weight_round_scale
self._provider_price_multiplier = provider_price_multiplier
self._filter_and_sort_prices = filter_and_sort_prices_fn
self._address_suggestion_providers: dict[str, AddressSuggestionProvider] = {
provider.name: provider for provider in address_suggestion_providers
}
self._address_suggestion_country_to_provider = (
address_suggestion_country_to_provider or {}
)
async def get_all_prices(
self, request: DeliveryCalculationRequest
@@ -125,6 +150,24 @@ class AggregatorService:
)
return [self._coerce_delivery_price(price) for price in filtered_and_sorted]
async def suggest_addresses(
self, request: AddressSuggestRequest
) -> list[AddressSuggestion]:
provider = self._resolve_address_suggestion_provider(request.country_code)
try:
suggestions = await provider.suggest(request)
except AddressSuggestionRequestError as exc:
raise InvalidAddressSuggestRequestError(
"Address suggestion request is invalid for the configured provider."
) from exc
except AddressSuggestionClientError as exc:
raise AddressSuggestionsUnavailableError(
"Address suggestions are temporarily unavailable."
) from exc
return [self._coerce_address_suggestion(item) for item in suggestions]
async def create_order(self, request: OrderCreateRequest) -> OrderCreateResponse:
if self._order_adapter is None:
raise OrderCreationUnavailableError(
@@ -238,3 +281,23 @@ class AggregatorService:
if not isinstance(value, list):
raise TypeError("Cached delivery prices must be a list.")
return [cls._coerce_delivery_price(item) for item in value]
@staticmethod
def _coerce_address_suggestion(value: object) -> AddressSuggestion:
return AddressSuggestion.model_validate(value, from_attributes=True)
def _resolve_address_suggestion_provider(
self, country_code: str
) -> AddressSuggestionProvider:
provider_id = self._address_suggestion_country_to_provider.get(country_code)
if provider_id is None:
raise UnsupportedAddressSuggestionCountryError(
"Address suggestions are not configured for the requested country."
)
provider = self._address_suggestion_providers.get(provider_id)
if provider is None:
raise UnsupportedAddressSuggestionCountryError(
"Address suggestions are not configured for the requested country."
)
return provider