- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER. - Vinculación del WhatsApp del profesor en el onboarding y en Ajustes. - Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a alumnos en riesgo (cooldown 14 días), con switches por grupo. - Idempotencia por (kind, attendee, semana ISO), webhooks firmados con HMAC y deduplicados, normalización de teléfonos a E.164. - Servicio openwa en docker-compose y guía en docs/whatsapp.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
7.7 KiB
TypeScript
267 lines
7.7 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,
|
|
};
|
|
|
|
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 } } }],
|
|
};
|
|
// 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' } } },
|
|
},
|
|
},
|
|
});
|
|
});
|
|
|
|
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,
|
|
},
|
|
});
|
|
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();
|
|
});
|
|
}); |