import type { PrismaClient } from '@generated/prisma/client'; import type { AttendeeDto, ProblemDetails, Result, UpdateAttendee } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people'; import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; type UpdateAttendeeDeps = { db?: Pick; }; type UpdateAttendeeCommand = { groupId: string; attendeeId: string; userId: string; input: UpdateAttendee; }; export class UpdateAttendeeDetails { constructor(private readonly deps: UpdateAttendeeDeps = {}) {} async execute(command: UpdateAttendeeCommand): Promise> { const { groupId, attendeeId, userId, input } = command; const db = this.deps.db ?? prisma; const access = await findGroupForUser(db, groupId, userId); if (!access.ok) return access; const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true }, }); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); // Contact data is the person's: the change shows in every group they are in. try { await db.person.update({ where: { id: attendee.personId }, data: normalizeEditableFields(input), }); } catch (error) { if (isUniqueViolation(error)) return err(personPhoneTakenProblem()); throw error; } const updated = await db.attendee.findUniqueOrThrow({ where: { id: attendeeId }, include: attendeeWithPerson, }); return ok(toAttendeeDto(updated)); } } function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee { return Object.fromEntries( Object.entries(input).map(([key, value]) => { if (value === '') return [key, null]; // Same normalization as the add form, so the phone keeps matching. if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)]; return [key, value]; }), ); }