256 lines
8.6 KiB
TypeScript
256 lines
8.6 KiB
TypeScript
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 { useIsMobile } from '@/hooks/useIsMobile'
|
||
import { setStatusMeta } from '@/utils/format'
|
||
import { SetItemsModal } from '@/pages/sets/SetItemsModal'
|
||
|
||
interface NameFormValues {
|
||
name: string
|
||
}
|
||
|
||
export function SetListPage() {
|
||
const queryClient = useQueryClient()
|
||
const isMobile = useIsMobile()
|
||
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
|
||
size="middle"
|
||
direction={isMobile ? 'vertical' : 'horizontal'}
|
||
style={isMobile ? { width: '100%' } : undefined}
|
||
>
|
||
<AreaTreeSelect
|
||
value={areaId}
|
||
onChange={changeArea}
|
||
placeholder="Зона (обязательно)"
|
||
allowClear
|
||
style={isMobile ? { width: '100%' } : undefined}
|
||
/>
|
||
<Button
|
||
type="primary"
|
||
block={isMobile}
|
||
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}
|
||
scroll={{ x: 'max-content' }}
|
||
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)} />
|
||
)}
|
||
</>
|
||
)
|
||
}
|