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>
This commit is contained in:
Jose Selesan
2026-10-27 16:35:07 -03:00
parent 90f31290d4
commit b99bc4d519
48 changed files with 2333 additions and 1379 deletions

View File

@@ -100,7 +100,7 @@ describe('GET /groups-risk/overview', () => {
});
});
it('cuenta el motivo: faltas seguidas o inactividad, sin repetir alumnos', async () => {
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'),
@@ -122,10 +122,13 @@ describe('GET /groups-risk/overview', () => {
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'PRESENT', at(3)),
// A single absence, but 14 days between their last presence and the
// class they missed (the ones in between have no record): inactivity.
// 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', 's7', 'PRESENT', at(15)),
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)),
@@ -268,8 +271,9 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
{ 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 and the group would land in attention; the
// middle class happened and has no record, so the real streak is 1.
// 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)),
@@ -280,13 +284,13 @@ it('una clase sin registro corta la racha: no son faltas seguidas', async () =>
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(0);
expect(items[0].ok).toBe(1);
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: 'ok',
level: 'atencion',
consecutiveAbsences: 1,
daysSinceLastAttendance: 1,
// Both marked classes were absences; the middle one does not go into the average.
@@ -340,7 +344,8 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
// 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.
// 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)),
@@ -350,14 +355,14 @@ it('una clase sin registrar después de las faltas las borra: la racha mira hast
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(0);
expect(items[0].atencion).toBe(1);
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].ok).toBe(1);
expect(items[0].absenceStreakCount).toBe(0);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'ok',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 0,

View File

@@ -14,9 +14,7 @@ import {
Two test-scaffold helpers:
- `dense` puts the classes on consecutive days, so that "how long since we
saw them" is always close by and the case isolates the rule it claims to
test (one class a week would trip the inactivity threshold almost always).
- `dense` puts the classes on consecutive days.
- `series` honors the offsets it is given, for the cases that do need gaps.
All dates hang off a fixed `NOW`: the function takes the moment as an
@@ -98,83 +96,46 @@ describe('getMemberAttendanceRisk', () => {
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok');
});
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
// A single absence, the most recent one: the streak doesn't reach. What drives
// the level is the time since they last showed up.
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
it('4 faltas en las últimas 6 clases dan riesgo alto aunque no haya racha', () => {
const { highWindowAbsences, highWindowSize } = ATTENDANCE_RISK_RULES;
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.daysSinceLastAttendance).toBe(30);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.highWindow).toEqual({ absences: highWindowAbsences, classes: highWindowSize });
expect(señales.level).toBe('riesgo_alto');
});
it('sin faltas después de la última presencia, la inactividad no cuenta', () => {
// The group stopped recording classes (or didn't meet): 30 days since the
// last presence, but the attendee missed nothing.
it('3 faltas en las últimas 6 sin racha son atención, no riesgo alto', () => {
const alumno = member(dense(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.highWindow.absences).toBe(3);
expect(señales.attentionWindow).toEqual({ absences: 2, classes: 4 });
expect(señales.level).toBe('atencion');
});
it('2 faltas en las últimas 4 clases dan atención', () => {
const alumno = member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT']));
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion');
});
it('una sola falta reciente no alcanza', () => {
const alumno = member(dense(['ABSENT', 'ABSENT', 'PRESENT', 'PRESENT', 'ABSENT', 'PRESENT']));
// The two old absences fall outside the short window (last 4).
expect(summarizeMemberAttendance(alumno, NOW).attentionWindow.absences).toBe(1);
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
});
it('los días sin venir se informan pero no mueven el nivel', () => {
// The group stopped recording classes: 30 days since the last presence,
// but the attendee missed nothing.
const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.daysSinceLastAttendance).toBe(30);
expect(señales.level).toBe('ok');
});
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
// Two streak absences, the latest one yesterday: attention comes from the
// streak. Inactivity is measured from the last presence to the latest
// missed class, so exactly 10 days there does not move the level.
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
).toBe('atencion');
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 2]])), NOW),
).toBe('riesgo_alto');
});
it('la inactividad se mide contra las clases que faltó, no contra hoy', () => {
// They missed one class 20 days ago and the group hasn't met since: 25 days
// without seeing them, but only 5 of those had a class they skipped.
const alumno = member(series([['ABSENT', 20], ['PRESENT', 25]]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.daysSinceLastAttendance).toBe(25);
expect(señales.level).toBe('ok');
});
it('una tendencia a la baja da atención', () => {
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
// the only thing that can raise the alert.
const candidato = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
]));
const señales = summarizeMemberAttendance(candidato, NOW);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.daysSinceLastAttendance).toBe(1);
expect(señales.level).toBe('atencion');
});
it('perder una sola clase no es tendencia', () => {
// Same case as the previous one with one class fewer missed in the recent
// window: 3 of 4 against 4 of 4. That's noise, not a drop-off.
const estable = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
]));
expect(getMemberAttendanceRisk(estable, NOW)).toBe('ok');
});
it('la tendencia necesita historia para las dos ventanas', () => {
// 5 marked classes: the previous window would be left with a single one, so
// there is nothing to compare against.
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
});
it('la racha manda sobre la tendencia', () => {
// 16 classes: the 4 before those are at 100%, and the last 4 have 3 back-to-back
// absences and one attended class. The trend alone would give attention;
// the 3 trailing absences give high risk, which is what has to win.
it('tres faltas seguidas son riesgo alto con buena historia detrás', () => {
// 16 classes at 81%: the 3 trailing absences are what decides the level.
const alumno = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
@@ -187,13 +148,13 @@ describe('getMemberAttendanceRisk', () => {
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
// Absent, the middle one has no record, absent again. The real streak
// is one, not two.
// is one, not two; the two absences still fill the short window.
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(conHueco, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
expect(señales.level).toBe('atencion');
});
it('una clase justificada es la clase que no cuenta', () => {
@@ -204,13 +165,14 @@ describe('getMemberAttendanceRisk', () => {
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
expect(señales.attentionWindow).toEqual({ absences: 2, classes: 2 });
});
it('avisar de la falta tampoco encadena las de alrededor', () => {
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0);
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
// No streak, but the two absences are still recent: attention, not high.
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('atencion');
});
it('no le importa el orden en que llegan las clases', () => {

View File

@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { Prisma } from '@generated/prisma/client';
import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case';
import { ResolveStudentAlert } from '@/modules/attention/features/resolve/use-case';
const NOW = new Date('2026-10-27T20:00:00.000Z');
const DAY_MS = 24 * 60 * 60 * 1000;
const at = (days: number) => new Date(NOW.getTime() - days * DAY_MS);
const db = {
group: { findMany: mock() },
attendee: { findMany: mock(), findFirst: mock() },
classSession: { findMany: mock() },
attendance: { findMany: mock() },
payment: { findMany: mock() },
attendeeAlertResolution: { findMany: mock(), upsert: mock() },
user: { findUnique: mock() },
};
function overview() {
return new GetAttentionOverview({ db: db as never, now: NOW });
}
beforeEach(() => {
for (const delegate of Object.values(db)) {
for (const fn of Object.values(delegate)) fn.mockReset();
}
});
describe('GetAttentionOverview', () => {
it('sin grupos no consulta nada más', async () => {
db.group.findMany.mockResolvedValue([]);
const result = await overview().execute('user-1');
expect(result).toEqual({ ok: true, value: { groups: [] } });
expect(db.attendee.findMany).not.toHaveBeenCalled();
});
it('devuelve todos los miembros con sus alertas, sin las resueltas', async () => {
db.user.findUnique.mockResolvedValue({ country: 'AR' });
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
db.attendee.findMany.mockResolvedValue([
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) },
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) },
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) },
]);
db.classSession.findMany.mockResolvedValue([
{ id: 's1', groupId: 'g1', startsAt: at(1) },
{ id: 's2', groupId: 'g1', startsAt: at(3) },
{ id: 's3', groupId: 'g1', startsAt: at(5) },
]);
const row = (attendeeId: string, sessionId: string, status: string, days: number) => ({
attendeeId,
classSessionId: sessionId,
status,
classSession: { startsAt: at(days) },
});
db.attendance.findMany.mockResolvedValue([
row('a1', 's1', 'ABSENT', 1),
row('a1', 's2', 'ABSENT', 3),
row('a1', 's3', 'ABSENT', 5),
// Valentina missed two classes, but the professor already resolved it.
row('a2', 's1', 'ABSENT', 1),
row('a2', 's2', 'ABSENT', 3),
row('a3', 's1', 'PRESENT', 1),
]);
db.payment.findMany.mockResolvedValue([
{
id: 'p1',
attendeeId: 'a2',
amount: new Prisma.Decimal('15000.00'),
currency: 'ARS',
dueDate: new Date('2026-10-10T12:00:00.000Z'),
checkoutUrl: 'https://mp.test/p1',
},
]);
db.attendeeAlertResolution.findMany.mockResolvedValue([
{ attendeeId: 'a2', kind: 'ATTENDANCE', signature: 's1' },
]);
const result = await overview().execute('user-1');
if (!result.ok) throw new Error('expected ok');
const [group] = result.value.groups;
expect(group).toMatchObject({ groupId: 'g1', groupName: 'Natación', capacity: 30 });
expect(group.members.map((member) => member.attendeeId)).toEqual(['a1', 'a2', 'a3']);
const [agustina, valentina, felipe] = group.members;
expect(agustina.phone).toBe('1155550000');
expect(agustina.whatsappPhone).toBe('+5491155550000');
expect(agustina.alerts).toMatchObject([{ tipo: 'asistencia', gravedad: 'urgente', etiqueta: '3 seguidas' }]);
expect(valentina.phone).toBe('1166660000');
expect(valentina.alerts).toMatchObject([{ tipo: 'pago', gravedad: 'vigilar', etiqueta: 'Cuota vencida' }]);
expect(valentina.overduePayments).toEqual([
{ id: 'p1', amount: 15000, currency: 'ARS', dueDate: '2026-10-10T12:00:00.000Z', checkoutUrl: 'https://mp.test/p1' },
]);
expect(felipe.alerts).toEqual([]);
});
});
describe('ResolveStudentAlert', () => {
it('guarda la firma con upsert por alumno y tipo', async () => {
db.attendee.findFirst.mockResolvedValue({ id: 'a1' });
const result = await new ResolveStudentAlert({ db: db as never }).execute('a1', 'user-1', {
tipo: 'pago',
firma: 'p1,p2',
});
expect(result).toEqual({ ok: true, value: { attendeeId: 'a1', tipo: 'pago', firma: 'p1,p2' } });
expect(db.attendeeAlertResolution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { attendeeId_kind: { attendeeId: 'a1', kind: 'PAYMENT' } },
create: expect.objectContaining({ signature: 'p1,p2', resolvedById: 'user-1' }),
}),
);
});
it('un alumno de un grupo ajeno es 404 y no escribe nada', async () => {
db.attendee.findFirst.mockResolvedValue(null);
const result = await new ResolveStudentAlert({ db: db as never }).execute('a9', 'user-1', {
tipo: 'asistencia',
firma: 's1',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.status).toBe(404);
expect(db.attendeeAlertResolution.upsert).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,193 @@
import { describe, expect, it } from 'bun:test';
import {
applyResolutions,
compareByWorstAlert,
computeStudentAlerts,
type MemberAttendance,
type MemberClassSession,
STUDENT_ALERT_RULES,
type StudentAlert,
worstAlert,
} from '@gruperly/shared';
/* The single source of the "Requiere atención" alerts. These tests pin the
thresholds (attendance through the shared risk rule, fees through
`STUDENT_ALERT_RULES`), the copy the screens show and the order. */
const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = new Date('2026-10-27T20:00:00.000Z');
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
type Status = MemberClassSession['status'];
/** Classes on consecutive days, oldest first; the last one is `ses_1`. */
function attendance(statuses: Status[]): MemberAttendance {
return {
attendeeId: 'at_1',
fullName: 'Agustina Pérez',
enrolledAt: daysAgo(365),
sessions: statuses.map((status, index) => ({
sessionId: `ses_${statuses.length - index}`,
startsAt: daysAgo(statuses.length - index),
status,
})),
};
}
const fee = (id: string, dueDate: string) => ({ id, dueDate });
function alertsFor(statuses: Status[], fees: { id: string; dueDate: string }[] = []) {
return computeStudentAlerts({ attendance: attendance(statuses), overduePayments: fees }, NOW);
}
describe('computeStudentAlerts: asistencia', () => {
it('sin faltas ni cuotas no hay alertas', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT'])).toEqual([]);
});
it('3 faltas seguidas son urgentes y lo dicen así', () => {
const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']);
expect(alert).toMatchObject({
tipo: 'asistencia',
gravedad: 'urgente',
etiqueta: '3 seguidas',
detalle: 'No viene hace 3 clases seguidas.',
firma: 'ses_1',
});
});
it('4 de las últimas 6 sin racha son urgentes', () => {
const [alert] = alertsFor(['PRESENT', 'ABSENT', 'ABSENT', 'PRESENT', 'ABSENT', 'ABSENT', 'PRESENT']);
expect(alert).toMatchObject({
gravedad: 'urgente',
etiqueta: '4 faltas',
detalle: 'Faltó a 4 de las últimas 6 clases.',
firma: 'ses_2',
});
});
it('2 faltas recientes son "a vigilar"', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])[0]).toMatchObject({
gravedad: 'vigilar',
etiqueta: '2 faltas',
detalle: 'Faltó a las últimas 2 clases.',
});
expect(alertsFor(['PRESENT', 'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT'])[0]).toMatchObject({
gravedad: 'vigilar',
detalle: 'Faltó a 2 de las últimas 4 clases.',
});
});
it('una sola falta no alcanza', () => {
expect(alertsFor(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])).toEqual([]);
});
it('las justificadas y las clases sin registro no cuentan como faltas', () => {
expect(alertsFor(['PRESENT', 'EXCUSED', 'ABSENT', null, 'EXCUSED'])).toEqual([]);
});
});
describe('computeStudentAlerts: pagos', () => {
it('1 cuota vencida es "a vigilar" con su fecha', () => {
expect(alertsFor([], [fee('pay_1', '2026-10-10T12:00:00.000Z')])).toEqual([
{
tipo: 'pago',
gravedad: 'vigilar',
etiqueta: 'Cuota vencida',
detalle: 'La cuota de octubre venció el 10/10.',
firma: 'pay_1',
peso: 1,
},
]);
});
it(`${STUDENT_ALERT_RULES.urgentOverdue} o más cuotas vencidas son urgentes y nombran los meses`, () => {
const [alert] = alertsFor(
[],
[fee('pay_b', '2026-10-10T12:00:00.000Z'), fee('pay_a', '2026-09-10T12:00:00.000Z')],
);
expect(alert).toMatchObject({
gravedad: 'urgente',
etiqueta: '2 cuotas',
detalle: 'Debe las cuotas de septiembre y octubre.',
firma: 'pay_a,pay_b',
});
});
it('con tres meses los separa con coma y "y"', () => {
const [alert] = alertsFor(
[],
[
fee('p1', '2026-08-10T12:00:00.000Z'),
fee('p2', '2026-09-10T12:00:00.000Z'),
fee('p3', '2026-10-10T12:00:00.000Z'),
],
);
expect(alert.detalle).toBe('Debe las cuotas de agosto, septiembre y octubre.');
});
it('dos cuotas del mismo mes caen al conteo', () => {
const [alert] = alertsFor([], [fee('p1', '2026-10-01T12:00:00.000Z'), fee('p2', '2026-10-20T12:00:00.000Z')]);
expect(alert.detalle).toBe('Debe 2 cuotas vencidas.');
});
});
describe('orden por gravedad', () => {
it('con varias alertas, la urgente va primero', () => {
const alerts = alertsFor(
['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'],
[fee('p1', '2026-09-10T12:00:00.000Z'), fee('p2', '2026-10-10T12:00:00.000Z')],
);
expect(alerts.map((alert) => [alert.tipo, alert.gravedad])).toEqual([
['pago', 'urgente'],
['asistencia', 'vigilar'],
]);
expect(worstAlert(alerts)?.tipo).toBe('pago');
});
it('ordena alumnos por su peor alerta, después por la fuerza y por nombre', () => {
const alert = (gravedad: StudentAlert['gravedad'], peso: number): StudentAlert => ({
tipo: 'asistencia',
gravedad,
etiqueta: '',
detalle: '',
firma: 'x',
peso,
});
const students = [
{ fullName: 'Zoe', alerts: [] },
{ fullName: 'Martina', alerts: [alert('vigilar', 2)] },
{ fullName: 'Tomás', alerts: [alert('urgente', 3)] },
{ fullName: 'Agustina', alerts: [alert('urgente', 4)] },
{ fullName: 'Bruno', alerts: [alert('vigilar', 2)] },
];
expect([...students].sort(compareByWorstAlert).map((student) => student.fullName)).toEqual([
'Agustina',
'Tomás',
'Bruno',
'Martina',
'Zoe',
]);
});
});
describe('applyResolutions', () => {
const statuses: Status[] = ['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'];
it('oculta la alerta resuelta mientras la firma sea la misma', () => {
const alerts = alertsFor(statuses);
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }])).toEqual([]);
});
it('una falta nueva cambia la firma y la alerta vuelve', () => {
const alerts = alertsFor([...statuses, 'ABSENT']);
expect(alerts[0].firma).toBe('ses_1');
// The resolution was stored when the last absence was `ses_2`.
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_2' }])).toHaveLength(1);
});
it('resolver la asistencia no oculta los pagos', () => {
const alerts = alertsFor(statuses, [fee('p1', '2026-10-10T12:00:00.000Z')]);
expect(applyResolutions(alerts, [{ tipo: 'asistencia', firma: 'ses_1' }]).map((a) => a.tipo)).toEqual(['pago']);
});
});