admin set

This commit is contained in:
a.ilin
2026-10-07 14:36:06 +03:00
parent b63aeb8d4b
commit 01c6e0f076
4 changed files with 111 additions and 71 deletions
+9 -4
View File
@@ -1,5 +1,5 @@
import { http } from '@/api/http'
import type { ActiveSet, AttractionSet } from '@/api/types'
import type { AttractionSet, SetItem } from '@/api/types'
export async function fetchSets(areaId: string): Promise<AttractionSet[]> {
const resp = await http.get<AttractionSet[]>(`/admin/areas/${areaId}/sets`)
@@ -36,8 +36,13 @@ export async function archiveSet(id: string): Promise<AttractionSet> {
return resp.data
}
/** Публичный активный набор зоны — единственный способ прочитать состав набора. */
export async function fetchActiveSet(areaId: string): Promise<ActiveSet> {
const resp = await http.get<ActiveSet>(`/areas/${areaId}/active-set`)
/** Удалить неактивный набор (DRAFT/ARCHIVED) вместе с составом; ACTIVE → 409. */
export async function deleteSet(id: string): Promise<void> {
await http.delete(`/admin/sets/${id}`)
}
/** Состав набора любого статуса (отсортирован по названию). */
export async function fetchSetItems(id: string): Promise<SetItem[]> {
const resp = await http.get<SetItem[]>(`/admin/sets/${id}/items`)
return resp.data
}
+9 -1
View File
@@ -112,13 +112,21 @@ export interface AttractionSet {
itemCount: number
}
/** Из публичного GET /areas/{areaId}/active-set — источник текущего состава ACTIVE-набора. */
/** Публичный активный набор зоны: GET /areas/{areaId}/active-set. */
export interface ActiveSet {
id: string
name: string
attractions: { id: string; name: string; iconUrl: string | null; visited: boolean }[]
}
/** Элемент состава из админского GET /admin/sets/{id}/items (любой статус набора). */
export interface SetItem {
attractionId: string
name: string
/** Presigned GET URL иконки (TTL 1 час) — не кэшировать надолго. */
iconUrl: string | null
}
// ---------- Визиты ----------
export type Verdict = 'match' | 'uncertain' | 'no_match'
+63 -57
View File
@@ -13,7 +13,7 @@ import {
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 { fetchSetItems, putSetItems } from '@/api/sets'
import type { AttractionSet } from '@/api/types'
interface SelectedItem {
@@ -22,10 +22,9 @@ interface SelectedItem {
}
/**
* Редактор состава набора. API не умеет читать состав напрямую:
* для ACTIVE-набора он восстанавливается из публичного активного набора зоны,
* для DRAFT редактор начинает с пустого списка. Сохранение всегда перезаписывает
* состав целиком (PUT).
* Редактор состава набора. Текущий состав читается админским эндпоинтом
* GET /admin/sets/{id}/items (работает для любого статуса). Для ARCHIVED —
* только просмотр; сохранение всегда перезаписывает состав целиком (PUT).
*/
export function SetItemsModal({
set,
@@ -37,30 +36,29 @@ export function SetItemsModal({
onClose: () => void
}) {
const queryClient = useQueryClient()
const readOnly = set.status === 'ARCHIVED'
// 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' }),
enabled: !readOnly,
})
const activeQuery = useQuery({
queryKey: ['active-set', areaId],
queryFn: () => fetchActiveSet(areaId),
enabled: set.status === 'ACTIVE',
retry: false,
const itemsQuery = useQuery({
queryKey: ['set-items', set.id],
queryFn: () => fetchSetItems(set.id),
})
// Предзаполнение: для 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 (itemsQuery.isSuccess) {
return itemsQuery.data.map((i) => ({ id: i.attractionId, name: i.name }))
}
if (activeQuery.isError) return []
if (itemsQuery.isError) return []
return null
}, [set.status, activeQuery.isSuccess, activeQuery.isError, activeQuery.data])
}, [itemsQuery.isSuccess, itemsQuery.isError, itemsQuery.data])
const items = draft ?? initialItems ?? []
const hydrated = initialItems != null
@@ -70,7 +68,7 @@ export function SetItemsModal({
onSuccess: (updated) => {
notifySuccess('Состав сохранён', `${updated.name}: ${updated.itemCount} шт.`)
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId] })
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
void queryClient.invalidateQueries({ queryKey: ['set-items', set.id] })
onClose()
},
onError: (e) => notifyApiError(e, 'Не удалось сохранить состав'),
@@ -103,41 +101,47 @@ export function SetItemsModal({
open
width={680}
onCancel={onClose}
footer={
readOnly ? (
<Button onClick={onClose}>Закрыть</Button>
) : undefined
}
confirmLoading={saveMutation.isPending}
okButtonProps={{ disabled: items.length === 0 }}
okText="Сохранить состав"
onOk={() => saveMutation.mutate(items.map((i) => i.id))}
>
{set.status === 'DRAFT' && (
{readOnly && (
<Alert
style={{ marginBottom: 16 }}
type="info"
showIcon
message="Состав черновика нельзя прочитать из API — редактор задаёт его целиком."
description="Сохранение полностью перезапишет текущий состав. Пустой состав сохранить нельзя."
message="Архивный набор неизменяем — состав доступен только для просмотра."
/>
)}
{!hydrated || attractionsQuery.isLoading ? (
{!hydrated || (!readOnly && 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="Все достопримечательности зоны уже в наборе"
/>
{!readOnly && (
<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">
Состав пуст — добавьте хотя бы один объект.
Состав пуст{readOnly ? '.' : ' — добавьте хотя бы один объект.'}
</Typography.Text>
) : (
<List
@@ -147,29 +151,31 @@ export function SetItemsModal({
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>
readOnly ? undefined : (
<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>
+30 -9
View File
@@ -15,7 +15,7 @@ import {
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 { activateSet, archiveSet, createSet, deleteSet, fetchSets, renameSet } from '@/api/sets'
import type { AttractionSet } from '@/api/types'
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
import { useIsMobile } from '@/hooks/useIsMobile'
@@ -45,7 +45,7 @@ export function SetListPage() {
const invalidate = () => {
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId ?? 'none'] })
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
void queryClient.invalidateQueries({ queryKey: ['set-items'] })
}
const createMutation = useMutation({
@@ -87,6 +87,15 @@ export function SetListPage() {
onError: (e) => notifyApiError(e, 'Не удалось заархивировать набор'),
})
const deleteMutation = useMutation({
mutationFn: (set: AttractionSet) => deleteSet(set.id),
onSuccess: (_void, set) => {
notifySuccess('Набор удалён', set.name)
invalidate()
},
onError: (e) => notifyApiError(e, 'Не удалось удалить набор'),
})
const changeArea = (value: string | null) => {
setAreaId(value)
setSearchParams(value ? { area: value } : {}, { replace: true })
@@ -116,11 +125,9 @@ export function SetListPage() {
width: 380,
render: (_, set) => (
<Space size={4} wrap>
{set.status !== 'ARCHIVED' && (
<Button size="small" onClick={() => setEditingItems(set)}>
Состав ({set.itemCount})
</Button>
)}
<Button size="small" onClick={() => setEditingItems(set)}>
Состав ({set.itemCount})
</Button>
{set.status !== 'ARCHIVED' && (
<Button size="small" onClick={() => setRenaming(set)}>
Переименовать
@@ -151,8 +158,22 @@ export function SetListPage() {
</Button>
</Popconfirm>
)}
{set.status === 'ARCHIVED' && (
<Typography.Text type="secondary">нет действий</Typography.Text>
{set.status !== 'ACTIVE' && (
<Popconfirm
title="Удалить набор?"
description="Набор и его состав будут удалены безвозвратно. Посещения пользователей не затрагиваются."
okText="Удалить"
okButtonProps={{ danger: true }}
onConfirm={() => deleteMutation.mutate(set)}
>
<Button
size="small"
danger
loading={deleteMutation.isPending && deleteMutation.variables?.id === set.id}
>
Удалить
</Button>
</Popconfirm>
)}
</Space>
),