Merge branch 'main' of github.com:med-logic/address-service
This commit is contained in:
commit
8569b546dc
|
|
@ -104,7 +104,8 @@ uv run python manage.py check
|
|||
## React-клиент
|
||||
|
||||
Простой клиент без авторизации находится в каталоге `client`. Он предоставляет
|
||||
строку поиска с автодополнением и показывает выбранный адрес в формате JSON.
|
||||
обязательный выбор региона, строку поиска с автодополнением и показывает
|
||||
выбранный адрес в формате JSON.
|
||||
|
||||
```bash
|
||||
cd client
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ from uuid import UUID
|
|||
|
||||
from django.db.models import Q
|
||||
from ninja import NinjaAPI, Query, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from .models import AddressObject, House
|
||||
|
||||
|
|
@ -155,6 +156,8 @@ def universal_search(
|
|||
params: Query[SearchParams],
|
||||
kind: Literal["region", "city", "street"] | None = None,
|
||||
):
|
||||
if not params.region_code:
|
||||
raise HttpError(422, "Для поиска необходимо указать region_code")
|
||||
levels = {
|
||||
"region": (AddressObject.Level.REGION,),
|
||||
"city": (AddressObject.Level.CITY, AddressObject.Level.SETTLEMENT),
|
||||
|
|
|
|||
|
|
@ -37,6 +37,14 @@ def test_search_city(addresses):
|
|||
assert response.json()["items"][0]["name"] == "Владивосток"
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_universal_search_requires_region(addresses):
|
||||
response = Client().get("/api-address/search", {"query": "Владивосток"})
|
||||
|
||||
assert response.status_code == 422
|
||||
assert response.json() == {"detail": "Для поиска необходимо указать region_code"}
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_streets_can_be_filtered_by_parent(addresses):
|
||||
_, city = addresses
|
||||
|
|
|
|||
|
|
@ -10,12 +10,13 @@ const levelNames = {
|
|||
8: "Улица",
|
||||
};
|
||||
|
||||
async function loadAddresses(query) {
|
||||
async function requestAddresses(path, query, regionCode) {
|
||||
const normalizedQuery = query.trim();
|
||||
if (normalizedQuery.length < 2) return [];
|
||||
|
||||
const parameters = new URLSearchParams({ query: normalizedQuery, limit: "20" });
|
||||
const response = await fetch(`${API_BASE_URL}/search?${parameters}`);
|
||||
if (regionCode) parameters.set("region_code", regionCode);
|
||||
const response = await fetch(`${API_BASE_URL}/${path}?${parameters}`);
|
||||
if (!response.ok) throw new Error(`Ошибка API: ${response.status}`);
|
||||
|
||||
const data = await response.json();
|
||||
|
|
@ -27,6 +28,9 @@ async function loadAddresses(query) {
|
|||
}));
|
||||
}
|
||||
|
||||
const loadRegions = (query) => requestAddresses("regions", query);
|
||||
const loadAddresses = (query, regionCode) => requestAddresses("search", query, regionCode);
|
||||
|
||||
const selectStyles = {
|
||||
control: (base, state) => ({
|
||||
...base,
|
||||
|
|
@ -69,19 +73,25 @@ function OptionLabel({ label, meta }) {
|
|||
}
|
||||
|
||||
export default function App() {
|
||||
const [region, setRegion] = useState(null);
|
||||
const [selected, setSelected] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const findAddresses = async (query) => {
|
||||
const findOptions = (loader) => async (query) => {
|
||||
try {
|
||||
setError("");
|
||||
return await loadAddresses(query);
|
||||
return await loader(query);
|
||||
} catch (requestError) {
|
||||
setError(requestError.message || "Не удалось выполнить поиск");
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const selectRegion = (option) => {
|
||||
setRegion(option);
|
||||
setSelected(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="page-shell">
|
||||
<section className="search-card">
|
||||
|
|
@ -89,20 +99,42 @@ export default function App() {
|
|||
<p className="eyebrow">ФИАС · адресный сервис</p>
|
||||
<h1>Найдите адрес</h1>
|
||||
<p className="subtitle">
|
||||
Начните вводить регион, город, населённый пункт или улицу.
|
||||
Сначала выберите регион, затем найдите город, населённый пункт или улицу.
|
||||
</p>
|
||||
|
||||
<div className="search-field">
|
||||
<label htmlFor="address-search">Адрес</label>
|
||||
<label htmlFor="region-search">Регион</label>
|
||||
<AsyncSelect
|
||||
inputId="region-search"
|
||||
aria-label="Выбор региона"
|
||||
cacheOptions
|
||||
defaultOptions={false}
|
||||
loadOptions={findOptions(loadRegions)}
|
||||
onChange={selectRegion}
|
||||
value={region}
|
||||
placeholder="Начните вводить название региона"
|
||||
noOptionsMessage={({ inputValue }) =>
|
||||
inputValue.trim().length < 2 ? "Введите хотя бы 2 символа" : "Регион не найден"
|
||||
}
|
||||
loadingMessage={() => "Ищем регион…"}
|
||||
formatOptionLabel={(option) => <OptionLabel {...option} />}
|
||||
styles={selectStyles}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="search-field address-field">
|
||||
<label htmlFor="address-search">Адрес в выбранном регионе</label>
|
||||
<AsyncSelect
|
||||
key={region?.value || "no-region"}
|
||||
inputId="address-search"
|
||||
aria-label="Поиск адреса"
|
||||
cacheOptions
|
||||
defaultOptions={false}
|
||||
loadOptions={findAddresses}
|
||||
isDisabled={!region}
|
||||
loadOptions={findOptions((query) => loadAddresses(query, region.address.region_code))}
|
||||
onChange={setSelected}
|
||||
value={selected}
|
||||
placeholder="Например, Владивосток или Светланская"
|
||||
placeholder={region ? "Например, Владивосток или Светланская" : "Сначала выберите регион"}
|
||||
noOptionsMessage={({ inputValue }) =>
|
||||
inputValue.trim().length < 2 ? "Введите хотя бы 2 символа" : "Ничего не найдено"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,6 +100,8 @@ h1 {
|
|||
font-weight: 750;
|
||||
}
|
||||
|
||||
.address-field { margin-top: 20px; }
|
||||
|
||||
.option-label { display: grid; gap: 3px; }
|
||||
.option-label span { font-weight: 650; }
|
||||
.option-label small { color: #858194; }
|
||||
|
|
|
|||
Loading…
Reference in New Issue