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>
This commit is contained in:
Jose Selesan
2026-11-03 09:46:37 -03:00
parent f1829fb5a9
commit d21e1c3730
84 changed files with 1981 additions and 423 deletions

View File

@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
import {
alreadyWaitlistedProblem,
capacityReachedProblem,
conflictProblem,
noGroupAccessProblem,
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
import {
alreadyInGroupProblem,
findPersonByPhone,
isUniqueViolation,
personExistsProblem,
} from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
};
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
}
const phone = normalizePhone(payload.phone);
const existing = await db.attendee.findFirst({
where: {
groupId,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
},
});
if (existing) {
return err(
conflictProblem({
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
code: 'attendee_already_registered',
}),
);
/* 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 } | null = null;
if (payload.personId) {
person = await db.person.findFirst({
where: { id: payload.personId, createdById: group.createdById },
select: { id: true, fullName: true },
});
if (!person) {
return err(notFoundResourceProblem('Person', payload.personId));
}
} else {
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
if (samePhone) {
return err(
samePhone.attendees.some((membership) => membership.groupId === groupId)
? alreadyInGroupProblem()
: personExistsProblem(),
);
}
}
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
// 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 ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
if (group.capacity !== null) {
const currentCount = await db.attendee.count({
@@ -108,25 +125,51 @@ export class CreateAttendeeUseCase {
}
}
// The owner's plan pays for the attendee, whoever adds it.
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
// 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;
}
const attendee = await db.attendee.create({
data: {
groupId,
fullName,
phone,
email: payload.email?.trim() || null,
notes: payload.notes?.trim() || null,
},
});
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,
},
},
},
include: attendeeWithPerson,
});
return ok({
outcome: 'created',
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord),
});
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;
}
}
}
}