From 8bbb6bcd89c4b291cf493814d2668f5753a68b94 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Thu, 23 Jul 2026 16:24:46 +0300 Subject: [PATCH] Updated hierarchy page --- src/pages/hierarchies/HierarchiesPage.tsx | 23 +- .../components/ChainDuplicateModal.tsx | 26 ++- .../components/HierarchyEditModal.tsx | 105 +++++++--- .../components/PersonDuplicateModal.tsx | 198 ++++++++++++++++++ 4 files changed, 320 insertions(+), 32 deletions(-) create mode 100644 src/pages/hierarchies/components/PersonDuplicateModal.tsx diff --git a/src/pages/hierarchies/HierarchiesPage.tsx b/src/pages/hierarchies/HierarchiesPage.tsx index 6c5744a..a3ec8d1 100644 --- a/src/pages/hierarchies/HierarchiesPage.tsx +++ b/src/pages/hierarchies/HierarchiesPage.tsx @@ -25,6 +25,7 @@ import { IconPlus, IconInfoCircle, IconCheck, + IconUsers, } from '@tabler/icons-react' import { modals } from '@mantine/modals' import { notifications } from '@mantine/notifications' @@ -45,6 +46,7 @@ import { import ChainVisualization from './components/ChainVisualization' import ChainDuplicateModal from './components/ChainDuplicateModal' import HierarchyEditModal from './components/HierarchyEditModal' +import PersonDuplicateModal from './components/PersonDuplicateModal' import type { UserHierarchy } from '@/types/api' const LIMIT = 20 @@ -69,8 +71,9 @@ export default function HierarchiesPage() { const [editHierarchy, setEditHierarchy] = useState(null) const [createModalOpened, setCreateModalOpened] = useState(false) const [presetGroup, setPresetGroup] = useState(null) - const [duplicateGroup, setDuplicateGroup] = useState(null) // 🆕 - const [duplicateModalOpened, setDuplicateModalOpened] = useState(false) // 🆕 + const [duplicateGroup, setDuplicateGroup] = useState(null) + const [duplicateModalOpened, setDuplicateModalOpened] = useState(false) + const [personDuplicateOpened, setPersonDuplicateOpened] = useState(false) // 🆕 const { data: categoryTopics } = useTopics({ limit: 1000, @@ -261,6 +264,17 @@ export default function HierarchiesPage() { { value: 'table', label: 'Таблица' }, ]} /> + {/* 🆕 Дублирование всех связей сотрудника целиком — для нового + сотрудника, а не для одной конкретной цепочки */} + + + - + + {isEditMode ? ( + + ) : ( +
+ )} + + + + diff --git a/src/pages/hierarchies/components/PersonDuplicateModal.tsx b/src/pages/hierarchies/components/PersonDuplicateModal.tsx new file mode 100644 index 0000000..72092c4 --- /dev/null +++ b/src/pages/hierarchies/components/PersonDuplicateModal.tsx @@ -0,0 +1,198 @@ +import { useState } from 'react' +import { + Modal, + Stack, + Select, + Group, + Button, + Text, + Paper, + Alert, + Badge, + Loader, + Center, +} from '@mantine/core' +import { IconInfoCircle, IconUsers } from '@tabler/icons-react' +import { notifications } from '@mantine/notifications' +import { useHierarchies, useCreateHierarchy } from '@/features/hierarchies/hooks/useHierarchies' +import { useUsers } from '@/features/users/hooks/useUsers' +import { useCategories } from '@/features/categories/hooks/useCategories' +import { useTopics } from '@/features/topics/hooks/useTopics' + +interface PersonDuplicateModalProps { + opened: boolean + onClose: () => void +} + +// 0 — заведомо несуществующий id пользователя, чтобы не дёргать хук +// условно (нарушает Rules of Hooks) и не гадать, как бэкенд обработает +// limit:0 — просто явно просим "ничего не найдётся". +const NO_USER_SENTINEL = 0 + +export default function PersonDuplicateModal({ opened, onClose }: PersonDuplicateModalProps) { + const [sourceId, setSourceId] = useState(null) + const [targetId, setTargetId] = useState(null) + const [isDuplicating, setIsDuplicating] = useState(false) + + const { data: users } = useUsers({ limit: 1000 }) + const { data: categories } = useCategories({ limit: 1000 }) + const { data: topics } = useTopics({ limit: 1000 }) + const createHierarchy = useCreateHierarchy() + + // Все связи исходного сотрудника — по всем областям действия сразу + // (глобальные + по категориям + по темам), без пагинации. + const { data: sourceHierarchies, isLoading: sourceLoading } = useHierarchies({ + subordinate_id: sourceId ? Number(sourceId) : NO_USER_SENTINEL, + limit: 1000, + }) + + const sourceRows = sourceId ? sourceHierarchies?.data || [] : [] + + const userOptions = users?.data?.map((u) => ({ + value: String(u.id), + label: u.full_name || `Пользователь #${u.id}`, + })) || [] + + const describeScope = (h: { topic_id?: number | null; topic_category_id?: number | null }) => { + if (h.topic_id) { + const t = topics?.data?.find((t) => t.id === h.topic_id) + return `Тема: ${t?.name || `#${h.topic_id}`}` + } + if (h.topic_category_id) { + const c = categories?.data?.find((c) => c.id === h.topic_category_id) + return `Категория: ${c?.name || `#${h.topic_category_id}`}` + } + return 'Глобально' + } + + const handleClose = () => { + setSourceId(null) + setTargetId(null) + onClose() + } + + const handleDuplicate = async () => { + if (!sourceId || !targetId || sourceRows.length === 0) return + setIsDuplicating(true) + try { + // Последовательно, а не Promise.all — чтобы не заваливать API + // залпом при большом количестве связей у сотрудника, и чтобы + // при ошибке было понятно, на какой именно записи остановились. + for (const h of sourceRows) { + if (!h.approver_id || !h.department_id) continue + await createHierarchy.mutateAsync({ + subordinate_id: Number(targetId), + approver_id: h.approver_id, + department_id: h.department_id, + priority: h.priority ?? 0, + topic_category_id: h.topic_category_id ?? null, + topic_id: h.topic_id ?? null, + }) + } + + notifications.show({ + title: 'Успешно', + message: `Продублировано связей: ${sourceRows.length}`, + color: 'green', + }) + handleClose() + } catch (error) { + notifications.show({ + title: 'Ошибка', + message: 'Не удалось продублировать связи — часть могла успеть создаться, проверьте список', + color: 'red', + }) + } finally { + setIsDuplicating(false) + } + } + + return ( + + + Дублировать все связи сотрудника + + } + size="lg" + centered + > + + } color="blue" variant="light"> + + Скопирует ВСЕ цепочки согласования выбранного сотрудника — глобальные, по + категориям и по темам — для нового сотрудника. Отдел, согласующие, + категории/темы и порядок шагов сохранятся как на образце. + + + + o.value !== sourceId)} + value={targetId} + onChange={setTargetId} + searchable + required + disabled={!sourceId} + /> + + {sourceId && ( + + + Будет продублировано + + {sourceLoading ? ( +
+ +
+ ) : sourceRows.length === 0 ? ( + + У этого сотрудника нет ни одной настроенной связи — дублировать нечего. + + ) : ( + + {sourceRows.map((h) => ( + + + {h.approver?.full_name || `Согласующий #${h.approver_id}`} + + + {describeScope(h)} + + + ))} + + )} +
+ )} + + + + + +
+
+ ) +} \ No newline at end of file