Files
gruperly/apps/backend/src/modules/analytics/lib/member-attendance.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

82 lines
3.5 KiB
TypeScript

import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared';
/* 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 6-class window and for
the attendance rate the card shows. */
export const MEMBER_HISTORY_LIMIT = 20;
export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date };
export type MemberSessionRow = { id: string; startsAt: Date };
export type MemberAttendanceRow = {
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
/**
* The input of the domain risk rule (`summarizeMemberAttendance` in shared) for
* one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the
* re-engagement job all build it here, so they can't disagree on who is at risk.
*
* `groupSessions` must come most recent first (as the queries order them).
*/
export function toMemberAttendance(
attendee: MemberAttendeeRow,
groupSessions: MemberSessionRow[],
attendances: MemberAttendanceRow[],
): MemberAttendance {
// If the attendee has attendances before their enrollment date in the DB
// (e.g. created today but with past classes already recorded), their
// effective join date is the first class they were marked for.
const earliestAttendance = attendances.reduce<Date | null>(
(earliest, att) =>
!earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest,
null,
);
const enrolledAt =
earliestAttendance && earliestAttendance < attendee.createdAt
? earliestAttendance
: attendee.createdAt;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
enrolledAt: enrolledAt.toISOString(),
sessions: memberSessions(groupSessions, attendances),
};
}
/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */
export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null {
if (level === 'riesgo_alto') return 'HIGH';
if (level === 'atencion') return 'MEDIUM';
return null;
}
/* The universe of classes is the group's, not the `Attendance` rows'.
Attendance is recorded attendee by attendee and only when someone marks a
class, so "this class happened and this attendee has no record" is a real
and frequent state, not an absence. If the list were built from the
attendance rows those classes wouldn't exist and the streak wouldn't break:
two absences separated by an unmarked class would count as three in a row.
The domain already treats them as neutral (`status: null`), so all that is
left here is to pick the right universe and keep the criterion on one side.
`sessions` comes from most recent to oldest, so keeping the first
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
and not global, so a group with a long history doesn't steal window from
the groups listed after it. */
function memberSessions(
sessions: MemberSessionRow[],
attendances: MemberAttendanceRow[],
): MemberClassSession[] {
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
sessionId: session.id,
startsAt: session.startsAt.toISOString(),
status: statusBySession.get(session.id) ?? null,
}));
}