Files
gruperly/apps/backend/test/analytics-groups-risk.test.ts
Jose Selesan b99bc4d519 feat: rediseño de Grupos y pantalla "Requiere atención"
- Grupos: subtítulo con resumen (grupos · alumnos · lugares libres),
  sección "Requiere atención" con los 4 alumnos más urgentes y tarjetas
  con avatares (punteados por lugar libre en grupos chicos, superpuestos
  con "+N" en grandes; con alerta primero y anillo de gravedad).
- Pantalla nueva /groups/attention: filtros Todos/Asistencia/Pagos,
  secciones Urgente y A vigilar, Contactar / Enviar recordatorio por
  wa.me y "Resuelto" persistente con update optimista.
- FAB "Nuevo grupo" que se pliega al scrollear (respeta reduced motion);
  los toasts en mobile suben para no quedar debajo.
- Alertas centralizadas en computeStudentAlerts (shared). La regla de
  asistencia pasa a: urgente = 3 seguidas o 4 de las últimas 6; a vigilar
  = 2 de las últimas 4 (sin inactividad por días ni tendencia). Cuotas:
  1 vencida vigilar, 2+ urgente.
- Backend: GET /attention y POST /attention/:attendeeId/resolve; tabla
  attendee_alert_resolutions (la alerta vuelve si cambia la firma).
- Tokens de gravedad para claro y oscuro; se quita el indicador de pills.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:35:07 -03:00

430 lines
15 KiB
TypeScript

