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

@@ -0,0 +1,20 @@
-- CreateEnum
CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT');
-- CreateTable
CREATE TABLE "attendee_alert_resolutions" (
"id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"kind" "StudentAlertKind" NOT NULL,
"signature" TEXT NOT NULL,
"resolved_by_id" TEXT NOT NULL,
"resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind");
-- AddForeignKey
ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -90,11 +90,34 @@ model Attendee {
attendances Attendance[]
slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[]
@@index([groupId], map: "attendees_groupId_idx")
@@map("attendees")
}
enum StudentAlertKind {
ATTENDANCE
PAYMENT
}
// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
// it hides the alert while its signature (last absence / overdue fees) stays
// the same, so a new absence or a new overdue fee brings it back on its own.
model AttendeeAlertResolution {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
kind StudentAlertKind
signature String
resolvedById String @map("resolved_by_id")
resolvedAt DateTime @default(now()) @map("resolved_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@unique([attendeeId, kind])
@@map("attendee_alert_resolutions")
}
model Payment {
id String @id @default(cuid())
groupId String @map("group_id")

View File

@@ -16,6 +16,7 @@ import {
studentStatusRoutes,
} from './modules/analytics';
import { attendeesRoutes } from './modules/attendees';
import { attentionRoutes } from './modules/attention';
import { authRoutes } from './modules/auth';
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
import { classesRoutes } from './modules/classes';
@@ -65,6 +66,7 @@ api.route('/waitlist', waitlistRoutes);
api.route('/classes', classesRoutes);
api.route('/students', studentStatusRoutes);
api.route('/groups-risk', groupsRiskOverviewRoute);
api.route('/attention', attentionRoutes);
app.notFound((c) => {
return problemJson(c, notFoundProblem(c.req.path));

View File

@@ -3,7 +3,7 @@ import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberCla
/* How many classes we look back per attendee. That is the real ceiling of the
model: `class_sessions` are not created on their own, they get materialized
when someone opens "today's classes", so pulling years of rows makes no
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
sense. 20 classes is enough for the streak, for the 6-class window and for
the attendance rate the card shows. */
export const MEMBER_HISTORY_LIMIT = 20;

View File

@@ -0,0 +1,19 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetAttentionOverview } from './use-case';
const route = new Hono();
route.get('/', async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const useCase = new GetAttentionOverview();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,174 @@
import type { Prisma } from '@generated/prisma/client';
import type {
AttendanceStatus,
AttentionGroup,
AttentionMember,
AttentionOverview,
ProblemDetails,
Result,
StudentAlertType,
} from '@gruperly/shared';
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = {
db?: {
group: Prisma.GroupDelegate;
attendee: Prisma.AttendeeDelegate;
classSession: Prisma.ClassSessionDelegate;
attendance: Prisma.AttendanceDelegate;
payment: Prisma.PaymentDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
user: Prisma.UserDelegate;
};
now?: Date;
};
type GroupRow = { id: string; name: string; capacity: number | null };
type AttendeeRow = {
id: string;
groupId: string;
fullName: string;
phone: string | null;
guardianPhone: string | null;
createdAt: Date;
};
type SessionRow = { id: string; groupId: string; startsAt: Date };
type AttendanceRow = {
attendeeId: string;
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
type PaymentRow = {
id: string;
attendeeId: string;
amount: Prisma.Decimal;
currency: string;
dueDate: Date;
checkoutUrl: string | null;
};
type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string };
/* Every ACTIVE member of the user's groups with their alerts ("Requiere
atención"). The list screen draws all the avatars from here, so it returns
members without alerts too. The rule is `computeStudentAlerts` (shared) over
the same attendance input the risk overview builds (`toMemberAttendance`). */
export class GetAttentionOverview {
constructor(private readonly deps: GetAttentionOverviewDeps = {}) {}
async execute(userId: string): Promise<Result<AttentionOverview, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const groups = (await db.group.findMany({
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
select: { id: true, name: true, capacity: true },
orderBy: { createdAt: 'asc' },
})) as GroupRow[];
if (groups.length === 0) {
return ok({ groups: [] });
}
const groupIds = groups.map((group) => group.id);
const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([
// Phones are stored the way people write them (`11 2345-6789`): the
// professor's country settles the calling code, as in the WhatsApp jobs.
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>,
// Past classes only, most recent first: `toMemberAttendance` keeps the
// last 20 per attendee, more than the 6-class window needs.
db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { lte: now } },
select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>,
db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
}) as Promise<AttendanceRow[]>,
db.payment.findMany({
where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' } },
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
orderBy: { dueDate: 'asc' },
}) as Promise<PaymentRow[]>,
db.attendeeAlertResolution.findMany({
where: { attendee: { groupId: { in: groupIds } } },
select: { attendeeId: true, kind: true, signature: true },
}) as Promise<ResolutionRow[]>,
]);
const country = countryCodeSchema.safeParse(owner?.country);
const sessionsByGroup = groupBy(sessions, (session) => session.groupId);
const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId);
const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId);
const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId);
const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId);
const items: AttentionGroup[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
capacity: group.capacity,
members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => {
const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({
id: payment.id,
amount: Number(payment.amount),
currency: payment.currency,
dueDate: payment.dueDate.toISOString(),
checkoutUrl: payment.checkoutUrl,
}));
const alerts = computeStudentAlerts(
{
attendance: toMemberAttendance(
attendee,
sessionsByGroup.get(group.id) ?? [],
attendanceByAttendee.get(attendee.id) ?? [],
),
overduePayments,
},
now,
);
const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({
tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType,
firma: row.signature,
}));
const phone = attendee.phone ?? attendee.guardianPhone;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
phone,
whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null,
alerts: applyResolutions(alerts, resolved),
overduePayments,
};
}),
}));
return ok({ groups: items });
}
}
function groupBy<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
const map = new Map<string, T[]>();
for (const row of rows) {
const list = map.get(key(row)) ?? [];
list.push(row);
map.set(key(row), list);
}
return map;
}

