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

@@ -2,10 +2,12 @@ export * from './lib/attendance-risk.js';
export * from './lib/phone.js';
export * from './lib/problem-details.js';
export * from './lib/result.js';
export * from './lib/student-alerts.js';
export * from './schemas/admin.js';
export * from './schemas/analytics.js';
export * from './schemas/attendance.js';
export * from './schemas/attendees.js';
export * from './schemas/attention.js';
export * from './schemas/billing.js';
export * from './schemas/country.js';
export * from './schemas/enums.js';

View File

@@ -36,26 +36,23 @@ export type AttendanceRiskLevel = AttendanceRiskLevelDto;
/**
* Thresholds of the risk rule. Moving these numbers changes the status light
* across the whole app, so this is the only source: nothing else hardcodes
* them.
* them. The windows count *marked* classes (PRESENT / ABSENT): an excused class
* or one with no record neither fills nor empties a window.
*/
export const ATTENDANCE_RISK_RULES = {
/** Unexcused absences in a streak from which the risk is high. */
highAbsenceStreak: 3,
/** Unexcused absences in a streak from which attention is needed. */
/** Size of the long window: "4 of the last 6 classes". */
highWindowSize: 6,
/** Absences inside the long window from which the risk is high. */
highWindowAbsences: 4,
/** Size of the short window: "2 recent absences" = 2 of the last 4. */
attentionWindowSize: 4,
/** Absences inside the short window from which attention is needed. */
attentionWindowAbsences: 2,
/** Unexcused absences in a streak that read as "they stopped coming" rather
* than as scattered absences. Only splits the reason, not the level. */
attentionAbsenceStreak: 2,
/** Days since last showing up to a class from which the risk is high. */
highInactivityDays: 10,
/** Size of each trend window: 4 recent classes vs the 4 before them. */
trendWindowSize: 4,
/** Marked classes needed to evaluate the trend. With fewer than this
* (6 = 4 + 2) any movement is noise, not a trend. */
trendMinClasses: 6,
/** How many classes have to be lost between one window and the other for
* the trend to count as "clearly" dropping. Counted in classes and not in
* percentage points on purpose: with a window of 4 the smallest possible
* jump is already 25 points, so a threshold in points would not tell
* "they missed a class" apart from "they are leaving". Two classes do. */
trendDropClasses: 2,
} as const;
/** A class of the group, seen from one attendee. */
@@ -98,8 +95,16 @@ export type MemberRiskSignals = {
attendanceRate: number | null;
/** Marked classes a verdict can be based on. */
markedClasses: number;
/** Absences over the last `highWindowSize` marked classes. */
highWindow: AbsenceWindow;
/** Absences over the last `attentionWindowSize` marked classes. */
attentionWindow: AbsenceWindow;
};
/** Absences inside the most recent marked classes. `classes` can be smaller
* than the window size when the attendee has less history. */
export type AbsenceWindow = { absences: number; classes: number };
export type UrgentMember = MemberRiskSignals & {
attendeeId: string;
fullName: string;
@@ -168,33 +173,43 @@ export function summarizeMemberAttendance(
const present = marked.filter((session) => session.status === 'PRESENT').length;
const attendanceRate = marked.length ? Math.round((present / marked.length) * 100) : null;
const level = classify(consecutiveAbsences, missedSpanDays(sessions, lastAttendedAt), marked);
const highWindow = absenceWindow(marked, ATTENDANCE_RISK_RULES.highWindowSize);
const attentionWindow = absenceWindow(marked, ATTENDANCE_RISK_RULES.attentionWindowSize);
return {
level,
level: classify(consecutiveAbsences, highWindow, attentionWindow),
consecutiveAbsences,
daysSinceLastAttendance,
attendanceRate,
markedClasses: marked.length,
highWindow,
attentionWindow,
};
}
/** Verdict: first the streak and the inactivity, then the trend. */
/** Verdict: the streak and the long window decide "high", the short one "attention". */
function classify(
consecutiveAbsences: number,
missedDays: number | null,
markedSessions: MemberClassSession[],
highWindow: AbsenceWindow,
attentionWindow: AbsenceWindow,
): AttendanceRiskLevel {
const rules = ATTENDANCE_RISK_RULES;
const inactive = missedDays !== null && missedDays > rules.highInactivityDays;
if (consecutiveAbsences >= rules.highAbsenceStreak || inactive) {
if (consecutiveAbsences >= rules.highAbsenceStreak || highWindow.absences >= rules.highWindowAbsences) {
return 'riesgo_alto';
}
if (consecutiveAbsences >= rules.attentionAbsenceStreak) {
if (attentionWindow.absences >= rules.attentionWindowAbsences) {
return 'atencion';
}
return isDeclining(markedSessions) ? 'atencion' : 'ok';
return 'ok';
}
/** Absences over the last `size` marked classes (`marked` comes oldest to newest). */
function absenceWindow(marked: MemberClassSession[], size: number): AbsenceWindow {
const window = marked.slice(-size);
return {
absences: window.filter((session) => session.status === 'ABSENT').length,
classes: window.length,
};
}
/**
@@ -239,8 +254,8 @@ export function getGroupAttendanceSummary(
};
/* Urgency order: worst level first; within the same level, whoever has more
consecutive absences, then whoever has gone the longest without showing
up, then whoever has the lower attendance. The name never breaks the tie:
consecutive absences, then more absences in the long window, then whoever
has gone the longest without showing up, then the lower attendance. The name never breaks the tie:
two people with the same signal keep the order they arrived in. */
function byUrgency(a: UrgentMember, b: UrgentMember): number {
const level = levelWeight(b.level) - levelWeight(a.level);
@@ -248,65 +263,15 @@ export function getGroupAttendanceSummary(
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
if (a.highWindow.absences !== b.highWindow.absences) {
return b.highWindow.absences - a.highWindow.absences;
}
const inactivity = (b.daysSinceLastAttendance ?? 0) - (a.daysSinceLastAttendance ?? 0);
if (inactivity !== 0) return inactivity;
return (a.attendanceRate ?? 101) - (b.attendanceRate ?? 101);
}
}
/**
* Attendance over the last 4 marked classes against the 4 before them. The
* drop-off is only declared when there is history for both windows: with one
* alone there is nothing to compare against, and guessing would flag attendees
* who are just starting out.
*
* With a window of 4, the smallest non-zero difference is one class, which is
* noise: that is why the threshold is `trendDropClasses` lost classes and not
* "any decrease".
*/
function isDeclining(sessions: MemberClassSession[]): boolean {
const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } =
ATTENDANCE_RISK_RULES;
if (sessions.length < minClasses) return false;
// `sessions` comes oldest to newest, so the recent window is the tail.
const recent = sessions.slice(-size);
const previous = sessions.slice(-size * 2, -size);
if (previous.length === 0 || recent.length === 0) return false;
return present(previous) - present(recent) >= dropClasses;
function present(window: MemberClassSession[]): number {
return window.filter((session) => session.status === 'PRESENT').length;
}
}
/**
* Inactivity as the group lived it: days from the last presence (or, if they
* never came, from their first class) to the most recent class they missed.
* It is measured against the classes and not against today on purpose: if the
* group stopped meeting, or nobody recorded attendance, those days are the
* group's, not the attendee's. Without this, a group that went 10 days without
* recording a class turned all its members red at once. `null` when they have
* not missed any class since their last presence.
*/
function missedSpanDays(
sessions: MemberClassSession[],
lastAttendedAt: string | undefined,
): number | null {
let lastMissedAt: string | undefined;
for (let index = sessions.length - 1; index >= 0; index -= 1) {
if (sessions[index].status === 'ABSENT') {
lastMissedAt = sessions[index].startsAt;
break;
}
}
const from = lastAttendedAt ?? sessions[0]?.startsAt;
if (!lastMissedAt || !from) return null;
const span = new Date(lastMissedAt).getTime() - new Date(from).getTime();
return span > 0 ? Math.floor(span / DAY_MS) : null;
}
/** Start of the most recent class with presence, or `undefined` if they have none. */
function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
for (let index = sessions.length - 1; index >= 0; index -= 1) {

View File

@@ -0,0 +1,194 @@
import type {
OverduePayment,
StudentAlert,
StudentAlertSeverity,
StudentAlertType,
} from '../schemas/attention.js';
import {
ATTENDANCE_RISK_RULES,
type MemberAttendance,
summarizeMemberAttendance,
} from './attendance-risk.js';
/* The alerts of one attendee, for the Grupos list and the "Requiere atención"
screen. Attendance reuses the single risk rule (`attendance-risk.ts`):
`riesgo_alto` is "urgente" and `atencion` is "vigilar", so a student can't be
urgent here and fine on Home. Payments only add their own threshold. */
/** Overdue-fee thresholds. The attendance ones live in `ATTENDANCE_RISK_RULES`. */
export const STUDENT_ALERT_RULES = {
/** Overdue fees from which the alert is urgent. */
urgentOverdue: 2,
/** Overdue fees from which the alert asks to keep an eye on it. */
watchOverdue: 1,
} as const;
export type StudentAlertInput = {
attendance: MemberAttendance;
overduePayments: Pick<OverduePayment, 'id' | 'dueDate'>[];
};
export type AlertResolution = { tipo: StudentAlertType; firma: string };
const MONTHS = [
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio',
'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
];
/** Every alert of the attendee, worst first. Empty when everything is fine. */
export function computeStudentAlerts(input: StudentAlertInput, now: Date = new Date()): StudentAlert[] {
const alerts: StudentAlert[] = [];
const attendance = attendanceAlert(input.attendance, now);
if (attendance) alerts.push(attendance);
const payment = paymentAlert(input.overduePayments);
if (payment) alerts.push(payment);
return alerts.sort(compareAlerts);
}
function attendanceAlert(member: MemberAttendance, now: Date): StudentAlert | null {
const signals = summarizeMemberAttendance(member, now);
if (signals.level === 'ok') return null;
const firma = lastAbsenceId(member, now);
if (!firma) return null;
const { consecutiveAbsences: streak, highWindow, attentionWindow } = signals;
if (signals.level === 'riesgo_alto') {
// The streak is the clearer story ("hace 3 clases que no viene"), so it
// wins over the window when both fire.
if (streak >= ATTENDANCE_RISK_RULES.highAbsenceStreak) {
return {
tipo: 'asistencia',
gravedad: 'urgente',
etiqueta: `${streak} seguidas`,
detalle: `No viene hace ${streak} clases seguidas.`,
firma,
peso: streak,
};
}
return {
tipo: 'asistencia',
gravedad: 'urgente',
etiqueta: `${highWindow.absences} faltas`,
detalle: `Faltó a ${highWindow.absences} de las últimas ${highWindow.classes} clases.`,
firma,
peso: highWindow.absences,
};
}
const { absences, classes } = attentionWindow;
return {
tipo: 'asistencia',
gravedad: 'vigilar',
etiqueta: `${absences} faltas`,
// When the absences are exactly the trailing streak, say so plainly.
detalle:
absences === streak
? `Faltó a las últimas ${absences} clases.`
: `Faltó a ${absences} de las últimas ${classes} clases.`,
firma,
peso: absences,
};
}
function paymentAlert(payments: StudentAlertInput['overduePayments']): StudentAlert | null {
const count = payments.length;
if (count < STUDENT_ALERT_RULES.watchOverdue) return null;
const sorted = [...payments].sort((a, b) => a.dueDate.localeCompare(b.dueDate));
const firma = sorted.map((payment) => payment.id).sort().join(',');
if (count >= STUDENT_ALERT_RULES.urgentOverdue) {
const months = [...new Set(sorted.map((payment) => monthName(payment.dueDate)))];
return {
tipo: 'pago',
gravedad: 'urgente',
etiqueta: `${count} cuotas`,
// Two fees in the same month (a re-created link) would read "las cuotas
// de octubre": fall back to the count.
detalle:
months.length === count
? `Debe las cuotas de ${joinList(months)}.`
: `Debe ${count} cuotas vencidas.`,
firma,
peso: count,
};
}
const [payment] = sorted;
return {
tipo: 'pago',
gravedad: 'vigilar',
etiqueta: 'Cuota vencida',
detalle: `La cuota de ${monthName(payment.dueDate)} venció el ${dayMonth(payment.dueDate)}.`,
firma,
peso: count,
};
}
/** Drops the alerts the professor already marked as resolved, as long as
* nothing changed since (same type and same signature). */
export function applyResolutions(alerts: StudentAlert[], resolutions: AlertResolution[]): StudentAlert[] {
return alerts.filter(
(alert) => !resolutions.some((resolved) => resolved.tipo === alert.tipo && resolved.firma === alert.firma),
);
}
/** Worst first: severity, then strength of the signal. Ties keep their order. */
export function compareAlerts(a: StudentAlert, b: StudentAlert): number {
const severity = severityWeight(b.gravedad) - severityWeight(a.gravedad);
if (severity !== 0) return severity;
return b.peso - a.peso;
}
/** The alert that represents the attendee where only one fits, or `null`. */
export function worstAlert(alerts: StudentAlert[]): StudentAlert | null {
return [...alerts].sort(compareAlerts)[0] ?? null;
}
/** Orders attendees by their worst alert, then by name. */
export function compareByWorstAlert<T extends { fullName: string; alerts: StudentAlert[] }>(a: T, b: T): number {
const worstA = worstAlert(a.alerts);
const worstB = worstAlert(b.alerts);
if (worstA && worstB) {
const byAlert = compareAlerts(worstA, worstB);
if (byAlert !== 0) return byAlert;
} else if (worstA || worstB) {
return worstA ? -1 : 1;
}
return a.fullName.localeCompare(b.fullName, 'es');
}
export function severityWeight(severity: StudentAlertSeverity): number {
return severity === 'urgente' ? 2 : 1;
}
/** Most recent past ABSENT class after enrollment: the attendance signature. */
function lastAbsenceId(member: MemberAttendance, now: Date): string | null {
const enrolledAt = new Date(member.enrolledAt).getTime();
let latest: { id: string; at: number } | null = null;
for (const session of member.sessions) {
if (session.status !== 'ABSENT') continue;
const at = new Date(session.startsAt).getTime();
if (at > now.getTime() || at < enrolledAt) continue;
if (!latest || at > latest.at) latest = { id: session.sessionId, at };
}
return latest?.id ?? null;
}
// `dueDate` is a calendar date the web sends at 12:00 UTC: reading it in UTC
// keeps the day the professor picked, whatever the server's time zone.
function monthName(iso: string): string {
return MONTHS[new Date(iso).getUTCMonth()];
}
function dayMonth(iso: string): string {
const date = new Date(iso);
return `${date.getUTCDate()}/${date.getUTCMonth() + 1}`;
}
function joinList(items: string[]): string {
if (items.length <= 1) return items.join('');
return `${items.slice(0, -1).join(', ')} y ${items.at(-1)}`;
}

View File

@@ -0,0 +1,72 @@
import { z } from 'zod';
const isoDateTimeSchema = z.string().datetime();
/* "Requiere atención": per-attendee alerts that the Grupos list and the
"Ver todos" screen read from the same endpoint. The rule that produces them
lives in `lib/student-alerts.ts`; this file only describes the transport. */
export const studentAlertTypeSchema = z.enum(['asistencia', 'pago']);
export type StudentAlertType = z.output<typeof studentAlertTypeSchema>;
export const studentAlertSeveritySchema = z.enum(['urgente', 'vigilar']);
export type StudentAlertSeverity = z.output<typeof studentAlertSeveritySchema>;
export const StudentAlertSchema = z.object({
tipo: studentAlertTypeSchema,
gravedad: studentAlertSeveritySchema,
/** Short reason for the pill: "4 faltas", "Cuota vencida". */
etiqueta: z.string(),
/** Natural-language line: "Faltó a 4 de las últimas 6 clases." */
detalle: z.string(),
/** What the alert is about (last absence / overdue payments). "Resuelto"
* stores it, so a new absence or a new overdue fee brings the alert back. */
firma: z.string(),
/** How strong the signal is inside its severity (absences, overdue fees);
* only used to order. */
peso: z.number().int().min(0),
});
export type StudentAlert = z.output<typeof StudentAlertSchema>;
export const OverduePaymentSchema = z.object({
id: z.string(),
amount: z.number(),
currency: z.string(),
dueDate: isoDateTimeSchema,
checkoutUrl: z.string().nullable(),
});
export type OverduePayment = z.output<typeof OverduePaymentSchema>;
export const AttentionMemberSchema = z.object({
attendeeId: z.string(),
fullName: z.string(),
/** `phone ?? guardianPhone`, as stored (national format). */
phone: z.string().nullable(),
/** The same phone in E.164 with the professor's country, ready for `wa.me`;
* `null` when it can't be normalized. */
whatsappPhone: z.string().nullable(),
/** Already filtered by "Resuelto" and ordered worst first. */
alerts: z.array(StudentAlertSchema),
overduePayments: z.array(OverduePaymentSchema),
});
export type AttentionMember = z.output<typeof AttentionMemberSchema>;
export const AttentionGroupSchema = z.object({
groupId: z.string(),
groupName: z.string(),
capacity: z.number().int().nullable(),
/** Every ACTIVE member, with or without alerts (the card draws them all). */
members: z.array(AttentionMemberSchema),
});
export type AttentionGroup = z.output<typeof AttentionGroupSchema>;
export const AttentionOverviewSchema = z.object({
groups: z.array(AttentionGroupSchema),
});
export type AttentionOverview = z.output<typeof AttentionOverviewSchema>;
export const ResolveAlertSchema = z.strictObject({
tipo: studentAlertTypeSchema,
firma: z.string().min(1),
});
export type ResolveAlert = z.output<typeof ResolveAlertSchema>;