Added routes
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
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'
|
||||
|
||||
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('Tu profesor ya tiene registrado el aviso. Gracias por avisar.', 'Ausencia avisada')
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
if (error instanceof ApiError && error.problem?.status === 404) {
|
||||
toast.error('Este enlace ya no es válido. Consultá a tu profesor.')
|
||||
return
|
||||
}
|
||||
toast.error(error instanceof Error ? error.message : 'No pudimos registrar el aviso.')
|
||||
},
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user