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