- 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>
198 lines
6.6 KiB
TypeScript
198 lines
6.6 KiB
TypeScript
import { Prisma } from '@generated/prisma/client';
|
|
import type {
|
|
AttendanceStatus,
|
|
GroupRiskLevel,
|
|
GroupRiskSummary,
|
|
GroupsRiskOverview,
|
|
ProblemDetails,
|
|
Result,
|
|
UrgentMemberSummary,
|
|
} 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 { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
|
|
|
type GetGroupsRiskOverviewDeps = {
|
|
db?: {
|
|
group: Prisma.GroupDelegate;
|
|
classSession: Prisma.ClassSessionDelegate;
|
|
attendee: Prisma.AttendeeDelegate;
|
|
attendance: Prisma.AttendanceDelegate;
|
|
};
|
|
now?: Date;
|
|
};
|
|
|
|
type GroupRow = {
|
|
id: string;
|
|
name: string;
|
|
capacity: number | null;
|
|
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
|
_count: { waitlist: number };
|
|
};
|
|
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
|
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
|
type AttendanceRow = {
|
|
attendeeId: string;
|
|
classSessionId: string;
|
|
status: AttendanceStatus;
|
|
classSession: { startsAt: Date };
|
|
};
|
|
|
|
// 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 = {}) {}
|
|
|
|
async execute(userId: string): Promise<Result<GroupsRiskOverview, ProblemDetails>> {
|
|
const db = this.deps.db ?? prisma;
|
|
const now = this.deps.now ?? new Date();
|
|
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
|
|
|
const groups = (await db.group.findMany({
|
|
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
capacity: true,
|
|
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
|
|
},
|
|
})) as unknown as GroupRow[];
|
|
|
|
if (groups.length === 0) {
|
|
return ok({ items: [] });
|
|
}
|
|
|
|
const groupIds = groups.map((group) => group.id);
|
|
|
|
const [attendees, sessions, attendances] = await Promise.all([
|
|
db.attendee.findMany({
|
|
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
|
select: { id: true, groupId: true, fullName: true, createdAt: true },
|
|
}) as Promise<AttendeeRow[]>,
|
|
db.classSession.findMany({
|
|
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
|
select: { id: true, groupId: true, startsAt: true },
|
|
orderBy: { startsAt: 'desc' },
|
|
}) as Promise<SessionRow[]>,
|
|
/* No date filter, as before: the status light streak counts over the
|
|
attendee's full history, not over the monthly window. No cap either:
|
|
the cut to the last 20 classes is done by `memberSessions`, over the
|
|
group's classes and not over these rows. */
|
|
db.attendance.findMany({
|
|
where: { attendee: { groupId: { in: groupIds } } },
|
|
select: {
|
|
attendeeId: true,
|
|
classSessionId: true,
|
|
status: true,
|
|
classSession: { select: { startsAt: true } },
|
|
},
|
|
orderBy: { classSession: { startsAt: 'desc' } },
|
|
}) as Promise<AttendanceRow[]>,
|
|
]);
|
|
|
|
const sessionsByGroup = new Map<string, SessionRow[]>();
|
|
for (const session of sessions) {
|
|
const list = sessionsByGroup.get(session.groupId) ?? [];
|
|
list.push(session);
|
|
sessionsByGroup.set(session.groupId, list);
|
|
}
|
|
|
|
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
|
|
|
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 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 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,
|
|
waitlistCount: group._count.waitlist,
|
|
now,
|
|
members: attendees
|
|
.filter((attendee) => attendee.groupId === group.id)
|
|
.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) => ({
|
|
attendeeId: urgente.attendeeId,
|
|
fullName: urgente.fullName,
|
|
level: urgente.level,
|
|
consecutiveAbsences: urgente.consecutiveAbsences,
|
|
daysSinceLastAttendance: urgente.daysSinceLastAttendance,
|
|
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,
|
|
libres: resumen.libres,
|
|
enEspera: resumen.enEspera,
|
|
asistencia: resumen.asistencia,
|
|
urgentes,
|
|
};
|
|
}
|
|
|
|
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
|
|
const byAttendee = new Map<string, AttendanceRow[]>();
|
|
for (const row of rows) {
|
|
const list = byAttendee.get(row.attendeeId) ?? [];
|
|
list.push(row);
|
|
byAttendee.set(row.attendeeId, list);
|
|
}
|
|
return byAttendee;
|
|
}
|