Add short_label, compact JSON, and omit nested parent by default.
Search items can return a step path without the region and a compact field set; clients that need the parent chain pass include_parent=true. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9b2e06e464
commit
71136db786
|
|
@ -12,7 +12,7 @@ UI и API ищут жилой адрес так: **Субъект РФ → на
|
|||
| Шаг | Уровень FIAS | Где в коде |
|
||||
|---|---|---|
|
||||
| Субъект РФ | `Level.REGION` (1) | `GET /regions`, UI «Субъект РФ» |
|
||||
| Населённый пункт | `LOCALITY_LEVELS` 2, 5, 6 **и** `PLANNING` (7) | `GET /localities?region_id=` |
|
||||
| Населённый пункт | `LOCALITY_LEVELS` 2, 5, 6 | `GET /localities?region_id=` |
|
||||
| Улица | `STREET_LEVELS`: `PLANNING` (7) **и** `STREET` (8) | `GET /streets` |
|
||||
| Дом | `House` | `GET /houses?parent_id=` выбранного объекта шага «улица» |
|
||||
|
||||
|
|
@ -26,14 +26,31 @@ UI и API ищут жилой адрес так: **Субъект РФ → на
|
|||
- `GET /localities` сортирует: сначала `г`/`г.`, потом `пгт`/`пгт.`, затем остальные (внутри группы — по имени; при нечётком поиске — ещё по релевантности).
|
||||
- Если выбран НП, `streets` берёт прямых детей **и** внуков: hop через `PLANNING` (улицы в СНТ) и через `SETTLEMENT`/`CITY` (улицы сёл в районе).
|
||||
- Иерархия не перескакивает уровни: `parent` — ближайший импортированный предок из PATH. Цепочка: улица → село → район → субъект, не «село → край».
|
||||
- В UI населённый пункт: объект, затем предки без субъекта через запятую (`тер. ДНТ Иволга-2, Надеждинский р-н, п. Соловей-Ключ`). Село в районе: `с. Лазо, Лазовский р-н`. JSON результата содержит `chain`.
|
||||
- В UI улица: первая строка — только объект (`ул. Адмирала Вершинина`), вторая — предки без субъекта (`Надеждинский р-н, тер. ДНТ Огонёк`). Не пиши `Улица · 25`.
|
||||
- Муниципальную ветку (`м.р-н`, `с.п.`, `г.п.`, уровни 3–4) не импортировать и не показывать в `GET /localities`: улиц и домов на ней нет. Планировки (СНТ, тер., уровень 7) в НП есть, чтобы выбрать СНТ и затем улицу внутри. Уровень 8 в `GET /localities` не входит.
|
||||
- Муниципальную ветку (`м.р-н`, `с.п.`, `г.п.`, уровни 3–4) не импортировать и не показывать в `GET /localities`: улиц и домов на ней нет.
|
||||
- Если НП не выбран, улицы ищутся по `region_code` субъекта.
|
||||
- Выбрали улицу без НП — UI подставляет `street.parent` как НП, **кроме** родителя уровня 1.
|
||||
- Выбрали улицу без НП — UI подставляет ближайшего предка уровней 2, 5 или 6, не СНТ и не субъекта.
|
||||
- Дом только у выбранной улицы/планировки. Импорт домов — регион 25; родитель только `STREET` (8) или `PLANNING` (7). Дом на субъекте, районе, городе или НП не импортируется и удаляется `delete_houses` (`SKIP_HOUSE_PARENT_LEVELS`).
|
||||
- Улица может висеть на субъекте-городе (`г.` Москва/СПб) — это ближайший предок в PATH.
|
||||
|
||||
## Подписи в UI
|
||||
|
||||
Код: `client/src/App.jsx`. Порядок как в адресе: крупное → мелкое. Субъект РФ (`level === 1`) не пишем. Поле показывает `option.label`. JSON: `label` — только объект, `short_label` — срез шага, `full_label` — вся цепочка с субъектом. Вложенный `parent` только при `include_parent=true` (по умолчанию false); `parent_id` всегда есть. `compact=true` — только `fias_id`, `label`, `short_label`, `level`, `region_code`, `full_label`; `include_parent` в этом режиме не действует.
|
||||
|
||||
Полный адрес `Приморский край, Надеждинский р-н, п. Западный, тер. СНТ Маргаритка, ул. Агатовая` делится так:
|
||||
|
||||
**Населённый пункт** (`toAddressOption`, `localityPathLabel`): только уровни 2, 5, 6.
|
||||
|
||||
- `Надеждинский р-н, п. Западный`
|
||||
- село в районе: `Лазовский р-н, с. Лазо`
|
||||
- город без района: `г. Владивосток`
|
||||
- в списке вторая строка: уровень и код региона (`Населённый пункт · 25`). JSON результата содержит `chain`.
|
||||
|
||||
**Улица / СНТ** (`toStreetOption`, `streetPathLabel`): только уровни 7 и 8, одной строкой. Не писать `Улица · 25` и не тащить район/НП в это поле.
|
||||
|
||||
- `тер. СНТ Маргаритка, ул. Агатовая`
|
||||
- улица в городе: `ул. Светланская`
|
||||
- само СНТ: `тер. СНТ Маргаритка`
|
||||
|
||||
## Чего не делать
|
||||
|
||||
- Не требовать НП, чтобы искать улицу.
|
||||
|
|
|
|||
141
address/api.py
141
address/api.py
|
|
@ -5,6 +5,8 @@ from uuid import UUID
|
|||
from django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity
|
||||
from django.db.models import Case, CharField, IntegerField, Q, Value, When
|
||||
from django.db.models.functions import Coalesce, Concat, Greatest, Lower, Replace
|
||||
from django.core.serializers.json import DjangoJSONEncoder
|
||||
from django.http import JsonResponse
|
||||
from ninja import NinjaAPI, Query, Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
|
|
@ -17,7 +19,7 @@ from .dadata import (
|
|||
suggest_houses,
|
||||
suggest_streets,
|
||||
)
|
||||
from .labels import address_full_label, address_label
|
||||
from .labels import address_full_label, address_label, address_short_label
|
||||
from .models import AddressObject, House, format_region_code
|
||||
|
||||
api = NinjaAPI(title="FIAS Address API", version="1.0.0", docs_url="docs/")
|
||||
|
|
@ -47,10 +49,15 @@ class AddressNodeOut(Schema):
|
|||
|
||||
class AddressOut(AddressNodeOut):
|
||||
full_label: str
|
||||
short_label: str
|
||||
|
||||
@staticmethod
|
||||
def resolve_full_label(obj: AddressObject) -> str:
|
||||
return address_full_label(obj)
|
||||
return getattr(obj, "resolved_full_label", None) or address_full_label(obj)
|
||||
|
||||
@staticmethod
|
||||
def resolve_short_label(obj: AddressObject) -> str:
|
||||
return getattr(obj, "resolved_short_label", None) or address_short_label(obj)
|
||||
|
||||
|
||||
class SearchParams(Schema):
|
||||
|
|
@ -64,6 +71,8 @@ class SearchParams(Schema):
|
|||
limit: int = 20
|
||||
offset: int = 0
|
||||
fuzzy: bool = True
|
||||
include_parent: bool = False
|
||||
compact: bool = False
|
||||
|
||||
|
||||
class LocalitySearchParams(SearchParams):
|
||||
|
|
@ -89,7 +98,6 @@ LOCALITY_LEVELS = (
|
|||
AddressObject.Level.CITY,
|
||||
AddressObject.Level.SETTLEMENT,
|
||||
)
|
||||
LOCALITY_SEARCH_LEVELS = (*LOCALITY_LEVELS, AddressObject.Level.PLANNING)
|
||||
STREET_LEVELS = (
|
||||
AddressObject.Level.PLANNING,
|
||||
AddressObject.Level.STREET,
|
||||
|
|
@ -103,6 +111,36 @@ class SearchResponse(Schema):
|
|||
items: list[AddressOut]
|
||||
|
||||
|
||||
class AddressCompactOut(Schema):
|
||||
fias_id: UUID
|
||||
label: str
|
||||
short_label: str
|
||||
level: int
|
||||
region_code: str
|
||||
full_label: str
|
||||
|
||||
@staticmethod
|
||||
def resolve_region_code(obj) -> str:
|
||||
return format_region_code(obj.region_code)
|
||||
|
||||
@staticmethod
|
||||
def resolve_label(obj) -> str:
|
||||
return getattr(obj, "label", None) or address_label(obj.type_name, obj.name)
|
||||
|
||||
@staticmethod
|
||||
def resolve_full_label(obj) -> str:
|
||||
return getattr(obj, "resolved_full_label", None) or address_full_label(obj)
|
||||
|
||||
@staticmethod
|
||||
def resolve_short_label(obj) -> str:
|
||||
return getattr(obj, "resolved_short_label", None) or address_short_label(obj)
|
||||
|
||||
|
||||
class CompactSearchResponse(Schema):
|
||||
count: int
|
||||
items: list[AddressCompactOut]
|
||||
|
||||
|
||||
PARENT_CHAIN = (
|
||||
"parent",
|
||||
"parent__parent",
|
||||
|
|
@ -128,6 +166,56 @@ class SearchResult:
|
|||
items: list
|
||||
|
||||
|
||||
class AddressView:
|
||||
"""Search hit. Nested parent is omitted unless include_parent is true."""
|
||||
|
||||
def __init__(self, obj, *, include_parent: bool):
|
||||
self._obj = obj
|
||||
self._include_parent = include_parent
|
||||
self.resolved_full_label = address_full_label(obj)
|
||||
self.resolved_short_label = address_short_label(obj)
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._obj, name)
|
||||
|
||||
@property
|
||||
def parent(self):
|
||||
if not self._include_parent:
|
||||
return None
|
||||
return self._obj.parent
|
||||
|
||||
|
||||
def present_addresses(result: SearchResult, include_parent: bool) -> SearchResult:
|
||||
return SearchResult(
|
||||
count=result.count,
|
||||
items=[AddressView(item, include_parent=include_parent) for item in result.items],
|
||||
)
|
||||
|
||||
|
||||
def compact_address(obj) -> dict:
|
||||
view = obj if isinstance(obj, AddressView) else AddressView(obj, include_parent=True)
|
||||
return {
|
||||
"fias_id": view.fias_id,
|
||||
"label": view.label,
|
||||
"short_label": view.resolved_short_label,
|
||||
"level": view.level,
|
||||
"region_code": format_region_code(view.region_code),
|
||||
"full_label": view.resolved_full_label,
|
||||
}
|
||||
|
||||
|
||||
def present_search(result: SearchResult, params: SearchParams):
|
||||
if params.compact:
|
||||
return JsonResponse(
|
||||
{
|
||||
"count": result.count,
|
||||
"items": [compact_address(item) for item in result.items],
|
||||
},
|
||||
encoder=DjangoJSONEncoder,
|
||||
)
|
||||
return present_addresses(result, params.include_parent)
|
||||
|
||||
|
||||
class HouseOut(Schema):
|
||||
fias_id: UUID
|
||||
object_id: int
|
||||
|
|
@ -467,38 +555,46 @@ def health(request):
|
|||
|
||||
@api.get("regions", response=SearchResponse, tags=["addresses"])
|
||||
def regions(request, params: Query[SearchParams]):
|
||||
return search((AddressObject.Level.REGION,), params)
|
||||
return present_search(search((AddressObject.Level.REGION,), params), params)
|
||||
|
||||
|
||||
@api.get("cities", response=SearchResponse, tags=["addresses"])
|
||||
def cities(request, params: Query[SearchParams]):
|
||||
return search(
|
||||
(AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT),
|
||||
return present_search(
|
||||
search(
|
||||
(AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT),
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
),
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
)
|
||||
|
||||
|
||||
@api.get("localities", response=LocalitySearchResponse, tags=["addresses"])
|
||||
def localities(request, params: Query[LocalitySearchParams]):
|
||||
params.region_code = str(params.region_id).zfill(2)
|
||||
return search(
|
||||
LOCALITY_SEARCH_LEVELS,
|
||||
return present_search(
|
||||
search(
|
||||
LOCALITY_LEVELS,
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
prefer_city_types=True,
|
||||
),
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
prefer_city_types=True,
|
||||
)
|
||||
|
||||
|
||||
@api.get("streets", response=StreetSearchResponse, tags=["addresses"])
|
||||
def streets(request, params: Query[SearchParams]):
|
||||
result = search(
|
||||
STREET_LEVELS,
|
||||
return present_search(
|
||||
search(
|
||||
STREET_LEVELS,
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=True,
|
||||
),
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=True,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def search_houses(params: HouseSearchParams) -> HouseSearchResponse:
|
||||
|
|
@ -544,17 +640,20 @@ def universal_search(
|
|||
"street": STREET_LEVELS,
|
||||
None: tuple(level.value for level in AddressObject.Level),
|
||||
}
|
||||
return search(
|
||||
levels[kind],
|
||||
return present_search(
|
||||
search(
|
||||
levels[kind],
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=kind == "street",
|
||||
),
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=kind == "street",
|
||||
)
|
||||
|
||||
|
||||
@api.get("suggest", response=SearchResponse, tags=["addresses"])
|
||||
def suggest(request, params: Query[SearchParams]):
|
||||
return suggest_search(params)
|
||||
return present_search(suggest_search(params), params)
|
||||
|
||||
|
||||
dadata_router = Router(tags=["dadata"])
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ message SearchRequest {
|
|||
optional string parent_kladr_id = 8;
|
||||
optional string parent_fias_id = 9;
|
||||
optional string fias_id = 10;
|
||||
optional bool include_parent = 11;
|
||||
}
|
||||
|
||||
message LocalitySearchRequest {
|
||||
|
|
@ -44,6 +45,7 @@ message LocalitySearchRequest {
|
|||
optional string fias_id = 8;
|
||||
optional string parent_kladr_id = 9;
|
||||
optional string parent_fias_id = 10;
|
||||
optional bool include_parent = 11;
|
||||
}
|
||||
|
||||
message UniversalSearchRequest {
|
||||
|
|
@ -58,6 +60,7 @@ message UniversalSearchRequest {
|
|||
optional string fias_id = 9;
|
||||
optional string parent_kladr_id = 10;
|
||||
optional string parent_fias_id = 11;
|
||||
optional bool include_parent = 12;
|
||||
}
|
||||
|
||||
message Address {
|
||||
|
|
@ -73,6 +76,7 @@ message Address {
|
|||
optional Address parent = 10;
|
||||
string label = 11;
|
||||
string full_label = 12;
|
||||
string short_label = 13;
|
||||
}
|
||||
|
||||
message SearchResponse {
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -19,7 +19,7 @@ SEARCH_KIND_CITY: SearchKind
|
|||
SEARCH_KIND_STREET: SearchKind
|
||||
|
||||
class SearchRequest(_message.Message):
|
||||
__slots__ = ("query", "region_code", "parent_id", "limit", "offset", "fuzzy", "kladr_id", "parent_kladr_id", "parent_fias_id", "fias_id")
|
||||
__slots__ = ("query", "region_code", "parent_id", "limit", "offset", "fuzzy", "kladr_id", "parent_kladr_id", "parent_fias_id", "fias_id", "include_parent")
|
||||
QUERY_FIELD_NUMBER: _ClassVar[int]
|
||||
REGION_CODE_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
|
|
@ -30,6 +30,7 @@ class SearchRequest(_message.Message):
|
|||
PARENT_KLADR_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
INCLUDE_PARENT_FIELD_NUMBER: _ClassVar[int]
|
||||
query: str
|
||||
region_code: str
|
||||
parent_id: int
|
||||
|
|
@ -40,10 +41,11 @@ class SearchRequest(_message.Message):
|
|||
parent_kladr_id: str
|
||||
parent_fias_id: str
|
||||
fias_id: str
|
||||
def __init__(self, query: _Optional[str] = ..., region_code: _Optional[str] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kladr_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ..., fias_id: _Optional[str] = ...) -> None: ...
|
||||
include_parent: bool
|
||||
def __init__(self, query: _Optional[str] = ..., region_code: _Optional[str] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kladr_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ..., fias_id: _Optional[str] = ..., include_parent: _Optional[bool] = ...) -> None: ...
|
||||
|
||||
class LocalitySearchRequest(_message.Message):
|
||||
__slots__ = ("query", "region_id", "parent_id", "limit", "offset", "fuzzy", "kladr_id", "fias_id", "parent_kladr_id", "parent_fias_id")
|
||||
__slots__ = ("query", "region_id", "parent_id", "limit", "offset", "fuzzy", "kladr_id", "fias_id", "parent_kladr_id", "parent_fias_id", "include_parent")
|
||||
QUERY_FIELD_NUMBER: _ClassVar[int]
|
||||
REGION_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
|
|
@ -54,6 +56,7 @@ class LocalitySearchRequest(_message.Message):
|
|||
FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_KLADR_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
INCLUDE_PARENT_FIELD_NUMBER: _ClassVar[int]
|
||||
query: str
|
||||
region_id: int
|
||||
parent_id: int
|
||||
|
|
@ -64,10 +67,11 @@ class LocalitySearchRequest(_message.Message):
|
|||
fias_id: str
|
||||
parent_kladr_id: str
|
||||
parent_fias_id: str
|
||||
def __init__(self, query: _Optional[str] = ..., region_id: _Optional[int] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kladr_id: _Optional[str] = ..., fias_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ...) -> None: ...
|
||||
include_parent: bool
|
||||
def __init__(self, query: _Optional[str] = ..., region_id: _Optional[int] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kladr_id: _Optional[str] = ..., fias_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ..., include_parent: _Optional[bool] = ...) -> None: ...
|
||||
|
||||
class UniversalSearchRequest(_message.Message):
|
||||
__slots__ = ("query", "region_code", "parent_id", "limit", "offset", "fuzzy", "kind", "kladr_id", "fias_id", "parent_kladr_id", "parent_fias_id")
|
||||
__slots__ = ("query", "region_code", "parent_id", "limit", "offset", "fuzzy", "kind", "kladr_id", "fias_id", "parent_kladr_id", "parent_fias_id", "include_parent")
|
||||
QUERY_FIELD_NUMBER: _ClassVar[int]
|
||||
REGION_CODE_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
|
|
@ -79,6 +83,7 @@ class UniversalSearchRequest(_message.Message):
|
|||
FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_KLADR_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
PARENT_FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
INCLUDE_PARENT_FIELD_NUMBER: _ClassVar[int]
|
||||
query: str
|
||||
region_code: str
|
||||
parent_id: int
|
||||
|
|
@ -90,10 +95,11 @@ class UniversalSearchRequest(_message.Message):
|
|||
fias_id: str
|
||||
parent_kladr_id: str
|
||||
parent_fias_id: str
|
||||
def __init__(self, query: _Optional[str] = ..., region_code: _Optional[str] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kind: _Optional[_Union[SearchKind, str]] = ..., kladr_id: _Optional[str] = ..., fias_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ...) -> None: ...
|
||||
include_parent: bool
|
||||
def __init__(self, query: _Optional[str] = ..., region_code: _Optional[str] = ..., parent_id: _Optional[int] = ..., limit: _Optional[int] = ..., offset: _Optional[int] = ..., fuzzy: _Optional[bool] = ..., kind: _Optional[_Union[SearchKind, str]] = ..., kladr_id: _Optional[str] = ..., fias_id: _Optional[str] = ..., parent_kladr_id: _Optional[str] = ..., parent_fias_id: _Optional[str] = ..., include_parent: _Optional[bool] = ...) -> None: ...
|
||||
|
||||
class Address(_message.Message):
|
||||
__slots__ = ("id", "fias_id", "object_id", "parent_id", "name", "type_name", "level", "region_code", "kladr_id", "parent", "label", "full_label")
|
||||
__slots__ = ("id", "fias_id", "object_id", "parent_id", "name", "type_name", "level", "region_code", "kladr_id", "parent", "label", "full_label", "short_label")
|
||||
ID_FIELD_NUMBER: _ClassVar[int]
|
||||
FIAS_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
OBJECT_ID_FIELD_NUMBER: _ClassVar[int]
|
||||
|
|
@ -106,6 +112,7 @@ class Address(_message.Message):
|
|||
PARENT_FIELD_NUMBER: _ClassVar[int]
|
||||
LABEL_FIELD_NUMBER: _ClassVar[int]
|
||||
FULL_LABEL_FIELD_NUMBER: _ClassVar[int]
|
||||
SHORT_LABEL_FIELD_NUMBER: _ClassVar[int]
|
||||
id: int
|
||||
fias_id: str
|
||||
object_id: int
|
||||
|
|
@ -118,7 +125,8 @@ class Address(_message.Message):
|
|||
parent: Address
|
||||
label: str
|
||||
full_label: str
|
||||
def __init__(self, id: _Optional[int] = ..., fias_id: _Optional[str] = ..., object_id: _Optional[int] = ..., parent_id: _Optional[int] = ..., name: _Optional[str] = ..., type_name: _Optional[str] = ..., level: _Optional[int] = ..., region_code: _Optional[str] = ..., kladr_id: _Optional[str] = ..., parent: _Optional[_Union[Address, _Mapping]] = ..., label: _Optional[str] = ..., full_label: _Optional[str] = ...) -> None: ...
|
||||
short_label: str
|
||||
def __init__(self, id: _Optional[int] = ..., fias_id: _Optional[str] = ..., object_id: _Optional[int] = ..., parent_id: _Optional[int] = ..., name: _Optional[str] = ..., type_name: _Optional[str] = ..., level: _Optional[int] = ..., region_code: _Optional[str] = ..., kladr_id: _Optional[str] = ..., parent: _Optional[_Union[Address, _Mapping]] = ..., label: _Optional[str] = ..., full_label: _Optional[str] = ..., short_label: _Optional[str] = ...) -> None: ...
|
||||
|
||||
class SearchResponse(_message.Message):
|
||||
__slots__ = ("count", "items")
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ from ninja.errors import HttpError
|
|||
|
||||
from address.api import (
|
||||
HOUSE_PARENT_REQUIRED,
|
||||
LOCALITY_SEARCH_LEVELS,
|
||||
LOCALITY_LEVELS,
|
||||
PARENT_CHAIN,
|
||||
STREET_LEVELS,
|
||||
HouseSearchParams,
|
||||
|
|
@ -15,7 +15,7 @@ from address.api import (
|
|||
suggest_search,
|
||||
)
|
||||
from address.grpc import address_pb2, address_pb2_grpc
|
||||
from address.labels import address_full_label
|
||||
from address.labels import address_full_label, address_short_label
|
||||
from address.models import AddressObject, format_region_code
|
||||
|
||||
_KIND_LEVELS = {
|
||||
|
|
@ -84,6 +84,18 @@ def _postal_code(value) -> str:
|
|||
return f"{value:06d}"
|
||||
|
||||
|
||||
def _include_parent(message) -> bool:
|
||||
return bool(_has_field(message, "include_parent") and message.include_parent)
|
||||
|
||||
|
||||
def _item_full_label(item) -> str:
|
||||
return getattr(item, "resolved_full_label", None) or address_full_label(item)
|
||||
|
||||
|
||||
def _item_short_label(item) -> str:
|
||||
return getattr(item, "resolved_short_label", None) or address_short_label(item)
|
||||
|
||||
|
||||
def _to_address(item, *, with_parent: bool = False, with_full_label: bool = True) -> address_pb2.Address:
|
||||
message = address_pb2.Address(
|
||||
id=item.id,
|
||||
|
|
@ -91,7 +103,8 @@ def _to_address(item, *, with_parent: bool = False, with_full_label: bool = True
|
|||
name=item.name,
|
||||
type_name=item.type_name,
|
||||
label=item.label,
|
||||
full_label=address_full_label(item) if with_full_label else "",
|
||||
full_label=_item_full_label(item) if with_full_label else "",
|
||||
short_label=_item_short_label(item) if with_full_label else "",
|
||||
level=item.level,
|
||||
region_code=_region_code(item.region_code),
|
||||
kladr_id=item.kladr_id or "",
|
||||
|
|
@ -138,7 +151,10 @@ def _search_response(result, *, with_parent: bool = False) -> address_pb2.Search
|
|||
|
||||
class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
||||
def SearchRegions(self, request, context):
|
||||
return _search_response(search((AddressObject.Level.REGION,), _search_params(request)))
|
||||
return _search_response(
|
||||
search((AddressObject.Level.REGION,), _search_params(request)),
|
||||
with_parent=_include_parent(request),
|
||||
)
|
||||
|
||||
def SearchCities(self, request, context):
|
||||
return _search_response(
|
||||
|
|
@ -146,7 +162,8 @@ class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
|||
(AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT),
|
||||
_search_params(request),
|
||||
select_related=PARENT_CHAIN,
|
||||
)
|
||||
),
|
||||
with_parent=_include_parent(request),
|
||||
)
|
||||
|
||||
def SearchLocalities(self, request, context):
|
||||
|
|
@ -167,12 +184,12 @@ class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
|||
)
|
||||
return _search_response(
|
||||
search(
|
||||
LOCALITY_SEARCH_LEVELS,
|
||||
LOCALITY_LEVELS,
|
||||
params,
|
||||
select_related=PARENT_CHAIN,
|
||||
prefer_city_types=True,
|
||||
),
|
||||
with_parent=True,
|
||||
with_parent=_include_parent(request),
|
||||
)
|
||||
|
||||
def SearchStreets(self, request, context):
|
||||
|
|
@ -183,7 +200,7 @@ class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
|||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=True,
|
||||
),
|
||||
with_parent=True,
|
||||
with_parent=_include_parent(request),
|
||||
)
|
||||
|
||||
def SearchHouses(self, request, context):
|
||||
|
|
@ -216,7 +233,7 @@ class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
|||
select_related=PARENT_CHAIN,
|
||||
include_planning_children=request.kind == address_pb2.SEARCH_KIND_STREET,
|
||||
),
|
||||
with_parent=request.kind == address_pb2.SEARCH_KIND_STREET,
|
||||
with_parent=_include_parent(request),
|
||||
)
|
||||
|
||||
def SearchSuggest(self, request, context):
|
||||
|
|
@ -232,7 +249,7 @@ class AddressServicer(address_pb2_grpc.AddressServiceServicer):
|
|||
result = suggest_search(params)
|
||||
except HttpError as exc:
|
||||
context.abort(grpc.StatusCode.INVALID_ARGUMENT, str(exc) or _REGION_REQUIRED)
|
||||
return _search_response(result, with_parent=True)
|
||||
return _search_response(result, with_parent=_include_parent(request))
|
||||
|
||||
def Health(self, request, context):
|
||||
return address_pb2.HealthResponse(status="ok")
|
||||
|
|
|
|||
|
|
@ -87,6 +87,13 @@ def address_label(type_name: str, name: str) -> str:
|
|||
return f"{type_name} {stripped}".strip()
|
||||
|
||||
|
||||
def _node_label(node) -> str:
|
||||
return getattr(node, "label", None) or address_label(
|
||||
getattr(node, "type_name", "") or "",
|
||||
getattr(node, "name", "") or "",
|
||||
)
|
||||
|
||||
|
||||
def address_full_label(obj) -> str:
|
||||
"""Склейка label от субъекта РФ до объекта: «Приморский край, …, тер. ДНТ Огонёк»."""
|
||||
parts = []
|
||||
|
|
@ -97,12 +104,41 @@ def address_full_label(obj) -> str:
|
|||
if marker in seen:
|
||||
break
|
||||
seen.add(marker)
|
||||
label = getattr(node, "label", None) or address_label(
|
||||
getattr(node, "type_name", "") or "",
|
||||
getattr(node, "name", "") or "",
|
||||
)
|
||||
label = _node_label(node)
|
||||
if label:
|
||||
parts.append(label)
|
||||
node = getattr(node, "parent", None)
|
||||
parts.reverse()
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
# НП: район / город / село. Улица: планировка / улица. Субъект в short_label не входит.
|
||||
_LOCALITY_SHORT_LEVELS = frozenset({2, 5, 6})
|
||||
_STREET_SHORT_LEVELS = frozenset({7, 8})
|
||||
|
||||
|
||||
def address_short_label(obj) -> str:
|
||||
"""Подпись шага без субъекта: «Лазовский р-н, с. Лазо» / «тер. СНТ Маргаритка, ул. Агатовая»."""
|
||||
level = getattr(obj, "level", None)
|
||||
if level in _STREET_SHORT_LEVELS:
|
||||
wanted = _STREET_SHORT_LEVELS
|
||||
elif level in _LOCALITY_SHORT_LEVELS:
|
||||
wanted = _LOCALITY_SHORT_LEVELS
|
||||
else:
|
||||
return _node_label(obj)
|
||||
|
||||
parts = []
|
||||
seen = set()
|
||||
node = obj
|
||||
while node is not None:
|
||||
marker = id(node)
|
||||
if marker in seen:
|
||||
break
|
||||
seen.add(marker)
|
||||
if getattr(node, "level", None) in wanted:
|
||||
label = _node_label(node)
|
||||
if label:
|
||||
parts.append(label)
|
||||
node = getattr(node, "parent", None)
|
||||
parts.reverse()
|
||||
return ", ".join(parts) or _node_label(obj)
|
||||
|
|
|
|||
|
|
@ -39,8 +39,51 @@ def test_search_city(addresses):
|
|||
assert response.status_code == 200
|
||||
assert response.json()["items"][0]["name"] == "Владивосток"
|
||||
assert response.json()["items"][0]["label"] == "г Владивосток"
|
||||
assert response.json()["items"][0]["short_label"] == "г Владивосток"
|
||||
assert response.json()["items"][0]["full_label"] == "Приморский край, г Владивосток"
|
||||
assert "full_label" not in response.json()["items"][0]["parent"]
|
||||
assert response.json()["items"][0]["parent"] is None
|
||||
|
||||
|
||||
COMPACT_KEYS = {"fias_id", "label", "short_label", "level", "region_code", "full_label"}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_compact_search_returns_short_fields(addresses):
|
||||
response = Client().get(
|
||||
api_url("cities"),
|
||||
{"query": "влад", "region_code": "25", "compact": "true"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
item = response.json()["items"][0]
|
||||
assert set(item) == COMPACT_KEYS
|
||||
assert item["label"] == "г Владивосток"
|
||||
assert item["short_label"] == "г Владивосток"
|
||||
assert item["full_label"] == "Приморский край, г Владивосток"
|
||||
assert item["level"] == 5
|
||||
assert item["region_code"] == "25"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_compact_ignores_include_parent(addresses):
|
||||
_, city = addresses
|
||||
response = Client().get(
|
||||
api_url("streets"),
|
||||
{
|
||||
"parent_id": city.pk,
|
||||
"query": "свет",
|
||||
"compact": "true",
|
||||
"include_parent": "true",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
item = response.json()["items"][0]
|
||||
assert set(item) == COMPACT_KEYS
|
||||
assert item["label"] == "ул Светланская"
|
||||
assert item["short_label"] == "ул Светланская"
|
||||
assert item["full_label"] == "Приморский край, г Владивосток, ул Светланская"
|
||||
assert "parent" not in item
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
|
|
@ -56,14 +99,19 @@ def test_address_label_avoids_type_repetition(addresses):
|
|||
)
|
||||
|
||||
region_response = Client().get(api_url("regions"), {"query": "прим"})
|
||||
street_response = Client().get(api_url("streets"), {"parent_id": city.pk, "query": "актин"})
|
||||
street_response = Client().get(
|
||||
api_url("streets"),
|
||||
{"parent_id": city.pk, "query": "актин", "include_parent": "true"},
|
||||
)
|
||||
|
||||
assert region_response.json()["items"][0]["label"] == "Приморский край"
|
||||
assert region_response.json()["items"][0]["full_label"] == "Приморский край"
|
||||
assert street_response.json()["items"][0]["label"] == "снт Актинидия"
|
||||
assert street_response.json()["items"][0]["short_label"] == "снт Актинидия"
|
||||
assert street_response.json()["items"][0]["full_label"] == "Приморский край, г Владивосток, снт Актинидия"
|
||||
assert street_response.json()["items"][0]["parent"]["label"] == "г Владивосток"
|
||||
assert "full_label" not in street_response.json()["items"][0]["parent"]
|
||||
assert "short_label" not in street_response.json()["items"][0]["parent"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
|
|
@ -90,14 +138,16 @@ def test_full_label_is_only_on_item():
|
|||
|
||||
response = Client().get(
|
||||
api_url("streets"),
|
||||
{"parent_id": district.pk, "query": "огон", "fuzzy": "false"},
|
||||
{"parent_id": district.pk, "query": "огон", "fuzzy": "false", "include_parent": "true"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
item = response.json()["items"][0]
|
||||
assert item["label"] == "тер. ДНТ Огонёк"
|
||||
assert item["short_label"] == "тер. ДНТ Огонёк"
|
||||
assert item["full_label"] == "Приморский край, Надеждинский р-н, тер. ДНТ Огонёк"
|
||||
assert "full_label" not in item["parent"]
|
||||
assert "short_label" not in item["parent"]
|
||||
assert "full_label" not in item["parent"]["parent"]
|
||||
|
||||
|
||||
|
|
@ -121,7 +171,7 @@ def test_suggest_requires_region(addresses):
|
|||
def test_suggest_finds_street_by_city_and_street(addresses):
|
||||
response = Client().get(
|
||||
api_url("suggest"),
|
||||
{"region_code": "25", "query": "владивосток светлан"},
|
||||
{"region_code": "25", "query": "владивосток светлан", "include_parent": "true"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
|
@ -320,7 +370,7 @@ def test_streets_can_be_filtered_by_region_without_parent(addresses):
|
|||
@pytest.mark.django_db
|
||||
def test_streets_include_parent_object(addresses):
|
||||
region, city = addresses
|
||||
response = Client().get(api_url("streets"), {"region_code": "25", "query": "свет"})
|
||||
response = Client().get(api_url("streets"), {"region_code": "25", "query": "свет", "include_parent": "true"})
|
||||
|
||||
assert response.status_code == 200
|
||||
item = response.json()["items"][0]
|
||||
|
|
@ -331,6 +381,19 @@ def test_streets_include_parent_object(addresses):
|
|||
assert item["parent"]["parent_id"] == region.pk
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_search_omits_parent_by_default(addresses):
|
||||
response = Client().get(api_url("streets"), {"region_code": "25", "query": "свет"})
|
||||
|
||||
assert response.status_code == 200
|
||||
item = response.json()["items"][0]
|
||||
assert item["name"] == "Светланская"
|
||||
assert item["parent"] is None
|
||||
assert item["parent_id"] is not None
|
||||
assert item["short_label"] == "ул Светланская"
|
||||
assert item["full_label"] == "Приморский край, г Владивосток, ул Светланская"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_streets_include_planning_structures(addresses):
|
||||
_, city = addresses
|
||||
|
|
@ -395,13 +458,17 @@ def test_streets_include_streets_inside_snt(addresses):
|
|||
parent=snt,
|
||||
)
|
||||
|
||||
response = Client().get(api_url("streets"), {"parent_id": city.pk, "fuzzy": "false"})
|
||||
response = Client().get(
|
||||
api_url("streets"),
|
||||
{"parent_id": city.pk, "fuzzy": "false", "include_parent": "true"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
items = {item["name"]: item for item in response.json()["items"]}
|
||||
assert set(items) == {"Светланская", "Сокол", "2-я Садовая"}
|
||||
assert items["2-я Садовая"]["parent"]["id"] == snt.pk
|
||||
assert items["2-я Садовая"]["parent"]["name"] == "Сокол"
|
||||
assert items["2-я Садовая"]["short_label"] == "снт Сокол, ул 2-я Садовая"
|
||||
assert inner.pk == items["2-я Садовая"]["id"]
|
||||
|
||||
|
||||
|
|
@ -527,47 +594,6 @@ def test_localities_exclude_municipal_branch(addresses):
|
|||
assert "Сальское" not in names
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_localities_include_planning_but_not_streets(addresses):
|
||||
region, _city = addresses
|
||||
district = AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Надеждинский",
|
||||
type_name="р-н",
|
||||
level=AddressObject.Level.DISTRICT,
|
||||
region_code="25",
|
||||
parent=region,
|
||||
)
|
||||
snt = AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Чистые пруды",
|
||||
type_name="тер. СНТ",
|
||||
level=AddressObject.Level.PLANNING,
|
||||
region_code="25",
|
||||
parent=district,
|
||||
)
|
||||
AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Агаровая",
|
||||
type_name="ул",
|
||||
level=AddressObject.Level.STREET,
|
||||
region_code="25",
|
||||
parent=snt,
|
||||
)
|
||||
|
||||
found = Client().get(api_url("localities"), {"region_id": "25", "query": "чистые"})
|
||||
assert found.status_code == 200
|
||||
assert found.json()["count"] == 1
|
||||
item = found.json()["items"][0]
|
||||
assert item["name"] == "Чистые пруды"
|
||||
assert item["type_name"] == "тер. СНТ"
|
||||
assert item["level"] == AddressObject.Level.PLANNING
|
||||
|
||||
missing = Client().get(api_url("localities"), {"region_id": "25", "query": "агаров"})
|
||||
assert missing.status_code == 200
|
||||
assert missing.json()["count"] == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_localities_include_district_parent(addresses):
|
||||
region, _city = addresses
|
||||
|
|
@ -590,7 +616,7 @@ def test_localities_include_district_parent(addresses):
|
|||
|
||||
response = Client().get(
|
||||
api_url("localities"),
|
||||
{"region_id": "25", "fuzzy": "false", "limit": 100},
|
||||
{"region_id": "25", "fuzzy": "false", "limit": 100, "include_parent": "true"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
|
@ -598,8 +624,10 @@ def test_localities_include_district_parent(addresses):
|
|||
assert item["parent"]["id"] == district.pk
|
||||
assert item["parent"]["name"] == "Лазовский"
|
||||
assert item["parent"]["type_name"] == "р-н"
|
||||
assert item["short_label"] == "Лазовский р-н, с. Лазо"
|
||||
assert item["full_label"] == "Приморский край, Лазовский р-н, с. Лазо"
|
||||
assert "full_label" not in item["parent"]
|
||||
assert "short_label" not in item["parent"]
|
||||
assert "full_label" not in item["parent"]["parent"]
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -54,9 +54,11 @@ def test_search_cities(addresses):
|
|||
assert response.count == 1
|
||||
assert response.items[0].name == "Владивосток"
|
||||
assert response.items[0].label == "г Владивосток"
|
||||
assert response.items[0].short_label == "г Владивосток"
|
||||
assert response.items[0].full_label == "Приморский край, г Владивосток"
|
||||
assert response.items[0].region_code == "25"
|
||||
assert response.items[0].parent_id == addresses[0].pk
|
||||
assert not response.items[0].HasField("parent")
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
|
|
@ -118,19 +120,36 @@ def test_search_by_fias_id(addresses):
|
|||
def test_search_streets_by_parent(addresses):
|
||||
region, city = addresses
|
||||
response = AddressServicer().SearchStreets(
|
||||
address_pb2.SearchRequest(parent_id=city.pk),
|
||||
address_pb2.SearchRequest(parent_id=city.pk, include_parent=True),
|
||||
_Context(),
|
||||
)
|
||||
|
||||
assert response.count == 1
|
||||
assert response.items[0].name == "Светланская"
|
||||
assert response.items[0].full_label == "Приморский край, г Владивосток, ул Светланская"
|
||||
assert response.items[0].short_label == "ул Светланская"
|
||||
assert response.items[0].HasField("parent")
|
||||
assert response.items[0].parent.id == city.pk
|
||||
assert response.items[0].parent.name == "Владивосток"
|
||||
assert response.items[0].parent.level == AddressObject.Level.CITY
|
||||
assert response.items[0].parent.parent_id == region.pk
|
||||
assert response.items[0].parent.full_label == ""
|
||||
assert response.items[0].parent.short_label == ""
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_search_streets_omit_parent_by_default(addresses):
|
||||
_, city = addresses
|
||||
response = AddressServicer().SearchStreets(
|
||||
address_pb2.SearchRequest(parent_id=city.pk),
|
||||
_Context(),
|
||||
)
|
||||
|
||||
assert response.count == 1
|
||||
assert response.items[0].name == "Светланская"
|
||||
assert response.items[0].short_label == "ул Светланская"
|
||||
assert not response.items[0].HasField("parent")
|
||||
assert response.items[0].parent_id == city.pk
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
|
|
@ -167,50 +186,6 @@ def test_search_localities(addresses):
|
|||
assert response.items[0].name == "Владивосток"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_search_localities_include_planning_but_not_streets(addresses):
|
||||
region, _city = addresses
|
||||
district = AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Надеждинский",
|
||||
type_name="р-н",
|
||||
level=AddressObject.Level.DISTRICT,
|
||||
region_code="25",
|
||||
parent=region,
|
||||
)
|
||||
snt = AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Чистые пруды",
|
||||
type_name="тер. СНТ",
|
||||
level=AddressObject.Level.PLANNING,
|
||||
region_code="25",
|
||||
parent=district,
|
||||
)
|
||||
AddressObject.objects.create(
|
||||
fias_id=uuid.uuid4(),
|
||||
name="Агаровая",
|
||||
type_name="ул",
|
||||
level=AddressObject.Level.STREET,
|
||||
region_code="25",
|
||||
parent=snt,
|
||||
)
|
||||
|
||||
found = AddressServicer().SearchLocalities(
|
||||
address_pb2.LocalitySearchRequest(region_id=25, query="чистые"),
|
||||
_Context(),
|
||||
)
|
||||
assert found.count == 1
|
||||
assert found.items[0].name == "Чистые пруды"
|
||||
assert found.items[0].type_name == "тер. СНТ"
|
||||
assert found.items[0].level == AddressObject.Level.PLANNING
|
||||
|
||||
missing = AddressServicer().SearchLocalities(
|
||||
address_pb2.LocalitySearchRequest(region_id=25, query="агаров"),
|
||||
_Context(),
|
||||
)
|
||||
assert missing.count == 0
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_universal_search_by_kind(addresses):
|
||||
response = AddressServicer().Search(
|
||||
|
|
@ -356,7 +331,7 @@ def test_search_suggest_requires_region(addresses):
|
|||
@pytest.mark.django_db
|
||||
def test_search_suggest_finds_street_by_city_and_street(addresses):
|
||||
response = AddressServicer().SearchSuggest(
|
||||
address_pb2.SearchRequest(region_code="25", query="владивосток светлан"),
|
||||
address_pb2.SearchRequest(region_code="25", query="владивосток светлан", include_parent=True),
|
||||
_Context(),
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import pytest
|
||||
|
||||
from address.labels import address_full_label, address_label
|
||||
from address.labels import address_full_label, address_label, address_short_label
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
|
@ -40,3 +40,18 @@ def test_address_full_label_joins_parent_chain():
|
|||
assert address_full_label(region) == "Приморский край"
|
||||
assert address_full_label(district) == "Приморский край, Надеждинский р-н"
|
||||
assert address_full_label(planning) == "Приморский край, Надеждинский р-н, тер. ДНТ Огонёк"
|
||||
|
||||
|
||||
def test_address_short_label_by_step():
|
||||
region = type("Obj", (), {"type_name": "край", "name": "Приморский", "level": 1, "parent": None})()
|
||||
district = type("Obj", (), {"type_name": "р-н", "name": "Надеждинский", "level": 2, "parent": region})()
|
||||
settlement = type("Obj", (), {"type_name": "п.", "name": "Западный", "level": 6, "parent": district})()
|
||||
snt = type("Obj", (), {"type_name": "тер. СНТ", "name": "Маргаритка", "level": 7, "parent": settlement})()
|
||||
street = type("Obj", (), {"type_name": "ул.", "name": "Агатовая", "level": 8, "parent": snt})()
|
||||
village = type("Obj", (), {"type_name": "с.", "name": "Лазо", "level": 6, "parent": type("Obj", (), {"type_name": "р-н", "name": "Лазовский", "level": 2, "parent": region})()})()
|
||||
|
||||
assert address_short_label(region) == "Приморский край"
|
||||
assert address_short_label(settlement) == "Надеждинский р-н, п. Западный"
|
||||
assert address_short_label(street) == "тер. СНТ Маргаритка, ул. Агатовая"
|
||||
assert address_short_label(snt) == "тер. СНТ Маргаритка"
|
||||
assert address_short_label(village) == "Лазовский р-н, с. Лазо"
|
||||
|
|
|
|||
|
|
@ -6,9 +6,11 @@ import Box from "@mui/material/Box";
|
|||
import Chip from "@mui/material/Chip";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import Container from "@mui/material/Container";
|
||||
import FormControlLabel from "@mui/material/FormControlLabel";
|
||||
import InputAdornment from "@mui/material/InputAdornment";
|
||||
import Paper from "@mui/material/Paper";
|
||||
import Stack from "@mui/material/Stack";
|
||||
import Switch from "@mui/material/Switch";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import Toolbar from "@mui/material/Toolbar";
|
||||
import Typography from "@mui/material/Typography";
|
||||
|
|
@ -73,40 +75,45 @@ function addressChain(address) {
|
|||
return items.reverse();
|
||||
}
|
||||
|
||||
const LOCALITY_LEVELS = new Set([2, 5, 6]);
|
||||
const STREET_LEVELS = new Set([7, 8]);
|
||||
|
||||
function chainLabels(address, levels) {
|
||||
return addressChain(address)
|
||||
.filter((item) => levels.has(item.level))
|
||||
.map((item) => item.label)
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
function localityPathLabel(address) {
|
||||
const chain = addressChain(address).filter((item) => item.level !== 1);
|
||||
if (!chain.length) return addressTitle(address);
|
||||
const self = chain[chain.length - 1];
|
||||
const ancestors = chain.slice(0, -1);
|
||||
if (!ancestors.length) return self.label;
|
||||
return [self.label, ...ancestors.map((item) => item.label)].join(", ");
|
||||
return chainLabels(address, LOCALITY_LEVELS) || addressTitle(address);
|
||||
}
|
||||
|
||||
function streetPathLabel(address) {
|
||||
return chainLabels(address, STREET_LEVELS) || addressTitle(address);
|
||||
}
|
||||
|
||||
function nearestLocality(address) {
|
||||
for (let node = address; node; node = node.parent) {
|
||||
if (node.level === 1) return null;
|
||||
if (LOCALITY_LEVELS.has(node.level)) return node;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toAddressOption(address) {
|
||||
return {
|
||||
value: address.fias_id,
|
||||
label: localityPathLabel(address),
|
||||
label: address.short_label || localityPathLabel(address),
|
||||
meta: `${levelNames[address.level] || "Адрес"} · ${address.region_code}`,
|
||||
address,
|
||||
};
|
||||
}
|
||||
|
||||
function streetAncestorContext(address) {
|
||||
const parts = [];
|
||||
const seen = new Set([address.id]);
|
||||
for (let node = address.parent; node && !seen.has(node.id); node = node.parent) {
|
||||
seen.add(node.id);
|
||||
if (node.level === 1) continue;
|
||||
parts.push(addressTitle(node));
|
||||
}
|
||||
return parts.reverse().join(", ");
|
||||
}
|
||||
|
||||
function toStreetOption(address) {
|
||||
return {
|
||||
value: address.fias_id,
|
||||
label: addressTitle(address),
|
||||
meta: streetAncestorContext(address),
|
||||
label: address.short_label || streetPathLabel(address),
|
||||
address,
|
||||
};
|
||||
}
|
||||
|
|
@ -121,7 +128,7 @@ function suggestPathLabel(address) {
|
|||
function toSuggestOption(address) {
|
||||
return {
|
||||
value: address.fias_id,
|
||||
label: suggestPathLabel(address),
|
||||
label: address.parent ? suggestPathLabel(address) : address.full_label || addressTitle(address),
|
||||
address,
|
||||
};
|
||||
}
|
||||
|
|
@ -134,36 +141,77 @@ function toHouseOption(house) {
|
|||
};
|
||||
}
|
||||
|
||||
function compactAddress(address) {
|
||||
if (!address) return null;
|
||||
return {
|
||||
fias_id: address.fias_id,
|
||||
label: address.label || addressTitle(address),
|
||||
short_label: address.short_label || address.label || addressTitle(address),
|
||||
level: address.level,
|
||||
region_code: address.region_code,
|
||||
full_label: address.full_label,
|
||||
};
|
||||
}
|
||||
|
||||
async function loadAddresses(path, query, extra, minLength = 2, toOption = toAddressOption) {
|
||||
const normalizedQuery = query.trim();
|
||||
if (normalizedQuery.length < minLength) return [];
|
||||
const data = await requestItems(path, { query: normalizedQuery, ...extra });
|
||||
const data = await requestItems(path, {
|
||||
query: normalizedQuery,
|
||||
...extra,
|
||||
});
|
||||
return data.items.map(toOption);
|
||||
}
|
||||
|
||||
async function loadHouses(query, streetId) {
|
||||
const extra = { parent_id: String(streetId) };
|
||||
async function loadHouses(query, street) {
|
||||
const extra = street.id
|
||||
? { parent_id: String(street.id) }
|
||||
: { parent_fias_id: String(street.fias_id) };
|
||||
if (query.trim()) extra.query = query.trim();
|
||||
const data = await requestItems("houses", extra);
|
||||
return data.items.map(toHouseOption);
|
||||
}
|
||||
|
||||
const loadRegions = (query) => loadAddresses("regions", query);
|
||||
const loadLocalities = (query, regionId) =>
|
||||
loadAddresses("localities", query, { region_id: String(regionId) });
|
||||
const loadStreets = (query, { parentId, regionCode } = {}) =>
|
||||
const loadRegions = (query, { includeParent, compact } = {}) =>
|
||||
loadAddresses("regions", query, {
|
||||
include_parent: String(Boolean(includeParent)),
|
||||
compact: String(Boolean(compact)),
|
||||
});
|
||||
const loadLocalities = (query, regionId, { includeParent, compact } = {}) =>
|
||||
loadAddresses("localities", query, {
|
||||
region_id: String(regionId),
|
||||
include_parent: String(Boolean(includeParent)),
|
||||
compact: String(Boolean(compact)),
|
||||
});
|
||||
const loadStreets = (query, { parentId, parentFiasId, regionCode, includeParent, compact } = {}) =>
|
||||
loadAddresses(
|
||||
"streets",
|
||||
query,
|
||||
{
|
||||
...(parentId ? { parent_id: String(parentId) } : {}),
|
||||
include_parent: String(Boolean(includeParent)),
|
||||
compact: String(Boolean(compact)),
|
||||
...(parentId
|
||||
? { parent_id: String(parentId) }
|
||||
: parentFiasId
|
||||
? { parent_fias_id: String(parentFiasId) }
|
||||
: {}),
|
||||
...(regionCode ? { region_code: String(regionCode) } : {}),
|
||||
},
|
||||
2,
|
||||
toStreetOption,
|
||||
);
|
||||
const loadSuggest = (query, regionCode) =>
|
||||
loadAddresses("suggest", query, { region_code: String(regionCode) }, 2, toSuggestOption);
|
||||
const loadSuggest = (query, regionCode, { includeParent, compact } = {}) =>
|
||||
loadAddresses(
|
||||
"suggest",
|
||||
query,
|
||||
{
|
||||
region_code: String(regionCode),
|
||||
include_parent: String(Boolean(includeParent)),
|
||||
compact: String(Boolean(compact)),
|
||||
},
|
||||
2,
|
||||
toSuggestOption,
|
||||
);
|
||||
|
||||
function twoCharHint(kind) {
|
||||
return ({ inputValue }) =>
|
||||
|
|
@ -305,6 +353,9 @@ export default function App() {
|
|||
const [locality, setLocality] = useState(null);
|
||||
const [street, setStreet] = useState(null);
|
||||
const [house, setHouse] = useState(null);
|
||||
const [includeParent, setIncludeParent] = useState(false);
|
||||
const [quickSearch, setQuickSearch] = useState(false);
|
||||
const [compact, setCompact] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const findOptions = (loader) => async (query) => {
|
||||
|
|
@ -336,33 +387,37 @@ export default function App() {
|
|||
setStreet(option);
|
||||
setHouse(null);
|
||||
setSuggest(option?.address ? toSuggestOption(option.address) : null);
|
||||
if (locality || !option?.address?.parent) return;
|
||||
const parent = option.address.parent;
|
||||
if (parent.level !== 1) {
|
||||
setLocality(toAddressOption(parent));
|
||||
}
|
||||
if (locality || !option?.address) return;
|
||||
const localityNode = nearestLocality(option.address);
|
||||
if (localityNode) setLocality(toAddressOption(localityNode));
|
||||
};
|
||||
|
||||
const selectSuggest = (option) => {
|
||||
setSuggest(option);
|
||||
setStreet(option?.address ? toStreetOption(option.address) : null);
|
||||
setHouse(null);
|
||||
const parent = option?.address?.parent;
|
||||
if (!parent || parent.level === 1) {
|
||||
setLocality(null);
|
||||
return;
|
||||
}
|
||||
setLocality(toAddressOption(parent));
|
||||
const localityNode = option?.address ? nearestLocality(option.address) : null;
|
||||
setLocality(localityNode ? toAddressOption(localityNode) : null);
|
||||
};
|
||||
|
||||
const result = region
|
||||
? {
|
||||
region: region.address,
|
||||
locality: locality?.address ?? null,
|
||||
street: street?.address ?? null,
|
||||
house: house?.house ?? null,
|
||||
chain: addressChain(street?.address || locality?.address || region.address),
|
||||
}
|
||||
? compact
|
||||
? {
|
||||
region: compactAddress(region.address),
|
||||
locality: compactAddress(locality?.address),
|
||||
street: compactAddress(street?.address),
|
||||
house: house?.house ?? null,
|
||||
chain: addressChain(street?.address || locality?.address || region.address).map(
|
||||
compactAddress,
|
||||
),
|
||||
}
|
||||
: {
|
||||
region: region.address,
|
||||
locality: locality?.address ?? null,
|
||||
street: street?.address ?? null,
|
||||
house: house?.house ?? null,
|
||||
chain: addressChain(street?.address || locality?.address || region.address),
|
||||
}
|
||||
: null;
|
||||
|
||||
return (
|
||||
|
|
@ -387,81 +442,128 @@ export default function App() {
|
|||
<Container maxWidth="md" sx={{ py: { xs: 2, sm: 4 } }}>
|
||||
<Stack spacing={3}>
|
||||
<Paper elevation={1} sx={{ p: { xs: 2, sm: 3 } }}>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
||||
Субъект РФ → населённый пункт → улица → дом
|
||||
</Typography>
|
||||
<Stack direction="row" useFlexGap flexWrap="wrap" spacing={1} sx={{ mb: 3 }}>
|
||||
<FormControlLabel
|
||||
sx={{ mr: 1 }}
|
||||
control={
|
||||
<Switch
|
||||
checked={includeParent}
|
||||
onChange={(event) => setIncludeParent(event.target.checked)}
|
||||
size="small"
|
||||
/>
|
||||
}
|
||||
label="Выводить родителей"
|
||||
/>
|
||||
<FormControlLabel
|
||||
sx={{ mr: 1 }}
|
||||
control={
|
||||
<Switch
|
||||
checked={quickSearch}
|
||||
onChange={(event) => setQuickSearch(event.target.checked)}
|
||||
size="small"
|
||||
/>
|
||||
}
|
||||
label="Быстрый поиск"
|
||||
/>
|
||||
<FormControlLabel
|
||||
sx={{ mr: 0 }}
|
||||
control={
|
||||
<Switch
|
||||
checked={compact}
|
||||
onChange={(event) => setCompact(event.target.checked)}
|
||||
size="small"
|
||||
/>
|
||||
}
|
||||
label="Короткий вывод"
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Stack spacing={2.5}>
|
||||
<AddressSelect
|
||||
inputId="region-search"
|
||||
label="Субъект РФ"
|
||||
icon={<AccountBalanceOutlined fontSize="small" />}
|
||||
selectKey={`${String(includeParent)}-${compact}`}
|
||||
value={region}
|
||||
onChange={selectRegion}
|
||||
loadOptions={findOptions(loadRegions)}
|
||||
loadOptions={findOptions((query) =>
|
||||
loadRegions(query, { includeParent, compact }),
|
||||
)}
|
||||
placeholder="Начните вводить название субъекта РФ"
|
||||
noOptionsMessage={twoCharHint("Субъект РФ")}
|
||||
loadingMessage={() => "Ищем субъект РФ…"}
|
||||
/>
|
||||
|
||||
<AddressSelect
|
||||
inputId="suggest-search"
|
||||
label="Быстрый поиск"
|
||||
icon={<SearchOutlined fontSize="small" />}
|
||||
selectKey={region?.value || "no-region"}
|
||||
value={suggest}
|
||||
onChange={selectSuggest}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region ? loadSuggest(query, region.address.region_code) : [],
|
||||
)}
|
||||
placeholder={
|
||||
region
|
||||
? "г Владивосток Адмирала Гор"
|
||||
: "Сначала выберите субъект РФ"
|
||||
}
|
||||
noOptionsMessage={twoCharHint("Адрес")}
|
||||
loadingMessage={() => "Ищем адрес…"}
|
||||
/>
|
||||
{quickSearch ? (
|
||||
<AddressSelect
|
||||
inputId="suggest-search"
|
||||
label="Быстрый поиск"
|
||||
icon={<SearchOutlined fontSize="small" />}
|
||||
selectKey={`${region?.value || "no-region"}-${includeParent}-${compact}`}
|
||||
value={suggest}
|
||||
onChange={selectSuggest}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region
|
||||
? loadSuggest(query, region.address.region_code, { includeParent, compact })
|
||||
: [],
|
||||
)}
|
||||
placeholder={
|
||||
region ? "Поиск по адресному объекту" : "Сначала выберите субъект РФ"
|
||||
}
|
||||
noOptionsMessage={twoCharHint("Адрес")}
|
||||
loadingMessage={() => "Ищем адрес…"}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<AddressSelect
|
||||
inputId="locality-search"
|
||||
label="Населённый пункт"
|
||||
icon={<LocationCityOutlined fontSize="small" />}
|
||||
selectKey={`${region?.value || "no-region"}-${includeParent}-${compact}`}
|
||||
value={locality}
|
||||
onChange={selectLocality}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region
|
||||
? loadLocalities(query, region.address.region_code, {
|
||||
includeParent,
|
||||
compact,
|
||||
})
|
||||
: [],
|
||||
)}
|
||||
placeholder={region ? "Например, Владивосток" : "Сначала выберите субъект РФ"}
|
||||
noOptionsMessage={twoCharHint("Населённый пункт")}
|
||||
loadingMessage={() => "Ищем населённый пункт…"}
|
||||
/>
|
||||
|
||||
<AddressSelect
|
||||
inputId="locality-search"
|
||||
label="Населённый пункт"
|
||||
icon={<LocationCityOutlined fontSize="small" />}
|
||||
selectKey={region?.value || "no-region"}
|
||||
value={locality}
|
||||
onChange={selectLocality}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region ? loadLocalities(query, region.address.region_code) : [],
|
||||
)}
|
||||
placeholder={region ? "Например, Владивосток" : "Сначала выберите субъект РФ"}
|
||||
noOptionsMessage={twoCharHint("Населённый пункт")}
|
||||
loadingMessage={() => "Ищем населённый пункт…"}
|
||||
/>
|
||||
|
||||
<AddressSelect
|
||||
inputId="street-search"
|
||||
label="Улица / СНТ"
|
||||
icon={<SignpostOutlined fontSize="small" />}
|
||||
selectKey={`${region?.value || "no-region"}-${locality?.value || "no-locality"}`}
|
||||
value={street}
|
||||
onChange={selectStreet}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region
|
||||
? loadStreets(query, {
|
||||
parentId: locality?.address.id,
|
||||
regionCode: region.address.region_code,
|
||||
})
|
||||
: [],
|
||||
)}
|
||||
placeholder={
|
||||
region ? "Например, Светланская или СНТ" : "Сначала выберите субъект РФ"
|
||||
}
|
||||
noOptionsMessage={twoCharHint("Улица или СНТ")}
|
||||
loadingMessage={() => "Ищем улицу…"}
|
||||
/>
|
||||
<AddressSelect
|
||||
inputId="street-search"
|
||||
label="Улица / СНТ"
|
||||
icon={<SignpostOutlined fontSize="small" />}
|
||||
selectKey={`${region?.value || "no-region"}-${locality?.value || "no-locality"}-${includeParent}-${compact}`}
|
||||
value={street}
|
||||
onChange={selectStreet}
|
||||
disabled={!region}
|
||||
loadOptions={findOptions((query) =>
|
||||
region
|
||||
? loadStreets(query, {
|
||||
parentId: locality?.address.id,
|
||||
parentFiasId: locality?.address.fias_id,
|
||||
regionCode: region.address.region_code,
|
||||
includeParent,
|
||||
compact,
|
||||
})
|
||||
: [],
|
||||
)}
|
||||
placeholder={
|
||||
region ? "Например, Светланская или СНТ" : "Сначала выберите субъект РФ"
|
||||
}
|
||||
noOptionsMessage={twoCharHint("Улица или СНТ")}
|
||||
loadingMessage={() => "Ищем улицу…"}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AddressSelect
|
||||
inputId="house-search"
|
||||
|
|
@ -473,7 +575,7 @@ export default function App() {
|
|||
disabled={!street}
|
||||
defaultOptions
|
||||
loadOptions={findOptions((query) =>
|
||||
street ? loadHouses(query, street.address.id) : [],
|
||||
street ? loadHouses(query, street.address) : [],
|
||||
)}
|
||||
placeholder={street ? "Например, 10" : "Сначала выберите улицу или СНТ"}
|
||||
noOptionsMessage={() => "Дом не найден"}
|
||||
|
|
|
|||
Loading…
Reference in New Issue