feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)

- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-26 17:01:07 -03:00
parent cd82a1e549
commit 9617447e05
42 changed files with 1938 additions and 457 deletions

View File

@@ -1,11 +1,15 @@
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';
import type { BillingProvider, ProviderSubscription } from '@/modules/billing/providers';
import {
MercadoPagoBillingProvider,
type MpAuthorizedPayment,
type PreapprovalClient,
} from '@/modules/billing/providers/mercado-pago';
const userId = 'user-1';
const now = new Date('2026-10-22T12:00:00.000Z');
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' });
const credentials = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' });
function subscription(overrides: Record<string, unknown> = {}) {
return {
@@ -14,7 +18,9 @@ function subscription(overrides: Record<string, unknown> = {}) {
country: 'AR',
currency: 'ARS',
status: 'PENDING',
mpPreapprovalId: 'pre-1',
provider: 'MERCADO_PAGO',
externalId: 'pre-1',
checkoutRef: null,
authorizedAt: null,
paidThrough: null,
...overrides,
@@ -62,8 +68,11 @@ function makeClient(params: { status?: string; externalReference?: string | null
} as unknown as PreapprovalClient;
}
// The real Mercado Pago adapter over a fake preapproval client: the sync and
// the adapter's mapping are tested together.
function sync(db: ReturnType<typeof makeDb>, client: PreapprovalClient) {
return new SyncSubscription({ db: db as never, client, credentials, now: () => now });
const provider = new MercadoPagoBillingProvider({ client, credentials });
return new SyncSubscription({ db: db as never, providers: () => provider, now: () => now });
}
describe('SyncSubscription', () => {
@@ -74,10 +83,10 @@ describe('SyncSubscription', () => {
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
expect(db.billingCharge.upsert).toHaveBeenCalledWith({
where: { mpAuthorizedPaymentId: 'inv-1' },
where: { externalId: 'inv-1' },
create: {
subscriptionId: 'sub-1',
mpAuthorizedPaymentId: 'inv-1',
externalId: 'inv-1',
amount: 15000,
currency: 'ARS',
status: 'approved',
@@ -88,15 +97,36 @@ describe('SyncSubscription', () => {
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: {
externalId: undefined,
status: 'AUTHORIZED',
authorizedAt: now,
nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'),
paidThrough: new Date('2026-11-20T10:00:00.000Z'),
payerEmail: undefined,
lastSyncedAt: now,
},
});
});
it('still marks the subscription authorized when listing the charges fails', async () => {
const db = makeDb(subscription());
const client = makeClient({});
(client.searchAuthorizedPayments as ReturnType<typeof mock>).mockImplementation(async () => {
throw new Error('400 Invalid value for limit');
});
const result = await sync(db, client).execute('sub-1');
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
expect(db.billingCharge.upsert).not.toHaveBeenCalled();
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
expect(data.status).toBe('AUTHORIZED');
expect(data.authorizedAt).toEqual(now);
expect(data.paidThrough).toBeNull();
// Without `lastSyncedAt` the next sync retries the charges.
expect(data.lastSyncedAt).toBeUndefined();
});
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 }));
@@ -142,11 +172,11 @@ describe('SyncSubscription', () => {
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');
const result = await sync(db, makeClient({})).byExternalId('MERCADO_PAGO', 'pre-1', 'AR');
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
where: { userId, country: 'AR', mpPreapprovalId: null },
data: { mpPreapprovalId: 'pre-1' },
where: { userId, provider: 'MERCADO_PAGO', externalId: null, country: 'AR' },
data: { externalId: 'pre-1' },
});
expect(result.ok && result.value.synced).toBe(true);
});
@@ -154,9 +184,92 @@ describe('SyncSubscription', () => {
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');
const result = await sync(db, makeClient({ status: 'cancelled' })).byExternalId('MERCADO_PAGO', 'old', 'AR');
expect(result).toEqual({ ok: true, value: { synced: false, status: null } });
expect(db.billingSubscription.updateMany).not.toHaveBeenCalled();
});
it('follows the row provider, not the country (a Mercado Pago subscription outside Argentina)', async () => {
const db = makeDb(subscription({ country: 'MX', currency: 'MXN' }));
const resolved: string[] = [];
const provider = new MercadoPagoBillingProvider({ client: makeClient({}), credentials });
await new SyncSubscription({
db: db as never,
providers: (id) => {
resolved.push(id);
return provider;
},
now: () => now,
}).execute('sub-1');
expect(resolved).toEqual(['MERCADO_PAGO']);
});
it('does nothing while the Stripe checkout is not completed', async () => {
const db = makeDb(subscription({ provider: 'STRIPE', externalId: null, checkoutRef: 'cs_1' }));
const provider = fakeProvider(null);
const result = await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute(
'sub-1',
);
expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } });
expect(provider.fetch).toHaveBeenCalledWith({ country: 'AR', externalId: null, checkoutRef: 'cs_1' });
expect(db.billingSubscription.update).not.toHaveBeenCalled();
});
it('stores the Stripe subscription id and payer email once the checkout completes', async () => {
const db = makeDb(subscription({ provider: 'STRIPE', country: 'MX', externalId: null, checkoutRef: 'cs_1' }));
const coveredUntil = new Date('2026-11-21T00:00:00.000Z');
const provider = fakeProvider(
{
externalId: 'sub_stripe',
ownerUserId: userId,
status: 'AUTHORIZED',
nextPaymentDate: coveredUntil,
payerEmail: 'card@mail.com',
},
[
{
externalId: 'in_1',
amount: 199,
currency: 'MXN',
status: 'approved',
paidAt: new Date('2026-10-21T00:00:00.000Z'),
coveredUntil,
},
],
);
await new SyncSubscription({ db: db as never, providers: () => provider, now: () => now }).execute('sub-1');
expect(provider.listCharges).toHaveBeenCalledWith({ country: 'MX', externalId: 'sub_stripe', checkoutRef: 'cs_1' });
expect(db.billingSubscription.update).toHaveBeenCalledWith({
where: { id: 'sub-1' },
data: {
externalId: 'sub_stripe',
status: 'AUTHORIZED',
authorizedAt: now,
nextPaymentDate: coveredUntil,
paidThrough: coveredUntil,
payerEmail: 'card@mail.com',
lastSyncedAt: now,
},
});
});
});
function fakeProvider(remote: ProviderSubscription | null, charges: Awaited<ReturnType<BillingProvider['listCharges']>> = []) {
return {
id: 'STRIPE',
requiresPayerEmail: false,
isAvailable: () => true,
start: mock(),
fetch: mock(async () => remote),
listCharges: mock(async () => charges),
cancel: mock(),
parseWebhook: mock(),
} satisfies BillingProvider;
}