diff --git a/.cursor/rules/address-search-steps.mdc b/.cursor/rules/address-search-steps.mdc index 8735a47..9e3ceee 100644 --- a/.cursor/rules/address-search-steps.mdc +++ b/.cursor/rules/address-search-steps.mdc @@ -34,7 +34,7 @@ UI и API ищут жилой адрес так: **Субъект РФ → на ## Подписи в 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` в этом режиме не действует. +Код: `client/src/App.jsx`. Порядок как в адресе: крупное → мелкое. Субъект РФ (`level === 1`) не пишем. Поле показывает `option.label`. JSON: `label` — только объект, `short_label` — срез шага, `full_label` — вся цепочка с субъектом. У `GET /regions` нет `short_label`, `full_label` и `level` (они совпадают с `label` / всегда 1). Вложенный `parent` только при `include_parent=true` (по умолчанию false); `parent_id` всегда есть. `compact=true` — только `fias_id`, `label`, `short_label`, `level`, `region_code`, `full_label`; для регионов — `fias_id`, `label`, `region_code`. `include_parent` в этом режиме не действует. Полный адрес `Приморский край, Надеждинский р-н, п. Западный, тер. СНТ Маргаритка, ул. Агатовая` делится так: diff --git a/address/api.py b/address/api.py index c2a2c60..5980030 100644 --- a/address/api.py +++ b/address/api.py @@ -25,7 +25,7 @@ from .models import AddressObject, House, format_region_code api = NinjaAPI(title="FIAS Address API", version="1.0.0", docs_url="docs/") -class AddressNodeOut(Schema): +class RegionOut(Schema): id: int fias_id: UUID object_id: int | None @@ -33,10 +33,9 @@ class AddressNodeOut(Schema): name: str type_name: str label: str - level: int region_code: str kladr_id: str - parent: "AddressNodeOut | None" = None + parent: "RegionOut | None" = None @staticmethod def resolve_region_code(obj: AddressObject) -> str: @@ -47,6 +46,11 @@ class AddressNodeOut(Schema): return getattr(obj, "label", None) or address_label(obj.type_name, obj.name) +class AddressNodeOut(RegionOut): + level: int + parent: "AddressNodeOut | None" = None + + class AddressOut(AddressNodeOut): full_label: str short_label: str @@ -111,6 +115,11 @@ class SearchResponse(Schema): items: list[AddressOut] +class RegionSearchResponse(Schema): + count: int + items: list[RegionOut] + + class AddressCompactOut(Schema): fias_id: UUID label: str @@ -192,9 +201,12 @@ def present_addresses(result: SearchResult, include_parent: bool) -> SearchResul ) -def compact_address(obj) -> dict: +REGION_COMPACT_KEYS = ("fias_id", "label", "region_code") + + +def compact_address(obj, *, keys: tuple[str, ...] | None = None) -> dict: view = obj if isinstance(obj, AddressView) else AddressView(obj, include_parent=True) - return { + payload = { "fias_id": view.fias_id, "label": view.label, "short_label": view.resolved_short_label, @@ -202,14 +214,22 @@ def compact_address(obj) -> dict: "region_code": format_region_code(view.region_code), "full_label": view.resolved_full_label, } + if keys is None: + return payload + return {key: payload[key] for key in keys} -def present_search(result: SearchResult, params: SearchParams): +def present_search( + result: SearchResult, + params: SearchParams, + *, + compact_keys: tuple[str, ...] | None = None, +): if params.compact: return JsonResponse( { "count": result.count, - "items": [compact_address(item) for item in result.items], + "items": [compact_address(item, keys=compact_keys) for item in result.items], }, encoder=DjangoJSONEncoder, ) @@ -553,9 +573,13 @@ def health(request): return {"status": "ok"} -@api.get("regions", response=SearchResponse, tags=["addresses"]) +@api.get("regions", response=RegionSearchResponse, tags=["addresses"]) def regions(request, params: Query[SearchParams]): - return present_search(search((AddressObject.Level.REGION,), params), params) + return present_search( + search((AddressObject.Level.REGION,), params), + params, + compact_keys=REGION_COMPACT_KEYS, + ) @api.get("cities", response=SearchResponse, tags=["addresses"]) diff --git a/address/tests/test_api.py b/address/tests/test_api.py index c3e89b3..3140665 100644 --- a/address/tests/test_api.py +++ b/address/tests/test_api.py @@ -45,6 +45,7 @@ def test_search_city(addresses): COMPACT_KEYS = {"fias_id", "label", "short_label", "level", "region_code", "full_label"} +REGION_COMPACT_KEYS = {"fias_id", "label", "region_code"} @pytest.mark.django_db @@ -86,6 +87,17 @@ def test_compact_ignores_include_parent(addresses): assert "parent" not in item +@pytest.mark.django_db +def test_compact_regions_omit_label_slices_and_level(addresses): + response = Client().get(api_url("regions"), {"query": "прим", "compact": "true"}) + + assert response.status_code == 200 + item = response.json()["items"][0] + assert set(item) == REGION_COMPACT_KEYS + assert item["label"] == "Приморский край" + assert item["region_code"] == "25" + + @pytest.mark.django_db def test_address_label_avoids_type_repetition(addresses): region, city = addresses @@ -105,7 +117,9 @@ def test_address_label_avoids_type_repetition(addresses): ) assert region_response.json()["items"][0]["label"] == "Приморский край" - assert region_response.json()["items"][0]["full_label"] == "Приморский край" + assert "short_label" not in region_response.json()["items"][0] + assert "full_label" not in region_response.json()["items"][0] + assert "level" not in region_response.json()["items"][0] assert street_response.json()["items"][0]["label"] == "снт Актинидия" assert street_response.json()["items"][0]["short_label"] == "снт Актинидия" assert street_response.json()["items"][0]["full_label"] == "Приморский край, г Владивосток, снт Актинидия" diff --git a/client/src/App.jsx b/client/src/App.jsx index e269bec..899257f 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -110,6 +110,15 @@ function toAddressOption(address) { }; } +function toRegionOption(address) { + return { + value: address.fias_id, + label: address.label || addressTitle(address), + meta: `Субъект РФ · ${address.region_code}`, + address, + }; +} + function toStreetOption(address) { return { value: address.fias_id, @@ -153,6 +162,15 @@ function compactAddress(address) { }; } +function compactRegion(address) { + if (!address) return null; + return { + fias_id: address.fias_id, + label: address.label || addressTitle(address), + region_code: address.region_code, + }; +} + async function loadAddresses(path, query, extra, minLength = 2, toOption = toAddressOption) { const normalizedQuery = query.trim(); if (normalizedQuery.length < minLength) return []; @@ -173,10 +191,16 @@ async function loadHouses(query, street) { } const loadRegions = (query, { includeParent, compact } = {}) => - loadAddresses("regions", query, { - include_parent: String(Boolean(includeParent)), - compact: String(Boolean(compact)), - }); + loadAddresses( + "regions", + query, + { + include_parent: String(Boolean(includeParent)), + compact: String(Boolean(compact)), + }, + 2, + toRegionOption, + ); const loadLocalities = (query, regionId, { includeParent, compact } = {}) => loadAddresses("localities", query, { region_id: String(regionId), @@ -403,7 +427,7 @@ export default function App() { const result = region ? compact ? { - region: compactAddress(region.address), + region: compactRegion(region.address), locality: compactAddress(locality?.address), street: compactAddress(street?.address), house: house?.house ?? null,