Added flow nodes page && tree guide page
Deploy Frontend / build-and-deploy (push) Failing after 21s
Details
Deploy Frontend / build-and-deploy (push) Failing after 21s
Details
This commit is contained in:
parent
f3ac7337bc
commit
d00ee99ab1
2
.env
2
.env
|
|
@ -1,5 +1,5 @@
|
|||
# API Configuration
|
||||
#VITE_API_BASE_URL=http://localhost:1726/api
|
||||
VITE_API_BASE_URL=http://localhost:1726/api
|
||||
VITE_API_KEY=test
|
||||
VITE_API_PUBLIC_KEY=ruspet_public_key_2026
|
||||
VITE_API_PRIVATE_KEY=ruspet_private_key_SUPER_SECRET_2026
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import TopicsPage from "@/pages/topics/TopicsPage.tsx";
|
|||
import SettingsPage from './pages/settings/SettingsPage'
|
||||
import AdminsPage from './pages/admins/AdminsPage'
|
||||
import ApprovalTasksPage from './pages/approvalTasks/ApprovalTasksPage'
|
||||
import FlowTreePage from "@/pages/flowNodes/FlowTreePage.tsx";
|
||||
import FlowTreeGuidePage from './pages/flowNodes/FlowTreeGuidePage'
|
||||
|
||||
const Placeholder = ({ title }: { title: string }) => (
|
||||
<div style={{ padding: 40 }}>
|
||||
|
|
@ -52,6 +54,7 @@ function App() {
|
|||
<Route path="/" element={<Placeholder title="Главная" /> } />
|
||||
<Route path="/notifications" element={<Placeholder title="Уведомления" /> } />
|
||||
<Route path="/approval-dash" element={<Dashboard />} />
|
||||
<Route path="/nodes" element={<FlowTreePage/>} />
|
||||
<Route path="/users" element={<UsersPage />} />
|
||||
<Route path="/departments" element={<DepartmentsPage />} />
|
||||
<Route path="/roles" element={<RolesPage />} />
|
||||
|
|
@ -64,6 +67,7 @@ function App() {
|
|||
<Route path="/settings" element={<SettingsPage />} />
|
||||
<Route path="/admins" element={<AdminsPage />} />
|
||||
<Route path="/approval-tasks" element={<ApprovalTasksPage />} />
|
||||
<Route path="/guide/flow-trees" element={<FlowTreeGuidePage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
import apiClient from './client'
|
||||
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
||||
|
||||
export interface CreateFlowNodeRequest {
|
||||
topic_id: number
|
||||
parent_id?: number | null
|
||||
key: string
|
||||
label: string
|
||||
data_key?: string | null
|
||||
data_value?: string | null
|
||||
is_input?: boolean
|
||||
input_key?: string | null
|
||||
input_hint?: string | null
|
||||
is_multi_select?: boolean
|
||||
multi_select_key?: string | null
|
||||
multi_select_value?: string | null
|
||||
topic_code?: string | null
|
||||
sort_order?: number
|
||||
}
|
||||
|
||||
export interface UpdateFlowNodeRequest {
|
||||
id: number
|
||||
topic_id?: number
|
||||
parent_id?: number | null
|
||||
key?: string
|
||||
label?: string
|
||||
data_key?: string | null
|
||||
data_value?: string | null
|
||||
is_input?: boolean
|
||||
input_key?: string | null
|
||||
input_hint?: string | null
|
||||
is_multi_select?: boolean
|
||||
multi_select_key?: string | null
|
||||
multi_select_value?: string | null
|
||||
topic_code?: string | null
|
||||
sort_order?: number
|
||||
}
|
||||
|
||||
export interface MoveFlowNodeRequest {
|
||||
new_parent_id?: number | null
|
||||
new_sort_order?: number
|
||||
}
|
||||
|
||||
export interface SaveTreeRequest {
|
||||
nodes: ApprovalFlowNode[]
|
||||
}
|
||||
|
||||
export const flowNodesApi = {
|
||||
getTree: (topicId: number) =>
|
||||
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/topic/${topicId}`),
|
||||
|
||||
getById: (id: number) =>
|
||||
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
||||
|
||||
create: (data: CreateFlowNodeRequest) =>
|
||||
apiClient.post<ApprovalFlowNode>('/flow-nodes/', data),
|
||||
|
||||
update: (data: UpdateFlowNodeRequest) =>
|
||||
apiClient.put<ApprovalFlowNode>('/flow-nodes/', data),
|
||||
|
||||
delete: (id: number) =>
|
||||
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
||||
|
||||
saveTree: (topicId: number, data: SaveTreeRequest) =>
|
||||
apiClient.post<boolean>(`/flow-nodes/topic/${topicId}/tree`, data),
|
||||
|
||||
move: (id: number, data: MoveFlowNodeRequest) =>
|
||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
||||
|
||||
duplicate: (id: number) =>
|
||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/duplicate`, {}),
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ export interface TopicsListParams {
|
|||
is_active?: boolean
|
||||
name?: string
|
||||
code?: string
|
||||
is_tree_root?: boolean
|
||||
}
|
||||
|
||||
export interface CreateTopicRequest {
|
||||
|
|
@ -16,6 +17,7 @@ export interface CreateTopicRequest {
|
|||
code: string
|
||||
duration_type?: string
|
||||
time_type?: string
|
||||
is_tree_root?: boolean
|
||||
payment_type?: string
|
||||
template?: string | null
|
||||
allows_file?: boolean
|
||||
|
|
@ -28,6 +30,8 @@ export interface CreateTopicRequest {
|
|||
requires_file?: boolean
|
||||
require_observer_selection?: boolean
|
||||
instructions?: string | null
|
||||
message_template?: string | null
|
||||
code_template?: string | null
|
||||
}
|
||||
|
||||
export interface UpdateTopicRequest {
|
||||
|
|
@ -38,6 +42,7 @@ export interface UpdateTopicRequest {
|
|||
duration_type?: string
|
||||
time_type?: string
|
||||
payment_type?: string
|
||||
is_tree_root?: boolean
|
||||
template?: string | null
|
||||
allows_file?: boolean
|
||||
is_active?: boolean
|
||||
|
|
@ -49,6 +54,8 @@ export interface UpdateTopicRequest {
|
|||
requires_file?: boolean
|
||||
require_observer_selection?: boolean
|
||||
instructions?: string | null
|
||||
message_template?: string | null
|
||||
code_template?: string | null
|
||||
}
|
||||
|
||||
export const topicsApi = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,158 @@
|
|||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
flowNodesApi,
|
||||
type CreateFlowNodeRequest,
|
||||
type UpdateFlowNodeRequest,
|
||||
type MoveFlowNodeRequest,
|
||||
type SaveTreeRequest,
|
||||
} from '@/api/flowNodes'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
|
||||
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
||||
|
||||
export function useFlowNodesTree(topicId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: [FLOW_NODES_QUERY_KEY, topicId],
|
||||
queryFn: async () => {
|
||||
if (!topicId) return null
|
||||
const response = await flowNodesApi.getTree(topicId)
|
||||
return response.data
|
||||
},
|
||||
enabled: !!topicId,
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateFlowNodeRequest) => flowNodesApi.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел создан',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось создать узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: UpdateFlowNodeRequest) => flowNodesApi.update(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел обновлён',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось обновить узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDeleteFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => flowNodesApi.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел удалён',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось удалить узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useSaveFlowTree() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ topicId, data }: { topicId: number; data: SaveTreeRequest }) =>
|
||||
flowNodesApi.saveTree(topicId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Дерево сохранено',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось сохранить дерево',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useMoveFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: number; data: MoveFlowNodeRequest }) =>
|
||||
flowNodesApi.move(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось переместить узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useDuplicateFlowNode() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => flowNodesApi.duplicate(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||
notifications.show({
|
||||
title: 'Успешно',
|
||||
message: 'Узел дублирован',
|
||||
color: 'green',
|
||||
})
|
||||
},
|
||||
onError: (error: any) => {
|
||||
notifications.show({
|
||||
title: 'Ошибка',
|
||||
message: error.response?.data?.error_description || 'Не удалось дублировать узел',
|
||||
color: 'red',
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -45,10 +45,10 @@ export default function CategoryEditModal({
|
|||
is_active: true,
|
||||
},
|
||||
validate: {
|
||||
name: (value) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
||||
code: (value) => {
|
||||
name: (value: string | any[]) => (value.length < 2 ? 'Название должно содержать минимум 2 символа' : null),
|
||||
code: (value: string | any[]) => {
|
||||
if (value.length < 2) return 'Код должен содержать минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(value)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
|
||||
if (!/^[a-z0-9_]+$/.test(value as string)) return 'Код должен содержать только lowercase буквы, цифры и подчеркивания'
|
||||
return null
|
||||
},
|
||||
},
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,402 @@
|
|||
import { useState, useMemo } from 'react'
|
||||
import {
|
||||
Paper,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Select,
|
||||
Loader,
|
||||
Center,
|
||||
Stack,
|
||||
Box,
|
||||
Badge,
|
||||
Textarea,
|
||||
Code,
|
||||
Divider,
|
||||
Alert,
|
||||
Collapse,
|
||||
ActionIcon,
|
||||
Tooltip,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconPlus,
|
||||
IconDeviceFloppy,
|
||||
IconRefresh,
|
||||
IconChevronDown,
|
||||
IconChevronRight,
|
||||
IconInfoCircle, IconBook,
|
||||
} from '@tabler/icons-react'
|
||||
import { modals } from '@mantine/modals'
|
||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
||||
import {
|
||||
useFlowNodesTree,
|
||||
useDeleteFlowNode,
|
||||
useSaveFlowTree,
|
||||
useMoveFlowNode,
|
||||
useDuplicateFlowNode,
|
||||
} from '@/features/flowNodes/hooks/useFlowNodes'
|
||||
import { useUpdateTopic } from '@/features/topics/hooks/useTopics'
|
||||
import FlowTreeNode from './components/FlowTreeNode'
|
||||
import FlowNodeEditModal from './components/FlowNodeEditModal'
|
||||
import type { ApprovalFlowNode, ApprovalTopic } from '@/types/api'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
|
||||
export default function FlowTreePage() {
|
||||
const [selectedTopicId, setSelectedTopicId] = useState<number | null>(null)
|
||||
const [showTemplates, setShowTemplates] = useState(false)
|
||||
|
||||
// Модалка редактирования узла
|
||||
const [editModal, setEditModal] = useState<{
|
||||
opened: boolean
|
||||
parentNode: ApprovalFlowNode | null
|
||||
editNode: ApprovalFlowNode | null
|
||||
}>({
|
||||
opened: false,
|
||||
parentNode: null,
|
||||
editNode: null,
|
||||
})
|
||||
|
||||
// Загружаем все темы
|
||||
const { data: topicsData } = useTopics({
|
||||
limit: 1000,
|
||||
is_tree_root: true
|
||||
})
|
||||
const topics = topicsData?.data || []
|
||||
|
||||
// Загружаем дерево для выбранной темы
|
||||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedTopicId)
|
||||
const tree = treeData?.data || []
|
||||
|
||||
const deleteFlowNode = useDeleteFlowNode()
|
||||
const saveTree = useSaveFlowTree()
|
||||
const moveFlowNode = useMoveFlowNode()
|
||||
const duplicateFlowNode = useDuplicateFlowNode()
|
||||
const updateTopic = useUpdateTopic()
|
||||
|
||||
const navigate = useNavigate()
|
||||
|
||||
// Выбранная тема
|
||||
const selectedTopic = useMemo(() => {
|
||||
return topics.find((t) => t.id === selectedTopicId) || null
|
||||
}, [topics, selectedTopicId])
|
||||
|
||||
const topicOptions = topics.map((t) => ({
|
||||
value: String(t.id),
|
||||
label: `${t.name} (${t.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!)
|
||||
}
|
||||
|
||||
const handleMoveUp = (node: ApprovalFlowNode) => {
|
||||
const parent = findParent(tree, node.id!)
|
||||
const siblings = parent ? parent.children! : tree
|
||||
const index = siblings.findIndex((n) => n.id === node.id)
|
||||
if (index > 0) {
|
||||
moveFlowNode.mutate({
|
||||
id: node.id!,
|
||||
data: { new_sort_order: index - 1 },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleMoveDown = (node: ApprovalFlowNode) => {
|
||||
const parent = findParent(tree, node.id!)
|
||||
const siblings = parent ? parent.children! : tree
|
||||
const index = siblings.findIndex((n) => n.id === node.id)
|
||||
if (index < siblings.length - 1) {
|
||||
moveFlowNode.mutate({
|
||||
id: node.id!,
|
||||
data: { new_sort_order: index + 1 },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Сохранение шаблонов темы
|
||||
const handleSaveTemplates = () => {
|
||||
if (!selectedTopic) return
|
||||
updateTopic.mutate({
|
||||
id: selectedTopic.id!,
|
||||
message_template: selectedTopic.message_template,
|
||||
code_template: selectedTopic.code_template,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Text size="xl" fw={700}>Конструктор деревьев</Text>
|
||||
<Group>
|
||||
{selectedTopic && (
|
||||
<Badge size="lg" variant="light">{totalNodes} узлов</Badge>
|
||||
)}
|
||||
<Button
|
||||
variant="light"
|
||||
leftSection={<IconBook size={16} />}
|
||||
onClick={() => navigate('/guide/flow-trees')}
|
||||
>
|
||||
Руководство
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Выбор темы */}
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label="Тема"
|
||||
placeholder="Выберите тему для редактирования дерева"
|
||||
data={topicOptions}
|
||||
value={selectedTopicId ? String(selectedTopicId) : null}
|
||||
onChange={(v) => setSelectedTopicId(v ? Number(v) : null)}
|
||||
searchable
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Шаблоны темы */}
|
||||
{selectedTopic && (
|
||||
<>
|
||||
<Divider label="Шаблоны темы" labelPosition="center" />
|
||||
|
||||
<Box>
|
||||
<Group
|
||||
justify="space-between"
|
||||
mb="xs"
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => setShowTemplates(!showTemplates)}
|
||||
>
|
||||
<Group gap="xs">
|
||||
{showTemplates ? (
|
||||
<IconChevronDown size={16} />
|
||||
) : (
|
||||
<IconChevronRight size={16} />
|
||||
)}
|
||||
<Text size="sm" fw={500}>
|
||||
Шаблоны сообщений и кодов
|
||||
</Text>
|
||||
</Group>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="light"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleSaveTemplates()
|
||||
}}
|
||||
loading={updateTopic.isPending}
|
||||
leftSection={<IconDeviceFloppy size={14} />}
|
||||
>
|
||||
Сохранить шаблоны
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<Collapse expanded={showTemplates}>
|
||||
<Stack gap="sm">
|
||||
<Textarea
|
||||
label="Шаблон сообщения для согласующего (Go template)"
|
||||
description={
|
||||
<Text size="xs">
|
||||
Доступные переменные:{' '}
|
||||
<Code>{'{{.initiator_name}}'}</Code>,{' '}
|
||||
<Code>{'{{.topic_name}}'}</Code>,{' '}
|
||||
<Code>{'{{.content}}'}</Code>,{' '}
|
||||
<Code>{'{{.region_label}}'}</Code>,{' '}
|
||||
<Code>{'{{.branch_label}}'}</Code>, и любые ключи из{' '}
|
||||
<Code>collected</Code> + суффикс <Code>_label</Code>
|
||||
</Text>
|
||||
}
|
||||
minRows={6}
|
||||
value={selectedTopic.message_template || ''}
|
||||
onChange={(e) => {
|
||||
if (selectedTopic) {
|
||||
selectedTopic.message_template = e.currentTarget.value
|
||||
}
|
||||
}}
|
||||
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
label="Шаблон кода темы (Go template)"
|
||||
description={
|
||||
<Text size="xs">
|
||||
Формирует финальный код темы. Если не задан — код формируется
|
||||
автоматически из всех значений <Code>collected</Code>. Функции:{' '}
|
||||
<Code>trimPrefix</Code>, <Code>eq</Code>, <Code>contains</Code>
|
||||
</Text>
|
||||
}
|
||||
minRows={2}
|
||||
value={selectedTopic.code_template || ''}
|
||||
onChange={(e) => {
|
||||
if (selectedTopic) {
|
||||
selectedTopic.code_template = e.currentTarget.value
|
||||
}
|
||||
}}
|
||||
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||
/>
|
||||
</Stack>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* Дерево */}
|
||||
{selectedTopicId && (
|
||||
<Paper withBorder p="md">
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between">
|
||||
<Group gap="xs">
|
||||
<Text fw={600}>Дерево навигации</Text>
|
||||
{treeLoading && <Loader size="xs" />}
|
||||
</Group>
|
||||
<Group>
|
||||
<Tooltip label="Обновить">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
onClick={() => {
|
||||
if (selectedTopicId) {
|
||||
// Инвалидация кэша
|
||||
window.location.reload()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<IconRefresh size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Button
|
||||
leftSection={<IconPlus size={16} />}
|
||||
onClick={handleAddRoot}
|
||||
>
|
||||
Добавить корневой узел
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||
<Text size="sm">
|
||||
<b>Совет:</b> Используйте кнопки ↑ ↓ для изменения порядка,{' '}
|
||||
<b>+</b> для добавления дочернего узла, <b>📋</b> для дублирования.
|
||||
Все изменения сохраняются автоматически.
|
||||
</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>
|
||||
) : (
|
||||
<Stack gap={4}>
|
||||
{tree.map((node, idx) => (
|
||||
<FlowTreeNode
|
||||
key={node.id}
|
||||
node={node}
|
||||
depth={0}
|
||||
siblings={tree}
|
||||
onEdit={handleEdit}
|
||||
onAddChild={handleAddChild}
|
||||
onDelete={handleDelete}
|
||||
onDuplicate={handleDuplicate}
|
||||
onMoveUp={handleMoveUp}
|
||||
onMoveDown={handleMoveDown}
|
||||
index={idx}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Модалка редактирования узла */}
|
||||
{selectedTopicId && (
|
||||
<FlowNodeEditModal
|
||||
topicId={selectedTopicId}
|
||||
parentNode={editModal.parentNode}
|
||||
editNode={editModal.editNode}
|
||||
opened={editModal.opened}
|
||||
onClose={() => setEditModal({ opened: false, parentNode: null, editNode: null })}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
// Вспомогательная функция: найти родителя узла по ID
|
||||
function findParent(
|
||||
nodes: ApprovalFlowNode[],
|
||||
targetId: number,
|
||||
parent: ApprovalFlowNode | null = null
|
||||
): ApprovalFlowNode | null {
|
||||
for (const node of nodes) {
|
||||
if (node.id === targetId) return parent
|
||||
if (node.children) {
|
||||
const found = findParent(node.children, targetId, node)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
|
@ -0,0 +1,463 @@
|
|||
import {
|
||||
Paper,
|
||||
Stack,
|
||||
Text,
|
||||
Code,
|
||||
Box,
|
||||
Group,
|
||||
Badge,
|
||||
Alert,
|
||||
Divider,
|
||||
Table,
|
||||
ThemeIcon,
|
||||
Collapse,
|
||||
ActionIcon,
|
||||
} from '@mantine/core'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
IconArrowRight,
|
||||
IconDatabase,
|
||||
IconCode,
|
||||
IconMessage,
|
||||
IconAlertTriangle,
|
||||
IconCheck,
|
||||
IconChevronDown,
|
||||
IconChevronRight, IconBulb,
|
||||
} from '@tabler/icons-react'
|
||||
|
||||
interface DataFlowExplainerProps {
|
||||
dataKey?: string
|
||||
dataValue?: string
|
||||
label?: string
|
||||
nodeType: 'button' | 'input' | 'multiselect'
|
||||
}
|
||||
|
||||
export default function DataFlowExplainer({
|
||||
dataKey,
|
||||
dataValue,
|
||||
label,
|
||||
nodeType,
|
||||
}: DataFlowExplainerProps) {
|
||||
const [showDetails, setShowDetails] = useState(false)
|
||||
|
||||
// Примеры из реальных тем
|
||||
const examples = [
|
||||
{
|
||||
label: 'Крым',
|
||||
dataKey: 'region',
|
||||
dataValue: 'crimea',
|
||||
description: 'Выбор региона',
|
||||
category: 'region',
|
||||
},
|
||||
{
|
||||
label: 'Ф1',
|
||||
dataKey: 'branch',
|
||||
dataValue: 'f1',
|
||||
description: 'Выбор филиала',
|
||||
category: 'branch',
|
||||
},
|
||||
{
|
||||
label: 'За свой счёт',
|
||||
dataKey: 'payment_type',
|
||||
dataValue: 'own_expense',
|
||||
description: 'Тип оплаты',
|
||||
category: 'payment',
|
||||
},
|
||||
{
|
||||
label: 'ТМЦ',
|
||||
dataKey: 'expense_type',
|
||||
dataValue: 'tmc',
|
||||
description: 'Тип расхода',
|
||||
category: 'expense',
|
||||
},
|
||||
{
|
||||
label: 'На один день',
|
||||
dataKey: 'duration_type',
|
||||
dataValue: 'single_day',
|
||||
description: 'Длительность',
|
||||
category: 'duration',
|
||||
},
|
||||
]
|
||||
|
||||
// Определяем, есть ли конфликт с существующими ключами
|
||||
const isDuplicateKey = examples.some(
|
||||
(e) => e.dataKey === dataKey && e.dataValue === dataValue
|
||||
)
|
||||
|
||||
return (
|
||||
<Paper withBorder p="md" bg="blue.0">
|
||||
<Stack gap="md">
|
||||
{/* Заголовок */}
|
||||
<Group justify="space-between">
|
||||
<Group gap="xs">
|
||||
<ThemeIcon color="blue" variant="light" size="lg">
|
||||
<IconBulb size={20} />
|
||||
</ThemeIcon>
|
||||
<div>
|
||||
<Text fw={600} size="sm">
|
||||
Что такое DataKey и DataValue?
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Краткое объяснение — нажми, чтобы узнать больше
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
onClick={() => setShowDetails(!showDetails)}
|
||||
>
|
||||
{showDetails ? (
|
||||
<IconChevronDown size={20} />
|
||||
) : (
|
||||
<IconChevronRight size={20} />
|
||||
)}
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
|
||||
{/* Краткое объяснение (всегда видно) */}
|
||||
<Box>
|
||||
<Text size="sm" mb="xs">
|
||||
<b>DataKey</b> и <b>DataValue</b> — это пара "ключ-значение", которая
|
||||
сохраняется в память пользователя, когда он нажимает на этот узел.
|
||||
</Text>
|
||||
<Text size="sm">
|
||||
Позже эти значения используются для:
|
||||
</Text>
|
||||
<Group gap="xs" mt="xs">
|
||||
<Badge color="green" variant="light" leftSection={<IconCode size={12} />}>
|
||||
Формирования кода темы
|
||||
</Badge>
|
||||
<Badge color="violet" variant="light" leftSection={<IconMessage size={12} />}>
|
||||
Сообщения согласующему
|
||||
</Badge>
|
||||
<Badge color="orange" variant="light" leftSection={<IconDatabase size={12} />}>
|
||||
Сохранения в заявке
|
||||
</Badge>
|
||||
</Group>
|
||||
</Box>
|
||||
|
||||
{/* Интерактивный превью */}
|
||||
{dataKey && dataValue && (
|
||||
<Paper withBorder p="sm" bg="white">
|
||||
<Text size="xs" fw={600} c="dimmed" mb="xs">
|
||||
📊 Что произойдёт, когда пользователь нажмёт "{label || 'этот узел'}":
|
||||
</Text>
|
||||
|
||||
{/* Поток данных */}
|
||||
<Stack gap="xs">
|
||||
{/* Шаг 1: Нажатие */}
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon size="sm" color="blue" variant="light">
|
||||
<Text size="xs" fw={700}>1</Text>
|
||||
</ThemeIcon>
|
||||
<Text size="xs" style={{ flex: 1 }}>
|
||||
Пользователь нажимает <b>"{label || '...'}"</b>
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
<Box ml={20}>
|
||||
<IconArrowRight size={14} style={{ color: 'gray' }} />
|
||||
</Box>
|
||||
|
||||
{/* Шаг 2: Сохранение */}
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon size="sm" color="green" variant="light">
|
||||
<Text size="xs" fw={700}>2</Text>
|
||||
</ThemeIcon>
|
||||
<Text size="xs" style={{ flex: 1 }}>
|
||||
В память сохраняется:{' '}
|
||||
<Code>{dataKey} = "{dataValue}"</Code>
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
<Box ml={20}>
|
||||
<IconArrowRight size={14} style={{ color: 'gray' }} />
|
||||
</Box>
|
||||
|
||||
{/* Шаг 3: Автоматический label */}
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon size="sm" color="cyan" variant="light">
|
||||
<Text size="xs" fw={700}>3</Text>
|
||||
</ThemeIcon>
|
||||
<Text size="xs" style={{ flex: 1 }}>
|
||||
Автоматически добавляется:{' '}
|
||||
<Code>{dataKey}_label = "{label || '...'}"</Code>
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
<Box ml={20}>
|
||||
<IconArrowRight size={14} style={{ color: 'gray' }} />
|
||||
</Box>
|
||||
|
||||
{/* Шаг 4: Использование */}
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon size="sm" color="violet" variant="light">
|
||||
<Text size="xs" fw={700}>4</Text>
|
||||
</ThemeIcon>
|
||||
<Text size="xs" style={{ flex: 1 }}>
|
||||
Эти значения можно использовать в шаблонах темы:
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
<Box ml={36}>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{`В message_template:
|
||||
"{{.${dataKey}}}" → "${dataValue}"
|
||||
"{{.${dataKey}_label}}" → "${label || '...'}"
|
||||
|
||||
В code_template:
|
||||
"{{.${dataKey}}}" → "${dataValue}"`}
|
||||
</Code>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Развёрнутое объяснение */}
|
||||
<Collapse expanded={showDetails}>
|
||||
<Stack gap="md" mt="md">
|
||||
<Divider label="Подробное объяснение" labelPosition="center" />
|
||||
|
||||
{/* Зачем это нужно */}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
🎯 Зачем это нужно?
|
||||
</Text>
|
||||
<Text size="xs" mb="xs">
|
||||
Представьте, что пользователь создаёт заявку "Отпуск на один день за свой счёт".
|
||||
Система должна понять, <b>какую именно тему</b> использовать и <b>как отформатировать
|
||||
сообщение</b> для согласующего. Для этого она собирает "память" пользователя —
|
||||
map <Code>collected</Code>, куда по пути попадают все DataKey/DataValue.
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
{/* Реальный пример */}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
📖 Реальный пример (тема "Отпуск")
|
||||
</Text>
|
||||
<Text size="xs" mb="xs">
|
||||
Пользователь проходит путь: <b>Отпуск → На один день → За свой счёт → Ввод текста</b>
|
||||
</Text>
|
||||
|
||||
<Table withTableBorder withColumnBorders>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Шаг</Table.Th>
|
||||
<Table.Th>Узел (Label)</Table.Th>
|
||||
<Table.Th>DataKey</Table.Th>
|
||||
<Table.Th>DataValue</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
<Table.Tr>
|
||||
<Table.Td>1</Table.Td>
|
||||
<Table.Td>Отпуск</Table.Td>
|
||||
<Table.Td><Code>absence_type</Code></Table.Td>
|
||||
<Table.Td><Code>vacation</Code></Table.Td>
|
||||
</Table.Tr>
|
||||
<Table.Tr>
|
||||
<Table.Td>2</Table.Td>
|
||||
<Table.Td>На один день</Table.Td>
|
||||
<Table.Td><Code>duration_type</Code></Table.Td>
|
||||
<Table.Td><Code>single_day</Code></Table.Td>
|
||||
</Table.Tr>
|
||||
<Table.Tr>
|
||||
<Table.Td>3</Table.Td>
|
||||
<Table.Td>За свой счёт</Table.Td>
|
||||
<Table.Td><Code>payment_type</Code></Table.Td>
|
||||
<Table.Td><Code>own_expense</Code></Table.Td>
|
||||
</Table.Tr>
|
||||
<Table.Tr>
|
||||
<Table.Td>4</Table.Td>
|
||||
<Table.Td>Ввод текста</Table.Td>
|
||||
<Table.Td><Code>content</Code></Table.Td>
|
||||
<Table.Td><i>(текст пользователя)</i></Table.Td>
|
||||
</Table.Tr>
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
|
||||
<Text size="xs" mt="xs" fw={600}>
|
||||
Итоговый collected:
|
||||
</Text>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{`{
|
||||
"absence_type": "vacation",
|
||||
"absence_type_label": "Отпуск", ← автоматически из Label
|
||||
"duration_type": "single_day",
|
||||
"duration_type_label": "На один день", ← автоматически
|
||||
"payment_type": "own_expense",
|
||||
"payment_type_label": "За свой счёт", ← автоматически
|
||||
"content": "22.02.2026"
|
||||
}`}
|
||||
</Code>
|
||||
</Box>
|
||||
|
||||
{/* Как это используется */}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
🔧 Как это используется?
|
||||
</Text>
|
||||
|
||||
<Text size="xs" fw={600} mt="xs" mb={4}>
|
||||
1. Формирование кода темы (code_template):
|
||||
</Text>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{`Шаблон: vacation_{{.duration_type}}_full_day_{{.payment_type}}
|
||||
Результат: vacation_single_day_full_day_own_expense
|
||||
|
||||
Этот код ищет в БД конкретную тему для заявки.`}
|
||||
</Code>
|
||||
|
||||
<Text size="xs" fw={600} mt="xs" mb={4}>
|
||||
2. Сообщение согласующему (message_template):
|
||||
</Text>
|
||||
<Code block style={{ fontSize: 11 }}>
|
||||
{`Шаблон:
|
||||
📋 <b>Тип: Отпуск</b>
|
||||
<b>{{.initiator_name}}</b>: прошу согласовать отпуск
|
||||
{{.content}}
|
||||
<i>{{.payment_type_label}}</i>
|
||||
|
||||
Результат:
|
||||
📋 <b>Тип: Отпуск</b>
|
||||
<b>Иванов И.И.</b>: прошу согласовать отпуск
|
||||
22.02.2026
|
||||
<i>За свой счёт</i>`}
|
||||
</Code>
|
||||
</Box>
|
||||
|
||||
{/* Правила */}
|
||||
<Alert icon={<IconAlertTriangle size={16} />} color="yellow" variant="light">
|
||||
<Text size="xs" fw={600} mb="xs">
|
||||
⚠️ Правила, которые нужно соблюдать:
|
||||
</Text>
|
||||
<Stack gap={4}>
|
||||
<Text size="xs">
|
||||
<b>1. DataKey должен быть осмысленным.</b> Используйте понятные имена:{' '}
|
||||
<Code>region</Code>, <Code>branch</Code>, <Code>payment_type</Code>.
|
||||
Не используйте <Code>x</Code>, <Code>val</Code>, <Code>data</Code>.
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
<b>2. DataValue должен быть уникальным в рамках одного DataKey.</b>{' '}
|
||||
Если у вас есть два узла с <Code>region=crimea</Code> и{' '}
|
||||
<Code>region=krasnodar</Code> — это правильно. Но если оба будут{' '}
|
||||
<Code>region=crimea</Code> — система не сможет их различить.
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
<b>3. Используйте snake_case.</b> Только lowercase, цифры и подчёркивания:{' '}
|
||||
<Code>own_expense</Code> ✅, <Code>OwnExpense</Code> ❌,{' '}
|
||||
<Code>own-expense</Code> ❌.
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
<b>4. Один DataKey на одном уровне дерева.</b> Если на одном уровне
|
||||
несколько кнопок — у всех должен быть одинаковый DataKey, но разные DataValue.
|
||||
Например, три кнопки "Крым/Краснодар/Беларусь" — все с <Code>region</Code>,
|
||||
но с разными значениями.
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
<b>5. Label — это то, что видит пользователь.</b> DataValue — техническое
|
||||
значение. Они могут отличаться: Label="За свой счёт", DataValue="own_expense".
|
||||
</Text>
|
||||
</Stack>
|
||||
</Alert>
|
||||
|
||||
{/* Типичные ошибки */}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
❌ Типичные ошибки:
|
||||
</Text>
|
||||
<Stack gap="xs">
|
||||
<Paper withBorder p="xs" bg="red.0">
|
||||
<Text size="xs">
|
||||
<b>Ошибка:</b> Два узла на одном уровне с одинаковыми DataKey и DataValue
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Последствие: система не сможет различить, какую ветку выбрал пользователь
|
||||
</Text>
|
||||
</Paper>
|
||||
<Paper withBorder p="xs" bg="red.0">
|
||||
<Text size="xs">
|
||||
<b>Ошибка:</b> Разные DataKey на одном уровне (например, у одной кнопки{' '}
|
||||
<Code>region</Code>, у другой <Code>area</Code>)
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Последствие: в collected появятся два разных ключа, что сломает шаблоны
|
||||
</Text>
|
||||
</Paper>
|
||||
<Paper withBorder p="xs" bg="red.0">
|
||||
<Text size="xs">
|
||||
<b>Ошибка:</b> DataValue с пробелами или заглавными буквами
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Последствие: код темы будет некорректным, заявка не создастся
|
||||
</Text>
|
||||
</Paper>
|
||||
<Paper withBorder p="xs" bg="red.0">
|
||||
<Text size="xs">
|
||||
<b>Ошибка:</b> Пустой DataKey или DataValue у кнопки
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
Последствие: данные не сохранятся, шаблон не сможет их использовать
|
||||
</Text>
|
||||
</Paper>
|
||||
</Stack>
|
||||
</Box>
|
||||
|
||||
{/* Правильные примеры */}
|
||||
<Box>
|
||||
<Text size="sm" fw={600} mb="xs">
|
||||
✅ Правильные примеры из реальных тем:
|
||||
</Text>
|
||||
<Table withTableBorder withColumnBorders>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>Label</Table.Th>
|
||||
<Table.Th>DataKey</Table.Th>
|
||||
<Table.Th>DataValue</Table.Th>
|
||||
<Table.Th>Комментарий</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
<Table.Tbody>
|
||||
{examples.map((ex, i) => (
|
||||
<Table.Tr key={i}>
|
||||
<Table.Td>{ex.label}</Table.Td>
|
||||
<Table.Td><Code>{ex.dataKey}</Code></Table.Td>
|
||||
<Table.Td><Code>{ex.dataValue}</Code></Table.Td>
|
||||
<Table.Td>{ex.description}</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Box>
|
||||
|
||||
{/* Подсказка по текущему узлу */}
|
||||
{dataKey && dataValue && label && (
|
||||
<Alert
|
||||
icon={<IconCheck size={16} />}
|
||||
color={isDuplicateKey ? 'blue' : 'green'}
|
||||
variant="light"
|
||||
>
|
||||
<Text size="xs">
|
||||
{isDuplicateKey ? (
|
||||
<>
|
||||
💡 Ваш узел похож на существующий пример. Убедитесь, что это именно то,
|
||||
что вам нужно.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
✅ Отлично! Ваш узел <b>"{label}"</b> с{' '}
|
||||
<Code>{dataKey}="{dataValue}"</Code> выглядит корректно.
|
||||
В шаблонах можно использовать <Code>{`{{.${dataKey}}}`}</Code> и{' '}
|
||||
<Code>{`{{.${dataKey}_label}}`}</Code>.
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Collapse>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,517 @@
|
|||
import { useEffect, useMemo } from 'react'
|
||||
import {
|
||||
Modal,
|
||||
Stack,
|
||||
TextInput,
|
||||
Textarea,
|
||||
Switch,
|
||||
Group,
|
||||
Button,
|
||||
Text,
|
||||
Loader,
|
||||
Center,
|
||||
Badge,
|
||||
Paper,
|
||||
Select,
|
||||
Code,
|
||||
Alert,
|
||||
Tooltip,
|
||||
Box,
|
||||
} from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { useCreateFlowNode, useUpdateFlowNode } from '@/features/flowNodes/hooks/useFlowNodes'
|
||||
import { useFlowNodesTree } from '@/features/flowNodes/hooks/useFlowNodes'
|
||||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
import { IconAlertCircle, IconInfoCircle } from '@tabler/icons-react'
|
||||
|
||||
interface FlowNodeEditModalProps {
|
||||
topicId: number
|
||||
parentNode: ApprovalFlowNode | null
|
||||
editNode: ApprovalFlowNode | null
|
||||
opened: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const NODE_TYPE_OPTIONS = [
|
||||
{ value: 'button', label: '🔘 Кнопка — пользователь нажимает и переходит дальше' },
|
||||
{ value: 'input', label: '📝 Текстовый ввод — пользователь вводит текст' },
|
||||
{ value: 'multiselect', label: '☑️ Мультиселект — пользователь выбирает несколько вариантов' },
|
||||
]
|
||||
|
||||
// Утилиты для генерации ключей
|
||||
// Таблица транслитерации
|
||||
const TRANSLIT_MAP: Record<string, string> = {
|
||||
'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo',
|
||||
'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm',
|
||||
'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',
|
||||
'ф': 'f', 'х': 'h', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'sch',
|
||||
'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu', 'я': 'ya',
|
||||
}
|
||||
|
||||
const transliterate = (text: string): string => {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.split('')
|
||||
.map(char => TRANSLIT_MAP[char] ?? char)
|
||||
.join('')
|
||||
}
|
||||
|
||||
const generateKeyFromLabel = (label: string): string => {
|
||||
if (!label || label.trim() === '') return ''
|
||||
|
||||
const transliterated = transliterate(label.trim().toLowerCase())
|
||||
|
||||
return transliterated
|
||||
.replace(/[\s\-]+/g, '_')
|
||||
.replace(/[^a-z0-9_]/g, '')
|
||||
.replace(/_+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
.substring(0, 50)
|
||||
}
|
||||
|
||||
export default function FlowNodeEditModal({
|
||||
topicId,
|
||||
parentNode,
|
||||
editNode,
|
||||
opened,
|
||||
onClose,
|
||||
}: FlowNodeEditModalProps) {
|
||||
const createFlowNode = useCreateFlowNode()
|
||||
const updateFlowNode = useUpdateFlowNode()
|
||||
const { data: treeData } = useFlowNodesTree(topicId)
|
||||
const tree = treeData?.data || []
|
||||
|
||||
const isEditMode = editNode !== null
|
||||
|
||||
const form = useForm({
|
||||
initialValues: {
|
||||
key: '',
|
||||
label: '',
|
||||
nodeType: 'button' as 'button' | 'input' | 'multiselect',
|
||||
data_key: '',
|
||||
data_value: '',
|
||||
input_key: 'content',
|
||||
input_hint: '',
|
||||
multi_select_key: '',
|
||||
multi_select_value: '',
|
||||
topic_code: '',
|
||||
auto_generate_key: true,
|
||||
},
|
||||
validate: {
|
||||
key: (v: string | any[]) => {
|
||||
if (!v || v.length < 2) return 'Ключ должен содержать минимум 2 символа'
|
||||
if (!/^[a-z0-9_]+$/.test(v as string)) return 'Только lowercase буквы, цифры и подчеркивания'
|
||||
|
||||
// Проверка уникальности ключа
|
||||
const existingKeys = collectAllKeys(tree)
|
||||
if (existingKeys.includes(v as string) && (!editNode || editNode.key !== v)) {
|
||||
return 'Ключ уже используется в этой теме'
|
||||
}
|
||||
return null
|
||||
},
|
||||
label: (v: string | any[]) => (!v || v.length < 1 ? 'Название обязательно' : null),
|
||||
data_key: (v: string | any[], values: { nodeType: string }) => {
|
||||
if (values.nodeType === 'button' || values.nodeType === 'input') {
|
||||
if (!v || v.length < 1) return 'DataKey обязателен для кнопок и ввода'
|
||||
}
|
||||
return null
|
||||
},
|
||||
data_value: (v: string | any[], values: { nodeType: string }) => {
|
||||
if (values.nodeType === 'button' || values.nodeType === 'input') {
|
||||
if (!v || v.length < 1) return 'DataValue обязателен для кнопок и ввода'
|
||||
}
|
||||
return null
|
||||
},
|
||||
input_hint: (v: string | any[], values: { nodeType: string }) => {
|
||||
if (values.nodeType === 'input' && (!v || v.length < 5)) {
|
||||
return 'Подсказка должна содержать минимум 5 символов'
|
||||
}
|
||||
return null
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Автоматическая генерация ключа из label
|
||||
useEffect(() => {
|
||||
if (form.values.auto_generate_key && form.values.label) {
|
||||
const generatedKey = generateKeyFromLabel(form.values.label)
|
||||
const parentPrefix = parentNode?.key ? `${parentNode.key}_` : ''
|
||||
form.setFieldValue('key', parentPrefix + generatedKey)
|
||||
}
|
||||
}, [form.values.label, form.values.auto_generate_key, parentNode])
|
||||
|
||||
// Автоматическое заполнение полей при смене типа узла
|
||||
useEffect(() => {
|
||||
const nodeType = form.values.nodeType
|
||||
|
||||
if (nodeType === 'button') {
|
||||
// Для кнопки — типичные значения
|
||||
if (!form.values.data_key) {
|
||||
form.setFieldValue('data_key', 'type')
|
||||
}
|
||||
if (!form.values.data_value) {
|
||||
form.setFieldValue('data_value', generateKeyFromLabel(form.values.label))
|
||||
}
|
||||
} else if (nodeType === 'input') {
|
||||
// Для ввода — стандартные значения
|
||||
form.setFieldValue('data_key', '')
|
||||
form.setFieldValue('data_value', '')
|
||||
form.setFieldValue('input_key', 'content')
|
||||
} else if (nodeType === 'multiselect') {
|
||||
// Для мультиселекта — типичные значения
|
||||
if (!form.values.multi_select_key) {
|
||||
form.setFieldValue('multi_select_key', 'options')
|
||||
}
|
||||
if (!form.values.multi_select_value) {
|
||||
form.setFieldValue('multi_select_value', generateKeyFromLabel(form.values.label))
|
||||
}
|
||||
}
|
||||
}, [form.values.nodeType])
|
||||
|
||||
// Заполнение формы при редактировании
|
||||
useEffect(() => {
|
||||
if (editNode) {
|
||||
let nodeType: 'button' | 'input' | 'multiselect' = 'button'
|
||||
if (editNode.is_input) nodeType = 'input'
|
||||
else if (editNode.is_multi_select) nodeType = 'multiselect'
|
||||
|
||||
form.setValues({
|
||||
key: editNode.key || '',
|
||||
label: editNode.label || '',
|
||||
nodeType,
|
||||
data_key: editNode.data_key || '',
|
||||
data_value: editNode.data_value || '',
|
||||
input_key: editNode.input_key || 'content',
|
||||
input_hint: editNode.input_hint || '',
|
||||
multi_select_key: editNode.multi_select_key || '',
|
||||
multi_select_value: editNode.multi_select_value || '',
|
||||
topic_code: editNode.topic_code || '',
|
||||
auto_generate_key: false, // При редактировании не генерируем автоматически
|
||||
})
|
||||
} else {
|
||||
form.reset()
|
||||
const baseKey = parentNode?.key || ''
|
||||
form.setValues({
|
||||
key: baseKey ? `${baseKey}_new` : 'new_node',
|
||||
label: '',
|
||||
nodeType: 'button',
|
||||
data_key: '',
|
||||
data_value: '',
|
||||
input_key: 'content',
|
||||
input_hint: '',
|
||||
multi_select_key: '',
|
||||
multi_select_value: '',
|
||||
topic_code: '',
|
||||
auto_generate_key: true,
|
||||
})
|
||||
}
|
||||
}, [editNode, parentNode, opened])
|
||||
|
||||
const handleSubmit = async (values: typeof form.values) => {
|
||||
const payload = {
|
||||
key: values.key,
|
||||
label: values.label,
|
||||
data_key: values.data_key || null,
|
||||
data_value: values.data_value || null,
|
||||
is_input: values.nodeType === 'input',
|
||||
input_key: values.nodeType === 'input' ? values.input_key : null,
|
||||
input_hint: values.nodeType === 'input' ? values.input_hint : null,
|
||||
is_multi_select: values.nodeType === 'multiselect',
|
||||
multi_select_key: values.nodeType === 'multiselect' ? values.multi_select_key : null,
|
||||
multi_select_value: values.nodeType === 'multiselect' ? values.multi_select_value : null,
|
||||
topic_code: values.topic_code || null,
|
||||
}
|
||||
|
||||
if (isEditMode && editNode?.id) {
|
||||
await updateFlowNode.mutateAsync({ id: editNode.id, ...payload })
|
||||
} else {
|
||||
await createFlowNode.mutateAsync({
|
||||
topic_id: topicId,
|
||||
parent_id: parentNode?.id || null,
|
||||
...payload,
|
||||
})
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
const isSubmitting = createFlowNode.isPending || updateFlowNode.isPending
|
||||
const nodeType = form.values.nodeType
|
||||
|
||||
// Предупреждения
|
||||
const warnings = useMemo(() => {
|
||||
const warns: string[] = []
|
||||
|
||||
if (nodeType === 'button' && !form.values.data_key) {
|
||||
warns.push('Для кнопки необходимо указать DataKey — ключ, куда сохранится значение')
|
||||
}
|
||||
if (nodeType === 'button' && !form.values.data_value) {
|
||||
warns.push('Для кнопки необходимо указать DataValue — значение, которое сохранится')
|
||||
}
|
||||
if (nodeType === 'input' && !form.values.input_hint) {
|
||||
warns.push('Рекомендуется добавить подсказку (InputHint) для пользователя')
|
||||
}
|
||||
if (nodeType === 'multiselect' && !form.values.multi_select_key) {
|
||||
warns.push('Для мультиселекта необходимо указать MultiSelectKey')
|
||||
}
|
||||
|
||||
return warns
|
||||
}, [nodeType, form.values])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={
|
||||
<Group>
|
||||
<Text fw={700}>
|
||||
{isEditMode ? 'Редактирование узла' : 'Новый узел'}
|
||||
</Text>
|
||||
{editNode && <Badge variant="light">ID: {editNode.id}</Badge>}
|
||||
{parentNode && (
|
||||
<Badge variant="light" color="gray">
|
||||
родитель: {parentNode.label}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
size="lg"
|
||||
>
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack gap="md">
|
||||
{/* Предупреждения */}
|
||||
{warnings.length > 0 && (
|
||||
<Alert icon={<IconAlertCircle size={16} />} color="yellow" variant="light">
|
||||
<Stack gap={4}>
|
||||
{warnings.map((w, i) => (
|
||||
<Text key={i} size="sm">
|
||||
⚠️ {w}
|
||||
</Text>
|
||||
))}
|
||||
</Stack>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Тип узла */}
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
1. Выберите тип узла
|
||||
</Text>
|
||||
<Select
|
||||
data={NODE_TYPE_OPTIONS}
|
||||
value={form.values.nodeType}
|
||||
onChange={(v) => form.setFieldValue('nodeType', (v as any) || 'button')}
|
||||
description="Тип узла определяет, как пользователь будет взаимодействовать с этим элементом"
|
||||
/>
|
||||
</Paper>
|
||||
|
||||
{/* Основные поля */}
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
2. Основные поля
|
||||
</Text>
|
||||
<Stack gap="sm">
|
||||
<TextInput
|
||||
label="Название (Label)"
|
||||
placeholder="Крым, ТМЦ, В счёт отпуска..."
|
||||
description="Текст, который увидит пользователь на кнопке"
|
||||
required
|
||||
{...form.getInputProps('label')}
|
||||
/>
|
||||
|
||||
<Group align="end" gap="sm">
|
||||
<TextInput
|
||||
label="Ключ (Key)"
|
||||
placeholder="crimea, f1_tmc..."
|
||||
description="Уникальный идентификатор узла в рамках темы (только lowercase, цифры, подчеркивания)"
|
||||
required
|
||||
style={{ flex: 1 }}
|
||||
disabled={form.values.auto_generate_key}
|
||||
{...form.getInputProps('key')}
|
||||
/>
|
||||
<Tooltip label={form.values.auto_generate_key ? 'Автогенерация включена' : 'Автогенерация выключена'}>
|
||||
<Switch
|
||||
label="Авто"
|
||||
checked={form.values.auto_generate_key}
|
||||
onChange={(e) => form.setFieldValue('auto_generate_key', e.currentTarget.checked)}
|
||||
mb={5}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
|
||||
{form.values.auto_generate_key && (
|
||||
<Text size="xs" c="dimmed">
|
||||
💡 Ключ генерируется автоматически из названия. Можно отключить и ввести вручную.
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
label="Код темы для проверки прав (опционально)"
|
||||
placeholder="non_budget_f1"
|
||||
description={
|
||||
<Text size="xs">
|
||||
Если задан — кнопка видна только пользователям с правом <Code>create</Code> на эту тему.
|
||||
Оставьте пустым, если кнопка должна быть видна всем.
|
||||
</Text>
|
||||
}
|
||||
{...form.getInputProps('topic_code')}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
{/* DataKey/DataValue — для кнопок и input */}
|
||||
{(nodeType === 'button' || nodeType === 'input') && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
3. Сохранение данных
|
||||
</Text>
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mb="sm">
|
||||
<Text size="xs">
|
||||
Когда пользователь выберет этот узел, система сохранит значение в формате:{' '}
|
||||
<Code>{form.values.data_key || 'key'} = {form.values.data_value || 'value'}</Code>
|
||||
</Text>
|
||||
</Alert>
|
||||
<Group gap="sm" align="end">
|
||||
<TextInput
|
||||
label="DataKey (ключ)"
|
||||
placeholder="region, branch, payment_type..."
|
||||
description="Имя переменной, куда сохранится значение"
|
||||
required={nodeType === 'button'}
|
||||
style={{ flex: 1 }}
|
||||
{...form.getInputProps('data_key')}
|
||||
/>
|
||||
<TextInput
|
||||
label="DataValue (значение)"
|
||||
placeholder="crimea, f1, own_expense..."
|
||||
description="Значение, которое сохранится"
|
||||
required={nodeType === 'button'}
|
||||
style={{ flex: 1 }}
|
||||
{...form.getInputProps('data_value')}
|
||||
/>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
💡 <b>Примеры:</b> region=crimea, branch=f1, payment_type=own_expense
|
||||
</Text>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Поля для input */}
|
||||
{nodeType === 'input' && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
3. Настройки текстового ввода
|
||||
</Text>
|
||||
<Stack gap="sm">
|
||||
<TextInput
|
||||
label="InputKey (ключ для сохранения текста)"
|
||||
placeholder="content"
|
||||
description="Ключ, куда сохранится введённый пользователем текст"
|
||||
required
|
||||
{...form.getInputProps('input_key')}
|
||||
/>
|
||||
<Textarea
|
||||
label="InputHint (подсказка для пользователя)"
|
||||
placeholder="Опишите изменения: текущие данные → новые данные"
|
||||
description="Шаблон или пример, который увидит пользователь при вводе текста"
|
||||
minRows={3}
|
||||
required
|
||||
{...form.getInputProps('input_hint')}
|
||||
/>
|
||||
<Text size="xs" c="dimmed">
|
||||
💡 Подсказка помогает пользователю понять, что именно нужно ввести
|
||||
</Text>
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Поля для multiselect */}
|
||||
{nodeType === 'multiselect' && (
|
||||
<Paper withBorder p="md">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
3. Настройки мультиселекта
|
||||
</Text>
|
||||
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light" mb="sm">
|
||||
<Text size="xs">
|
||||
Мультиселект позволяет пользователю выбрать несколько вариантов.
|
||||
Все выбранные значения сохранятся через запятую в указанный ключ.
|
||||
</Text>
|
||||
</Alert>
|
||||
<Group gap="sm" align="end">
|
||||
<TextInput
|
||||
label="MultiSelectKey (ключ)"
|
||||
placeholder="systems, options..."
|
||||
description="Ключ, куда сохранятся все выбранные значения (через запятую)"
|
||||
required
|
||||
style={{ flex: 1 }}
|
||||
{...form.getInputProps('multi_select_key')}
|
||||
/>
|
||||
<TextInput
|
||||
label="MultiSelectValue (значение этого варианта)"
|
||||
placeholder="okb, option1..."
|
||||
description="Значение именно этого варианта мультиселекта"
|
||||
required
|
||||
style={{ flex: 1 }}
|
||||
{...form.getInputProps('multi_select_value')}
|
||||
/>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
💡 <b>Пример:</b> Если пользователь выберет "ОКБ" и "1С", то сохранится:{' '}
|
||||
<Code>systems = okb,1c</Code>
|
||||
</Text>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{/* Превью */}
|
||||
<Paper withBorder p="md" bg="gray.0">
|
||||
<Text size="sm" fw={600} mb="sm">
|
||||
Превью для пользователя
|
||||
</Text>
|
||||
<Box>
|
||||
<Text size="sm" c="dimmed">
|
||||
Пользователь увидит:
|
||||
</Text>
|
||||
<Text fw={500} size="lg" mt="xs">
|
||||
{form.values.label || 'Название узла'}
|
||||
</Text>
|
||||
{nodeType === 'input' && form.values.input_hint && (
|
||||
<Text size="sm" c="dimmed" mt="xs">
|
||||
💬 Подсказка: {form.values.input_hint}
|
||||
</Text>
|
||||
)}
|
||||
{(nodeType === 'button' || nodeType === 'input') && form.values.data_key && (
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
Сохранится: <Code>{form.values.data_key} = {form.values.data_value}</Code>
|
||||
</Text>
|
||||
)}
|
||||
{nodeType === 'multiselect' && form.values.multi_select_key && (
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
Сохранится: <Code>{form.values.multi_select_key} = ..., {form.values.multi_select_value}, ...</Code>
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={onClose} disabled={isSubmitting}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{isEditMode ? 'Сохранить' : 'Создать'}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// Утилитарная функция для сбора всех ключей из дерева
|
||||
function collectAllKeys(nodes: ApprovalFlowNode[]): string[] {
|
||||
const keys: string[] = []
|
||||
for (const node of nodes) {
|
||||
if (node.key) keys.push(node.key)
|
||||
if (node.children) {
|
||||
keys.push(...collectAllKeys(node.children))
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
|
@ -0,0 +1,227 @@
|
|||
import {
|
||||
Group,
|
||||
Text,
|
||||
ActionIcon,
|
||||
Badge,
|
||||
Paper,
|
||||
Stack,
|
||||
Tooltip,
|
||||
Box,
|
||||
Code,
|
||||
Collapse,
|
||||
} from '@mantine/core'
|
||||
import {
|
||||
IconPencil,
|
||||
IconTrash,
|
||||
IconCopy,
|
||||
IconPlus,
|
||||
IconChevronRight,
|
||||
IconChevronDown,
|
||||
IconArrowUp,
|
||||
IconArrowDown,
|
||||
IconKeyboard,
|
||||
IconCheckbox,
|
||||
IconHierarchy,
|
||||
} from '@tabler/icons-react'
|
||||
import { useState } from 'react'
|
||||
import type { ApprovalFlowNode } from '@/types/api'
|
||||
|
||||
interface FlowTreeNodeProps {
|
||||
node: ApprovalFlowNode
|
||||
depth: number
|
||||
siblings: ApprovalFlowNode[]
|
||||
onEdit: (node: ApprovalFlowNode) => void
|
||||
onAddChild: (parent: ApprovalFlowNode) => void
|
||||
onDelete: (node: ApprovalFlowNode) => void
|
||||
onDuplicate: (node: ApprovalFlowNode) => void
|
||||
onMoveUp: (node: ApprovalFlowNode) => void
|
||||
onMoveDown: (node: ApprovalFlowNode) => void
|
||||
index: number
|
||||
}
|
||||
|
||||
export default function FlowTreeNode({
|
||||
node,
|
||||
depth,
|
||||
siblings,
|
||||
onEdit,
|
||||
onAddChild,
|
||||
onDelete,
|
||||
onDuplicate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
index,
|
||||
}: FlowTreeNodeProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(true)
|
||||
const hasChildren = node.children && node.children.length > 0
|
||||
|
||||
// Определяем тип узла для иконки
|
||||
let typeIcon = <IconHierarchy size={14} />
|
||||
let typeColor = 'blue'
|
||||
let typeLabel = 'Кнопка'
|
||||
|
||||
if (node.is_input) {
|
||||
typeIcon = <IconKeyboard size={14} />
|
||||
typeColor = 'orange'
|
||||
typeLabel = 'Ввод'
|
||||
} else if (node.is_multi_select) {
|
||||
typeIcon = <IconCheckbox size={14} />
|
||||
typeColor = 'violet'
|
||||
typeLabel = 'Мульти'
|
||||
}
|
||||
|
||||
return (
|
||||
<Box style={{ marginLeft: depth * 24 }}>
|
||||
<Paper
|
||||
withBorder
|
||||
p="xs"
|
||||
style={{
|
||||
backgroundColor: depth === 0 ? 'var(--mantine-color-blue-0)' : undefined,
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap="xs" wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
||||
{/* Раскрывалка */}
|
||||
{hasChildren ? (
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
{isExpanded ? <IconChevronDown size={16} /> : <IconChevronRight size={16} />}
|
||||
</ActionIcon>
|
||||
) : (
|
||||
<Box w={24} />
|
||||
)}
|
||||
|
||||
{/* Иконка типа */}
|
||||
<Tooltip label={typeLabel}>
|
||||
<Badge size="xs" variant="light" color={typeColor} leftSection={typeIcon}>
|
||||
{typeLabel}
|
||||
</Badge>
|
||||
</Tooltip>
|
||||
|
||||
{/* Название */}
|
||||
<Text fw={500} size="sm" lineClamp={1} title={node.label}>
|
||||
{node.label}
|
||||
</Text>
|
||||
|
||||
{/* Техническая информация */}
|
||||
<Code style={{ fontSize: 11 }}>{node.key}</Code>
|
||||
|
||||
{/* DataKey/DataValue */}
|
||||
{node.data_key && node.data_value && (
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{node.data_key}={node.data_value}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{/* Topic code */}
|
||||
{node.topic_code && (
|
||||
<Badge size="xs" variant="dot" color="red">
|
||||
🔒 {node.topic_code}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
{/* Действия */}
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Tooltip label="Переместить вверх">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
color="gray"
|
||||
onClick={() => onMoveUp(node)}
|
||||
disabled={index === 0}
|
||||
>
|
||||
<IconArrowUp size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Переместить вниз">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
color="gray"
|
||||
onClick={() => onMoveDown(node)}
|
||||
disabled={index === siblings.length - 1}
|
||||
>
|
||||
<IconArrowDown size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Добавить дочерний">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="green"
|
||||
size="sm"
|
||||
onClick={() => onAddChild(node)}
|
||||
>
|
||||
<IconPlus size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Редактировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="blue"
|
||||
size="sm"
|
||||
onClick={() => onEdit(node)}
|
||||
>
|
||||
<IconPencil size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Дублировать">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="violet"
|
||||
size="sm"
|
||||
onClick={() => onDuplicate(node)}
|
||||
>
|
||||
<IconCopy size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Tooltip label="Удалить (с детьми)">
|
||||
<ActionIcon
|
||||
variant="light"
|
||||
color="red"
|
||||
size="sm"
|
||||
onClick={() => onDelete(node)}
|
||||
>
|
||||
<IconTrash size={14} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
{/* Input hint preview */}
|
||||
{node.is_input && node.input_hint && (
|
||||
<Box ml={32} mt={4}>
|
||||
<Text size="xs" c="dimmed" lineClamp={2}>
|
||||
💬 {node.input_hint}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
|
||||
{/* Дети */}
|
||||
{hasChildren && (
|
||||
<Collapse expanded={isExpanded}>
|
||||
<Stack gap={4} mt={4}>
|
||||
{node.children!.map((child, idx) => (
|
||||
<FlowTreeNode
|
||||
key={child.id}
|
||||
node={child}
|
||||
depth={depth + 1}
|
||||
siblings={node.children!}
|
||||
onEdit={onEdit}
|
||||
onAddChild={onAddChild}
|
||||
onDelete={onDelete}
|
||||
onDuplicate={onDuplicate}
|
||||
onMoveUp={onMoveUp}
|
||||
onMoveDown={onMoveDown}
|
||||
index={idx}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</Collapse>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
|
@ -191,7 +191,7 @@ export default function HierarchyEditModal({
|
|||
<Stack gap="md">
|
||||
{/* Подчинённый */}
|
||||
<Select
|
||||
label="Подчинённый (инициатор)"
|
||||
label="Сотрудник (инициатор)"
|
||||
placeholder="Выберите пользователя"
|
||||
data={userOptions}
|
||||
value={form.values.subordinate_id ? String(form.values.subordinate_id) : null}
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ export default function TopicEditModal({
|
|||
requires_file: false,
|
||||
require_observer_selection: false,
|
||||
instructions: '',
|
||||
is_tree_root: false,
|
||||
},
|
||||
validate: {
|
||||
category_id: (v) => (v === null ? 'Выберите категорию' : null),
|
||||
|
|
@ -290,6 +291,13 @@ export default function TopicEditModal({
|
|||
checked={form.values.require_approver_comment}
|
||||
onChange={(e) => form.setFieldValue('require_approver_comment', e.currentTarget.checked)}
|
||||
/>
|
||||
|
||||
<Switch
|
||||
label="Имеет дерево навигации"
|
||||
description="У этой темы будет дерево кнопок для навигации"
|
||||
checked={form.values.is_tree_root}
|
||||
onChange={(e) => form.setFieldValue('is_tree_root', e.currentTarget.checked)}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
|
|
|
|||
|
|
@ -222,7 +222,10 @@ export interface ApprovalTopic {
|
|||
instructions?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
message_template?: string | null
|
||||
code_template?: string | null
|
||||
category?: ApprovalTopicCategory
|
||||
is_tree_root?: boolean
|
||||
}
|
||||
|
||||
export interface Admin {
|
||||
|
|
@ -262,4 +265,25 @@ export interface ApprovalTask {
|
|||
approval?: Approval
|
||||
executor?: User
|
||||
files?: ApprovalFile[]
|
||||
}
|
||||
|
||||
export interface ApprovalFlowNode {
|
||||
id?: number
|
||||
topic_id?: number
|
||||
parent_id?: number | null
|
||||
key: string
|
||||
label: string
|
||||
data_key?: string | null
|
||||
data_value?: string | null
|
||||
is_input?: boolean
|
||||
input_key?: string | null
|
||||
input_hint?: string | null
|
||||
is_multi_select?: boolean
|
||||
multi_select_key?: string | null
|
||||
multi_select_value?: string | null
|
||||
topic_code?: string | null
|
||||
sort_order?: number
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
children?: ApprovalFlowNode[]
|
||||
}
|
||||
Loading…
Reference in New Issue