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

117 lines
4.3 KiB
TypeScript

import { describe, expect, it, mock } from 'bun:test';
import { err, ok } from '@gruperly/shared';
import { noActiveSubscriptionProblem } from '@/http/problem-builders';
import { SelectPlan } from '@/modules/onboarding/features/select-plan/use-case';
const userId = 'user-1';
const now = new Date('2026-10-22T12:00:00.000Z');
function makeDb(subscription: Record<string, unknown> | null, user: Record<string, unknown> = {}) {
return {
user: {
findUnique: mock(async () => ({ id: userId, onboardingCompleted: false, ...user })),
update: mock(async () => ({})),
},
billingSubscription: {
findUnique: mock(async () => subscription),
update: mock(async () => ({})),
},
};
}
function makeDeps(db: ReturnType<typeof makeDb>) {
return {
db: db as never,
subscribe: { execute: mock(async () => ok({ checkoutUrl: 'https://mp/checkout' })) },
cancel: { execute: mock(async () => ok({ status: 'CANCELLED' as const })) },
now: () => now,
};
}
describe('SelectPlan (onboarding)', () => {
it('stores the country first and marks Free as chosen', async () => {
const db = makeDb(null);
const deps = makeDeps(db);
const result = await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'CL' });
expect(result).toEqual(ok({ plan: 'FREE', checkoutUrl: null }));
expect(db.user.update).toHaveBeenNthCalledWith(1, { where: { id: userId }, data: { country: 'CL' } });
expect(db.user.update).toHaveBeenNthCalledWith(2, { where: { id: userId }, data: { planSelectedAt: now } });
expect(deps.subscribe.execute).not.toHaveBeenCalled();
});
it('voids an abandoned Pro attempt when switching to Free', async () => {
const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: 'pre-1' });
const deps = makeDeps(db);
await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' });
expect(deps.cancel.execute).toHaveBeenCalledWith(userId);
});
it('voids it locally when Mercado Pago never got the attempt', async () => {
const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: null });
const deps = makeDeps(db);
deps.cancel.execute = mock(async () => err(noActiveSubscriptionProblem())) as never;
await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' });
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: { status: 'CANCELLED', nextPaymentDate: null },
});
});
it('starts the subscription for Pro and comes back to the onboarding', async () => {
const db = makeDb(null);
const deps = makeDeps(db);
const result = await new SelectPlan(deps).execute(userId, {
plan: 'PRO',
country: 'AR',
payerEmail: 'profe@mail.com',
});
expect(result).toEqual(ok({ plan: 'PRO', checkoutUrl: 'https://mp/checkout' }));
expect(deps.subscribe.execute).toHaveBeenCalledWith(userId, {
payerEmail: 'profe@mail.com',
returnTo: 'onboarding',
});
expect(db.user.update).toHaveBeenLastCalledWith({ where: { id: userId }, data: { planSelectedAt: now } });
});
it('does not mark a plan when the subscription could not start', async () => {
const db = makeDb(null);
const deps = makeDeps(db);
deps.subscribe.execute = mock(async () => err({ title: 'x', status: 503, code: 'billing_not_available' })) as never;
const result = await new SelectPlan(deps).execute(userId, {
plan: 'PRO',
country: 'PE',
payerEmail: 'profe@mail.com',
});
expect(result.ok).toBe(false);
expect(db.user.update).toHaveBeenCalledTimes(1);
});
it('never drops an authorized subscription from the onboarding', async () => {
const db = makeDb({ id: 'sub-1', status: 'AUTHORIZED' });
const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('subscription_already_active');
});
it('refuses once the onboarding is completed', async () => {
const db = makeDb(null, { onboardingCompleted: true });
const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('onboarding_already_completed');
});
});