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:
Jose Selesan
2026-10-27 11:28:21 -03:00
parent b12ffdda37
commit e6d405a71e
17 changed files with 297 additions and 278 deletions

View File

@@ -6,15 +6,11 @@ import type {
StudentAtRisk,
StudentsAtRisk,
} from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import {
classifyRisk,
lastAttendedAt,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetStudentsAtRiskDeps = {
@@ -24,6 +20,7 @@ type GetStudentsAtRiskDeps = {
type AttendanceStreamRow = {
attendeeId: string;
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
@@ -56,8 +53,10 @@ export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' |
/**
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
* the "Alumnos en riesgo" screen and the weekly re-engagement job, so both
* agree on who is at risk. Does not check access: callers do.
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
* with the same domain rule as the group listing and Home
* (`summarizeMemberAttendance`), so every screen agrees on who is at risk.
* Does not check access: callers do.
*/
export async function findStudentsAtRisk(
db: StudentsAtRiskDb,
@@ -69,16 +68,18 @@ export async function findStudentsAtRisk(
const [windowSessions, attendees, attendances] = await Promise.all([
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true },
select: { id: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true },
select: { id: true, fullName: true, phone: true, createdAt: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
@@ -91,20 +92,21 @@ export async function findStudentsAtRisk(
const atRisk: StudentAtRisk[] = [];
for (const attendee of attendees) {
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const consecutiveAbsences = trailingAbsentStreak(stream);
const rows = streamByAttendee.get(attendee.id) ?? [];
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
const riskLevel = toRiskLevel(signals.level);
if (!riskLevel) {
continue;
}
// Display only: the verdict is the domain's. The rate keeps counting
// unrecorded classes as missed, which is what "asistencia mensual" says.
const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
const consecutiveAbsences = signals.consecutiveAbsences;
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
if (!riskLevel) {
continue;
}
atRisk.push({
attendeeId: attendee.id,
fullName: attendee.fullName,