feat: una sola regla de riesgo y preinscripciones pendientes en Inicio
- Estadísticas ("Alumnos en riesgo") y el job de reenganche usan la misma
regla de dominio que la lista de grupos e Inicio
(summarizeMemberAttendance). El armado del historial por alumno vive en
analytics/lib/member-attendance.ts y se borra el clasificador viejo
(racha o asistencia mensual < 50%).
- El badge de alumnos en riesgo muestra el motivo real (faltas seguidas,
días sin venir o asistencia en baja).
- GET /home devuelve pendingPreRegistrations por grupo (en la misma
consulta de grupos) y "Para atender" las lista con link a la ficha en
la pestaña Pendientes (?section=pending).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
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 4+4 trend 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,
|
||||
}));
|
||||
}
|
||||
Reference in New Issue
Block a user