67 lines
2.5 KiB
TypeScript
67 lines
2.5 KiB
TypeScript
import { createContext, useContext, useState } from 'react'
|
|
import type { ReactNode } from 'react'
|
|
import { useMutation, useQuery } from '@tanstack/react-query'
|
|
import type { AbsenceDetails } from '@gruperly/shared'
|
|
import { useToast } from '../../components/ui'
|
|
import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api'
|
|
import { errorMessage } from '../../i18n'
|
|
import { i18n } from '../../i18n/instance'
|
|
|
|
type AbsenceNotifyContextValue = {
|
|
token: string
|
|
details: AbsenceDetails | undefined
|
|
detailsPending: boolean
|
|
detailsFailed: boolean
|
|
isNotified: (session: { notified: boolean; sessionId: string }) => boolean
|
|
isNotifying: (sessionId: string) => boolean
|
|
notify: (sessionId: string) => void
|
|
}
|
|
|
|
const AbsenceNotifyContext = createContext<AbsenceNotifyContextValue | null>(null)
|
|
|
|
export function AbsenceNotifyProvider({ token, children }: { token: string; children: ReactNode }) {
|
|
const toast = useToast()
|
|
const [locallyNotified, setLocallyNotified] = useState<string[]>([])
|
|
|
|
const detailsQuery = useQuery({
|
|
queryKey: ['absence-details', token],
|
|
queryFn: () => getAbsenceDetails(token),
|
|
enabled: Boolean(token),
|
|
retry: 1,
|
|
})
|
|
|
|
const notifyMutation = useMutation({
|
|
mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }),
|
|
onSuccess: (_data, sessionId) => {
|
|
setLocallyNotified((prev) => [...prev, sessionId])
|
|
toast.success(i18n.t('public:absence.done'), i18n.t('public:absence.doneTitle'))
|
|
},
|
|
onError: (error: unknown) => {
|
|
if (error instanceof ApiError && error.problem?.status === 404) {
|
|
toast.error(i18n.t('public:absence.invalidLink'))
|
|
return
|
|
}
|
|
toast.error(errorMessage(error, i18n.t('public:absence.error')))
|
|
},
|
|
})
|
|
|
|
const value: AbsenceNotifyContextValue = {
|
|
token,
|
|
details: detailsQuery.data,
|
|
detailsPending: detailsQuery.isPending,
|
|
detailsFailed: detailsQuery.isError,
|
|
isNotified: (session) => session.notified || locallyNotified.includes(session.sessionId),
|
|
isNotifying: (sessionId) => notifyMutation.isPending && notifyMutation.variables === sessionId,
|
|
notify: (sessionId) => notifyMutation.mutate(sessionId),
|
|
}
|
|
|
|
return <AbsenceNotifyContext.Provider value={value}>{children}</AbsenceNotifyContext.Provider>
|
|
}
|
|
|
|
export function useAbsenceNotify() {
|
|
const context = useContext(AbsenceNotifyContext)
|
|
if (!context) {
|
|
throw new Error('useAbsenceNotify debe usarse dentro de <AbsenceNotifyProvider>')
|
|
}
|
|
return context
|
|
} |