|
|
|
|
@@ -1,99 +1,102 @@
|
|
|
|
|
import type { AttendanceRiskLevelDto, AttendanceStatus } from '../schemas/attendance.js';
|
|
|
|
|
|
|
|
|
|
/* Riesgo de abandono de un alumno, derivado del historial de asistencia.
|
|
|
|
|
Vive en `shared` y no importa nada de UI: lo usan el resumen por grupo del
|
|
|
|
|
backend, la tarjeta del listado y la sección de seguimiento del Inicio.
|
|
|
|
|
/* Dropout risk of an attendee, derived from the attendance history.
|
|
|
|
|
It lives in `shared` and imports nothing from the UI: the backend's
|
|
|
|
|
per-group summary, the listing card and the Home follow-up section use it.
|
|
|
|
|
|
|
|
|
|
Los umbrales viven todos acá, en un solo objeto. La regla es de negocio
|
|
|
|
|
("3 faltas seguidas = alguien se está yendo"), no de pantalla, así que un
|
|
|
|
|
componente nunca debería escribir el número crudo.
|
|
|
|
|
All the thresholds live here, in a single object. The rule is a business
|
|
|
|
|
rule ("3 consecutive absences = someone is leaving"), not a screen rule, so
|
|
|
|
|
a component should never write the raw number.
|
|
|
|
|
|
|
|
|
|
── Qué clase se considera ────────────────────────────────────────────────
|
|
|
|
|
El modelo actual guarda la asistencia como `Attendance` (una fila por alumno
|
|
|
|
|
y clase, con `PRESENT` / `ABSENT` / `EXCUSED`) colgando de un `ClassSession`
|
|
|
|
|
que tiene `startsAt`. No existe columna de "clase cancelada", así que las
|
|
|
|
|
dos señales de que una clase no computa son:
|
|
|
|
|
── Which classes count ───────────────────────────────────────────────────
|
|
|
|
|
The current model stores attendance as `Attendance` (one row per attendee
|
|
|
|
|
and class, with `PRESENT` / `ABSENT` / `EXCUSED`) hanging off a `ClassSession`
|
|
|
|
|
that has `startsAt`. There is no "class cancelled" column, so the two signals
|
|
|
|
|
that a class does not count are:
|
|
|
|
|
|
|
|
|
|
- `status: null` — la clase pasó y nadie registró asistencia. Sin dato no hay
|
|
|
|
|
ni asistencia ni ausencia: no entra en el promedio y **corta** la racha (si
|
|
|
|
|
no, un alumno con una clase sin registrar entre dos faltas tendría una
|
|
|
|
|
racha que nunca ocurrió).
|
|
|
|
|
- `status: 'EXCUSED'` — el alumno avisó la ausencia con anticipación y le
|
|
|
|
|
liberaron el lugar (`SlotRelease`). Es la clase que "no cuenta": corta la
|
|
|
|
|
racha igual que `PRESENT` y tampoco entra en el promedio.
|
|
|
|
|
- `status: null` — the class happened and nobody recorded attendance. With
|
|
|
|
|
no record there is neither attendance nor absence: it does not enter the
|
|
|
|
|
average and it **breaks** the streak (otherwise, an attendee with an
|
|
|
|
|
unrecorded class between two absences would have a streak that never
|
|
|
|
|
happened).
|
|
|
|
|
- `status: 'EXCUSED'` — the attendee gave notice ahead of time and the spot
|
|
|
|
|
was released to them (`SlotRelease`). This is the class that "does not
|
|
|
|
|
count": it breaks the streak just like `PRESENT` and it does not enter the
|
|
|
|
|
average either.
|
|
|
|
|
|
|
|
|
|
Sólo entran al cálculo las clases que (a) ya ocurrieron, `startsAt <= now`, y
|
|
|
|
|
(b) son posteriores al alta del alumno, `startsAt >= enrolledAt`. Un alumno
|
|
|
|
|
recién incorporado no es penalizado por clases en las que todavía no estaba
|
|
|
|
|
inscripto. */
|
|
|
|
|
Only the classes that (a) already happened, `startsAt <= now`, and (b) come
|
|
|
|
|
after the attendee's enrollment, `startsAt >= enrolledAt`, enter the
|
|
|
|
|
computation. A newly enrolled attendee is not penalized for classes they
|
|
|
|
|
were not enrolled in yet. */
|
|
|
|
|
|
|
|
|
|
/** El mismo tipo que valida `attendanceRiskLevelSchema` cuando el nivel viaja
|
|
|
|
|
* por la API: una sola definición para el dominio y el transporte. */
|
|
|
|
|
/** The same type `attendanceRiskLevelSchema` validates when the level travels
|
|
|
|
|
* over the API: a single definition for both domain and transport. */
|
|
|
|
|
export type AttendanceRiskLevel = AttendanceRiskLevelDto;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Umbrales de la regla de riesgo. Mover estos números cambia el semáforo de
|
|
|
|
|
* toda la app, así que son la única fuente: nada más los hardcodea.
|
|
|
|
|
* 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.
|
|
|
|
|
*/
|
|
|
|
|
export const ATTENDANCE_RISK_RULES = {
|
|
|
|
|
/** Faltas consecutivas sin justificar desde las cuales el riesgo es alto. */
|
|
|
|
|
/** Unexcused absences in a streak from which the risk is high. */
|
|
|
|
|
highAbsenceStreak: 3,
|
|
|
|
|
/** Faltas consecutivas sin justificar desde las cuales hay que mirar. */
|
|
|
|
|
/** Unexcused absences in a streak from which attention is needed. */
|
|
|
|
|
attentionAbsenceStreak: 2,
|
|
|
|
|
/** Días sin aparecer a una clase desde los cuales el riesgo es alto. */
|
|
|
|
|
/** Days since last showing up to a class from which the risk is high. */
|
|
|
|
|
highInactivityDays: 10,
|
|
|
|
|
/** Tamaño de cada ventana de la tendencia: 4 clases recientes vs 4 anteriores. */
|
|
|
|
|
/** Size of each trend window: 4 recent classes vs the 4 before them. */
|
|
|
|
|
trendWindowSize: 4,
|
|
|
|
|
/** Clases con dato necesarias para evaluar la tendencia. Con menos que esto
|
|
|
|
|
* (6 = 4 + 2) cualquier movimiento es ruido, no tendencia. */
|
|
|
|
|
/** Marked classes needed to evaluate the trend. With fewer than this
|
|
|
|
|
* (6 = 4 + 2) any movement is noise, not a trend. */
|
|
|
|
|
trendMinClasses: 6,
|
|
|
|
|
/** Cuántas clases hay que haber perdido entre una ventana y la otra para que
|
|
|
|
|
* la tendencia cuente como "claramente" a la baja. Se cuenta en clases y no
|
|
|
|
|
* en puntos porcentuales a propósito: con ventana de 4 el salto más chico
|
|
|
|
|
* posible ya es de 25 puntos, así que un umbral en puntos no distinguiría
|
|
|
|
|
* "se le cayó una clase" de "se está yendo". Dos clases sí lo distingue. */
|
|
|
|
|
/** 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;
|
|
|
|
|
|
|
|
|
|
/** Una clase del grupo, vista desde un alumno. */
|
|
|
|
|
/** A class of the group, seen from one attendee. */
|
|
|
|
|
export type MemberClassSession = {
|
|
|
|
|
sessionId: string;
|
|
|
|
|
/** Instante real de la clase (ISO). */
|
|
|
|
|
/** Actual moment of the class (ISO). */
|
|
|
|
|
startsAt: string;
|
|
|
|
|
/** `null` cuando la clase pasó y no hay registro de asistencia. */
|
|
|
|
|
/** `null` when the class happened and there is no attendance record. */
|
|
|
|
|
status: AttendanceStatus | null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type MemberAttendance = {
|
|
|
|
|
attendeeId: string;
|
|
|
|
|
fullName: string;
|
|
|
|
|
/** Momento del alta en el grupo (`Attendee.createdAt`), ISO. */
|
|
|
|
|
/** Moment of enrollment in the group (`Attendee.createdAt`), ISO. */
|
|
|
|
|
enrolledAt: string;
|
|
|
|
|
/** Clases del grupo. Las funciones no asumen orden ni completitud. */
|
|
|
|
|
/** The group's classes. The functions assume neither order nor completeness. */
|
|
|
|
|
sessions: MemberClassSession[];
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type GroupAttendanceInput = {
|
|
|
|
|
groupId: string;
|
|
|
|
|
/** `null` cuando el grupo no tiene cupo definido. */
|
|
|
|
|
/** `null` when the group has no capacity defined. */
|
|
|
|
|
capacity: number | null;
|
|
|
|
|
/** Miembros esperando cupo (`GroupWaitlistEntry` en PENDING). */
|
|
|
|
|
/** Members waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
|
|
|
|
waitlistCount: number;
|
|
|
|
|
members: MemberAttendance[];
|
|
|
|
|
/** Momento de referencia. Por defecto `new Date()`. */
|
|
|
|
|
/** Reference moment. Defaults to `new Date()`. */
|
|
|
|
|
now?: Date;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export type MemberRiskSignals = {
|
|
|
|
|
level: AttendanceRiskLevel;
|
|
|
|
|
/** Faltas consecutivas sin justificar, contadas desde la clase más reciente. */
|
|
|
|
|
/** Unexcused absences in a streak, counted from the most recent class. */
|
|
|
|
|
consecutiveAbsences: number;
|
|
|
|
|
/** Días desde la última clase con presencia, o `null` si nunca asistió a
|
|
|
|
|
* ninguna clase elegible. */
|
|
|
|
|
/** Days since the last class with presence, or `null` if they never attended
|
|
|
|
|
* any eligible class. */
|
|
|
|
|
daysSinceLastAttendance: number | null;
|
|
|
|
|
/** Asistencia 0..100 sobre las clases con dato, o `null` si no hay ninguna. */
|
|
|
|
|
/** Attendance 0..100 over the marked classes, or `null` if there are none. */
|
|
|
|
|
attendanceRate: number | null;
|
|
|
|
|
/** Clase con dato sobre las cuales se puede emitir un juicio. */
|
|
|
|
|
/** Marked classes a verdict can be based on. */
|
|
|
|
|
markedClasses: number;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
@@ -106,23 +109,23 @@ export type GroupAttendanceSummary = {
|
|
|
|
|
riesgoAlto: number;
|
|
|
|
|
atencion: number;
|
|
|
|
|
ok: number;
|
|
|
|
|
/** Lugares del cupo sin ocupar. Con el grupo lleno o sin cupo, 0. */
|
|
|
|
|
/** Free spots in the capacity. 0 when the group is full or has no capacity. */
|
|
|
|
|
libres: number;
|
|
|
|
|
/** Miembros esperando cupo. */
|
|
|
|
|
/** Members waiting for a spot. */
|
|
|
|
|
enEspera: number;
|
|
|
|
|
/** Miembros que hay que mirar primero, ordenados de peor a mejor. */
|
|
|
|
|
/** Members to look at first, ordered worst to best. */
|
|
|
|
|
urgentes: UrgentMember[];
|
|
|
|
|
/** El peor nivel presente en el grupo, o `null` si el grupo está vacío. */
|
|
|
|
|
/** The worst level present in the group, or `null` if the group is empty. */
|
|
|
|
|
peorNivel: AttendanceRiskLevel | null;
|
|
|
|
|
/** Asistencia promedio del grupo 0..100 sobre las clases con dato, o `null`. */
|
|
|
|
|
/** Group average attendance 0..100 over the marked classes, or `null`. */
|
|
|
|
|
asistencia: number | null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Nivel de riesgo de un alumno. Es el atajo a `summarizeMemberAttendance` para
|
|
|
|
|
* cuando solo hace falta el semáforo.
|
|
|
|
|
* Risk level of an attendee. Shortcut to `summarizeMemberAttendance` for when
|
|
|
|
|
* only the status light is needed.
|
|
|
|
|
*/
|
|
|
|
|
export function getMemberAttendanceRisk(
|
|
|
|
|
member: MemberAttendance,
|
|
|
|
|
@@ -131,31 +134,31 @@ export function getMemberAttendanceRisk(
|
|
|
|
|
return summarizeMemberAttendance(member, now).level;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Todas las señales de un alumno, no solo el veredicto. */
|
|
|
|
|
/** All the signals of an attendee, not just the verdict. */
|
|
|
|
|
export function summarizeMemberAttendance(
|
|
|
|
|
member: MemberAttendance,
|
|
|
|
|
now: Date = new Date(),
|
|
|
|
|
): MemberRiskSignals {
|
|
|
|
|
const sessions = eligibleSessions(member, now);
|
|
|
|
|
|
|
|
|
|
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que la
|
|
|
|
|
// racha se cuenta desde el final. PRESENT, EXCUSED y las clases sin registro
|
|
|
|
|
// cortan la cadena: una clase justificada o sin dato no es una falta más.
|
|
|
|
|
// `eligibleSessions` returns oldest to newest, so the streak is counted from
|
|
|
|
|
// the end. PRESENT, EXCUSED and classes with no record break the chain: an
|
|
|
|
|
// excused class or one with no record is not one more absence.
|
|
|
|
|
let consecutiveAbsences = 0;
|
|
|
|
|
for (let index = sessions.length - 1; index >= 0; index -= 1) {
|
|
|
|
|
if (sessions[index].status !== 'ABSENT') break;
|
|
|
|
|
consecutiveAbsences += 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que
|
|
|
|
|
// "la última clase con presencia" es la primera que aparece yendo desde el
|
|
|
|
|
// final. (Se recorre al revés y no con `findLast` porque el target del repo es
|
|
|
|
|
// ES2022 y ese método es ES2023.)
|
|
|
|
|
// `eligibleSessions` returns oldest to newest, so "the last class with
|
|
|
|
|
// presence" is the first one found walking from the end. (It walks backwards
|
|
|
|
|
// instead of using `findLast` because the repo targets ES2022 and that
|
|
|
|
|
// method is ES2023.)
|
|
|
|
|
const lastAttendedAt = lastPresentAt(sessions);
|
|
|
|
|
|
|
|
|
|
// Si nunca asistió a ninguna clase elegible, la referencia es la última clase
|
|
|
|
|
// que tuvo: "hace cuánto no lo vemos" sigue siendo cierto, y evita que un
|
|
|
|
|
// alumno con dos faltas de hace dos meses quede en verde para siempre.
|
|
|
|
|
// If they never attended any eligible class, the reference is the last class
|
|
|
|
|
// they had: "how long have we not seen them" still holds, and it keeps an
|
|
|
|
|
// attendee with two absences from two months ago from staying green forever.
|
|
|
|
|
const reference = lastAttendedAt ?? sessions.at(-1)?.startsAt;
|
|
|
|
|
const daysSinceLastAttendance = reference
|
|
|
|
|
? Math.floor((now.getTime() - new Date(reference).getTime()) / DAY_MS)
|
|
|
|
|
@@ -176,7 +179,7 @@ export function summarizeMemberAttendance(
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Veredicto: primero la racha y la inactividad, después la tendencia. */
|
|
|
|
|
/** Verdict: first the streak and the inactivity, then the trend. */
|
|
|
|
|
function classify(
|
|
|
|
|
consecutiveAbsences: number,
|
|
|
|
|
daysSinceLastAttendance: number | null,
|
|
|
|
|
@@ -197,12 +200,12 @@ function classify(
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Conteo por nivel del grupo, lugares libres y los miembros más urgentes.
|
|
|
|
|
* Count per level for the group, free spots and the most urgent members.
|
|
|
|
|
*
|
|
|
|
|
* `libres` se acota a 0 porque el detalle cuenta todos los miembros, sin
|
|
|
|
|
* filtro de estado: un grupo con más miembros que lugares (o con el cupo sin
|
|
|
|
|
* definir) tiene 0 libres, nunca negativos. Un grupo vacío tiene los tres
|
|
|
|
|
* conteos en 0, `libres` igual al cupo y `peorNivel` en `null`.
|
|
|
|
|
* `libres` is clamped to 0 because the detail page counts every member, with
|
|
|
|
|
* no status filter: a group with more members than spots (or with no capacity
|
|
|
|
|
* defined) has 0 free, never negative ones. An empty group has all three counts
|
|
|
|
|
* at 0, `libres` equal to the capacity and `peorNivel` at `null`.
|
|
|
|
|
*/
|
|
|
|
|
export function getGroupAttendanceSummary(
|
|
|
|
|
group: GroupAttendanceInput,
|
|
|
|
|
@@ -216,8 +219,8 @@ export function getGroupAttendanceSummary(
|
|
|
|
|
const riesgoAlto = urgentes.filter((member) => member.level === 'riesgo_alto').length;
|
|
|
|
|
const atencion = urgentes.filter((member) => member.level === 'atencion').length;
|
|
|
|
|
|
|
|
|
|
// Una parte de los miembros ya tiene señal: el promedio entre los que sí
|
|
|
|
|
// tienen. Los alumnos sin ninguna clase registrada no mueven la aguja.
|
|
|
|
|
// Part of the members already have a signal: the average is over the ones
|
|
|
|
|
// that do. Attendees with no recorded class do not move the needle.
|
|
|
|
|
const rates = urgentes
|
|
|
|
|
.map((member) => member.attendanceRate)
|
|
|
|
|
.filter((rate): rate is number => rate !== null);
|
|
|
|
|
@@ -237,10 +240,10 @@ export function getGroupAttendanceSummary(
|
|
|
|
|
asistencia,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/* Orden de urgencia: peor nivel primero; dentro del mismo nivel, quien
|
|
|
|
|
tiene más faltas seguidas, después quien hace más que no aparece, después
|
|
|
|
|
quien tiene menos asistencia. El nombre nunca desempata: dos personas con
|
|
|
|
|
la misma señal mantienen el orden en que llegaron. */
|
|
|
|
|
/* 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:
|
|
|
|
|
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);
|
|
|
|
|
if (level !== 0) return level;
|
|
|
|
|
@@ -254,21 +257,21 @@ export function getGroupAttendanceSummary(
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Asistencia de las últimas 4 clases con dato contra las 4 anteriores. Solo se
|
|
|
|
|
* declara la caída cuando hay historia para las dos ventanas: con una sola no
|
|
|
|
|
* hay contra qué comparar, y adivinar sería marcar alumnos que recién empiezan.
|
|
|
|
|
* 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.
|
|
|
|
|
*
|
|
|
|
|
* Con ventana de 4, la diferencia mínima no nula es de una clase, que es ruido:
|
|
|
|
|
* por eso el umbral es de `trendDropClasses` clases perdidas y no de "cualquier
|
|
|
|
|
* descenso".
|
|
|
|
|
* 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` viene de más antigua a más reciente, así que la ventana
|
|
|
|
|
// reciente es la cola.
|
|
|
|
|
// `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;
|
|
|
|
|
@@ -280,7 +283,7 @@ function isDeclining(sessions: MemberClassSession[]): boolean {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Inicio de la clase con presencia más reciente, o `undefined` si no tiene ninguna. */
|
|
|
|
|
/** 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) {
|
|
|
|
|
if (sessions[index].status === 'PRESENT') return sessions[index].startsAt;
|
|
|
|
|
@@ -288,7 +291,7 @@ function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Clases que ya ocurrieron y en las que el alumno ya estaba inscripto. */
|
|
|
|
|
/** Classes that already happened and in which the attendee was already enrolled. */
|
|
|
|
|
function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSession[] {
|
|
|
|
|
const enrolledAt = new Date(member.enrolledAt).getTime();
|
|
|
|
|
const nowMs = now.getTime();
|
|
|
|
|
@@ -301,7 +304,7 @@ function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSessi
|
|
|
|
|
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Clase con dato: sin `EXCUSED` (no computa) y sin nula (no hay registro). */
|
|
|
|
|
/** Marked class: neither `EXCUSED` (does not count) nor null (no record). */
|
|
|
|
|
function isMarked(session: MemberClassSession): boolean {
|
|
|
|
|
return session.status === 'PRESENT' || session.status === 'ABSENT';
|
|
|
|
|
}
|
|
|
|
|
|