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

@@ -4,30 +4,21 @@ import type {
GroupRiskLevel,
GroupRiskSummary,
GroupsRiskOverview,
MemberClassSession,
ProblemDetails,
Result,
UrgentMemberSummary,
} from '@gruperly/shared';
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
import {
ATTENDANCE_RISK_RULES,
getGroupAttendanceSummary,
ok,
URGENT_MEMBERS_LIMIT,
} from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import {
classifyRisk,
MIN_RISK_ABSENCE_STREAK,
MIN_RISK_MONTHLY_RATE,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
/* 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. */
const MEMBER_HISTORY_LIMIT = 20;
type GetGroupsRiskOverviewDeps = {
db?: {
group: Prisma.GroupDelegate;
@@ -54,10 +45,10 @@ type AttendanceRow = {
classSession: { startsAt: Date };
};
// Risk status light summary per group for the group listing.
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if
// any is at medium risk and NONE otherwise. The counters state the reason
// (consecutive absences or low attendance) so the listing can name it.
// Risk summary per group for the group listing and Home. Everything comes from
// the domain rule (`getGroupAttendanceSummary`): the status light is the worst
// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -117,75 +108,31 @@ export class GetGroupsRiskOverview {
const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
// Why there is risk, computed in the same pass: a member with an absence
// streak counts in the first counter and only there; the second one
// groups the members that don't reach a streak and are still below the
// attendance minimum.
const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>();
for (const attendee of attendees) {
const groupId = attendee.groupId;
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const streak = trailingAbsentStreak(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
sessionsByGroup.get(groupId)?.length ?? 0,
);
const riskLevel = classifyRisk(streak, monthlyRate);
if (!riskLevel) {
continue;
}
if (streak >= MIN_RISK_ABSENCE_STREAK) {
bump(absenceStreakCountByGroup, groupId);
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
bump(lowAttendanceCountByGroup, groupId);
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if (
riskLevel === 'HIGH' ||
(riskLevel === 'MEDIUM' && current === 'NONE')
) {
worstRiskByGroup.set(groupId, riskLevel);
}
}
const items: GroupRiskSummary[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
}));
const items: GroupRiskSummary[] = groups.map((group) =>
buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
);
return ok({ items });
}
}
/**
* The per-level summary consumed by the listing card and the Home follow-up
* section. It comes from `getGroupAttendanceSummary`, the same domain function
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
* The per-level summary consumed by the listing card and Home. It comes from
* `getGroupAttendanceSummary`, the same domain function that
* `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
* copies: one here and another in the client.
*
* `libres` and `enEspera` come from here and not from the `Attendee` count: the
* summary counts the group members and the card needs the capacity slots to
* paint the indicator.
*/
function buildSummaryFields(
function buildSummary(
group: GroupRow,
attendees: AttendeeRow[],
sessionsByGroup: Map<string, SessionRow[]>,
attendanceByAttendee: Map<string, AttendanceRow[]>,
now: Date,
) {
): GroupRiskSummary {
const resumen = getGroupAttendanceSummary({
groupId: group.id,
capacity: group.capacity,
@@ -193,35 +140,23 @@ function buildSummaryFields(
now,
members: attendees
.filter((attendee) => attendee.groupId === group.id)
.map((attendee) => {
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
// 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 = attendeeAttendances.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(
sessionsByGroup.get(group.id) ?? [],
attendeeAttendances,
),
};
}),
.map((attendee) =>
toMemberAttendance(
attendee,
sessionsByGroup.get(group.id) ?? [],
attendanceByAttendee.get(attendee.id) ?? [],
),
),
});
// Why there is risk, over every member and not only the urgent ones sent to
// the client. Disjoint: an absence streak counts in the first and only
// there; the second groups the rest (inactivity or a declining trend).
const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok');
const absenceStreakCount = atRisk.filter(
(member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak,
).length;
const urgentes: UrgentMemberSummary[] = resumen.urgentes
.slice(0, URGENT_MEMBERS_LIMIT)
.map((urgente) => ({
@@ -233,7 +168,14 @@ function buildSummaryFields(
attendanceRate: urgente.attendanceRate,
}));
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
return {
groupId: group.id,
groupName: group.name,
riskLevel,
absenceStreakCount,
lowAttendanceCount: atRisk.length - absenceStreakCount,
riesgoAlto: resumen.riesgoAlto,
atencion: resumen.atencion,
ok: resumen.ok,
@@ -244,10 +186,6 @@ function buildSummaryFields(
};
}
function bump(counter: Map<string, number>, key: string) {
counter.set(key, (counter.get(key) ?? 0) + 1);
}
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) {
@@ -257,25 +195,3 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
}
return byAttendee;
}
/* 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: SessionRow[], attendances: AttendanceRow[]): 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,
}));
}

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,

View 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,
}));
}

View File

@@ -3,27 +3,6 @@ export type AttendanceStreamEntry = {
occurredAt: Date;
};
export type RiskLevel = 'HIGH' | 'MEDIUM';
/** Minimum streak of unexcused absences that already triggers risk. */
export const MIN_RISK_ABSENCE_STREAK = 2;
/** Monthly attendance (30-day window) below which there is risk. */
export const MIN_RISK_MONTHLY_RATE = 50;
// Counts the consecutive unexcused absences from the most recent class.
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
let streak = 0;
for (const entry of entries) {
if (entry.status !== 'ABSENT') {
break;
}
streak += 1;
}
return streak;
}
// Date of the last class the attendee showed up to (PRESENT), or null.
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
for (const entry of entries) {
@@ -46,17 +25,3 @@ export function monthlyAttendanceRate(
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
return Math.round((present / totalSessions) * 100);
}
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
export function classifyRisk(
consecutiveAbsences: number,
monthlyRate: number,
): RiskLevel | null {
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
return 'HIGH';
}
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
return 'MEDIUM';
}
return null;
}

View File

@@ -24,7 +24,7 @@ type GroupSummaryRecord = {
name: string;
days: NextClass['days'];
time: string | null;
_count: { attendees: number };
_count: { attendees: number; preRegistrations: number };
};
export class GetHomeSummary {
@@ -42,7 +42,11 @@ export class GetHomeSummary {
name: true,
days: true,
time: true,
_count: { select: { attendees: true } },
// The pending pre-registrations ride on the same query: Home lists
// them under "Para atender" without one request per group.
_count: {
select: { attendees: true, preRegistrations: { where: { status: 'PENDING' } } },
},
},
});
@@ -51,6 +55,7 @@ export class GetHomeSummary {
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
nextClass: null,
upcomingPayments: [],
pendingPreRegistrations: [],
});
}
@@ -93,6 +98,13 @@ export class GetHomeSummary {
groupName: payment.group.name,
attendeeName: payment.attendee.fullName,
})),
pendingPreRegistrations: groups
.filter((group) => group._count.preRegistrations > 0)
.map((group) => ({
groupId: group.id,
groupName: group.name,
count: group._count.preRegistrations,
})),
});
}