import type { Prisma } from '@generated/prisma/client'; import type { AttendanceStatus, AttentionGroup, AttentionMember, AttentionOverview, ProblemDetails, Result, StudentAlertType, } from '@gruperly/shared'; import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; type GetAttentionOverviewDeps = { db?: { group: Prisma.GroupDelegate; attendee: Prisma.AttendeeDelegate; classSession: Prisma.ClassSessionDelegate; attendance: Prisma.AttendanceDelegate; payment: Prisma.PaymentDelegate; attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate; user: Prisma.UserDelegate; }; now?: Date; }; type GroupRow = { id: string; name: string; capacity: number | null }; type AttendeeRow = { id: string; groupId: string; fullName: string; phone: string | null; guardianPhone: string | null; createdAt: Date; }; type SessionRow = { id: string; groupId: string; startsAt: Date }; type AttendanceRow = { attendeeId: string; classSessionId: string; status: AttendanceStatus; classSession: { startsAt: Date }; }; type PaymentRow = { id: string; attendeeId: string; amount: Prisma.Decimal; currency: string; dueDate: Date; checkoutUrl: string | null; }; type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string }; /* Every ACTIVE member of the user's groups with their alerts ("Requiere atención"). The list screen draws all the avatars from here, so it returns members without alerts too. The rule is `computeStudentAlerts` (shared) over the same attendance input the risk overview builds (`toMemberAttendance`). */ export class GetAttentionOverview { constructor(private readonly deps: GetAttentionOverviewDeps = {}) {} async execute(userId: string): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const groups = (await db.group.findMany({ where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, select: { id: true, name: true, capacity: true }, orderBy: { createdAt: 'asc' }, })) as GroupRow[]; if (groups.length === 0) { return ok({ groups: [] }); } const groupIds = groups.map((group) => group.id); const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([ // Phones are stored the way people write them (`11 2345-6789`): the // professor's country settles the calling code, as in the WhatsApp jobs. db.user.findUnique({ where: { id: userId }, select: { country: true } }), db.attendee.findMany({ where: { groupId: { in: groupIds }, status: 'ACTIVE' }, select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true }, orderBy: { createdAt: 'asc' }, }) as Promise, // Past classes only, most recent first: `toMemberAttendance` keeps the // last 20 per attendee, more than the 6-class window needs. db.classSession.findMany({ where: { groupId: { in: groupIds }, startsAt: { lte: now } }, select: { id: true, groupId: true, startsAt: true }, orderBy: { startsAt: 'desc' }, }) as Promise, db.attendance.findMany({ where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } }, select: { attendeeId: true, classSessionId: true, status: true, classSession: { select: { startsAt: true } }, }, }) as Promise, db.payment.findMany({ where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' }, // A fee the student reported (with a receipt) is out of the alert while // the teacher reviews it; a rejection brings it back. reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } }, }, select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true }, orderBy: { dueDate: 'asc' }, }) as Promise, db.attendeeAlertResolution.findMany({ where: { attendee: { groupId: { in: groupIds } } }, select: { attendeeId: true, kind: true, signature: true }, }) as Promise, ]); const country = countryCodeSchema.safeParse(owner?.country); const sessionsByGroup = groupBy(sessions, (session) => session.groupId); const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId); const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId); const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId); const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId); const items: AttentionGroup[] = groups.map((group) => ({ groupId: group.id, groupName: group.name, capacity: group.capacity, members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => { const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({ id: payment.id, amount: Number(payment.amount), currency: payment.currency, dueDate: payment.dueDate.toISOString(), checkoutUrl: payment.checkoutUrl, })); const alerts = computeStudentAlerts( { attendance: toMemberAttendance( attendee, sessionsByGroup.get(group.id) ?? [], attendanceByAttendee.get(attendee.id) ?? [], ), overduePayments, }, now, ); const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({ tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType, firma: row.signature, })); const phone = attendee.phone ?? attendee.guardianPhone; return { attendeeId: attendee.id, fullName: attendee.fullName, phone, whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null, alerts: applyResolutions(alerts, resolved), overduePayments, }; }), })); return ok({ groups: items }); } } function groupBy(rows: T[], key: (row: T) => string): Map { const map = new Map(); for (const row of rows) { const list = map.get(key(row)) ?? []; list.push(row); map.set(key(row), list); } return map; }