Files
gruperly/apps/backend/test/onboarding.test.ts
Jose Selesan f5e77c99f6 feat(billing): planes Free/Pro con Suscripciones de Mercado Pago
- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales
  de plataforma por país, webhook firmado y reconciliación por polling.
- PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o
  activan automatizaciones (402 plan_limit_reached / plan_feature_required /
  plan_read_only), detrás de BILLING_ENFORCEMENT.
- Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se
  saltean Cobros y WhatsApp.
- Web: pantalla /billing, aviso de Pro desde el MutationCache.
- Migración billing_subscriptions y docs/billing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:49:27 -03:00

308 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,
},
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,
},
});
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);
});
});
});