admin_ruspet/src/features/flowNodes/hooks/useFlowNodes.ts

150 lines
6.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
flowNodesApi,
type CreateFlowNodeRequest,
type UpdateFlowNodeRequest,
type MoveFlowNodeRequest,
type PreviewFlowRequest,
} from '@/api/flowNodes'
import { notifications } from '@mantine/notifications'
export const FLOW_NODES_QUERY_KEY = 'flowNodes'
export function useFlowNodesTree(categoryId: number | null) {
return useQuery({
queryKey: [FLOW_NODES_QUERY_KEY, categoryId],
queryFn: async () => {
if (!categoryId) return null
const response = await flowNodesApi.getTree(categoryId)
return response.data
},
enabled: !!categoryId,
})
}
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',
})
},
})
}
// Перемещение узла — используется и для ↑/↓ среди соседей, и для
// "поднять/опустить уровень" (там просто другой new_parent_id).
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',
})
},
})
}
// НОВОЕ: живой предпросмотр — код темы + текст сообщения согласующему
// для конкретного набора выборов. Не мутирует данные, поэтому это
// useMutation, вызываемый вручную (а не useQuery), чтобы не дёргать
// сервер на каждое нажатие клавиши, а только по явному запросу/дебаунсу.
// НОВОЕ: кнопка "Обновить бота" — форсирует у бота перечитывание дерева тем
// из БД, не дожидаясь фонового тика (см. reload_watcher.go в telegram_service).
export function useReloadBot() {
return useMutation({
mutationFn: () => flowNodesApi.reloadBot(),
onSuccess: () => {
notifications.show({
title: 'Готово',
message: 'Бот обновит список тем в течение нескольких секунд',
color: 'green',
})
},
onError: (error: any) => {
notifications.show({
title: 'Не получилось',
message: error.response?.data?.error_description || 'Не удалось обновить бота',
color: 'red',
})
},
})
}
export function usePreviewFlow(categoryId: number | null) {
return useMutation({
mutationFn: async (data: PreviewFlowRequest) => {
if (!categoryId) throw new Error('categoryId is required')
const response = await flowNodesApi.preview(categoryId, data)
return response.data // разворачиваем AxiosResponse -> PreviewFlowResponse
},
})
}