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

495 lines
22 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.

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>
)
}