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> { 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, db.classSession.findMany({ where: { groupId: { in: groupIds }, startsAt: { gte: since } }, select: { id: true, groupId: true, startsAt: true }, orderBy: { startsAt: 'desc' }, }) as Promise, /* 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, ]); const sessionsByGroup = new Map(); 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, attendanceByAttendee: Map, 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 { 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; }