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

@@ -0,0 +1,175 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
count: mock(),
create: mock(),
update: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const group = (overrides: Record<string, unknown> = {}) => ({
id: 'group-1',
name: 'Taller de Pintura',
createdById: teacherId,
capacity: 20,
...overrides,
});
const targetGroup = (overrides: Record<string, unknown> = {}) =>
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
const person = {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
};
const membership = (overrides: Record<string, unknown> = {}) => ({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
person,
notifyToken: 'notify-2',
status: 'ACTIVE',
createdAt: new Date('2026-11-02T10:00:00.000Z'),
updatedAt: new Date('2026-11-02T10:00:00.000Z'),
...overrides,
});
function addRequest(targetGroupId: string, userId = teacherId) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', { id: userId } as never);
await next();
});
app.route('/groups', groupsRoutes);
return app.request('/groups/group-1/attendees/att-1/add-to-group', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
}
describe('POST /groups/:groupId/attendees/:attendeeId/add-to-group', () => {
beforeEach(() => {
vi.clearAllMocks();
prisma.group.findUnique.mockReset();
prisma.attendee.findFirst.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.count.mockResolvedValue(3);
});
it('creates a membership of the same person in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
prisma.attendee.create.mockResolvedValue(membership() as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
fullName: 'Martín Gómez',
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
// The source membership is not touched.
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('reactivates a former (DROPPED) membership in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-old', status: 'DROPPED' } as never);
prisma.attendee.update.mockResolvedValue(membership({ id: 'att-old' }) as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-old' },
data: { status: 'ACTIVE' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the person is already in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-2', status: 'PAUSED' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ capacity: 3 }) as never);
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('group_capacity_reached');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects adding to the same group', async () => {
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-1');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_same_group');
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
});

View File

@@ -38,12 +38,21 @@ function makeGroup(overrides: Record<string, unknown> = {}) {
const attendee = {
id: 'a-1',
groupId: 'group-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
// Every membership of the person: this one and another group.
attendees: [
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
{ id: 'a-2', groupId: 'group-2', status: 'PAUSED', group: { name: 'Yoga' } },
],
},
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -67,6 +76,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
expect(await res.json()).toEqual({
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
@@ -77,10 +87,12 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z',
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
});
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
where: { id: 'a-1', groupId: 'group-1' },
include: {
person: { select: expect.objectContaining({ fullName: true, attendees: expect.any(Object) }) },
payments: {
where: {
status: { not: 'CANCELLED' },

View File

@@ -56,12 +56,16 @@ const targetGroup = (overrides: Record<string, unknown> = {}) =>
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: 'notify-1',
status: 'ACTIVE',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
@@ -105,6 +109,7 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-1' },
data: { groupId: 'group-2' },
include: { person: { select: expect.any(Object) } },
});
const futureOldClasses = {
classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } },
@@ -169,7 +174,7 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled();
});
it('rejects with 409 when the phone already belongs to a member of the target group', async () => {
it('rejects with 409 when the person is already a member of the target group', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
@@ -182,6 +187,10 @@ describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.findFirst).toHaveBeenLastCalledWith({
where: { groupId: 'group-2', personId: 'person-1' },
select: { id: true },
});
expect(prisma.attendee.update).not.toHaveBeenCalled();
});

View File

@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
import { Prisma } from '@generated/prisma/client'
import { Hono } from 'hono'
const db = {
group: { findUnique: mock() },
attendee: { findFirst: mock(), update: mock() },
attendee: { findFirst: mock(), findUniqueOrThrow: mock() },
person: { update: mock() },
}
mock.module('@/lib/prisma', () => ({
@@ -15,15 +17,20 @@ mock.module('@/lib/prisma', () => ({
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
const userId = 'user-1'
const attendee = {
id: 'a-1',
groupId: 'group-1',
const person = {
id: 'person-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: 'Llega temprano',
}
const attendee = {
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
person,
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
@@ -51,11 +58,10 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
db.attendee.findFirst.mockResolvedValue(attendee)
})
it('actualiza contacto y conserva los campos vacíos como null', async () => {
db.attendee.update.mockResolvedValue({
it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue({
...attendee,
email: 'ana@example.com',
phone: null,
person: { ...person, email: 'ana@example.com' },
})
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
@@ -65,14 +71,49 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
})
expect(response.status).toBe(200)
expect(db.attendee.update).toHaveBeenCalledWith({
where: { id: 'a-1' },
expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' })
// The person's row: the change shows in every group they are in.
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { email: 'ana@example.com', phone: null },
})
})
it('normaliza el teléfono como el alta', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue(attendee)
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '11 2345-6789' }),
})
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { phone: '1123456789' },
})
})
it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => {
db.person.update.mockRejectedValueOnce(
new Prisma.PrismaClientKnownRequestError('Unique constraint failed', {
code: 'P2002',
clientVersion: 'test',
}),
)
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '1123456789' }),
})
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: 'person_phone_taken' })
})
it('actualiza una única nota', async () => {
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' })
db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } })
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
@@ -80,8 +121,8 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
body: JSON.stringify({ notes: 'Traer colchoneta' }),
})
expect(db.attendee.update).toHaveBeenCalledWith({
where: { id: 'a-1' },
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { notes: 'Traer colchoneta' },
})
})
@@ -94,6 +135,6 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
})
expect(response.status).toBe(400)
expect(db.attendee.update).not.toHaveBeenCalled()
expect(db.person.update).not.toHaveBeenCalled()
})
})

