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:
@@ -1,19 +1,19 @@
|
||||
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';
|
||||
import type { BillingProvider } from '@/modules/billing/providers';
|
||||
import { MercadoPagoBillingProvider, 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' });
|
||||
|
||||
let calls: string[] = [];
|
||||
|
||||
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'MX') {
|
||||
// Argentina: Mercado Pago. Any other country goes to Stripe.
|
||||
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'AR') {
|
||||
return {
|
||||
user: { findUnique: mock(async () => ({ id: userId, country })) },
|
||||
user: { findUnique: mock(async () => ({ id: userId, country, email: 'login@mail.com' })) },
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => existing),
|
||||
upsert: mock(async (args: { create: Record<string, unknown> }) => {
|
||||
@@ -44,11 +44,16 @@ function makeClient(): PreapprovalClient {
|
||||
} as unknown as PreapprovalClient;
|
||||
}
|
||||
|
||||
function mpProvider(client: PreapprovalClient) {
|
||||
return new MercadoPagoBillingProvider({ client, credentials });
|
||||
}
|
||||
|
||||
function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
|
||||
const provider = mpProvider(client);
|
||||
return {
|
||||
client,
|
||||
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
|
||||
new Subscribe({ db: db as never, client, credentials, webOrigin: 'http://web', now: () => now }).execute(
|
||||
new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute(
|
||||
userId,
|
||||
{ payerEmail: 'profe@mail.com', returnTo },
|
||||
),
|
||||
@@ -72,14 +77,14 @@ describe('Subscribe', () => {
|
||||
reason: 'Gruperly Pro',
|
||||
externalReference: userId,
|
||||
payerEmail: 'profe@mail.com',
|
||||
amount: 199,
|
||||
currencyId: 'MXN',
|
||||
amount: 15000,
|
||||
currencyId: 'ARS',
|
||||
backUrl: 'http://web/billing?sub=return',
|
||||
startDate: undefined,
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { mpPreapprovalId: 'pre-1', lastSyncedAt: now },
|
||||
data: { externalId: 'pre-1', checkoutRef: null, lastSyncedAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -93,7 +98,7 @@ describe('Subscribe', () => {
|
||||
});
|
||||
|
||||
it('refuses a second subscription while one is authorized', async () => {
|
||||
const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', mpPreapprovalId: 'pre-0' }));
|
||||
const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', provider: 'MERCADO_PAGO', externalId: 'pre-0' }));
|
||||
|
||||
const result = await run();
|
||||
|
||||
@@ -103,7 +108,7 @@ describe('Subscribe', () => {
|
||||
});
|
||||
|
||||
it('cancels an abandoned attempt before starting a new one', async () => {
|
||||
const { run } = subscribe(makeDb({ status: 'PENDING', mpPreapprovalId: 'old' }));
|
||||
const { run } = subscribe(makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null }));
|
||||
|
||||
await run();
|
||||
|
||||
@@ -112,7 +117,7 @@ describe('Subscribe', () => {
|
||||
|
||||
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 }));
|
||||
const { client, run } = subscribe(makeDb({ status: 'CANCELLED', provider: 'MERCADO_PAGO', externalId: 'old', paidThrough }));
|
||||
|
||||
await run();
|
||||
|
||||
@@ -123,13 +128,13 @@ describe('Subscribe', () => {
|
||||
});
|
||||
|
||||
it('answers 503 when Gruperly has no account in that country', async () => {
|
||||
const db = makeDb(null, 'PE');
|
||||
const db = makeDb(null, 'AR');
|
||||
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' });
|
||||
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
|
||||
const result = await new Subscribe({ db: db as never, providers: () => provider }).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' });
|
||||
@@ -155,13 +160,21 @@ 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' })),
|
||||
findUnique: mock(async () => ({
|
||||
id: 'sub-1',
|
||||
status: 'AUTHORIZED',
|
||||
provider: 'MERCADO_PAGO',
|
||||
externalId: 'pre-1',
|
||||
checkoutRef: null,
|
||||
country: 'AR',
|
||||
})),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
};
|
||||
const client = makeClient();
|
||||
|
||||
const result = await new CancelSubscription({ db: db as never, client, credentials }).execute(userId);
|
||||
const provider = mpProvider(client);
|
||||
const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } });
|
||||
expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1');
|
||||
@@ -174,9 +187,113 @@ describe('CancelSubscription', () => {
|
||||
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);
|
||||
const provider = mpProvider(makeClient());
|
||||
const result = await new CancelSubscription({ db: db as never, providers: () => provider }).execute(userId);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.code).toBe('no_active_subscription');
|
||||
});
|
||||
});
|
||||
|
||||
function fakeStripe(overrides: Partial<BillingProvider> = {}) {
|
||||
return {
|
||||
id: 'STRIPE',
|
||||
requiresPayerEmail: false,
|
||||
isAvailable: () => true,
|
||||
start: mock(async () => {
|
||||
calls.push('start');
|
||||
return { checkoutUrl: 'https://checkout.stripe/cs_1', externalId: null, checkoutRef: 'cs_1' };
|
||||
}),
|
||||
fetch: mock(),
|
||||
listCharges: mock(),
|
||||
cancel: mock(async () => {
|
||||
calls.push('cancel');
|
||||
}),
|
||||
parseWebhook: mock(),
|
||||
...overrides,
|
||||
} as BillingProvider;
|
||||
}
|
||||
|
||||
describe('Subscribe outside Argentina (Stripe)', () => {
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
it('picks the provider of the country and starts a checkout without asking the email', async () => {
|
||||
const db = makeDb(null, 'MX');
|
||||
const stripe = fakeStripe();
|
||||
const resolved: string[] = [];
|
||||
|
||||
const result = await new Subscribe({
|
||||
db: db as never,
|
||||
providers: (id) => {
|
||||
resolved.push(id);
|
||||
return stripe;
|
||||
},
|
||||
webOrigin: 'http://web',
|
||||
now: () => now,
|
||||
}).execute(userId, { returnTo: 'billing' });
|
||||
|
||||
expect(resolved).toEqual(['STRIPE']);
|
||||
expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://checkout.stripe/cs_1' } });
|
||||
expect(stripe.start).toHaveBeenCalledWith({
|
||||
userId,
|
||||
country: 'MX',
|
||||
amount: 199,
|
||||
currency: 'MXN',
|
||||
payerEmail: null,
|
||||
backUrl: 'http://web/billing?sub=return',
|
||||
startDate: undefined,
|
||||
});
|
||||
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
|
||||
provider: 'STRIPE',
|
||||
payerEmail: 'login@mail.com',
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { externalId: null, checkoutRef: 'cs_1', lastSyncedAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
it('voids an abandoned attempt with the provider it was created with', async () => {
|
||||
const db = makeDb({ status: 'PENDING', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null }, 'MX');
|
||||
const client = makeClient();
|
||||
const mp = mpProvider(client);
|
||||
const stripe = fakeStripe();
|
||||
|
||||
await new Subscribe({
|
||||
db: db as never,
|
||||
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
|
||||
webOrigin: 'http://web',
|
||||
now: () => now,
|
||||
}).execute(userId, { returnTo: 'billing' });
|
||||
|
||||
expect(calls).toEqual(['cancelPreapproval', 'upsert', 'start', 'update']);
|
||||
});
|
||||
|
||||
it('answers 503 when Stripe is not configured', async () => {
|
||||
const db = makeDb(null, 'CL');
|
||||
const stripe = fakeStripe({ isAvailable: () => false });
|
||||
|
||||
const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, {
|
||||
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('still requires the payer email for Mercado Pago', async () => {
|
||||
const db = makeDb(null, 'AR');
|
||||
const provider = mpProvider(makeClient());
|
||||
|
||||
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
|
||||
returnTo: 'billing',
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 400 });
|
||||
expect(db.billingSubscription.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user