admin_ruspet/src/pages/hierarchies/components/ChainVisualization.tsx

324 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// ChainVisualization.tsx
import {useMemo, useState} from 'react'
import {
Paper,
Group,
Stack,
Text,
Badge,
ActionIcon,
Avatar,
Box,
Divider,
Tooltip,
Select,
} from '@mantine/core'
import {
IconChevronRight,
IconPencil,
IconTrash,
IconWorld,
IconCategory,
IconFileText,
IconCopy,
IconPlus,
IconServer,
} from '@tabler/icons-react'
import type { ChainGroup } from '@/features/hierarchies/utils'
import { SCOPE_COLORS, SCOPE_LABELS } from '@/features/hierarchies/utils'
import {
useCategorySystemOptions,
ALL_SYSTEMS_VALUE,
useAllSystemOptions
} from '@/features/hierarchies/hooks/useSystemOptions'
import {useTopics} from "@/features/topics/hooks/useTopics.ts";
interface ChainVisualizationProps {
group: ChainGroup
onEditStep: (hierarchyId: number) => void
onDeleteStep: (hierarchyId: number) => void
onAddStep: (group: ChainGroup) => void
onDuplicateChain: (group: ChainGroup) => void
onBulkUpdateSystem?: (group: ChainGroup, targetSystem: string | null) => void
}
const ScopeIcon = ({ type }: { type: string }) => {
switch (type) {
case 'global':
return <IconWorld size={13} />
case 'category':
return <IconCategory size={13} />
case 'topic':
return <IconFileText size={13} />
default:
return <IconWorld size={13} />
}
}
// Внутри компонента ChainVisualization:
export default function ChainVisualization({
group,
onEditStep,
onDeleteStep,
onAddStep,
onDuplicateChain,
onBulkUpdateSystem,
}: ChainVisualizationProps) {
// Получаем все темы, чтобы уметь мапить topicId -> categoryId, если scopeType === 'topic'
const { data: allTopics } = useTopics({ limit: 1000 })
const resolvedCategoryId = useMemo(() => {
if (group.scopeType === 'category') {
return group.scopeObjectId
}
if (group.scopeType === 'topic' && group.scopeObjectId && allTopics?.data) {
const foundTopic = allTopics.data.find(t => t.id === group.scopeObjectId)
return foundTopic?.category_id || null
}
return null
}, [group.scopeType, group.scopeObjectId, allTopics?.data])
// Если цепочка глобальная (resolvedCategoryId === null), берем вообще все системы через useAllSystemOptions,
// иначе — системы конкретной категории через useCategorySystemOptions.
const categoryOptionsResult = useCategorySystemOptions(resolvedCategoryId)
const allOptionsResult = useAllSystemOptions(group.scopeType === 'global')
const systemOptions = group.scopeType === 'global' ? allOptionsResult.options : categoryOptionsResult.options
console.log(`[ChainVisualization] Группа ${group.key} (scope: ${group.scopeType}): resolvedCategoryId = ${resolvedCategoryId}, доступно систем:`, systemOptions)
// Текущая система цепочки (если у всех шагов одинаковая система, иначе 'all')
const currentChainSystem = group.steps.every(
(s) => s.target_system === group.steps[0]?.target_system
)
? group.steps[0]?.target_system || ALL_SYSTEMS_VALUE
: ALL_SYSTEMS_VALUE
// Формируем опции для Select
const selectData = [
{ value: ALL_SYSTEMS_VALUE, label: 'Система: Все' },
...systemOptions.map((opt) => ({
value: opt.value,
label: `Система: ${opt.label}`,
})),
]
return (
<Paper
withBorder
p="lg"
style={{
backgroundColor: 'var(--mantine-color-white)',
borderColor: 'var(--mantine-color-gray-3)',
}}
>
{/* Заголовок группы */}
<Group justify="space-between" mb="lg">
<Group gap="md">
<Avatar size="md" radius="xl" color="gray" variant="filled">
{group.subordinateName.charAt(0).toUpperCase()}
</Avatar>
<Stack gap={0}>
<Text fw={600} size="sm" c="dark">
{group.subordinateName}
</Text>
<Text size="xs" c="dimmed">
{group.departmentName}
</Text>
</Stack>
<Divider orientation="vertical" />
<Badge
variant="outline"
color={SCOPE_COLORS[group.scopeType]}
leftSection={<ScopeIcon type={group.scopeType} />}
size="sm"
tt="none"
>
{SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName}
</Badge>
{/* Выпадающий список систем отображается ТОЛЬКО если у темы/категории есть заданные systems */}
{systemOptions.length > 0 && (
<Select
size="xs"
leftSection={<IconServer size={14} />}
data={selectData}
value={currentChainSystem}
onChange={(val) => {
const newSystem = val === ALL_SYSTEMS_VALUE ? null : val
if (onBulkUpdateSystem) {
onBulkUpdateSystem(group, newSystem)
}
}}
style={{ width: 180 }}
/>
)}
</Group>
<Group gap="xs">
<Tooltip label="Добавить шаг" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="md"
onClick={() => onAddStep(group)}
>
<IconPlus size={18} />
</ActionIcon>
</Tooltip>
<Tooltip label="Дублировать цепочку" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="md"
onClick={() => onDuplicateChain(group)}
>
<IconCopy size={18} />
</ActionIcon>
</Tooltip>
</Group>
</Group>
<Divider mb="lg" />
{/* Цепочка согласования */}
<Box style={{ overflowX: 'auto' }}>
<Group gap={0} wrap="nowrap" align="stretch">
{/* Карточка инициатора */}
<Paper
withBorder
p="md"
style={{
minWidth: 180,
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-gray-0)',
}}
>
<Stack gap="xs" align="center">
<Text
size="xs"
fw={600}
c="dimmed"
tt="uppercase"
style={{ letterSpacing: '0.5px' }}
>
Инициатор
</Text>
<Avatar size="md" radius="xl" color="gray" variant="filled">
{group.subordinateName.charAt(0).toUpperCase()}
</Avatar>
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{group.subordinateName}
</Text>
</Stack>
</Paper>
{/* Шаги согласования */}
{group.steps.map((step, index) => (
<Group key={step.id} gap={0} wrap="nowrap" align="stretch">
<Stack
gap={2}
align="center"
justify="center"
px="xs"
style={{ minWidth: 60 }}
>
<IconChevronRight size={20} color="var(--mantine-color-gray-5)" />
<Badge size="xs" variant="light" color="gray" tt="none">
{index + 1}
</Badge>
</Stack>
{/* Карточка согласующего */}
<Paper
withBorder
p="md"
style={{
minWidth: 180,
borderColor: 'var(--mantine-color-gray-3)',
backgroundColor: 'var(--mantine-color-white)',
cursor: 'pointer',
transition: 'border-color 0.15s ease',
position: 'relative',
}}
onClick={() => onEditStep(step.id!)}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-blue-5)'
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = 'var(--mantine-color-gray-3)'
}}
>
<Stack gap="xs" align="center">
<Group gap={6}>
<Text
size="xs"
fw={600}
c="dimmed"
tt="uppercase"
style={{ letterSpacing: '0.5px' }}
>
Шаг {index + 1}
</Text>
<Badge size="xs" variant="light" color="gray" tt="none">
#{step.priority}
</Badge>
</Group>
<Avatar size="md" radius="xl" color="blue" variant="filled">
{step.approver?.full_name?.charAt(0).toUpperCase() || '?'}
</Avatar>
<Text size="sm" fw={500} ta="center" lineClamp={2} c="dark">
{step.approver?.full_name || '—'}
</Text>
{/* Бейдж конкретной целевой системы для шага (если выбрано) */}
{step.target_system && (
<Badge size="xs" color="cyan" variant="light">
Система: {step.target_system}
</Badge>
)}
<Divider style={{ width: '100%', margin: '4px 0' }} />
<Group gap="xs" justify="center">
<Tooltip label="Редактировать" withArrow>
<ActionIcon
variant="subtle"
color="gray"
size="sm"
onClick={(e) => {
e.stopPropagation()
onEditStep(step.id!)
}}
>
<IconPencil size={14} />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить" withArrow>
<ActionIcon
variant="subtle"
color="red"
size="sm"
onClick={(e) => {
e.stopPropagation()
onDeleteStep(step.id!)
}}
>
<IconTrash size={14} />
</ActionIcon>
</Tooltip>
</Group>
</Stack>
</Paper>
</Group>
))}
</Group>
</Box>
</Paper>
)
}