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>
This commit is contained in:
Jose Selesan
2026-11-11 13:27:13 -03:00
parent aac142d324
commit 58c776e18c
89 changed files with 1805 additions and 110 deletions

View File

@@ -8,6 +8,9 @@ const db = {
attendee: {
findFirst: mock(),
},
personGuardian: {
findMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
@@ -44,9 +47,9 @@ const attendee = {
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
// The adult in charge, a person of their own.
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '5598765432', email: null } }],
// Every membership of the person: this one and another group.
attendees: [
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
@@ -69,6 +72,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
it('devuelve el participante del grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(attendee);
prisma.personGuardian.findMany.mockResolvedValue([{ child: { id: 'person-2', fullName: 'Tomás Pérez' } }]);
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
@@ -80,15 +84,21 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: '5512345678',
guardianPersonId: 'person-9',
guardianName: 'Luis Pérez',
guardianPhone: null,
guardianPhone: '5598765432',
guardianEmail: null,
notes: null,
notifyToken: 'token-1',
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' }],
siblings: [{ personId: 'person-2', fullName: 'Tomás Pérez' }],
});
expect(prisma.personGuardian.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { guardianId: 'person-9', childId: { not: 'person-1' } } }),
);
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
where: { id: 'a-1', groupId: 'group-1' },
include: {

View File

@@ -218,7 +218,7 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(res.status).toBe(201);
expect(prisma.person.findFirst).toHaveBeenCalledWith({
where: { id: 'person-1', createdById: teacherId },
select: { id: true, fullName: true },
select: expect.objectContaining({ id: true, fullName: true }),
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },

View File

@@ -24,9 +24,12 @@ const personSelect = {
fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
guardians: {
take: 1,
orderBy: { createdAt: 'asc' },
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
},
};
const person = {
@@ -34,9 +37,8 @@ const person = {
fullName: 'Ana Pérez',
email: 'ana@example.com',
phone: null,
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null,
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '1199990000', email: null } }],
};
const attendeeRow = {
@@ -75,8 +77,10 @@ describe('attendees routes', () => {
fullName: person.fullName,
email: person.email,
phone: person.phone,
guardianName: person.guardianName,
guardianPhone: person.guardianPhone,
guardianPersonId: 'person-9',
guardianName: 'Luis Pérez',
guardianPhone: '1199990000',
guardianEmail: null,
notes: person.notes,
createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(),

View File

@@ -39,9 +39,9 @@ describe('GetAttentionOverview', () => {
db.user.findUnique.mockResolvedValue({ country: 'AR' });
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
db.attendee.findMany.mockResolvedValue([
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) },
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) },
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) },
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', createdAt: at(90) },
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardians: [{ guardian: { phone: '1166660000' } }], createdAt: at(90) },
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, createdAt: at(90) },
]);
db.classSession.findMany.mockResolvedValue([
{ id: 's1', groupId: 'g1', startsAt: at(1) },

View File

@@ -1,11 +1,12 @@
import { describe, expect, it, mock } from 'bun:test';
import { err } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
planFeatureRequiredProblem,
planLimitReachedProblem,
} from '@/http/problem-builders';
import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case';
import { CreateGroup } from '@/modules/groups/features/create/use-case';
import { UpdateGroupUseCase } from '@/modules/groups/features/update/use-case';
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
@@ -14,7 +15,10 @@ const ownerId = 'owner-1';
describe('plan guards in the use cases', () => {
it('does not create a group past the Free limit', async () => {
const unitOfWork = { executeResult: mock() };
const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) };
const planGuard = {
canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))),
requireFeature: mock(async () => ok(undefined)),
};
const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
{} as never,
@@ -92,4 +96,100 @@ describe('plan guards in the use cases', () => {
expect(off.ok).toBe(true);
expect(db.group.update).toHaveBeenCalled();
});
it('needs the kidsGroups feature to create a kids group, not a regular one', async () => {
const unitOfWork = { executeResult: mock(async () => err({ status: 500 } as never)) };
const planGuard = {
canCreateGroup: mock(async () => ok(undefined)),
requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))),
};
const useCase = new CreateGroup({ unitOfWork: unitOfWork as never, planGuard });
const kids = await useCase.execute({ audience: 'KIDS' } as never, ownerId);
expect(kids.ok).toBe(false);
if (!kids.ok) expect(kids.error).toMatchObject({ status: 402, code: 'plan_feature_required', params: { feature: 'kidsGroups' } });
expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'kidsGroups');
expect(unitOfWork.executeResult).not.toHaveBeenCalled();
planGuard.requireFeature.mockClear();
await useCase.execute({ audience: 'ADULTS' } as never, ownerId);
expect(planGuard.requireFeature).not.toHaveBeenCalled();
expect(unitOfWork.executeResult).toHaveBeenCalled();
});
it('needs the kidsGroups feature to turn a group into a kids group, never to go back', async () => {
const db = {
group: {
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'ADULTS' })),
update: mock(async () => groupRow({ audience: 'ADULTS' })),
},
attendee: { count: mock(async () => 0) },
};
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))) };
const useCase = new UpdateGroupUseCase({ db: db as never, planGuard });
const toKids = await useCase.execute('g1', ownerId, { audience: 'KIDS' });
expect(toKids.ok).toBe(false);
expect(db.group.update).not.toHaveBeenCalled();
// An existing kids group keeps working after a downgrade: editing it does
// not ask for the feature again, and it can go back to adults.
db.group.findUnique.mockResolvedValue({ id: 'g1', createdById: ownerId, audience: 'KIDS' });
const rename = await useCase.execute('g1', ownerId, { name: 'Natación chicos', audience: 'KIDS' });
expect(rename.ok).toBe(true);
const toAdults = await useCase.execute('g1', ownerId, { audience: 'ADULTS' });
expect(toAdults.ok).toBe(true);
expect(planGuard.requireFeature).toHaveBeenCalledTimes(1);
expect(db.group.update).toHaveBeenLastCalledWith({ where: { id: 'g1' }, data: { audience: 'ADULTS' } });
});
it('does not turn a kids group back into adults while a kid has no phone of their own', async () => {
const db = {
group: {
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'KIDS' })),
update: mock(),
},
attendee: { count: mock(async () => 2) },
};
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { audience: 'ADULTS' });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatchObject({ status: 409, code: 'group_has_kids_without_phone', params: { count: 2 } });
}
expect(db.attendee.count).toHaveBeenCalledWith({
where: { groupId: 'g1', status: { not: 'DROPPED' }, person: { phone: null } },
});
expect(db.group.update).not.toHaveBeenCalled();
});
it('only lets the owner edit the group', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: 'someone-else', audience: 'ADULTS' })), update: mock() },
attendee: { count: mock() },
};
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { name: 'Otro' });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 403, code: 'group_owner_required' });
expect(db.group.update).not.toHaveBeenCalled();
});
});
function groupRow(overrides: Record<string, unknown> = {}) {
const at = new Date('2026-11-01T00:00:00.000Z');
return {
id: 'g1',
name: 'Natación',
description: null,
createdById: ownerId,
createdAt: at,
updatedAt: at,
days: ['MONDAY'],
time: '18:00',
capacity: 10,
price: 1000,
billingType: 'MONTHLY',
dueDay: 1,
...overrides,
};
}

