import type { PrismaClient } from '@generated/prisma/client'; import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared'; import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; import { toAttendeeListItemDto } from '../../lib/helpers'; type ListAttendeesDeps = { db?: Pick; }; export class ListAttendees { constructor(private readonly deps: ListAttendeesDeps = {}) {} async execute(query: AttendeeQuery): Promise> { const db = this.deps.db ?? prisma; const where = query.groupId ? { groupId: query.groupId } : undefined; const [records, total] = await Promise.all([ /* Each row's summary travels in the same query instead of being built with one request per member. Both relations are capped on purpose: the payments table grows one row per month forever, and the listing only needs each person's current state. */ db.attendee.findMany({ ...(where ? { where } : {}), skip: getPaginationOffset(query), take: query.pageSize, orderBy: { createdAt: 'desc' }, include: { // By class date, not by `markedAt`: marking attendance late must not // change which class counts as recent. attendances: { orderBy: { classSession: { startsAt: 'desc' } }, take: RECENT_ATTENDANCE_LIMIT, select: { status: true }, }, payments: { where: { status: { not: 'CANCELLED' } }, orderBy: { dueDate: 'desc' }, take: 3, select: { status: true, dueDate: true }, }, }, }), where ? db.attendee.count({ where }) : db.attendee.count(), ]); return ok({ data: records.map((record) => toAttendeeListItemDto(record)), pagination: getPaginationMetadata(query, total), }); } }