import { describe, expect, it, mock } from 'bun:test'; 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 = () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }); function subscription(overrides: Record = {}) { return { id: 'sub-1', userId, country: 'AR', currency: 'ARS', status: 'PENDING', provider: 'MERCADO_PAGO', externalId: 'pre-1', checkoutRef: null, authorizedAt: null, paidThrough: null, ...overrides, }; } function invoice(overrides: Partial = {}): 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 | 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; } // The real Mercado Pago adapter over a fake preapproval client: the sync and // the adapter's mapping are tested together. function sync(db: ReturnType, client: PreapprovalClient) { const provider = new MercadoPagoBillingProvider({ client, credentials }); return new SyncSubscription({ db: db as never, providers: () => provider, 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: { externalId: 'inv-1' }, create: { subscriptionId: 'sub-1', externalId: '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: { 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).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 }])[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 })); await sync(db, makeClient({ invoices: [invoice({ paymentStatus: 'rejected' })] })).execute('sub-1'); const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record }])[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 }])[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({})).byExternalId('MERCADO_PAGO', 'pre-1', 'AR'); expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({ where: { userId, provider: 'MERCADO_PAGO', externalId: null, country: 'AR' }, data: { externalId: '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' })).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> = []) { return { id: 'STRIPE', requiresPayerEmail: false, isAvailable: () => true, start: mock(), fetch: mock(async () => remote), listCharges: mock(async () => charges), cancel: mock(), parseWebhook: mock(), } satisfies BillingProvider; }