Upodate flow nodes page
Deploy Frontend / build-and-deploy (push) Successful in 39s
Details
Deploy Frontend / build-and-deploy (push) Successful in 39s
Details
This commit is contained in:
parent
8a95692122
commit
262c6d930f
|
|
@ -2,7 +2,7 @@ import apiClient from './client'
|
||||||
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
import type { ApprovalFlowNode, ApiResponse } from '@/types/api'
|
||||||
|
|
||||||
export interface CreateFlowNodeRequest {
|
export interface CreateFlowNodeRequest {
|
||||||
topic_id: number
|
category_id: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key: string
|
key: string
|
||||||
label: string
|
label: string
|
||||||
|
|
@ -15,12 +15,14 @@ export interface CreateFlowNodeRequest {
|
||||||
multi_select_key?: string | null
|
multi_select_key?: string | null
|
||||||
multi_select_value?: string | null
|
multi_select_value?: string | null
|
||||||
topic_code?: string | null
|
topic_code?: string | null
|
||||||
|
message_template?: string | null
|
||||||
|
code_template?: string | null
|
||||||
sort_order?: number
|
sort_order?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateFlowNodeRequest {
|
export interface UpdateFlowNodeRequest {
|
||||||
id: number
|
id: number
|
||||||
topic_id?: number
|
category_id?: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key?: string
|
key?: string
|
||||||
label?: string
|
label?: string
|
||||||
|
|
@ -33,6 +35,8 @@ export interface UpdateFlowNodeRequest {
|
||||||
multi_select_key?: string | null
|
multi_select_key?: string | null
|
||||||
multi_select_value?: string | null
|
multi_select_value?: string | null
|
||||||
topic_code?: string | null
|
topic_code?: string | null
|
||||||
|
message_template?: string | null
|
||||||
|
code_template?: string | null
|
||||||
sort_order?: number
|
sort_order?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,8 +50,8 @@ export interface SaveTreeRequest {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const flowNodesApi = {
|
export const flowNodesApi = {
|
||||||
getTree: (topicId: number) =>
|
getTree: (categoryId: number) =>
|
||||||
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/topic/${topicId}`),
|
apiClient.get<ApiResponse<ApprovalFlowNode[]>>(`/flow-nodes/category/${categoryId}`),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
apiClient.get<ApprovalFlowNode>(`/flow-nodes/${id}`),
|
||||||
|
|
@ -61,8 +65,8 @@ export const flowNodesApi = {
|
||||||
delete: (id: number) =>
|
delete: (id: number) =>
|
||||||
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
apiClient.delete<boolean>('/flow-nodes/', { data: { id } }),
|
||||||
|
|
||||||
saveTree: (topicId: number, data: SaveTreeRequest) =>
|
saveTree: (categoryId: number, data: SaveTreeRequest) =>
|
||||||
apiClient.post<boolean>(`/flow-nodes/topic/${topicId}/tree`, data),
|
apiClient.post<boolean>(`/flow-nodes/category/${categoryId}/tree`, data),
|
||||||
|
|
||||||
move: (id: number, data: MoveFlowNodeRequest) =>
|
move: (id: number, data: MoveFlowNodeRequest) =>
|
||||||
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
apiClient.post<ApprovalFlowNode>(`/flow-nodes/${id}/move`, data),
|
||||||
|
|
|
||||||
|
|
@ -10,15 +10,15 @@ import { notifications } from '@mantine/notifications'
|
||||||
|
|
||||||
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
|
||||||
|
|
||||||
export function useFlowNodesTree(topicId: number | null) {
|
export function useFlowNodesTree(categoryId: number | null) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: [FLOW_NODES_QUERY_KEY, topicId],
|
queryKey: [FLOW_NODES_QUERY_KEY, categoryId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
if (!topicId) return null
|
if (!categoryId) return null
|
||||||
const response = await flowNodesApi.getTree(topicId)
|
const response = await flowNodesApi.getTree(categoryId)
|
||||||
return response.data
|
return response.data
|
||||||
},
|
},
|
||||||
enabled: !!topicId,
|
enabled: !!categoryId,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -95,8 +95,8 @@ export function useSaveFlowTree() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ topicId, data }: { topicId: number; data: SaveTreeRequest }) =>
|
mutationFn: ({ categoryId, data }: { categoryId: number; data: SaveTreeRequest }) =>
|
||||||
flowNodesApi.saveTree(topicId, data),
|
flowNodesApi.saveTree(categoryId, data),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] })
|
||||||
notifications.show({
|
notifications.show({
|
||||||
|
|
|
||||||
|
|
@ -8,26 +8,19 @@ import {
|
||||||
Loader,
|
Loader,
|
||||||
Center,
|
Center,
|
||||||
Stack,
|
Stack,
|
||||||
Box,
|
|
||||||
Badge,
|
Badge,
|
||||||
Textarea,
|
|
||||||
Code,
|
|
||||||
Divider,
|
|
||||||
Alert,
|
Alert,
|
||||||
Collapse,
|
|
||||||
ActionIcon,
|
ActionIcon,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import {
|
import {
|
||||||
IconPlus,
|
IconPlus,
|
||||||
IconDeviceFloppy,
|
|
||||||
IconRefresh,
|
IconRefresh,
|
||||||
IconChevronDown,
|
IconInfoCircle,
|
||||||
IconChevronRight,
|
IconBook,
|
||||||
IconInfoCircle, IconBook,
|
|
||||||
} from '@tabler/icons-react'
|
} from '@tabler/icons-react'
|
||||||
import { modals } from '@mantine/modals'
|
import { modals } from '@mantine/modals'
|
||||||
import { useTopics } from '@/features/topics/hooks/useTopics'
|
import { useCategories } from '@/features/categories/hooks/useCategories'
|
||||||
import {
|
import {
|
||||||
useFlowNodesTree,
|
useFlowNodesTree,
|
||||||
useDeleteFlowNode,
|
useDeleteFlowNode,
|
||||||
|
|
@ -35,17 +28,19 @@ import {
|
||||||
useMoveFlowNode,
|
useMoveFlowNode,
|
||||||
useDuplicateFlowNode,
|
useDuplicateFlowNode,
|
||||||
} from '@/features/flowNodes/hooks/useFlowNodes'
|
} from '@/features/flowNodes/hooks/useFlowNodes'
|
||||||
import { useUpdateTopic } from '@/features/topics/hooks/useTopics'
|
|
||||||
import FlowTreeNode from './components/FlowTreeNode'
|
import FlowTreeNode from './components/FlowTreeNode'
|
||||||
import FlowNodeEditModal from './components/FlowNodeEditModal'
|
import FlowNodeEditModal from './components/FlowNodeEditModal'
|
||||||
import type { ApprovalFlowNode, ApprovalTopic } from '@/types/api'
|
import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
|
||||||
export default function FlowTreePage() {
|
export default function FlowTreePage() {
|
||||||
const [selectedTopicId, setSelectedTopicId] = useState<number | null>(null)
|
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null)
|
||||||
const [showTemplates, setShowTemplates] = useState(false)
|
|
||||||
|
|
||||||
// Модалка редактирования узла
|
// Модалка редактирования узла.
|
||||||
|
// Шаблоны сообщения/кода для темы (message_template / code_template)
|
||||||
|
// редактируются здесь же, как поля узла — в БД они хранятся на
|
||||||
|
// ApprovalFlowNode (обычно на терминальном узле, где также заполнен
|
||||||
|
// topic_code), а не на ApprovalTopic.
|
||||||
const [editModal, setEditModal] = useState<{
|
const [editModal, setEditModal] = useState<{
|
||||||
opened: boolean
|
opened: boolean
|
||||||
parentNode: ApprovalFlowNode | null
|
parentNode: ApprovalFlowNode | null
|
||||||
|
|
@ -56,33 +51,34 @@ export default function FlowTreePage() {
|
||||||
editNode: null,
|
editNode: null,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Загружаем все темы
|
// Загружаем все активные категории — именно категория является
|
||||||
const { data: topicsData } = useTopics({
|
// единицей дерева навигации (Registry строит Topic-интерфейс на
|
||||||
|
// основе категории + узлов дерева, привязанных к category_id)
|
||||||
|
const { data: categoriesData } = useCategories({
|
||||||
limit: 1000,
|
limit: 1000,
|
||||||
is_tree_root: true
|
is_active: true,
|
||||||
})
|
})
|
||||||
const topics = topicsData?.data || []
|
const categories = categoriesData?.data || []
|
||||||
|
|
||||||
// Загружаем дерево для выбранной темы
|
// Загружаем дерево для выбранной категории
|
||||||
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedTopicId)
|
const { data: treeData, isLoading: treeLoading } = useFlowNodesTree(selectedCategoryId)
|
||||||
const tree = treeData?.data || []
|
const tree = treeData?.data || []
|
||||||
|
|
||||||
const deleteFlowNode = useDeleteFlowNode()
|
const deleteFlowNode = useDeleteFlowNode()
|
||||||
const saveTree = useSaveFlowTree()
|
const saveTree = useSaveFlowTree()
|
||||||
const moveFlowNode = useMoveFlowNode()
|
const moveFlowNode = useMoveFlowNode()
|
||||||
const duplicateFlowNode = useDuplicateFlowNode()
|
const duplicateFlowNode = useDuplicateFlowNode()
|
||||||
const updateTopic = useUpdateTopic()
|
|
||||||
|
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
// Выбранная тема
|
// Выбранная категория
|
||||||
const selectedTopic = useMemo(() => {
|
const selectedCategory = useMemo<ApprovalTopicCategory | null>(() => {
|
||||||
return topics.find((t) => t.id === selectedTopicId) || null
|
return categories.find((c) => c.id === selectedCategoryId) || null
|
||||||
}, [topics, selectedTopicId])
|
}, [categories, selectedCategoryId])
|
||||||
|
|
||||||
const topicOptions = topics.map((t) => ({
|
const categoryOptions = categories.map((c) => ({
|
||||||
value: String(t.id),
|
value: String(c.id),
|
||||||
label: `${t.name} (${t.code})`,
|
label: `${c.name} (${c.code})`,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// Подсчёт узлов
|
// Подсчёт узлов
|
||||||
|
|
@ -97,7 +93,6 @@ export default function FlowTreePage() {
|
||||||
|
|
||||||
// Обработчики
|
// Обработчики
|
||||||
const handleEdit = (node: ApprovalFlowNode) => {
|
const handleEdit = (node: ApprovalFlowNode) => {
|
||||||
// Находим родителя
|
|
||||||
const parent = findParent(tree, node.id!)
|
const parent = findParent(tree, node.id!)
|
||||||
setEditModal({
|
setEditModal({
|
||||||
opened: true,
|
opened: true,
|
||||||
|
|
@ -164,22 +159,12 @@ export default function FlowTreePage() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сохранение шаблонов темы
|
|
||||||
const handleSaveTemplates = () => {
|
|
||||||
if (!selectedTopic) return
|
|
||||||
updateTopic.mutate({
|
|
||||||
id: selectedTopic.id!,
|
|
||||||
message_template: selectedTopic.message_template,
|
|
||||||
code_template: selectedTopic.code_template,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Text size="xl" fw={700}>Конструктор деревьев</Text>
|
<Text size="xl" fw={700}>Конструктор деревьев</Text>
|
||||||
<Group>
|
<Group>
|
||||||
{selectedTopic && (
|
{selectedCategory && (
|
||||||
<Badge size="lg" variant="light">{totalNodes} узлов</Badge>
|
<Badge size="lg" variant="light">{totalNodes} узлов</Badge>
|
||||||
)}
|
)}
|
||||||
<Button
|
<Button
|
||||||
|
|
@ -192,108 +177,21 @@ export default function FlowTreePage() {
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
{/* Выбор темы */}
|
{/* Выбор категории */}
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="md">
|
<Select
|
||||||
<Select
|
label="Категория"
|
||||||
label="Тема"
|
placeholder="Выберите категорию для редактирования дерева"
|
||||||
placeholder="Выберите тему для редактирования дерева"
|
data={categoryOptions}
|
||||||
data={topicOptions}
|
value={selectedCategoryId ? String(selectedCategoryId) : null}
|
||||||
value={selectedTopicId ? String(selectedTopicId) : null}
|
onChange={(v) => setSelectedCategoryId(v ? Number(v) : null)}
|
||||||
onChange={(v) => setSelectedTopicId(v ? Number(v) : null)}
|
searchable
|
||||||
searchable
|
required
|
||||||
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>
|
</Paper>
|
||||||
|
|
||||||
{/* Дерево */}
|
{/* Дерево */}
|
||||||
{selectedTopicId && (
|
{selectedCategoryId && (
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
|
|
@ -306,8 +204,7 @@ export default function FlowTreePage() {
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="light"
|
variant="light"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (selectedTopicId) {
|
if (selectedCategoryId) {
|
||||||
// Инвалидация кэша
|
|
||||||
window.location.reload()
|
window.location.reload()
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
|
@ -328,7 +225,9 @@ export default function FlowTreePage() {
|
||||||
<Text size="sm">
|
<Text size="sm">
|
||||||
<b>Совет:</b> Используйте кнопки ↑ ↓ для изменения порядка,{' '}
|
<b>Совет:</b> Используйте кнопки ↑ ↓ для изменения порядка,{' '}
|
||||||
<b>+</b> для добавления дочернего узла, <b>📋</b> для дублирования.
|
<b>+</b> для добавления дочернего узла, <b>📋</b> для дублирования.
|
||||||
Все изменения сохраняются автоматически.
|
Все изменения сохраняются автоматически. Шаблоны сообщения и кода
|
||||||
|
темы (Go template) задаются в редакторе узла — обычно на том узле,
|
||||||
|
где также указан <b>topic_code</b>.
|
||||||
</Text>
|
</Text>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|
||||||
|
|
@ -371,10 +270,14 @@ export default function FlowTreePage() {
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Модалка редактирования узла */}
|
{/* Модалка редактирования узла.
|
||||||
{selectedTopicId && (
|
Помимо key/label/data_key и т.д. должна включать поля
|
||||||
|
message_template и code_template (Go template) — они
|
||||||
|
хранятся на самом узле. saveTree/create/update передают
|
||||||
|
category_id вместо topic_id. */}
|
||||||
|
{selectedCategoryId && (
|
||||||
<FlowNodeEditModal
|
<FlowNodeEditModal
|
||||||
topicId={selectedTopicId}
|
categoryId={selectedCategoryId}
|
||||||
parentNode={editModal.parentNode}
|
parentNode={editModal.parentNode}
|
||||||
editNode={editModal.editNode}
|
editNode={editModal.editNode}
|
||||||
opened={editModal.opened}
|
opened={editModal.opened}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useEffect, useMemo } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Stack,
|
Stack,
|
||||||
|
|
@ -8,8 +8,6 @@ import {
|
||||||
Group,
|
Group,
|
||||||
Button,
|
Button,
|
||||||
Text,
|
Text,
|
||||||
Loader,
|
|
||||||
Center,
|
|
||||||
Badge,
|
Badge,
|
||||||
Paper,
|
Paper,
|
||||||
Select,
|
Select,
|
||||||
|
|
@ -17,15 +15,16 @@ import {
|
||||||
Alert,
|
Alert,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Box,
|
Box,
|
||||||
|
Collapse,
|
||||||
|
ActionIcon,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useForm } from '@mantine/form'
|
import { useForm } from '@mantine/form'
|
||||||
import { useCreateFlowNode, useUpdateFlowNode } from '@/features/flowNodes/hooks/useFlowNodes'
|
import { useCreateFlowNode, useUpdateFlowNode, useFlowNodesTree } from '@/features/flowNodes/hooks/useFlowNodes'
|
||||||
import { useFlowNodesTree } from '@/features/flowNodes/hooks/useFlowNodes'
|
|
||||||
import type { ApprovalFlowNode } from '@/types/api'
|
import type { ApprovalFlowNode } from '@/types/api'
|
||||||
import { IconAlertCircle, IconInfoCircle } from '@tabler/icons-react'
|
import { IconAlertCircle, IconInfoCircle, IconChevronDown, IconChevronRight } from '@tabler/icons-react'
|
||||||
|
|
||||||
interface FlowNodeEditModalProps {
|
interface FlowNodeEditModalProps {
|
||||||
topicId: number
|
categoryId: number
|
||||||
parentNode: ApprovalFlowNode | null
|
parentNode: ApprovalFlowNode | null
|
||||||
editNode: ApprovalFlowNode | null
|
editNode: ApprovalFlowNode | null
|
||||||
opened: boolean
|
opened: boolean
|
||||||
|
|
@ -70,7 +69,7 @@ const generateKeyFromLabel = (label: string): string => {
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function FlowNodeEditModal({
|
export default function FlowNodeEditModal({
|
||||||
topicId,
|
categoryId,
|
||||||
parentNode,
|
parentNode,
|
||||||
editNode,
|
editNode,
|
||||||
opened,
|
opened,
|
||||||
|
|
@ -78,9 +77,11 @@ export default function FlowNodeEditModal({
|
||||||
}: FlowNodeEditModalProps) {
|
}: FlowNodeEditModalProps) {
|
||||||
const createFlowNode = useCreateFlowNode()
|
const createFlowNode = useCreateFlowNode()
|
||||||
const updateFlowNode = useUpdateFlowNode()
|
const updateFlowNode = useUpdateFlowNode()
|
||||||
const { data: treeData } = useFlowNodesTree(topicId)
|
const { data: treeData } = useFlowNodesTree(categoryId)
|
||||||
const tree = treeData?.data || []
|
const tree = treeData?.data || []
|
||||||
|
|
||||||
|
const [showTemplates, setShowTemplates] = useState(false)
|
||||||
|
|
||||||
const isEditMode = editNode !== null
|
const isEditMode = editNode !== null
|
||||||
|
|
||||||
const form = useForm({
|
const form = useForm({
|
||||||
|
|
@ -95,6 +96,8 @@ export default function FlowNodeEditModal({
|
||||||
multi_select_key: '',
|
multi_select_key: '',
|
||||||
multi_select_value: '',
|
multi_select_value: '',
|
||||||
topic_code: '',
|
topic_code: '',
|
||||||
|
message_template: '',
|
||||||
|
code_template: '',
|
||||||
auto_generate_key: true,
|
auto_generate_key: true,
|
||||||
},
|
},
|
||||||
validate: {
|
validate: {
|
||||||
|
|
@ -105,7 +108,7 @@ export default function FlowNodeEditModal({
|
||||||
// Проверка уникальности ключа
|
// Проверка уникальности ключа
|
||||||
const existingKeys = collectAllKeys(tree)
|
const existingKeys = collectAllKeys(tree)
|
||||||
if (existingKeys.includes(v as string) && (!editNode || editNode.key !== v)) {
|
if (existingKeys.includes(v as string) && (!editNode || editNode.key !== v)) {
|
||||||
return 'Ключ уже используется в этой теме'
|
return 'Ключ уже используется в этой категории'
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
},
|
},
|
||||||
|
|
@ -186,8 +189,11 @@ export default function FlowNodeEditModal({
|
||||||
multi_select_key: editNode.multi_select_key || '',
|
multi_select_key: editNode.multi_select_key || '',
|
||||||
multi_select_value: editNode.multi_select_value || '',
|
multi_select_value: editNode.multi_select_value || '',
|
||||||
topic_code: editNode.topic_code || '',
|
topic_code: editNode.topic_code || '',
|
||||||
|
message_template: editNode.message_template || '',
|
||||||
|
code_template: editNode.code_template || '',
|
||||||
auto_generate_key: false, // При редактировании не генерируем автоматически
|
auto_generate_key: false, // При редактировании не генерируем автоматически
|
||||||
})
|
})
|
||||||
|
setShowTemplates(!!(editNode.message_template || editNode.code_template))
|
||||||
} else {
|
} else {
|
||||||
form.reset()
|
form.reset()
|
||||||
const baseKey = parentNode?.key || ''
|
const baseKey = parentNode?.key || ''
|
||||||
|
|
@ -202,8 +208,11 @@ export default function FlowNodeEditModal({
|
||||||
multi_select_key: '',
|
multi_select_key: '',
|
||||||
multi_select_value: '',
|
multi_select_value: '',
|
||||||
topic_code: '',
|
topic_code: '',
|
||||||
|
message_template: '',
|
||||||
|
code_template: '',
|
||||||
auto_generate_key: true,
|
auto_generate_key: true,
|
||||||
})
|
})
|
||||||
|
setShowTemplates(false)
|
||||||
}
|
}
|
||||||
}, [editNode, parentNode, opened])
|
}, [editNode, parentNode, opened])
|
||||||
|
|
||||||
|
|
@ -220,13 +229,15 @@ export default function FlowNodeEditModal({
|
||||||
multi_select_key: values.nodeType === 'multiselect' ? values.multi_select_key : null,
|
multi_select_key: values.nodeType === 'multiselect' ? values.multi_select_key : null,
|
||||||
multi_select_value: values.nodeType === 'multiselect' ? values.multi_select_value : null,
|
multi_select_value: values.nodeType === 'multiselect' ? values.multi_select_value : null,
|
||||||
topic_code: values.topic_code || null,
|
topic_code: values.topic_code || null,
|
||||||
|
message_template: values.message_template || null,
|
||||||
|
code_template: values.code_template || null,
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isEditMode && editNode?.id) {
|
if (isEditMode && editNode?.id) {
|
||||||
await updateFlowNode.mutateAsync({ id: editNode.id, ...payload })
|
await updateFlowNode.mutateAsync({ id: editNode.id, ...payload })
|
||||||
} else {
|
} else {
|
||||||
await createFlowNode.mutateAsync({
|
await createFlowNode.mutateAsync({
|
||||||
topic_id: topicId,
|
category_id: categoryId,
|
||||||
parent_id: parentNode?.id || null,
|
parent_id: parentNode?.id || null,
|
||||||
...payload,
|
...payload,
|
||||||
})
|
})
|
||||||
|
|
@ -253,6 +264,9 @@ export default function FlowNodeEditModal({
|
||||||
if (nodeType === 'multiselect' && !form.values.multi_select_key) {
|
if (nodeType === 'multiselect' && !form.values.multi_select_key) {
|
||||||
warns.push('Для мультиселекта необходимо указать MultiSelectKey')
|
warns.push('Для мультиселекта необходимо указать MultiSelectKey')
|
||||||
}
|
}
|
||||||
|
if ((form.values.message_template || form.values.code_template) && !form.values.topic_code) {
|
||||||
|
warns.push('Шаблоны сообщения/кода обычно имеют смысл только на узле с заполненным Code темы (topic_code)')
|
||||||
|
}
|
||||||
|
|
||||||
return warns
|
return warns
|
||||||
}, [nodeType, form.values])
|
}, [nodeType, form.values])
|
||||||
|
|
@ -322,7 +336,7 @@ export default function FlowNodeEditModal({
|
||||||
<TextInput
|
<TextInput
|
||||||
label="Ключ (Key)"
|
label="Ключ (Key)"
|
||||||
placeholder="crimea, f1_tmc..."
|
placeholder="crimea, f1_tmc..."
|
||||||
description="Уникальный идентификатор узла в рамках темы (только lowercase, цифры, подчеркивания)"
|
description="Уникальный идентификатор узла в рамках категории (только lowercase, цифры, подчеркивания)"
|
||||||
required
|
required
|
||||||
style={{ flex: 1 }}
|
style={{ flex: 1 }}
|
||||||
disabled={form.values.auto_generate_key}
|
disabled={form.values.auto_generate_key}
|
||||||
|
|
@ -345,12 +359,15 @@ export default function FlowNodeEditModal({
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<TextInput
|
<TextInput
|
||||||
label="Код темы для проверки прав (опционально)"
|
label="Код темы (topic_code)"
|
||||||
placeholder="non_budget_f1"
|
placeholder="non_budget_f1"
|
||||||
description={
|
description={
|
||||||
<Text size="xs">
|
<Text size="xs">
|
||||||
Если задан — кнопка видна только пользователям с правом <Code>create</Code> на эту тему.
|
Используется двояко: (1) для проверки прав — если задан,
|
||||||
Оставьте пустым, если кнопка должна быть видна всем.
|
кнопка видна только пользователям с правом <Code>create</Code> на
|
||||||
|
эту тему; (2) как код итоговой <Code>ApprovalTopic</Code>, в
|
||||||
|
которую резолвится этот путь по дереву — от него зависят
|
||||||
|
шаблоны ниже. Оставьте пустым для промежуточных узлов дерева.
|
||||||
</Text>
|
</Text>
|
||||||
}
|
}
|
||||||
{...form.getInputProps('topic_code')}
|
{...form.getInputProps('topic_code')}
|
||||||
|
|
@ -460,6 +477,74 @@ export default function FlowNodeEditModal({
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Шаблоны темы (Go template) — хранятся на узле (message_template / code_template) */}
|
||||||
|
<Paper withBorder p="md">
|
||||||
|
<Group
|
||||||
|
justify="space-between"
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
onClick={() => setShowTemplates(!showTemplates)}
|
||||||
|
>
|
||||||
|
<Group gap="xs">
|
||||||
|
{showTemplates ? (
|
||||||
|
<IconChevronDown size={16} />
|
||||||
|
) : (
|
||||||
|
<IconChevronRight size={16} />
|
||||||
|
)}
|
||||||
|
<Text size="sm" fw={600}>
|
||||||
|
4. Шаблоны сообщения и кода темы (опционально)
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
<ActionIcon variant="subtle" size="sm">
|
||||||
|
{showTemplates ? <IconChevronDown size={14} /> : <IconChevronRight size={14} />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
<Collapse expanded={showTemplates}>
|
||||||
|
<Stack gap="sm" mt="sm">
|
||||||
|
<Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
|
||||||
|
<Text size="xs">
|
||||||
|
Задаются на узле, где также указан <Code>topic_code</Code> — то
|
||||||
|
есть в точке, где путь по дереву резолвится в конкретную тему
|
||||||
|
согласования (<Code>ApprovalTopic</Code>). Если оставить пустым,
|
||||||
|
используется поведение по умолчанию.
|
||||||
|
</Text>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<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}
|
||||||
|
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||||
|
{...form.getInputProps('message_template')}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Textarea
|
||||||
|
label="Шаблон кода темы (Go template)"
|
||||||
|
description={
|
||||||
|
<Text size="xs">
|
||||||
|
Формирует финальный код темы. Если не задан — код формируется
|
||||||
|
автоматически из всех значений <Code>collected</Code>. Функции:{' '}
|
||||||
|
<Code>trimPrefix</Code>, <Code>eq</Code>, <Code>contains</Code>
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
minRows={2}
|
||||||
|
styles={{ input: { fontFamily: 'monospace', fontSize: 12 } }}
|
||||||
|
{...form.getInputProps('code_template')}
|
||||||
|
/>
|
||||||
|
</Stack>
|
||||||
|
</Collapse>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
{/* Превью */}
|
{/* Превью */}
|
||||||
<Paper withBorder p="md" bg="gray.0">
|
<Paper withBorder p="md" bg="gray.0">
|
||||||
<Text size="sm" fw={600} mb="sm">
|
<Text size="sm" fw={600} mb="sm">
|
||||||
|
|
|
||||||
|
|
@ -228,10 +228,7 @@ export interface ApprovalTopic {
|
||||||
instructions?: string
|
instructions?: string
|
||||||
created_at?: string
|
created_at?: string
|
||||||
updated_at?: string
|
updated_at?: string
|
||||||
message_template?: string | null
|
|
||||||
code_template?: string | null
|
|
||||||
category?: ApprovalTopicCategory
|
category?: ApprovalTopicCategory
|
||||||
is_tree_root?: boolean
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Admin {
|
export interface Admin {
|
||||||
|
|
@ -278,6 +275,9 @@ export interface ApprovalFlowNode {
|
||||||
topic_id?: number
|
topic_id?: number
|
||||||
parent_id?: number | null
|
parent_id?: number | null
|
||||||
key: string
|
key: string
|
||||||
|
category_id: number
|
||||||
|
message_template?: string | null
|
||||||
|
code_template?: string | null
|
||||||
label: string
|
label: string
|
||||||
data_key?: string | null
|
data_key?: string | null
|
||||||
data_value?: string | null
|
data_value?: string | null
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue