From f7ca74a7b598e4486402b49f421a54c4c767a078 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Wed, 18 Nov 2026 15:32:58 +0300 Subject: [PATCH] Updated categories page --- result.txt | 6 +- src/pages/categories/CategoriesPage.tsx | 10 +- src/pages/hierarchies/HierarchiesPage.tsx | 796 +++++------------- .../components/ChainDuplicateDrawer.tsx | 233 +++++ .../components/ChainDuplicateModal.tsx | 527 ------------ .../components/ChainVisualization.tsx | 284 ++----- .../components/HierarchyEditDrawer.tsx | 285 +++++++ .../components/HierarchyEditModal.tsx | 421 --------- .../components/PersonDuplicateDrawer.tsx | 197 +++++ .../components/PersonDuplicateModal.tsx | 401 --------- 10 files changed, 993 insertions(+), 2167 deletions(-) create mode 100644 src/pages/hierarchies/components/ChainDuplicateDrawer.tsx delete mode 100644 src/pages/hierarchies/components/ChainDuplicateModal.tsx create mode 100644 src/pages/hierarchies/components/HierarchyEditDrawer.tsx delete mode 100644 src/pages/hierarchies/components/HierarchyEditModal.tsx create mode 100644 src/pages/hierarchies/components/PersonDuplicateDrawer.tsx delete mode 100644 src/pages/hierarchies/components/PersonDuplicateModal.tsx diff --git a/result.txt b/result.txt index 32ce226..6d8f9d2 100644 --- a/result.txt +++ b/result.txt @@ -161,10 +161,10 @@ │ │ ├── hierarchies │ │ │ ├── HierarchiesPage.tsx │ │ │ ├── components -│ │ │ │ ├── ChainDuplicateModal.tsx +│ │ │ │ ├── ChainDuplicateDrawer.tsx │ │ │ │ ├── ChainVisualization.tsx -│ │ │ │ ├── HierarchyEditModal.tsx -│ │ │ │ ├── PersonDuplicateModal.tsx +│ │ │ │ ├── HierarchyEditDrawer.tsx +│ │ │ │ ├── PersonDuplicateDrawer.tsx │ │ ├── monthlyOrders │ │ │ ├── MonthlyOrdersSettingsPage.tsx │ │ ├── notifications diff --git a/src/pages/categories/CategoriesPage.tsx b/src/pages/categories/CategoriesPage.tsx index 12ecb08..b050e0c 100644 --- a/src/pages/categories/CategoriesPage.tsx +++ b/src/pages/categories/CategoriesPage.tsx @@ -1,11 +1,11 @@ import { useEffect, useMemo, useState } from 'react' -import { ActionIcon, Badge, Button, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core' +import { ActionIcon, Badge, Button, Group, Select, Stack, Text, TextInput, Tooltip } from '@mantine/core' import { useDebouncedValue } from '@mantine/hooks' import { IconPencil, IconPlus, IconSearch, IconTrash } from '@tabler/icons-react' import { useCategories, useDeleteCategory } from '@/features/categories/hooks/useCategories' -import type { Category } from '@/features/categories/types' +import { ApprovalTopicCategory } from '@/src/types/api' import { PageHeader } from '@/components/ui/PageHeader' import { FilterBar } from '@/components/ui/FilterBar' import { DataTable, type Column } from '@/components/ui/DataTable' @@ -31,7 +31,7 @@ export default function CategoriesPage() { const [debouncedSearch] = useDebouncedValue(searchInput.trim(), 400) const [drawerId, setDrawerId] = useState(null) - const [deleteTarget, setDeleteTarget] = useState(null) + const [deleteTarget, setDeleteTarget] = useState(null) const deleteCategory = useDeleteCategory() @@ -70,7 +70,7 @@ export default function CategoriesPage() { setDeleteTarget(null) } - const columns: Column[] = [ + const columns: Column[] = [ { key: 'id', header: 'ID', @@ -170,7 +170,7 @@ export default function CategoriesPage() { /> - + columns={columns} rows={data?.data ?? []} getRowId={(r) => r.id!} diff --git a/src/pages/hierarchies/HierarchiesPage.tsx b/src/pages/hierarchies/HierarchiesPage.tsx index 053be36..a4bb9a4 100644 --- a/src/pages/hierarchies/HierarchiesPage.tsx +++ b/src/pages/hierarchies/HierarchiesPage.tsx @@ -1,61 +1,35 @@ import { useState, useMemo } from 'react' -import { - Paper, - Table, - Group, - ActionIcon, - Button, - Text, - Select, - Loader, - Center, - Tooltip, - Box, - Stack, - SegmentedControl, - Badge, - Alert, - ScrollArea, - Pagination, - Checkbox, -} from '@mantine/core' -import { - IconPencil, - IconTrash, - IconPlus, - IconInfoCircle, - IconUsers, -} from '@tabler/icons-react' +import { ActionIcon, Badge, Box, Button, Checkbox, Group, SegmentedControl, Select, Stack, Text, Tooltip } from '@mantine/core' +import { IconCopy, IconPencil, IconPlus, IconTrash, IconUsers } from '@tabler/icons-react' import { modals } from '@mantine/modals' import { notifications } from '@mantine/notifications' -import { - useHierarchies, - useDeleteHierarchy, - useUpdateHierarchy, HIERARCHIES_QUERY_KEY, -} from '@/features/hierarchies/hooks/useHierarchies' +import { useQueryClient } from '@tanstack/react-query' + +import { useHierarchies, useDeleteHierarchy, useUpdateHierarchy, HIERARCHIES_QUERY_KEY } 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 { - groupHierarchiesIntoChains, - SCOPE_COLORS, - SCOPE_LABELS, - type ChainGroup, -} from '@/features/hierarchies/utils' -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' import { hierarchiesApi } from '@/api/hierarchies' -import { useQueryClient } from '@tanstack/react-query' +import type { UserHierarchy } from '@/types/api' +import { groupHierarchiesIntoChains, SCOPE_COLORS, SCOPE_LABELS, type ChainGroup } from '@/features/hierarchies/utils' + +import { PageHeader } from '@/components/ui/PageHeader' +import { FilterBar } from '@/components/ui/FilterBar' +import { DataTable, type Column } from '@/components/ui/DataTable' +import { ConfirmModal } from '@/components/ui/ConfirmModal' + +import ChainVisualization from './components/ChainVisualization' +import HierarchyEditDrawer from './components/HierarchyEditDrawer' +import ChainDuplicateDrawer from './components/ChainDuplicateDrawer' +import PersonDuplicateDrawer from './components/PersonDuplicateDrawer' const LIMIT = 20 - type ViewMode = 'chains' | 'table' export default function HierarchiesPage() { + const queryClient = useQueryClient() + const [viewMode, setViewMode] = useState('chains') const [page, setPage] = useState(1) @@ -67,17 +41,17 @@ export default function HierarchiesPage() { const [categoryFilter, setCategoryFilter] = useState(null) const [topicFilter, setTopicFilter] = useState(null) - // Массовое удаление const [selectedIds, setSelectedIds] = useState([]) const [isDeleting, setIsDeleting] = useState(false) - // Модалки + // Drawers const [editHierarchy, setEditHierarchy] = useState(null) - const [createModalOpened, setCreateModalOpened] = useState(false) + const [createDrawerOpened, setCreateDrawerOpened] = useState(false) const [presetGroup, setPresetGroup] = useState(null) + const [duplicateGroup, setDuplicateGroup] = useState(null) - const [duplicateModalOpened, setDuplicateModalOpened] = useState(false) const [personDuplicateOpened, setPersonDuplicateOpened] = useState(false) + const [deleteTarget, setDeleteTarget] = useState(null) const { data: categoryTopics } = useTopics({ limit: 1000, @@ -92,9 +66,7 @@ export default function HierarchiesPage() { ...(departmentFilter && { department_id: Number(departmentFilter) }), ...(categoryFilter && { topic_category_id: Number(categoryFilter) }), ...(topicFilter && { topic_id: Number(topicFilter) }), - ...(userStatusFilter && { - user_status: userStatusFilter as 'active' | 'fired' | 'blocked', - }), + ...(userStatusFilter && { user_status: userStatusFilter as 'active' | 'fired' | 'blocked' }), }) const { data: users } = useUsers({ limit: 1000 }) @@ -105,14 +77,11 @@ export default function HierarchiesPage() { const deleteHierarchy = useDeleteHierarchy() const updateHierarchy = useUpdateHierarchy() - const totalPages = data?.total_count ? Math.ceil(data.total_count / LIMIT) : 1 - - const chains = useMemo(() => { - if (!data?.data) return [] - return groupHierarchiesIntoChains(data.data) - }, [data]) + const total = data?.total_count ?? 0 const enrichedChains = useMemo(() => { + if (!data?.data) return [] + const chains = groupHierarchiesIntoChains(data.data) return chains.map((chain) => { let scopeObjectName = 'Все темы' if (chain.scopeType === 'category' && chain.scopeObjectId) { @@ -124,7 +93,7 @@ export default function HierarchiesPage() { } return { ...chain, scopeObjectName } }) - }, [chains, categories, topics]) + }, [data, categories, topics]) const filteredUsers = useMemo(() => { if (!users?.data) return [] @@ -136,116 +105,39 @@ export default function HierarchiesPage() { }) }, [users, userStatusFilter]) - const userOptions = - filteredUsers.map((u) => ({ - value: String(u.id), - label: u.full_name || `Пользователь #${u.id}`, - })) || [] - users?.data?.map((u) => ({ - value: String(u.id), - label: u.full_name || `Пользователь #${u.id}`, - })) || []; - - const allUserOptions = - 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 = - (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({ - value: String(t.id), - label: t.name || '', - })) || [] + const userOptions = filteredUsers.map((u) => ({ value: String(u.id), label: u.full_name || `ID ${u.id}` })) + const allUserOptions = 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 = (categoryFilter ? categoryTopics?.data : topics?.data)?.map((t) => ({ value: String(t.id), label: t.name || '' })) || [] const handleSelectAll = () => { - if (selectedIds.length === data?.data?.length) { - setSelectedIds([]) - } else { - setSelectedIds(data?.data?.map((h) => h.id!) || []) - } + if (selectedIds.length === data?.data?.length) setSelectedIds([]) + else setSelectedIds(data?.data?.map((h) => h.id!) || []) } const handleSelectOne = (id: number) => { - setSelectedIds((prev) => - prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id] - ) + setSelectedIds((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]) } - const handleFilterChange = - (setter: (value: string | null) => void) => (value: string | null) => { - setter(value) - setPage(1) + const setFilter = (setter: (val: string | null) => void) => (val: string | null) => { + setter(val) + setPage(1) + setSelectedIds([]) + } + + const handleBulkDelete = async () => { + setIsDeleting(true) + try { + await Promise.all(selectedIds.map((id) => hierarchiesApi.delete(id))) + await queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) + notifications.show({ title: 'Успешно', message: `Удалено связей: ${selectedIds.length}`, color: 'green' }) setSelectedIds([]) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось удалить выбранные связи', color: 'red' }) + } finally { + setIsDeleting(false) } - - const queryClient = useQueryClient() - - const handleBulkDelete = () => { - modals.openConfirmModal({ - title: 'Подтвердите массовое удаление', - children: ( - - Вы уверены, что хотите удалить {selectedIds.length}{' '} - записей? Это действие необратимо. - - ), - labels: { confirm: 'Удалить все', cancel: 'Отмена' }, - confirmProps: { color: 'red', loading: isDeleting }, - onConfirm: async () => { - setIsDeleting(true) - try { - // Удаляем напрямую через API, не вызывая мутацию поштучно - await Promise.all(selectedIds.map((id) => hierarchiesApi.delete(id))) - - // Обновляем список один раз - queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) - - notifications.show({ - title: 'Успешно', - message: `Успешно удалено записей: ${selectedIds.length}`, - color: 'green', - }) - setSelectedIds([]) - } catch (error) { - notifications.show({ - title: 'Ошибка', - message: 'Не удалось удалить некоторые записи', - color: 'red', - }) - } finally { - setIsDeleting(false) - } - }, - }) - } - - const handleDelete = (id: number) => { - modals.openConfirmModal({ - title: 'Подтвердите удаление', - children: ( - - Вы уверены, что хотите удалить эту связь? - - ), - labels: { confirm: 'Удалить', cancel: 'Отмена' }, - confirmProps: { color: 'red' }, - onConfirm: async () => { - await deleteHierarchy.mutateAsync(id) - }, - }) } const handleDeleteChain = (group: ChainGroup) => { @@ -254,464 +146,216 @@ export default function HierarchiesPage() { modals.openConfirmModal({ title: 'Удалить всю цепочку', - children: ( - - Вы уверены, что хотите удалить всю цепочку согласования для{' '} - {group.subordinateName} ({group.scopeObjectName}, шагов:{' '} - {stepIds.length})? Это действие необратимо. - - ), - labels: { confirm: 'Удалить цепочку', cancel: 'Отмена' }, + children: Вы уверены, что хотите удалить цепочку согласования для {group.subordinateName} (шагов: {stepIds.length})?, + labels: { confirm: 'Удалить', cancel: 'Отмена' }, confirmProps: { color: 'red' }, onConfirm: async () => { try { await Promise.all(stepIds.map((id) => hierarchiesApi.delete(id))) - queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) - notifications.show({ - title: 'Успешно', - message: `Цепочка удалена (удалено шагов: ${stepIds.length})`, - color: 'green', - }) - } catch (error) { - notifications.show({ - title: 'Ошибка', - message: 'Не удалось удалить цепочку полностью', - color: 'red', - }) + await queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) + notifications.show({ title: 'Успешно', message: 'Цепочка удалена', color: 'green' }) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось удалить цепочку', color: 'red' }) } }, }) } - const handleEditStep = (id: number) => { - const hierarchy = data?.data?.find((h) => h.id === id) - if (hierarchy) { - setEditHierarchy(hierarchy) + const handleSwapSteps = async (stepA: UserHierarchy, stepB: UserHierarchy) => { + try { + await Promise.all([ + updateHierarchy.mutateAsync({ id: stepA.id!, priority: stepB.priority }), + updateHierarchy.mutateAsync({ id: stepB.id!, priority: stepA.priority }), + ]) + await queryClient.invalidateQueries({ queryKey: [HIERARCHIES_QUERY_KEY] }) + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось изменить порядок', color: 'red' }) } } - const handleAddStep = (group: ChainGroup) => { - setPresetGroup(group) - setCreateModalOpened(true) - } - - const handleDuplicateChain = (group: ChainGroup) => { - setDuplicateGroup(group) - setDuplicateModalOpened(true) - } - - const handleCloseModal = () => { - setEditHierarchy(null) - setCreateModalOpened(false) - setPresetGroup(null) - } - - const handleCloseDuplicateModal = () => { - 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) - const handleBulkUpdateSystem = async (group: ChainGroup, targetSystem: string | null) => { try { - // Обновляем все шаги в выбранной цепочке асинхронно await Promise.all( group.steps.map((step) => - updateHierarchy.mutateAsync({ - id: step.id!, - subordinate_id: step.subordinate_id, - approver_id: step.approver_id, - department_id: step.department_id, - topic_category_id: step.topic_category_id, - topic_id: step.topic_id, - priority: step.priority, - target_system: targetSystem, // Применяем новую систему - }) + updateHierarchy.mutateAsync({ ...step, target_system: targetSystem }) ) ) } catch (error) { - console.error("Ошибка при массовом обновлении систем цепочки", error) + notifications.show({ title: 'Ошибка', message: 'Не удалось обновить систему', color: 'red' }) } } - return ( - - {/* Заголовок */} - - Иерархия согласований - - - Всего: {data?.total_count || 0} - - { - setViewMode(v as ViewMode) - setSelectedIds([]) - }} - data={[ - { value: 'chains', label: 'Цепочки' }, - { value: 'table', label: 'Таблица' }, - ]} - /> - - + const isAllSelected = (data?.data?.length ?? 0) > 0 && selectedIds.length === (data?.data?.length ?? 0) + const isIndeterminate = selectedIds.length > 0 && selectedIds.length < (data?.data?.length || 0) + + const activeCount = [ + subordinateFilter, approverFilter, userStatusFilter, departmentFilter, categoryFilter, topicFilter + ].filter(Boolean).length + + const resetFilters = () => { + setSubordinateFilter(null) + setApproverFilter(null) + setUserStatusFilter(null) + setDepartmentFilter(null) + setCategoryFilter(null) + setTopicFilter(null) + setPage(1) + setSelectedIds([]) + } + + const columns: Column[] = [ + { + key: 'select', + header: , + width: 50, + cell: (r) => ( + handleSelectOne(r.id!)} + onClick={(e) => e.stopPropagation()} + /> + ), + }, + { key: 'id', header: 'ID', width: 60, cell: (r) => #{r.id} }, + { key: 'sub', header: 'Подчинённый', cell: (r) => {r.subordinate?.full_name || '—'} }, + { key: 'app', header: 'Согласующий', cell: (r) => {r.approver?.full_name || '—'} }, + { key: 'dep', header: 'Отдел', cell: (r) => {r.department?.name || '—'} }, + { + key: 'scope', + header: 'Область', + cell: (r) => { + const type = r.topic_id ? 'topic' : r.topic_category_id ? 'category' : 'global' + return {SCOPE_LABELS[type]} + } + }, + { key: 'priority', header: 'Порядок', width: 80, cell: (r) => #{r.priority} }, + { + key: 'actions', + header: '', + width: 100, + align: 'right', + cell: (r) => ( + + + { e.stopPropagation(); setEditHierarchy(r); }}> + + + + + { e.stopPropagation(); setDeleteTarget(r.id!); }}> + + - - + ), + }, + ] - } color="blue" variant="light"> - - Иерархия определяет порядок согласования заявок. Каждая цепочка показывает, - через каких согласующих проходит заявка от конкретного сотрудника. - - + return ( + + + { setViewMode(v as ViewMode); setSelectedIds([]); }} + data={[{ value: 'chains', label: 'Цепочки' }, { value: 'table', label: 'Таблица' }]} + /> + + + + + + } + /> - {/* Фильтры */} - + + + + + + + {viewMode === 'chains' ? ( - - - - - + ))} - - - {/* Контент */} - - {isLoading ? ( -
- -
- ) : viewMode === 'chains' ? ( - - - {enrichedChains.length === 0 ? ( -
- Связи не найдены -
- ) : ( - enrichedChains.map((chain) => ( - - )) - )} -
-
- ) : ( - <> - {selectedIds.length > 0 && ( - - - - Выбрано записей: {selectedIds.length} - - - - - + ) : ( + + {selectedIds.length > 0 && ( + + + Выбрано записей: {selectedIds.length} + + + - - )} - - - - - - - - ID - Подчинённый - Согласующий - Отдел - Область - Объект - Порядок - Действия - - - - {data?.data?.length === 0 ? ( - - -
- Связи не найдены -
-
-
- ) : ( - data?.data?.map((h) => { - const scopeType = h.topic_id - ? 'topic' - : h.topic_category_id - ? 'category' - : 'global' - let scopeObjectName = 'Все темы' - if (scopeType === 'category' && h.topic_category_id) { - const cat = categories?.data?.find( - (c) => c.id === h.topic_category_id - ) - scopeObjectName = cat?.name || `#${h.topic_category_id}` - } else if (scopeType === 'topic' && h.topic_id) { - const topic = topics?.data?.find( - (t) => t.id === h.topic_id - ) - scopeObjectName = topic?.name || `#${h.topic_id}` - } - - return ( - - - handleSelectOne(h.id!)} - /> - - {h.id} - - - {h.subordinate?.full_name || '—'} - - - - - {h.approver?.full_name || '—'} - - - - - {h.department?.name || '—'} - - - - - { - SCOPE_LABELS[ - scopeType as keyof typeof SCOPE_LABELS - ] - } - - - - - {scopeObjectName} - - - - - #{h.priority} - - - - - - setEditHierarchy(h)} - > - - - - - handleDelete(h.id!)} - > - - - - - - - ) - }) - )} -
-
- - )} - - {totalPages > 1 && ( - - - - Страница {page} из {totalPages} - - { - setPage(newPage) - setSelectedIds([]) - }} - total={totalPages} - withEdges - /> - - - )} -
- - {isFetching && !isLoading && ( - - - + + + )} + + columns={columns} + rows={data?.data ?? []} + getRowId={(r) => r.id!} + loading={isLoading} + refreshing={isFetching} + onRowClick={(r) => setEditHierarchy(r)} + empty={{ title: 'Связи не найдены' }} + pagination={{ page, pageSize: LIMIT, total, onChange: (p) => { setPage(p); setSelectedIds([]); } }} + /> +
)} - {/* Модалки */} - - - { setEditHierarchy(null); setPresetGroup(null); setCreateDrawerOpened(false); }} /> - setDuplicateGroup(null)} /> - setPersonDuplicateOpened(false)} /> + + setDeleteTarget(null)} + onConfirm={async () => { + await deleteHierarchy.mutateAsync(deleteTarget!); + setDeleteTarget(null); + }} + title="Удалить связь" + message="Вы уверены, что хотите удалить этого согласующего из цепочки?" + confirmLabel="Удалить" + danger + /> ) } \ No newline at end of file diff --git a/src/pages/hierarchies/components/ChainDuplicateDrawer.tsx b/src/pages/hierarchies/components/ChainDuplicateDrawer.tsx new file mode 100644 index 0000000..f8c5cb0 --- /dev/null +++ b/src/pages/hierarchies/components/ChainDuplicateDrawer.tsx @@ -0,0 +1,233 @@ +import { useEffect } from 'react' +import { Drawer, Stack, Select, Group, Button, Text, Paper, Divider, ActionIcon, Badge, Avatar, Box, Radio, Alert } from '@mantine/core' +import { useForm } from '@mantine/form' +import { IconInfoCircle, IconPlus, IconTrash, 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 { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' +import type { ChainGroup } from '@/features/hierarchies/utils' +import classes from '@/components/UserDrawer.module.css' + +interface Props { + group: ChainGroup | null + opened: boolean + onClose: () => void +} + +type ScopeType = 'global' | 'category' | 'topic' + +interface StepForm { + approver_id: number | null + priority: number + target_system: string | null +} + +export default function ChainDuplicateDrawer({ group, opened, onClose }: Props) { + const createHierarchy = useCreateHierarchy() + const { data: users } = useUsers({ limit: 1000 }) + const { data: departments } = useDepartments() + const { data: categories } = useCategories({ limit: 1000 }) + const { options: systemOptions } = useAllSystemOptions() + const { data: allTopics } = useTopics({ 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, values) => { + 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 (!opened) return + if (group) { + let resolvedCategoryId: number | null = null + if (group.scopeType === 'category') resolvedCategoryId = group.scopeObjectId + else if (group.scopeType === 'topic') { + const matchedTopic = allTopics?.data?.find((t) => t.id === group.scopeObjectId) + resolvedCategoryId = matchedTopic?.category_id || null + } + + form.setValues({ + subordinate_id: group.subordinateId, + department_id: group.departmentId, + scope_type: group.scopeType, + topic_category_id: resolvedCategoryId, + topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null, + steps: group.steps.map((s, idx) => ({ + approver_id: s.approver_id || null, + priority: idx, + target_system: s.target_system || null, + })), + }) + } + }, [group, 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 addStep = () => { + form.insertListItem('steps', { approver_id: null, priority: form.values.steps.length, target_system: null }) + } + + const removeStep = (index: number) => { + form.removeListItem('steps', index) + 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 || `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 handleSubmit = async (values: typeof form.values) => { + if (values.steps.length === 0) return notifications.show({ title: 'Ошибка', message: 'Добавьте хотя бы один шаг', color: 'red' }) + 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, + target_system: step.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, + }) + } + notifications.show({ title: 'Успешно', message: `Создана цепочка (${values.steps.length} шагов)`, color: 'green' }) + onClose() + } catch { + notifications.show({ title: 'Ошибка', message: 'Не удалось дублировать', color: 'red' }) + } + } + + const isSubmitting = createHierarchy.isPending + + return ( + + + + + Дублирование цепочки + + + + +
+ + } color="blue" variant="light"> + Новая цепочка на основе выбранной. Измените инициатора, отдел, область действия или шаги. + + + + Общие параметры + + form.setFieldValue('department_id', v ? Number(v) : null)} searchable required error={form.errors.department_id} /> + + + + + Область действия + + handleScopeTypeChange(v as ScopeType)}> + + + + + + + {(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && ( + form.setFieldValue('topic_id', v ? Number(v) : null)} searchable required disabled={!form.values.topic_category_id} error={form.errors.topic_id} /> + )} + + + + + + Шаги согласования + + + + {form.values.steps.map((step, index) => ( + + + {index + 1} + + + ({ value: s.value, label: `Система: ${s.label}` }))]} value={step.target_system || 'all'} onChange={(v) => form.setFieldValue(`steps.${index}.target_system`, (v === 'all' || !v) ? null : v)} clearable /> + + + removeStep(index)}> + + + ))} + + + + {form.values.steps.length > 0 && ( + + Предпросмотр + + {users?.data?.find((u) => u.id === form.values.subordinate_id)?.full_name || 'Инициатор'} + {form.values.steps.map((step, index) => ( + + + + {users?.data?.find((u) => u.id === step.approver_id)?.full_name || `Шаг ${index + 1}`} + {step.target_system && ` (${step.target_system})`} + + + ))} + + + )} + + + + + + +
+
+
+
+ ) +} \ No newline at end of file diff --git a/src/pages/hierarchies/components/ChainDuplicateModal.tsx b/src/pages/hierarchies/components/ChainDuplicateModal.tsx deleted file mode 100644 index 9312db8..0000000 --- a/src/pages/hierarchies/components/ChainDuplicateModal.tsx +++ /dev/null @@ -1,527 +0,0 @@ -import { useEffect } from 'react' -import { - Modal, - Stack, - Select, - 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 { useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' // 👈 ИМПОРТИРОВАЛИ ХУК -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 - target_system: string | null // 👈 ДОБАВИЛИ ПОЛЕ В ИНТЕРФЕЙС -} - -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 { options: systemOptions } = useAllSystemOptions() - - const { data: allTopics } = useTopics({ 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, values) => { - 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) { - let resolvedCategoryId: number | null = null - if (group.scopeType === 'category') { - resolvedCategoryId = group.scopeObjectId - } else if (group.scopeType === 'topic') { - const matchedTopic = allTopics?.data?.find((t) => t.id === group.scopeObjectId) - resolvedCategoryId = matchedTopic?.category_id || null - } - - form.setValues({ - subordinate_id: group.subordinateId, - department_id: group.departmentId, - scope_type: group.scopeType, - topic_category_id: resolvedCategoryId, - topic_id: group.scopeType === 'topic' ? group.scopeObjectId : null, - steps: group.steps.map((s, idx) => ({ - approver_id: s.approver_id || null, - priority: idx, - target_system: s.target_system || null, // 👈 ИНИЦИАЛИЗИРУЕМ ИЗ БД - })), - }) - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [group, 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 addStep = () => { - form.insertListItem('steps', { - approver_id: null, - priority: form.values.steps.length, - target_system: null, // 👈 ИНИЦИАЛИЗИРУЕМ ДЛЯ НОВОГО ШАГА - }) - } - - const removeStep = (index: number) => { - form.removeListItem('steps', index) - 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, - target_system: step.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, - }) - } - - notifications.show({ - title: 'Успешно', - message: `Цепочка дублирована (${values.steps.length} шагов)`, - color: 'green', - }) - onClose() - } catch (error) { - notifications.show({ - title: 'Ошибка', - message: 'Не удалось дублировать цепочку', - color: 'red', - }) - } - } - - const isSubmitting = createHierarchy.isPending - - return ( - - - Дублирование цепочки - - } - size="lg" - centered - > -
- - } color="blue" variant="light"> - - Создайте новую цепочку на основе существующей. Вы можете изменить - инициатора, отдел, область действия и согласующих. - - - - {/* Общие параметры */} - - - Общие параметры - - - - form.setFieldValue( - 'department_id', - v ? Number(v) : null - ) - } - searchable - required - error={form.errors.department_id} - /> - - - - {/* Область действия */} - - - Область действия - - - handleScopeTypeChange(v as ScopeType)} - > - - - - - - - - {(form.values.scope_type === 'category' || - form.values.scope_type === 'topic') && ( - - form.setFieldValue('topic_id', v ? Number(v) : null) - } - searchable - required - disabled={!form.values.topic_category_id} - error={form.errors.topic_id} - /> - )} - - - - {/* Шаги согласования */} - - - - Шаги согласования - - - - - - {form.values.steps.length === 0 ? ( - - - Нет шагов согласования. Добавьте хотя бы один. - - - ) : ( - form.values.steps.map((step, index) => ( - - - - {index + 1} - - - - - - Шаг {index + 1} - - - Priority: {step.priority} - - - - - ({ value: s.value, label: `Система: ${s.label}` })), - ]} - value={step.target_system || 'all'} - onChange={(v) => - form.setFieldValue( - `steps.${index}.target_system`, - (v === 'all' || !v) ? null : v - ) - } - clearable - /> - - - - removeStep(index)} - > - - - - - )) - )} - - - - {/* Предпросмотр */} - {form.values.steps.length > 0 && ( - - - Предпросмотр цепочки - - - - {users?.data?.find( - (u) => u.id === form.values.subordinate_id - )?.full_name || 'Инициатор'} - - {form.values.steps.map((step, index) => ( - - - - {users?.data?.find( - (u) => u.id === step.approver_id - )?.full_name || `Шаг ${index + 1}`} - {step.target_system && ` (${step.target_system})`} - - - ))} - - - )} - - - - - - - - -
-
- ) -} \ No newline at end of file diff --git a/src/pages/hierarchies/components/ChainVisualization.tsx b/src/pages/hierarchies/components/ChainVisualization.tsx index 9c9641d..b044839 100644 --- a/src/pages/hierarchies/components/ChainVisualization.tsx +++ b/src/pages/hierarchies/components/ChainVisualization.tsx @@ -1,78 +1,39 @@ -// 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 { useMemo } 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, IconArrowLeft, IconArrowRight } 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"; +import type { UserHierarchy } from '@/types/api' +import { useCategorySystemOptions, ALL_SYSTEMS_VALUE, useAllSystemOptions } from '@/features/hierarchies/hooks/useSystemOptions' +import { useTopics } from '@/features/topics/hooks/useTopics' -interface ChainVisualizationProps { +interface Props { group: ChainGroup onEditStep: (hierarchyId: number) => void onDeleteStep: (hierarchyId: number) => void - onDeleteChain: (group: ChainGroup) => void // <-- ДОБАВЛЕНО + onDeleteChain: (group: ChainGroup) => void onAddStep: (group: ChainGroup) => void onDuplicateChain: (group: ChainGroup) => void onBulkUpdateSystem?: (group: ChainGroup, targetSystem: string | null) => void + onSwapSteps: (stepA: UserHierarchy, stepB: UserHierarchy) => void } const ScopeIcon = ({ type }: { type: string }) => { switch (type) { - case 'global': - return - case 'category': - return - case 'topic': - return - default: - return + case 'category': return + case 'topic': return + default: return } } -// Внутри компонента ChainVisualization: export default function ChainVisualization({ - group, - onEditStep, - onDeleteStep, - onDeleteChain, - onAddStep, - onDuplicateChain, - onBulkUpdateSystem, - }: ChainVisualizationProps) { - // Получаем все темы, чтобы уметь мапить topicId -> categoryId, если scopeType === 'topic' + group, onEditStep, onDeleteStep, onDeleteChain, onAddStep, onDuplicateChain, onBulkUpdateSystem, onSwapSteps + }: Props) { const { data: allTopics } = useTopics({ limit: 1000 }) const resolvedCategoryId = useMemo(() => { - if (group.scopeType === 'category') { - return group.scopeObjectId - } + 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 @@ -80,248 +41,103 @@ export default function ChainVisualization({ 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 - ) + 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}`, - })), + ...systemOptions.map((opt) => ({ value: opt.value, label: `Система: ${opt.label}` })), ] return ( - - {/* Заголовок группы */} + {group.subordinateName.charAt(0).toUpperCase()} - - - {group.subordinateName} - - - {group.departmentName} - + {group.subordinateName} + {group.departmentName} - - - } - size="sm" - tt="none" - > + } size="sm" tt="none"> {SCOPE_LABELS[group.scopeType]}: {group.scopeObjectName} - {/* Выпадающий список систем отображается ТОЛЬКО если у темы/категории есть заданные systems */} {systemOptions.length > 0 && ( form.setFieldValue('subordinate_id', v ? Number(v) : null)} + searchable required disabled={!!presetGroup} + error={form.errors.subordinate_id} + /> + + form.setFieldValue('approver_id', v ? Number(v) : null)} + searchable required + error={form.errors.approver_id} + /> + + + Область действия + handleScopeTypeChange(v as ScopeType)}> + + + + + + + + + {(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && ( + form.setFieldValue('topic_id', v ? Number(v) : null)} + searchable required={!isEditMode} disabled={!form.values.topic_category_id || isEditMode || !!presetGroup} + error={form.errors.topic_id} + /> + )} + + form.setFieldValue('subordinate_id', v ? Number(v) : null)} - searchable - required - disabled={!!presetGroup} - description="Пользователь, для которого настраивается согласование" - error={form.errors.subordinate_id} - /> - - {/* Отдел */} - form.setFieldValue('approver_id', v ? Number(v) : null)} - searchable - required - description="Пользователь, который будет согласовывать заявки" - error={form.errors.approver_id} - /> - - {/* Область действия */} - - - Область действия - - handleScopeTypeChange(v as ScopeType)} - > - - - - - - - - - {/* Категория */} - {(form.values.scope_type === 'category' || form.values.scope_type === 'topic') && ( - form.setFieldValue('topic_id', v ? Number(v) : null)} - searchable - required={!isEditMode} - disabled={!form.values.topic_category_id || isEditMode || !!presetGroup} - description={!form.values.topic_category_id && !isEditMode ? 'Сначала выберите категорию' : undefined} - error={form.errors.topic_id} - /> - )} - - o.value !== targetId)} value={sourceId} onChange={setSourceId} searchable required /> + o.value !== targetId)} - value={sourceId} - onChange={setSourceId} - searchable - required - /> - -