Files
gruperly/apps/backend/test/billing-plan-guards.test.ts
Jose Selesan 58c776e18c 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>
2026-11-11 13:27:13 -03:00

196 lines
8.4 KiB
TypeScript

import { describe, expect, it, mock } from 'bun:test';
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';
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))),
requireFeature: mock(async () => ok(undefined)),
};
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();
});
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,
};
}