import { afterEach, describe, expect, it, vi } from 'vitest'; import { Pay0CreditVerifier } from '../../src/document-workbench/pay0-credit-verification'; const snapshot = { tenantId: 'tenant-a', purchaseId: 'purchase-1', checkoutSessionId: 'session-1', amountMinor: 1000, currency: 'SEK', credits: 50, }; const context = { tenantId: 'tenant-a', actorId: 'svc-0pt', capability: '0pt.credit.purchase', correlationId: 'req-1', }; const checkout = { id: 'session-1', tenant_id: 'tenant-a', payment_intent_id: 'intent-1', payable_type: '0pt_credit_purchase', payable_ref: 'purchase-1', amount_snapshot: 1000, currency: 'SEK', status: 'completed', provider: 'stripe', provider_reference: 'stripe-session', }; const intent = { id: 'intent-1', tenant_id: 'tenant-a', payable_type: '0pt_credit_purchase', payable_ref: 'purchase-1', amount: 1000, currency: 'SEK', canonical_status: 'captured', captured_amount: 1000, refunded_amount: 0, }; function mockPay0(checkoutPatch: Record = {}, intentPatch: Record = {}) { return vi.stubGlobal( 'fetch', vi.fn( async (url: string) => new Response( JSON.stringify({ data: url.includes('checkout-sessions') ? { ...checkout, ...checkoutPatch } : { ...intent, ...intentPatch }, }), { status: 200, headers: { 'content-type': 'application/json' } }, ), ), ); } afterEach(() => vi.unstubAllGlobals()); describe('PAY0 credit verification', () => { it('derives a deterministic credit command only after both PAY0 reads match', async () => { mockPay0(); const command = await new Pay0CreditVerifier('https://pay0.test', 'service-token').verify( snapshot, context, ); expect(command).toEqual({ tenantId: 'tenant-a', idempotencyKey: 'pay0:credit-purchase:purchase-1', kind: 'verified_payment', reference: 'pay0:intent:intent-1', amount: 50, }); expect(fetch).toHaveBeenCalledTimes(2); }); it.each([ [{ tenant_id: 'tenant-b' }, {}], [{ status: 'processing' }, {}], [{ amount_snapshot: 1 }, {}], [{ provider_reference: undefined }, {}], [{}, { canonical_status: 'processing' }], [{}, { refunded_amount: 1 }], [{}, { captured_amount: 999 }], [{}, { payable_ref: 'other' }], ])('rejects mismatched or unconfirmed payment state', async (checkoutPatch, intentPatch) => { mockPay0(checkoutPatch, intentPatch); await expect( new Pay0CreditVerifier('https://pay0.test', 'service-token').verify(snapshot, context), ).rejects.toThrow(); }); it('rejects mismatched tenant before any call', async () => { mockPay0(); await expect( new Pay0CreditVerifier('https://pay0.test', 'service-token').verify(snapshot, { ...context, tenantId: 'other', }), ).rejects.toThrow(); expect(fetch).not.toHaveBeenCalled(); }); });