import type { PrismaClient } from '@generated/prisma/client'; import type { AttendanceStatus, ProblemDetails, Result, StudentAtRisk, StudentsAtRisk, } from '@gruperly/shared'; import { ok, summarizeMemberAttendance } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { flattenPerson } from '@/modules/attendees/lib/helpers'; import { contactPhone, guardianSelect } from '@/modules/people/lib/people'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; type GetStudentsAtRiskDeps = { db?: AnalyticsAccessDb & StudentsAtRiskDb; now?: Date; }; type AttendanceStreamRow = { attendeeId: string; classSessionId: string; status: AttendanceStatus; classSession: { startsAt: Date }; }; export class GetStudentsAtRisk { constructor(private readonly deps: GetStudentsAtRiskDeps = {}) {} async execute( groupId: string, userId: string, ): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const access = await findGroupForUser(db, groupId, userId); if (!access.ok) { return access; } const atRisk = await findStudentsAtRisk(db, groupId, now); return ok({ groupName: access.value.name, data: atRisk, }); } } export type StudentsAtRiskDb = Pick; /** * 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, 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, groupId: string, now: Date, ): Promise { const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); const [windowSessions, attendees, attendances] = await Promise.all([ db.classSession.findMany({ where: { groupId, startsAt: { gte: since } }, select: { id: true, startsAt: true }, orderBy: { startsAt: 'desc' }, }), db.attendee.findMany({ where: { groupId, status: 'ACTIVE' }, select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } }, }).then((rows) => rows.map(flattenPerson)), db.attendance.findMany({ where: { attendee: { groupId } }, select: { attendeeId: true, classSessionId: true, status: true, classSession: { select: { startsAt: true } }, }, orderBy: { classSession: { startsAt: 'desc' } }, }), ]); const totalWindowSessions = windowSessions.length; const streamByAttendee = groupAttendanceByAttendee(attendances); const atRisk: StudentAtRisk[] = []; for (const attendee of attendees) { 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, ); atRisk.push({ attendeeId: attendee.id, fullName: attendee.fullName, // The number to reach them on: the adult in charge for a kid. phone: contactPhone(attendee), riskLevel, consecutiveAbsences, lastAttendedAt: attendedAt ? attendedAt.toISOString() : null, monthlyAttendanceRate: monthlyRate, }); } atRisk.sort((a, b) => { if (a.riskLevel !== b.riskLevel) { return a.riskLevel === 'HIGH' ? -1 : 1; } if (a.consecutiveAbsences !== b.consecutiveAbsences) { return b.consecutiveAbsences - a.consecutiveAbsences; } return a.monthlyAttendanceRate - b.monthlyAttendanceRate; }); return atRisk; } function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map { const byAttendee = new Map(); for (const row of rows) { const list = byAttendee.get(row.attendeeId) ?? []; list.push(row); byAttendee.set(row.attendeeId, list); } return byAttendee; }