update hierarchy page
Deploy Frontend / build-and-deploy (push) Failing after 23s Details

This commit is contained in:
romanskijdev 2026-06-25 14:39:20 +03:00
parent 573ab61563
commit b4fdeb0efb
3 changed files with 698 additions and 179 deletions

View File

@ -25,13 +25,12 @@ import {
IconPlus, IconPlus,
IconInfoCircle, IconInfoCircle,
IconCheck, IconCheck,
IconCopy,
} from '@tabler/icons-react' } from '@tabler/icons-react'
import { modals } from '@mantine/modals' import { modals } from '@mantine/modals'
import { notifications } from '@mantine/notifications' import { notifications } from '@mantine/notifications'
import { import {
useHierarchies, useHierarchies,
useDeleteHierarchy useDeleteHierarchy,
} from '@/features/hierarchies/hooks/useHierarchies' } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers' import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments' import { useDepartments } from '@/features/departments/hooks/useDepartments'
@ -44,6 +43,7 @@ import {
type ChainGroup, type ChainGroup,
} from '@/features/hierarchies/utils' } from '@/features/hierarchies/utils'
import ChainVisualization from './components/ChainVisualization' import ChainVisualization from './components/ChainVisualization'
import ChainDuplicateModal from './components/ChainDuplicateModal'
import HierarchyEditModal from './components/HierarchyEditModal' import HierarchyEditModal from './components/HierarchyEditModal'
import type { UserHierarchy } from '@/types/api' import type { UserHierarchy } from '@/types/api'
@ -65,26 +65,18 @@ export default function HierarchiesPage() {
const [selectedIds, setSelectedIds] = useState<number[]>([]) const [selectedIds, setSelectedIds] = useState<number[]>([])
const [isDeleting, setIsDeleting] = useState(false) const [isDeleting, setIsDeleting] = useState(false)
// Модалки
const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null) const [editHierarchy, setEditHierarchy] = useState<UserHierarchy | null>(null)
const [createModalOpened, setCreateModalOpened] = useState(false) const [createModalOpened, setCreateModalOpened] = useState(false)
const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null) const [presetGroup, setPresetGroup] = useState<ChainGroup | null>(null)
const [duplicateGroup, setDuplicateGroup] = useState<ChainGroup | null>(null) // 🆕
const [duplicateModalOpened, setDuplicateModalOpened] = useState(false) // 🆕
// Добавляем состояние для дублирования
const [duplicateGroup, setDuplicateGroup] = useState<ChainGroup | null>(null)
// Обработчик дублирования
const handleDuplicateChain = (group: ChainGroup) => {
setDuplicateGroup(group)
setCreateModalOpened(true)
}
// Загружаем темы только для выбранной категории (если она выбрана)
const { data: categoryTopics } = useTopics({ const { data: categoryTopics } = useTopics({
limit: 1000, limit: 1000,
...(categoryFilter && { category_id: Number(categoryFilter) }), ...(categoryFilter && { category_id: Number(categoryFilter) }),
}) })
// Основной запрос с пагинацией и фильтрами
const { data, isLoading, isFetching } = useHierarchies({ const { data, isLoading, isFetching } = useHierarchies({
offset: (page - 1) * LIMIT, offset: (page - 1) * LIMIT,
limit: LIMIT, limit: LIMIT,
@ -103,13 +95,11 @@ export default function HierarchiesPage() {
const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1 const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1
// Группируем в цепочки
const chains = useMemo(() => { const chains = useMemo(() => {
if (!data?.data) return [] if (!data?.data) return []
return groupHierarchiesIntoChains(data.data) return groupHierarchiesIntoChains(data.data)
}, [data]) }, [data])
// Обогатим цепочки названиями объектов
const enrichedChains = useMemo(() => { const enrichedChains = useMemo(() => {
return chains.map((chain) => { return chains.map((chain) => {
let scopeObjectName = 'Все темы' let scopeObjectName = 'Все темы'
@ -124,29 +114,30 @@ export default function HierarchiesPage() {
}) })
}, [chains, categories, topics]) }, [chains, categories, topics])
// Опции для фильтров const userOptions =
const userOptions = users?.data?.map((u) => ({ users?.data?.map((u) => ({
value: String(u.id), value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`, label: u.full_name || `Пользователь #${u.id}`,
})) || [] })) || []
const departmentOptions = departments?.data?.map((d) => ({ const departmentOptions =
value: String(d.id), departments?.data?.map((d) => ({
label: d.name || '', value: String(d.id),
})) || [] label: d.name || '',
})) || []
const categoryOptions = categories?.data?.map((c) => ({ const categoryOptions =
value: String(c.id), categories?.data?.map((c) => ({
label: c.name || '', value: String(c.id),
})) || [] label: c.name || '',
})) || []
// Если выбрана категория, показываем только её темы, иначе все темы const topicOptions =
const topicOptions = (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({ (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({
value: String(t.id), value: String(t.id),
label: t.name || '', label: t.name || '',
})) || [] })) || []
// Обработка выбора записей
const handleSelectAll = () => { const handleSelectAll = () => {
if (selectedIds.length === data?.data?.length) { if (selectedIds.length === data?.data?.length) {
setSelectedIds([]) setSelectedIds([])
@ -161,21 +152,20 @@ export default function HierarchiesPage() {
) )
} }
// Сброс выбора при изменении страницы или фильтров const handleFilterChange =
const handleFilterChange = (setter: (value: string | null) => void) => (value: string | null) => { (setter: (value: string | null) => void) => (value: string | null) => {
setter(value) setter(value)
setPage(1) setPage(1)
setSelectedIds([]) setSelectedIds([])
} }
// Массовое удаление
const handleBulkDelete = () => { const handleBulkDelete = () => {
modals.openConfirmModal({ modals.openConfirmModal({
title: 'Подтвердите массовое удаление', title: 'Подтвердите массовое удаление',
children: ( children: (
<Text size="sm"> <Text size="sm">
Вы уверены, что хотите удалить <strong>{selectedIds.length}</strong> записей? Вы уверены, что хотите удалить <strong>{selectedIds.length}</strong>{' '}
Это действие необратимо и может повлиять на процессы согласования. записей? Это действие необратимо.
</Text> </Text>
), ),
labels: { confirm: 'Удалить все', cancel: 'Отмена' }, labels: { confirm: 'Удалить все', cancel: 'Отмена' },
@ -184,14 +174,12 @@ export default function HierarchiesPage() {
setIsDeleting(true) setIsDeleting(true)
try { try {
await Promise.all(selectedIds.map((id) => deleteHierarchy.mutateAsync(id))) await Promise.all(selectedIds.map((id) => deleteHierarchy.mutateAsync(id)))
notifications.show({ notifications.show({
title: 'Успешно', title: 'Успешно',
message: `Удалено записей: ${selectedIds.length}`, message: `Удалено записей: ${selectedIds.length}`,
color: 'green', color: 'green',
icon: <IconCheck size={16} />, icon: <IconCheck size={16} />,
}) })
setSelectedIds([]) setSelectedIds([])
} catch (error) { } catch (error) {
notifications.show({ notifications.show({
@ -211,7 +199,7 @@ export default function HierarchiesPage() {
title: 'Подтвердите удаление', title: 'Подтвердите удаление',
children: ( children: (
<Text size="sm"> <Text size="sm">
Вы уверены, что хотите удалить эту связь? Это может повлиять на процесс согласования. Вы уверены, что хотите удалить эту связь?
</Text> </Text>
), ),
labels: { confirm: 'Удалить', cancel: 'Отмена' }, labels: { confirm: 'Удалить', cancel: 'Отмена' },
@ -232,15 +220,26 @@ export default function HierarchiesPage() {
setCreateModalOpened(true) setCreateModalOpened(true)
} }
const handleDuplicateChain = (group: ChainGroup) => {
setDuplicateGroup(group)
setDuplicateModalOpened(true)
}
const handleCloseModal = () => { const handleCloseModal = () => {
setEditHierarchy(null) setEditHierarchy(null)
setCreateModalOpened(false) setCreateModalOpened(false)
setPresetGroup(null) setPresetGroup(null)
setDuplicateGroup(null) // 🆕
} }
const isAllSelected = (data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0) const handleCloseDuplicateModal = () => {
const isIndeterminate = selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0) setDuplicateGroup(null)
setDuplicateModalOpened(false)
}
const isAllSelected =
(data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0)
const isIndeterminate =
selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0)
return ( return (
<Stack gap="md"> <Stack gap="md">
@ -259,7 +258,7 @@ export default function HierarchiesPage() {
}} }}
data={[ data={[
{ value: 'chains', label: 'Цепочки' }, { value: 'chains', label: 'Цепочки' },
{ value: 'table', label: 'Таблица'}, { value: 'table', label: 'Таблица' },
]} ]}
/> />
<Button <Button
@ -274,12 +273,10 @@ export default function HierarchiesPage() {
</Group> </Group>
</Group> </Group>
{/* Подсказка */}
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light"> <Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm"> <Text size="sm">
Иерархия определяет порядок согласования заявок. Каждая цепочка показывает, Иерархия определяет порядок согласования заявок. Каждая цепочка показывает,
через каких согласующих проходит заявка от конкретного сотрудника. через каких согласующих проходит заявка от конкретного сотрудника.
Шаги выполняются последовательно в порядке возрастания приоритета.
</Text> </Text>
</Alert> </Alert>
@ -297,7 +294,6 @@ export default function HierarchiesPage() {
searchable searchable
style={{ flex: 1, minWidth: 250 }} style={{ flex: 1, minWidth: 250 }}
/> />
<Select <Select
label="Отдел" label="Отдел"
placeholder="Все отделы" placeholder="Все отделы"
@ -308,7 +304,6 @@ export default function HierarchiesPage() {
style={{ flex: 1, minWidth: 200 }} style={{ flex: 1, minWidth: 200 }}
/> />
</Group> </Group>
<Group gap="md" align="flex-end"> <Group gap="md" align="flex-end">
<Select <Select
label="Категория" label="Категория"
@ -323,7 +318,6 @@ export default function HierarchiesPage() {
searchable searchable
style={{ flex: 1, minWidth: 200 }} style={{ flex: 1, minWidth: 200 }}
/> />
<Select <Select
label="Тема" label="Тема"
placeholder="Все темы" placeholder="Все темы"
@ -345,7 +339,6 @@ export default function HierarchiesPage() {
<Loader /> <Loader />
</Center> </Center>
) : viewMode === 'chains' ? ( ) : viewMode === 'chains' ? (
// Режим цепочек
<ScrollArea p="md"> <ScrollArea p="md">
<Stack gap="md"> <Stack gap="md">
{enrichedChains.length === 0 ? ( {enrichedChains.length === 0 ? (
@ -367,11 +360,13 @@ export default function HierarchiesPage() {
</Stack> </Stack>
</ScrollArea> </ScrollArea>
) : ( ) : (
// Режим таблицы
<> <>
{/* Панель массовых действий */}
{selectedIds.length > 0 && ( {selectedIds.length > 0 && (
<Box p="sm" bg="red.0" style={{ borderBottom: '1px solid var(--mantine-color-red-3)' }}> <Box
p="sm"
bg="red.0"
style={{ borderBottom: '1px solid var(--mantine-color-red-3)' }}
>
<Group justify="space-between"> <Group justify="space-between">
<Text size="sm" fw={500}> <Text size="sm" fw={500}>
Выбрано записей: <strong>{selectedIds.length}</strong> Выбрано записей: <strong>{selectedIds.length}</strong>
@ -406,7 +401,6 @@ export default function HierarchiesPage() {
checked={isAllSelected} checked={isAllSelected}
indeterminate={isIndeterminate} indeterminate={isIndeterminate}
onChange={handleSelectAll} onChange={handleSelectAll}
aria-label="Выбрать все"
/> />
</Table.Th> </Table.Th>
<Table.Th style={{ width: 60 }}>ID</Table.Th> <Table.Th style={{ width: 60 }}>ID</Table.Th>
@ -430,14 +424,21 @@ export default function HierarchiesPage() {
</Table.Tr> </Table.Tr>
) : ( ) : (
data?.data?.map((h) => { data?.data?.map((h) => {
const scopeType = h.topic_id ? 'topic' : const scopeType = h.topic_id
h.topic_category_id ? 'category' : 'global' ? 'topic'
: h.topic_category_id
? 'category'
: 'global'
let scopeObjectName = 'Все темы' let scopeObjectName = 'Все темы'
if (scopeType === 'category' && h.topic_category_id) { if (scopeType === 'category' && h.topic_category_id) {
const cat = categories?.data?.find((c) => c.id === h.topic_category_id) const cat = categories?.data?.find(
(c) => c.id === h.topic_category_id
)
scopeObjectName = cat?.name || `#${h.topic_category_id}` scopeObjectName = cat?.name || `#${h.topic_category_id}`
} else if (scopeType === 'topic' && h.topic_id) { } else if (scopeType === 'topic' && h.topic_id) {
const topic = topics?.data?.find((t) => t.id === h.topic_id) const topic = topics?.data?.find(
(t) => t.id === h.topic_id
)
scopeObjectName = topic?.name || `#${h.topic_id}` scopeObjectName = topic?.name || `#${h.topic_id}`
} }
@ -447,14 +448,13 @@ export default function HierarchiesPage() {
style={{ style={{
backgroundColor: selectedIds.includes(h.id!) backgroundColor: selectedIds.includes(h.id!)
? 'var(--mantine-color-blue-0)' ? 'var(--mantine-color-blue-0)'
: undefined : undefined,
}} }}
> >
<Table.Td> <Table.Td>
<Checkbox <Checkbox
checked={selectedIds.includes(h.id!)} checked={selectedIds.includes(h.id!)}
onChange={() => handleSelectOne(h.id!)} onChange={() => handleSelectOne(h.id!)}
aria-label={`Выбрать запись ${h.id}`}
/> />
</Table.Td> </Table.Td>
<Table.Td>{h.id}</Table.Td> <Table.Td>{h.id}</Table.Td>
@ -469,19 +469,31 @@ export default function HierarchiesPage() {
</Text> </Text>
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
<Text size="sm">{h.department?.name || '—'}</Text> <Text size="sm">
{h.department?.name || '—'}
</Text>
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
<Badge <Badge
size="xs" size="xs"
color={SCOPE_COLORS[scopeType as keyof typeof SCOPE_COLORS]} color={
SCOPE_COLORS[
scopeType as keyof typeof SCOPE_COLORS
]
}
variant="light" variant="light"
> >
{SCOPE_LABELS[scopeType as keyof typeof SCOPE_LABELS]} {
SCOPE_LABELS[
scopeType as keyof typeof SCOPE_LABELS
]
}
</Badge> </Badge>
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
<Text size="sm" lineClamp={1}>{scopeObjectName}</Text> <Text size="sm" lineClamp={1}>
{scopeObjectName}
</Text>
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
<Badge variant="light" color="gray"> <Badge variant="light" color="gray">
@ -519,7 +531,6 @@ export default function HierarchiesPage() {
</> </>
)} )}
{/* Пагинация */}
{totalPages > 1 && ( {totalPages > 1 && (
<Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}> <Box p="md" style={{ borderTop: '1px solid var(--mantine-color-gray-3)' }}>
<Group justify="space-between"> <Group justify="space-between">
@ -546,11 +557,10 @@ export default function HierarchiesPage() {
</Box> </Box>
)} )}
{/* Модальные окна */} {/* Модалки */}
<HierarchyEditModal <HierarchyEditModal
hierarchy={null} hierarchy={editHierarchy}
presetGroup={duplicateGroup || presetGroup} opened={editHierarchy !== null}
opened={createModalOpened}
onClose={handleCloseModal} onClose={handleCloseModal}
/> />
@ -560,6 +570,12 @@ export default function HierarchiesPage() {
opened={createModalOpened} opened={createModalOpened}
onClose={handleCloseModal} onClose={handleCloseModal}
/> />
<ChainDuplicateModal
group={duplicateGroup}
opened={duplicateModalOpened}
onClose={handleCloseDuplicateModal}
/>
</Stack> </Stack>
) )
} }

View File

@ -0,0 +1,495 @@
import { useEffect } from 'react'
import {
Modal,
Stack,
Select,
NumberInput,
Group,
Button,
Text,
Paper,
Divider,
ActionIcon,
Badge,
Avatar,
Box,
Radio,
Alert,
} from '@mantine/core'
import { useForm } from '@mantine/form'
import {
IconInfoCircle,
IconPlus,
IconTrash,
IconCopy,
IconChevronRight,
} from '@tabler/icons-react'
import { notifications } from '@mantine/notifications'
import { useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies'
import { useUsers } from '@/features/users/hooks/useUsers'
import { useDepartments } from '@/features/departments/hooks/useDepartments'
import { useCategories } from '@/features/categories/hooks/useCategories'
import { useTopics } from '@/features/topics/hooks/useTopics'
import type { ChainGroup } from '@/features/hierarchies/utils'
interface ChainDuplicateModalProps {
group: ChainGroup | null
opened: boolean
onClose: () => void
}
type ScopeType = 'global' | 'category' | 'topic'
interface StepForm {
approver_id: number | null
priority: number
}
export default function ChainDuplicateModal({
group,
opened,
onClose,
}: ChainDuplicateModalProps) {
const createHierarchy = useCreateHierarchy()
const { data: users } = useUsers({ limit: 1000 })
const { data: departments } = useDepartments()
const { data: categories } = useCategories({ limit: 1000 })
const form = useForm({
initialValues: {
subordinate_id: null as number | null,
department_id: null as number | null,
scope_type: 'global' as ScopeType,
topic_category_id: null as number | null,
topic_id: null as number | null,
steps: [] as StepForm[],
},
validate: {
subordinate_id: (v) => (v === null ? 'Выберите инициатора' : null),
department_id: (v) => (v === null ? 'Выберите отдел' : null),
topic_category_id: (v, values) => {
if (
(values.scope_type === 'category' || values.scope_type === 'topic') &&
v === null
) {
return 'Выберите категорию'
}
return null
},
topic_id: (v: null, values: { scope_type: string }) => {
if (values.scope_type === 'topic' && v === null) {
return 'Выберите тему'
}
return null
},
steps: {
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
},
},
})
const { data: categoryTopics } = useTopics({
limit: 1000,
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
})
// Заполняем форму данными из цепочки
useEffect(() => {
if (group && opened) {
form.setValues({
subordinate_id: group.subordinateId,
department_id: group.departmentId,
scope_type: group.scopeType,
topic_category_id:
group.scopeType === 'category' || group.scopeType === 'topic'
? group.scopeObjectId
: null,
topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null,
steps: group.steps.map((s, idx) => ({
approver_id: s.approver_id || null,
priority: idx,
})),
})
}
}, [group, opened])
const handleScopeTypeChange = (value: ScopeType) => {
form.setFieldValue('scope_type', value)
if (value === 'global') {
form.setFieldValue('topic_category_id', null)
form.setFieldValue('topic_id', null)
} else if (value === 'category') {
form.setFieldValue('topic_id', null)
}
}
const addStep = () => {
form.insertListItem('steps', {
approver_id: null,
priority: form.values.steps.length,
})
}
const removeStep = (index: number) => {
form.removeListItem('steps', index)
// Пересчитываем priority
form.values.steps.forEach((_, idx) => {
form.setFieldValue(`steps.${idx}.priority`, idx)
})
}
const userOptions =
users?.data?.map((u) => ({
value: String(u.id),
label: u.full_name || `Пользователь #${u.id}`,
})) || []
const departmentOptions =
departments?.data?.map((d) => ({
value: String(d.id),
label: d.name || '',
})) || []
const categoryOptions =
categories?.data?.map((c) => ({
value: String(c.id),
label: c.name || '',
})) || []
const topicOptions =
categoryTopics?.data?.map((t) => ({
value: String(t.id),
label: t.name || '',
})) || []
const handleSubmit = async (values: typeof form.values) => {
if (values.steps.length === 0) {
notifications.show({
title: 'Ошибка',
message: 'Добавьте хотя бы один шаг согласования',
color: 'red',
})
return
}
try {
// Создаём все записи последовательно
for (const step of values.steps) {
await createHierarchy.mutateAsync({
subordinate_id: values.subordinate_id!,
approver_id: step.approver_id!,
department_id: values.department_id!,
priority: step.priority,
topic_category_id:
values.scope_type === 'global'
? null
: values.scope_type === 'category'
? values.topic_category_id
: null,
topic_id: values.scope_type === 'topic' ? values.topic_id : null,
})
}
notifications.show({
title: 'Успешно',
message: `Цепочка дублирована (${values.steps.length} шагов)`,
color: 'green',
})
onClose()
} catch (error) {
notifications.show({
title: 'Ошибка',
message: 'Не удалось дублировать цепочку',
color: 'red',
})
}
}
const isSubmitting = createHierarchy.isPending
return (
<Modal
opened={opened}
onClose={onClose}
title={
<Group gap="xs">
<IconCopy size={20} />
<Text fw={600}>Дублирование цепочки</Text>
</Group>
}
size="lg"
centered
>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack gap="md">
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
<Text size="sm">
Создайте новую цепочку на основе существующей. Вы можете изменить
инициатора, отдел, область действия и согласующих.
</Text>
</Alert>
{/* Общие параметры */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm" c="dark">
Общие параметры
</Text>
<Stack gap="sm">
<Select
label="Инициатор"
placeholder="Выберите пользователя"
data={userOptions}
value={
form.values.subordinate_id
? String(form.values.subordinate_id)
: null
}
onChange={(v) =>
form.setFieldValue(
'subordinate_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.subordinate_id}
/>
<Select
label="Отдел"
placeholder="Выберите отдел"
data={departmentOptions}
value={
form.values.department_id
? String(form.values.department_id)
: null
}
onChange={(v) =>
form.setFieldValue(
'department_id',
v ? Number(v) : null
)
}
searchable
required
error={form.errors.department_id}
/>
</Stack>
</Paper>
{/* Область действия */}
<Paper withBorder p="md">
<Text size="sm" fw={600} mb="sm" c="dark">
Область действия
</Text>
<Stack gap="sm">
<Radio.Group
value={form.values.scope_type}
onChange={(v) => handleScopeTypeChange(v as ScopeType)}
>
<Stack gap="xs">
<Radio
value="global"
label="Глобальное правило"
description="Для всех тем согласований"
/>
<Radio
value="category"
label="Для категории тем"
description="Только для тем выбранной категории"
/>
<Radio
value="topic"
label="Для конкретной темы"
description="Только для выбранной темы"
/>
</Stack>
</Radio.Group>
{(form.values.scope_type === 'category' ||
form.values.scope_type === 'topic') && (
<Select
label="Категория"
placeholder="Выберите категорию"
data={categoryOptions}
value={
form.values.topic_category_id
? String(form.values.topic_category_id)
: null
}
onChange={(v) => {
form.setFieldValue(
'topic_category_id',
v ? Number(v) : null
)
form.setFieldValue('topic_id', null)
}}
searchable
required
error={form.errors.topic_category_id}
/>
)}
{form.values.scope_type === 'topic' && (
<Select
label="Тема"
placeholder="Выберите тему"
data={topicOptions}
value={
form.values.topic_id
? String(form.values.topic_id)
: null
}
onChange={(v) =>
form.setFieldValue('topic_id', v ? Number(v) : null)
}
searchable
required
disabled={!form.values.topic_category_id}
error={form.errors.topic_id}
/>
)}
</Stack>
</Paper>
{/* Шаги согласования */}
<Paper withBorder p="md">
<Group justify="space-between" mb="sm">
<Text size="sm" fw={600} c="dark">
Шаги согласования
</Text>
<Button
variant="subtle"
size="xs"
leftSection={<IconPlus size={14} />}
onClick={addStep}
>
Добавить шаг
</Button>
</Group>
<Stack gap="sm">
{form.values.steps.length === 0 ? (
<Box py="md">
<Text size="sm" c="dimmed" ta="center">
Нет шагов согласования. Добавьте хотя бы один.
</Text>
</Box>
) : (
form.values.steps.map((step, index) => (
<Paper
key={index}
withBorder
p="sm"
style={{
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-gray-0)',
}}
>
<Group gap="sm" align="flex-start">
<Avatar
size="sm"
radius="xl"
color="blue"
variant="filled"
mt={4}
>
{index + 1}
</Avatar>
<Stack gap="xs" style={{ flex: 1 }}>
<Group gap="xs">
<Badge
size="xs"
variant="light"
color="gray"
tt="none"
>
Шаг {index + 1}
</Badge>
<Badge
size="xs"
variant="light"
color="gray"
tt="none"
>
Priority: {step.priority}
</Badge>
</Group>
<Select
placeholder="Выберите согласующего"
data={userOptions}
value={step.approver_id ? String(step.approver_id) : null}
onChange={(v) =>
form.setFieldValue(`steps.${index}.approver_id`, v ? Number(v) : null)
}
searchable
error={
Array.isArray(form.errors.steps) && form.errors.steps[index]
? (form.errors.steps[index] as any)?.approver_id
: undefined
}
/>
</Stack>
<ActionIcon
variant="subtle"
color="red"
size="md"
mt={4}
onClick={() => removeStep(index)}
>
<IconTrash size={16} />
</ActionIcon>
</Group>
</Paper>
))
)}
</Stack>
</Paper>
{/* Предпросмотр */}
{form.values.steps.length > 0 && (
<Paper withBorder p="md" bg="gray.0">
<Text size="xs" fw={600} c="dimmed" mb="xs" tt="uppercase">
Предпросмотр цепочки
</Text>
<Group gap="xs" wrap="nowrap" style={{ overflowX: 'auto' }}>
<Badge variant="light" color="gray" tt="none">
{users?.data?.find(
(u) => u.id === form.values.subordinate_id
)?.full_name || 'Инициатор'}
</Badge>
{form.values.steps.map((step, index) => (
<Group key={index} gap={4} wrap="nowrap">
<IconChevronRight
size={14}
color="var(--mantine-color-gray-5)"
/>
<Badge variant="light" color="blue" tt="none">
{users?.data?.find(
(u) => u.id === step.approver_id
)?.full_name || `Шаг ${index + 1}`}
</Badge>
</Group>
))}
</Group>
</Paper>
)}
<Divider />
<Group justify="flex-end" gap="sm">
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" loading={isSubmitting}>
Дублировать цепочку
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}

View File

@ -7,12 +7,11 @@ import {
ActionIcon, ActionIcon,
Avatar, Avatar,
Box, Box,
ThemeIcon,
Tooltip,
Divider, Divider,
Tooltip,
} from '@mantine/core' } from '@mantine/core'
import { import {
IconArrowRight, IconChevronRight,
IconPencil, IconPencil,
IconTrash, IconTrash,
IconUser, IconUser,
@ -20,8 +19,7 @@ import {
IconCategory, IconCategory,
IconFileText, IconFileText,
IconCopy, IconCopy,
IconShield, IconPlus,
IconCheck,
} from '@tabler/icons-react' } from '@tabler/icons-react'
import type { ChainGroup } from '@/features/hierarchies/utils' import type { ChainGroup } from '@/features/hierarchies/utils'
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils' import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
@ -36,10 +34,14 @@ interface ChainVisualizationProps {
const ScopeIcon = ({ type }: { type: string }) => { const ScopeIcon = ({ type }: { type: string }) => {
switch (type) { switch (type) {
case 'global': return <IconWorld size={14} /> case 'global':
case 'category': return <IconCategory size={14} /> return <IconWorld size={13} />
case 'topic': return <IconFileText size={14} /> case 'category':
default: return <IconWorld size={14} /> return <IconCategory size={13} />
case 'topic':
return <IconFileText size={13} />
default:
return <IconWorld size={13} />
} }
} }
@ -53,60 +55,56 @@ export default function ChainVisualization({
return ( return (
<Paper <Paper
withBorder withBorder
p="md" p="lg"
mb="md"
style={{ style={{
background: 'linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%)', backgroundColor: 'var(--mantine-color-white)',
transition: 'all 0.2s ease', borderColor: 'var(--mantine-color-gray-3)',
}} }}
className="chain-card"
> >
{/* Заголовок группы */} {/* Заголовок группы */}
<Group justify="space-between" mb="md"> <Group justify="space-between" mb="lg">
<Group gap="md"> <Group gap="md">
<Avatar <Avatar size="md" radius="xl" color="gray" variant="filled">
size="lg" {group.subordinateName.charAt(0).toUpperCase()}
radius="xl"
color="blue"
style={{
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
border: '2px solid white'
}}
>
{group.subordinateName.charAt(0)}
</Avatar> </Avatar>
<Stack gap={2}>
<Text fw={700} size="sm">{group.subordinateName}</Text> <Stack gap={0}>
<Text size="xs" c="dimmed">{group.departmentName}</Text> <Text fw={600} size="sm" c="dark">
{group.subordinateName}
</Text>
<Text size="xs" c="dimmed">
{group.departmentName}
</Text>
</Stack> </Stack>
<Divider orientation="vertical" /> <Divider orientation="vertical" />
<Badge <Badge
variant="filled" variant="outline"
color={SCOPE_COLORS[group.scopeType]} color={SCOPE_COLORS[group.scopeType]}
leftSection={<ScopeIcon type={group.scopeType} />} leftSection={<ScopeIcon type={group.scopeType} />}
size="lg" size="sm"
tt="none"
> >
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName} {SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
</Badge> </Badge>
</Group> </Group>
<Group gap="xs"> <Group gap="xs">
<Tooltip label="Добавить шаг"> <Tooltip label="Добавить шаг" withArrow>
<ActionIcon <ActionIcon
variant="filled" variant="subtle"
color="green" color="gray"
size="md" size="md"
onClick={() => onAddStep(group)} onClick={() => onAddStep(group)}
> >
<IconUser size={18} /> <IconPlus size={18} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
<Tooltip label="Дублировать цепочку"> <Tooltip label="Дублировать цепочку" withArrow>
<ActionIcon <ActionIcon
variant="filled" variant="subtle"
color="violet" color="gray"
size="md" size="md"
onClick={() => onDuplicateChain(group)} onClick={() => onDuplicateChain(group)}
> >
@ -116,39 +114,35 @@ export default function ChainVisualization({
</Group> </Group>
</Group> </Group>
<Divider mb="md" /> <Divider mb="lg" />
<Box style={{ overflowX: 'auto', padding: '8px 0' }}> {/* Цепочка согласования */}
<Group gap="sm" wrap="nowrap" align="center"> <Box style={{ overflowX: 'auto' }}>
<Group gap={0} wrap="nowrap" align="stretch">
{/* Карточка инициатора */} {/* Карточка инициатора */}
<Paper <Paper
withBorder withBorder
p="md" p="md"
style={{ style={{
minWidth: 160, minWidth: 180,
background: 'linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)', borderColor: 'var(--mantine-color-gray-3)',
borderColor: '#2196f3', backgroundColor: 'var(--mantine-color-gray-0)',
boxShadow: '0 2px 8px rgba(33, 150, 243, 0.2)',
}} }}
> >
<Stack gap={6} align="center"> <Stack gap="xs" align="center">
<Badge <Text
variant="filled" size="xs"
color="blue" fw={600}
size="sm" c="dimmed"
leftSection={<IconUser size={12} />} tt="uppercase"
style={{ letterSpacing: '0.5px' }}
> >
ИНИЦИАТОР Инициатор
</Badge> </Text>
<Avatar <Avatar size="md" radius="xl" color="gray" variant="filled">
size="lg" {group.subordinateName.charAt(0).toUpperCase()}
radius="xl"
color="blue"
style={{ border: '3px solid white' }}
>
{group.subordinateName.charAt(0)}
</Avatar> </Avatar>
<Text size="sm" fw={600} ta="center" lineClamp={2}> <Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{group.subordinateName} {group.subordinateName}
</Text> </Text>
</Stack> </Stack>
@ -156,15 +150,21 @@ export default function ChainVisualization({
{/* Шаги согласования */} {/* Шаги согласования */}
{group.steps.map((step, index) => ( {group.steps.map((step, index) => (
<Group key={step.id} gap="sm" wrap="nowrap" align="center"> <Group key={step.id} gap={0} wrap="nowrap" align="stretch">
{/* Стрелка с номером */} {/* Разделитель со стрелкой */}
<Stack gap={2} align="center"> <Stack
<IconArrowRight size={24} color="#495057" /> gap={2}
align="center"
justify="center"
px="xs"
style={{ minWidth: 60 }}
>
<IconChevronRight size={20} color="var(--mantine-color-gray-5)" />
<Badge <Badge
size="xs"
variant="light" variant="light"
color="gray" color="gray"
size="xs" tt="none"
circle
> >
{index + 1} {index + 1}
</Badge> </Badge>
@ -175,48 +175,67 @@ export default function ChainVisualization({
withBorder withBorder
p="md" p="md"
style={{ style={{
minWidth: 160, minWidth: 180,
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-white)',
cursor: 'pointer', cursor: 'pointer',
transition: 'all 0.2s ease', transition: 'border-color 0.15s ease',
borderColor: '#4caf50', position: 'relative',
background: 'linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%)',
boxShadow: '0 2px 8px rgba(76, 175, 80, 0.2)',
}} }}
onClick={() => onEditStep(step.id!)} onClick={() => onEditStep(step.id!)}
className="approver-card" onMouseEnter={(e) => {
e.currentTarget.style.borderColor =
'var(--mantine-color-blue-5)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor =
'var(--mantine-color-gray-3)'
}}
> >
<Stack gap={6} align="center"> <Stack gap="xs" align="center">
<Group gap={4}> <Group gap={6}>
<Badge <Text
variant="filled" size="xs"
color="green" fw={600}
size="sm" c="dimmed"
leftSection={<IconShield size={12} />} tt="uppercase"
style={{ letterSpacing: '0.5px' }}
>
Шаг {index + 1}
</Text>
<Badge
size="xs"
variant="light"
color="gray"
tt="none"
> >
ШАГ {index + 1}
</Badge>
<Badge size="xs" variant="light" color="gray">
#{step.priority} #{step.priority}
</Badge> </Badge>
</Group> </Group>
<Avatar <Avatar
size="lg" size="md"
radius="xl" radius="xl"
color="green" color="blue"
style={{ border: '3px solid white' }} variant="filled"
> >
{step.approver?.full_name?.charAt(0) || '?'} {step.approver?.full_name?.charAt(0).toUpperCase() || '?'}
</Avatar> </Avatar>
<Text size="sm" fw={600} ta="center" lineClamp={2}>
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{step.approver?.full_name || '—'} {step.approver?.full_name || '—'}
</Text> </Text>
<Divider
style={{ width: '100%', margin: '4px 0' }}
/>
{/* Кнопки действий */} {/* Кнопки действий */}
<Group gap={4} mt={4}> <Group gap="xs" justify="center">
<Tooltip label="Редактировать"> <Tooltip label="Редактировать" withArrow>
<ActionIcon <ActionIcon
variant="filled" variant="subtle"
color="blue" color="gray"
size="sm" size="sm"
onClick={(e) => { onClick={(e) => {
e.stopPropagation() e.stopPropagation()
@ -226,9 +245,9 @@ export default function ChainVisualization({
<IconPencil size={14} /> <IconPencil size={14} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
<Tooltip label="Удалить"> <Tooltip label="Удалить" withArrow>
<ActionIcon <ActionIcon
variant="filled" variant="subtle"
color="red" color="red"
size="sm" size="sm"
onClick={(e) => { onClick={(e) => {
@ -246,17 +265,6 @@ export default function ChainVisualization({
))} ))}
</Group> </Group>
</Box> </Box>
<style>{`
.chain-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.approver-card:hover {
transform: translateY(-3px);
box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}
`}</style>
</Paper> </Paper>
) )
} }