- 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>
274 lines
7.9 KiB
TypeScript
274 lines
7.9 KiB
TypeScript
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
|
|
const db = {
|
|
group: {
|
|
findMany: mock(),
|
|
count: mock(),
|
|
create: mock(),
|
|
},
|
|
groupMember: {
|
|
create: 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';
|
|
import { ListGroups } from '@/modules/groups/features/get-all/use-case';
|
|
|
|
const userId = 'user-1';
|
|
const group = {
|
|
id: 'group-1',
|
|
name: 'Cuadrilla Alfa',
|
|
description: null,
|
|
createdById: userId,
|
|
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
|
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
|
days: null,
|
|
time: null,
|
|
capacity: null,
|
|
price: null,
|
|
billingType: null,
|
|
dueDay: null,
|
|
inviteToken: null,
|
|
autoPaymentReminders: false,
|
|
autoReengagement: false,
|
|
audience: 'ADULTS',
|
|
};
|
|
|
|
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;
|
|
}
|
|
|
|
describe('groups routes', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it('lists groups scoped to the current user', async () => {
|
|
prisma.group.findMany.mockResolvedValue([
|
|
{ ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } },
|
|
]);
|
|
prisma.group.count.mockResolvedValue(1);
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups');
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({
|
|
data: [
|
|
{
|
|
...group,
|
|
createdAt: group.createdAt.toISOString(),
|
|
updatedAt: group.updatedAt.toISOString(),
|
|
attendeesCount: 4,
|
|
waitlistCount: 1,
|
|
unpaidPaymentsCount: 3,
|
|
},
|
|
],
|
|
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
|
});
|
|
const where = {
|
|
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
|
};
|
|
// The occupancy counters ride along in the same query; the waitlist
|
|
// counts only PENDING, the ones still waiting for a spot.
|
|
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
|
where,
|
|
include: {
|
|
_count: {
|
|
select: {
|
|
attendees: true,
|
|
waitlist: { where: { status: 'PENDING' } },
|
|
payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
});
|
|
|
|
it('rejects listing groups without a session', async () => {
|
|
const res = await makeApp(null).request('/groups');
|
|
|
|
expect(res.status).toBe(401);
|
|
expect(await res.json()).toMatchObject({ code: 'unauthorized' });
|
|
});
|
|
|
|
it('rejects invalid pagination query parameters', async () => {
|
|
const res = await makeApp({ id: userId }).request('/groups?pageSize=101');
|
|
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('rejects an invalid time zone', async () => {
|
|
const res = await makeApp({ id: userId }).request('/groups?timeZone=Marte/Olympus');
|
|
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('ordena los grupos por la clase más cercana y deja al final los sin horario', async () => {
|
|
prisma.group.findMany.mockResolvedValue([
|
|
{ ...group, id: 'sin-horario', name: 'Sin horario' },
|
|
{ ...group, id: 'proxima-semana', name: 'Próxima semana', days: ['MONDAY'], time: '08:00' },
|
|
{ ...group, id: 'manana', name: 'Mañana', days: ['TUESDAY'], time: '09:00' },
|
|
{ ...group, id: 'hoy-tarde', name: 'Hoy a la tarde', days: ['MONDAY'], time: '18:00' },
|
|
{
|
|
...group,
|
|
id: 'hoy-tarde-viejo',
|
|
name: 'Hoy a la tarde (viejo)',
|
|
days: ['MONDAY'],
|
|
time: '18:00',
|
|
createdAt: new Date('2026-07-01T10:00:00.000Z'),
|
|
},
|
|
]);
|
|
|
|
// Monday 2026-01-05 at noon in Mexico City: the 18:00 class
|
|
// hasn't started yet, so that group goes first.
|
|
const result = await new ListGroups({
|
|
db,
|
|
now: new Date('2026-01-05T18:00:00.000Z'),
|
|
}).execute({ page: 1, pageSize: 10, timeZone: 'America/Mexico_City' }, userId);
|
|
|
|
expect(result.ok).toBe(true);
|
|
if (!result.ok) return;
|
|
// On a tie the newest one goes first, which was the previous criterion.
|
|
expect(result.value.data.map((item) => item.id)).toEqual([
|
|
'hoy-tarde',
|
|
'hoy-tarde-viejo',
|
|
'manana',
|
|
'proxima-semana',
|
|
'sin-horario',
|
|
]);
|
|
expect(result.value.pagination).toEqual({ page: 1, pageSize: 10, total: 5, totalPages: 1 });
|
|
});
|
|
|
|
it('pagina la lista ya ordenada por próxima clase', async () => {
|
|
prisma.group.findMany.mockResolvedValue([
|
|
{ ...group, id: 'a', name: 'A', days: ['MONDAY'], time: '10:00' },
|
|
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' },
|
|
]);
|
|
|
|
// Monday at noon: A's 10:00 class already happened, so its
|
|
// next occurrence is next Monday and B (Wednesday) goes first.
|
|
const result = await new ListGroups({
|
|
db,
|
|
now: new Date('2026-01-05T18:00:00.000Z'),
|
|
}).execute({ page: 2, pageSize: 1, timeZone: 'UTC' }, userId);
|
|
|
|
expect(result.ok).toBe(true);
|
|
if (!result.ok) return;
|
|
expect(result.value.data.map((item) => item.id)).toEqual(['a']);
|
|
expect(result.value.pagination).toEqual({ page: 2, pageSize: 1, total: 2, totalPages: 2 });
|
|
});
|
|
|
|
it('creates a group with billing configuration', async () => {
|
|
prisma.group.create.mockResolvedValue({
|
|
...group,
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
});
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups', {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
name: 'Cuadrilla Alfa',
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
}),
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(await res.json()).toEqual({
|
|
group: {
|
|
...group,
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
createdAt: group.createdAt.toISOString(),
|
|
updatedAt: group.updatedAt.toISOString(),
|
|
},
|
|
});
|
|
expect(prisma.group.create).toHaveBeenCalledWith({
|
|
data: {
|
|
name: 'Cuadrilla Alfa',
|
|
createdById: userId,
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
audience: 'ADULTS',
|
|
},
|
|
});
|
|
expect(prisma.groupMember.create).toHaveBeenCalledWith({
|
|
data: { groupId: 'group-1', userId, role: 'OWNER' },
|
|
});
|
|
});
|
|
|
|
it('creates a group without Mercado Pago linked, since linking is optional', async () => {
|
|
prisma.group.create.mockResolvedValue({
|
|
...group,
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
});
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups', {
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
name: 'Cuadrilla Alfa',
|
|
days: ['MONDAY'],
|
|
time: '09:00',
|
|
capacity: 20,
|
|
price: 500,
|
|
billingType: 'MONTHLY',
|
|
dueDay: 5,
|
|
}),
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
expect(res.status).toBe(201);
|
|
expect(prisma.group.create).toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects creating a group with an invalid payload', async () => {
|
|
const res = await makeApp({ id: userId }).request('/groups', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ name: 'x' }),
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
expect(res.status).toBe(400);
|
|
expect(prisma.group.create).not.toHaveBeenCalled();
|
|
});
|
|
}); |