import { describe, expect, it } from 'vitest'; import type Stripe from 'stripe'; import { StripeCreditVerificationError, verifyStripeCreditPurchase, type StripeCheckoutReader, } from '../../src/document-workbench/stripe-credit-verification'; const snapshot = { tenantId: 't_0pt', purchaseId: 'purchase-1', checkoutSessionId: 'cs_test_1', amountMinor: 9900, currency: 'SEK', credits: 100, }; function stripeReturning(session: unknown): StripeCheckoutReader { return { checkout: { sessions: { retrieve: async () => session as Stripe.Checkout.Session, }, }, }; } function session(overrides: Record = {}) { return { id: 'cs_test_1', metadata: { kind: '0pt_credit_purchase', tenant_id: 't_0pt', purchase_id: 'purchase-1', }, amount_total: 9900, currency: 'sek', payment_status: 'paid', payment_intent: { id: 'pi_123', status: 'succeeded', currency: 'sek', amount_received: 9900, }, ...overrides, }; } describe('Stripe credit verification', () => { it('derives an idempotent verified-payment command from the re-read session', async () => { const command = await verifyStripeCreditPurchase(stripeReturning(session()), snapshot, { tenantId: 't_0pt', }); expect(command).toEqual({ tenantId: 't_0pt', idempotencyKey: 'credit_purchase:t_0pt:purchase-1', kind: 'verified_payment', reference: 'pi_123', amount: 100, }); }); it('refuses a session that belongs to another tenant or purchase', async () => { await expect( verifyStripeCreditPurchase( stripeReturning( session({ metadata: { kind: '0pt_credit_purchase', tenant_id: 't_b', purchase_id: 'purchase-1' } }), ), snapshot, { tenantId: 't_0pt' }, ), ).rejects.toBeInstanceOf(StripeCreditVerificationError); }); it('refuses an amount that differs from the server price snapshot', async () => { await expect( verifyStripeCreditPurchase(stripeReturning(session({ amount_total: 100 })), snapshot, { tenantId: 't_0pt', }), ).rejects.toMatchObject({ reason: 'mismatch' }); }); it('refuses an unpaid session or a non-succeeded payment intent', async () => { await expect( verifyStripeCreditPurchase(stripeReturning(session({ payment_status: 'unpaid' })), snapshot, { tenantId: 't_0pt', }), ).rejects.toMatchObject({ reason: 'not_paid' }); await expect( verifyStripeCreditPurchase( stripeReturning( session({ payment_intent: { id: 'pi_123', status: 'processing', currency: 'sek', amount_received: 0 }, }), ), snapshot, { tenantId: 't_0pt' }, ), ).rejects.toMatchObject({ reason: 'not_paid' }); }); it('refuses a mismatched caller tenant before any Stripe call', async () => { const reader = { checkout: { sessions: { retrieve: async () => { throw new Error('should not be called'); }, }, }, } as unknown as StripeCheckoutReader; await expect(verifyStripeCreditPurchase(reader, snapshot, { tenantId: 't_b' })).rejects.toMatchObject({ reason: 'mismatch', }); }); });