diff --git a/src/api/sets.ts b/src/api/sets.ts index 6b6b15c..b0da035 100644 --- a/src/api/sets.ts +++ b/src/api/sets.ts @@ -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 { const resp = await http.get(`/admin/areas/${areaId}/sets`) @@ -36,8 +36,13 @@ export async function archiveSet(id: string): Promise { return resp.data } -/** Публичный активный набор зоны — единственный способ прочитать состав набора. */ -export async function fetchActiveSet(areaId: string): Promise { - const resp = await http.get(`/areas/${areaId}/active-set`) +/** Удалить неактивный набор (DRAFT/ARCHIVED) вместе с составом; ACTIVE → 409. */ +export async function deleteSet(id: string): Promise { + await http.delete(`/admin/sets/${id}`) +} + +/** Состав набора любого статуса (отсортирован по названию). */ +export async function fetchSetItems(id: string): Promise { + const resp = await http.get(`/admin/sets/${id}/items`) return resp.data } diff --git a/src/api/types.ts b/src/api/types.ts index cca77c0..e21fcfc 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -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' diff --git a/src/pages/sets/SetItemsModal.tsx b/src/pages/sets/SetItemsModal.tsx index e3a4e28..2407afc 100644 --- a/src/pages/sets/SetItemsModal.tsx +++ b/src/pages/sets/SetItemsModal.tsx @@ -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(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 ? ( + + ) : undefined + } confirmLoading={saveMutation.isPending} okButtonProps={{ disabled: items.length === 0 }} okText="Сохранить состав" onOk={() => saveMutation.mutate(items.map((i) => i.id))} > - {set.status === 'DRAFT' && ( + {readOnly && ( )} - {!hydrated || attractionsQuery.isLoading ? ( + {!hydrated || (!readOnly && attractionsQuery.isLoading) ? (
) : ( - { + if (value) addItem(value, nameById.get(value) ?? value) + }} + showSearch + optionFilterProp="label" + style={{ width: '100%' }} + notFoundContent="Все достопримечательности зоны уже в наборе" + /> + )} {items.length === 0 ? ( - Состав пуст — добавьте хотя бы один объект. + Состав пуст{readOnly ? '.' : ' — добавьте хотя бы один объект.'} ) : ( ( - - )} + {set.status !== 'ARCHIVED' && ( )} - {set.status === 'ARCHIVED' && ( - нет действий + {set.status !== 'ACTIVE' && ( + deleteMutation.mutate(set)} + > + + )} ),