Files
gruperly/apps/backend/test/billing-plan-guards.test.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

96 lines
4.1 KiB
TypeScript

import { describe, expect, it, mock } from 'bun:test';
import { err } 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 { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
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 result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
{} as never,
ownerId,
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' });
expect(unitOfWork.executeResult).not.toHaveBeenCalled();
});
it('checks a bulk import against the group owner, with the number of new attendees', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
attendee: { create: mock() },
// '1111' is already in this group; '4444' is active in another group.
person: {
findMany: mock(async () => [
{ id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] },
{ id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] },
]),
},
};
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
const result = await new BulkCreateAttendeesUseCase({ db: db as never, planGuard }).execute('g1', 'admin-1', {
attendees: [
{ fullName: 'Ana', phone: '2222' },
{ fullName: 'Beto', phone: '3333' },
{ fullName: 'Repetido', phone: '1111' },
{ fullName: 'De otro grupo', phone: '4444' },
],
} as never);
// Only the two new people: the one already active elsewhere takes no slot.
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
expect(result.ok).toBe(false);
expect(db.attendee.create).not.toHaveBeenCalled();
});
it('keeps charging with Mercado Pago for Pro', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, price: 100, members: [] })) },
attendee: { findMany: mock() },
payment: { create: mock() },
user: { findUnique: mock() },
};
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('mpCharges'))) };
const result = await new CreatePaymentBatch({ db: db as never, planGuard }).execute('g1', ownerId, {
dueDate: '2026-11-05T12:00:00.000Z',
});
expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'mpCharges');
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' });
expect(db.attendee.findMany).not.toHaveBeenCalled();
});
it('blocks turning automations on for Free, but lets them be turned off', async () => {
const db = {
group: {
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId })),
update: mock(async () => ({ autoPaymentReminders: false, autoReengagement: false })),
},
};
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('whatsappAutomations'))) };
const useCase = new UpdateGroupAutomationsUseCase({ db: db as never, planGuard });
const on = await useCase.execute('g1', ownerId, { autoPaymentReminders: true });
expect(on.ok).toBe(false);
expect(db.group.update).not.toHaveBeenCalled();
const off = await useCase.execute('g1', ownerId, { autoPaymentReminders: false });
expect(off.ok).toBe(true);
expect(db.group.update).toHaveBeenCalled();
});
});