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 = {}) { return { id: 'sub-1', userId, country: 'AR', currency: 'ARS', status: 'PENDING', mpPreapprovalId: 'pre-1', 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; } function sync(db: ReturnType, 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 }])[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({})).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(); }); });