Files
gruperly/apps/backend/test/onboarding.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

310 lines
9.5 KiB
TypeScript

import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
user: {
findUnique: mock(),
update: mock(),
},
mpAccount: {
findUnique: mock(),
},
whatsappAccount: {
findUnique: mock(async () => null),
},
billingSubscription: {
findUnique: mock(async () => null),
},
group: {
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 { onboardingRoutes } from '@/modules/onboarding';
const userId = 'user-1';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/onboarding', onboardingRoutes);
return app;
}
const group = {
id: 'group-1',
name: 'Clase de Yoga',
description: null,
createdById: userId,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
time: '09:00',
capacity: 20,
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
autoPaymentReminders: false,
autoReengagement: false,
};
const firstGroupPayload = {
name: group.name,
days: group.days,
time: group.time,
capacity: group.capacity,
price: group.price,
billingType: group.billingType,
dueDay: group.dueDay,
country: 'AR',
};
const noPlan = { planSelected: false, selectedPlan: null, subscriptionStatus: null, country: null };
const planSelectedAt = new Date('2026-08-01T09:00:00.000Z');
describe('onboarding routes', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('GET /onboarding/status', () => {
it('returns NOT_STARTED for a user that has not started', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/onboarding/status');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
whatsappConnected: false,
completed: false,
...noPlan,
});
});
it('returns PAYMENT_CONNECTED when Mercado Pago is linked and active', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId: userId, status: 'ACTIVE' });
const res = await makeApp({ id: userId }).request('/onboarding/status');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
step: 'PAYMENT_CONNECTED',
paymentConnected: true,
whatsappConnected: false,
completed: false,
...noPlan,
});
});
it('returns NOT_STARTED when the account needs to be linked again', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
prisma.mpAccount.findUnique.mockResolvedValue({
id: 'mp-1',
ownerId: userId,
status: 'REQUIRES_REAUTH',
});
const res = await makeApp({ id: userId }).request('/onboarding/status');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
whatsappConnected: false,
completed: false,
...noPlan,
});
});
it('returns COMPLETED when onboarding is already done', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true });
const res = await makeApp({ id: userId }).request('/onboarding/status');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
step: 'COMPLETED',
paymentConnected: true,
whatsappConnected: false,
completed: true,
...noPlan,
});
});
it('reports a chosen Pro plan while its subscription is still pending', async () => {
prisma.user.findUnique.mockResolvedValue({
id: userId,
onboardingCompleted: false,
planSelectedAt,
country: 'MX',
});
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.billingSubscription.findUnique.mockResolvedValueOnce({ status: 'PENDING' });
const res = await makeApp({ id: userId }).request('/onboarding/status');
expect(await res.json()).toMatchObject({
planSelected: true,
selectedPlan: 'PRO',
subscriptionStatus: 'PENDING',
country: 'MX',
});
});
it('rejects without a session', async () => {
const res = await makeApp(null).request('/onboarding/status');
expect(res.status).toBe(401);
expect(await res.json()).toMatchObject({ code: 'unauthorized' });
});
});
describe('POST /onboarding/first-group', () => {
it('creates the first group and completes onboarding', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt });
prisma.group.create.mockResolvedValue(group);
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(firstGroupPayload),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(201);
expect(await res.json()).toEqual({
group: {
id: 'group-1',
name: 'Clase de Yoga',
description: null,
createdById: userId,
createdAt: group.createdAt.toISOString(),
updatedAt: group.updatedAt.toISOString(),
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
time: '09:00',
capacity: 20,
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
autoPaymentReminders: false,
autoReengagement: false,
audience: 'ADULTS',
},
onboardingCompleted: true,
});
expect(prisma.group.create).toHaveBeenCalledWith({
data: {
name: 'Clase de Yoga',
createdById: userId,
days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'],
time: '09:00',
capacity: 20,
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
audience: 'ADULTS',
},
});
expect(prisma.groupMember.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', userId, role: 'OWNER' },
});
expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: userId },
data: { onboardingCompleted: true, country: 'AR' },
});
});
it('creates the group without Mercado Pago linked, since that step is skippable', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt });
prisma.mpAccount.findUnique.mockResolvedValue(null);
prisma.group.create.mockResolvedValue(group);
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(firstGroupPayload),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(201);
expect(prisma.group.create).toHaveBeenCalled();
});
it('rejects until a plan was chosen, since the Plan step is mandatory', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt: null });
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(firstGroupPayload),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(409);
expect(await res.json()).toMatchObject({ code: 'plan_not_selected' });
expect(prisma.group.create).not.toHaveBeenCalled();
});
it('rejects when onboarding is already completed', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true });
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(firstGroupPayload),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(409);
expect(await res.json()).toMatchObject({ code: 'onboarding_already_completed' });
expect(prisma.group.create).not.toHaveBeenCalled();
});
it('rejects invalid payloads', async () => {
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify({
name: 'Ab',
days: [],
time: '25:99',
capacity: 0,
price: -1,
billingType: 'WEEKLY',
dueDay: 31,
}),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(400);
expect(prisma.group.create).not.toHaveBeenCalled();
});
it('rejects without a session', async () => {
const res = await makeApp(null).request('/onboarding/first-group', {
method: 'POST',
body: JSON.stringify(firstGroupPayload),
headers: { 'Content-Type': 'application/json' },
});
expect(res.status).toBe(401);
});
});
});