Files
gruperly/apps/backend/test/groups.test.ts
Jose Selesan 454f20ed25 feat(api): add timezone support for group fetching and increase page size
feat(attendance): refactor attendance summary logic and update tests

feat(analytics): extend GroupRiskSummary schema with absence and attendance counts

feat(groups): enhance group schema with attendee and waitlist counts

chore(skills): add frontend design skill with guidelines and license

feat(attendee-detail): implement AttendeePhoneLine component for phone display

feat(groups): create AttendanceBadge and CapacityIndicator components for group cards

feat(groups): add card utility functions for attendance alerts and capacity summaries

test(groups): implement tests for attendance alert and capacity summary logic
2026-09-30 17:39:13 -03:00

262 lines
7.8 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(),
},
merchantAccount: {
findUnique: 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,
};
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 } },
]);
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,
},
],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
});
const where = {
OR: [{ createdById: userId }, { members: { some: { userId } } }],
};
// Los contadores de ocupación viajan en la misma consulta; la lista de
// espera cuenta solo los PENDING, los que siguen esperando cupo.
expect(prisma.group.findMany).toHaveBeenCalledWith({
where,
include: {
_count: {
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
},
},
});
});
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'),
},
]);
// Lunes 2026-01-05 al mediodía en Ciudad de México: la clase de las 18:00
// todavía no empieza, así que ese grupo va primero.
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;
// A igual clase se pone delante el más nuevo, que era el criterio anterior.
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' },
]);
// Lunes al mediodía: la clase de las 10:00 de A ya pasó, así que su
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero.
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.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
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,
},
});
expect(prisma.groupMember.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', userId, role: 'OWNER' },
});
});
it('rejects creating a group without a linked merchant account', async () => {
prisma.merchantAccount.findUnique.mockResolvedValue(null);
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(409);
expect(await res.json()).toMatchObject({ code: 'payment_not_setup' });
expect(prisma.group.create).not.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();
});
});