import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findMany: mock(),
},
attendee: {
findMany: mock(),
},
classSession: {
findMany: mock(),
},
attendance: {
findMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import { groupsRiskOverviewRoute } from '@/modules/analytics';
const userId = 'user-1';
const DAY_MS = 24 * 60 * 60 * 1000;
const now = Date.now();
const at = (offsetDays: number) => new Date(now - offsetDays * DAY_MS);
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/groups-risk', groupsRiskOverviewRoute);
return app;
}
describe('GET /groups-risk/overview', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('devuelve items vacíos si el usuario no tiene grupos', async () => {
prismaFetchGroupFindMany([]);
prismaFetchAttendeeFindMany([]);
prismaFetchClassSessionFindMany([]);
prismaFetchAttendanceFindMany([]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ items: [] });
});
it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', 'group-2')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
{ id: 's4', groupId: 'group-2', startsAt: at(1) },
]);
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
attendance('a-2', 's4', 'PRESENT', at(1)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
// `toMatchObject` because the item now also carries the per-level summary
// the card consumes; here we are testing the usual status light.
expect(await res.json()).toMatchObject({
items: [
{
groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'HIGH',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'NONE',
absenceStreakCount: 0,
lowAttendanceCount: 0,
},
],
});
});
it('cuenta el motivo: faltas seguidas o faltas sueltas, sin repetir alumnos', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
prismaFetchAttendeeFindMany([
attendee('a-1', 'group-1'),
attendee('a-2', 'group-1'),
attendee('a-3', 'group-1'),
attendee('b-1', 'group-2'),
]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
{ id: 's7', groupId: 'group-1', startsAt: at(15) },
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
]);
prismaFetchAttendanceFindMany([
// Two consecutive absences: counts toward the absence reason.
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'PRESENT', at(3)),
// No streak (they came to s2), but 4 of their last 5 classes missed:
// high risk through the window, not through the streak.
attendance('a-2', 's1', 'ABSENT', at(1)),
attendance('a-2', 's2', 'PRESENT', at(2)),
attendance('a-2', 's3', 'ABSENT', at(3)),
attendance('a-2', 's4', 'ABSENT', at(4)),
attendance('a-2', 's7', 'ABSENT', at(15)),
// Ok.
attendance('a-3', 's1', 'PRESENT', at(1)),
attendance('a-3', 's2', 'PRESENT', at(2)),
attendance('a-3', 's3', 'PRESENT', at(3)),
attendance('a-3', 's4', 'PRESENT', at(4)),
// Again via streak, in the other group.
attendance('b-1', 's5', 'ABSENT', at(1)),
attendance('b-1', 's6', 'ABSENT', at(2)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
items: [
{
groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'HIGH',
absenceStreakCount: 1,
lowAttendanceCount: 1,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'MEDIUM',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
],
});
});
});
/* What the listing card consumes. The status light above already had its
tests; what was missing was pinning the new payload against the same
endpoint, because that is the contract the frontend reads. */
it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
prismaFetchAttendeeFindMany([
attendee('a-1', 'group-1', 'Sofía Díaz'),
attendee('a-2', 'group-1', 'Diego Soto'),
attendee('a-3', 'group-1', 'Ana Ruiz'),
]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// The mock ignores `orderBy`, so the rows come most recent first, as Prisma
// would return them: the streak depends on that order.
// `at(n)` is n days back; the summary drops what has not happened yet, so
// the dates have to be in the past, not in the future.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
attendance('a-2', 's1', 'ABSENT', at(1)),
attendance('a-2', 's2', 'ABSENT', at(2)),
attendance('a-2', 's3', 'PRESENT', at(3)),
attendance('a-3', 's1', 'PRESENT', at(1)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0]).toMatchObject({
riesgoAlto: 1,
atencion: 1,
ok: 1,
// Capacity is 5 and there are 3 members, not 2: free spots are computed
// against capacity, not as "the ones with no signal at all".
libres: 2,
enEspera: 2,
// Average of the already-rounded per-person rates: 0, 33 and 100 → 44.
asistencia: 44,
});
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'riesgo_alto',
consecutiveAbsences: 3,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
{
attendeeId: 'a-2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 2,
// Counted from their last class they attended, not from the group's
// most recent one: theirs was 3 days ago.
daysSinceLastAttendance: 3,
attendanceRate: 33,
},
{
attendeeId: 'a-3',
fullName: 'Ana Ruiz',
level: 'ok',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 100,
},
]);
});
it('un grupo sin capacidad declarada no inventa lugares libres', async () => {
prismaFetchGroupFindMany([group('group-1', 'Sin cupo', null)]);
prismaFetchAttendeeFindMany([]);
prismaFetchClassSessionFindMany([]);
prismaFetchAttendanceFindMany([]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
items: [
{
riskLevel: 'NONE',
riesgoAlto: 0,
atencion: 0,
ok: 0,
libres: 0,
enEspera: 0,
asistencia: null,
urgentes: [],
},
],
});
});
it('una clase sin registro corta la racha: no son faltas seguidas', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// Absence, unmarked class, absence. Reading only the `Attendance` rows this
// would look like a streak of 2; the middle class happened and has no
// record, so the real streak is 1. The level is still attention, but because
// of the short window (2 absences in the last marked classes), not the streak.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's3', 'ABSENT', at(3)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].atencion).toBe(1);
expect(items[0].absenceStreakCount).toBe(0);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'atencion',
consecutiveAbsences: 1,
daysSinceLastAttendance: 1,
// Both marked classes were absences; the middle one does not go into the average.
attendanceRate: 0,
},
]);
});
it('las faltas pegadas hasta la última clase sí cuentan como racha', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// The streak is counted backwards from the most recent class, so they reach
// exactly the end: s1 and s2 back to back, and the one 3 days ago is
// unmarked, which falls before the streak and does not touch it.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(1);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'atencion',
consecutiveAbsences: 2,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
]);
});
it('una clase sin registrar después de las faltas las borra: la racha mira hasta la última clase', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// The same two back-to-back absences as the previous case, but the most
// recent class (s1) is the one with no record. Since the streak is counted
// from the end and "no record" is not an absence, there is no streak: the
// asymmetry is there on purpose, because it is the same thing that already
// happens with an excused class. The two absences still fill the short
// window, so the level is attention without a streak.
prismaFetchAttendanceFindMany([
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(1);
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].absenceStreakCount).toBe(0);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
]);
});
it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]);
// The attendee was created today (offset 0), but has 3 absences in classes 7, 3 and 1 days ago.
prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(3) },
{ id: 's3', groupId: 'group-1', startsAt: at(7) },
]);
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(3)),
attendance('a-1', 's3', 'ABSENT', at(7)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].riesgoAlto).toBe(1);
expect(items[0].riskLevel).toBe('HIGH');
expect(items[0].absenceStreakCount).toBe(1);
});
/* The use-case asks for `capacity` and the waitlist count to compute the
free spots, and `fullName` + `createdAt` of every attendee for the per-level
summary. The fixtures provide them so the older tests don't have to know
about that. */
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
return { id, name, capacity, _count: { waitlist: waiting } };
}
function attendee(id: string, groupId: string, fullName = id) {
return { id, groupId, fullName, createdAt: at(90) };
}
function prismaFetchGroupFindMany(rows: unknown[]) {
db.group.findMany.mockResolvedValue(rows);
}
function prismaFetchAttendeeFindMany(rows: unknown[]) {
db.attendee.findMany.mockResolvedValue(rows);
}
function prismaFetchClassSessionFindMany(rows: unknown[]) {
db.classSession.findMany.mockResolvedValue(rows);
}
function prismaFetchAttendanceFindMany(rows: unknown[]) {
db.attendance.findMany.mockResolvedValue(rows);
}
/* The `classSessionId` matters: the summary is built by cross-referencing the
group's class sessions with the attendance rows, and without that join every
class would have no record for everyone. */
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
}