import type { PrismaClient } from '@generated/prisma/client'; import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { alreadyWaitlistedProblem, capacityReachedProblem, noGroupAccessProblem, notFoundResourceProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { alreadyInGroupProblem, contactPhone, findPersonByPhone, guardianRequiredProblem, guardianSelect, isUniqueViolation, personExistsProblem, type WithGuardians, } from '@/modules/people/lib/people'; import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; type CreateAttendeeDeps = { db?: Pick; planGuard?: Pick; }; type CreateAttendeeOptions = { allowOverflow?: boolean; }; export class CreateAttendeeUseCase { constructor(private readonly deps: CreateAttendeeDeps = {}) {} async execute( groupId: string, userId: string, payload: CreateAttendee, options: CreateAttendeeOptions = {}, ): Promise> { const db = this.deps.db ?? prisma; const group = await db.group.findUnique({ where: { id: groupId }, include: { members: { where: { userId } }, }, }); if (!group) { return err(notFoundResourceProblem('Group', groupId)); } const isOwner = group.createdById === userId; const isMember = group.members.length > 0; if (!isOwner && !isMember) { return err(noGroupAccessProblem()); } const isKidsGroup = group.audience === 'KIDS'; if (isKidsGroup && !payload.personId && !payload.guardian) { return err(guardianRequiredProblem()); } // A kid may have no phone of their own: the adult in charge is the contact. const phone = payload.phone ? normalizePhone(payload.phone) : null; /* The person: the one the form picked (`personId`, after the "ya existe" hint) or a new one. A phone the teacher already has is never duplicated. */ let person: ({ id: string; fullName: string; phone: string | null } & WithGuardians) | null = null; // Kids groups: the adult in charge, already one of the teacher's people or new. let guardian: { id: string } | null = null; if (payload.personId) { person = await db.person.findFirst({ where: { id: payload.personId, createdById: group.createdById }, select: { id: true, fullName: true, phone: true, ...guardianSelect }, }); if (!person) { return err(notFoundResourceProblem('Person', payload.personId)); } } else { if (payload.phone) { // The raw phone: its variants also match older rows stored as typed. const samePhone = await findPersonByPhone(db, group.createdById, payload.phone); if (samePhone) { return err( samePhone.attendees.some((membership) => membership.groupId === groupId) ? alreadyInGroupProblem() : personExistsProblem(), ); } } if (payload.guardian) { guardian = await findPersonByPhone(db, group.createdById, payload.guardian.phone); // The same kid of the same adult (same name) is that kid, not a twin. if (guardian) { person = await db.person.findFirst({ where: { createdById: group.createdById, fullName: { equals: kidFullName(payload), mode: 'insensitive' }, guardians: { some: { guardianId: guardian.id } }, }, select: { id: true, fullName: true, phone: true, ...guardianSelect }, }); } } } // A former member (DROPPED) comes back on the same membership: history included. const membership = person ? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } }) : null; if (membership && membership.status !== 'DROPPED') { return err(alreadyInGroupProblem()); } const fullName = person?.fullName ?? kidFullName(payload); // Who the waitlist row (and later the messages) reaches. const reachPhone = (person ? contactPhone(person) : null) ?? phone ?? (payload.guardian ? normalizePhone(payload.guardian.phone) : null); if (group.capacity !== null) { const currentCount = await db.attendee.count({ where: { groupId, status: 'ACTIVE' }, }); if (currentCount >= group.capacity) { if (isOwner && !options.allowOverflow) { return err(capacityReachedProblem(group.capacity)); } if (!isOwner) { const existingWaitlistEntry = reachPhone ? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } }) : null; if (existingWaitlistEntry) { return err(alreadyWaitlistedProblem()); } await db.groupWaitlistEntry.create({ data: { groupId, fullName, phone: reachPhone ?? '', email: payload.email?.trim() || null, notes: payload.notes?.trim() || null, }, }); return ok({ outcome: 'waitlisted', message: `${fullName} fue agregado a la lista de espera del grupo.`, }); } } } // The owner's plan pays for the attendee, whoever adds it. It counts people: // someone already active in another group does not take a new slot. const alreadyCounted = person ? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0 : false; const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees( group.createdById, alreadyCounted ? 0 : 1, ); if (!allowed.ok) { return allowed; } try { const attendee = membership ? await db.attendee.update({ where: { id: membership.id }, data: { status: 'ACTIVE' }, include: attendeeWithPerson, }) : await db.attendee.create({ data: { group: { connect: { id: groupId } }, person: person ? { connect: { id: person.id } } : { create: { createdById: group.createdById, fullName, phone, email: payload.email?.trim() || null, notes: payload.notes?.trim() || null, ...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}), }, }, }, include: attendeeWithPerson, }); return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) }); } catch (error) { // Lost a race: someone created that person or membership meanwhile. if (isUniqueViolation(error)) { return err(person ? alreadyInGroupProblem() : personExistsProblem()); } throw error; } } } function kidFullName(payload: CreateAttendee): string { return `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); } /* Nested create of the kid's link to the adult in charge: the existing adult, or a new person with the adult's data. */ function guardianLink(ownerId: string, input: GuardianInput, existing: { id: string } | null) { return { guardian: existing ? { connect: { id: existing.id } } : { create: { createdById: ownerId, fullName: input.fullName.trim(), phone: normalizePhone(input.phone), email: input.email?.trim() || null, }, }, }; }