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>
This commit is contained in:
182
apps/backend/test/billing-subscribe.test.ts
Normal file
182
apps/backend/test/billing-subscribe.test.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { billingNotAvailableProblem } from '@/http/problem-builders';
|
||||
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
|
||||
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
|
||||
import type { PreapprovalClient } from '@/modules/billing/lib';
|
||||
|
||||
const userId = 'user-1';
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' });
|
||||
|
||||
let calls: string[] = [];
|
||||
|
||||
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'MX') {
|
||||
return {
|
||||
user: { findUnique: mock(async () => ({ id: userId, country })) },
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => existing),
|
||||
upsert: mock(async (args: { create: Record<string, unknown> }) => {
|
||||
calls.push('upsert');
|
||||
return { id: 'sub-1', paidThrough: existing?.paidThrough ?? null, ...args.create };
|
||||
}),
|
||||
update: mock(async () => {
|
||||
calls.push('update');
|
||||
return {};
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeClient(): PreapprovalClient {
|
||||
return {
|
||||
createPreapproval: mock(async () => {
|
||||
calls.push('createPreapproval');
|
||||
return { id: 'pre-1', status: 'pending', externalReference: userId, initPoint: 'https://mp/checkout', nextPaymentDate: null };
|
||||
}),
|
||||
cancelPreapproval: mock(async () => {
|
||||
calls.push('cancelPreapproval');
|
||||
return { id: 'old', status: 'cancelled', externalReference: userId, initPoint: null, nextPaymentDate: null };
|
||||
}),
|
||||
getPreapproval: mock(),
|
||||
getAuthorizedPayment: mock(),
|
||||
searchAuthorizedPayments: mock(),
|
||||
} as unknown as PreapprovalClient;
|
||||
}
|
||||
|
||||
function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
|
||||
return {
|
||||
client,
|
||||
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
|
||||
new Subscribe({ db: db as never, client, credentials, webOrigin: 'http://web', now: () => now }).execute(
|
||||
userId,
|
||||
{ payerEmail: 'profe@mail.com', returnTo },
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
describe('Subscribe', () => {
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
it('writes the PENDING row before asking Mercado Pago, in the country currency', async () => {
|
||||
const db = makeDb(null);
|
||||
const { client, run } = subscribe(db);
|
||||
|
||||
const result = await run();
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://mp/checkout' } });
|
||||
expect(calls).toEqual(['upsert', 'createPreapproval', 'update']);
|
||||
expect(client.createPreapproval).toHaveBeenCalledWith('platform-token', {
|
||||
reason: 'Gruperly Pro',
|
||||
externalReference: userId,
|
||||
payerEmail: 'profe@mail.com',
|
||||
amount: 199,
|
||||
currencyId: 'MXN',
|
||||
backUrl: 'http://web/billing?sub=return',
|
||||
startDate: undefined,
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { mpPreapprovalId: 'pre-1', lastSyncedAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the onboarding back to its own step', async () => {
|
||||
const { client, run } = subscribe(makeDb(null));
|
||||
await run('onboarding');
|
||||
|
||||
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
|
||||
backUrl: 'http://web/onboarding?sub=return',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a second subscription while one is authorized', async () => {
|
||||
const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', mpPreapprovalId: 'pre-0' }));
|
||||
|
||||
const result = await run();
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 409, code: 'subscription_already_active' });
|
||||
expect(client.createPreapproval).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels an abandoned attempt before starting a new one', async () => {
|
||||
const { run } = subscribe(makeDb({ status: 'PENDING', mpPreapprovalId: 'old' }));
|
||||
|
||||
await run();
|
||||
|
||||
expect(calls).toEqual(['cancelPreapproval', 'upsert', 'createPreapproval', 'update']);
|
||||
});
|
||||
|
||||
it('delays the first charge to the end of a period already paid', async () => {
|
||||
const paidThrough = new Date('2026-11-10T00:00:00.000Z');
|
||||
const { client, run } = subscribe(makeDb({ status: 'CANCELLED', mpPreapprovalId: 'old', paidThrough }));
|
||||
|
||||
await run();
|
||||
|
||||
expect(client.cancelPreapproval).not.toHaveBeenCalled();
|
||||
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
|
||||
startDate: paidThrough,
|
||||
});
|
||||
});
|
||||
|
||||
it('answers 503 when Gruperly has no account in that country', async () => {
|
||||
const db = makeDb(null, 'PE');
|
||||
const client = makeClient();
|
||||
const result = await new Subscribe({
|
||||
db: db as never,
|
||||
client,
|
||||
credentials: () => ({ ok: false, error: billingNotAvailableProblem() }),
|
||||
}).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing' });
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' });
|
||||
expect(db.billingSubscription.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a Mercado Pago failure as 502 and keeps the row', async () => {
|
||||
const client = makeClient();
|
||||
client.createPreapproval = mock(async () => {
|
||||
throw new Error('down');
|
||||
}) as never;
|
||||
const db = makeDb(null);
|
||||
|
||||
const result = await subscribe(db, client).run();
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.status).toBe(502);
|
||||
expect(db.billingSubscription.upsert).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CancelSubscription', () => {
|
||||
it('cancels in Mercado Pago and keeps what was paid', async () => {
|
||||
const db = {
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => ({ id: 'sub-1', status: 'AUTHORIZED', mpPreapprovalId: 'pre-1', country: 'AR' })),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
};
|
||||
const client = makeClient();
|
||||
|
||||
const result = await new CancelSubscription({ db: db as never, client, credentials }).execute(userId);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } });
|
||||
expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1');
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('has nothing to cancel without a live subscription', async () => {
|
||||
const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } };
|
||||
|
||||
const result = await new CancelSubscription({ db: db as never, client: makeClient(), credentials }).execute(userId);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.code).toBe('no_active_subscription');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user