View File

@@ -42,6 +42,7 @@ const group = {
inviteToken: null,
autoPaymentReminders: false,
autoReengagement: false,
audience: 'ADULTS',
};
function makeApp(userValue: unknown) {
@@ -223,6 +224,7 @@ describe('groups routes', () => {
price: 500,
billingType: 'MONTHLY',
dueDay: 5,
audience: 'ADULTS',
},
});
expect(prisma.groupMember.create).toHaveBeenCalledWith({

View File

@@ -0,0 +1,219 @@
import { describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { CreateAttendeeUseCase } from '@/modules/attendees/features/create/use-case';
import { UpdateAttendeeGuardian } from '@/modules/attendees/features/update-guardian/use-case';
import { contactPhone, findPersonSummaryByPhone } from '@/modules/people/lib/people';
const ownerId = 'owner-1';
const at = new Date('2026-11-01T00:00:00.000Z');
function kidsGroup(overrides: Record<string, unknown> = {}) {
return { id: 'g1', createdById: ownerId, capacity: null, audience: 'KIDS', members: [], ...overrides };
}
function createdAttendee(guardian = { id: 'adult-1', fullName: 'Ana Pérez', phone: '1155550000', email: null }) {
return {
id: 'att-1',
groupId: 'g1',
personId: 'kid-1',
notifyToken: null,
createdAt: at,
updatedAt: at,
person: { id: 'kid-1', fullName: 'Juan Pérez', email: null, phone: null, notes: null, guardians: [{ guardian }] },
};
}
function makeDb(overrides: { adult?: unknown; sameNameKid?: unknown } = {}) {
return {
group: { findUnique: mock(async () => kidsGroup()) },
person: {
// 1st call: the adult by phone. 2nd: a kid of that adult with the same name.
findFirst: mock()
.mockResolvedValueOnce(overrides.adult ?? null)
.mockResolvedValueOnce(overrides.sameNameKid ?? null),
},
attendee: {
findFirst: mock(async () => null),
count: mock(async () => 0),
create: mock(async () => createdAttendee()),
update: mock(),
},
groupWaitlistEntry: { findFirst: mock(), create: mock() },
};
}
const planGuard = { canAddAttendees: mock(async () => ok(undefined)) };
const guardian = { fullName: 'Ana Pérez', phone: '11 5555-0000' };
describe('kids groups: adding a kid', () => {
it('asks for the adult in charge', async () => {
const db = makeDb();
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Juan',
lastName: 'Pérez',
phone: '1144440000',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 400, code: 'guardian_required' });
expect(db.attendee.create).not.toHaveBeenCalled();
});
it('creates the kid with no phone and a new adult in charge', async () => {
const db = makeDb();
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Juan',
lastName: 'Pérez',
guardian,
});
expect(result.ok).toBe(true);
if (result.ok && result.value.outcome === 'created') {
expect(result.value.attendee).toMatchObject({ guardianName: 'Ana Pérez', guardianPhone: '1155550000', phone: null });
}
expect(db.attendee.create).toHaveBeenCalledWith(
expect.objectContaining({
data: {
group: { connect: { id: 'g1' } },
person: {
create: {
createdById: ownerId,
fullName: 'Juan Pérez',
phone: null,
email: null,
notes: null,
guardians: {
create: {
guardian: { create: { createdById: ownerId, fullName: 'Ana Pérez', phone: '1155550000', email: null } },
},
},
},
},
},
}),
);
});
it('links a sibling to the adult the teacher already has (same phone)', async () => {
const db = makeDb({ adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] } });
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Sofía',
lastName: 'Pérez',
guardian,
});
expect(result.ok).toBe(true);
// The sibling lookup: same adult, same name, case-insensitive.
expect(db.person.findFirst.mock.calls[1]?.[0]).toMatchObject({
where: {
createdById: ownerId,
fullName: { equals: 'Sofía Pérez', mode: 'insensitive' },
guardians: { some: { guardianId: 'adult-1' } },
},
});
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({
data: { person: { create: { fullName: 'Sofía Pérez', guardians: { create: { guardian: { connect: { id: 'adult-1' } } } } } } },
});
});
it('recognizes the same kid of the same adult instead of creating a twin', async () => {
const db = makeDb({
adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] },
sameNameKid: { id: 'kid-1', fullName: 'Juan Pérez', phone: null, guardians: [] },
});
db.attendee.findFirst.mockResolvedValue({ id: 'att-1', status: 'ACTIVE' } as never);
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'juan',
lastName: 'pérez',
guardian,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ code: 'attendee_already_registered' });
expect(db.attendee.create).not.toHaveBeenCalled();
});
it('keeps asking for a phone in an adults group', async () => {
const db = makeDb();
db.group.findUnique.mockResolvedValue(kidsGroup({ audience: 'ADULTS' }));
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Ana',
lastName: '',
});
expect(result.ok).toBe(true);
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({ data: { person: { create: { phone: null } } } });
});
});
describe('kids groups: contact', () => {
it('reaches a kid through the adult in charge', () => {
expect(contactPhone({ phone: '1144440000', guardians: [{ guardian: { phone: '1155550000' } }] })).toBe('1155550000');
expect(contactPhone({ phone: '1144440000', guardians: [] })).toBe('1144440000');
expect(contactPhone({ phone: null })).toBeNull();
});
it('the lookup by phone offers the kids of that adult', async () => {
const db = {
person: {
findFirst: mock(async () => ({ id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] })),
findUnique: mock(async () => ({
children: [
{
child: {
id: 'kid-1',
fullName: 'Juan Pérez',
attendees: [{ id: 'att-1', groupId: 'g1', status: 'ACTIVE', group: { name: 'Natación' } }],
},
},
],
})),
},
};
const summary = await findPersonSummaryByPhone(db as never, ownerId, '1155550000');
expect(summary?.children).toEqual([
{ id: 'kid-1', fullName: 'Juan Pérez', groups: [{ attendeeId: 'att-1', groupId: 'g1', groupName: 'Natación', status: 'ACTIVE' }] },
]);
});
});
describe('kids groups: editing the adult in charge', () => {
function guardianDb(person: Record<string, unknown>) {
return {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [] })) },
attendee: {
findFirst: mock(async () => ({ personId: 'kid-1', person: { id: 'kid-1', ...person } })),
findUniqueOrThrow: mock(async () => createdAttendee()),
},
person: { update: mock(), findFirst: mock(async () => null), create: mock(async () => ({ id: 'adult-2' })) },
personGuardian: { create: mock() },
};
}
it('edits the adult the kid already has (shared with the siblings)', async () => {
const db = guardianDb({ phone: null, guardians: [{ guardian: { id: 'adult-1', fullName: 'Ana', phone: '1155550000', email: null } }] });
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
groupId: 'g1',
attendeeId: 'att-1',
userId: ownerId,
input: { fullName: 'Ana Pérez', phone: '11 5555-0001', email: 'ana@example.com' },
});
expect(result.ok).toBe(true);
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'adult-1' },
data: { fullName: 'Ana Pérez', phone: '1155550001', email: 'ana@example.com' },
});
expect(db.personGuardian.create).not.toHaveBeenCalled();
});
it('links a new adult when the kid had none', async () => {
const db = guardianDb({ phone: null, guardians: [] });
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
groupId: 'g1',
attendeeId: 'att-1',
userId: ownerId,
input: { fullName: 'Ana Pérez', phone: '1155550000' },
});
expect(result.ok).toBe(true);
expect(db.personGuardian.create).toHaveBeenCalledWith({ data: { childId: 'kid-1', guardianId: 'adult-2' } });
});
});

View File

@@ -207,6 +207,7 @@ describe('onboarding routes', () => {
dueDay: 5,
autoPaymentReminders: false,
autoReengagement: false,
audience: 'ADULTS',
},
onboardingCompleted: true,
});
@@ -220,6 +221,7 @@ describe('onboarding routes', () => {
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
audience: 'ADULTS',
},
});
expect(prisma.groupMember.create).toHaveBeenCalledWith({

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: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
attendee: { id: attendee.id, person: { phone: null, ...attendee } },
...overrides,
};
}
@@ -174,7 +174,7 @@ describe('payment reminders', () => {
it('falls back to the guardian phone and skips members without a usable one', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }),
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardians: [{ guardian: { phone: '1123456789' } }] }),
payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
]);