- Added Large Title component to manage immersive screen headers. - Created ImmersiveBarProvider to handle the sticky bar for immersive routes. - Updated RootLayout to conditionally render Header based on immersive routes. - Modified Sidebar to adjust its position and height in immersive mode. - Integrated Large Title in ClassAttendanceView and AnalyticsView for consistent header display. - Updated GroupHeader to use Large Title for better layout management. - Implemented isImmersiveRoute function to determine immersive routes. - Added tests for immersive route detection.
240 lines
10 KiB
TypeScript
240 lines
10 KiB
TypeScript
import { useState } from 'react'
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import { Link, useParams } from '@tanstack/react-router'
|
|
import type { GroupDto, StudentAtRiskDto } from '@gruperly/shared'
|
|
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
|
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
|
import { Badge, Button, useToast } from '../../../components/ui'
|
|
import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api'
|
|
import { KpiCard } from './KpiCard'
|
|
import { AtRiskStudentCard, type StatusAction } from './AtRiskStudentCard'
|
|
import { AttendeeHistoryModal } from './AttendeeHistoryModal'
|
|
import { StatusActionModal } from './StatusActionModal'
|
|
|
|
export function AnalyticsView() {
|
|
const { groupId } = useParams({ strict: false }) as { groupId: string }
|
|
const queryClient = useQueryClient()
|
|
const toast = useToast()
|
|
|
|
const [historyStudent, setHistoryStudent] = useState<StudentAtRiskDto | null>(null)
|
|
const [statusAction, setStatusAction] = useState<StatusAction>(null)
|
|
const [menuOpenFor, setMenuOpenFor] = useState<string | null>(null)
|
|
|
|
const analyticsQuery = useQuery({
|
|
queryKey: ['group-analytics', groupId],
|
|
queryFn: () => getGroupAnalytics(groupId),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const riskQuery = useQuery({
|
|
queryKey: ['students-at-risk', groupId],
|
|
queryFn: () => getStudentsAtRisk(groupId),
|
|
enabled: Boolean(groupId),
|
|
})
|
|
|
|
const historyQuery = useQuery({
|
|
queryKey: ['attendee-history', groupId, historyStudent?.attendeeId],
|
|
queryFn: () => getAttendeeHistory(groupId, historyStudent!.attendeeId!),
|
|
enabled: Boolean(groupId && historyStudent),
|
|
})
|
|
|
|
const statusMutation = useMutation({
|
|
mutationFn: (action: Exclude<StatusAction, null>) =>
|
|
updateAttendeeStatus(action.student.attendeeId, action.status),
|
|
onSuccess: (_result, action) => {
|
|
const name = action.student.fullName.split(' ')[0]
|
|
toast.success(
|
|
action.status === 'DROPPED'
|
|
? `${name} fue dado de baja del grupo. Su vacante quedó disponible.`
|
|
: `La vacante de ${name} quedó pausada.`,
|
|
)
|
|
setStatusAction(null)
|
|
void queryClient.invalidateQueries({ queryKey: ['students-at-risk', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
|
void queryClient.invalidateQueries({ queryKey: ['classes-today'] })
|
|
void queryClient.invalidateQueries({ queryKey: ['home-summary'] })
|
|
void queryClient.invalidateQueries({ queryKey: ['groups-risk-overview'] })
|
|
},
|
|
onError: (err: Error) => {
|
|
toast.error(err.message || 'No pudimos actualizar el estado del alumno.')
|
|
},
|
|
})
|
|
|
|
const handleReengage = async (student: StudentAtRiskDto, groupName: string) => {
|
|
if (!student.phone) return
|
|
const firstName = student.fullName.split(' ')[0] ?? student.fullName
|
|
const message =
|
|
`¡Hola ${firstName}! 👋 Te extrañamos en ${groupName}. ` +
|
|
'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' +
|
|
'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.'
|
|
const waUrl = `https://wa.me/${student.phone.replace(/\D/g, '')}?text=${encodeURIComponent(message)}`
|
|
try {
|
|
await navigator.clipboard.writeText(message)
|
|
toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.')
|
|
} catch {
|
|
// Si clipboard falla, igual abrimos WhatsApp con el mensaje.
|
|
}
|
|
window.open(waUrl, '_blank', 'noopener,noreferrer')
|
|
}
|
|
|
|
// El nombre suele estar en caché porque se llega desde la ficha del grupo: así
|
|
// el título grande aparece de entrada y no hay salto cuando cargan las queries.
|
|
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
|
|
const groupName = riskQuery.data?.groupName ?? cachedGroupName
|
|
const analytics = analyticsQuery.data
|
|
const atRisk = riskQuery.data?.data ?? []
|
|
|
|
const isPending = analyticsQuery.isPending || riskQuery.isPending
|
|
const hasFailed = analyticsQuery.isError || riskQuery.isError
|
|
// El contenido necesita los dos queries: sin `riskQuery` no hay ni el nombre
|
|
// del grupo ni la lista de alumnos en riesgo.
|
|
const showContent = !isPending && !hasFailed && Boolean(analytics)
|
|
|
|
return (
|
|
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
|
{/* El título grande va siempre, incluso cargando: es lo que da altura a
|
|
la barra y evita que el layout salte cuando llegan los datos. */}
|
|
<LargeTitle
|
|
title={groupName ?? 'Grupo'}
|
|
leading={
|
|
<Link
|
|
to="/groups/$groupId"
|
|
params={{ groupId }}
|
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
|
>
|
|
<ArrowLeft className="size-4" />
|
|
Volver al grupo
|
|
</Link>
|
|
}
|
|
>
|
|
{/* "Estadísticas" es el subtítulo de la pantalla, no el título: el
|
|
título grande identifica el grupo y la barra colapsada lo muestra
|
|
para saber siempre sobre qué se está mirando. */}
|
|
<div className="mt-2 flex flex-wrap items-center justify-between gap-3">
|
|
<div className="min-w-0">
|
|
<p className="text-[14px] font-semibold uppercase tracking-wide text-foreground/70">
|
|
Estadísticas
|
|
</p>
|
|
<p className="mt-0.5 text-pretty text-sm text-foreground/80">
|
|
Asistencia y gestión de riesgo
|
|
</p>
|
|
</div>
|
|
<span className="shrink-0 rounded-xl bg-primary-soft px-3 py-1.5 text-xs font-semibold text-foreground/70">
|
|
Últimos 30 días
|
|
</span>
|
|
</div>
|
|
</LargeTitle>
|
|
|
|
{isPending ? (
|
|
<div className="flex items-center justify-center py-20">
|
|
<Loader2 className="size-8 animate-spin text-accent" />
|
|
</div>
|
|
) : null}
|
|
|
|
{hasFailed ? (
|
|
<div className="mt-6 rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
|
<h2 className="text-lg font-semibold">No pudimos cargar las estadísticas</h2>
|
|
<p className="mt-2 text-sm">Verificá tu conexión e intentá de nuevo.</p>
|
|
<Button
|
|
variant="outline"
|
|
className="mt-4"
|
|
onClick={() => {
|
|
void analyticsQuery.refetch()
|
|
void riskQuery.refetch()
|
|
}}
|
|
>
|
|
Reintentar
|
|
</Button>
|
|
</div>
|
|
) : null}
|
|
|
|
{showContent && analytics ? (
|
|
<>
|
|
<div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
|
<KpiCard
|
|
icon={<Percent className="size-5" />}
|
|
label="Asistencia promedio"
|
|
value={`${analytics.attendanceRate}%`}
|
|
hint="últimos 30 días"
|
|
/>
|
|
<KpiCard
|
|
icon={<CalendarCheck className="size-5" />}
|
|
label="Asistencias del mes"
|
|
value={analytics.totalPresent.toLocaleString('es-MX')}
|
|
hint={`${analytics.totalClasses} clases dictadas`}
|
|
/>
|
|
<KpiCard
|
|
icon={<DoorOpen className="size-5" />}
|
|
label="Cupos recuperados"
|
|
value={analytics.recoveredSlots.toLocaleString('es-MX')}
|
|
hint="por ausencias avisadas"
|
|
/>
|
|
</div>
|
|
|
|
<div className="mt-8">
|
|
<div className="flex items-center gap-2">
|
|
<Users className="size-5 text-accent" />
|
|
<h2 className="text-lg font-semibold text-primary">Alumnos en riesgo</h2>
|
|
{atRisk.length > 0 ? (
|
|
<Badge variant={atRisk.some((s) => s.riskLevel === 'HIGH') ? 'danger' : 'warning'}>
|
|
{atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'}
|
|
</Badge>
|
|
) : null}
|
|
</div>
|
|
<p className="mt-1 text-sm text-foreground/60">
|
|
Alumnos con ausencias consecutivas o baja asistencia mensual.
|
|
</p>
|
|
|
|
{atRisk.length === 0 ? (
|
|
<div className="mt-4 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
|
<p className="font-medium text-primary">¡Sin alumnos en riesgo!</p>
|
|
<p className="mt-1 text-sm text-foreground/60">
|
|
No hay ausencias consecutivas ni asistencia por debajo del 50%.
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<ul className="mt-4 space-y-3">
|
|
{atRisk.map((student) => (
|
|
<AtRiskStudentCard
|
|
key={student.attendeeId}
|
|
student={student}
|
|
menuOpen={menuOpenFor === student.attendeeId}
|
|
onToggleMenu={() =>
|
|
setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId)
|
|
}
|
|
onViewHistory={() => setHistoryStudent(student)}
|
|
onReengage={() => void handleReengage(student, groupName ?? 'tu clase')}
|
|
onRequestStatusAction={(action) => {
|
|
setStatusAction(action)
|
|
setMenuOpenFor(null)
|
|
}}
|
|
/>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
</>
|
|
) : null}
|
|
|
|
<AttendeeHistoryModal
|
|
student={historyStudent}
|
|
sessions={historyQuery.data?.sessions}
|
|
attendanceRate={historyQuery.data?.attendanceRate}
|
|
isPending={historyQuery.isPending}
|
|
isError={historyQuery.isError}
|
|
onClose={() => setHistoryStudent(null)}
|
|
/>
|
|
|
|
<StatusActionModal
|
|
action={statusAction}
|
|
isPending={statusMutation.isPending}
|
|
groupName={groupName}
|
|
onCancel={() => setStatusAction(null)}
|
|
onConfirm={() => {
|
|
if (statusAction) statusMutation.mutate(statusAction)
|
|
}}
|
|
/>
|
|
</section>
|
|
)
|
|
} |