Files
gruperly/apps/backend/src/modules/attendees/features/remove/use-case.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

80 lines
2.7 KiB
TypeScript

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<PrismaClient, 'group' | 'attendee' | 'payment'>;
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<Result<RemoveAttendeeResult, ProblemDetails>> {
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<Result<RemoveAttendeeResult, ProblemDetails>> => {
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),
});
},
);
}
}