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:
162
apps/backend/test/billing-sync.test.ts
Normal file
162
apps/backend/test/billing-sync.test.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import type { MpAuthorizedPayment, PreapprovalClient } from '@/modules/billing/lib';
|
||||
import { SyncSubscription } from '@/modules/billing/lib/sync';
|
||||
|
||||
const userId = 'user-1';
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' });
|
||||
|
||||
function subscription(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'sub-1',
|
||||
userId,
|
||||
country: 'AR',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
mpPreapprovalId: 'pre-1',
|
||||
authorizedAt: null,
|
||||
paidThrough: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function invoice(overrides: Partial<MpAuthorizedPayment> = {}): MpAuthorizedPayment {
|
||||
return {
|
||||
id: 'inv-1',
|
||||
preapprovalId: 'pre-1',
|
||||
status: 'processed',
|
||||
paymentStatus: 'approved',
|
||||
amount: 15000,
|
||||
currencyId: 'ARS',
|
||||
debitDate: '2026-10-20T10:00:00.000Z',
|
||||
createdAt: '2026-10-20T09:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDb(row: Record<string, unknown> | null) {
|
||||
return {
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => row),
|
||||
update: mock(async () => ({})),
|
||||
updateMany: mock(async () => ({ count: 0 })),
|
||||
},
|
||||
billingCharge: { upsert: mock(async () => ({})) },
|
||||
};
|
||||
}
|
||||
|
||||
function makeClient(params: { status?: string; externalReference?: string | null; invoices?: MpAuthorizedPayment[] }) {
|
||||
return {
|
||||
getPreapproval: mock(async (_token: string, id: string) => ({
|
||||
id,
|
||||
status: params.status ?? 'authorized',
|
||||
externalReference: params.externalReference === undefined ? userId : params.externalReference,
|
||||
initPoint: null,
|
||||
nextPaymentDate: '2026-11-20T10:00:00.000Z',
|
||||
})),
|
||||
searchAuthorizedPayments: mock(async () => params.invoices ?? []),
|
||||
createPreapproval: mock(),
|
||||
cancelPreapproval: mock(),
|
||||
getAuthorizedPayment: mock(),
|
||||
} as unknown as PreapprovalClient;
|
||||
}
|
||||
|
||||
function sync(db: ReturnType<typeof makeDb>, client: PreapprovalClient) {
|
||||
return new SyncSubscription({ db: db as never, client, credentials, now: () => now });
|
||||
}
|
||||
|
||||
describe('SyncSubscription', () => {
|
||||
it('marks the subscription authorized and extends paidThrough one month from the debit', async () => {
|
||||
const db = makeDb(subscription());
|
||||
|
||||
const result = await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
|
||||
expect(db.billingCharge.upsert).toHaveBeenCalledWith({
|
||||
where: { mpAuthorizedPaymentId: 'inv-1' },
|
||||
create: {
|
||||
subscriptionId: 'sub-1',
|
||||
mpAuthorizedPaymentId: 'inv-1',
|
||||
amount: 15000,
|
||||
currency: 'ARS',
|
||||
status: 'approved',
|
||||
paidAt: new Date('2026-10-20T10:00:00.000Z'),
|
||||
},
|
||||
update: { status: 'approved', paidAt: new Date('2026-10-20T10:00:00.000Z') },
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: {
|
||||
status: 'AUTHORIZED',
|
||||
authorizedAt: now,
|
||||
nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'),
|
||||
paidThrough: new Date('2026-11-20T10:00:00.000Z'),
|
||||
lastSyncedAt: now,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('records a rejected charge without extending what was paid', async () => {
|
||||
const paidThrough = new Date('2026-10-25T00:00:00.000Z');
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough }));
|
||||
|
||||
await sync(db, makeClient({ invoices: [invoice({ paymentStatus: 'rejected' })] })).execute('sub-1');
|
||||
|
||||
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
|
||||
expect(data.paidThrough).toEqual(paidThrough);
|
||||
expect(data.authorizedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('never moves paidThrough back', async () => {
|
||||
const paidThrough = new Date('2027-01-01T00:00:00.000Z');
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED', paidThrough }));
|
||||
|
||||
await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1');
|
||||
|
||||
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
|
||||
expect(data.paidThrough).toEqual(paidThrough);
|
||||
});
|
||||
|
||||
it('mirrors a cancellation done in Mercado Pago', async () => {
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED' }));
|
||||
|
||||
const result = await sync(db, makeClient({ status: 'cancelled' })).execute('sub-1');
|
||||
|
||||
expect(result.ok && result.value.status).toBe('CANCELLED');
|
||||
});
|
||||
|
||||
it('ignores a preapproval whose external_reference is not this user', async () => {
|
||||
const db = makeDb(subscription());
|
||||
|
||||
const result = await sync(db, makeClient({ externalReference: 'someone-else' })).execute('sub-1');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } });
|
||||
expect(db.billingSubscription.update).not.toHaveBeenCalled();
|
||||
expect(db.billingCharge.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('claims a preapproval that beat our own write of its id', async () => {
|
||||
const db = makeDb(null);
|
||||
let lookups = 0;
|
||||
db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never;
|
||||
db.billingSubscription.updateMany = mock(async () => ({ count: 1 }));
|
||||
|
||||
const result = await sync(db, makeClient({})).byPreapprovalId('AR', 'pre-1');
|
||||
|
||||
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId, country: 'AR', mpPreapprovalId: null },
|
||||
data: { mpPreapprovalId: 'pre-1' },
|
||||
});
|
||||
expect(result.ok && result.value.synced).toBe(true);
|
||||
});
|
||||
|
||||
it('does not claim a cancelled preapproval (a replaced attempt)', async () => {
|
||||
const db = makeDb(null);
|
||||
|
||||
const result = await sync(db, makeClient({ status: 'cancelled' })).byPreapprovalId('AR', 'old');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: false, status: null } });
|
||||
expect(db.billingSubscription.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user