285 lines
15 KiB
TypeScript
285 lines
15 KiB
TypeScript
import { useEffect } from 'react'
|
||
import { Drawer, Stack, Select, NumberInput, Group, Button, Text, Badge, Paper, Alert, Radio, Box } from '@mantine/core'
|
||
import { useForm } from '@mantine/form'
|
||
import { IconInfoCircle, IconAlertCircle, IconCopy } from '@tabler/icons-react'
|
||
import { notifications } from '@mantine/notifications'
|
||
|
||
import { useCreateHierarchy, useUpdateHierarchy } 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 { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions'
|
||
import type { UserHierarchy } from '@/types/api'
|
||
import type { ChainGroup } from '@/features/hierarchies/utils'
|
||
import classes from '@/components/UserDrawer.module.css'
|
||
|
||
interface Props {
|
||
hierarchy: UserHierarchy | null
|
||
presetGroup?: ChainGroup | null
|
||
opened: boolean
|
||
onClose: () => void
|
||
}
|
||
|
||
type ScopeType = 'global' | 'category' | 'topic'
|
||
|
||
export default function HierarchyEditDrawer({ hierarchy, presetGroup, opened, onClose }: Props) {
|
||
const createHierarchy = useCreateHierarchy()
|
||
const updateHierarchy = useUpdateHierarchy()
|
||
|
||
const { data: users } = useUsers({ limit: 1000 })
|
||
const { data: departments } = useDepartments()
|
||
const { data: categories } = useCategories({ limit: 1000 })
|
||
const { options: systemOptions } = useAllSystemOptions()
|
||
|
||
const isEditMode = hierarchy !== null
|
||
|
||
const form = useForm({
|
||
initialValues: {
|
||
subordinate_id: null as number | null,
|
||
approver_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,
|
||
priority: 0,
|
||
target_system: null as string | null
|
||
},
|
||
validate: {
|
||
subordinate_id: (v) => (v === null ? 'Выберите подчинённого' : null),
|
||
approver_id: (v) => (v === null ? 'Выберите согласующего' : null),
|
||
department_id: (v) => (!isEditMode && v === null ? 'Выберите отдел' : null),
|
||
topic_category_id: (v, values) => {
|
||
if (isEditMode) return null
|
||
if ((values.scope_type === 'category' || values.scope_type === 'topic') && v === null) return 'Выберите категорию'
|
||
return null
|
||
},
|
||
topic_id: (v, values) => {
|
||
if (isEditMode) return null
|
||
if (values.scope_type === 'topic' && v === null) return 'Выберите тему'
|
||
return null
|
||
},
|
||
},
|
||
})
|
||
|
||
const { data: categoryTopics } = useTopics({
|
||
limit: 1000,
|
||
...(form.values.topic_category_id && { category_id: form.values.topic_category_id }),
|
||
})
|
||
const { data: allTopics } = useTopics({ limit: 1000 })
|
||
|
||
useEffect(() => {
|
||
if (!opened) return
|
||
if (hierarchy) {
|
||
let scopeType: ScopeType = 'global'
|
||
if (hierarchy.topic_id) scopeType = 'topic'
|
||
else if (hierarchy.topic_category_id) scopeType = 'category'
|
||
|
||
let resolvedCategoryId = hierarchy.topic_category_id || null
|
||
if (scopeType === 'topic' && !resolvedCategoryId && allTopics?.data) {
|
||
const matchedTopic = allTopics.data.find((t) => t.id === hierarchy.topic_id)
|
||
resolvedCategoryId = matchedTopic?.category_id || null
|
||
}
|
||
|
||
form.setValues({
|
||
subordinate_id: hierarchy.subordinate_id || null,
|
||
approver_id: hierarchy.approver_id || null,
|
||
department_id: hierarchy.department_id || null,
|
||
scope_type: scopeType,
|
||
topic_category_id: resolvedCategoryId,
|
||
topic_id: hierarchy.topic_id || null,
|
||
target_system: hierarchy.target_system || null,
|
||
priority: hierarchy.priority ?? 0,
|
||
})
|
||
} else if (presetGroup) {
|
||
let resolvedCategoryId: number | null = null
|
||
if (presetGroup.scopeType === 'category') resolvedCategoryId = presetGroup.scopeObjectId
|
||
else if (presetGroup.scopeType === 'topic') {
|
||
const matchedTopic = allTopics?.data?.find((t) => t.id === presetGroup.scopeObjectId)
|
||
resolvedCategoryId = matchedTopic?.category_id || null
|
||
}
|
||
|
||
form.setValues({
|
||
subordinate_id: presetGroup.subordinateId,
|
||
department_id: presetGroup.departmentId,
|
||
scope_type: presetGroup.scopeType,
|
||
topic_category_id: resolvedCategoryId,
|
||
topic_id: presetGroup.scopeType === 'topic' ? presetGroup.scopeObjectId : null,
|
||
priority: presetGroup.steps.length,
|
||
approver_id: null,
|
||
})
|
||
} else {
|
||
form.reset()
|
||
}
|
||
}, [hierarchy, presetGroup, opened, allTopics])
|
||
|
||
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 userOptions = users?.data?.map((u) => ({ value: String(u.id), label: u.full_name || `ID ${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 buildPayload = (values: typeof form.values) => ({
|
||
subordinate_id: values.subordinate_id!,
|
||
approver_id: values.approver_id!,
|
||
department_id: values.department_id!,
|
||
priority: values.priority,
|
||
target_system: values.target_system || null,
|
||
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,
|
||
})
|
||
|
||
const handleSubmit = async (values: typeof form.values) => {
|
||
const payload = buildPayload(values)
|
||
if (isEditMode && hierarchy?.id) await updateHierarchy.mutateAsync({ id: hierarchy.id, ...payload })
|
||
else await createHierarchy.mutateAsync(payload)
|
||
onClose()
|
||
}
|
||
|
||
const handleDuplicate = async () => {
|
||
if (!isEditMode) return
|
||
try {
|
||
await createHierarchy.mutateAsync(buildPayload(form.values))
|
||
notifications.show({ title: 'Успешно', message: 'Связь продублирована', color: 'green' })
|
||
onClose()
|
||
} catch {
|
||
notifications.show({ title: 'Ошибка', message: 'Не удалось продублировать связь', color: 'red' })
|
||
}
|
||
}
|
||
|
||
const isSubmitting = createHierarchy.isPending || updateHierarchy.isPending
|
||
const hasErrors = Object.keys(form.errors).length > 0
|
||
|
||
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>
|
||
{hierarchy && <Badge variant="light">ID: {hierarchy.id}</Badge>}
|
||
</Group>
|
||
</Box>
|
||
<Drawer.CloseButton />
|
||
</Drawer.Header>
|
||
|
||
<Drawer.Body className={classes.body}>
|
||
<form style={{ display: 'contents' }} onSubmit={form.onSubmit(handleSubmit)}>
|
||
<Stack gap="lg" className={classes.section}>
|
||
{hasErrors && (
|
||
<Alert icon={<IconAlertCircle size={16} />} color="red" variant="light">
|
||
<Text size="sm">Проверьте поля, отмеченные красным.</Text>
|
||
</Alert>
|
||
)}
|
||
|
||
<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 disabled={!!presetGroup}
|
||
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={!isEditMode} disabled={isEditMode || !!presetGroup}
|
||
error={form.errors.department_id}
|
||
/>
|
||
|
||
<Select
|
||
label="Согласующий"
|
||
placeholder="Выберите пользователя"
|
||
data={userOptions}
|
||
value={form.values.approver_id ? String(form.values.approver_id) : null}
|
||
onChange={(v) => form.setFieldValue('approver_id', v ? Number(v) : null)}
|
||
searchable required
|
||
error={form.errors.approver_id}
|
||
/>
|
||
|
||
<Paper withBorder p="md">
|
||
<Text size="sm" fw={500} mb="sm">Область действия</Text>
|
||
<Radio.Group value={form.values.scope_type} onChange={(v) => handleScopeTypeChange(v as ScopeType)}>
|
||
<Stack gap="xs">
|
||
<Radio value="global" label="Глобальное правило" disabled={isEditMode} />
|
||
<Radio value="category" label="Для категории тем" disabled={isEditMode} />
|
||
<Radio value="topic" label="Для конкретной темы" disabled={isEditMode} />
|
||
</Stack>
|
||
</Radio.Group>
|
||
</Paper>
|
||
|
||
{(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={!isEditMode} disabled={isEditMode || !!presetGroup}
|
||
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={!isEditMode} disabled={!form.values.topic_category_id || isEditMode || !!presetGroup}
|
||
error={form.errors.topic_id}
|
||
/>
|
||
)}
|
||
|
||
<Select
|
||
label="Целевая система шага"
|
||
placeholder="Все системы"
|
||
data={[{ value: 'all', label: 'Все системы' }, ...systemOptions.map((s) => ({ value: s.value, label: s.label }))]}
|
||
value={form.values.target_system || 'all'}
|
||
onChange={(v) => form.setFieldValue('target_system', (v === 'all' || !v) ? "" : v)}
|
||
/>
|
||
|
||
<NumberInput
|
||
label="Порядок шага (priority)"
|
||
value={form.values.priority}
|
||
onChange={(v) => form.setFieldValue('priority', Number(v) || 0)}
|
||
min={0} required
|
||
/>
|
||
</Stack>
|
||
|
||
<Group className={classes.footer} justify="space-between" wrap="nowrap">
|
||
{isEditMode ? (
|
||
<Button variant="light" color="teal" leftSection={<IconCopy size={16} />} onClick={handleDuplicate} disabled={isSubmitting}>
|
||
Дублировать
|
||
</Button>
|
||
) : <div />}
|
||
<Group gap="xs">
|
||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>Отмена</Button>
|
||
<Button type="submit" loading={isSubmitting}>{isEditMode ? 'Сохранить' : 'Создать'}</Button>
|
||
</Group>
|
||
</Group>
|
||
</form>
|
||
</Drawer.Body>
|
||
</Drawer.Content>
|
||
</Drawer.Root>
|
||
)
|
||
} |