Updated categories page
Deploy Frontend / build-and-deploy (push) Failing after 25s
Details
Deploy Frontend / build-and-deploy (push) Failing after 25s
Details
This commit is contained in:
parent
f1e21f2112
commit
c3290d7c1d
|
|
@ -148,7 +148,7 @@
|
|||
│ │ ├── categories
|
||||
│ │ │ ├── CategoriesPage.tsx
|
||||
│ │ │ ├── components
|
||||
│ │ │ │ ├── CategoryEditModal.tsx
|
||||
│ │ │ │ ├── CategoryDrawer.tsx
|
||||
│ │ ├── flowNodes
|
||||
│ │ │ ├── FlowTreeGuidePage.tsx
|
||||
│ │ │ ├── FlowTreePage.tsx
|
||||
|
|
|
|||
|
|
@ -1,230 +1,204 @@
|
|||
import { useState } from 'react'
|
||||
import {
|
||||
Paper,
|
||||
Table,
|
||||
Badge,
|
||||
Group,
|
||||
ActionIcon,
|
||||
Button,
|
||||
Text,
|
||||
TextInput,
|
||||
Pagination,
|
||||
Loader,
|
||||
Center,
|
||||
Tooltip,
|
||||
Box,
|
||||
Stack,
|
||||
Switch,
|
||||
} from '@mantine/core'
|
||||
import { IconPencil, IconTrash, IconPlus, IconSearch } from '@tabler/icons-react'
|
||||
import { modals } from '@mantine/modals'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { ActionIcon, Badge, Button, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core'
|
||||
import { useDebouncedValue } from '@mantine/hooks'
|
||||
import { IconPencil, IconPlus, IconSearch, IconTrash } from '@tabler/icons-react'
|
||||
|
||||
import { useCategories, useDeleteCategory } from '@/features/categories/hooks/useCategories'
|
||||
import CategoryEditModal from './components/CategoryEditModal'
|
||||
import type { Category } from '@/features/categories/types'
|
||||
|
||||
import { PageHeader } from '@/components/ui/PageHeader'
|
||||
import { FilterBar } from '@/components/ui/FilterBar'
|
||||
import { DataTable, type Column } from '@/components/ui/DataTable'
|
||||
import { ConfirmModal } from '@/components/ui/ConfirmModal'
|
||||
import CategoryDrawer from './components/CategoryDrawer'
|
||||
|
||||
const LIMIT = 20
|
||||
|
||||
interface Filters {
|
||||
search: string
|
||||
isActive: string | null
|
||||
}
|
||||
|
||||
const EMPTY_FILTERS: Filters = {
|
||||
search: '',
|
||||
isActive: null,
|
||||
}
|
||||
|
||||
export default function CategoriesPage() {
|
||||
const [page, setPage] = useState(1)
|
||||
const [search, setSearch] = useState('')
|
||||
const [activeFilter, setActiveFilter] = useState<boolean | null>(null)
|
||||
const [editCategoryId, setEditCategoryId] = useState<number | null>(null)
|
||||
const [createModalOpened, setCreateModalOpened] = useState(false)
|
||||
const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS)
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400)
|
||||
|
||||
const { data, isLoading, isFetching } = useCategories({
|
||||
offset: (page - 1) * LIMIT,
|
||||
limit: LIMIT,
|
||||
...(search && { name: search }),
|
||||
...(activeFilter !== null && { is_active: activeFilter }),
|
||||
})
|
||||
const [drawerId, setDrawerId] = useState<number | 'new' | null>(null)
|
||||
const [deleteTarget, setDeleteTarget] = useState<Category | null>(null)
|
||||
|
||||
const deleteCategory = useDeleteCategory()
|
||||
|
||||
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
|
||||
// Сброс страницы при поиске
|
||||
useEffect(() => setPage(1), [debouncedSearch])
|
||||
|
||||
const handleDelete = (id: number) => {
|
||||
modals.openConfirmModal({
|
||||
title: 'Подтвердите удаление',
|
||||
children: (
|
||||
<Text size="sm">
|
||||
Вы уверены, что хотите удалить эту категорию? Все темы этой категории останутся без категории.
|
||||
</Text>
|
||||
),
|
||||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||||
confirmProps: { color: 'red' },
|
||||
onConfirm: () => deleteCategory.mutate(id),
|
||||
})
|
||||
const updateFilter = (patch: Partial<Filters>) => {
|
||||
setFilters((prev) => ({ ...prev, ...patch }))
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const requestParams = useMemo(() => {
|
||||
const params: Record<string, any> = { offset: (page - 1) * LIMIT, limit: LIMIT }
|
||||
if (debouncedSearch.length >= 2) params.name = debouncedSearch
|
||||
if (filters.isActive !== null) params.is_active = filters.isActive === 'true'
|
||||
return params
|
||||
}, [page, filters, debouncedSearch])
|
||||
|
||||
const { data, isLoading, isFetching } = useCategories(requestParams)
|
||||
const total = data?.total_count ?? 0
|
||||
|
||||
const activeCount = [
|
||||
debouncedSearch.length >= 2,
|
||||
filters.isActive !== null,
|
||||
].filter(Boolean).length
|
||||
|
||||
const handleReset = () => {
|
||||
setSearchInput('')
|
||||
setFilters(EMPTY_FILTERS)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget?.id) return
|
||||
await deleteCategory.mutateAsync(deleteTarget.id)
|
||||
setDeleteTarget(null)
|
||||
}
|
||||
|
||||
const columns: Column<Category>[] = [
|
||||
{
|
||||
key: 'id',
|
||||
header: 'ID',
|
||||
width: 80,
|
||||
cell: (r) => <Text size="sm" fw={500}>#{r.id}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'name',
|
||||
header: 'Название',
|
||||
cell: (r) => <Text size="sm" fw={500}>{r.name}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'code',
|
||||
header: 'Код',
|
||||
width: 200,
|
||||
cell: (r) => <Text size="sm" ff="monospace" c="dimmed">{r.code}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: 'Описание',
|
||||
cell: (r) => <Text size="sm" lineClamp={2} c="dimmed">{r.description || '—'}</Text>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Статус',
|
||||
width: 120,
|
||||
cell: (r) => (
|
||||
<Badge
|
||||
color={r.is_active ? 'green' : 'gray'}
|
||||
variant={r.is_active ? 'light' : 'filled'}
|
||||
size="sm"
|
||||
>
|
||||
{r.is_active ? 'Активна' : 'Неактивна'}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
width: 100,
|
||||
align: 'right',
|
||||
cell: (r) => (
|
||||
<Group gap="xs" justify="flex-end" wrap="nowrap">
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="blue"
|
||||
onClick={(e) => { e.stopPropagation(); setDrawerId(r.id!); }}
|
||||
>
|
||||
<IconPencil size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="red"
|
||||
onClick={(e) => { e.stopPropagation(); setDeleteTarget(r); }}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Категории тем</Text>
|
||||
<Group>
|
||||
<Text c="dimmed" size="sm">
|
||||
Всего: {data?.total_count || 0}
|
||||
</Text>
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={() => setCreateModalOpened(true)}
|
||||
>
|
||||
<Stack gap="lg">
|
||||
<PageHeader
|
||||
title="Категории тем"
|
||||
description={isLoading ? undefined : `Всего: ${total}`}
|
||||
actions={
|
||||
<Button leftSection={<IconPlus size={16} />} onClick={() => setDrawerId('new')}>
|
||||
Создать категорию
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Фильтры */}
|
||||
<Paper withBorder p="md">
|
||||
<Group gap="md" align="flex-end">
|
||||
<TextInput
|
||||
label="Поиск по названию"
|
||||
placeholder="Отпуска, больничные..."
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.currentTarget.value)
|
||||
setPage(1)
|
||||
}}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Только активные"
|
||||
checked={activeFilter === true}
|
||||
onChange={(e) => {
|
||||
setActiveFilter(e.currentTarget.checked ? true : null)
|
||||
setPage(1)
|
||||
}}
|
||||
/>
|
||||
</Group>
|
||||
</Paper>
|
||||
|
||||
{/* Таблица */}
|
||||
<Paper withBorder>
|
||||
{isLoading ? (
|
||||
<Center p={60}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<>
|
||||
<Table striped highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th style={{ width: 60 }}>ID</Table.Th>
|
||||
<Table.Th>Название</Table.Th>
|
||||
<Table.Th>Код</Table.Th>
|
||||
<Table.Th>Описание</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Статус</Table.Th>
|
||||
<Table.Th style={{ width: 100 }}>Действия</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{data?.data?.length === 0 ? (
|
||||
<Table.Tr>
|
||||
<Table.Td colSpan={6}>
|
||||
<Center p={40}>
|
||||
<Text c="dimmed">Категории не найдены</Text>
|
||||
</Center>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
) : (
|
||||
(data?.data || []).map((category) => (
|
||||
<Table.Tr key={category.id}>
|
||||
<Table.Td>{category.id}</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fw={500}>{category.name}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" ff="monospace" c="dimmed">
|
||||
{category.code}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text size="sm" lineClamp={2}>
|
||||
{category.description || '—'}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Badge
|
||||
color={category.is_active ? 'green' : 'gray'}
|
||||
variant={category.is_active ? 'light' : 'filled'}
|
||||
>
|
||||
{category.is_active ? 'Активна' : 'Неактивна'}
|
||||
</Badge>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Group gap="xs">
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
onClick={() => setEditCategoryId(category.id!)}
|
||||
>
|
||||
<IconPencil size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="red"
|
||||
onClick={() => handleDelete(category.id!)}
|
||||
>
|
||||
<IconTrash size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
|
||||
{/* Пагинация */}
|
||||
{totalPages > 1 && (
|
||||
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
Страница {page} из {totalPages}
|
||||
</Text>
|
||||
<Pagination
|
||||
value={page}
|
||||
onChange={setPage}
|
||||
total={totalPages}
|
||||
withEdges
|
||||
/>
|
||||
</Group>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Индикатор обновления */}
|
||||
{isFetching && !isLoading && (
|
||||
<Box
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
right: 20,
|
||||
zIndex: 1000
|
||||
}}
|
||||
>
|
||||
<Loader size="xs" />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Модальное окно редактирования */}
|
||||
<CategoryEditModal
|
||||
categoryId={editCategoryId}
|
||||
opened={editCategoryId !== null}
|
||||
onClose={() => setEditCategoryId(null)}
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Модальное окно создания */}
|
||||
<CategoryEditModal
|
||||
categoryId={null}
|
||||
opened={createModalOpened}
|
||||
onClose={() => setCreateModalOpened(false)}
|
||||
<FilterBar activeCount={activeCount} onReset={handleReset}>
|
||||
<TextInput
|
||||
placeholder="Поиск по названию"
|
||||
leftSection={<IconSearch size={16} />}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.currentTarget.value)}
|
||||
w={280}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Статус"
|
||||
data={[
|
||||
{ value: 'true', label: 'Только активные' },
|
||||
{ value: 'false', label: 'Неактивные' },
|
||||
]}
|
||||
value={filters.isActive}
|
||||
onChange={(isActive) => updateFilter({ isActive })}
|
||||
clearable
|
||||
w={180}
|
||||
/>
|
||||
</FilterBar>
|
||||
|
||||
<DataTable<Category>
|
||||
columns={columns}
|
||||
rows={data?.data ?? []}
|
||||
getRowId={(r) => r.id!}
|
||||
loading={isLoading}
|
||||
refreshing={isFetching}
|
||||
onRowClick={(r) => setDrawerId(r.id!)}
|
||||
empty={{
|
||||
title: 'Категории не найдены',
|
||||
description: activeCount > 0 ? 'Измените параметры фильтрации' : undefined,
|
||||
}}
|
||||
pagination={{ page, pageSize: LIMIT, total, onChange: setPage }}
|
||||
/>
|
||||
|
||||
<CategoryDrawer
|
||||
categoryId={drawerId === 'new' ? null : drawerId}
|
||||
opened={drawerId !== null}
|
||||
onClose={() => setDrawerId(null)}
|
||||
/>
|
||||
|
||||
<ConfirmModal
|
||||
opened={deleteTarget !== null}
|
||||
onClose={() => setDeleteTarget(null)}
|
||||
onConfirm={handleDelete}
|
||||
title="Подтвердите удаление"
|
||||
message="Вы уверены, что хотите удалить эту категорию? Все темы, привязанные к ней, останутся без категории."
|
||||
confirmLabel="Удалить"
|
||||
danger
|
||||
loading={deleteCategory.isPending}
|
||||
/>
|
||||
</Stack>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,145 @@
|
|||
import { useEffect } from 'react'
|
||||
import { Badge, Box, Button, Drawer, Group, Stack, Switch, Text, Textarea, TextInput, Skeleton } from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
|
||||
import { useCategory, useCreateCategory, useUpdateCategory } from '@/features/categories/hooks/useCategories'
|
||||
import classes from '@/components/UserDrawer.module.css'
|
||||
|
||||
interface Props {
|
||||
categoryId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function CategoryDrawer({ categoryId, opened, onClose }: Props) {
|
||||
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
|
||||
|
||||
const createCategory = useCreateCategory()
|
||||
const updateCategory = useUpdateCategory()
|
||||
|
||||
const isEditMode = categoryId !== null
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
is_active: true,
|
||||
},
|
||||
validate: {
|
||||
name: (v) => (v.trim().length < 2 ? 'Минимум 2 символа' : null),
|
||||
code: (v) => {
|
||||
if (v.trim().length < 2) return 'Минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(v)) return 'Только lowercase буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (category && opened) {
|
||||
form.setValues({
|
||||
name: category.name || '',
|
||||
code: category.code || '',
|
||||
description: category.description || '',
|
||||
is_active: category.is_active ?? true,
|
||||
})
|
||||
form.resetDirty()
|
||||
} else if (!isEditMode && opened) {
|
||||
form.reset()
|
||||
}
|
||||
}, [category, isEditMode, opened])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (isEditMode && categoryId) {
|
||||
await updateCategory.mutateAsync({ id: categoryId, ...values })
|
||||
} else {
|
||||
await createCategory.mutateAsync(values)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const isLoading = isEditMode && categoryLoading
|
||||
const isSubmitting = createCategory.isPending || updateCategory.isPending
|
||||
|
||||
return (
|
||||
<Drawer.Root opened={opened} onClose={onClose} position="right" size="min(480px, 100vw)">
|
||||
<Drawer.Overlay backgroundOpacity={0.25} />
|
||||
<Drawer.Content>
|
||||
<Drawer.Header>
|
||||
<Box style={{ minWidth: 0 }}>
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<Text fw={600}>{isEditMode ? 'Редактирование' : 'Новая категория'}</Text>
|
||||
{isEditMode && category && (
|
||||
<Badge variant="light" color={category.is_active ? 'green' : 'gray'}>
|
||||
ID {category.id}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Box>
|
||||
<Drawer.CloseButton />
|
||||
</Drawer.Header>
|
||||
|
||||
<Drawer.Body className={classes.body}>
|
||||
{isLoading ? (
|
||||
<Stack className={classes.section} gap="md">
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={40} />
|
||||
<Skeleton h={90} />
|
||||
</Stack>
|
||||
) : (
|
||||
<form style={{ display: 'contents' }} onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="lg" className={classes.section}>
|
||||
<TextInput
|
||||
label="Название"
|
||||
placeholder="Например: Отпуска и отгулы"
|
||||
withAsterisk
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Код"
|
||||
placeholder="vacation"
|
||||
description="Уникальный системный идентификатор (только lowercase)"
|
||||
withAsterisk
|
||||
disabled={isEditMode}
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Описание"
|
||||
placeholder="Для чего нужна эта категория..."
|
||||
minRows={3}
|
||||
autosize
|
||||
{...form.getInputProps('description')}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Активна"
|
||||
description="Скрытые категории не будут доступны при создании новых заявок"
|
||||
color="green"
|
||||
checked={form.values.is_active}
|
||||
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">
|
||||
{form.isDirty() ? 'Есть несохраненные изменения' : ''}
|
||||
</Text>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting} disabled={isEditMode && !form.isDirty()}>
|
||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</form>
|
||||
)}
|
||||
</Drawer.Body>
|
||||
</Drawer.Content>
|
||||
</Drawer.Root>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,152 +0,0 @@
|
|||
import { useEffect } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Textarea,
|
||||
Switch,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Loader,
|
||||
Center,
|
||||
Badge,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import {
|
||||
useCategory,
|
||||
useCreateCategory,
|
||||
useUpdateCategory
|
||||
} from '@/features/categories/hooks/useCategories'
|
||||
|
||||
interface CategoryEditModalProps {
|
||||
categoryId: number | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function CategoryEditModal({
|
||||
categoryId,
|
||||
opened,
|
||||
onClose
|
||||
}: CategoryEditModalProps) {
|
||||
const { data: category, isLoading: categoryLoading } = useCategory(categoryId)
|
||||
|
||||
const createCategory = useCreateCategory()
|
||||
const updateCategory = useUpdateCategory()
|
||||
|
||||
const isEditMode = categoryId !== null
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
is_active: true,
|
||||
},
|
||||
validate: {
|
||||
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
||||
code: (value: string | any[]) => {
|
||||
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Заполняем форму данными категории
|
||||
useEffect(() => {
|
||||
if (category) {
|
||||
form.setValues({
|
||||
name: category.name || '',
|
||||
code: category.code || '',
|
||||
description: category.description || '',
|
||||
is_active: category.is_active ?? true,
|
||||
})
|
||||
} else if (!isEditMode) {
|
||||
form.reset()
|
||||
}
|
||||
}, [category, isEditMode])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
if (isEditMode && categoryId) {
|
||||
// Режим редактирования
|
||||
await updateCategory.mutateAsync({
|
||||
id: categoryId,
|
||||
...values,
|
||||
})
|
||||
} else {
|
||||
// Режим создания
|
||||
await createCategory.mutateAsync(values)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const isLoading = categoryLoading
|
||||
const isSubmitting = createCategory.isPending || updateCategory.isPending
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>
|
||||
{isEditMode ? 'Редактирование категории' : 'Создание категории'}
|
||||
</Text>
|
||||
{category && <Badge variant="light">ID: {category.id}</Badge>}
|
||||
</Group>
|
||||
}
|
||||
size="md"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Center p={40}>
|
||||
<Loader />
|
||||
</Center>
|
||||
) : (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Название"
|
||||
placeholder="Отпуска и отгулы"
|
||||
required
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
|
||||
<TextInput
|
||||
label="Код"
|
||||
placeholder="vacation"
|
||||
required
|
||||
description="Уникальный идентификатор категории (lowercase, цифры, подчеркивания)"
|
||||
disabled={isEditMode}
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Описание"
|
||||
placeholder="Описание категории..."
|
||||
minRows={3}
|
||||
{...form.getInputProps('description')}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Активна"
|
||||
description="Неактивные категории не будут доступны для выбора при создании тем"
|
||||
checked={form.values.is_active}
|
||||
onChange={(e) => form.setFieldValue('is_active', e.currentTarget.checked)}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in New Issue