View File

@@ -0,0 +1,23 @@
import type { ResolveAlert } from '@gruperly/shared';
import { ResolveAlertSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { ResolveStudentAlert } from './use-case';
const route = new Hono();
route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const payload = c.req.valid('json') as ResolveAlert;
const useCase = new ResolveStudentAlert();
const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,49 @@
import type { Prisma } from '@generated/prisma/client';
import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind';
type ResolveAlertDeps = {
db?: {
attendee: Prisma.AttendeeDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
};
};
export type ResolveAlertResult = ResolveAlert & { attendeeId: string };
/* "Resuelto": stores the signature of the alert the professor saw. One row per
attendee and type, overwritten on each resolve, so the table never grows past
two rows per attendee. An attendee outside the user's groups is a 404, not a
403: we don't confirm that the id exists. */
export class ResolveStudentAlert {
constructor(private readonly deps: ResolveAlertDeps = {}) {}
async execute(
attendeeId: string,
userId: string,
payload: ResolveAlert,
): Promise<Result<ResolveAlertResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput },
select: { id: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
const kind = ALERT_TYPE_TO_KIND[payload.tipo];
await db.attendeeAlertResolution.upsert({
where: { attendeeId_kind: { attendeeId, kind } },
create: { attendeeId, kind, signature: payload.firma, resolvedById: userId },
update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() },
});
return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma });
}
}

View File

@@ -0,0 +1 @@
export { default as attentionRoutes } from './routes';

View File

@@ -0,0 +1,13 @@
import type { StudentAlertKind } from '@generated/prisma/client';
import type { StudentAlertType } from '@gruperly/shared';
/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */
export const ALERT_KIND_TO_TYPE: Record<StudentAlertKind, StudentAlertType> = {
ATTENDANCE: 'asistencia',
PAYMENT: 'pago',
};
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
asistencia: 'ATTENDANCE',
pago: 'PAYMENT',
};

View File

@@ -0,0 +1,10 @@
import { Hono } from 'hono';
import getOverviewRoute from './features/get-overview/route';
import resolveRoute from './features/resolve/route';
const routes = new Hono();
routes.route('/', getOverviewRoute);
routes.route('/', resolveRoute);
export default routes;

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']);
});
});