import type { PrismaClient } from '@generated/prisma/client'; import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { capacityReachedProblem } from '@/http/problem-builders'; import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers'; import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people'; import { type GroupWaitlistEntryRecord } from './helpers'; export type PromoteDb = Pick; type PromoteGroup = { id: string; capacity: number | null; createdById: string; }; export async function findFirstPendingWaitlistEntry( db: PromoteDb, groupId: string, ): Promise { const record = await db.groupWaitlistEntry.findFirst({ where: { groupId, status: 'PENDING' }, orderBy: { createdAt: 'asc' }, }); return record as GroupWaitlistEntryRecord | null; } /* Whether someone can join `group`: free capacity (ACTIVE members) and the person (when there already is one) not being a member there yet. Shared by the waitlist promotion, the member move and "Agregar a otro grupo". */ export async function checkCanJoinGroup( db: Pick, group: Pick, personId: string | null, ): Promise> { if (group.capacity !== null) { const currentCount = await db.attendee.count({ where: { groupId: group.id, status: 'ACTIVE' }, }); if (currentCount >= group.capacity) { return err(capacityReachedProblem(group.capacity)); } } if (personId) { const existing = await db.attendee.findFirst({ where: { groupId: group.id, personId }, select: { id: true }, }); if (existing) { return err(alreadyInGroupProblem()); } } return ok(undefined); } /* The entry has its own contact data; if its phone is already one of the teacher's people, the new membership goes to that person. */ export async function promoteWaitlistEntryRecord( db: PromoteDb, group: PromoteGroup, entry: GroupWaitlistEntryRecord, ): Promise> { const person = await findOrCreatePerson(db, group.createdById, { fullName: entry.fullName, phone: entry.phone, email: entry.email, notes: entry.notes, }); const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id); if (!canJoin.ok) { return canJoin; } const attendee = await db.attendee.create({ data: { groupId: group.id, personId: person.id }, include: attendeeWithPerson, }); return ok(toAttendeeDto(attendee)); } export type PromoteFirstResult = { attendee: AttendeeDto; entry: GroupWaitlistEntryRecord; }; export async function promoteFirstPendingWaitlistEntry( db: PromoteDb, group: PromoteGroup, ): Promise> { const entry = await findFirstPendingWaitlistEntry(db, group.id); if (!entry) { return ok(null); } const result = await promoteWaitlistEntryRecord(db, group, entry); if (!result.ok) { return result; } return ok({ attendee: result.value, entry }); }