init
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.idea
|
||||
.vscode
|
||||
*.log
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
@@ -0,0 +1,7 @@
|
||||
# Базовый путь API: в dev запросы уходят через vite-прокси на http://localhost:8080.
|
||||
VITE_API_BASE_URL=/api
|
||||
|
||||
# Keycloak (переопределяется при прод-сборке через переменные окружения CI).
|
||||
VITE_KEYCLOAK_URL=http://localhost:8081
|
||||
VITE_KEYCLOAK_REALM=gorodar
|
||||
VITE_KEYCLOAK_CLIENT_ID=gorodar
|
||||
@@ -0,0 +1,5 @@
|
||||
# Force LF in the repo; checkout as-is on all platforms
|
||||
* text=auto eol=lf
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.webp binary
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Сборка SPA
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Runtime: nginx + генерация конфигурации из env при старте
|
||||
FROM nginx:1.29-alpine
|
||||
|
||||
# Отключаем дефолтный template-механизм nginx (конфиг пишет наш скрипт),
|
||||
# чтобы envsubst не интерферировал с /etc/nginx/conf.d.
|
||||
RUN rm -f /etc/nginx/conf.d/default.conf /etc/nginx/templates/default.conf.template
|
||||
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY docker/app-config.sh /docker-entrypoint.d/40-app-config.sh
|
||||
RUN chmod +x /docker-entrypoint.d/40-app-config.sh
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
# Конфигурация при старте (см. docker/app-config.sh):
|
||||
# KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_CLIENT_ID — сервер авторизации;
|
||||
# BACKEND_URL — куда nginx проксирует /api;
|
||||
# API_BASE_URL — база API в SPA (по умолчанию /api).
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -0,0 +1,149 @@
|
||||
# Городар — админ-панель
|
||||
|
||||
SPA для административной части сервиса «Городар»: управление зонами, карточками
|
||||
достопримечательностей и эталонными фото, наборами и просмотр визитов.
|
||||
Работает поверх REST API бэкенда `../back` (`/api/admin/**`).
|
||||
|
||||
## Стек
|
||||
|
||||
- React 19 + TypeScript, Vite
|
||||
- Ant Design (русская локаль), dayjs
|
||||
- TanStack Query — серверное состояние
|
||||
- React Router — маршрутизация и guards по ролям
|
||||
- keycloak-js — авторизация (OAuth2 / OIDC, PKCE)
|
||||
|
||||
## Запуск (разработка)
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # http://localhost:5173
|
||||
```
|
||||
|
||||
Требуется Node.js ≥ 22.
|
||||
|
||||
Перед стартом должны быть доступны:
|
||||
|
||||
- **бэкенд** `http://localhost:8080` — в dev запросы `/api` проксируются туда
|
||||
vite-плагином (`vite.config.ts`), CORS не нужен;
|
||||
- **Keycloak** `http://localhost:8081` (realm `gorodar`).
|
||||
|
||||
### Разработка без настоящего Keycloak
|
||||
|
||||
Если Keycloak поднимать не хочется, есть мини-мок (realm `gorodar`, клиент
|
||||
`gorodar`, «логинит» как `admin` с обеими ролями, токены не подписаны):
|
||||
|
||||
```bash
|
||||
npm run mock-keycloak # отдельный терминал, поднимает http://localhost:8081
|
||||
npm run dev # второй терминал
|
||||
```
|
||||
|
||||
Мок реализует discovery, authorization (с `iss` во fragment — так требует
|
||||
keycloak-js 25+), token, userinfo и logout.
|
||||
|
||||
## Скрипты
|
||||
|
||||
| Команда | Действие |
|
||||
| ----------------------- | ----------------------------------------- |
|
||||
| `npm run dev` | dev-сервер с HMR (порт 5173) |
|
||||
| `npm run build` | production-сборка (tsc + vite) в `dist/` |
|
||||
| `npm run preview` | локальный просмотр production-сборки |
|
||||
| `npm run lint` | oxlint |
|
||||
| `npm run mock-keycloak` | мок Keycloak на 8081 для работы без IdP |
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
Для **локальной разработки** — `VITE_*` в `.env` (значения по умолчанию),
|
||||
переопределяются при сборке через переменные окружения CI. В **Docker** эти же
|
||||
настройки задаются runtime-переменными при старте контейнера (см. раздел
|
||||
Docker) — `VITE_*` там не используются.
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
| -------------------------- | ------------------------- | ------------------------------ |
|
||||
| `VITE_API_BASE_URL` | `/api` | базовый путь API |
|
||||
| `VITE_KEYCLOAK_URL` | `http://localhost:8081` | URL Keycloak |
|
||||
| `VITE_KEYCLOAK_REALM` | `gorodar` | realm |
|
||||
| `VITE_KEYCLOAK_CLIENT_ID` | `gorodar` | OAuth2-клиент |
|
||||
|
||||
## Настройка Keycloak (обязательно, один раз)
|
||||
|
||||
Бэкенд — OAuth2 resource server: проверяет подпись JWT, а также что `aud`
|
||||
содержит `gorodar` **или** `azp` = `gorodar`. Роли читаются из
|
||||
`resource_access.gorodar.roles` (клиентские роли клиента `gorodar`).
|
||||
|
||||
Для работы админки нужен **public-клиент** со включённым **Standard flow**:
|
||||
|
||||
1. Вариант А — переиспользовать клиент `gorodar`: сделать его public и включить
|
||||
Standard flow; тогда `azp` в токенах будет `gorodar` и проверка аудитории проходит.
|
||||
2. Вариант Б — создать отдельный public-клиент `gorodar-admin` (Standard flow) и
|
||||
добавить ему protocol-mapper типа **Audience** со значением `gorodar`;
|
||||
тогда `VITE_KEYCLOAK_CLIENT_ID=gorodar-admin`.
|
||||
|
||||
В обоих вариантах:
|
||||
|
||||
- Valid redirect URIs: `http://localhost:5173/*` (и URL прод-стенда);
|
||||
- Web origins: `http://localhost:5173`;
|
||||
- пользователям выдать клиентские роли клиента `gorodar`:
|
||||
- `manage_area` — разделы «Зоны», «Наборы», «Визиты»;
|
||||
- `manage_attraction` — раздел «Достопримечательности».
|
||||
|
||||
## Продакшен
|
||||
|
||||
`npm run build` кладёт статику в `dist/`. Разворачивать за реверс-прокси,
|
||||
который отдаёт статику и проксирует `/api` на бэкенд (same-origin — CORS на
|
||||
бэкенке не настраивается). Минимальный пример nginx:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
root /var/www/gorodar-admin/dist;
|
||||
location /api/ { proxy_pass http://back:8080; }
|
||||
location / { try_files /index.html =404; }
|
||||
}
|
||||
```
|
||||
|
||||
## Docker
|
||||
|
||||
Multi-stage образ: сборка Vite → nginx. Конфигурация задаётся **переменными
|
||||
окружения при старте контейнера** (не при сборке): entrypoint-скрипт
|
||||
`docker/app-config.sh` генерирует `/config.js` для SPA и конфиг nginx.
|
||||
|
||||
```bash
|
||||
docker build -t gorodar-admin-front .
|
||||
|
||||
docker run -d --name gorodar-admin -p 80:80 \
|
||||
-e KEYCLOAK_URL=https://keycloak.example.com \
|
||||
-e KEYCLOAK_REALM=gorodar \
|
||||
-e KEYCLOAK_CLIENT_ID=gorodar \
|
||||
-e BACKEND_URL=http://back:8080 \
|
||||
gorodar-admin-front
|
||||
```
|
||||
|
||||
| Переменная | По умолчанию | Назначение |
|
||||
| --------------------- | ----------------------- | ------------------------------------------- |
|
||||
| `KEYCLOAK_URL` | `http://localhost:8081` | URL Keycloak (должен быть доступен браузеру) |
|
||||
| `KEYCLOAK_REALM` | `gorodar` | realm |
|
||||
| `KEYCLOAK_CLIENT_ID` | `gorodar` | OAuth2-клиент |
|
||||
| `BACKEND_URL` | `http://localhost:8080` | куда nginx проксирует `/api` (доступен из контейнера) |
|
||||
| `API_BASE_URL` | `/api` | база API в SPA — менять не нужно, пока `/api` проксируется |
|
||||
|
||||
Нюансы:
|
||||
|
||||
- `/api` проксируется nginx'ом same-origin — CORS на бэкенде не нужен;
|
||||
`client_max_body_size 25m` покрывает multipart-лимит бэкенда (22 МБ).
|
||||
- Если бэкенд и Keycloak запущены на хосте (не в compose-сети), из контейнера
|
||||
используйте `http://host.docker.internal:8080`; при этом `KEYCLOAK_URL` в
|
||||
браузере должен оставаться `http://localhost:8081`.
|
||||
- Изменение `KEYCLOAK_CLIENT_ID` на `gorodar-admin` требует audience-mapper
|
||||
на `gorodar` (см. раздел про Keycloak).
|
||||
|
||||
## Известные ограничения (следуют из API бэкенда)
|
||||
|
||||
- Состав **DRAFT**-набора нельзя прочитать: редактор состава задаёт список
|
||||
целиком (PUT). Для ACTIVE-наборов текущий состав подтягивается из публичного
|
||||
эндпоинта активного набора зоны.
|
||||
- В админ-API нет GET достопримечательности по id: при обновлении страницы
|
||||
карточка восстанавливается из списка зоны (первая страница до 100 записей).
|
||||
- Селекторы зон/достопримечательностей подгружают до 100 элементов на уровень.
|
||||
- PATCH карточки не умеет «очищать» поля — пустые значения не отправляются.
|
||||
- Время визитов и фото отображается в UTC (как хранит бэкенд).
|
||||
- Presigned-ссылки на фото/иконки живут 1 час — страница не кэширует их дольше.
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/bin/sh
|
||||
# Entrypoint-скрипт контейнера (кладётся в /docker-entrypoint.d/ образа nginx,
|
||||
# выполняется официозным entrypoint до старта nginx).
|
||||
#
|
||||
# Генерирует из переменных окружения:
|
||||
# /usr/share/nginx/html/config.js — runtime-конфигурацию SPA (см. src/env.ts)
|
||||
# /etc/nginx/conf.d/default.conf — SPA-роутинг + проксирование /api
|
||||
#
|
||||
# Переменные окружения:
|
||||
# KEYCLOAK_URL URL Keycloak (по умолч. http://localhost:8081)
|
||||
# KEYCLOAK_REALM realm (по умолчанию gorodar)
|
||||
# KEYCLOAK_CLIENT_ID OAuth2-клиент (по умолчанию gorodar)
|
||||
# BACKEND_URL URL бэкенда для /api (по умолч. http://localhost:8080)
|
||||
# API_BASE_URL база API в SPA (по умолчанию /api — через nginx)
|
||||
set -e
|
||||
|
||||
: "${KEYCLOAK_URL:=http://localhost:8081}"
|
||||
: "${KEYCLOAK_REALM:=gorodar}"
|
||||
: "${KEYCLOAK_CLIENT_ID:=gorodar}"
|
||||
: "${BACKEND_URL:=http://localhost:8080}"
|
||||
: "${API_BASE_URL:=/api}"
|
||||
|
||||
echo "app-config: KEYCLOAK_URL=$KEYCLOAK_URL realm=$KEYCLOAK_REALM client=$KEYCLOAK_CLIENT_ID backend=$BACKEND_URL"
|
||||
|
||||
cat > /usr/share/nginx/html/config.js <<EOF
|
||||
window.__APP_CONFIG__ = {
|
||||
apiBaseUrl: "${API_BASE_URL}",
|
||||
keycloak: {
|
||||
url: "${KEYCLOAK_URL}",
|
||||
realm: "${KEYCLOAK_REALM}",
|
||||
clientId: "${KEYCLOAK_CLIENT_ID}"
|
||||
}
|
||||
};
|
||||
EOF
|
||||
|
||||
# В nginx.conf экранируем $-переменные nginx от подстановки шеллом.
|
||||
cat > /etc/nginx/conf.d/default.conf <<EOF
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Runtime-конфиг не кэшировать — он зависит от окружения контейнера.
|
||||
location = /config.js {
|
||||
add_header Cache-Control "no-store";
|
||||
}
|
||||
|
||||
# Проксирование на бэкенд: same-origin, CORS не нужен.
|
||||
# Лимит запроса 25m — чуть выше multipart-лимита бэкенда (22MB).
|
||||
location /api/ {
|
||||
proxy_pass ${BACKEND_URL};
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
client_max_body_size 25m;
|
||||
}
|
||||
|
||||
# SPA-роутинг: все неизвестные пути отдают index.html.
|
||||
location / {
|
||||
try_files \$uri /index.html;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<script src="/config.js"></script>
|
||||
<title>Городар — админ-панель</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2755
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "gorodar-admin-front",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview",
|
||||
"mock-keycloak": "node scripts/mock-keycloak.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.3.4",
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"antd": "^6.6.5",
|
||||
"axios": "^1.20.0",
|
||||
"dayjs": "^1.11.23",
|
||||
"keycloak-js": "^26.2.4",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"oxlint": "^1.81.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Runtime-конфигурация приложения. В dev пусто (используются VITE_* из .env);
|
||||
// в Docker этот файл перезаписывается entrypoint-скриптом при старте контейнера.
|
||||
window.__APP_CONFIG__ = {};
|
||||
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" rx="6" fill="#1677ff"/>
|
||||
<path d="M6 26h20v2H6zM8 26h16l-1.5-9h-13zM15 9h2v4h-2z" fill="#fff"/>
|
||||
<path d="M16 4l8 5H8z" fill="#fff"/>
|
||||
<circle cx="16" cy="7" r="1.4" fill="#1677ff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 285 B |
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Мини-мок Keycloak для локальной разработки админки без настоящего Keycloak.
|
||||
*
|
||||
* Поднимает http://localhost:8081 c realm `gorodar` и клиентом `gorodar`,
|
||||
* автоматически «логинит» любого пользователя как admin с обеими ролями
|
||||
* (manage_area, manage_attraction). Токены не подписаны — только для UI-разработки.
|
||||
*
|
||||
* Использование: node scripts/mock-keycloak.mjs (затем npm run dev)
|
||||
*/
|
||||
import { createServer } from 'node:http'
|
||||
|
||||
const PORT = Number(process.env.MOCK_PORT ?? 8081)
|
||||
const REALM = 'gorodar'
|
||||
const CLIENT_ID = 'gorodar'
|
||||
const USER = 'admin'
|
||||
const ROLES = ['manage_area', 'manage_attraction']
|
||||
|
||||
const base = `http://localhost:${PORT}`
|
||||
const realmBase = `${base}/realms/${REALM}`
|
||||
const oidcPath = `/realms/${REALM}/protocol/openid-connect`
|
||||
|
||||
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url')
|
||||
|
||||
function makeToken(ttlSeconds) {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const header = b64url({ alg: 'HS256', typ: 'JWT' })
|
||||
const payload = b64url({
|
||||
iss: realmBase,
|
||||
sub: 'mock-user-id',
|
||||
aud: CLIENT_ID,
|
||||
azp: CLIENT_ID,
|
||||
iat: now,
|
||||
exp: now + ttlSeconds,
|
||||
preferred_username: USER,
|
||||
name: 'Админ Мок',
|
||||
resource_access: { [CLIENT_ID]: { roles: ROLES } },
|
||||
})
|
||||
return `${header}.${payload}.mock-signature`
|
||||
}
|
||||
|
||||
function sendJson(res, req, body, status = 200) {
|
||||
const headers = { 'Content-Type': 'application/json' }
|
||||
// keycloak-js отправляет token-запрос с credentials, поэтому эхаем Origin
|
||||
// вместо '*': wildcard не сочетается с Access-Control-Allow-Credentials.
|
||||
const origin = req.headers.origin
|
||||
if (origin) {
|
||||
headers['Access-Control-Allow-Origin'] = origin
|
||||
headers['Access-Control-Allow-Credentials'] = 'true'
|
||||
headers.Vary = 'Origin'
|
||||
}
|
||||
res.writeHead(status, headers)
|
||||
res.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? '/', base)
|
||||
console.log(new Date().toISOString(), req.method, url.pathname + (url.search || ''))
|
||||
|
||||
// discovery
|
||||
if (url.pathname === `/realms/${REALM}/.well-known/openid-configuration`) {
|
||||
return sendJson(res, req, {
|
||||
issuer: realmBase,
|
||||
authorization_endpoint: `${realmBase}/protocol/openid-connect/auth`,
|
||||
token_endpoint: `${realmBase}/protocol/openid-connect/token`,
|
||||
userinfo_endpoint: `${realmBase}/protocol/openid-connect/userinfo`,
|
||||
end_session_endpoint: `${realmBase}/protocol/openid-connect/logout`,
|
||||
jwks_uri: `${realmBase}/protocol/openid-connect/certs`,
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
})
|
||||
}
|
||||
|
||||
// авторизация: сразу возвращаем код в redirect_uri (во fragment — keycloak-js
|
||||
// по умолчанию использует response_mode=fragment; iss обязателен для keycloak-js 25+)
|
||||
if (url.pathname === `${oidcPath}/auth`) {
|
||||
const redirect = new URL(url.searchParams.get('redirect_uri') ?? base)
|
||||
const fragment = new URLSearchParams({
|
||||
state: url.searchParams.get('state') ?? '',
|
||||
session_state: 'mock-session',
|
||||
code: 'mock-code',
|
||||
iss: realmBase,
|
||||
})
|
||||
res.writeHead(302, { Location: `${redirect.toString()}#${fragment.toString()}` })
|
||||
return res.end()
|
||||
}
|
||||
|
||||
// обмен кода на токены
|
||||
if (url.pathname === `${oidcPath}/token` && req.method === 'POST') {
|
||||
return sendJson(res, req, {
|
||||
access_token: makeToken(300),
|
||||
expires_in: 300,
|
||||
refresh_expires_in: 1800,
|
||||
refresh_token: makeToken(1800),
|
||||
token_type: 'Bearer',
|
||||
'not-before-policy': 0,
|
||||
session_state: 'mock-session',
|
||||
scope: 'openid profile',
|
||||
})
|
||||
}
|
||||
|
||||
if (url.pathname === `${oidcPath}/userinfo`) {
|
||||
return sendJson(res, req, { sub: 'mock-user-id', preferred_username: USER })
|
||||
}
|
||||
|
||||
if (url.pathname === `${oidcPath}/logout`) {
|
||||
const redirect = url.searchParams.get('post_logout_redirect_uri') ?? url.searchParams.get('redirect_uri') ?? base
|
||||
res.writeHead(302, { Location: redirect })
|
||||
return res.end()
|
||||
}
|
||||
|
||||
if (url.pathname === `/realms/${REALM}/`) {
|
||||
return sendJson(res, req, { realm: REALM, public: true, 'token-service': realmBase + '/protocol/openid-connect' })
|
||||
}
|
||||
|
||||
sendJson(res, req, { error: 'not_found' }, 404)
|
||||
})
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`Mock Keycloak: ${realmBase} (user=${USER}, roles=${ROLES.join(', ')})`)
|
||||
})
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
import { useAuth } from '@/auth/AuthContext'
|
||||
import { RequireRole } from '@/auth/RequireRole'
|
||||
import { ROLE_MANAGE_AREA, ROLE_MANAGE_ATTRACTION } from '@/auth/roles'
|
||||
import { AdminLayout } from '@/layouts/AdminLayout'
|
||||
import { AreaListPage } from '@/pages/areas/AreaListPage'
|
||||
import { AttractionDetailPage } from '@/pages/attractions/AttractionDetailPage'
|
||||
import { AttractionListPage } from '@/pages/attractions/AttractionListPage'
|
||||
import { ForbiddenPage } from '@/pages/ForbiddenPage'
|
||||
import { NotFoundPage } from '@/pages/NotFoundPage'
|
||||
import { SetListPage } from '@/pages/sets/SetListPage'
|
||||
import { VisitListPage } from '@/pages/visits/VisitListPage'
|
||||
|
||||
function HomeRedirect() {
|
||||
const { hasRole } = useAuth()
|
||||
if (hasRole(ROLE_MANAGE_AREA)) return <Navigate to="/areas" replace />
|
||||
if (hasRole(ROLE_MANAGE_ATTRACTION)) return <Navigate to="/attractions" replace />
|
||||
return <Navigate to="/forbidden" replace />
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route element={<AdminLayout />}>
|
||||
<Route index element={<HomeRedirect />} />
|
||||
<Route
|
||||
path="/areas"
|
||||
element={
|
||||
<RequireRole role={ROLE_MANAGE_AREA}>
|
||||
<AreaListPage />
|
||||
</RequireRole>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/attractions"
|
||||
element={
|
||||
<RequireRole role={ROLE_MANAGE_ATTRACTION}>
|
||||
<AttractionListPage />
|
||||
</RequireRole>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/attractions/:id"
|
||||
element={
|
||||
<RequireRole role={ROLE_MANAGE_ATTRACTION}>
|
||||
<AttractionDetailPage />
|
||||
</RequireRole>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/sets"
|
||||
element={
|
||||
<RequireRole role={ROLE_MANAGE_AREA}>
|
||||
<SetListPage />
|
||||
</RequireRole>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/visits"
|
||||
element={
|
||||
<RequireRole role={ROLE_MANAGE_AREA}>
|
||||
<VisitListPage />
|
||||
</RequireRole>
|
||||
}
|
||||
/>
|
||||
<Route path="/forbidden" element={<ForbiddenPage />} />
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { http } from '@/api/http'
|
||||
import type { Area, CreateAreaRequest, Page, UpdateAreaRequest } from '@/api/types'
|
||||
|
||||
export interface AreaListParams {
|
||||
/** null/undefined — корневые зоны. */
|
||||
parentId?: string | null
|
||||
page?: number
|
||||
size?: number
|
||||
/** Например 'name,asc'. */
|
||||
sort?: string
|
||||
}
|
||||
|
||||
export async function fetchAreas(params: AreaListParams = {}): Promise<Page<Area>> {
|
||||
const resp = await http.get<Page<Area>>('/admin/areas', {
|
||||
params: {
|
||||
'parent-id': params.parentId ?? undefined,
|
||||
page: params.page,
|
||||
size: params.size,
|
||||
sort: params.sort,
|
||||
},
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function createArea(request: CreateAreaRequest): Promise<Area> {
|
||||
const resp = await http.post<Area>('/admin/areas', request)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function updateArea(id: string, request: UpdateAreaRequest): Promise<Area> {
|
||||
const resp = await http.patch<Area>(`/admin/areas/${id}`, request)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
/** Публичный эндпоинт (permitAll) — источник имени зоны, когда путь в дереве не загружен. */
|
||||
export async function fetchAreaName(id: string): Promise<string> {
|
||||
const resp = await http.get<{ id: string; name: string }>(`/areas/${id}`)
|
||||
return resp.data.name
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { http } from '@/api/http'
|
||||
import type {
|
||||
Attraction,
|
||||
AttractionCard,
|
||||
CreateAttractionRequest,
|
||||
Page,
|
||||
Photo,
|
||||
UpdateAttractionRequest,
|
||||
} from '@/api/types'
|
||||
|
||||
export interface AttractionListParams {
|
||||
areaId: string
|
||||
page?: number
|
||||
size?: number
|
||||
sort?: string
|
||||
}
|
||||
|
||||
export async function fetchAttractions(params: AttractionListParams): Promise<Page<Attraction>> {
|
||||
const resp = await http.get<Page<Attraction>>('/admin/attractions', {
|
||||
params: {
|
||||
'area-id': params.areaId,
|
||||
page: params.page,
|
||||
size: params.size,
|
||||
sort: params.sort,
|
||||
},
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function createAttraction(request: CreateAttractionRequest): Promise<Attraction> {
|
||||
const resp = await http.post<Attraction>('/admin/attractions', request)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function updateAttraction(
|
||||
id: string,
|
||||
request: UpdateAttractionRequest,
|
||||
): Promise<Attraction> {
|
||||
const resp = await http.patch<Attraction>(`/admin/attractions/${id}`, request)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function uploadIcon(id: string, file: File): Promise<Attraction> {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const resp = await http.post<Attraction>(`/admin/attractions/${id}/icon`, form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
/** Публичная карточка (permitAll) — источник presigned iconUrl для превью. */
|
||||
export async function fetchAttractionCard(id: string): Promise<AttractionCard> {
|
||||
const resp = await http.get<AttractionCard>(`/attractions/${id}`)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function fetchPhotos(attractionId: string): Promise<Photo[]> {
|
||||
const resp = await http.get<Photo[]>(`/admin/attractions/${attractionId}/photos`)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function uploadPhoto(
|
||||
attractionId: string,
|
||||
file: File,
|
||||
sortOrder?: number,
|
||||
): Promise<Photo> {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const resp = await http.post<Photo>(`/admin/attractions/${attractionId}/photos`, form, {
|
||||
params: { 'sort-order': sortOrder },
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function updatePhotoSortOrder(
|
||||
attractionId: string,
|
||||
photoId: string,
|
||||
sortOrder: number,
|
||||
): Promise<Photo> {
|
||||
const resp = await http.patch<Photo>(
|
||||
`/admin/attractions/${attractionId}/photos/${photoId}`,
|
||||
{ sortOrder },
|
||||
)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
/** Перезапустить извлечение признаков через сервис open_cv. */
|
||||
export async function recalcPhotoFeatures(
|
||||
attractionId: string,
|
||||
photoId: string,
|
||||
): Promise<Photo> {
|
||||
const resp = await http.post<Photo>(
|
||||
`/admin/attractions/${attractionId}/photos/${photoId}/features`,
|
||||
)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function deletePhoto(attractionId: string, photoId: string): Promise<void> {
|
||||
await http.delete(`/admin/attractions/${attractionId}/photos/${photoId}`)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { isAxiosError } from 'axios'
|
||||
import { notify } from '@/api/notify'
|
||||
|
||||
/** Нормализованная ошибка API: код из тела ApiError + человекочитаемое сообщение. */
|
||||
export interface ApiErrorInfo {
|
||||
status: number
|
||||
code?: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export function toApiError(e: unknown): ApiErrorInfo {
|
||||
if (isAxiosError(e)) {
|
||||
const status = e.response?.status ?? 0
|
||||
const data = e.response?.data as { code?: string; message?: string } | undefined
|
||||
|
||||
if (status === 0) {
|
||||
return { status, message: 'Нет соединения с сервером. Убедитесь, что бэкенд запущен.' }
|
||||
}
|
||||
if (status === 401) {
|
||||
return { status, code: data?.code, message: 'Сессия истекла. Выполните вход заново.' }
|
||||
}
|
||||
if (status === 403) {
|
||||
return { status, code: data?.code, message: 'Недостаточно прав для этого действия.' }
|
||||
}
|
||||
if (data?.code && data.message) {
|
||||
// Основной случай: бэкенд отдаёт { code, message, timestamp } с русским message.
|
||||
return { status, code: data.code, message: data.message }
|
||||
}
|
||||
if (status >= 500) {
|
||||
return { status, message: 'Внутренняя ошибка сервера. Попробуйте позже.' }
|
||||
}
|
||||
return {
|
||||
status,
|
||||
code: data?.code,
|
||||
message: data?.message ?? `Ошибка запроса (HTTP ${status})`,
|
||||
}
|
||||
}
|
||||
return { status: 0, message: e instanceof Error ? e.message : 'Неизвестная ошибка' }
|
||||
}
|
||||
|
||||
/** Показать ошибку API пользователю (notification). */
|
||||
export function notifyApiError(e: unknown, title = 'Ошибка'): void {
|
||||
const info = toApiError(e)
|
||||
notify('error', title, info.message)
|
||||
}
|
||||
|
||||
export function notifySuccess(message: string, description?: string): void {
|
||||
notify('success', message, description)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import axios, { type InternalAxiosRequestConfig } from 'axios'
|
||||
import { env } from '@/env'
|
||||
import { getToken, keycloak, login } from '@/auth/keycloak'
|
||||
|
||||
export const http = axios.create({
|
||||
baseURL: env.apiBaseUrl,
|
||||
})
|
||||
|
||||
interface RetriableConfig extends InternalAxiosRequestConfig {
|
||||
_retried?: boolean
|
||||
}
|
||||
|
||||
http.interceptors.request.use(async (config) => {
|
||||
if (keycloak.authenticated) {
|
||||
config.headers.Authorization = `Bearer ${await getToken()}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error: unknown) => {
|
||||
if (axios.isAxiosError(error) && error.response?.status === 401) {
|
||||
const original = error.config as RetriableConfig | undefined
|
||||
if (original && !original._retried && keycloak.authenticated) {
|
||||
original._retried = true
|
||||
try {
|
||||
// Минимальный minValidity фактически форсирует refresh.
|
||||
await keycloak.updateToken(9999)
|
||||
return http.request(original)
|
||||
} catch {
|
||||
login()
|
||||
}
|
||||
}
|
||||
}
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export type NotifyKind = 'success' | 'error' | 'info'
|
||||
|
||||
export type Notifier = (kind: NotifyKind, message: ReactNode, description?: ReactNode) => void
|
||||
|
||||
// Мост между axios-перехватчиками (вне React) и antd notification (внутри React).
|
||||
// Корневой компонент регистрирует here функцию из App.useApp().
|
||||
let notifier: Notifier | null = null
|
||||
|
||||
export function setNotifier(fn: Notifier | null): void {
|
||||
notifier = fn
|
||||
}
|
||||
|
||||
export function notify(kind: NotifyKind, message: ReactNode, description?: ReactNode): void {
|
||||
notifier?.(kind, message, description)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { http } from '@/api/http'
|
||||
import type { ActiveSet, AttractionSet } from '@/api/types'
|
||||
|
||||
export async function fetchSets(areaId: string): Promise<AttractionSet[]> {
|
||||
const resp = await http.get<AttractionSet[]>(`/admin/areas/${areaId}/sets`)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function createSet(areaId: string, name: string): Promise<AttractionSet> {
|
||||
const resp = await http.post<AttractionSet>(`/admin/areas/${areaId}/sets`, { name })
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function renameSet(id: string, name: string): Promise<AttractionSet> {
|
||||
const resp = await http.patch<AttractionSet>(`/admin/sets/${id}`, { name })
|
||||
return resp.data
|
||||
}
|
||||
|
||||
/** Полная замена состава; порядок id задаёт порядок элементов. */
|
||||
export async function putSetItems(id: string, attractionIds: string[]): Promise<AttractionSet> {
|
||||
const resp = await http.put<AttractionSet>(`/admin/sets/${id}/items`, { attractionIds })
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function removeSetItem(id: string, attractionId: string): Promise<void> {
|
||||
await http.delete(`/admin/sets/${id}/items/${attractionId}`)
|
||||
}
|
||||
|
||||
export async function activateSet(id: string): Promise<AttractionSet> {
|
||||
const resp = await http.post<AttractionSet>(`/admin/sets/${id}/activate`)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export async function archiveSet(id: string): Promise<AttractionSet> {
|
||||
const resp = await http.post<AttractionSet>(`/admin/sets/${id}/archive`)
|
||||
return resp.data
|
||||
}
|
||||
|
||||
/** Публичный активный набор зоны — единственный способ прочитать состав набора. */
|
||||
export async function fetchActiveSet(areaId: string): Promise<ActiveSet> {
|
||||
const resp = await http.get<ActiveSet>(`/areas/${areaId}/active-set`)
|
||||
return resp.data
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Типы, зеркалящие DTO бэкенда (ru.gorodar.api.dto).
|
||||
* JSON-поля camelCase, query-параметры kebab-case — конвенция бэкенда.
|
||||
*/
|
||||
|
||||
/** Spring Data Page (сериализация PageImpl). */
|
||||
export interface Page<T> {
|
||||
content: T[]
|
||||
totalElements: number
|
||||
totalPages: number
|
||||
number: number
|
||||
size: number
|
||||
first: boolean
|
||||
last: boolean
|
||||
empty: boolean
|
||||
}
|
||||
|
||||
// ---------- Зоны ----------
|
||||
|
||||
export interface Area {
|
||||
id: string
|
||||
parentId: string | null
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface CreateAreaRequest {
|
||||
name: string
|
||||
parentId?: string | null
|
||||
}
|
||||
|
||||
/** Частичное обновление: отсутствующее поле = «не менять». */
|
||||
export interface UpdateAreaRequest {
|
||||
name?: string
|
||||
parentId?: string | null
|
||||
}
|
||||
|
||||
// ---------- Достопримечательности ----------
|
||||
|
||||
export type CvProfile = 'facade' | 'monument' | 'repetitive'
|
||||
|
||||
export interface Attraction {
|
||||
id: string
|
||||
areaId: string
|
||||
name: string
|
||||
/** Сырой ключ S3, не URL (для превью используется публичный эндпоинт). */
|
||||
iconKey: string | null
|
||||
about: string | null
|
||||
latitude: number | null
|
||||
longitude: number | null
|
||||
address: string | null
|
||||
facts: string[] | null
|
||||
cvProfile: CvProfile
|
||||
photoCount: number
|
||||
}
|
||||
|
||||
export interface CreateAttractionRequest {
|
||||
areaId: string
|
||||
name: string
|
||||
cvProfile: CvProfile
|
||||
about?: string
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
address?: string
|
||||
facts?: string[]
|
||||
}
|
||||
|
||||
export interface UpdateAttractionRequest {
|
||||
name?: string
|
||||
cvProfile?: CvProfile
|
||||
about?: string
|
||||
latitude?: number
|
||||
longitude?: number
|
||||
address?: string
|
||||
facts?: string[]
|
||||
}
|
||||
|
||||
// ---------- Эталонные фото ----------
|
||||
|
||||
export interface Photo {
|
||||
id: string
|
||||
/** Presigned GET URL (TTL 1 час) — не кэшировать надолго. */
|
||||
photoUrl: string
|
||||
sortOrder: number
|
||||
featureFormatVersion: number
|
||||
algoId: string
|
||||
keypointsCount: number
|
||||
/** UTC, ISO-8601 без зоны. */
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
// ---------- Наборы ----------
|
||||
|
||||
export type SetStatus = 'DRAFT' | 'ACTIVE' | 'ARCHIVED'
|
||||
|
||||
export interface AttractionSet {
|
||||
id: string
|
||||
areaId: string
|
||||
name: string
|
||||
status: SetStatus
|
||||
itemCount: number
|
||||
}
|
||||
|
||||
/** Из публичного GET /areas/{areaId}/active-set — источник текущего состава ACTIVE-набора. */
|
||||
export interface ActiveSet {
|
||||
id: string
|
||||
name: string
|
||||
attractions: { id: string; name: string; iconUrl: string | null; visited: boolean }[]
|
||||
}
|
||||
|
||||
// ---------- Визиты ----------
|
||||
|
||||
export type Verdict = 'match' | 'uncertain' | 'no_match'
|
||||
|
||||
export interface Visit {
|
||||
id: string
|
||||
attractionId: string
|
||||
attractionName: string
|
||||
/** UTC, ISO-8601 без зоны. */
|
||||
visitedAt: string
|
||||
verdict: Verdict
|
||||
confidence: number
|
||||
}
|
||||
|
||||
export interface VisitFilter {
|
||||
areaId?: string
|
||||
attractionId?: string
|
||||
userId?: string
|
||||
/** YYYY-MM-DD, включительно. */
|
||||
from?: string
|
||||
/** YYYY-MM-DD, включительно (бэкенд трактует как дату «по»). */
|
||||
to?: string
|
||||
}
|
||||
|
||||
// ---------- Публичный каталог ----------
|
||||
|
||||
export interface AttractionCard {
|
||||
id: string
|
||||
name: string
|
||||
iconUrl: string | null
|
||||
about: string | null
|
||||
latitude: number | null
|
||||
longitude: number | null
|
||||
address: string | null
|
||||
facts: string[] | null
|
||||
photoUrl: string | null
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { http } from '@/api/http'
|
||||
import type { Page, Visit, VisitFilter } from '@/api/types'
|
||||
|
||||
export interface VisitListParams {
|
||||
page?: number
|
||||
size?: number
|
||||
/** Например 'visitedAt,desc'. */
|
||||
sort?: string
|
||||
}
|
||||
|
||||
/** Фильтр передаётся телом запроса, пагинация — query-параметрами (так задумано API). */
|
||||
export async function fetchVisits(
|
||||
filter: VisitFilter,
|
||||
params: VisitListParams = {},
|
||||
): Promise<Page<Visit>> {
|
||||
const body: VisitFilter = {}
|
||||
if (filter.areaId) body.areaId = filter.areaId
|
||||
if (filter.attractionId) body.attractionId = filter.attractionId
|
||||
if (filter.userId && filter.userId.trim()) body.userId = filter.userId.trim()
|
||||
if (filter.from) body.from = filter.from
|
||||
if (filter.to) body.to = filter.to
|
||||
|
||||
const resp = await http.post<Page<Visit>>('/admin/visits', body, {
|
||||
params: { page: params.page, size: params.size, sort: params.sort },
|
||||
})
|
||||
return resp.data
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
|
||||
import { initAuth, login, logout, readProfile } from '@/auth/keycloak'
|
||||
|
||||
interface AuthContextValue {
|
||||
/** Keycloak инициализацию завершил (успешно или с ошибкой). */
|
||||
ready: boolean
|
||||
authenticated: boolean
|
||||
userName: string
|
||||
roles: string[]
|
||||
hasRole: (role: string) => boolean
|
||||
login: () => void
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
interface AuthState {
|
||||
ready: boolean
|
||||
authenticated: boolean
|
||||
userName: string
|
||||
roles: string[]
|
||||
}
|
||||
|
||||
const initialState: AuthState = { ready: false, authenticated: false, userName: '', roles: [] }
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<AuthState>(initialState)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
initAuth()
|
||||
.then((authenticated) => {
|
||||
if (cancelled) return
|
||||
setState({
|
||||
ready: true,
|
||||
authenticated,
|
||||
...(authenticated ? readProfile() : { userName: '', roles: [] }),
|
||||
})
|
||||
})
|
||||
.catch((err) => {
|
||||
// Keycloak недоступен и т.п. — показываем экран ошибки вместо редиректа-цикла.
|
||||
console.error('Keycloak init failed', err)
|
||||
if (!cancelled) setState({ ready: true, authenticated: false, userName: '', roles: [] })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
...state,
|
||||
hasRole: (role) => state.roles.includes(role),
|
||||
login,
|
||||
logout,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth должен использоваться внутри <AuthProvider>')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from '@/auth/AuthContext'
|
||||
|
||||
/** Пропускает детей только при наличии роли, иначе — на страницу «нет доступа». */
|
||||
export function RequireRole({ role, children }: { role: string; children: ReactNode }) {
|
||||
const { ready, authenticated, hasRole } = useAuth()
|
||||
|
||||
if (!ready) return null
|
||||
if (!authenticated || !hasRole(role)) return <Navigate to="/forbidden" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import Keycloak from 'keycloak-js'
|
||||
import { env } from '@/env'
|
||||
|
||||
export const keycloak = new Keycloak({
|
||||
url: env.keycloak.url,
|
||||
realm: env.keycloak.realm,
|
||||
clientId: env.keycloak.clientId,
|
||||
})
|
||||
|
||||
let initPromise: Promise<boolean> | null = null
|
||||
|
||||
export interface UserProfile {
|
||||
userName: string
|
||||
roles: string[]
|
||||
}
|
||||
|
||||
/** Инициализация Keycloak (single-flight: повторные вызовы возвращают тот же промис). */
|
||||
export function initAuth(): Promise<boolean> {
|
||||
if (!initPromise) {
|
||||
initPromise = keycloak.init({
|
||||
onLoad: 'login-required',
|
||||
pkceMethod: 'S256',
|
||||
checkLoginIframe: false,
|
||||
})
|
||||
}
|
||||
return initPromise
|
||||
}
|
||||
|
||||
/** Актуальный access-токен; при истечении в ближайшие 30 с — молча обновляет. */
|
||||
export async function getToken(): Promise<string> {
|
||||
if (!keycloak.authenticated) return ''
|
||||
await keycloak.updateToken(30)
|
||||
return keycloak.token ?? ''
|
||||
}
|
||||
|
||||
export function readProfile(): UserProfile {
|
||||
const parsed = keycloak.tokenParsed as Record<string, unknown> | undefined
|
||||
const resourceAccess = parsed?.['resource_access'] as
|
||||
| Record<string, { roles?: string[] }>
|
||||
| undefined
|
||||
const roles = resourceAccess?.[env.keycloak.clientId]?.roles ?? []
|
||||
const userName =
|
||||
(parsed?.['preferred_username'] as string | undefined) ??
|
||||
(parsed?.['name'] as string | undefined) ??
|
||||
'пользователь'
|
||||
return { userName, roles }
|
||||
}
|
||||
|
||||
export function login(): void {
|
||||
void keycloak.login()
|
||||
}
|
||||
|
||||
export function logout(): void {
|
||||
void keycloak.logout({ redirectUri: window.location.origin })
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/** Ключевые роли (клиентские роли Keycloak клиента gorodar). */
|
||||
export const ROLE_MANAGE_AREA = 'manage_area'
|
||||
export const ROLE_MANAGE_ATTRACTION = 'manage_attraction'
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
|
||||
import { TreeSelect, type TreeSelectProps } from 'antd'
|
||||
import { fetchAreas, fetchAreaName } from '@/api/areas'
|
||||
import { notifyApiError } from '@/api/errors'
|
||||
|
||||
const ROOT_KEY = '__root__'
|
||||
|
||||
interface AreaTreeNode {
|
||||
value: string
|
||||
title: string
|
||||
isLeaf?: boolean
|
||||
children?: AreaTreeNode[]
|
||||
}
|
||||
|
||||
interface AreaTreeSelectProps {
|
||||
value?: string | null
|
||||
onChange?: (value: string | null) => void
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
allowClear?: boolean
|
||||
style?: CSSProperties
|
||||
/** Скрыть эту зону (например, саму зону при смене родителя). */
|
||||
excludeId?: string
|
||||
/** Показать виртуальный узел «Корень»: его выбор означает parentId = null. */
|
||||
rootAsOption?: boolean
|
||||
}
|
||||
|
||||
function filterTree(nodes: AreaTreeNode[], excludeId?: string): AreaTreeNode[] {
|
||||
if (!excludeId) return nodes
|
||||
return nodes
|
||||
.filter((n) => n.value !== excludeId)
|
||||
.map((n) => ({
|
||||
...n,
|
||||
children: n.children ? filterTree(n.children, excludeId) : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
function containsValue(nodes: AreaTreeNode[], value: string): boolean {
|
||||
return nodes.some(
|
||||
(n) => n.value === value || (n.children ? containsValue(n.children, value) : false),
|
||||
)
|
||||
}
|
||||
|
||||
function insertChildren(
|
||||
nodes: AreaTreeNode[],
|
||||
key: string,
|
||||
children: AreaTreeNode[],
|
||||
): AreaTreeNode[] {
|
||||
return nodes.map((n) => {
|
||||
if (n.value === key) return { ...n, children }
|
||||
if (n.children) return { ...n, children: insertChildren(n.children, key, children) }
|
||||
return n
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Лениво загружаемый TreeSelect зон: дети подтягиваются при раскрытии узла
|
||||
* (GET /admin/areas?parent-id=…&size=100 — глубже 100 детей на уровень не видно).
|
||||
* Если значение задано снаружи (например, из URL) и путь до него ещё не загружен,
|
||||
* имя зоны разрешается через публичный GET /areas/{id}.
|
||||
*/
|
||||
export function AreaTreeSelect({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'Выберите зону',
|
||||
disabled,
|
||||
allowClear,
|
||||
style,
|
||||
excludeId,
|
||||
rootAsOption,
|
||||
}: AreaTreeSelectProps) {
|
||||
const [roots, setRoots] = useState<AreaTreeNode[]>([])
|
||||
const [resolvedName, setResolvedName] = useState<string | null>(null)
|
||||
const loadedKeys = useRef(new Set<string>())
|
||||
const rootLoaded = useRef(false)
|
||||
const resolvedValues = useRef(new Set<string>())
|
||||
|
||||
useEffect(() => {
|
||||
if (rootLoaded.current) return
|
||||
rootLoaded.current = true
|
||||
void loadChildren(ROOT_KEY)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function loadChildren(key: string): Promise<void> {
|
||||
if (loadedKeys.current.has(key)) return
|
||||
loadedKeys.current.add(key)
|
||||
try {
|
||||
const page = await fetchAreas({
|
||||
parentId: key === ROOT_KEY ? null : key,
|
||||
size: 100,
|
||||
sort: 'name,asc',
|
||||
})
|
||||
const children: AreaTreeNode[] = page.content.map((area) => ({
|
||||
value: area.id,
|
||||
title: area.name,
|
||||
isLeaf: false,
|
||||
}))
|
||||
if (key === ROOT_KEY) setRoots(children)
|
||||
else setRoots((prev) => insertChildren(prev, key, children))
|
||||
} catch (e) {
|
||||
loadedKeys.current.delete(key)
|
||||
notifyApiError(e, 'Не удалось загрузить зоны')
|
||||
}
|
||||
}
|
||||
|
||||
const needsNameResolution = value != null && value !== ROOT_KEY && !containsValue(roots, value)
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsNameResolution || !value || resolvedValues.current.has(value)) return
|
||||
resolvedValues.current.add(value)
|
||||
let cancelled = false
|
||||
fetchAreaName(value)
|
||||
.then((name) => {
|
||||
if (!cancelled) setResolvedName(name)
|
||||
})
|
||||
.catch((e) => notifyApiError(e, 'Не удалось получить имя зоны'))
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [needsNameResolution, value])
|
||||
|
||||
const treeData = useMemo<AreaTreeNode[]>(() => {
|
||||
const visible = filterTree(roots, excludeId)
|
||||
const withSynthetic =
|
||||
value && resolvedName && !containsValue(visible, value)
|
||||
? [{ value, title: resolvedName, isLeaf: true }, ...visible]
|
||||
: visible
|
||||
if (rootAsOption) {
|
||||
return [{ value: ROOT_KEY, title: 'Корень', isLeaf: false, children: withSynthetic }]
|
||||
}
|
||||
return withSynthetic
|
||||
}, [roots, excludeId, rootAsOption, value, resolvedName])
|
||||
|
||||
const handleChange: TreeSelectProps['onChange'] = (selected) => {
|
||||
if (selected == null || selected === '') {
|
||||
onChange?.(null)
|
||||
return
|
||||
}
|
||||
onChange?.(String(selected))
|
||||
}
|
||||
|
||||
return (
|
||||
<TreeSelect
|
||||
style={style ?? { width: 320 }}
|
||||
value={value ?? undefined}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
allowClear={allowClear}
|
||||
treeData={treeData}
|
||||
treeDefaultExpandAll={false}
|
||||
loadData={async (node) => {
|
||||
const key = node.value === undefined ? ROOT_KEY : String(node.value)
|
||||
await loadChildren(key)
|
||||
}}
|
||||
showSearch
|
||||
treeNodeFilterProp="title"
|
||||
/>
|
||||
)
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Конфигурация приложения.
|
||||
*
|
||||
* Приоритет источников:
|
||||
* 1. window.__APP_CONFIG__ — инжектится файлом /config.js. В Docker этот файл
|
||||
* генерируется entrypoint-скриптом из переменных окружения контейнера
|
||||
* (KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_CLIENT_ID, API_BASE_URL).
|
||||
* 2. VITE_* — переменные Vite из .env (локальная разработка).
|
||||
* 3. Значения по умолчанию ниже.
|
||||
*/
|
||||
export interface AppConfig {
|
||||
apiBaseUrl?: string
|
||||
keycloak?: {
|
||||
url?: string
|
||||
realm?: string
|
||||
clientId?: string
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__APP_CONFIG__?: AppConfig
|
||||
}
|
||||
}
|
||||
|
||||
const runtime: AppConfig = window.__APP_CONFIG__ ?? {}
|
||||
|
||||
export const env = {
|
||||
apiBaseUrl:
|
||||
runtime.apiBaseUrl ?? import.meta.env.VITE_API_BASE_URL ?? '/api',
|
||||
keycloak: {
|
||||
url: runtime.keycloak?.url ?? import.meta.env.VITE_KEYCLOAK_URL ?? 'http://localhost:8081',
|
||||
realm: runtime.keycloak?.realm ?? import.meta.env.VITE_KEYCLOAK_REALM ?? 'gorodar',
|
||||
clientId:
|
||||
runtime.keycloak?.clientId ?? import.meta.env.VITE_KEYCLOAK_CLIENT_ID ?? 'gorodar',
|
||||
},
|
||||
} as const
|
||||
@@ -0,0 +1,36 @@
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
|
||||
'Noto Sans', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.fullscreen-spin {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.page-header-flex {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import {
|
||||
ApartmentOutlined,
|
||||
BarChartOutlined,
|
||||
CameraOutlined,
|
||||
LogoutOutlined,
|
||||
OrderedListOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons'
|
||||
import { Avatar, Button, Layout, Menu, Result, Space, Spin, Tag, Typography } from 'antd'
|
||||
import { Outlet, useLocation } from 'react-router-dom'
|
||||
import { useAuth } from '@/auth/AuthContext'
|
||||
import { ROLE_MANAGE_AREA, ROLE_MANAGE_ATTRACTION } from '@/auth/roles'
|
||||
|
||||
const { Header, Sider, Content } = Layout
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
[ROLE_MANAGE_AREA]: 'управление зонами',
|
||||
[ROLE_MANAGE_ATTRACTION]: 'управление контентом',
|
||||
}
|
||||
|
||||
export function AdminLayout() {
|
||||
const { ready, authenticated, userName, roles, logout } = useAuth()
|
||||
const location = useLocation()
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="fullscreen-spin">
|
||||
<Spin size="large" tip="Проверка авторизации…">
|
||||
<div style={{ width: 160, height: 60 }} />
|
||||
</Spin>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return (
|
||||
<Result
|
||||
status="warning"
|
||||
title="Не удалось авторизоваться"
|
||||
subTitle="Сервер Keycloak недоступен или сессия истекла. Попробуйте войти снова."
|
||||
extra={
|
||||
<Button type="primary" onClick={logout}>
|
||||
Войти заново
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const hasManageArea = roles.includes(ROLE_MANAGE_AREA)
|
||||
const hasManageAttraction = roles.includes(ROLE_MANAGE_ATTRACTION)
|
||||
|
||||
if (!hasManageArea && !hasManageAttraction) {
|
||||
return (
|
||||
<Result
|
||||
status="403"
|
||||
title="Нет административных прав"
|
||||
subTitle="Вашей учётной записи не назначена роль manage_area или manage_attraction в Keycloak."
|
||||
extra={
|
||||
<Button icon={<LogoutOutlined />} onClick={logout}>
|
||||
Выйти
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const menuItems = [
|
||||
hasManageArea && { key: '/areas', icon: <ApartmentOutlined />, label: 'Зоны' },
|
||||
hasManageAttraction && {
|
||||
key: '/attractions',
|
||||
icon: <CameraOutlined />,
|
||||
label: 'Достопримечательности',
|
||||
},
|
||||
hasManageArea && {
|
||||
key: '/sets',
|
||||
icon: <OrderedListOutlined />,
|
||||
label: 'Наборы',
|
||||
},
|
||||
hasManageArea && { key: '/visits', icon: <BarChartOutlined />, label: 'Визиты' },
|
||||
].filter(Boolean) as { key: string; icon: React.ReactNode; label: string }[]
|
||||
|
||||
const selectedKey =
|
||||
'/' +
|
||||
(location.pathname.split('/')[1] ?? '')
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
<Header
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: 16,
|
||||
}}
|
||||
>
|
||||
<Space size="middle">
|
||||
<Typography.Title level={4} style={{ color: '#fff', margin: 0 }}>
|
||||
Городар · Админ-панель
|
||||
</Typography.Title>
|
||||
</Space>
|
||||
<Space size="middle">
|
||||
<Space size={4} wrap>
|
||||
{roles
|
||||
.filter((role) => ROLE_LABELS[role])
|
||||
.map((role) => (
|
||||
<Tag key={role} color="gold">
|
||||
{ROLE_LABELS[role]}
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
<Space size={8}>
|
||||
<Avatar size="small" icon={<UserOutlined />} />
|
||||
<Typography.Text style={{ color: 'rgba(255,255,255,0.85)' }}>
|
||||
{userName}
|
||||
</Typography.Text>
|
||||
<Button
|
||||
type="text"
|
||||
icon={<LogoutOutlined />}
|
||||
onClick={logout}
|
||||
style={{ color: 'rgba(255,255,255,0.85)' }}
|
||||
>
|
||||
Выйти
|
||||
</Button>
|
||||
</Space>
|
||||
</Space>
|
||||
</Header>
|
||||
<Layout>
|
||||
<Sider theme="light" width={220}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[selectedKey]}
|
||||
items={menuItems}
|
||||
style={{ height: '100%', borderRight: 0, paddingTop: 8 }}
|
||||
/>
|
||||
</Sider>
|
||||
<Content style={{ padding: 24 }}>
|
||||
<Outlet />
|
||||
</Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect } from 'react'
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { App as AntdApp, ConfigProvider } from 'antd'
|
||||
import ruRU from 'antd/locale/ru_RU'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/ru'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { App } from '@/App'
|
||||
import { AuthProvider } from '@/auth/AuthContext'
|
||||
import { setNotifier } from '@/api/notify'
|
||||
import '@/index.css'
|
||||
|
||||
dayjs.locale('ru')
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
/** Подключает antd notification к мосту, которым пользуются axios-перехватчики. */
|
||||
function NotifierBridge() {
|
||||
const { notification } = AntdApp.useApp()
|
||||
useEffect(() => {
|
||||
setNotifier((kind, message, description) => {
|
||||
if (kind === 'success') notification.success({ message, description })
|
||||
else if (kind === 'error') notification.error({ message, description })
|
||||
else notification.info({ message, description })
|
||||
})
|
||||
return () => setNotifier(null)
|
||||
}, [notification])
|
||||
return null
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConfigProvider locale={ruRU}>
|
||||
<AntdApp>
|
||||
<NotifierBridge />
|
||||
<AuthProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</AuthProvider>
|
||||
</AntdApp>
|
||||
</ConfigProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Result } from 'antd'
|
||||
|
||||
export function ForbiddenPage() {
|
||||
return (
|
||||
<Result
|
||||
status="403"
|
||||
title="Нет доступа"
|
||||
subTitle="У вас нет роли, необходимой для этого раздела."
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Button, Result } from 'antd'
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<Result
|
||||
status="404"
|
||||
title="Страница не найдена"
|
||||
extra={
|
||||
<Button type="primary">
|
||||
<Link to="/" style={{ color: 'inherit' }}>
|
||||
На главную
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import { useState } from 'react'
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Breadcrumb, Button, Empty, Form, Input, Modal, Space, Table, Typography } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { createArea, fetchAreas, updateArea } from '@/api/areas'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import type { Area } from '@/api/types'
|
||||
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
||||
|
||||
interface TrailItem {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface CreateFormValues {
|
||||
name: string
|
||||
}
|
||||
|
||||
interface EditFormValues {
|
||||
name: string
|
||||
/** undefined — не менять; null — сделать корневой; строка — новый родитель. */
|
||||
newParent?: string | null
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
export function AreaListPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const [parentId, setParentId] = useState<string | null>(null)
|
||||
const [trail, setTrail] = useState<TrailItem[]>([])
|
||||
const [page, setPage] = useState(0)
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<Area | null>(null)
|
||||
const [createForm] = Form.useForm<CreateFormValues>()
|
||||
const [editForm] = Form.useForm<EditFormValues>()
|
||||
|
||||
const areasQuery = useQuery({
|
||||
queryKey: ['admin-areas', parentId ?? 'root', page],
|
||||
queryFn: () =>
|
||||
fetchAreas({ parentId, page, size: PAGE_SIZE, sort: 'name,asc' }),
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-areas'] })
|
||||
}
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: createArea,
|
||||
onSuccess: (area) => {
|
||||
notifySuccess('Зона создана', area.name)
|
||||
setCreateOpen(false)
|
||||
createForm.resetFields()
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось создать зону'),
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, request }: { id: string; request: EditFormValues }) => {
|
||||
const body: { name?: string; parentId?: string | null } = {}
|
||||
if (request.name && request.name.trim()) body.name = request.name.trim()
|
||||
if (request.newParent !== undefined) {
|
||||
body.parentId = request.newParent === '__root__' ? null : request.newParent
|
||||
}
|
||||
return updateArea(id, body)
|
||||
},
|
||||
onSuccess: (area) => {
|
||||
notifySuccess('Зона обновлена', area.name)
|
||||
setEditing(null)
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось обновить зону'),
|
||||
})
|
||||
|
||||
const openArea = (area: Area) => {
|
||||
setTrail((prev) => [...prev, { id: area.id, name: area.name }])
|
||||
setParentId(area.id)
|
||||
setPage(0)
|
||||
}
|
||||
|
||||
const navigateTo = (index: number) => {
|
||||
// -1 — корень, иначе обрезаем путь до index включительно.
|
||||
if (index < 0) {
|
||||
setTrail([])
|
||||
setParentId(null)
|
||||
} else {
|
||||
const item = trail[index]
|
||||
setTrail(trail.slice(0, index + 1))
|
||||
setParentId(item.id)
|
||||
}
|
||||
setPage(0)
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Area> = [
|
||||
{
|
||||
title: 'Название',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
render: (_, area) => (
|
||||
<Button type="link" onClick={() => openArea(area)} style={{ padding: 0 }}>
|
||||
{area.name}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Действия',
|
||||
key: 'actions',
|
||||
width: 200,
|
||||
render: (_, area) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => openArea(area)}>
|
||||
Внутрь
|
||||
</Button>
|
||||
<Button size="small" onClick={() => setEditing(area)}>
|
||||
Изменить
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
const data = areasQuery.data
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="page-header-flex">
|
||||
<Typography.Title level={3} className="page-title">
|
||||
Зоны
|
||||
</Typography.Title>
|
||||
<Button type="primary" onClick={() => setCreateOpen(true)}>
|
||||
Создать зону
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Breadcrumb
|
||||
style={{ marginBottom: 16 }}
|
||||
items={[
|
||||
{
|
||||
title: (
|
||||
<Button type="link" size="small" style={{ padding: 0 }} onClick={() => navigateTo(-1)}>
|
||||
Корень
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
...trail.map((item, index) => ({
|
||||
title:
|
||||
index === trail.length - 1 ? (
|
||||
item.name
|
||||
) : (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: 0 }}
|
||||
onClick={() => navigateTo(index)}
|
||||
>
|
||||
{item.name}
|
||||
</Button>
|
||||
),
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
|
||||
<Table<Area>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={data?.content ?? []}
|
||||
loading={areasQuery.isLoading}
|
||||
locale={{
|
||||
emptyText: <Empty description="В этой зоне нет вложенных зон" />,
|
||||
}}
|
||||
pagination={{
|
||||
current: (data?.number ?? 0) + 1,
|
||||
pageSize: data?.size ?? PAGE_SIZE,
|
||||
total: data?.totalElements ?? 0,
|
||||
showSizeChanger: false,
|
||||
onChange: (p) => setPage(p - 1),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
title="Создать зону"
|
||||
key={createOpen ? 'create-open' : 'create-closed'}
|
||||
open={createOpen}
|
||||
onCancel={() => setCreateOpen(false)}
|
||||
confirmLoading={createMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await createForm.validateFields()
|
||||
createMutation.mutate({
|
||||
name: values.name.trim(),
|
||||
parentId: parentId ?? undefined,
|
||||
})
|
||||
}}
|
||||
>
|
||||
<Form form={createForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Название"
|
||||
rules={[{ required: true, message: 'Укажите название' }]}
|
||||
>
|
||||
<Input placeholder="Например, Центральный район" maxLength={255} />
|
||||
</Form.Item>
|
||||
<Form.Item label="Родительская зона">
|
||||
<Input disabled value={trail.length ? trail[trail.length - 1].name : '— корень —'} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="Изменить зону"
|
||||
key={editing?.id ?? 'edit-closed'}
|
||||
open={editing != null}
|
||||
onCancel={() => setEditing(null)}
|
||||
confirmLoading={updateMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await editForm.validateFields()
|
||||
updateMutation.mutate({ id: editing!.id, request: values })
|
||||
}}
|
||||
>
|
||||
<Form
|
||||
form={editForm}
|
||||
layout="vertical"
|
||||
initialValues={{ name: editing?.name, newParent: undefined }}
|
||||
>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Название"
|
||||
rules={[{ required: true, message: 'Укажите название' }]}
|
||||
>
|
||||
<Input maxLength={255} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="newParent"
|
||||
label="Новая родительская зона"
|
||||
extra="Не выбрано — родитель не меняется. «Корень» — сделать зоной верхнего уровня."
|
||||
initialValue={undefined}
|
||||
>
|
||||
<AreaTreeSelect
|
||||
placeholder="Родитель не меняется"
|
||||
rootAsOption
|
||||
excludeId={editing?.id}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Descriptions,
|
||||
Form,
|
||||
Image,
|
||||
Modal,
|
||||
Result,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
Upload,
|
||||
} from 'antd'
|
||||
import { ArrowLeftOutlined, EditOutlined, UploadOutlined } from '@ant-design/icons'
|
||||
import type { UploadProps } from 'antd'
|
||||
import { Link, useLocation, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { fetchAttractionCard, fetchAttractions, updateAttraction, uploadIcon } from '@/api/attractions'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import { notify } from '@/api/notify'
|
||||
import type { Attraction } from '@/api/types'
|
||||
import { cvProfileMeta } from '@/utils/format'
|
||||
import {
|
||||
AttractionForm,
|
||||
toUpdateRequest,
|
||||
type AttractionFormValues,
|
||||
} from '@/pages/attractions/AttractionForm'
|
||||
import { PhotoGallery } from '@/pages/attractions/PhotoGallery'
|
||||
|
||||
const MAX_FILE_SIZE = 20 * 1024 * 1024
|
||||
|
||||
export function AttractionDetailPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const location = useLocation()
|
||||
const [searchParams] = useSearchParams()
|
||||
const areaId = searchParams.get('area')
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const passedState = (location.state as { attraction?: Attraction } | null)?.attraction
|
||||
// Карточка = последний ответ мутации (или router state), иначе — восстановление из списка зоны.
|
||||
const [mutated, setMutated] = useState<Attraction | null>(passedState ?? null)
|
||||
const [editOpen, setEditOpen] = useState(false)
|
||||
const [editForm] = Form.useForm<AttractionFormValues>()
|
||||
|
||||
// В админ-API нет GET по id — при прямом открытии/обновлении страницы
|
||||
// восстанавливаем карточку из постраничного списка зоны.
|
||||
const fallbackQuery = useQuery({
|
||||
queryKey: ['admin-attractions', areaId ?? 'none', 0, 'fallback'],
|
||||
queryFn: () => fetchAttractions({ areaId: areaId!, page: 0, size: 100, sort: 'name,asc' }),
|
||||
enabled: mutated == null && areaId != null && id != null,
|
||||
})
|
||||
const fallback =
|
||||
mutated == null ? (fallbackQuery.data?.content.find((a) => a.id === id) ?? null) : null
|
||||
const attraction = mutated ?? fallback
|
||||
|
||||
// Публичная карточка — единственный источник presigned iconUrl для превью.
|
||||
const cardQuery = useQuery({
|
||||
queryKey: ['public-card', id],
|
||||
queryFn: () => fetchAttractionCard(id!),
|
||||
enabled: id != null,
|
||||
staleTime: 30 * 60 * 1000, // presigned URL живёт 1 час
|
||||
})
|
||||
|
||||
const editMutation = useMutation({
|
||||
mutationFn: (request: AttractionFormValues) => updateAttraction(id!, toUpdateRequest(request)),
|
||||
onSuccess: (updated) => {
|
||||
notifySuccess('Карточка обновлена', updated.name)
|
||||
setMutated(updated)
|
||||
setEditOpen(false)
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-attractions'] })
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось обновить карточку'),
|
||||
})
|
||||
|
||||
const iconMutation = useMutation({
|
||||
mutationFn: (file: File) => uploadIcon(id!, file),
|
||||
onSuccess: (updated) => {
|
||||
notifySuccess('Иконка обновлена')
|
||||
setMutated(updated)
|
||||
void queryClient.invalidateQueries({ queryKey: ['public-card', id] })
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось загрузить иконку'),
|
||||
})
|
||||
|
||||
const iconUploadProps: UploadProps = {
|
||||
accept: 'image/jpeg,image/png,image/webp,image/svg+xml',
|
||||
showUploadList: false,
|
||||
beforeUpload: (file) => {
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
notify('error', 'Файл больше 20 МБ')
|
||||
return Upload.LIST_IGNORE
|
||||
}
|
||||
return true
|
||||
},
|
||||
customRequest: ({ file, onSuccess, onError }) => {
|
||||
iconMutation
|
||||
.mutateAsync(file as File)
|
||||
.then(() => onSuccess?.(null))
|
||||
.catch((e: unknown) => onError?.(e as Error))
|
||||
},
|
||||
}
|
||||
|
||||
if (attraction == null) {
|
||||
if (fallbackQuery.isLoading || fallbackQuery.isFetching) {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 64 }}>
|
||||
<Spin />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (areaId == null) {
|
||||
return (
|
||||
<Result
|
||||
status="warning"
|
||||
title="Не удалось восстановить карточку"
|
||||
subTitle="Откройте достопримечательность из списка зоны."
|
||||
extra={
|
||||
<Button type="primary">
|
||||
<Link to="/attractions" style={{ color: 'inherit' }}>
|
||||
К списку
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Result
|
||||
status="404"
|
||||
title="Достопримечательность не найдена"
|
||||
subTitle="Возможно, она удалена или находится в другой зоне."
|
||||
extra={
|
||||
<Button type="primary">
|
||||
<Link to={`/attractions?area=${areaId}`} style={{ color: 'inherit' }}>
|
||||
К списку зоны
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const iconUrl = cardQuery.data?.iconUrl
|
||||
|
||||
return (
|
||||
<>
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<div className="page-header-flex">
|
||||
<Space>
|
||||
<Link to={`/attractions?area=${attraction.areaId}`}>
|
||||
<Button icon={<ArrowLeftOutlined />}>К списку</Button>
|
||||
</Link>
|
||||
<Typography.Title level={3} className="page-title">
|
||||
{attraction.name}
|
||||
</Typography.Title>
|
||||
</Space>
|
||||
<Button icon={<EditOutlined />} onClick={() => setEditOpen(true)}>
|
||||
Редактировать
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card title="Карточка">
|
||||
<Descriptions column={2} bordered size="small">
|
||||
<Descriptions.Item label="Название">{attraction.name}</Descriptions.Item>
|
||||
<Descriptions.Item label="CV-профиль">
|
||||
<Tag color={cvProfileMeta[attraction.cvProfile].color}>
|
||||
{cvProfileMeta[attraction.cvProfile].label}
|
||||
</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Адрес">{attraction.address ?? '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="Координаты">
|
||||
{attraction.latitude != null && attraction.longitude != null
|
||||
? `${attraction.latitude}, ${attraction.longitude}`
|
||||
: '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Фото" span={2}>
|
||||
{attraction.photoCount}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Описание" span={2}>
|
||||
{attraction.about ?? '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Факты" span={2}>
|
||||
{attraction.facts?.length ? (
|
||||
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||
{attraction.facts.map((fact) => (
|
||||
<li key={fact}>{fact}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
|
||||
<Card title="Иконка">
|
||||
<Space size="large" align="start">
|
||||
{iconUrl ? (
|
||||
<Image src={iconUrl} width={96} height={96} style={{ objectFit: 'cover' }} />
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
width: 96,
|
||||
height: 96,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
border: '1px dashed #d9d9d9',
|
||||
borderRadius: 8,
|
||||
color: '#999',
|
||||
}}
|
||||
>
|
||||
нет
|
||||
</div>
|
||||
)}
|
||||
<Space direction="vertical">
|
||||
<Upload {...iconUploadProps}>
|
||||
<Button icon={<UploadOutlined />} loading={iconMutation.isPending}>
|
||||
Загрузить иконку
|
||||
</Button>
|
||||
</Upload>
|
||||
<Typography.Text type="secondary">
|
||||
JPEG / PNG / WebP / SVG, до 20 МБ. Перезаписывает текущую иконку.
|
||||
</Typography.Text>
|
||||
<Typography.Text type="secondary">
|
||||
Ключ в S3:{' '}
|
||||
<Typography.Text code copyable={{ text: attraction.iconKey ?? '' }}>
|
||||
{attraction.iconKey ?? '—'}
|
||||
</Typography.Text>
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card title="Эталонные фото">
|
||||
<PhotoGallery
|
||||
attractionId={attraction.id}
|
||||
onCountDelta={(delta) =>
|
||||
setMutated((prev) =>
|
||||
prev ? { ...prev, photoCount: prev.photoCount + delta } : prev,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
</Space>
|
||||
|
||||
<Modal
|
||||
title="Редактировать карточку"
|
||||
open={editOpen}
|
||||
onCancel={() => setEditOpen(false)}
|
||||
confirmLoading={editMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await editForm.validateFields()
|
||||
editMutation.mutate(values)
|
||||
}}
|
||||
>
|
||||
<AttractionForm
|
||||
form={editForm}
|
||||
key={editOpen ? 'edit-open' : 'edit-closed'}
|
||||
initialValues={attraction}
|
||||
/>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { FormInstance } from 'antd'
|
||||
import { Button, Form, Input, InputNumber, Select, Space } from 'antd'
|
||||
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
|
||||
import type { CreateAttractionRequest, CvProfile, UpdateAttractionRequest } from '@/api/types'
|
||||
import { cvProfileOptions } from '@/utils/format'
|
||||
|
||||
export interface AttractionFormValues {
|
||||
name: string
|
||||
cvProfile: CvProfile
|
||||
about?: string
|
||||
address?: string
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
facts?: (string | undefined)[]
|
||||
}
|
||||
|
||||
export interface AttractionFormInitialValues {
|
||||
name: string
|
||||
cvProfile: CvProfile
|
||||
about?: string | null
|
||||
address?: string | null
|
||||
latitude?: number | null
|
||||
longitude?: number | null
|
||||
facts?: string[] | null
|
||||
}
|
||||
|
||||
function normalizeFacts(facts: (string | undefined)[] | undefined): string[] {
|
||||
return (facts ?? [])
|
||||
.map((f) => f?.trim())
|
||||
.filter((f): f is string => !!f)
|
||||
}
|
||||
|
||||
export function toCreateRequest(
|
||||
areaId: string,
|
||||
v: AttractionFormValues,
|
||||
): CreateAttractionRequest {
|
||||
const facts = normalizeFacts(v.facts)
|
||||
return {
|
||||
areaId,
|
||||
name: v.name.trim(),
|
||||
cvProfile: v.cvProfile,
|
||||
about: v.about?.trim() || undefined,
|
||||
address: v.address?.trim() || undefined,
|
||||
latitude: v.latitude ?? undefined,
|
||||
longitude: v.longitude ?? undefined,
|
||||
facts: facts.length ? facts : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH-семантика бэкенда: отсутствующее поле = «не менять»,
|
||||
* поэтому пустые значения просто не отправляем (API не поддерживает очистку полей).
|
||||
*/
|
||||
export function toUpdateRequest(v: AttractionFormValues): UpdateAttractionRequest {
|
||||
const request: UpdateAttractionRequest = {}
|
||||
const name = v.name?.trim()
|
||||
if (name) request.name = name
|
||||
if (v.cvProfile) request.cvProfile = v.cvProfile
|
||||
const about = v.about?.trim()
|
||||
if (about) request.about = about
|
||||
const address = v.address?.trim()
|
||||
if (address) request.address = address
|
||||
if (v.latitude != null) request.latitude = v.latitude
|
||||
if (v.longitude != null) request.longitude = v.longitude
|
||||
const facts = normalizeFacts(v.facts)
|
||||
if (facts.length) request.facts = facts
|
||||
return request
|
||||
}
|
||||
|
||||
export function AttractionForm({
|
||||
form,
|
||||
initialValues,
|
||||
}: {
|
||||
form: FormInstance<AttractionFormValues>
|
||||
initialValues?: AttractionFormInitialValues
|
||||
}) {
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={
|
||||
initialValues && {
|
||||
name: initialValues.name,
|
||||
cvProfile: initialValues.cvProfile,
|
||||
about: initialValues.about ?? undefined,
|
||||
address: initialValues.address ?? undefined,
|
||||
latitude: initialValues.latitude ?? undefined,
|
||||
longitude: initialValues.longitude ?? undefined,
|
||||
facts: initialValues.facts ?? [],
|
||||
}
|
||||
}
|
||||
>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Название"
|
||||
rules={[{ required: true, message: 'Укажите название' }]}
|
||||
>
|
||||
<Input maxLength={255} placeholder="Например, Дом со шпилем" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="cvProfile"
|
||||
label="CV-профиль распознавания"
|
||||
rules={[{ required: true, message: 'Выберите профиль' }]}
|
||||
extra="Влияет на алгоритм сопоставления фотографий."
|
||||
>
|
||||
<Select options={cvProfileOptions} />
|
||||
</Form.Item>
|
||||
<Form.Item name="about" label="Описание">
|
||||
<Input.TextArea rows={3} maxLength={4000} />
|
||||
</Form.Item>
|
||||
<Form.Item name="address" label="Адрес">
|
||||
<Input maxLength={255} />
|
||||
</Form.Item>
|
||||
<Space size="large" style={{ display: 'flex' }} align="start">
|
||||
<Form.Item
|
||||
name="latitude"
|
||||
label="Широта"
|
||||
style={{ width: 220 }}
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value: number | null | undefined) =>
|
||||
value == null || (value >= -90 && value <= 90)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error('Диапазон −90…90')),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<InputNumber style={{ width: '100%' }} min={-90} max={90} step={0.000001} placeholder="55.751244" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="longitude"
|
||||
label="Долгота"
|
||||
style={{ width: 220 }}
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value: number | null | undefined) =>
|
||||
value == null || (value >= -180 && value <= 180)
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error('Диапазон −180…180')),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<InputNumber style={{ width: '100%' }} min={-180} max={180} step={0.000001} placeholder="37.618423" />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
<Form.Item label="Интересные факты" style={{ marginBottom: 0 }}>
|
||||
<Form.List name="facts">
|
||||
{(fields, { add, remove }) => (
|
||||
<>
|
||||
{fields.map((field) => (
|
||||
<Space key={field.key} align="baseline" style={{ display: 'flex', marginBottom: 4 }}>
|
||||
<Form.Item
|
||||
name={field.name}
|
||||
rules={[{ required: true, message: 'Пустой факт — удалите строку' }]}
|
||||
noStyle
|
||||
>
|
||||
<Input placeholder="Текст факта" maxLength={500} style={{ width: 440 }} />
|
||||
</Form.Item>
|
||||
<MinusCircleOutlined onClick={() => remove(field.name)} />
|
||||
</Space>
|
||||
))}
|
||||
<Button
|
||||
type="dashed"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => add()}
|
||||
style={{ width: 472 }}
|
||||
>
|
||||
Добавить факт
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useState } from 'react'
|
||||
import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { Button, Empty, Form, Modal, Space, Table, Tag, Typography } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { createAttraction, fetchAttractions } from '@/api/attractions'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import type { Attraction } from '@/api/types'
|
||||
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
||||
import { cvProfileMeta } from '@/utils/format'
|
||||
import {
|
||||
AttractionForm,
|
||||
toCreateRequest,
|
||||
type AttractionFormValues,
|
||||
} from '@/pages/attractions/AttractionForm'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
export function AttractionListPage() {
|
||||
const navigate = useNavigate()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [areaId, setAreaId] = useState<string | null>(searchParams.get('area'))
|
||||
const [page, setPage] = useState(0)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [createForm] = Form.useForm<AttractionFormValues>()
|
||||
|
||||
const attractionsQuery = useQuery({
|
||||
queryKey: ['admin-attractions', areaId ?? 'none', page],
|
||||
queryFn: () => fetchAttractions({ areaId: areaId!, page, size: PAGE_SIZE, sort: 'name,asc' }),
|
||||
enabled: areaId != null,
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: createAttraction,
|
||||
onSuccess: (attraction) => {
|
||||
notifySuccess('Достопримечательность создана', attraction.name)
|
||||
setCreateOpen(false)
|
||||
createForm.resetFields()
|
||||
navigate(`/attractions/${attraction.id}?area=${attraction.areaId}`)
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось создать достопримечательность'),
|
||||
})
|
||||
|
||||
const openDetail = (attraction: Attraction) => {
|
||||
navigate(`/attractions/${attraction.id}?area=${attraction.areaId}`)
|
||||
}
|
||||
|
||||
const changeArea = (value: string | null) => {
|
||||
setAreaId(value)
|
||||
setPage(0)
|
||||
setSearchParams(value ? { area: value } : {}, { replace: true })
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Attraction> = [
|
||||
{
|
||||
title: 'Название',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
render: (_, attraction) => (
|
||||
<Button type="link" style={{ padding: 0 }} onClick={() => openDetail(attraction)}>
|
||||
{attraction.name}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{ title: 'Адрес', dataIndex: 'address', key: 'address', render: (v) => v ?? '—' },
|
||||
{
|
||||
title: 'CV-профиль',
|
||||
dataIndex: 'cvProfile',
|
||||
key: 'cvProfile',
|
||||
width: 180,
|
||||
render: (v: Attraction['cvProfile']) => (
|
||||
<Tag color={cvProfileMeta[v].color}>{cvProfileMeta[v].label}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Координаты',
|
||||
key: 'coords',
|
||||
width: 220,
|
||||
render: (_, a) =>
|
||||
a.latitude != null && a.longitude != null
|
||||
? `${a.latitude}, ${a.longitude}`
|
||||
: '—',
|
||||
},
|
||||
{
|
||||
title: 'Фото',
|
||||
dataIndex: 'photoCount',
|
||||
key: 'photoCount',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
},
|
||||
{
|
||||
title: 'Действия',
|
||||
key: 'actions',
|
||||
width: 120,
|
||||
render: (_, attraction) => (
|
||||
<Button size="small" onClick={() => openDetail(attraction)}>
|
||||
Открыть
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
const data = attractionsQuery.data
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="page-header-flex">
|
||||
<Typography.Title level={3} className="page-title">
|
||||
Достопримечательности
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<AreaTreeSelect
|
||||
value={areaId}
|
||||
onChange={changeArea}
|
||||
placeholder="Зона (обязательно)"
|
||||
allowClear
|
||||
/>
|
||||
<Button type="primary" disabled={!areaId} onClick={() => setCreateOpen(true)}>
|
||||
Создать
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{!areaId ? (
|
||||
<Empty description="Выберите зону, чтобы увидеть достопримечательности" style={{ marginTop: 64 }} />
|
||||
) : (
|
||||
<Table<Attraction>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={data?.content ?? []}
|
||||
loading={attractionsQuery.isLoading}
|
||||
locale={{ emptyText: <Empty description="В зоне пока нет достопримечательностей" /> }}
|
||||
pagination={{
|
||||
current: (data?.number ?? 0) + 1,
|
||||
pageSize: data?.size ?? PAGE_SIZE,
|
||||
total: data?.totalElements ?? 0,
|
||||
showSizeChanger: false,
|
||||
onChange: (p) => setPage(p - 1),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
title="Новая достопримечательность"
|
||||
open={createOpen}
|
||||
onCancel={() => setCreateOpen(false)}
|
||||
confirmLoading={createMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await createForm.validateFields()
|
||||
createMutation.mutate(toCreateRequest(areaId!, values))
|
||||
}}
|
||||
>
|
||||
<AttractionForm form={createForm} />
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Empty,
|
||||
Image,
|
||||
InputNumber,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
Typography,
|
||||
Upload,
|
||||
} from 'antd'
|
||||
import { DeleteOutlined, ExperimentOutlined, SaveOutlined, UploadOutlined } from '@ant-design/icons'
|
||||
import type { UploadProps } from 'antd'
|
||||
import {
|
||||
deletePhoto,
|
||||
fetchPhotos,
|
||||
recalcPhotoFeatures,
|
||||
updatePhotoSortOrder,
|
||||
uploadPhoto,
|
||||
} from '@/api/attractions'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import { notify } from '@/api/notify'
|
||||
import type { Photo } from '@/api/types'
|
||||
import { formatUtc } from '@/utils/format'
|
||||
|
||||
const MAX_FILE_SIZE = 20 * 1024 * 1024
|
||||
const ACCEPTED_TYPES = 'image/jpeg,image/png,image/webp,image/svg+xml'
|
||||
|
||||
export function PhotoGallery({
|
||||
attractionId,
|
||||
onCountDelta,
|
||||
}: {
|
||||
attractionId: string
|
||||
onCountDelta: (delta: number) => void
|
||||
}) {
|
||||
const queryClient = useQueryClient()
|
||||
const [uploadSortOrder, setUploadSortOrder] = useState<number | null>(null)
|
||||
/** Черновики позиций: photoId → введённое, но не сохранённое значение. */
|
||||
const [pendingOrders, setPendingOrders] = useState<Record<string, number>>({})
|
||||
|
||||
const photosQuery = useQuery({
|
||||
queryKey: ['admin-photos', attractionId],
|
||||
queryFn: () => fetchPhotos(attractionId),
|
||||
})
|
||||
|
||||
const photosKey = ['admin-photos', attractionId] as const
|
||||
const setPhotos = (updater: (prev: Photo[]) => Photo[]) => {
|
||||
queryClient.setQueryData<Photo[]>(photosKey, (prev) =>
|
||||
prev ? updater([...prev]).sort((a, b) => a.sortOrder - b.sortOrder) : prev,
|
||||
)
|
||||
}
|
||||
|
||||
const uploadMutation = useMutation({
|
||||
mutationFn: ({ file, sortOrder }: { file: File; sortOrder?: number }) =>
|
||||
uploadPhoto(attractionId, file, sortOrder),
|
||||
onSuccess: (photo) => {
|
||||
setPhotos((prev) => (prev.some((p) => p.id === photo.id) ? prev : [...prev, photo]))
|
||||
onCountDelta(1)
|
||||
notifySuccess('Фото загружено', `Позиция ${photo.sortOrder}`)
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось загрузить фото'),
|
||||
})
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ photoId, sortOrder }: { photoId: string; sortOrder: number }) =>
|
||||
updatePhotoSortOrder(attractionId, photoId, sortOrder),
|
||||
onSuccess: (photo) => {
|
||||
setPhotos((prev) => prev.map((p) => (p.id === photo.id ? photo : p)))
|
||||
setPendingOrders((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[photo.id]
|
||||
return next
|
||||
})
|
||||
notifySuccess('Позиция обновлена')
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось изменить позицию'),
|
||||
})
|
||||
|
||||
const recalcMutation = useMutation({
|
||||
mutationFn: (photoId: string) => recalcPhotoFeatures(attractionId, photoId),
|
||||
onSuccess: (photo) => {
|
||||
setPhotos((prev) => prev.map((p) => (p.id === photo.id ? photo : p)))
|
||||
notifySuccess('Признаки пересчитаны', `Keypoints: ${photo.keypointsCount}`)
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось пересчитать признаки'),
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (photoId: string) => deletePhoto(attractionId, photoId),
|
||||
onSuccess: (_, photoId) => {
|
||||
setPhotos((prev) => prev.filter((p) => p.id !== photoId))
|
||||
onCountDelta(-1)
|
||||
notifySuccess('Фото удалено')
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось удалить фото'),
|
||||
})
|
||||
|
||||
const uploadProps: UploadProps = {
|
||||
accept: ACCEPTED_TYPES,
|
||||
multiple: false,
|
||||
showUploadList: false,
|
||||
beforeUpload: (file) => {
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
notify('error', 'Файл больше 20 МБ')
|
||||
return Upload.LIST_IGNORE
|
||||
}
|
||||
return true
|
||||
},
|
||||
customRequest: ({ file, onSuccess, onError }) => {
|
||||
uploadMutation
|
||||
.mutateAsync({ file: file as File, sortOrder: uploadSortOrder ?? undefined })
|
||||
.then(() => onSuccess?.(null))
|
||||
.catch((e: unknown) => onError?.(e as Error))
|
||||
},
|
||||
}
|
||||
|
||||
if (photosQuery.isLoading) {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
|
||||
<Spin />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (photosQuery.isError) {
|
||||
return (
|
||||
<Empty description="Не удалось загрузить список фото. Обновите страницу." style={{ padding: 32 }} />
|
||||
)
|
||||
}
|
||||
|
||||
const photos = photosQuery.data ?? []
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Space wrap>
|
||||
<Upload {...uploadProps}>
|
||||
<Button type="primary" icon={<UploadOutlined />} loading={uploadMutation.isPending}>
|
||||
Загрузить фото
|
||||
</Button>
|
||||
</Upload>
|
||||
<Space>
|
||||
<Typography.Text>Позиция:</Typography.Text>
|
||||
<InputNumber
|
||||
min={1}
|
||||
precision={0}
|
||||
value={uploadSortOrder ?? undefined}
|
||||
onChange={setUploadSortOrder}
|
||||
placeholder="авто"
|
||||
style={{ width: 90 }}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
без позиции — следующая свободная
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{photos.length === 0 ? (
|
||||
<Empty description="Эталонных фото пока нет" style={{ padding: 24 }} />
|
||||
) : (
|
||||
<Row gutter={[16, 16]}>
|
||||
{photos.map((photo) => (
|
||||
<Col key={photo.id} xs={24} sm={12} lg={8} xl={6}>
|
||||
<Card
|
||||
size="small"
|
||||
cover={
|
||||
<Image
|
||||
src={photo.photoUrl}
|
||||
height={180}
|
||||
width="100%"
|
||||
style={{ objectFit: 'cover' }}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Space direction="vertical" size={4} style={{ width: '100%' }}>
|
||||
<Space size={8} wrap>
|
||||
<Tag color="blue">позиция {photo.sortOrder}</Tag>
|
||||
<Typography.Text type="secondary">
|
||||
{formatUtc(photo.createdAt)} UTC
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
keypoints: {photo.keypointsCount} · algo: {photo.algoId || '—'} · формат:{' '}
|
||||
{photo.featureFormatVersion}
|
||||
</Typography.Text>
|
||||
<Space size={8} wrap>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={1}
|
||||
precision={0}
|
||||
value={pendingOrders[photo.id] ?? photo.sortOrder}
|
||||
onChange={(v) =>
|
||||
setPendingOrders((prev) => ({
|
||||
...prev,
|
||||
[photo.id]: v ?? photo.sortOrder,
|
||||
}))
|
||||
}
|
||||
status={
|
||||
pendingOrders[photo.id] != null &&
|
||||
pendingOrders[photo.id] !== photo.sortOrder
|
||||
? 'warning'
|
||||
: undefined
|
||||
}
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<SaveOutlined />}
|
||||
disabled={pendingOrders[photo.id] == null || pendingOrders[photo.id] === photo.sortOrder}
|
||||
onClick={() =>
|
||||
updateMutation.mutate({
|
||||
photoId: photo.id,
|
||||
sortOrder: pendingOrders[photo.id]!,
|
||||
})
|
||||
}
|
||||
>
|
||||
Позиция
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ExperimentOutlined />}
|
||||
loading={recalcMutation.isPending && recalcMutation.variables === photo.id}
|
||||
onClick={() => recalcMutation.mutate(photo.id)}
|
||||
>
|
||||
Признаки
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="Удалить это фото?"
|
||||
description="Единственное фото объекта в активном наборе удалить нельзя."
|
||||
okText="Удалить"
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={() => deleteMutation.mutate(photo.id)}
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
loading={deleteMutation.isPending && deleteMutation.variables === photo.id}
|
||||
/>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
)}
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
List,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined } from '@ant-design/icons'
|
||||
import { fetchAttractions } from '@/api/attractions'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import { fetchActiveSet, putSetItems } from '@/api/sets'
|
||||
import type { AttractionSet } from '@/api/types'
|
||||
|
||||
interface SelectedItem {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Редактор состава набора. API не умеет читать состав напрямую:
|
||||
* для ACTIVE-набора он восстанавливается из публичного активного набора зоны,
|
||||
* для DRAFT редактор начинает с пустого списка. Сохранение всегда перезаписывает
|
||||
* состав целиком (PUT).
|
||||
*/
|
||||
export function SetItemsModal({
|
||||
set,
|
||||
areaId,
|
||||
onClose,
|
||||
}: {
|
||||
set: AttractionSet
|
||||
areaId: string
|
||||
onClose: () => void
|
||||
}) {
|
||||
const queryClient = useQueryClient()
|
||||
// null = предзаполнение ещё не готово; иначе — черновик пользователя.
|
||||
const [draft, setDraft] = useState<SelectedItem[] | null>(null)
|
||||
|
||||
const attractionsQuery = useQuery({
|
||||
queryKey: ['admin-attractions', areaId, 'all'],
|
||||
queryFn: () => fetchAttractions({ areaId, page: 0, size: 100, sort: 'name,asc' }),
|
||||
})
|
||||
|
||||
const activeQuery = useQuery({
|
||||
queryKey: ['active-set', areaId],
|
||||
queryFn: () => fetchActiveSet(areaId),
|
||||
enabled: set.status === 'ACTIVE',
|
||||
retry: false,
|
||||
})
|
||||
|
||||
// Предзаполнение: для ACTIVE-набора состав читается из публичного активного набора зоны.
|
||||
const initialItems: SelectedItem[] | null = useMemo(() => {
|
||||
if (set.status !== 'ACTIVE') return []
|
||||
if (activeQuery.isSuccess) {
|
||||
return activeQuery.data.attractions.map((a) => ({ id: a.id, name: a.name }))
|
||||
}
|
||||
if (activeQuery.isError) return []
|
||||
return null
|
||||
}, [set.status, activeQuery.isSuccess, activeQuery.isError, activeQuery.data])
|
||||
|
||||
const items = draft ?? initialItems ?? []
|
||||
const hydrated = initialItems != null
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: (attractionIds: string[]) => putSetItems(set.id, attractionIds),
|
||||
onSuccess: (updated) => {
|
||||
notifySuccess('Состав сохранён', `${updated.name}: ${updated.itemCount} шт.`)
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
|
||||
onClose()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось сохранить состав'),
|
||||
})
|
||||
|
||||
const availableOptions = useMemo(() => {
|
||||
const chosen = new Set((draft ?? initialItems ?? []).map((i) => i.id))
|
||||
return (attractionsQuery.data?.content ?? [])
|
||||
.filter((a) => !chosen.has(a.id))
|
||||
.map((a) => ({ value: a.id, label: a.name }))
|
||||
}, [attractionsQuery.data, draft, initialItems])
|
||||
|
||||
const addItem = (id: string, name: string) => {
|
||||
setDraft([...items, { id, name }])
|
||||
}
|
||||
|
||||
const move = (index: number, delta: -1 | 1) => {
|
||||
const next = [...items]
|
||||
const target = index + delta
|
||||
if (target < 0 || target >= next.length) return
|
||||
;[next[index], next[target]] = [next[target], next[index]]
|
||||
setDraft(next)
|
||||
}
|
||||
|
||||
const nameById = new Map((attractionsQuery.data?.content ?? []).map((a) => [a.id, a.name]))
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={`Состав набора «${set.name}»`}
|
||||
open
|
||||
width={680}
|
||||
onCancel={onClose}
|
||||
confirmLoading={saveMutation.isPending}
|
||||
okButtonProps={{ disabled: items.length === 0 }}
|
||||
okText="Сохранить состав"
|
||||
onOk={() => saveMutation.mutate(items.map((i) => i.id))}
|
||||
>
|
||||
{set.status === 'DRAFT' && (
|
||||
<Alert
|
||||
style={{ marginBottom: 16 }}
|
||||
type="info"
|
||||
showIcon
|
||||
message="Состав черновика нельзя прочитать из API — редактор задаёт его целиком."
|
||||
description="Сохранение полностью перезапишет текущий состав. Пустой состав сохранить нельзя."
|
||||
/>
|
||||
)}
|
||||
{!hydrated || attractionsQuery.isLoading ? (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
|
||||
<Spin />
|
||||
</div>
|
||||
) : (
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Select
|
||||
placeholder="Добавить достопримечательность зоны…"
|
||||
value={null}
|
||||
options={availableOptions}
|
||||
onSelect={(value: string | null) => {
|
||||
if (value) addItem(value, nameById.get(value) ?? value)
|
||||
}}
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: '100%' }}
|
||||
notFoundContent="Все достопримечательности зоны уже в наборе"
|
||||
/>
|
||||
{items.length === 0 ? (
|
||||
<Typography.Text type="secondary">
|
||||
Состав пуст — добавьте хотя бы один объект.
|
||||
</Typography.Text>
|
||||
) : (
|
||||
<List
|
||||
size="small"
|
||||
bordered
|
||||
dataSource={items.map((item, index) => ({ ...item, index }))}
|
||||
renderItem={(item) => (
|
||||
<List.Item
|
||||
extra={
|
||||
<Space size={4}>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
icon={<ArrowUpOutlined />}
|
||||
disabled={item.index === 0}
|
||||
onClick={() => move(item.index, -1)}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
icon={<ArrowDownOutlined />}
|
||||
disabled={item.index === items.length - 1}
|
||||
onClick={() => move(item.index, 1)}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
type="text"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => setDraft(items.filter((i) => i.id !== item.id))}
|
||||
/>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<Typography.Text>
|
||||
{item.index + 1}. {item.name}
|
||||
</Typography.Text>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||
import { activateSet, archiveSet, createSet, fetchSets, renameSet } from '@/api/sets'
|
||||
import type { AttractionSet } from '@/api/types'
|
||||
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
||||
import { setStatusMeta } from '@/utils/format'
|
||||
import { SetItemsModal } from '@/pages/sets/SetItemsModal'
|
||||
|
||||
interface NameFormValues {
|
||||
name: string
|
||||
}
|
||||
|
||||
export function SetListPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [areaId, setAreaId] = useState<string | null>(searchParams.get('area'))
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [renaming, setRenaming] = useState<AttractionSet | null>(null)
|
||||
const [editingItems, setEditingItems] = useState<AttractionSet | null>(null)
|
||||
const [createForm] = Form.useForm<NameFormValues>()
|
||||
const [renameForm] = Form.useForm<NameFormValues>()
|
||||
|
||||
const setsQuery = useQuery({
|
||||
queryKey: ['admin-sets', areaId ?? 'none'],
|
||||
queryFn: () => fetchSets(areaId!),
|
||||
enabled: areaId != null,
|
||||
})
|
||||
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId ?? 'none'] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
|
||||
}
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (name: string) => createSet(areaId!, name),
|
||||
onSuccess: (set) => {
|
||||
notifySuccess('Набор создан', `${set.name} (черновик)`)
|
||||
setCreateOpen(false)
|
||||
createForm.resetFields()
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось создать набор'),
|
||||
})
|
||||
|
||||
const renameMutation = useMutation({
|
||||
mutationFn: ({ id, name }: { id: string; name: string }) => renameSet(id, name),
|
||||
onSuccess: (set) => {
|
||||
notifySuccess('Набор переименован', set.name)
|
||||
setRenaming(null)
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось переименовать набор'),
|
||||
})
|
||||
|
||||
const activateMutation = useMutation({
|
||||
mutationFn: activateSet,
|
||||
onSuccess: (set) => {
|
||||
notifySuccess('Набор активирован', set.name)
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось активировать набор'),
|
||||
})
|
||||
|
||||
const archiveMutation = useMutation({
|
||||
mutationFn: archiveSet,
|
||||
onSuccess: (set) => {
|
||||
notifySuccess('Набор заархивирован', set.name)
|
||||
invalidate()
|
||||
},
|
||||
onError: (e) => notifyApiError(e, 'Не удалось заархивировать набор'),
|
||||
})
|
||||
|
||||
const changeArea = (value: string | null) => {
|
||||
setAreaId(value)
|
||||
setSearchParams(value ? { area: value } : {}, { replace: true })
|
||||
}
|
||||
|
||||
const columns: ColumnsType<AttractionSet> = [
|
||||
{ title: 'Название', dataIndex: 'name', key: 'name' },
|
||||
{
|
||||
title: 'Статус',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
width: 140,
|
||||
render: (status: AttractionSet['status']) => (
|
||||
<Tag color={setStatusMeta[status].color}>{setStatusMeta[status].label}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Объектов',
|
||||
dataIndex: 'itemCount',
|
||||
key: 'itemCount',
|
||||
width: 100,
|
||||
align: 'right',
|
||||
},
|
||||
{
|
||||
title: 'Действия',
|
||||
key: 'actions',
|
||||
width: 380,
|
||||
render: (_, set) => (
|
||||
<Space size={4} wrap>
|
||||
{set.status !== 'ARCHIVED' && (
|
||||
<Button size="small" onClick={() => setEditingItems(set)}>
|
||||
Состав ({set.itemCount})
|
||||
</Button>
|
||||
)}
|
||||
{set.status !== 'ARCHIVED' && (
|
||||
<Button size="small" onClick={() => setRenaming(set)}>
|
||||
Переименовать
|
||||
</Button>
|
||||
)}
|
||||
{set.status === 'DRAFT' && (
|
||||
<Popconfirm
|
||||
title="Активировать набор?"
|
||||
description="Текущий активный набор зоны (если есть) будет автоматически заархивирован."
|
||||
okText="Активировать"
|
||||
onConfirm={() => activateMutation.mutate(set.id)}
|
||||
>
|
||||
<Button size="small" type="primary" loading={activateMutation.isPending && activateMutation.variables === set.id}>
|
||||
Активировать
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{set.status === 'ACTIVE' && (
|
||||
<Popconfirm
|
||||
title="Заархивировать набор?"
|
||||
description="Набор станет неизменяемым; в зоне не останется активного набора, пока не будет активирован другой."
|
||||
okText="Архивировать"
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={() => archiveMutation.mutate(set.id)}
|
||||
>
|
||||
<Button size="small" danger loading={archiveMutation.isPending && archiveMutation.variables === set.id}>
|
||||
В архив
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{set.status === 'ARCHIVED' && (
|
||||
<Typography.Text type="secondary">нет действий</Typography.Text>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
const sets = setsQuery.data ?? []
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="page-header-flex">
|
||||
<Typography.Title level={3} className="page-title">
|
||||
Наборы
|
||||
</Typography.Title>
|
||||
<Space>
|
||||
<AreaTreeSelect
|
||||
value={areaId}
|
||||
onChange={changeArea}
|
||||
placeholder="Зона (обязательно)"
|
||||
allowClear
|
||||
/>
|
||||
<Button type="primary" disabled={!areaId} onClick={() => setCreateOpen(true)}>
|
||||
Создать набор
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{!areaId ? (
|
||||
<Empty description="Выберите зону, чтобы увидеть наборы" style={{ marginTop: 64 }} />
|
||||
) : (
|
||||
<Table<AttractionSet>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={sets}
|
||||
loading={setsQuery.isLoading}
|
||||
pagination={false}
|
||||
locale={{ emptyText: <Empty description="В зоне пока нет наборов" /> }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
title="Новый набор"
|
||||
open={createOpen}
|
||||
onCancel={() => setCreateOpen(false)}
|
||||
confirmLoading={createMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await createForm.validateFields()
|
||||
createMutation.mutate(values.name.trim())
|
||||
}}
|
||||
>
|
||||
<Form form={createForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Название"
|
||||
rules={[{ required: true, message: 'Укажите название' }]}
|
||||
>
|
||||
<Input placeholder="Например, Весна 2027" maxLength={255} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="Переименовать набор"
|
||||
key={renaming?.id ?? 'rename-closed'}
|
||||
open={renaming != null}
|
||||
onCancel={() => setRenaming(null)}
|
||||
confirmLoading={renameMutation.isPending}
|
||||
onOk={async () => {
|
||||
const values = await renameForm.validateFields()
|
||||
renameMutation.mutate({ id: renaming!.id, name: values.name.trim() })
|
||||
}}
|
||||
>
|
||||
<Form form={renameForm} layout="vertical" initialValues={{ name: renaming?.name }}>
|
||||
<Form.Item
|
||||
name="name"
|
||||
label="Название"
|
||||
rules={[{ required: true, message: 'Укажите название' }]}
|
||||
>
|
||||
<Input maxLength={255} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{editingItems != null && areaId != null && (
|
||||
<SetItemsModal set={editingItems} areaId={areaId} onClose={() => setEditingItems(null)} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useState } from 'react'
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query'
|
||||
import { Button, Card, DatePicker, Form, Input, Select, Space, Table, Tag, Typography } from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import type { TablePaginationConfig } from 'antd/es/table'
|
||||
import type { FilterValue, SorterResult } from 'antd/es/table/interface'
|
||||
import type { Dayjs } from 'dayjs'
|
||||
import { fetchAttractions } from '@/api/attractions'
|
||||
import { fetchVisits } from '@/api/visits'
|
||||
import type { Visit, VisitFilter } from '@/api/types'
|
||||
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
||||
import { formatConfidence, formatUtc, verdictMeta } from '@/utils/format'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
const DEFAULT_SORT = 'visitedAt,desc'
|
||||
|
||||
interface FilterFormValues {
|
||||
areaId?: string | null
|
||||
attractionId?: string | null
|
||||
userId?: string
|
||||
range?: [Dayjs | null, Dayjs | null] | null
|
||||
}
|
||||
|
||||
export function VisitListPage() {
|
||||
const [form] = Form.useForm<FilterFormValues>()
|
||||
const watchedAreaId = Form.useWatch('areaId', form)
|
||||
const [applied, setApplied] = useState<VisitFilter>({})
|
||||
const [page, setPage] = useState(0)
|
||||
const [sort, setSort] = useState(DEFAULT_SORT)
|
||||
|
||||
const attractionsQuery = useQuery({
|
||||
queryKey: ['admin-attractions', watchedAreaId ?? 'none', 'filter'],
|
||||
queryFn: () =>
|
||||
fetchAttractions({ areaId: watchedAreaId!, page: 0, size: 100, sort: 'name,asc' }),
|
||||
enabled: watchedAreaId != null,
|
||||
})
|
||||
|
||||
const visitsQuery = useQuery({
|
||||
queryKey: ['admin-visits', applied, page, sort],
|
||||
queryFn: () => fetchVisits(applied, { page, size: PAGE_SIZE, sort }),
|
||||
placeholderData: keepPreviousData,
|
||||
})
|
||||
|
||||
const applyFilters = (values: FilterFormValues) => {
|
||||
setPage(0)
|
||||
setApplied({
|
||||
areaId: values.areaId ?? undefined,
|
||||
attractionId: values.attractionId ?? undefined,
|
||||
userId: values.userId?.trim() || undefined,
|
||||
from: values.range?.[0]?.format('YYYY-MM-DD'),
|
||||
to: values.range?.[1]?.format('YYYY-MM-DD'),
|
||||
})
|
||||
}
|
||||
|
||||
const handleTableChange = (
|
||||
pagination: TablePaginationConfig,
|
||||
_filters: Record<string, FilterValue | null>,
|
||||
sorter: SorterResult<Visit> | SorterResult<Visit>[],
|
||||
) => {
|
||||
if (pagination.current != null) setPage(pagination.current - 1)
|
||||
const single = !Array.isArray(sorter) ? sorter : sorter[0]
|
||||
if (single?.order) {
|
||||
setSort(`${single.field as string},${single.order === 'ascend' ? 'asc' : 'desc'}`)
|
||||
} else {
|
||||
setSort(DEFAULT_SORT)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<Visit> = [
|
||||
{ title: 'Достопримечательность', dataIndex: 'attractionName', key: 'attractionName' },
|
||||
{
|
||||
title: 'Дата и время (UTC)',
|
||||
dataIndex: 'visitedAt',
|
||||
key: 'visitedAt',
|
||||
width: 190,
|
||||
render: (v: string) => formatUtc(v),
|
||||
sorter: true,
|
||||
defaultSortOrder: 'descend',
|
||||
},
|
||||
{
|
||||
title: 'Вердикт',
|
||||
dataIndex: 'verdict',
|
||||
key: 'verdict',
|
||||
width: 170,
|
||||
render: (v: Visit['verdict']) => (
|
||||
<Tag color={verdictMeta[v].color}>{verdictMeta[v].label}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Уверенность',
|
||||
dataIndex: 'confidence',
|
||||
key: 'confidence',
|
||||
width: 130,
|
||||
align: 'right',
|
||||
render: (v: number) => formatConfidence(v),
|
||||
sorter: true,
|
||||
},
|
||||
]
|
||||
|
||||
const data = visitsQuery.data
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography.Title level={3} className="page-title" style={{ marginBottom: 16 }}>
|
||||
Визиты
|
||||
</Typography.Title>
|
||||
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
onFinish={applyFilters}
|
||||
style={{ rowGap: 12, flexWrap: 'wrap', alignItems: 'center' }}
|
||||
>
|
||||
<Form.Item name="areaId" style={{ marginRight: 12 }}>
|
||||
<AreaTreeSelect
|
||||
placeholder="Зона"
|
||||
allowClear
|
||||
onChange={() => form.setFieldValue('attractionId', undefined)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="attractionId" style={{ marginRight: 12 }}>
|
||||
<Select
|
||||
placeholder={watchedAreaId ? 'Достопримечательность' : 'Сначала выберите зону'}
|
||||
disabled={watchedAreaId == null}
|
||||
loading={attractionsQuery.isLoading}
|
||||
options={(attractionsQuery.data?.content ?? []).map((a) => ({
|
||||
value: a.id,
|
||||
label: a.name,
|
||||
}))}
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
style={{ width: 280 }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="userId" style={{ marginRight: 12 }}>
|
||||
<Input placeholder="ID пользователя" allowClear style={{ width: 240 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="range" style={{ marginRight: 12 }}>
|
||||
<DatePicker.RangePicker placeholder={['С даты', 'По дату']} allowEmpty={[true, true]} />
|
||||
</Form.Item>
|
||||
<Form.Item style={{ marginRight: 0 }}>
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit" loading={visitsQuery.isFetching}>
|
||||
Применить
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
form.resetFields()
|
||||
setApplied({})
|
||||
setPage(0)
|
||||
}}
|
||||
>
|
||||
Сбросить
|
||||
</Button>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Table<Visit>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={data?.content ?? []}
|
||||
loading={visitsQuery.isLoading}
|
||||
onChange={handleTableChange}
|
||||
pagination={{
|
||||
current: (data?.number ?? 0) + 1,
|
||||
pageSize: data?.size ?? PAGE_SIZE,
|
||||
total: data?.totalElements ?? 0,
|
||||
showSizeChanger: false,
|
||||
showTotal: (total) => `Всего: ${total}`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import type { CvProfile, SetStatus, Verdict } from '@/api/types'
|
||||
|
||||
dayjs.extend(utc)
|
||||
|
||||
/** Бэкенд хранит время в UTC без зоны — форматируем как UTC. */
|
||||
export function formatUtc(iso: string | null | undefined): string {
|
||||
if (!iso) return '—'
|
||||
const d = dayjs.utc(iso)
|
||||
return d.isValid() ? d.format('DD.MM.YYYY HH:mm:ss') : iso
|
||||
}
|
||||
|
||||
export function formatConfidence(confidence: number | null | undefined): string {
|
||||
if (confidence == null) return '—'
|
||||
return confidence.toFixed(2)
|
||||
}
|
||||
|
||||
export const verdictMeta: Record<Verdict, { label: string; color: string }> = {
|
||||
match: { label: 'Совпадение', color: 'green' },
|
||||
uncertain: { label: 'Неопределённо', color: 'orange' },
|
||||
no_match: { label: 'Нет совпадения', color: 'red' },
|
||||
}
|
||||
|
||||
export const cvProfileMeta: Record<CvProfile, { label: string; color: string }> = {
|
||||
facade: { label: 'Фасад', color: 'blue' },
|
||||
monument: { label: 'Памятник', color: 'purple' },
|
||||
repetitive: { label: 'Повторяющийся объект', color: 'cyan' },
|
||||
}
|
||||
|
||||
export const setStatusMeta: Record<SetStatus, { label: string; color: string }> = {
|
||||
DRAFT: { label: 'Черновик', color: 'default' },
|
||||
ACTIVE: { label: 'Активен', color: 'green' },
|
||||
ARCHIVED: { label: 'В архиве', color: 'default' },
|
||||
}
|
||||
|
||||
export const cvProfileOptions = (Object.keys(cvProfileMeta) as CvProfile[]).map((value) => ({
|
||||
value,
|
||||
label: cvProfileMeta[value].label,
|
||||
}))
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
|
||||
/* Path alias for '@/' */
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
// Бэкенд не настраивает CORS, поэтому в dev все запросы /api идут через прокси.
|
||||
'/api': {
|
||||
target: 'http://localhost:8080',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user