56 lines
2.0 KiB
TypeScript
56 lines
2.0 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||
import {
|
||
notificationsApi,
|
||
type NotificationsListParams,
|
||
type CreateNotificationRequest,
|
||
} from '@/api/notifications'
|
||
import { notifications as mantineNotifications } from '@mantine/notifications'
|
||
|
||
export const NOTIFICATIONS_QUERY_KEY = 'notifications'
|
||
|
||
export function useNotifications(params: NotificationsListParams = {}) {
|
||
return useQuery({
|
||
queryKey: [NOTIFICATIONS_QUERY_KEY, params],
|
||
queryFn: async () => {
|
||
const response = await notificationsApi.getList(params)
|
||
return response.data
|
||
},
|
||
})
|
||
}
|
||
|
||
export function useNotification(id: number | null) {
|
||
return useQuery({
|
||
queryKey: ['notification', id],
|
||
queryFn: async () => {
|
||
if (!id) return null
|
||
const response = await notificationsApi.getById(id)
|
||
return response.data
|
||
},
|
||
enabled: !!id,
|
||
})
|
||
}
|
||
|
||
export function useCreateNotification() {
|
||
const queryClient = useQueryClient()
|
||
|
||
return useMutation({
|
||
mutationFn: (data: CreateNotificationRequest) => notificationsApi.create(data),
|
||
onSuccess: (response) => {
|
||
queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_QUERY_KEY] })
|
||
const n = response.data
|
||
const hasFailed = (n.failed_count ?? 0) > 0
|
||
mantineNotifications.show({
|
||
title: hasFailed ? 'Отправлено с ошибками' : 'Отправлено',
|
||
message: `Доставлено: ${n.sent_count ?? 0} из ${n.total_count ?? 0}`,
|
||
color: hasFailed ? 'yellow' : 'green',
|
||
})
|
||
},
|
||
onError: (error: any) => {
|
||
mantineNotifications.show({
|
||
title: 'Ошибка',
|
||
message: error.response?.data?.error_description || 'Не удалось отправить уведомление',
|
||
color: 'red',
|
||
})
|
||
},
|
||
})
|
||
} |