View File

@@ -15,6 +15,10 @@ const db = {
create: mock(),
count: mock(),
},
person: {
findFirst: mock(),
findMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -60,9 +64,34 @@ function makeApp(userValue: unknown) {
return app;
}
const personRow = (overrides: Record<string, unknown> = {}) => ({
id: 'person-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
...overrides,
});
const attendeeRow = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: personRow(),
notifyToken: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
describe('attendee incorporation & invite-token in groups', () => {
beforeEach(() => {
vi.clearAllMocks();
// Nobody with that phone among the teacher's people, unless a test says so.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.findMany.mockResolvedValue([]);
});
describe('GET /groups/:groupId/invite-token', () => {
@@ -109,18 +138,7 @@ describe('attendee incorporation & invite-token in groups', () => {
it('creates an attendee for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
@@ -140,20 +158,95 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(data.outcome).toBe('created');
expect(data.attendee.fullName).toBe('Martín Gómez');
expect(data.attendee.phone).toBe('+5491133445566');
expect(data.attendee.personId).toBe('person-1');
// A new person of the group owner, created with the membership.
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
group: { connect: { id: 'group-1' } },
person: {
create: {
createdById: teacherId,
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
},
},
},
include: { person: { select: expect.any(Object) } },
});
});
it('answers person_exists when the phone is already a person of another group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-9', groupId: 'group-9', status: 'ACTIVE', group: { name: 'Yoga' } }],
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'Martín', lastName: 'Gómez', phone: '+54 9 11 3344-5566' }),
});
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('person_exists');
expect(prisma.person.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { createdById: teacherId, phone: { in: ['+5491133445566', '+54 9 11 3344-5566'] } },
}),
);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('adds an existing person (personId) to the group without a new plan slot', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({ id: 'person-1', fullName: 'Martín Gómez' } as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(1);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-1' }),
});
expect(res.status).toBe(201);
expect(prisma.person.findFirst).toHaveBeenCalledWith({
where: { id: 'person-1', createdById: teacherId },
select: { id: true, fullName: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
include: { person: { select: expect.any(Object) } },
});
});
it('returns 404 for a personId of another teacher', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue(null);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-other' }),
});
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects duplicate phone number in individual add', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
@@ -197,18 +290,7 @@ describe('attendee incorporation & invite-token in groups', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20);
prisma.attendee.create.mockResolvedValue({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
@@ -412,16 +494,19 @@ describe('attendee incorporation & invite-token in groups', () => {
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
// Simulate that an attendee with phone '11111111' already exists
prisma.attendee.findMany.mockResolvedValue([
{ phone: '11111111' },
// The teacher's people: '11111111' is already in this group, '44444444'
// is in another group only (and active there).
prisma.person.findMany.mockResolvedValue([
{ id: 'person-in-group', phone: '11111111', attendees: [{ groupId: 'group-1', status: 'ACTIVE' }] },
{ id: 'person-elsewhere', phone: '44444444', attendees: [{ groupId: 'group-9', status: 'ACTIVE' }] },
] as never);
prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({
id: `att-${Math.random()}`,
...data,
guardianName: null,
guardianPhone: null,
groupId: 'group-1',
personId: data.personId ?? 'person-new',
notifyToken: null,
person: personRow({ fullName: data.person?.create?.fullName ?? 'Existente' }),
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
}));
@@ -434,19 +519,27 @@ describe('attendee incorporation & invite-token in groups', () => {
attendees: [
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the group
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
{ firstName: 'Otra', lastName: 'Persona', phone: '44444444' }, // In another group: linked
],
}),
});
expect(res.status).toBe(201);
const data = await res.json();
expect(data.totalProcessed).toBe(4);
expect(data.createdCount).toBe(2);
expect(data.totalProcessed).toBe(5);
expect(data.createdCount).toBe(3);
expect(data.linkedCount).toBe(1);
expect(data.duplicatesCount).toBe(2);
expect(data.message).toBe('2 alumnos agregados con éxito, 2 duplicados omitidos.');
expect(prisma.attendee.create).toHaveBeenCalledTimes(2);
expect(data.message).toBe(
'3 alumnos agregados con éxito (1 ya estaban en otros de tus grupos), 2 duplicados omitidos.',
);
expect(prisma.attendee.create).toHaveBeenCalledTimes(3);
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-elsewhere' },
include: { person: { select: expect.any(Object) } },
});
});
});
@@ -456,12 +549,8 @@ describe('attendee incorporation & invite-token in groups', () => {
{
id: 'att-1',
groupId: 'group-1',
fullName: 'Ana García',
email: null,
phone: '22222222',
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: personRow({ fullName: 'Ana García', phone: '22222222', email: null, notes: null }),
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
attendances: [],
@@ -487,6 +576,7 @@ describe('attendee incorporation & invite-token in groups', () => {
// The row summary is requested in the same query: one request per
// member would be N+1 over a listing of up to 100.
include: {
person: { select: expect.any(Object) },
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -11,12 +11,16 @@ function record(
return {
id: 'att-1',
groupId: 'group-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -89,10 +93,12 @@ describe('toAttendeeListItemDto', () => {
});
it('conserva los campos del DTO plano', () => {
const dto = toAttendeeListItemDto(record({ phone: '22222222' }));
const base = record();
const dto = toAttendeeListItemDto(record({ person: { ...base.person, phone: '22222222' } }));
expect(dto.fullName).toBe('Ana Pérez');
expect(dto.phone).toBe('22222222');
expect(dto.personId).toBe('person-1');
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
});
});

View File

@@ -19,15 +19,30 @@ import { attendeesRoutes } from '@/modules/attendees';
const app = new Hono();
app.route('/attendees', attendeesRoutes);
const attendeeRow = {
id: 'attendee-1',
groupId: 'group-1',
const personSelect = {
id: true,
fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
};
const person = {
id: 'person-1',
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: null,
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
};
const attendeeRow = {
id: 'attendee-1',
groupId: 'group-1',
personId: 'person-1',
notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -36,6 +51,7 @@ const attendeeRow = {
// What the Prisma mock returns: the row plus the summary relations.
const attendee = {
...attendeeRow,
person,
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
};
@@ -56,6 +72,12 @@ describe('attendees routes', () => {
data: [
{
...attendeeRow,
fullName: person.fullName,
email: person.email,
phone: person.phone,
guardianName: person.guardianName,
guardianPhone: person.guardianPhone,
notes: person.notes,
createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(),
// The query comes most recent first; the row shows them
@@ -71,6 +93,7 @@ describe('attendees routes', () => {
take: 10,
orderBy: { createdAt: 'desc' },
include: {
person: { select: personSelect },
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -12,7 +12,8 @@ function makeDb(params: {
return {
billingSubscription: { findUnique: mock(async () => params.subscription ?? null) },
group: { count: mock(async () => params.groups ?? 0) },
attendee: { count: mock(async () => params.attendees ?? 0) },
// People with an active membership: someone in two groups counts once.
person: { count: mock(async () => params.attendees ?? 0) },
};
}

View File

@@ -29,7 +29,14 @@ describe('plan guards in the use cases', () => {
it('checks a bulk import against the group owner, with the number of new attendees', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() },
attendee: { create: mock() },
// '1111' is already in this group; '4444' is active in another group.
person: {
findMany: mock(async () => [
{ id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] },
{ id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] },
]),
},
};
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
@@ -38,9 +45,11 @@ describe('plan guards in the use cases', () => {
{ fullName: 'Ana', phone: '2222' },
{ fullName: 'Beto', phone: '3333' },
{ fullName: 'Repetido', phone: '1111' },
{ fullName: 'De otro grupo', phone: '4444' },
],
} as never);
// Only the two new people: the one already active elsewhere takes no slot.
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
expect(result.ok).toBe(false);
expect(db.attendee.create).not.toHaveBeenCalled();

View File

@@ -159,8 +159,8 @@ describe('classes routes', () => {
it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => {
prisma.classSession.findUnique.mockResolvedValue(makeSession());
prisma.attendee.findMany.mockResolvedValue([
{ id: 'attendee-1', fullName: 'Ana Pérez' },
{ id: 'attendee-2', fullName: 'Bruno Díaz' },
{ id: 'attendee-1', person: { fullName: 'Ana Pérez' } },
{ id: 'attendee-2', person: { fullName: 'Bruno Díaz' } },
]);
prisma.payment.findMany.mockResolvedValue([
{ attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') },
@@ -443,7 +443,7 @@ describe('classes routes', () => {
prisma.attendee.findUnique.mockResolvedValue({
id: 'attendee-1',
fullName: 'Ana Pérez',
person: { fullName: 'Ana Pérez' },
group: {
id: 'group-1',
name: 'Funcional',

View File

@@ -63,7 +63,10 @@ describe.skipIf(!url)('payment review (real database)', () => {
],
});
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } });
await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } });
await db.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } });
await db.attendee.create({
data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, createdAt: new Date('2026-01-01T00:00:00Z') },
});
await db.studentAccount.create({
data: {
id: ids.account,
@@ -71,7 +74,7 @@ describe.skipIf(!url)('payment review (real database)', () => {
createdById: ids.teacher,
recoveryEmail: 'ana@test.local',
recoveryEmailVerifiedAt: NOW,
attendees: { create: { attendeeId: ids.ana } },
people: { create: { personId: `${ids.ana}-person` } },
},
});
await db.payment.create({

View File

@@ -19,7 +19,14 @@ describe.skipIf(!url)('student access (real database)', () => {
// Same contract as UnitOfWork.executeResult, built on this file's own client
// (other test files mock '@/lib/prisma').
let unitOfWork: { executeResult: unknown };
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` };
const ids = {
user: `test-user-${suffix}`,
group: `test-group-${suffix}`,
group2: `test-group2-${suffix}`,
person: `test-person-${suffix}`,
attendee: `test-att-${suffix}`,
attendee2: `test-att2-${suffix}`,
};
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
@@ -42,7 +49,11 @@ describe.skipIf(!url)('student access (real database)', () => {
};
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } });
await db.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } });
// One person in two groups of the teacher.
await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } });
await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } });
});
afterAll(async () => {
@@ -96,7 +107,7 @@ describe.skipIf(!url)('student access (real database)', () => {
if (!loser.ok) expect(loser.error.status).toBe(410);
}
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
expect(sessions).toHaveLength(1);
expect(sessions[0]?.device).toBe('iPhone · Safari');
@@ -122,7 +133,7 @@ describe.skipIf(!url)('student access (real database)', () => {
if (!first.ok) throw new Error('invite failed');
const consumed = await consume(tokenOf(first.value.url));
expect(consumed.ok).toBe(true);
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const linked = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
await db.studentPasskey.create({
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
});
@@ -141,9 +152,25 @@ describe.skipIf(!url)('student access (real database)', () => {
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
});
it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => {
const fromFirst = await invite();
if (!fromFirst.ok) throw new Error('invite failed');
const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(
ids.group2,
ids.attendee2,
ids.user,
);
if (!fromSecond.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1);
// Same state from both groups: it is the person's access.
const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user);
expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } });
});
});

View File

@@ -8,6 +8,7 @@ import type { FileStorage } from '@/lib/storage';
import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case';
import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case';
import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case';
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
@@ -30,7 +31,12 @@ describe.skipIf(!url)('student portal (real database)', () => {
const ids = {
user: `t-user-${suffix}`,
group: `t-group-${suffix}`,
yoga: `t-yoga-${suffix}`,
personAna: `t-p-ana-${suffix}`,
personBeto: `t-p-beto-${suffix}`,
ana: `t-ana-${suffix}`,
anaYoga: `t-ana-yoga-${suffix}`,
betoYoga: `t-beto-yoga-${suffix}`,
beto: `t-beto-${suffix}`,
accountAna: `t-acc-ana-${suffix}`,
accountBeto: `t-acc-beto-${suffix}`,
@@ -50,17 +56,29 @@ describe.skipIf(!url)('student portal (real database)', () => {
await db.group.create({
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
});
await db.group.create({
data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' },
});
await db.person.createMany({
data: [
{ id: ids.personAna, createdById: ids.user, fullName: 'Ana' },
{ id: ids.personBeto, createdById: ids.user, fullName: 'Beto' },
],
});
// Ana and Beto are in both groups.
await db.attendee.createMany({
data: [
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
{ id: ids.ana, groupId: ids.group, personId: ids.personAna },
{ id: ids.beto, groupId: ids.group, personId: ids.personBeto },
{ id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna },
{ id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto },
],
});
await db.studentAccount.create({
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } },
});
await db.studentAccount.create({
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } },
});
await db.payment.createMany({
data: [
@@ -117,6 +135,21 @@ describe.skipIf(!url)('student portal (real database)', () => {
expect(!invented.ok && invented.error.status).toBe(400);
});
it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => {
const me = await new GetStudentMe({ db }).execute(ids.accountAna);
if (!me.ok) throw new Error('me failed');
expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([
[ids.ana, 'Natación'],
[ids.anaYoga, 'Yoga'],
]);
// Her membership in the second group is reachable; Beto's in that group is not.
expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true);
const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga);
expect(foreign.ok).toBe(false);
if (!foreign.ok) expect(foreign.error.status).toBe(404);
});
it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => {
expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);

View File

@@ -82,7 +82,7 @@ describe('GetHomeSummary', () => {
dueDate: new Date('2026-09-25T12:00:00.000Z'),
status: 'PENDING',
group: { name: 'Cuadrilla A' },
attendee: { fullName: 'Ana García' },
attendee: { person: { fullName: 'Ana García' } },
},
]);
@@ -130,7 +130,7 @@ describe('GetHomeSummary', () => {
where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: [{ dueDate: 'asc' }],
take: 5,
include: { group: { select: { name: true } }, attendee: { select: { fullName: true } } },
include: { group: { select: { name: true } }, attendee: { select: { person: { select: { fullName: true } } } } },
});
});

View File

@@ -81,8 +81,8 @@ describe('create payments batch', () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([
{ id: 'att-1', fullName: 'Juana' },
{ id: 'att-2', fullName: 'Pedro' },
{ id: 'att-1', person: { fullName: 'Juana' } },
{ id: 'att-2', person: { fullName: 'Pedro' } },
]);
prisma.payment.create
.mockResolvedValueOnce({ id: 'pay-1' })
@@ -149,7 +149,7 @@ describe('create payments batch', () => {
it('derives the currency from the owner country and defaults when there is none', async () => {
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]);
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
const useCase = batchUseCase();
createPreference.mockResolvedValueOnce({
@@ -169,13 +169,14 @@ describe('create payments batch', () => {
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
include: { person: { select: { fullName: true } } },
});
});
it('propagates the not-connected problem and creates no rows', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
getToken = mock(async () => ({
ok: false,
error: {
@@ -203,7 +204,7 @@ describe('create payments batch', () => {
it('answers 409 over HTTP when the owner has no linked account', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {

View File

@@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
paidAt: null,
createdAt: new Date('2026-10-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
attendee: { fullName: 'Juana Pérez' },
attendee: { person: { fullName: 'Juana Pérez' } },
group: {
name: 'Vinyasa',
price: { toString: () => '120.00' },
@@ -107,7 +107,7 @@ describe('renew payment link', () => {
where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
include: {
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } },
},
});

View File

@@ -36,7 +36,7 @@ const payment = {
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
group: { name: 'Cuadrilla Alfa', price: 150.5 },
attendee: { fullName: 'Juana Pérez' },
attendee: { person: { fullName: 'Juana Pérez' } },
};
function makeApp(userValue: unknown) {
@@ -93,7 +93,7 @@ describe('payments routes', () => {
where: { groupId: { in: ['group-1'] } },
include: {
group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
skip: 0,
take: 10,

View File

@@ -10,6 +10,11 @@ const db = {
count: mock(),
create: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findFirst: mock(),
create: mock(),
@@ -69,12 +74,16 @@ const preRegistration = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: 'notify-1',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
@@ -107,6 +116,9 @@ function makeApp(userValue: unknown) {
describe('group pre-registrations', () => {
beforeEach(() => {
vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
});
describe('GET /groups/:groupId/preregistrations', () => {
@@ -183,14 +195,19 @@ describe('group pre-registrations', () => {
expect(body.outcome).toBe('added');
expect(body.attendee.fullName).toBe('Martín Gómez');
expect(body.waitlistEntry).toBeNull();
expect(prisma.attendee.create).toHaveBeenCalledWith({
expect(prisma.person.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
createdById: teacherId,
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
notes: null,
},
select: { id: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
where: { id: 'pre-1' },
@@ -255,7 +272,14 @@ describe('group pre-registrations', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await makeApp({ id: teacherId }).request(
'/groups/group-1/preregistrations/pre-1/approve',

View File

@@ -74,7 +74,7 @@ describe('link del alumno', () => {
expiresAt: new Date(NOW.getTime() + 1000),
account: {
name: 'Ana',
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
people: [{ person: { attendees: [{ group: { name: 'Natación', owner: { name: 'Caro' } } }] } }],
},
})),
updateMany: mock(),

View File

@@ -12,6 +12,11 @@ const db = {
create: mock(),
delete: mock(),
},
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
@@ -70,12 +75,16 @@ const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
@@ -94,6 +103,9 @@ function makeApp(userValue: unknown) {
describe('group waitlist management', () => {
beforeEach(() => {
vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
});
describe('GET /groups/:groupId/waitlist', () => {
@@ -146,7 +158,12 @@ describe('group waitlist management', () => {
const data = await res.json();
expect(data.attendee.fullName).toBe('Martín Gómez');
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-1', fullName: 'Martín Gómez', phone: '+5491133445566' }),
data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ createdById: teacherId, fullName: 'Martín Gómez', phone: '+5491133445566' }),
select: { id: true },
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
@@ -167,10 +184,17 @@ describe('group waitlist management', () => {
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
it('rejects with 409 when the phone already belongs to an attendee', async () => {
it('rejects with 409 when the person is already a member of the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
@@ -227,7 +251,8 @@ describe('group waitlist management', () => {
expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } });
expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-2', fullName: 'Martín Gómez' }),
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
@@ -325,6 +350,10 @@ describe('group waitlist management', () => {
expect(body.removedAttendeeId).toBe('att-1');
expect(body.promoted).toBeNull();
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
// Their last group: the person goes too (no-op if they are in others).
expect(prisma.person.deleteMany).toHaveBeenCalledWith({
where: { id: 'person-1', attendees: { none: {} } },
});
});
it('removes an attendee and promotes the first pending waitlist entry atomically', async () => {
@@ -353,8 +382,9 @@ describe('group waitlist management', () => {
expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' });
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }),
select: { id: true },
});
});

View File

@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`,
attendee: { phone: null, guardianPhone: null, ...attendee },
attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
...overrides,
};
}
@@ -282,11 +282,11 @@ describe('re-engagement messages', () => {
]);
db.attendee.findMany
.mockResolvedValueOnce([
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled },
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled },
{ id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled },
{ id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled },
])
.mockResolvedValueOnce([
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
{ id: 'att-1', person: { phone: '1123456789', guardianPhone: null } },
]);
db.attendance.findMany.mockResolvedValue([
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },