- Estadísticas ("Alumnos en riesgo") y el job de reenganche usan la misma
regla de dominio que la lista de grupos e Inicio
(summarizeMemberAttendance). El armado del historial por alumno vive en
analytics/lib/member-attendance.ts y se borra el clasificador viejo
(racha o asistencia mensual < 50%).
- El badge de alumnos en riesgo muestra el motivo real (faltas seguidas,
días sin venir o asistencia en baja).
- GET /home devuelve pendingPreRegistrations por grupo (en la misma
consulta de grupos) y "Para atender" las lista con link a la ficha en
la pestaña Pendientes (?section=pending).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
409 lines
15 KiB
TypeScript
409 lines
15 KiB
TypeScript
import { createContext, useContext, useMemo, useState } from 'react'
|
|
import type { ReactNode } from 'react'
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import type {
|
|
AttendeeDto,
|
|
UpdateGroupAutomations,
|
|
AttendeeListItem,
|
|
GroupDto,
|
|
GroupPreRegistrationDto,
|
|
GroupWaitlistEntryDto,
|
|
GroupRiskLevel,
|
|
} from '@gruperly/shared'
|
|
import { useToast } from '../../../components/ui'
|
|
import { useAuth } from '../../../context/AuthProvider'
|
|
import {
|
|
ApiError,
|
|
approveGroupPreRegistration,
|
|
getGroup,
|
|
getGroupAttendees,
|
|
getGroupPreRegistrations,
|
|
getGroupsRiskOverview,
|
|
getGroupWaitlist,
|
|
getInviteToken,
|
|
promoteGroupWaitlistEntry,
|
|
rejectGroupPreRegistration,
|
|
removeGroupWaitlistEntry,
|
|
updateGroupAutomations,
|
|
} from '../../../lib/api'
|
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
|
|
|
export type ListSection = 'members' | 'pending'
|
|
|
|
type GroupDetailContextValue = {
|
|
groupId: string
|
|
group: GroupDto | undefined
|
|
/** Name for the large title: real data, cache or "Grupo" while loading. */
|
|
groupTitle: string
|
|
groupQueryPending: boolean
|
|
riskLevel: GroupRiskLevel
|
|
attendees: AttendeeListItem[]
|
|
attendeesTotal: number
|
|
attendeesPending: boolean
|
|
waitlistEntries: GroupWaitlistEntryDto[]
|
|
waitlistTotal: number
|
|
waitlistPending: boolean
|
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
|
preRegistrations: GroupPreRegistrationDto[]
|
|
preRegistrationsTotal: number
|
|
preRegistrationsPending: boolean
|
|
hasFreeCapacity: boolean
|
|
inviteUrl: string | undefined
|
|
invitePending: boolean
|
|
whatsappMessage: string
|
|
searchFilter: string
|
|
setSearchFilter: (value: string) => void
|
|
/** The member list narrows down to those whose charge is overdue. */
|
|
overdueOnly: boolean
|
|
setOverdueOnly: (value: boolean) => void
|
|
listSection: ListSection
|
|
setListSection: (value: ListSection) => void
|
|
isInviteModalOpen: boolean
|
|
openInviteModal: () => void
|
|
closeInviteModal: () => void
|
|
attendeeToRemove: AttendeeDto | null
|
|
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
|
cancelRemoveAttendee: () => void
|
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
|
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
|
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
|
selectedPreRegistration: GroupPreRegistrationDto | null
|
|
setSelectedPreRegistration: (entry: GroupPreRegistrationDto | null) => void
|
|
isSubmittingRemoval: boolean
|
|
isSubmittingPromotion: boolean
|
|
isSubmittingWaitlistRemoval: boolean
|
|
isSubmittingApproval: boolean
|
|
isSubmittingRejection: boolean
|
|
isRegeneratingInvite: boolean
|
|
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
|
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
|
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
|
|
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
|
|
regenerateInvite: () => void
|
|
copyInviteLink: () => Promise<void>
|
|
copyWhatsappMessage: () => Promise<void>
|
|
openWhatsapp: () => Promise<void>
|
|
/** Solo el dueño ve y cambia las automatizaciones: salen de su WhatsApp. */
|
|
isGroupOwner: boolean
|
|
updateAutomations: (patch: UpdateGroupAutomations) => void
|
|
isUpdatingAutomations: boolean
|
|
}
|
|
|
|
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
|
|
|
export function GroupDetailProvider({
|
|
groupId,
|
|
initialSection = 'members',
|
|
children,
|
|
}: {
|
|
groupId: string
|
|
/** Lets a link open the detail straight on Pendientes (Home's "Para atender"). */
|
|
initialSection?: ListSection
|
|
children: ReactNode
|
|
}) {
|
|
const queryClient = useQueryClient()
|
|
const toast = useToast()
|
|
const { user } = useAuth()
|
|
|
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
|
const [listSection, setListSectionState] = useState<ListSection>(initialSection)
|
|
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
|
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
|
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
|
const [searchFilter, setSearchFilter] = useState('')
|
|
const [overdueOnly, setOverdueOnly] = useState(false)
|
|
|
|
// The list's controls belong to the view that opened them: on a tab change
|
|
// they are cleared so as not to inherit a filter with no matches.
|
|
const setListSection = (value: ListSection) => {
|
|
setListSectionState(value)
|
|
setSearchFilter('')
|
|
setOverdueOnly(false)
|
|
}
|
|
|
|
const groupQuery = useQuery({
|
|
queryKey: ['group', groupId],
|
|
queryFn: () => getGroup(groupId),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const riskOverviewQuery = useQuery({
|
|
queryKey: ['groups-risk-overview'],
|
|
queryFn: getGroupsRiskOverview,
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const inviteTokenQuery = useQuery({
|
|
queryKey: ['invite-token', groupId],
|
|
queryFn: () => getInviteToken(groupId),
|
|
enabled: Boolean(groupId) && isInviteModalOpen,
|
|
})
|
|
|
|
const attendeesQuery = useQuery({
|
|
queryKey: ['group-attendees', groupId],
|
|
queryFn: () => getGroupAttendees(groupId, 1, 100),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const waitlistQuery = useQuery({
|
|
queryKey: ['group-waitlist', groupId],
|
|
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const preRegistrationsQuery = useQuery({
|
|
queryKey: ['group-preregistrations', groupId],
|
|
queryFn: () => getGroupPreRegistrations(groupId, 1, 100),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const group = groupQuery.data
|
|
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
|
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
|
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
|
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
|
const preRegistrations = useMemo(
|
|
() => preRegistrationsQuery.data?.data ?? [],
|
|
[preRegistrationsQuery.data],
|
|
)
|
|
const preRegistrationsTotal =
|
|
preRegistrationsQuery.data?.pagination?.total ?? preRegistrations.length
|
|
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
|
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
|
|
|
const invalidateGroupQueries = () => {
|
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group-preregistrations', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
|
}
|
|
|
|
const regenerateTokenMutation = useMutation({
|
|
mutationFn: () => getInviteToken(groupId, true),
|
|
onSuccess: (data) => {
|
|
queryClient.setQueryData(['invite-token', groupId], data)
|
|
toast.success('Se generó un nuevo enlace de invitación.')
|
|
},
|
|
onError: () => {
|
|
toast.error('No se pudo regenerar el enlace de invitación.')
|
|
},
|
|
})
|
|
|
|
const automationsMutation = useMutation({
|
|
mutationFn: (patch: UpdateGroupAutomations) => updateGroupAutomations(groupId, patch),
|
|
onSuccess: (automations) => {
|
|
queryClient.setQueryData<GroupDto>(['group', groupId], (current) =>
|
|
current ? { ...current, ...automations } : current,
|
|
)
|
|
toast.success('Guardamos los mensajes automáticos del grupo.')
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'No se pudieron guardar los mensajes automáticos.')
|
|
},
|
|
})
|
|
|
|
const removeAttendeeMutation = useRemoveAttendee({
|
|
groupId,
|
|
onRemoved: () => setAttendeeToRemove(null),
|
|
})
|
|
|
|
const promoteWaitlistMutation = useMutation({
|
|
mutationFn: (entryId: string) => promoteGroupWaitlistEntry(groupId, entryId),
|
|
onSuccess: (result) => {
|
|
toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`)
|
|
invalidateGroupQueries()
|
|
},
|
|
onError: (err: Error) => {
|
|
if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') {
|
|
toast.error('El grupo alcanzó su cupo. Quita un miembro o aumenta el cupo primero.')
|
|
} else {
|
|
toast.error(err.message || 'No se pudo pasar al miembro al grupo.')
|
|
}
|
|
},
|
|
})
|
|
|
|
const removeWaitlistEntryMutation = useMutation({
|
|
mutationFn: (entry: GroupWaitlistEntryDto) => removeGroupWaitlistEntry(groupId, entry.id),
|
|
onSuccess: (_result, entry) => {
|
|
toast.success(`${entry.fullName} fue quitado de la lista de espera.`)
|
|
invalidateGroupQueries()
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'No se pudo quitar de la lista de espera.')
|
|
},
|
|
})
|
|
|
|
const approvePreRegistrationMutation = useMutation({
|
|
mutationFn: (entry: GroupPreRegistrationDto) =>
|
|
approveGroupPreRegistration(groupId, entry.id),
|
|
onSuccess: (result, entry) => {
|
|
setSelectedPreRegistration(null)
|
|
toast.success(
|
|
result.outcome === 'added'
|
|
? `${entry.fullName} ahora es miembro del grupo.`
|
|
: `${entry.fullName} fue agregado a la lista de espera: el grupo está completo.`,
|
|
)
|
|
invalidateGroupQueries()
|
|
},
|
|
onError: (err: Error) => {
|
|
if (err instanceof ApiError) {
|
|
if (err.problem?.code === 'attendee_already_registered') {
|
|
toast.error('Ya hay un miembro con ese teléfono en el grupo. Puedes rechazar la pre-inscripción.')
|
|
return
|
|
}
|
|
if (err.problem?.code === 'pre_registration_already_reviewed') {
|
|
toast.error('Esta pre-inscripción ya fue revisada.')
|
|
invalidateGroupQueries()
|
|
return
|
|
}
|
|
}
|
|
toast.error(err.message || 'No se pudo aprobar la pre-inscripción.')
|
|
},
|
|
})
|
|
|
|
const rejectPreRegistrationMutation = useMutation({
|
|
mutationFn: (entry: GroupPreRegistrationDto) =>
|
|
rejectGroupPreRegistration(groupId, entry.id),
|
|
onSuccess: (_result, entry) => {
|
|
setSelectedPreRegistration(null)
|
|
toast.success(`La pre-inscripción de ${entry.fullName} fue rechazada.`)
|
|
invalidateGroupQueries()
|
|
},
|
|
onError: (err: Error) => {
|
|
if (err instanceof ApiError && err.problem?.code === 'pre_registration_already_reviewed') {
|
|
toast.error('Esta pre-inscripción ya fue revisada.')
|
|
invalidateGroupQueries()
|
|
return
|
|
}
|
|
toast.error(err.message || 'No se pudo rechazar la pre-inscripción.')
|
|
},
|
|
})
|
|
|
|
const inviteUrl = inviteTokenQuery.data?.inviteUrl
|
|
const whatsappMessage =
|
|
group && inviteUrl
|
|
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:\n${inviteUrl}`
|
|
: ''
|
|
const whatsappShareUrl = whatsappMessage
|
|
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
|
: ''
|
|
|
|
const copyInviteLink = async () => {
|
|
if (!inviteUrl) return
|
|
try {
|
|
await navigator.clipboard.writeText(inviteUrl)
|
|
toast.success('¡Enlace de invitación copiado al portapapeles!')
|
|
} catch {
|
|
toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.')
|
|
}
|
|
}
|
|
|
|
const copyWhatsappMessage = async () => {
|
|
if (!whatsappMessage) return
|
|
try {
|
|
await navigator.clipboard.writeText(whatsappMessage)
|
|
toast.success('¡Mensaje copiado al portapapeles!')
|
|
} catch {
|
|
toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.')
|
|
}
|
|
}
|
|
|
|
const openWhatsapp = async () => {
|
|
if (!whatsappShareUrl) return
|
|
try {
|
|
if (whatsappMessage) {
|
|
await navigator.clipboard.writeText(whatsappMessage)
|
|
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
|
|
}
|
|
} catch {
|
|
// If the clipboard fails, we still open WhatsApp with the message.
|
|
}
|
|
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
|
}
|
|
|
|
// The large title always renders, even while loading: it is what gives the
|
|
// immersive bar its height and stops the layout from jumping. Arriving from
|
|
// the group detail page the name is already cached; on the first load it falls
|
|
// back to "Grupo".
|
|
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
|
const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'
|
|
|
|
const value: GroupDetailContextValue = {
|
|
groupId,
|
|
group,
|
|
groupTitle,
|
|
groupQueryPending: groupQuery.isPending,
|
|
isGroupOwner: Boolean(group && user && group.createdById === user.id),
|
|
updateAutomations: (patch) => automationsMutation.mutate(patch),
|
|
isUpdatingAutomations: automationsMutation.isPending,
|
|
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
|
attendees,
|
|
attendeesTotal,
|
|
attendeesPending: attendeesQuery.isPending,
|
|
waitlistEntries,
|
|
waitlistTotal,
|
|
waitlistPending: waitlistQuery.isPending,
|
|
firstWaitlistEntry,
|
|
preRegistrations,
|
|
preRegistrationsTotal,
|
|
preRegistrationsPending: preRegistrationsQuery.isPending,
|
|
hasFreeCapacity,
|
|
inviteUrl,
|
|
invitePending: inviteTokenQuery.isPending,
|
|
whatsappMessage,
|
|
searchFilter,
|
|
setSearchFilter,
|
|
overdueOnly,
|
|
setOverdueOnly,
|
|
listSection,
|
|
setListSection,
|
|
isInviteModalOpen,
|
|
openInviteModal: () => setIsInviteModalOpen(true),
|
|
closeInviteModal: () => setIsInviteModalOpen(false),
|
|
attendeeToRemove,
|
|
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
|
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
|
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
|
if (!attendeeToRemove) return
|
|
removeAttendeeMutation.removeAttendee({ attendee: attendeeToRemove, promoteFromWaitlist })
|
|
},
|
|
selectedWaitlistEntry,
|
|
setSelectedWaitlistEntry,
|
|
selectedPreRegistration,
|
|
setSelectedPreRegistration,
|
|
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
|
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
|
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
|
isSubmittingApproval: approvePreRegistrationMutation.isPending,
|
|
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
|
|
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
|
promoteEntry: (entry) => {
|
|
setSelectedWaitlistEntry(null)
|
|
promoteWaitlistMutation.mutate(entry.id)
|
|
},
|
|
removeEntry: (entry) => {
|
|
setSelectedWaitlistEntry(null)
|
|
removeWaitlistEntryMutation.mutate(entry)
|
|
},
|
|
approvePreRegistration: (entry) => {
|
|
approvePreRegistrationMutation.mutate(entry)
|
|
},
|
|
rejectPreRegistration: (entry) => {
|
|
rejectPreRegistrationMutation.mutate(entry)
|
|
},
|
|
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
|
copyInviteLink,
|
|
copyWhatsappMessage,
|
|
openWhatsapp,
|
|
}
|
|
|
|
return <GroupDetailContext.Provider value={value}>{children}</GroupDetailContext.Provider>
|
|
}
|
|
|
|
export function useGroupDetail() {
|
|
const context = useContext(GroupDetailContext)
|
|
if (!context) {
|
|
throw new Error('useGroupDetail debe usarse dentro de <GroupDetailProvider>')
|
|
}
|
|
return context
|
|
} |