213 lines
9.5 KiB
TypeScript
213 lines
9.5 KiB
TypeScript
import { useState, useMemo } from 'react'
|
||
import {
|
||
Paper,
|
||
Group,
|
||
Button,
|
||
Text,
|
||
Select,
|
||
Loader,
|
||
Center,
|
||
Stack,
|
||
Badge,
|
||
Alert,
|
||
Tooltip,
|
||
} from '@mantine/core'
|
||
import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh } from '@tabler/icons-react'
|
||
import { modals } from '@mantine/modals'
|
||
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||
import {
|
||
useFlowNodesTree,
|
||
useDeleteFlowNode,
|
||
useDuplicateFlowNode,
|
||
useReloadBot,
|
||
} from '@/features/flowNodes/hooks/useFlowNodes'
|
||
import { findParent } from '@/features/flowNodes/utils/treeWalk'
|
||
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
|
||
import { useNavigate } from 'react-router-dom'
|
||
import CategoryCreateModal from "@/pages/flowNodes/components/CategoryCreateModal.tsx";
|
||
import FlowNodeEditModal from "@/pages/flowNodes/components/FlowNodeEditModal.tsx";
|
||
import SortableFlowTree from "@/pages/flowNodes/components/SortableFlowTree.tsx";
|
||
import TreeHealthPanel from "@/pages/flowNodes/components/TreeHealthPanel.tsx";
|
||
|
||
export default function FlowTreePage() {
|
||
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
|
||
const [categoryModalOpened, setCategoryModalOpened] = useState(false)
|
||
|
||
const [editModal, setEditModal] = useState<{
|
||
opened: boolean
|
||
parentNode: ApprovalFlowNode | null
|
||
editNode: ApprovalFlowNode | null
|
||
}>({ opened: false, parentNode: null, editNode: null })
|
||
|
||
const { data: categoriesData } = useCategories({ limit: 1000, is_active: true })
|
||
const categories = categoriesData?.data || []
|
||
|
||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
|
||
const tree = treeData?.data || []
|
||
|
||
const deleteFlowNode = useDeleteFlowNode()
|
||
const duplicateFlowNode = useDuplicateFlowNode()
|
||
const reloadBot = useReloadBot()
|
||
|
||
const navigate = useNavigate()
|
||
|
||
const selectedCategory = useMemo<ApprovalTopicCategory | null>(
|
||
() => categories.find((c) => c.id === selectedCategoryId) || null,
|
||
[categories, selectedCategoryId]
|
||
)
|
||
|
||
const categoryOptions = categories.map((c) => ({ value: String(c.id), label: `${c.name} (${c.code})` }))
|
||
|
||
const countNodes = (nodes: ApprovalFlowNode[]): number => {
|
||
let count = nodes.length
|
||
for (const n of nodes) if (n.children) count += countNodes(n.children)
|
||
return count
|
||
}
|
||
const totalNodes = countNodes(tree)
|
||
|
||
const handleEdit = (node: ApprovalFlowNode) => {
|
||
const parent = findParent(tree, node.id!)
|
||
setEditModal({ opened: true, parentNode: parent, editNode: node })
|
||
}
|
||
|
||
const handleAddChild = (parent: ApprovalFlowNode) => {
|
||
setEditModal({ opened: true, parentNode: parent, editNode: null })
|
||
}
|
||
|
||
const handleAddRoot = () => {
|
||
setEditModal({ opened: true, parentNode: null, editNode: null })
|
||
}
|
||
|
||
const handleDelete = (node: ApprovalFlowNode) => {
|
||
modals.openConfirmModal({
|
||
title: 'Удалить этот шаг?',
|
||
children: (
|
||
<Text size="sm">
|
||
Удалить шаг <b>{node.label}</b>? Все шаги, которые идут после него, тоже удалятся.
|
||
</Text>
|
||
),
|
||
labels: { confirm: 'Удалить', cancel: 'Отмена' },
|
||
confirmProps: { color: 'red' },
|
||
onConfirm: () => deleteFlowNode.mutate(node.id!),
|
||
})
|
||
}
|
||
|
||
const handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!)
|
||
|
||
return (
|
||
<Stack gap="md">
|
||
<Group justify="space-between">
|
||
<Text size="xl" fw={700}>
|
||
Конструктор дерева заявок
|
||
</Text>
|
||
<Group>
|
||
{selectedCategory && <Badge size="lg" variant="light">{totalNodes} шагов</Badge>}
|
||
<Tooltip label="Заставить бота немедленно перечитать разделы/деревья/темы из базы, не дожидаясь автоматической проверки">
|
||
<Button
|
||
variant="light"
|
||
color="orange"
|
||
leftSection={<IconRefresh size={16} />}
|
||
onClick={() => reloadBot.mutate()}
|
||
loading={reloadBot.isPending}
|
||
>
|
||
Обновить бота
|
||
</Button>
|
||
</Tooltip>
|
||
<Button variant="light" leftSection={<IconBook size={16} />} onClick={() => navigate('/guide/flow-trees')}>
|
||
Руководство
|
||
</Button>
|
||
</Group>
|
||
</Group>
|
||
|
||
<Paper withBorder p="md">
|
||
<Group align="end" gap="sm">
|
||
<Select
|
||
label="Раздел заявок"
|
||
placeholder="Выберите раздел, дерево которого будете настраивать"
|
||
data={categoryOptions}
|
||
value={selectedCategoryId ? String(selectedCategoryId) : null}
|
||
onChange={(v) => setSelectedCategoryId(v ? Number(v) : null)}
|
||
searchable
|
||
style={{ flex: 1 }}
|
||
/>
|
||
<Tooltip label="Завести новый раздел заявок, не выходя отсюда">
|
||
<Button
|
||
variant="default"
|
||
leftSection={<IconFolderPlus size={16} />}
|
||
onClick={() => setCategoryModalOpened(true)}
|
||
>
|
||
Новый раздел
|
||
</Button>
|
||
</Tooltip>
|
||
</Group>
|
||
</Paper>
|
||
|
||
{selectedCategoryId && (
|
||
<Paper withBorder p="md">
|
||
<Stack gap="md">
|
||
<Group justify="space-between">
|
||
<Group gap="xs">
|
||
<Text fw={600}>Дерево вопросов</Text>
|
||
{treeLoading && <Loader size="xs" />}
|
||
</Group>
|
||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot} disabled={tree.length > 0}>
|
||
Добавить первый вопрос
|
||
</Button>
|
||
</Group>
|
||
|
||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||
<Text size="sm">
|
||
Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните
|
||
влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева
|
||
(с пометкой «начало дерева») не перетаскивается. + — добавить следующий шаг;
|
||
✏️ — изменить; 📋 — сделать копию; 🗑 — удалить. Всё сохраняется сразу.
|
||
</Text>
|
||
</Alert>
|
||
|
||
{treeLoading ? (
|
||
<Center p={40}>
|
||
<Loader />
|
||
</Center>
|
||
) : tree.length === 0 ? (
|
||
<Center p={40}>
|
||
<Stack gap="sm" align="center">
|
||
<Text c="dimmed">В этом разделе пока нет вопросов</Text>
|
||
<Button leftSection={<IconPlus size={16} />} onClick={handleAddRoot}>
|
||
Добавить первый вопрос
|
||
</Button>
|
||
</Stack>
|
||
</Center>
|
||
) : (
|
||
<SortableFlowTree
|
||
tree={tree}
|
||
onEdit={handleEdit}
|
||
onAddChild={handleAddChild}
|
||
onDelete={handleDelete}
|
||
onDuplicate={handleDuplicate}
|
||
/>
|
||
)}
|
||
</Stack>
|
||
</Paper>
|
||
)}
|
||
|
||
{selectedCategoryId && tree.length > 0 && <TreeHealthPanel categoryId={selectedCategoryId} tree={tree} />}
|
||
|
||
{selectedCategoryId && (
|
||
<FlowNodeEditModal
|
||
categoryId={selectedCategoryId}
|
||
tree={tree}
|
||
parentNode={editModal.parentNode}
|
||
editNode={editModal.editNode}
|
||
opened={editModal.opened}
|
||
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
|
||
/>
|
||
)}
|
||
|
||
<CategoryCreateModal
|
||
opened={categoryModalOpened}
|
||
onClose={() => setCategoryModalOpened(false)}
|
||
onCreated={(newId) => setSelectedCategoryId(newId)}
|
||
/>
|
||
</Stack>
|
||
)
|
||
} |