Added routes
This commit is contained in:
219
apps/web/src/features/groups/analytics/AnalyticsView.tsx
Normal file
219
apps/web/src/features/groups/analytics/AnalyticsView.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Link, useParams } from '@tanstack/react-router'
|
||||
import type { StudentAtRiskDto } from '@gruperly/shared'
|
||||
import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react'
|
||||
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')
|
||||
}
|
||||
|
||||
const groupName = riskQuery.data?.groupName
|
||||
|
||||
if (analyticsQuery.isPending || riskQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-8 animate-spin text-accent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) {
|
||||
return (
|
||||
<div className="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>
|
||||
)
|
||||
}
|
||||
|
||||
const analytics = analyticsQuery.data
|
||||
const atRisk = riskQuery.data?.data ?? []
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-md lg:max-w-6xl">
|
||||
<Link
|
||||
to="/groups/$groupId"
|
||||
params={{ groupId }}
|
||||
className="mb-3 hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
Volver a {groupName ?? 'el grupo'}
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-primary">Estadísticas</h1>
|
||||
<p className="mt-2 text-sm text-foreground/60">
|
||||
Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}.
|
||||
</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>
|
||||
|
||||
<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>
|
||||
|
||||
<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>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user