import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; 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 = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }); let calls: string[] = []; // Argentina: Mercado Pago. Any other country goes to Stripe. function makeDb(existing: Record | null, country: string | null = 'AR') { return { user: { findUnique: mock(async () => ({ id: userId, country, email: 'login@mail.com' })) }, billingSubscription: { findUnique: mock(async () => existing), upsert: mock(async (args: { create: Record }) => { 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 mpProvider(client: PreapprovalClient) { return new MercadoPagoBillingProvider({ client, credentials }); } function subscribe(db: ReturnType, client = makeClient()) { const provider = mpProvider(client); return { client, run: (returnTo: 'billing' | 'onboarding' = 'billing') => new Subscribe({ db: db as never, providers: () => provider, 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: 15000, currencyId: 'ARS', backUrl: 'http://web/billing?sub=return', startDate: undefined, }); expect(db.billingSubscription.update).toHaveBeenCalledWith({ where: { id: 'sub-1' }, data: { externalId: 'pre-1', checkoutRef: null, 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).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', provider: 'MERCADO_PAGO', externalId: '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', provider: 'MERCADO_PAGO', country: 'AR', externalId: 'old', checkoutRef: null })); 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', provider: 'MERCADO_PAGO', externalId: 'old', paidThrough })); await run(); expect(client.cancelPreapproval).not.toHaveBeenCalled(); expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ startDate: paidThrough, }); }); it('answers 503 when Gruperly has no account in that country', async () => { const db = makeDb(null, 'AR'); const client = makeClient(); 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' }); 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', provider: 'MERCADO_PAGO', externalId: 'pre-1', checkoutRef: null, country: 'AR', })), update: mock(async () => ({})), }, }; const client = makeClient(); 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'); 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 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 = {}) { 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 }])[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(); }); });