import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, RemoveAttendeeResult, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { attendeeHasPaymentsProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { findGroupOwnedByUser, toGroupWaitlistEntryDto, } from '@/modules/group-waitlist/lib/helpers'; import { promoteFirstPendingWaitlistEntry } from '@/modules/group-waitlist/lib/promote'; type RemoveAttendeeDeps = { db?: Pick; unitOfWork?: UnitOfWork; }; type RemoveAttendeeOptions = { promoteFromWaitlist?: boolean; }; export class RemoveAttendee { constructor(private readonly deps: RemoveAttendeeDeps = {}) {} async execute( groupId: string, attendeeId: string, userId: string, options: RemoveAttendeeOptions = {}, ): Promise> { const db = this.deps.db ?? prisma; const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const groupResult = await findGroupOwnedByUser(db, groupId, userId); if (!groupResult.ok) { return groupResult; } const group = groupResult.value; const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true }, }); if (!attendee) { return err(notFoundResourceProblem('Attendee', attendeeId)); } const paymentsCount = await db.payment.count({ where: { attendeeId } }); if (paymentsCount > 0) { return err(attendeeHasPaymentsProblem()); } return unitOfWork.executeResult( async (tx: Prisma.TransactionClient): Promise> => { await tx.attendee.delete({ where: { id: attendeeId } }); // Their last group: the person goes too (with their student app link). await tx.person.deleteMany({ where: { id: attendee.personId, attendees: { none: {} } }, }); if (!options.promoteFromWaitlist) { return ok({ removedAttendeeId: attendeeId, promoted: null }); } const promoteResult = await promoteFirstPendingWaitlistEntry(tx, group); if (!promoteResult.ok) { return err(promoteResult.error); } if (!promoteResult.value) { return ok({ removedAttendeeId: attendeeId, promoted: null }); } await tx.groupWaitlistEntry.delete({ where: { id: promoteResult.value.entry.id } }); return ok({ removedAttendeeId: attendeeId, promoted: toGroupWaitlistEntryDto(promoteResult.value.entry), }); }, ); } }