|
| 1 | +/** @vitest-environment node */ |
| 2 | +import { stripe } from '@better-auth/stripe' |
| 3 | +import { createMockStripeEvent, dbChainMockFns, resetDbChainMock, schemaMock } from '@sim/testing' |
| 4 | +import { betterAuth } from 'better-auth' |
| 5 | +import { memoryAdapter } from 'better-auth/adapters/memory' |
| 6 | +import Stripe from 'stripe' |
| 7 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 8 | + |
| 9 | +const { mockSyncSubscriptionUsageLimits } = vi.hoisted(() => ({ |
| 10 | + mockSyncSubscriptionUsageLimits: vi.fn(), |
| 11 | +})) |
| 12 | + |
| 13 | +vi.mock('@/lib/billing/organization', () => ({ |
| 14 | + syncSubscriptionUsageLimits: mockSyncSubscriptionUsageLimits, |
| 15 | +})) |
| 16 | + |
| 17 | +import { handleSubscriptionUsageUpdate } from '@/lib/billing/webhooks/subscription-usage' |
| 18 | + |
| 19 | +const persistedSubscription = { |
| 20 | + id: 'subscription-1', |
| 21 | + referenceId: 'org-1', |
| 22 | + plan: 'team', |
| 23 | + status: 'active', |
| 24 | + seats: 2, |
| 25 | +} |
| 26 | + |
| 27 | +const updateEvent = () => |
| 28 | + createMockStripeEvent('customer.subscription.updated', { |
| 29 | + id: 'sub_stripe', |
| 30 | + object: 'subscription', |
| 31 | + customer: 'cus_1', |
| 32 | + status: 'active', |
| 33 | + cancel_at_period_end: false, |
| 34 | + metadata: {}, |
| 35 | + items: { |
| 36 | + data: [ |
| 37 | + { |
| 38 | + id: 'si_1', |
| 39 | + quantity: 2, |
| 40 | + current_period_start: 1788220800, |
| 41 | + current_period_end: 1790812800, |
| 42 | + price: { id: 'price_team', recurring: { interval: 'month' } }, |
| 43 | + }, |
| 44 | + ], |
| 45 | + }, |
| 46 | + }) |
| 47 | + |
| 48 | +describe('handleSubscriptionUsageUpdate', () => { |
| 49 | + beforeEach(() => { |
| 50 | + resetDbChainMock() |
| 51 | + mockSyncSubscriptionUsageLimits.mockReset().mockResolvedValue(undefined) |
| 52 | + dbChainMockFns.limit.mockResolvedValue([persistedSubscription]) |
| 53 | + }) |
| 54 | + |
| 55 | + afterEach(resetDbChainMock) |
| 56 | + |
| 57 | + it('uses the persisted payer reference after subscription callbacks have rehomed it', async () => { |
| 58 | + await handleSubscriptionUsageUpdate(updateEvent()) |
| 59 | + |
| 60 | + expect(dbChainMockFns.where).toHaveBeenCalledWith({ |
| 61 | + type: 'eq', |
| 62 | + left: schemaMock.subscription.stripeSubscriptionId, |
| 63 | + right: 'sub_stripe', |
| 64 | + }) |
| 65 | + expect(mockSyncSubscriptionUsageLimits).toHaveBeenCalledExactlyOnceWith(persistedSubscription) |
| 66 | + }) |
| 67 | + |
| 68 | + it('ignores other event types', async () => { |
| 69 | + await handleSubscriptionUsageUpdate(createMockStripeEvent('customer.subscription.created', {})) |
| 70 | + |
| 71 | + expect(dbChainMockFns.select).not.toHaveBeenCalled() |
| 72 | + expect(mockSyncSubscriptionUsageLimits).not.toHaveBeenCalled() |
| 73 | + }) |
| 74 | + |
| 75 | + it('ignores subscriptions that are not tracked locally', async () => { |
| 76 | + dbChainMockFns.limit.mockResolvedValueOnce([]) |
| 77 | + |
| 78 | + await handleSubscriptionUsageUpdate(updateEvent()) |
| 79 | + |
| 80 | + expect(mockSyncSubscriptionUsageLimits).not.toHaveBeenCalled() |
| 81 | + }) |
| 82 | + |
| 83 | + it.each(['lookup', 'reconciliation'])( |
| 84 | + 'returns a failed webhook response on %s failure and reconciles on redelivery', |
| 85 | + async (failure) => { |
| 86 | + const onSubscriptionUpdate = vi.fn() |
| 87 | + const stripeClient = new Stripe('sk_test_placeholder') |
| 88 | + const webhookSecret = 'whsec_subscription_usage_test' |
| 89 | + const provider = betterAuth({ |
| 90 | + baseURL: 'https://sim.test', |
| 91 | + secret: 'isolated-stripe-webhook-test-secret-123456789', |
| 92 | + database: memoryAdapter({ |
| 93 | + user: [], |
| 94 | + session: [], |
| 95 | + account: [], |
| 96 | + verification: [], |
| 97 | + subscription: [ |
| 98 | + { |
| 99 | + ...persistedSubscription, |
| 100 | + stripeCustomerId: 'cus_1', |
| 101 | + stripeSubscriptionId: 'sub_stripe', |
| 102 | + }, |
| 103 | + ], |
| 104 | + }), |
| 105 | + logger: { disabled: true }, |
| 106 | + plugins: [ |
| 107 | + stripe({ |
| 108 | + stripeClient, |
| 109 | + stripeWebhookSecret: webhookSecret, |
| 110 | + subscription: { |
| 111 | + enabled: true, |
| 112 | + plans: [{ name: 'team', priceId: 'price_team' }], |
| 113 | + onSubscriptionUpdate, |
| 114 | + }, |
| 115 | + onEvent: handleSubscriptionUsageUpdate, |
| 116 | + }), |
| 117 | + ], |
| 118 | + }) |
| 119 | + const payload = JSON.stringify(updateEvent()) |
| 120 | + const signature = stripeClient.webhooks.generateTestHeaderString({ |
| 121 | + payload, |
| 122 | + secret: webhookSecret, |
| 123 | + }) |
| 124 | + const deliver = () => |
| 125 | + provider.handler( |
| 126 | + new Request('https://sim.test/api/auth/stripe/webhook', { |
| 127 | + method: 'POST', |
| 128 | + headers: { 'Content-Type': 'application/json', 'stripe-signature': signature }, |
| 129 | + body: payload, |
| 130 | + }) |
| 131 | + ) |
| 132 | + |
| 133 | + if (failure === 'lookup') { |
| 134 | + dbChainMockFns.limit.mockRejectedValueOnce(new Error('database unavailable')) |
| 135 | + } else { |
| 136 | + mockSyncSubscriptionUsageLimits.mockRejectedValueOnce(new Error('database unavailable')) |
| 137 | + } |
| 138 | + |
| 139 | + const failed = await deliver() |
| 140 | + expect(failed.ok).toBe(false) |
| 141 | + expect(await failed.json()).toMatchObject({ code: 'STRIPE_WEBHOOK_ERROR' }) |
| 142 | + expect(onSubscriptionUpdate).toHaveBeenCalledOnce() |
| 143 | + |
| 144 | + const retried = await deliver() |
| 145 | + expect(retried.status).toBe(200) |
| 146 | + expect(await retried.json()).toEqual({ success: true }) |
| 147 | + expect(onSubscriptionUpdate).toHaveBeenCalledTimes(2) |
| 148 | + expect(mockSyncSubscriptionUsageLimits).toHaveBeenLastCalledWith(persistedSubscription) |
| 149 | + } |
| 150 | + ) |
| 151 | +}) |
0 commit comments