admin set
This commit is contained in:
+9
-4
@@ -1,5 +1,5 @@
|
|||||||
import { http } from '@/api/http'
|
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[]> {
|
export async function fetchSets(areaId: string): Promise<AttractionSet[]> {
|
||||||
const resp = await http.get<AttractionSet[]>(`/admin/areas/${areaId}/sets`)
|
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
|
return resp.data
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Публичный активный набор зоны — единственный способ прочитать состав набора. */
|
/** Удалить неактивный набор (DRAFT/ARCHIVED) вместе с составом; ACTIVE → 409. */
|
||||||
export async function fetchActiveSet(areaId: string): Promise<ActiveSet> {
|
export async function deleteSet(id: string): Promise<void> {
|
||||||
const resp = await http.get<ActiveSet>(`/areas/${areaId}/active-set`)
|
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
|
return resp.data
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-1
@@ -112,13 +112,21 @@ export interface AttractionSet {
|
|||||||
itemCount: number
|
itemCount: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Из публичного GET /areas/{areaId}/active-set — источник текущего состава ACTIVE-набора. */
|
/** Публичный активный набор зоны: GET /areas/{areaId}/active-set. */
|
||||||
export interface ActiveSet {
|
export interface ActiveSet {
|
||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
attractions: { id: string; name: string; iconUrl: string | null; visited: boolean }[]
|
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'
|
export type Verdict = 'match' | 'uncertain' | 'no_match'
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined } from '@ant-design/icons'
|
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined } from '@ant-design/icons'
|
||||||
import { fetchAttractions } from '@/api/attractions'
|
import { fetchAttractions } from '@/api/attractions'
|
||||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
import { notifyApiError, notifySuccess } from '@/api/errors'
|
||||||
import { fetchActiveSet, putSetItems } from '@/api/sets'
|
import { fetchSetItems, putSetItems } from '@/api/sets'
|
||||||
import type { AttractionSet } from '@/api/types'
|
import type { AttractionSet } from '@/api/types'
|
||||||
|
|
||||||
interface SelectedItem {
|
interface SelectedItem {
|
||||||
@@ -22,10 +22,9 @@ interface SelectedItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Редактор состава набора. API не умеет читать состав напрямую:
|
* Редактор состава набора. Текущий состав читается админским эндпоинтом
|
||||||
* для ACTIVE-набора он восстанавливается из публичного активного набора зоны,
|
* GET /admin/sets/{id}/items (работает для любого статуса). Для ARCHIVED —
|
||||||
* для DRAFT редактор начинает с пустого списка. Сохранение всегда перезаписывает
|
* только просмотр; сохранение всегда перезаписывает состав целиком (PUT).
|
||||||
* состав целиком (PUT).
|
|
||||||
*/
|
*/
|
||||||
export function SetItemsModal({
|
export function SetItemsModal({
|
||||||
set,
|
set,
|
||||||
@@ -37,30 +36,29 @@ export function SetItemsModal({
|
|||||||
onClose: () => void
|
onClose: () => void
|
||||||
}) {
|
}) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const readOnly = set.status === 'ARCHIVED'
|
||||||
// null = предзаполнение ещё не готово; иначе — черновик пользователя.
|
// null = предзаполнение ещё не готово; иначе — черновик пользователя.
|
||||||
const [draft, setDraft] = useState<SelectedItem[] | null>(null)
|
const [draft, setDraft] = useState<SelectedItem[] | null>(null)
|
||||||
|
|
||||||
const attractionsQuery = useQuery({
|
const attractionsQuery = useQuery({
|
||||||
queryKey: ['admin-attractions', areaId, 'all'],
|
queryKey: ['admin-attractions', areaId, 'all'],
|
||||||
queryFn: () => fetchAttractions({ areaId, page: 0, size: 100, sort: 'name,asc' }),
|
queryFn: () => fetchAttractions({ areaId, page: 0, size: 100, sort: 'name,asc' }),
|
||||||
|
enabled: !readOnly,
|
||||||
})
|
})
|
||||||
|
|
||||||
const activeQuery = useQuery({
|
const itemsQuery = useQuery({
|
||||||
queryKey: ['active-set', areaId],
|
queryKey: ['set-items', set.id],
|
||||||
queryFn: () => fetchActiveSet(areaId),
|
queryFn: () => fetchSetItems(set.id),
|
||||||
enabled: set.status === 'ACTIVE',
|
|
||||||
retry: false,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Предзаполнение: для ACTIVE-набора состав читается из публичного активного набора зоны.
|
// Предзаполнение: состав читается напрямую, включая черновики и архив.
|
||||||
const initialItems: SelectedItem[] | null = useMemo(() => {
|
const initialItems: SelectedItem[] | null = useMemo(() => {
|
||||||
if (set.status !== 'ACTIVE') return []
|
if (itemsQuery.isSuccess) {
|
||||||
if (activeQuery.isSuccess) {
|
return itemsQuery.data.map((i) => ({ id: i.attractionId, name: i.name }))
|
||||||
return activeQuery.data.attractions.map((a) => ({ id: a.id, name: a.name }))
|
|
||||||
}
|
}
|
||||||
if (activeQuery.isError) return []
|
if (itemsQuery.isError) return []
|
||||||
return null
|
return null
|
||||||
}, [set.status, activeQuery.isSuccess, activeQuery.isError, activeQuery.data])
|
}, [itemsQuery.isSuccess, itemsQuery.isError, itemsQuery.data])
|
||||||
|
|
||||||
const items = draft ?? initialItems ?? []
|
const items = draft ?? initialItems ?? []
|
||||||
const hydrated = initialItems != null
|
const hydrated = initialItems != null
|
||||||
@@ -70,7 +68,7 @@ export function SetItemsModal({
|
|||||||
onSuccess: (updated) => {
|
onSuccess: (updated) => {
|
||||||
notifySuccess('Состав сохранён', `${updated.name}: ${updated.itemCount} шт.`)
|
notifySuccess('Состав сохранён', `${updated.name}: ${updated.itemCount} шт.`)
|
||||||
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId] })
|
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
|
void queryClient.invalidateQueries({ queryKey: ['set-items', set.id] })
|
||||||
onClose()
|
onClose()
|
||||||
},
|
},
|
||||||
onError: (e) => notifyApiError(e, 'Не удалось сохранить состав'),
|
onError: (e) => notifyApiError(e, 'Не удалось сохранить состав'),
|
||||||
@@ -103,41 +101,47 @@ export function SetItemsModal({
|
|||||||
open
|
open
|
||||||
width={680}
|
width={680}
|
||||||
onCancel={onClose}
|
onCancel={onClose}
|
||||||
|
footer={
|
||||||
|
readOnly ? (
|
||||||
|
<Button onClick={onClose}>Закрыть</Button>
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
confirmLoading={saveMutation.isPending}
|
confirmLoading={saveMutation.isPending}
|
||||||
okButtonProps={{ disabled: items.length === 0 }}
|
okButtonProps={{ disabled: items.length === 0 }}
|
||||||
okText="Сохранить состав"
|
okText="Сохранить состав"
|
||||||
onOk={() => saveMutation.mutate(items.map((i) => i.id))}
|
onOk={() => saveMutation.mutate(items.map((i) => i.id))}
|
||||||
>
|
>
|
||||||
{set.status === 'DRAFT' && (
|
{readOnly && (
|
||||||
<Alert
|
<Alert
|
||||||
style={{ marginBottom: 16 }}
|
style={{ marginBottom: 16 }}
|
||||||
type="info"
|
type="info"
|
||||||
showIcon
|
showIcon
|
||||||
message="Состав черновика нельзя прочитать из API — редактор задаёт его целиком."
|
message="Архивный набор неизменяем — состав доступен только для просмотра."
|
||||||
description="Сохранение полностью перезапишет текущий состав. Пустой состав сохранить нельзя."
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{!hydrated || attractionsQuery.isLoading ? (
|
{!hydrated || (!readOnly && attractionsQuery.isLoading) ? (
|
||||||
<div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
|
||||||
<Spin />
|
<Spin />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||||
<Select
|
{!readOnly && (
|
||||||
placeholder="Добавить достопримечательность зоны…"
|
<Select
|
||||||
value={null}
|
placeholder="Добавить достопримечательность зоны…"
|
||||||
options={availableOptions}
|
value={null}
|
||||||
onSelect={(value: string | null) => {
|
options={availableOptions}
|
||||||
if (value) addItem(value, nameById.get(value) ?? value)
|
onSelect={(value: string | null) => {
|
||||||
}}
|
if (value) addItem(value, nameById.get(value) ?? value)
|
||||||
showSearch
|
}}
|
||||||
optionFilterProp="label"
|
showSearch
|
||||||
style={{ width: '100%' }}
|
optionFilterProp="label"
|
||||||
notFoundContent="Все достопримечательности зоны уже в наборе"
|
style={{ width: '100%' }}
|
||||||
/>
|
notFoundContent="Все достопримечательности зоны уже в наборе"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{items.length === 0 ? (
|
{items.length === 0 ? (
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
Состав пуст — добавьте хотя бы один объект.
|
Состав пуст{readOnly ? '.' : ' — добавьте хотя бы один объект.'}
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
) : (
|
) : (
|
||||||
<List
|
<List
|
||||||
@@ -147,29 +151,31 @@ export function SetItemsModal({
|
|||||||
renderItem={(item) => (
|
renderItem={(item) => (
|
||||||
<List.Item
|
<List.Item
|
||||||
extra={
|
extra={
|
||||||
<Space size={4}>
|
readOnly ? undefined : (
|
||||||
<Button
|
<Space size={4}>
|
||||||
size="small"
|
<Button
|
||||||
type="text"
|
size="small"
|
||||||
icon={<ArrowUpOutlined />}
|
type="text"
|
||||||
disabled={item.index === 0}
|
icon={<ArrowUpOutlined />}
|
||||||
onClick={() => move(item.index, -1)}
|
disabled={item.index === 0}
|
||||||
/>
|
onClick={() => move(item.index, -1)}
|
||||||
<Button
|
/>
|
||||||
size="small"
|
<Button
|
||||||
type="text"
|
size="small"
|
||||||
icon={<ArrowDownOutlined />}
|
type="text"
|
||||||
disabled={item.index === items.length - 1}
|
icon={<ArrowDownOutlined />}
|
||||||
onClick={() => move(item.index, 1)}
|
disabled={item.index === items.length - 1}
|
||||||
/>
|
onClick={() => move(item.index, 1)}
|
||||||
<Button
|
/>
|
||||||
size="small"
|
<Button
|
||||||
type="text"
|
size="small"
|
||||||
danger
|
type="text"
|
||||||
icon={<DeleteOutlined />}
|
danger
|
||||||
onClick={() => setDraft(items.filter((i) => i.id !== item.id))}
|
icon={<DeleteOutlined />}
|
||||||
/>
|
onClick={() => setDraft(items.filter((i) => i.id !== item.id))}
|
||||||
</Space>
|
/>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Typography.Text>
|
<Typography.Text>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
import type { ColumnsType } from 'antd/es/table'
|
import type { ColumnsType } from 'antd/es/table'
|
||||||
import { useSearchParams } from 'react-router-dom'
|
import { useSearchParams } from 'react-router-dom'
|
||||||
import { notifyApiError, notifySuccess } from '@/api/errors'
|
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 type { AttractionSet } from '@/api/types'
|
||||||
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
import { AreaTreeSelect } from '@/components/AreaTreeSelect'
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile'
|
import { useIsMobile } from '@/hooks/useIsMobile'
|
||||||
@@ -45,7 +45,7 @@ export function SetListPage() {
|
|||||||
|
|
||||||
const invalidate = () => {
|
const invalidate = () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId ?? 'none'] })
|
void queryClient.invalidateQueries({ queryKey: ['admin-sets', areaId ?? 'none'] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['active-set', areaId] })
|
void queryClient.invalidateQueries({ queryKey: ['set-items'] })
|
||||||
}
|
}
|
||||||
|
|
||||||
const createMutation = useMutation({
|
const createMutation = useMutation({
|
||||||
@@ -87,6 +87,15 @@ export function SetListPage() {
|
|||||||
onError: (e) => notifyApiError(e, 'Не удалось заархивировать набор'),
|
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) => {
|
const changeArea = (value: string | null) => {
|
||||||
setAreaId(value)
|
setAreaId(value)
|
||||||
setSearchParams(value ? { area: value } : {}, { replace: true })
|
setSearchParams(value ? { area: value } : {}, { replace: true })
|
||||||
@@ -116,11 +125,9 @@ export function SetListPage() {
|
|||||||
width: 380,
|
width: 380,
|
||||||
render: (_, set) => (
|
render: (_, set) => (
|
||||||
<Space size={4} wrap>
|
<Space size={4} wrap>
|
||||||
{set.status !== 'ARCHIVED' && (
|
<Button size="small" onClick={() => setEditingItems(set)}>
|
||||||
<Button size="small" onClick={() => setEditingItems(set)}>
|
Состав ({set.itemCount})
|
||||||
Состав ({set.itemCount})
|
</Button>
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{set.status !== 'ARCHIVED' && (
|
{set.status !== 'ARCHIVED' && (
|
||||||
<Button size="small" onClick={() => setRenaming(set)}>
|
<Button size="small" onClick={() => setRenaming(set)}>
|
||||||
Переименовать
|
Переименовать
|
||||||
@@ -151,8 +158,22 @@ export function SetListPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
)}
|
)}
|
||||||
{set.status === 'ARCHIVED' && (
|
{set.status !== 'ACTIVE' && (
|
||||||
<Typography.Text type="secondary">нет действий</Typography.Text>
|
<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>
|
</Space>
|
||||||
),
|
),
|
||||||
|
|||||||
Reference in New Issue
Block a user