import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers'; import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote'; import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers'; type MoveAttendeeDeps = { db?: Pick; unitOfWork?: UnitOfWork; now?: () => Date; }; type MoveAttendeeCommand = { groupId: string; attendeeId: string; userId: string; targetGroupId: string; }; /* Moves a member to another group of the same teacher. It is the same attendee with another `groupId`: past attendance, fees (they stay owed to the old group) and the student app access go with them. Only what was booked for the old group's future classes is undone: absence notices, the EXCUSED rows they left and the released slots. */ export class MoveAttendee { constructor(private readonly deps: MoveAttendeeDeps = {}) {} async execute(command: MoveAttendeeCommand): Promise> { const { groupId, attendeeId, userId, targetGroupId } = command; const db = this.deps.db ?? prisma; const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const now = this.deps.now?.() ?? new Date(); const sourceResult = await findGroupOwnedByUser(db, groupId, userId); if (!sourceResult.ok) return sourceResult; const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); if (targetGroupId === groupId) { return err( conflictProblem({ detail: 'El miembro ya pertenece a este grupo.', code: 'attendee_same_group', }), ); } const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId); if (!targetResult.ok) return targetResult; return unitOfWork.executeResult( async (tx: Prisma.TransactionClient): Promise> => { const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId); if (!canJoin.ok) return canJoin; const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } }; await tx.absenceNotice.updateMany({ where: { attendeeId, cancelledAt: null, ...futureOldClasses }, data: { cancelledAt: now }, }); await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } }); await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } }); const moved = await tx.attendee.update({ where: { id: attendeeId }, data: { groupId: targetGroupId }, include: attendeeWithPerson, }); return ok(toAttendeeDto(moved)); }, ); } }