Files
gruperly/apps/backend/test/attendees-incorporation.test.ts
Jose Selesan 58c776e18c feat(groups): kids groups with an adult in charge
- Add the `kidsGroups` plan feature (Pro) and `Group.audience` (ADULTS | KIDS);
  creating or switching a group to KIDS requires the feature, existing KIDS
  groups keep working after a downgrade.
- Model the adult in charge as a Person linked through `person_guardians`;
  migrate the old guardian_name/guardian_phone columns and drop them.
- Kids quick add: kid + guardian form, guardian lookup by phone to pick an
  existing kid or add a sibling; backend rejects KIDS adds without guardian.
- Attendee page: "Adulto a cargo" section with siblings, editable via
  PATCH /groups/:gid/attendees/:aid/guardian.
- Contact phone (WhatsApp jobs, attention, student access invite, students at
  risk, attendee actions) prefers the guardian's phone.
- Edit group screen (PATCH /groups/:gid, owner only); switching back to ADULTS
  is blocked while kids have no phone of their own.
- Hide bulk import in KIDS groups until it carries guardian data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:27:13 -03:00

596 lines
21 KiB
TypeScript

import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
findFirst: mock(),
update: mock(),
count: mock(),
},
attendee: {
findMany: mock(),
findFirst: mock(),
create: mock(),
count: mock(),
},
person: {
findFirst: mock(),
findMany: mock(),
},
groupWaitlistEntry: {
findMany: mock(),
findFirst: mock(),
create: mock(),
count: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const mockGroup = {
id: 'group-1',
name: 'Taller de Pintura',
description: 'Acuarelas para principiantes',
createdById: teacherId,
inviteToken: 'pintura-token-xyz',
createdAt: new Date('2026-09-01T10:00:00.000Z'),
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
days: ['MONDAY'],
time: '18:00',
capacity: 20,
price: 1500,
billingType: 'MONTHLY',
dueDay: 10,
members: [],
};
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/groups', groupsRoutes);
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', () => {
it('returns existing invite token and url', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/invite-token');
expect(res.status).toBe(200);
const data = await res.json();
expect(data.token).toBe('pintura-token-xyz');
expect(data.inviteUrl).toContain('/join/pintura-token-xyz');
});
it('generates a new token if group did not have one', async () => {
prisma.group.findUnique.mockResolvedValue({
...mockGroup,
inviteToken: null,
} as never);
prisma.group.update.mockResolvedValue({} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/invite-token');
expect(res.status).toBe(200);
const data = await res.json();
expect(data.token).toBeDefined();
expect(data.token.length).toBeGreaterThan(5);
expect(prisma.group.update).toHaveBeenCalled();
});
it('rejects user without access to the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
const app = makeApp({ id: 'other-user' });
const res = await app.request('/groups/group-1/invite-token');
expect(res.status).toBe(403);
});
});
describe('POST /groups/:groupId/attendees (individual quick add)', () => {
it('creates an attendee for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
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: 'Martín',
lastName: 'Gómez',
phone: '+54 9 11 3344-5566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
}),
});
expect(res.status).toBe(201);
const data = await res.json();
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: {
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: expect.objectContaining({ 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.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', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(409);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects owner with 409 group_capacity_reached when the group is full', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20); // capacity full
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: '1133445566',
}),
});
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('group_capacity_reached');
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled();
});
it('allows the owner to add anyway when allowOverflow is set', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.outcome).toBe('created');
expect(body.attendee.fullName).toBe('Martín Gómez');
expect(prisma.attendee.create).toHaveBeenCalled();
});
it('adds to the waitlist when a non-owner member tries to add to a full group', async () => {
const memberGroup = {
...mockGroup,
members: [{ id: 'gm-1', role: 'MEMBER' }],
};
prisma.group.findUnique.mockResolvedValue(memberGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
prisma.groupWaitlistEntry.create.mockResolvedValue({
id: 'wl-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
notes: null,
status: 'PENDING',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
const app = makeApp({ id: 'member-1' });
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: '1133445566',
}),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.outcome).toBe('waitlisted');
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '1133445566',
email: null,
notes: null,
},
});
});
it('still waitlists a non-owner member even when allowOverflow is set', async () => {
const memberGroup = {
...mockGroup,
members: [{ id: 'gm-1', role: 'MEMBER' }],
};
prisma.group.findUnique.mockResolvedValue(memberGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
const app = makeApp({ id: 'member-1' });
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.outcome).toBe('waitlisted');
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalled();
});
});
describe('POST /groups/:groupId/waitlist (add to group waitlist)', () => {
it('creates a waitlist entry for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
prisma.groupWaitlistEntry.create.mockResolvedValue({
id: 'wl-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
status: 'PENDING',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/waitlist', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '+54 9 11 3344-5566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
}),
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.fullName).toBe('Martín Gómez');
expect(body.phone).toBe('+5491133445566');
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
data: {
groupId: 'group-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: 'martin@example.com',
notes: 'Viene con su hermano',
},
});
});
it('rejects when the phone number already belongs to an attendee', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/waitlist', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('attendee_already_registered');
expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled();
});
it('rejects when the phone number is already on the waitlist', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue({ id: 'wl-existing' } as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/waitlist', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('already_waitlisted');
});
it('rejects user without access to the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
const app = makeApp({ id: 'other-user' });
const res = await app.request('/groups/group-1/waitlist', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
firstName: 'Martín',
lastName: 'Gómez',
phone: '1133445566',
}),
});
expect(res.status).toBe(403);
});
});
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);
// 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()}`,
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'),
}));
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees/bulk', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
attendees: [
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
{ 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(5);
expect(data.createdCount).toBe(3);
expect(data.linkedCount).toBe(1);
expect(data.duplicatesCount).toBe(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) } },
});
});
});
describe('GET /groups/:groupId/attendees', () => {
it('lists attendees filtered by groupId', async () => {
prisma.attendee.findMany.mockResolvedValue([
{
id: 'att-1',
groupId: 'group-1',
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: [],
payments: [],
},
] as never);
prisma.attendee.count.mockResolvedValue(1);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees');
expect(res.status).toBe(200);
const data = await res.json();
expect(data.data.length).toBe(1);
expect(data.data[0].fullName).toBe('Ana García');
expect(data.data[0].recentAttendance).toEqual([]);
expect(data.data[0].payment).toBeNull();
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1' },
skip: 0,
take: 10,
orderBy: { createdAt: 'desc' },
// 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,
select: { status: true },
},
payments: {
where: { status: { not: 'CANCELLED' } },
orderBy: { dueDate: 'desc' },
take: 3,
select: { status: true, dueDate: true },
},
},
});
});
});
});