diff --git a/eslint-suppressions.json b/eslint-suppressions.json index b7f8cb1870c..852197abe8a 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -209,11 +209,6 @@ "count": 1 } }, - "src/platform/cloud/subscription/composables/useSubscription.ts": { - "comfy/no-new-error-throw": { - "count": 1 - } - }, "src/platform/cloud/subscription/launchCancellationFlow.ts": { "comfy/no-new-error-throw": { "count": 1 diff --git a/src/components/dialog/content/TopUpCreditsDialogContentLegacy.test.ts b/src/components/dialog/content/TopUpCreditsDialogContentLegacy.test.ts index 1cad8119d11..f837aacb9d4 100644 --- a/src/components/dialog/content/TopUpCreditsDialogContentLegacy.test.ts +++ b/src/components/dialog/content/TopUpCreditsDialogContentLegacy.test.ts @@ -4,21 +4,23 @@ import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import { createI18n } from 'vue-i18n' -import { useAuthActions } from '@/composables/auth/useAuthActions' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingRouting } from '@/composables/billing/useBillingRouting' import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { useTelemetry } from '@/platform/telemetry' -import { AuthStoreError } from '@/stores/authStore' +import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { useDialogStore } from '@/stores/dialogStore' import TopUpCreditsDialogContentLegacy from './TopUpCreditsDialogContentLegacy.vue' +const PENDING_TOPUP_KEY = 'pending_topup_timestamp' + const mockToastAdd = vi.fn() const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: false })) -vi.mock(import('@/composables/auth/useAuthActions')) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/composables/billing/useBillingRouting')) @@ -28,11 +30,6 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog')) vi.mock(import('@/platform/telemetry')) -const mockClearPendingTopup = vi.hoisted(() => vi.fn()) -vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ - usePendingTopup: () => ({ clearPendingTopup: mockClearPendingTopup }) -})) - vi.mock( import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports @@ -98,41 +95,47 @@ async function clickBuyCredits() { describe('TopUpCreditsDialogContentLegacy', () => { beforeEach(() => { + localStorage.clear() useBillingRouting().shouldUseWorkspaceBilling = computed( () => mockShouldUseWorkspaceBilling.value ) vi.mocked(useSubscription().isSubscriptionEnabled).mockReturnValue(true) mockShouldUseWorkspaceBilling.value = false + const billingContext = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billingContext) + billingContext.canAccessSubscriptionFeatures = computed(() => true) + vi.mocked(useAuthStore().initiateCreditPurchase).mockResolvedValue({ + checkout_url: 'https://checkout.stripe.test' + }) + vi.spyOn(window, 'open').mockImplementation(() => window) }) it('shows Plan & Credits after a successful Cloud purchase', async () => { - vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue( - undefined - ) - renderDialog() await clickBuyCredits() - expect(useAuthActions().purchaseCreditsDirect).toHaveBeenCalledWith(50) + expect(useAuthStore().initiateCreditPurchase).toHaveBeenCalledWith({ + amount_micros: 50_000_000, + currency: 'usd' + }) expect(useDialogStore().closeDialog).toHaveBeenCalled() expect(useSettingsDialog().show).toHaveBeenCalledWith('workspace') - expect(mockClearPendingTopup).not.toHaveBeenCalled() + expect(localStorage.getItem(PENDING_TOPUP_KEY)).not.toBeNull() }) it('clears the pending top-up marker when the user closes the dialog', async () => { + localStorage.setItem(PENDING_TOPUP_KEY, Date.now().toString()) + renderDialog() const user = userEvent.setup() await user.click(screen.getByRole('button', { name: 'Close' })) - expect(mockClearPendingTopup).toHaveBeenCalled() + expect(localStorage.getItem(PENDING_TOPUP_KEY)).toBeNull() expect(useDialogStore().closeDialog).toHaveBeenCalled() }) it('shows Plan & Credits when no billing rail is active', async () => { vi.mocked(useSubscription().isSubscriptionEnabled).mockReturnValue(false) - vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue( - undefined - ) renderDialog() await clickBuyCredits() @@ -142,9 +145,6 @@ describe('TopUpCreditsDialogContentLegacy', () => { it('shows the workspace settings panel when workspace billing is active', async () => { mockShouldUseWorkspaceBilling.value = true - vi.mocked(useAuthActions().purchaseCreditsDirect).mockResolvedValue( - undefined - ) renderDialog() await clickBuyCredits() @@ -153,7 +153,7 @@ describe('TopUpCreditsDialogContentLegacy', () => { }) it('tracks the failure and surfaces a toast when the purchase rejects', async () => { - vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue( + vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue( new Error('declined for person@example.com') ) @@ -176,12 +176,8 @@ describe('TopUpCreditsDialogContentLegacy', () => { }) it('categorizes an auth-store rejection with an HTTP status via the shared classifier', async () => { - const authStoreError = new AuthStoreError( - 'backend rejected the purchase', - 400 - ) - vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue( - authStoreError + vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue( + new AuthStoreError('backend rejected the purchase', 400) ) renderDialog() @@ -196,9 +192,8 @@ describe('TopUpCreditsDialogContentLegacy', () => { }) it('categorizes an auth-store rejection with no HTTP status as a network failure', async () => { - const authStoreError = new AuthStoreError('offline') - vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue( - authStoreError + vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue( + new AuthStoreError('offline') ) renderDialog() @@ -215,14 +210,19 @@ describe('TopUpCreditsDialogContentLegacy', () => { it.for([ { name: 'a checkout that opens stays pending', - purchase: () => Promise.resolve(), + purchase: () => + Promise.resolve({ checkout_url: 'https://checkout.stripe.test' }), + openedWindow: window, expectedEvents: [ [{ operation: 'topup', stage: 'started', outcome: 'pending' }] - ] + ], + markerKept: true, + settingsCalls: [['workspace']] }, { name: 'a rejected purchase closes as failed', purchase: () => Promise.reject(new Error('declined')), + openedWindow: window, expectedEvents: [ [{ operation: 'topup', stage: 'started', outcome: 'pending' }], [ @@ -233,14 +233,43 @@ describe('TopUpCreditsDialogContentLegacy', () => { failure_category: 'unknown' } ] - ] + ], + markerKept: false, + settingsCalls: [] + }, + { + name: 'a checkout tab the browser blocks closes as a popup-blocked failure', + purchase: () => + Promise.resolve({ checkout_url: 'https://checkout.stripe.test' }), + openedWindow: null, + expectedEvents: [ + [{ operation: 'topup', stage: 'started', outcome: 'pending' }], + [ + { + operation: 'topup', + stage: 'failed', + outcome: 'failure', + failure_category: 'redirect', + error_code: 'payment_popup_blocked' + } + ] + ], + markerKept: false, + settingsCalls: [] } ])( 'opens every purchase attempt with one started event: $name', - async ({ purchase, expectedEvents }) => { - vi.mocked(useAuthActions().purchaseCreditsDirect).mockImplementation( + async ({ + purchase, + openedWindow, + expectedEvents, + markerKept, + settingsCalls + }) => { + vi.mocked(useAuthStore().initiateCreditPurchase).mockImplementation( purchase ) + vi.spyOn(window, 'open').mockImplementation(() => openedWindow) renderDialog() await clickBuyCredits() @@ -250,11 +279,29 @@ describe('TopUpCreditsDialogContentLegacy', () => { expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual( expectedEvents ) + expect(localStorage.getItem(PENDING_TOPUP_KEY) !== null).toBe(markerKept) + expect(vi.mocked(useSettingsDialog().show).mock.calls).toEqual( + settingsCalls + ) } ) + it('sends no started event when the customer cannot buy credits', async () => { + useBillingContext().canAccessSubscriptionFeatures = computed(() => false) + + renderDialog() + await clickBuyCredits() + + const telemetry = useTelemetry() + assert.exists(telemetry) + expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([]) + expect(useAuthStore().initiateCreditPurchase).not.toHaveBeenCalled() + expect(localStorage.getItem(PENDING_TOPUP_KEY)).toBeNull() + expect(useSettingsDialog().show).toHaveBeenCalledWith('workspace') + }) + it('uses the same bounded category when the rejection is not an Error', async () => { - vi.mocked(useAuthActions().purchaseCreditsDirect).mockRejectedValue('boom') + vi.mocked(useAuthStore().initiateCreditPurchase).mockRejectedValue('boom') renderDialog() await clickBuyCredits() @@ -267,3 +314,4 @@ describe('TopUpCreditsDialogContentLegacy', () => { }) }) }) +vi.mock(import('firebase/auth')) diff --git a/src/components/dialog/content/TopUpCreditsDialogContentLegacy.vue b/src/components/dialog/content/TopUpCreditsDialogContentLegacy.vue index 967339921d2..094ee7690aa 100644 --- a/src/components/dialog/content/TopUpCreditsDialogContentLegacy.vue +++ b/src/components/dialog/content/TopUpCreditsDialogContentLegacy.vue @@ -161,7 +161,7 @@ import { useAuthActions } from '@/composables/auth/useAuthActions' import { useExternalLink } from '@/composables/useExternalLink' import { useTelemetry } from '@/platform/telemetry' import { usePendingTopup } from '@/composables/billing/usePendingTopup' -import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' +import { describeBillingFailure } from '@/platform/telemetry/utils/billingFailureCategory' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { useDialogStore } from '@/stores/dialogStore' import { cn } from '@comfyorg/tailwind-utils' @@ -252,11 +252,13 @@ async function handleBuy() { loading.value = true try { telemetry?.trackApiCreditTopupButtonPurchaseClicked(payAmount.value) - telemetry?.trackBillingEvent({ - operation: 'topup', - stage: 'started', - outcome: 'pending' - }) + if (authActions.canPurchaseCredits()) { + telemetry?.trackBillingEvent({ + operation: 'topup', + stage: 'started', + outcome: 'pending' + }) + } await authActions.purchaseCreditsDirect(payAmount.value) // Close top-up dialog (keep tracking) and open Plan & Credits to show the @@ -276,7 +278,7 @@ async function handleBuy() { operation: 'topup', stage: 'failed', outcome: 'failure', - failure_category: categorizeBillingApiError(error) + ...describeBillingFailure(error) }) toast.add({ severity: 'error', diff --git a/src/components/dialog/content/setting/UsageLogsTable.test.ts b/src/components/dialog/content/setting/UsageLogsTable.test.ts index a0bbf4cb43e..c0702b03927 100644 --- a/src/components/dialog/content/setting/UsageLogsTable.test.ts +++ b/src/components/dialog/content/setting/UsageLogsTable.test.ts @@ -25,8 +25,10 @@ vi.mock(import('@/services/customerEventsService')) vi.mock(import('@/platform/telemetry')) +const CONFIRMED_AT_MS = Date.parse('2024-06-15T12:30:00Z') + const mockPendingTopup = vi.hoisted(() => ({ - isPendingTopupCompleted: vi.fn().mockReturnValue(true) + consumeCompletedTopup: vi.fn().mockReturnValue({ startedAtMs: Date.now() }) })) vi.mock(import('@/composables/billing/usePendingTopup'), () => ({ usePendingTopup: () => mockPendingTopup @@ -392,7 +394,9 @@ describe('UsageLogsTable', () => { useBillingRouting().shouldUseWorkspaceBilling = computed( () => workspaceBilling.value ) - mockPendingTopup.isPendingTopupCompleted.mockReturnValue(true) + mockPendingTopup.consumeCompletedTopup.mockReturnValue({ + startedAtMs: Date.now() + }) let resolveLegacy!: (value: ReturnType) => void vi.mocked(useCustomerEventsService().getMyEvents).mockReturnValue( new Promise((resolve) => { @@ -428,7 +432,7 @@ describe('UsageLogsTable', () => { resolveLegacy(legacyResponse) await waitFor(() => { - expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith( + expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith( legacyResponse.events ) expect(useTelemetry()?.trackApiCreditTopupSucceeded).toHaveBeenCalled() @@ -437,21 +441,29 @@ describe('UsageLogsTable', () => { it.for([ { - name: 'a completed legacy top-up closes as succeeded', - completed: true, + name: 'a completed legacy top-up closes as succeeded, measured from its start', + completedTopup: { startedAtMs: CONFIRMED_AT_MS - 90_000 }, expectedEvents: [ - [{ operation: 'topup', stage: 'succeeded', outcome: 'success' }] + [ + { + operation: 'topup', + stage: 'succeeded', + outcome: 'success', + duration_ms: 90_000 + } + ] ] }, { name: 'no completed top-up reports nothing', - completed: false, + completedTopup: null, expectedEvents: [] } ])( 'reports top-up completion to the billing funnel: $name', - async ({ completed, expectedEvents }) => { - mockPendingTopup.isPendingTopupCompleted.mockReturnValue(completed) + async ({ completedTopup, expectedEvents }) => { + vi.spyOn(Date, 'now').mockReturnValue(CONFIRMED_AT_MS) + mockPendingTopup.consumeCompletedTopup.mockReturnValue(completedTopup) await renderLoaded() @@ -464,11 +476,11 @@ describe('UsageLogsTable', () => { ) it('skips top-up telemetry when no completion is pending', async () => { - mockPendingTopup.isPendingTopupCompleted.mockReturnValue(false) + mockPendingTopup.consumeCompletedTopup.mockReturnValue(null) await renderLoaded() - expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith( + expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith( mockEventsResponse.events ) expect( @@ -628,11 +640,13 @@ describe('UsageLogsTable', () => { it('runs top-up completion telemetry off the reader page', async () => { onTheRail() - mockPendingTopup.isPendingTopupCompleted.mockReturnValue(true) + mockPendingTopup.consumeCompletedTopup.mockReturnValue({ + startedAtMs: Date.now() + }) await renderLoaded() - expect(mockPendingTopup.isPendingTopupCompleted).toHaveBeenCalledWith( + expect(mockPendingTopup.consumeCompletedTopup).toHaveBeenCalledWith( railResponse.events ) expect(useTelemetry()?.trackApiCreditTopupSucceeded).toHaveBeenCalled() diff --git a/src/components/dialog/content/setting/UsageLogsTable.vue b/src/components/dialog/content/setting/UsageLogsTable.vue index aae2b9a04c0..9dc7b4800ae 100644 --- a/src/components/dialog/content/setting/UsageLogsTable.vue +++ b/src/components/dialog/content/setting/UsageLogsTable.vue @@ -174,13 +174,17 @@ const loadEvents = async () => { // Completion telemetry must run even when a mid-checkout route flip // supersedes this load, since legacy and workspace backends emit different // top-up events and the winning fetch may not carry the completion yet. - if (usePendingTopup().isPendingTopupCompleted(response?.events)) { + const completedTopup = usePendingTopup().consumeCompletedTopup( + response?.events + ) + if (completedTopup) { const telemetry = useTelemetry() telemetry?.trackApiCreditTopupSucceeded() telemetry?.trackBillingEvent({ operation: 'topup', stage: 'succeeded', - outcome: 'success' + outcome: 'success', + duration_ms: Date.now() - completedTopup.startedAtMs }) } diff --git a/src/composables/auth/__mocks__/useAuthActions.ts b/src/composables/auth/__mocks__/useAuthActions.ts index f8adcd834c8..0156af4eb1b 100644 --- a/src/composables/auth/__mocks__/useAuthActions.ts +++ b/src/composables/auth/__mocks__/useAuthActions.ts @@ -8,7 +8,9 @@ const actions: ReturnType = { sendPasswordReset: vi.fn(async () => true), purchaseCredits: vi.fn(async () => undefined), purchaseCreditsDirect: vi.fn(async () => undefined), + canPurchaseCredits: vi.fn(() => true), accessBillingPortal: vi.fn(async () => true), + accessBillingPortalDirect: vi.fn(async () => true), fetchBalance: vi.fn(async () => null), signInWithGoogle: vi.fn(async () => undefined), signInWithGithub: vi.fn(async () => undefined), diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index 4eee9ecb488..5c54cac4a8a 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -137,7 +137,7 @@ describe('useAuthActions.purchaseCreditsDirect', () => { }) it('starts top-up tracking before opening Stripe checkout', async () => { - const open = vi.spyOn(window, 'open').mockImplementation(() => null) + const open = vi.spyOn(window, 'open').mockImplementation(() => window) const { purchaseCreditsDirect } = useAuthActions() await purchaseCreditsDirect(25) diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index b9e7fc1eeb4..2b452924fab 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -18,6 +18,7 @@ import enMessages from '@/locales/en/main.json' with { type: 'json' } import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { AuthFlowAction } from '@/platform/telemetry/types' +import { PaymentPopupBlockedError } from '@/platform/telemetry/utils/billingFailureCategory' import { useToastStore } from '@/platform/updates/common/toastStore' import { clearAllWorkspaceStorage, @@ -172,6 +173,10 @@ export const useAuthActions = () => { reportAuthFlowError('password_reset') ) + /** Whether `purchaseCreditsDirect` goes on to open a checkout. */ + const canPurchaseCredits = (): boolean => + useBillingContext().canAccessSubscriptionFeatures.value + /** * Raw (unwrapped) credit purchase. Exposed separately from `purchaseCredits` * so callers that need to observe a rejection directly (e.g. to fire failure @@ -179,8 +184,7 @@ export const useAuthActions = () => { * resolves instead of re-throwing on failure. */ const purchaseCreditsDirect = async (amount: number): Promise => { - const { canAccessSubscriptionFeatures } = useBillingContext() - if (!canAccessSubscriptionFeatures.value) return + if (!canPurchaseCredits()) return const response = await authStore.initiateCreditPurchase({ amount_micros: usdToMicros(amount), @@ -197,8 +201,14 @@ export const useAuthActions = () => { // Mark the pending top-up directly, not via telemetry, so the balance // refresh on return still fires when telemetry consent is off. - usePendingTopup().startPendingTopup() - window.open(response.checkout_url, '_blank') + const pendingTopup = usePendingTopup() + pendingTopup.startPendingTopup() + if (!window.open(response.checkout_url, '_blank')) { + pendingTopup.clearPendingTopup() + throw new PaymentPopupBlockedError( + t('subscription.preview.paymentPopupBlocked') + ) + } watchForTopupBalanceUpdate() } @@ -207,10 +217,10 @@ export const useAuthActions = () => { reportError ) - const accessBillingPortal = wrapWithErrorHandlingAsync< - [targetTier?: BillingPortalTargetTier, openInNewTab?: boolean], - boolean - >(async (targetTier, openInNewTab = true) => { + /** Unwrapped `accessBillingPortal`: rejects on failure, false when the tab is blocked. */ + const accessBillingPortalDirect = async ( + targetTier?: BillingPortalTargetTier + ): Promise => { const response = await authStore.accessBillingPortal(targetTier) if (!response.billing_portal_url) { throw new Error( @@ -219,13 +229,13 @@ export const useAuthActions = () => { }) ) } - if (openInNewTab) { - return window.open(response.billing_portal_url, '_blank') !== null - } + return window.open(response.billing_portal_url, '_blank') !== null + } - globalThis.location.href = response.billing_portal_url - return true - }, reportError) + const accessBillingPortal = wrapWithErrorHandlingAsync( + accessBillingPortalDirect, + reportError + ) const fetchBalance = wrapWithErrorHandlingAsync(async () => { const result = await authStore.fetchBalance() @@ -324,7 +334,9 @@ export const useAuthActions = () => { sendPasswordReset, purchaseCredits, purchaseCreditsDirect, + canPurchaseCredits, accessBillingPortal, + accessBillingPortalDirect, fetchBalance, signInWithGoogle, signInWithGithub, diff --git a/src/composables/billing/usePendingTopup.test.ts b/src/composables/billing/usePendingTopup.test.ts index 3e698a23195..15fd718b6da 100644 --- a/src/composables/billing/usePendingTopup.test.ts +++ b/src/composables/billing/usePendingTopup.test.ts @@ -53,36 +53,35 @@ describe('usePendingTopup', () => { expect(localStorage.getItem(STORAGE_KEY)).toBeNull() }) - describe('isPendingTopupCompleted', () => { - it('is false when no marker is set', () => { - const { isPendingTopupCompleted } = usePendingTopup() - expect(isPendingTopupCompleted([creditAddedEvent(Date.now())])).toBe( - false - ) + describe('consumeCompletedTopup', () => { + it('finds nothing when no marker is set', () => { + const { consumeCompletedTopup } = usePendingTopup() + expect(consumeCompletedTopup([creditAddedEvent(Date.now())])).toBeNull() }) - it('is false when there are no events', () => { - const { startPendingTopup, isPendingTopupCompleted } = usePendingTopup() + it('finds nothing when there are no events', () => { + const { startPendingTopup, consumeCompletedTopup } = usePendingTopup() startPendingTopup() - expect(isPendingTopupCompleted([])).toBe(false) - expect(isPendingTopupCompleted(null)).toBe(false) + expect(consumeCompletedTopup([])).toBeNull() + expect(consumeCompletedTopup(null)).toBeNull() }) - it('is true and clears the marker when a credit_added event lands after tracking', () => { - const { startPendingTopup, isPendingTopupCompleted } = usePendingTopup() - startPendingTopup() + it('returns the tracked start and clears the marker when a credit_added event lands after tracking', () => { + const startedAtMs = Date.now() - 30_000 + localStorage.setItem(STORAGE_KEY, String(startedAtMs)) + const { consumeCompletedTopup } = usePendingTopup() expect( - isPendingTopupCompleted([creditAddedEvent(Date.now() + 1000)]) - ).toBe(true) + consumeCompletedTopup([creditAddedEvent(Date.now() + 1000)]) + ).toEqual({ startedAtMs }) expect(localStorage.getItem(STORAGE_KEY)).toBeNull() }) it('ignores credit events that predate tracking', () => { - const { startPendingTopup, isPendingTopupCompleted } = usePendingTopup() + const { startPendingTopup, consumeCompletedTopup } = usePendingTopup() startPendingTopup() expect( - isPendingTopupCompleted([creditAddedEvent(Date.now() - 60_000)]) - ).toBe(false) + consumeCompletedTopup([creditAddedEvent(Date.now() - 60_000)]) + ).toBeNull() expect(localStorage.getItem(STORAGE_KEY)).not.toBeNull() }) }) diff --git a/src/composables/billing/usePendingTopup.ts b/src/composables/billing/usePendingTopup.ts index f4875ca5cf4..9444feef3ba 100644 --- a/src/composables/billing/usePendingTopup.ts +++ b/src/composables/billing/usePendingTopup.ts @@ -3,6 +3,11 @@ import type { AuditLog } from '@/services/customerEventsService' const STORAGE_KEY = 'pending_topup_timestamp' const MAX_AGE_MS = 24 * 60 * 60 * 1000 // 24 hours +interface CompletedTopup { + /** Set when the checkout tab opened, one purchase request after `started`. */ + startedAtMs: number +} + function getPendingTopupTimestamp(): number | null { const timestampStr = localStorage.getItem(STORAGE_KEY) if (timestampStr === null) return null @@ -28,13 +33,13 @@ export function usePendingTopup() { localStorage.setItem(STORAGE_KEY, Date.now().toString()) } - // True if a credit top-up completed after tracking started; clears on hit. - function isPendingTopupCompleted( + // The top-up a later credit_added completed, if any; clears the marker on hit. + function consumeCompletedTopup( events: AuditLog[] | undefined | null - ): boolean { + ): CompletedTopup | null { const timestamp = getPendingTopupTimestamp() - if (timestamp === null) return false - if (!events || events.length === 0) return false + if (timestamp === null) return null + if (!events || events.length === 0) return null const completedTopup = events.find( (e) => @@ -43,11 +48,9 @@ export function usePendingTopup() { new Date(e.createdAt).getTime() > timestamp ) - if (completedTopup) { - localStorage.removeItem(STORAGE_KEY) - return true - } - return false + if (!completedTopup) return null + localStorage.removeItem(STORAGE_KEY) + return { startedAtMs: timestamp } } // Non-consuming: true if a pending top-up is awaiting a balance refresh. @@ -62,7 +65,7 @@ export function usePendingTopup() { return { startPendingTopup, - isPendingTopupCompleted, + consumeCompletedTopup, pendingTopupNeedsRefresh, clearPendingTopup } diff --git a/src/platform/cloud/subscription/components/CreditsTile.test.ts b/src/platform/cloud/subscription/components/CreditsTile.test.ts index 80bd0901867..ce76081441c 100644 --- a/src/platform/cloud/subscription/components/CreditsTile.test.ts +++ b/src/platform/cloud/subscription/components/CreditsTile.test.ts @@ -792,15 +792,20 @@ describe('CreditsTile', () => { expect(useCustomerEventsService().getMyEvents).not.toHaveBeenCalled() }) - it('closes a confirmed legacy top-up with one succeeded event', async () => { + it('closes a confirmed legacy top-up with one succeeded event measured from its start', async () => { + const confirmedAtMs = Date.parse('2024-06-15T12:30:00Z') + vi.spyOn(Date, 'now').mockReturnValue(confirmedAtMs) activeProSubscription() state.type = 'legacy' - localStorage.setItem('pending_topup_timestamp', Date.now().toString()) + localStorage.setItem( + 'pending_topup_timestamp', + String(confirmedAtMs - 90_000) + ) vi.mocked(useCustomerEventsService().getMyEvents).mockResolvedValueOnce({ events: [ { event_type: 'credit_added', - createdAt: new Date(Date.now() + 1000).toISOString() + createdAt: new Date(confirmedAtMs - 1000).toISOString() } ] }) @@ -813,7 +818,14 @@ describe('CreditsTile', () => { const telemetry = useTelemetry() assert.exists(telemetry) expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ - [{ operation: 'topup', stage: 'succeeded', outcome: 'success' }] + [ + { + operation: 'topup', + stage: 'succeeded', + outcome: 'success', + duration_ms: 90_000 + } + ] ]) }) diff --git a/src/platform/cloud/subscription/components/CreditsTile.vue b/src/platform/cloud/subscription/components/CreditsTile.vue index 1b08818edd9..a921d65633d 100644 --- a/src/platform/cloud/subscription/components/CreditsTile.vue +++ b/src/platform/cloud/subscription/components/CreditsTile.vue @@ -269,7 +269,7 @@ const { showPricingTable } = useSubscriptionDialog() const customerEventsService = useCustomerEventsService() const dialogService = useDialogService() const telemetry = useTelemetry() -const { pendingTopupNeedsRefresh, isPendingTopupCompleted } = usePendingTopup() +const { pendingTopupNeedsRefresh, consumeCompletedTopup } = usePendingTopup() const tierKey = computed(() => { const tier = subscription.value?.tier @@ -488,12 +488,14 @@ async function refreshCredits() { customerEventsService.error.value ?? 'Fetching customer events failed' ) } - if (isPendingTopupCompleted(response.events)) { + const completedTopup = consumeCompletedTopup(response.events) + if (completedTopup) { telemetry?.trackApiCreditTopupSucceeded() telemetry?.trackBillingEvent({ operation: 'topup', stage: 'succeeded', - outcome: 'success' + outcome: 'success', + duration_ms: Date.now() - completedTopup.startedAtMs }) } } diff --git a/src/platform/cloud/subscription/components/PricingTable.test.ts b/src/platform/cloud/subscription/components/PricingTable.test.ts index 78170a5a004..d046d88ef44 100644 --- a/src/platform/cloud/subscription/components/PricingTable.test.ts +++ b/src/platform/cloud/subscription/components/PricingTable.test.ts @@ -1,11 +1,10 @@ -import { useAuthStore } from '@/stores/authStore' +import { AuthStoreError, useAuthStore } from '@/stores/authStore' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { computed, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' -import { useAuthActions } from '@/composables/auth/useAuthActions' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useErrorHandling } from '@/composables/useErrorHandling' import { useTelemetry } from '@/platform/telemetry' @@ -28,6 +27,14 @@ function createDeferredPromise() { return { promise, resolve } } +type BillingPortalResponse = Awaited< + ReturnType['accessBillingPortal']> +> + +const billingPortal: BillingPortalResponse = { + billing_portal_url: 'https://billing.stripe.com/p/session' +} + const mockCanAccessSubscriptionFeatures = ref(false) const mockSubscriptionTier = ref(null) const mockSubscriptionDuration = ref<'MONTHLY' | 'ANNUAL'>('MONTHLY') @@ -65,8 +72,6 @@ Object.defineProperty(globalThis, 'localStorage', { vi.mock(import('@/composables/billing/useBillingContext')) -vi.mock(import('@/composables/auth/useAuthActions')) - vi.mock(import('@/composables/useErrorHandling')) vi.mock(import('@/platform/telemetry')) @@ -210,6 +215,8 @@ beforeEach(() => { vi.mocked(useAuthStore().fetchWithCustomerRecovery).mockImplementation( (input, init) => fetch(input, init) ) + vi.mocked(useAuthStore().accessBillingPortal).mockResolvedValue(billingPortal) + vi.spyOn(window, 'open').mockImplementation(() => window) }) describe('PricingTable', () => { @@ -252,7 +259,7 @@ describe('PricingTable', () => { checkout_attempt_id: expect.any(String), previous_tier: 'standard' }) - expect(useAuthActions().accessBillingPortal).toHaveBeenCalledWith( + expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( 'creator-yearly' ) }) @@ -271,7 +278,7 @@ describe('PricingTable', () => { await userEvent.click(proButton!) await flushPromises() - expect(useAuthActions().accessBillingPortal).toHaveBeenCalledWith( + expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( 'pro-yearly' ) }) @@ -280,8 +287,8 @@ describe('PricingTable', () => { mockCanAccessSubscriptionFeatures.value = true mockSubscriptionTier.value = 'STANDARD' - const portalOpen = createDeferredPromise() - vi.mocked(useAuthActions().accessBillingPortal).mockReturnValueOnce( + const portalOpen = createDeferredPromise() + vi.mocked(useAuthStore().accessBillingPortal).mockReturnValueOnce( portalOpen.promise ) @@ -299,10 +306,10 @@ describe('PricingTable', () => { await userEvent.click(monthlyToggle) await flushPromises() - portalOpen.resolve(true) + portalOpen.resolve(billingPortal) await flushPromises() - expect(useAuthActions().accessBillingPortal).toHaveBeenCalledWith( + expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( 'creator-yearly' ) expect( @@ -327,8 +334,8 @@ describe('PricingTable', () => { Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-early' }) - const portalOpen = createDeferredPromise() - vi.mocked(useAuthActions().accessBillingPortal).mockReturnValueOnce( + const portalOpen = createDeferredPromise() + vi.mocked(useAuthStore().accessBillingPortal).mockReturnValueOnce( portalOpen.promise ) @@ -345,7 +352,7 @@ describe('PricingTable', () => { Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-late' }) - portalOpen.resolve(true) + portalOpen.resolve(billingPortal) await flushPromises() expect( @@ -363,9 +370,7 @@ describe('PricingTable', () => { it('does not record a pending upgrade when the billing portal does not open', async () => { mockCanAccessSubscriptionFeatures.value = true mockSubscriptionTier.value = 'STANDARD' - vi.mocked(useAuthActions().accessBillingPortal).mockResolvedValueOnce( - false - ) + vi.spyOn(window, 'open').mockImplementation(() => null) renderComponent() await flushPromises() @@ -428,7 +433,7 @@ describe('PricingTable', () => { await userEvent.click(currentPlanButton!) await flushPromises() - expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() + expect(useAuthStore().accessBillingPortal).not.toHaveBeenCalled() }) it('does not highlight a current plan when the facade duration differs from the selected cycle', async () => { @@ -463,7 +468,7 @@ describe('PricingTable', () => { await userEvent.click(subscribeButton!) await flushPromises() - expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() + expect(useAuthStore().accessBillingPortal).not.toHaveBeenCalled() expect(global.fetch).toHaveBeenCalledWith( expect.stringContaining('/customers/cloud-subscription-checkout/'), expect.any(Object) @@ -508,7 +513,7 @@ describe('PricingTable', () => { failure_category: 'api_rejected', duration_ms: expect.any(Number) }) - expect(useAuthActions().reportError).toHaveBeenCalled() + expect(useErrorHandling().toastErrorHandler).toHaveBeenCalled() }) it('categorizes a connectivity failure as network, not api_rejected', async () => { @@ -546,10 +551,161 @@ describe('PricingTable', () => { await userEvent.click(standardButton!) await flushPromises() - expect(useAuthActions().accessBillingPortal).toHaveBeenCalledWith( + expect(useAuthStore().accessBillingPortal).toHaveBeenCalledWith( 'standard-yearly' ) }) + + it.for([ + { + name: 'the portal opens and the attempt waits for its success', + currentTier: 'STANDARD', + currentDuration: 'MONTHLY', + target: 'Creator', + portal: () => Promise.resolve(billingPortal), + openedWindow: window, + expectedEvents: [ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000006', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'change' + } + ] + ], + storedAttempt: expect.objectContaining({ + attempt_id: '00000000-0000-4000-8000-000000000006', + start_reported: true + }) + }, + { + name: 'the browser blocks the portal tab', + currentTier: 'STANDARD', + currentDuration: 'MONTHLY', + target: 'Creator', + portal: () => Promise.resolve(billingPortal), + openedWindow: null, + expectedEvents: [ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000006', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'change' + } + ], + [ + { + operation: 'subscription_checkout', + stage: 'failed', + outcome: 'failure', + checkout_attempt_id: '00000000-0000-4000-8000-000000000006', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'change', + failure_category: 'redirect', + error_code: 'payment_popup_blocked', + duration_ms: expect.any(Number) + } + ] + ], + storedAttempt: null + }, + { + name: 'the portal request is rejected', + currentTier: 'STANDARD', + currentDuration: 'MONTHLY', + target: 'Creator', + portal: () => + Promise.reject(new AuthStoreError('portal unavailable', 503)), + openedWindow: window, + expectedEvents: [ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000006', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'change' + } + ], + [ + { + operation: 'subscription_checkout', + stage: 'failed', + outcome: 'failure', + checkout_attempt_id: '00000000-0000-4000-8000-000000000006', + tier: 'creator', + cycle: 'yearly', + checkout_type: 'change', + failure_category: 'api_rejected', + duration_ms: expect.any(Number) + } + ] + ], + storedAttempt: null + }, + { + name: 'a downgrade opens the plain portal and reports nothing', + currentTier: 'PRO', + currentDuration: 'ANNUAL', + target: 'Standard', + portal: () => Promise.resolve(billingPortal), + openedWindow: window, + expectedEvents: [], + storedAttempt: null + } + ] as const)( + 'reports a portal plan change attempt once: $name', + async ({ + currentTier, + currentDuration, + target, + portal, + openedWindow, + expectedEvents, + storedAttempt + }) => { + vi.spyOn(crypto, 'randomUUID').mockReturnValue( + '00000000-0000-4000-8000-000000000006' + ) + mockCanAccessSubscriptionFeatures.value = true + mockSubscriptionTier.value = currentTier + mockSubscriptionDuration.value = currentDuration + vi.mocked(useAuthStore().accessBillingPortal).mockImplementation(portal) + vi.spyOn(window, 'open').mockImplementation(() => openedWindow) + + renderComponent() + await flushPromises() + const targetButton = screen + .getAllByRole('button') + .find((button) => button.textContent.includes(target)) + await userEvent.click(targetButton!) + await flushPromises() + + const telemetry = useTelemetry() + assert.exists(telemetry) + expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual( + expectedEvents + ) + expect( + JSON.parse( + window.localStorage.getItem( + PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY + ) ?? 'null' + ) + ).toEqual(storedAttempt) + } + ) }) describe('credit allotment display', () => { diff --git a/src/platform/cloud/subscription/components/PricingTable.vue b/src/platform/cloud/subscription/components/PricingTable.vue index 57f99146293..dc7b4d82dea 100644 --- a/src/platform/cloud/subscription/components/PricingTable.vue +++ b/src/platform/cloud/subscription/components/PricingTable.vue @@ -281,10 +281,13 @@ import type { TierPricing } from '@/platform/cloud/subscription/constants/tierPricing' import { - recordPendingSubscriptionCheckoutAttempt, + persistPendingSubscriptionCheckoutAttempt, withPendingCheckoutAttemptId } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' -import { performSubscriptionCheckout } from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil' +import { + performSubscriptionCheckout, + runReportedCheckoutAttempt +} from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil' import { isPlanDowngrade } from '@/platform/cloud/subscription/utils/subscriptionTierRank' import type { BillingCycle } from '@/platform/cloud/subscription/utils/subscriptionTierRank' import { isCloud } from '@/platform/distribution/types' @@ -293,6 +296,7 @@ import type { CheckoutAttributionMetadata, PaymentIntentSource } from '@/platform/telemetry/types' +import { PaymentPopupBlockedError } from '@/platform/telemetry/utils/billingFailureCategory' import { useAuthStore } from '@/stores/authStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -388,7 +392,8 @@ const isYearlySubscription = computed( const telemetry = useTelemetry() const { userId } = storeToRefs(useAuthStore()) const workspaceStore = useTeamWorkspaceStore() -const { accessBillingPortal, reportError } = useAuthActions() +const { accessBillingPortal, accessBillingPortalDirect, reportError } = + useAuthActions() const { wrapWithErrorHandlingAsync } = useErrorHandling() const isLoading = ref(false) @@ -515,31 +520,38 @@ const handleSubscribe = wrapWithErrorHandlingAsync( telemetry?.trackBeginCheckout(beginCheckoutMetadata) } } else { - const didOpenPortal = await accessBillingPortal(checkoutTier) - if (!didOpenPortal) { - return - } - - const pendingAttempt = recordPendingSubscriptionCheckoutAttempt({ - tier: targetPlan.tierKey, - cycle: targetPlan.billingCycle, - checkout_type: 'change', - owner_id: checkoutOwnerId, - workspace_id: checkoutWorkspaceId, - payment_intent_source: reason, - ...(previousPlan ? { previous_tier: previousPlan.tierKey } : {}), - ...(previousPlan - ? { previous_cycle: previousPlan.billingCycle } - : {}) - }) - if (beginCheckoutMetadata) { - telemetry?.trackBeginCheckout( - withPendingCheckoutAttemptId( - beginCheckoutMetadata, - pendingAttempt - ) - ) - } + await runReportedCheckoutAttempt( + { + tier: targetPlan.tierKey, + cycle: targetPlan.billingCycle, + checkout_type: 'change', + owner_id: checkoutOwnerId, + workspace_id: checkoutWorkspaceId, + payment_intent_source: reason, + ...(previousPlan + ? { + previous_tier: previousPlan.tierKey, + previous_cycle: previousPlan.billingCycle + } + : {}) + }, + async (pendingAttempt) => { + if (!(await accessBillingPortalDirect(checkoutTier))) { + throw new PaymentPopupBlockedError( + t('subscription.billingTabBlocked') + ) + } + persistPendingSubscriptionCheckoutAttempt(pendingAttempt) + if (beginCheckoutMetadata) { + telemetry?.trackBeginCheckout( + withPendingCheckoutAttemptId( + beginCheckoutMetadata, + pendingAttempt + ) + ) + } + } + ) } } else { // Failure telemetry now lives in performSubscriptionCheckout itself. diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index b9b313c55a4..6d0137b90ef 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -817,6 +817,85 @@ describe('useSubscription', () => { windowOpenSpy.mockRestore() }) + + it.for([ + { + name: 'the checkout request is rejected', + checkoutResponse: () => + ({ + ok: false, + status: 400, + statusText: 'Bad Request', + json: async () => ({ message: 'declined' }), + text: async () => '' + }) as Response, + openedWindow: window, + rejection: 'Failed to initiate subscription', + failure: { failure_category: 'api_rejected' } + }, + { + name: 'no checkout URL comes back', + checkoutResponse: () => new Response(JSON.stringify({})), + openedWindow: window, + rejection: 'No checkout URL returned', + failure: { + failure_category: 'unknown', + error_code: 'missing_checkout_response' + } + }, + { + name: 'the browser blocks the checkout tab', + checkoutResponse: () => + new Response( + JSON.stringify({ checkout_url: 'https://checkout.stripe.com/x' }) + ), + openedWindow: null, + rejection: "Couldn't open the payment page", + failure: { + failure_category: 'redirect', + error_code: 'payment_popup_blocked' + } + } + ])( + 'closes a resubscribe checkout that never opened with one failure: $name', + async ({ checkoutResponse, openedWindow, rejection, failure }) => { + vi.spyOn(crypto, 'randomUUID').mockReturnValue( + '00000000-0000-4000-8000-000000000005' + ) + vi.mocked(global.fetch).mockResolvedValue(checkoutResponse()) + vi.spyOn(window, 'open').mockImplementation(() => openedWindow) + + await expect( + useSubscriptionWithScope().subscribeDirect({ + operation: 'resubscribe', + source: 'settings_billing_panel' + }) + ).rejects.toThrow(rejection) + + const attemptEvent = { + operation: 'subscription_checkout', + checkout_attempt_id: '00000000-0000-4000-8000-000000000005', + tier: 'standard', + cycle: 'monthly', + checkout_type: 'new' + } + expect(mockTelemetry.trackBillingEvent.mock.calls).toEqual([ + [{ ...attemptEvent, stage: 'started', outcome: 'pending' }], + [ + { + ...attemptEvent, + stage: 'failed', + outcome: 'failure', + ...failure, + duration_ms: expect.any(Number) + } + ] + ]) + expect( + localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) + ).toBeNull() + } + ) }) describe('pending checkout recovery', () => { @@ -1993,20 +2072,45 @@ describe('useSubscription', () => { tier: 'creator', cycle: 'yearly', checkout_type: 'new', - payment_intent_source: 'out_of_credits' + payment_intent_source: 'out_of_credits', + duration_ms: expect.any(Number) } ] ] }, { - name: 'a plain subscribeDirect never reported a start, so it reports nothing', + name: 'subscribeDirect reported the start, so it closes with one success', open: (subscription: ReturnType) => subscription.subscribeDirect(), activeStatus: { subscription_tier: 'STANDARD', subscription_duration: 'MONTHLY' } satisfies Partial, - expectedEvents: [] + expectedEvents: [ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000003', + tier: 'standard', + cycle: 'monthly', + checkout_type: 'new' + } + ], + [ + { + operation: 'subscription_checkout', + stage: 'succeeded', + outcome: 'success', + checkout_attempt_id: '00000000-0000-4000-8000-000000000003', + tier: 'standard', + cycle: 'monthly', + checkout_type: 'new', + duration_ms: expect.any(Number) + } + ] + ] } ])( 'closes a confirmed checkout only in the funnel it opened: $name', @@ -2061,7 +2165,7 @@ describe('useSubscription', () => { it.for([ { - name: 'a portal plan change never opened a checkout, so it reports none', + name: 'an attempt that never reported a start reports none', attempt: { attempt_id: 'attempt-change', tier: 'pro', @@ -2166,10 +2270,59 @@ describe('useSubscription', () => { tier: 'pro', cycle: 'monthly', checkout_type: 'change', - recovery_outcome: 'late_success' + recovery_outcome: 'late_success', + duration_ms: expect.any(Number) + } + ] + ]) + }) + + it('measures a reported success from the attempt start', async () => { + localStorage.setItem( + PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY, + JSON.stringify({ + attempt_id: 'attempt-measured', + started_at_ms: Date.now() - 90_000, + tier: 'pro', + cycle: 'monthly', + checkout_type: 'change', + previous_tier: 'creator', + start_reported: true + }) + ) + mockGetBillingStatus.mockResolvedValue({ + is_active: true, + has_funds: true, + renewal_date: '2025-11-16', + subscription_tier: 'PRO', + subscription_duration: 'MONTHLY' + }) + + useCurrentUser().isLoggedIn = computed(() => true) + useSubscriptionWithScope() + + await vi.waitFor(() => { + expect( + localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) + ).toBeNull() + }) + expect(mockTelemetry.trackBillingEvent.mock.calls).toEqual([ + [ + { + operation: 'subscription_checkout', + stage: 'succeeded', + outcome: 'success', + checkout_attempt_id: 'attempt-measured', + tier: 'pro', + cycle: 'monthly', + checkout_type: 'change', + duration_ms: expect.any(Number) } ] ]) + const [[succeeded]] = mockTelemetry.trackBillingEvent.mock.calls + expect(succeeded.duration_ms).toBeGreaterThanOrEqual(90_000) + expect(succeeded.duration_ms).toBeLessThan(120_000) }) it('rechecks pending checkout attempts when the document becomes visible', async () => { diff --git a/src/platform/cloud/subscription/composables/useSubscription.ts b/src/platform/cloud/subscription/composables/useSubscription.ts index e1270b1a5e2..98bf951d225 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.ts @@ -28,7 +28,10 @@ import { } from '@/platform/workspace/api/workspaceApi' import { readOnRail } from '@/platform/workspace/composables/readOnRail' import { useBillingReadRail } from '@/platform/workspace/composables/useBillingReadRail' -import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' +import { + PaymentPopupBlockedError, + categorizeBillingApiError +} from '@/platform/telemetry/utils/billingFailureCategory' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { platformLink } from '@/platform/workspace/utils/platformLink' import { AuthStoreError, useAuthStore } from '@/stores/authStore' @@ -46,8 +49,13 @@ import { claimPendingCheckoutTerminal, getPendingCheckoutTerminal, hasPendingSubscriptionCheckoutAttempt, - recordPendingSubscriptionCheckoutAttempt + persistPendingSubscriptionCheckoutAttempt } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' +import type { ReportedCheckoutAttemptInput } from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil' +import { + missingCheckoutUrlError, + runReportedCheckoutAttempt +} from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil' import { useSubscriptionCancellationWatcher } from './useSubscriptionCancellationWatcher' type CloudSubscriptionCheckoutResponse = NonNullable< @@ -377,7 +385,8 @@ function useSubscriptionInternal() { const trackSubscriptionCheckoutSuccess = ( metadata: SubscriptionSuccessMetadata, - startReported: boolean + startReported: boolean, + startedAtMs: number ) => { if (!startReported && metadata.recovery_outcome !== 'late_success') return telemetry?.trackBillingEvent({ @@ -389,7 +398,8 @@ function useSubscriptionInternal() { cycle: metadata.cycle, checkout_type: metadata.checkout_type, payment_intent_source: metadata.payment_intent_source, - recovery_outcome: metadata.recovery_outcome + recovery_outcome: metadata.recovery_outcome, + duration_ms: Date.now() - startedAtMs }) } @@ -426,14 +436,22 @@ function useSubscriptionInternal() { return } - const { start_reported: startReported, ...metadata } = consumed + const { + start_reported: startReported, + started_at_ms: startedAtMs, + ...metadata + } = consumed telemetry?.trackMonthlySubscriptionSucceeded({ ...(authStore.userId ? { user_id: authStore.userId } : {}), ...metadata }) - trackSubscriptionCheckoutSuccess(metadata, startReported === true) + trackSubscriptionCheckoutSuccess( + metadata, + startReported === true, + startedAtMs + ) // The recovery flow is shared with plain (non-resubscribe) legacy subscribes, // which all funnel through the same subscribeDirect(). Only emit the canonical @@ -477,70 +495,60 @@ function useSubscriptionInternal() { if (subscriptionDuration.value === 'MONTHLY') return 'monthly' } - const recordStandardCheckoutAttempt = ( - options: SubscribeDirectOptions | undefined, - scope: { - ownerId: string | undefined - workspaceId: string | null - previousCancelAt: string | null | undefined - } + const resubscribeAttemptDetails = ( + options: SubscribeDirectOptions | undefined ) => { + if (options?.operation !== 'resubscribe') return {} + const previousCancelAt = subscriptionStatus.value + ? (subscriptionStatus.value.cancel_at ?? null) + : undefined + + return { + operation: options.operation, + resubscribe_source: options.source, + ...(previousCancelAt !== undefined + ? { previous_cancel_at: previousCancelAt } + : {}) + } + } + + const standardCheckoutAttemptInput = ( + options: SubscribeDirectOptions | undefined + ): ReportedCheckoutAttemptInput => { const previousTier = subscriptionTier.value ? toTierKey(subscriptionTier.value) : null - const previousCycle = getPreviousCycle() - - const resubscribeDetails = - options?.operation === 'resubscribe' - ? { - operation: options.operation, - resubscribe_source: options.source, - ...(scope.previousCancelAt !== undefined - ? { previous_cancel_at: scope.previousCancelAt } - : {}) - } - : {} - recordPendingSubscriptionCheckoutAttempt({ + return { tier: 'standard', cycle: 'monthly', checkout_type: canAccessSubscriptionFeatures.value ? 'change' : 'new', previous_tier: previousTier ?? undefined, - previous_cycle: previousCycle, - ...resubscribeDetails, - owner_id: scope.ownerId, - workspace_id: scope.workspaceId - }) + previous_cycle: getPreviousCycle(), + ...resubscribeAttemptDetails(options), + owner_id: authStore.userId ?? undefined, + workspace_id: workspaceStore.activeWorkspaceId + } } /** Unwrapped `subscribe`, for callers that need rejections to propagate (e.g. telemetry). */ - const subscribeDirect = async ( - options?: SubscribeDirectOptions - ): Promise => { - const checkoutScope = { - ownerId: authStore.userId ?? undefined, - workspaceId: workspaceStore.activeWorkspaceId, - previousCancelAt: subscriptionStatus.value - ? (subscriptionStatus.value.cancel_at ?? null) - : undefined - } - const response = await initiateSubscriptionCheckout() - - if (!response.checkout_url) { - throw new Error( - t('toastMessages.failedToInitiateSubscription', { - error: 'No checkout URL returned' - }) - ) - } - - const checkoutWindow = window.open(response.checkout_url, '_blank') - if (!checkoutWindow) { - return - } + const subscribeDirect = (options?: SubscribeDirectOptions): Promise => + runReportedCheckoutAttempt( + standardCheckoutAttemptInput(options), + async (attempt) => { + const response = await initiateSubscriptionCheckout() + + if (!response.checkout_url) throw missingCheckoutUrlError() + + if (!window.open(response.checkout_url, '_blank')) { + throw new PaymentPopupBlockedError( + t('subscription.preview.paymentPopupBlocked') + ) + } - recordStandardCheckoutAttempt(options, checkoutScope) - } + persistPendingSubscriptionCheckoutAttempt(attempt) + } + ) const subscribe = wrapWithErrorHandlingAsync(subscribeDirect, reportError) diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutTracker.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutTracker.ts index 53b170b25cc..90770a985b1 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutTracker.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutTracker.ts @@ -88,7 +88,7 @@ export interface PendingSubscriptionCheckoutAttempt { start_reported?: true } -interface PendingSubscriptionCheckoutAttemptInput { +export interface PendingSubscriptionCheckoutAttemptInput { tier: TierKey cycle: BillingCycle checkout_type: SubscriptionCheckoutType @@ -493,7 +493,10 @@ export const consumePendingSubscriptionCheckoutSuccess = ( status: SubscriptionStatusSnapshot ): | (SubscriptionSuccessMetadata & - Pick) + Pick< + PendingSubscriptionCheckoutAttempt, + 'start_reported' | 'started_at_ms' + >) | null => { const attempt = getPendingSubscriptionCheckoutAttempt() if (!attempt || !didAttemptSucceed(attempt, status)) { @@ -522,6 +525,7 @@ export const consumePendingSubscriptionCheckoutSuccess = ( ? { recovery_outcome: 'late_success' as const } : {}), ...(attempt.start_reported ? { start_reported: true as const } : {}), + started_at_ms: attempt.started_at_ms, value, currency: 'USD', ecommerce: { diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts index f23ed0c7063..cf9b94c0632 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts @@ -241,7 +241,7 @@ describe('performSubscriptionCheckout', () => { it('continues checkout when attribution collection fails', async () => { const checkoutUrl = 'https://checkout.stripe.com/test' - const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) mockGetCheckoutAttribution.mockRejectedValueOnce( new Error('Attribution failed') ) @@ -282,7 +282,7 @@ describe('performSubscriptionCheckout', () => { }) it('reports a failed attribution chunk load as the module_load stage', async () => { - vi.spyOn(window, 'open').mockImplementation(() => null) + vi.spyOn(window, 'open').mockImplementation(() => window) vi.mocked(global.fetch).mockResolvedValue({ ok: true, json: async () => ({ checkout_url: 'https://checkout.stripe.com/test' }) @@ -388,7 +388,10 @@ describe('performSubscriptionCheckout', () => { expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') }) - it('does not persist the pending attempt when the checkout popup is blocked', async () => { + it('closes a blocked checkout tab as a popup-blocked failure and keeps no attempt', async () => { + vi.spyOn(crypto, 'randomUUID').mockReturnValue( + '00000000-0000-4000-8000-000000000004' + ) const checkoutUrl = 'https://checkout.stripe.com/test' const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) @@ -397,7 +400,11 @@ describe('performSubscriptionCheckout', () => { json: async () => ({ checkout_url: checkoutUrl }) } as Response) - await performSubscriptionCheckout('pro', 'monthly') + await expect( + performSubscriptionCheckout('pro', 'monthly', { + paymentIntentSource: 'deep_link' + }) + ).rejects.toThrow("Couldn't open the payment page") expect(openSpy).toHaveBeenCalledWith(checkoutUrl, '_blank') const storedAttempt = window.localStorage.getItem( @@ -407,9 +414,86 @@ describe('performSubscriptionCheckout', () => { expect(mockLocalStorage.setItem).not.toHaveBeenCalled() expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( expect.objectContaining({ - checkout_attempt_id: expect.any(String) + checkout_attempt_id: '00000000-0000-4000-8000-000000000004' }) ) + const telemetry = useTelemetry() + assert.exists(telemetry) + expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000004', + tier: 'pro', + cycle: 'monthly', + checkout_type: 'new', + payment_intent_source: 'deep_link' + } + ], + [ + { + operation: 'subscription_checkout', + stage: 'failed', + outcome: 'failure', + checkout_attempt_id: '00000000-0000-4000-8000-000000000004', + tier: 'pro', + cycle: 'monthly', + checkout_type: 'new', + payment_intent_source: 'deep_link', + failure_category: 'redirect', + error_code: 'payment_popup_blocked', + duration_ms: expect.any(Number) + } + ] + ]) + }) + + it('closes an attempt with no checkout URL with one failure and surfaces the error', async () => { + vi.spyOn(crypto, 'randomUUID').mockReturnValue( + '00000000-0000-4000-8000-000000000007' + ) + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => window) + vi.mocked(global.fetch).mockResolvedValue(new Response(JSON.stringify({}))) + + await expect(performSubscriptionCheckout('pro', 'monthly')).rejects.toThrow( + 'Failed to initiate subscription: No checkout URL returned' + ) + + const telemetry = useTelemetry() + assert.exists(telemetry) + expect(vi.mocked(telemetry.trackBillingEvent).mock.calls).toEqual([ + [ + { + operation: 'subscription_checkout', + stage: 'started', + outcome: 'pending', + checkout_attempt_id: '00000000-0000-4000-8000-000000000007', + tier: 'pro', + cycle: 'monthly', + checkout_type: 'new' + } + ], + [ + { + operation: 'subscription_checkout', + stage: 'failed', + outcome: 'failure', + checkout_attempt_id: '00000000-0000-4000-8000-000000000007', + tier: 'pro', + cycle: 'monthly', + checkout_type: 'new', + failure_category: 'unknown', + error_code: 'missing_checkout_response', + duration_ms: expect.any(Number) + } + ] + ]) + expect(openSpy).not.toHaveBeenCalled() + expect( + window.localStorage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY) + ).toBeNull() }) it('opens the attempt with one started event that the pending attempt shares', async () => { diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts index 7d7b73f0e5e..21fe159cfda 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.ts @@ -1,7 +1,10 @@ import { getComfyApiBaseUrl } from '@/config/comfyApi' import { t } from '@/i18n' import type { TierKey } from '@/platform/cloud/subscription/constants/tierPricing' -import type { PendingSubscriptionCheckoutAttempt } from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' +import type { + PendingSubscriptionCheckoutAttempt, + PendingSubscriptionCheckoutAttemptInput +} from '@/platform/cloud/subscription/utils/subscriptionCheckoutTracker' import { createPendingSubscriptionCheckoutAttempt, persistPendingSubscriptionCheckoutAttempt, @@ -16,7 +19,11 @@ import type { PaymentIntentSource } from '@/platform/telemetry/types' import { parseErrorResponse } from '@/platform/remote/comfyui/errors' -import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' +import { + BillingFailureError, + PaymentPopupBlockedError, + describeBillingFailure +} from '@/platform/telemetry/utils/billingFailureCategory' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { AuthStoreError, useAuthStore } from '@/stores/authStore' @@ -93,7 +100,6 @@ const checkoutAuthHeader = async (authStore: ReturnType) => (await authStore.getFirebaseAuthHeader()) interface PerformSubscriptionCheckoutOptions { - openInNewTab?: boolean paymentIntentSource?: PaymentIntentSource } @@ -118,23 +124,54 @@ export async function performSubscriptionCheckout( ): Promise { if (!isCloud) return + await runReportedCheckoutAttempt( + { + tier: tierKey, + cycle: currentBillingCycle, + checkout_type: 'new', + payment_intent_source: options.paymentIntentSource, + owner_id: useAuthStore().userId ?? undefined, + workspace_id: useTeamWorkspaceStore().activeWorkspaceId + }, + (pendingAttempt) => + initiateSubscriptionCheckout(pendingAttempt, options.paymentIntentSource) + ) +} + +export const missingCheckoutUrlError = () => + new BillingFailureError( + t('toastMessages.failedToInitiateSubscription', { + error: 'No checkout URL returned' + }), + { failure_category: 'unknown', error_code: 'missing_checkout_response' } + ) + +export type ReportedCheckoutAttemptInput = Omit< + PendingSubscriptionCheckoutAttemptInput, + 'start_reported' +> + +/** + * Reports `started` for one legacy checkout attempt and `failed` when `launch` + * rejects. Its success is reported later by the pending-checkout recovery, + * which closes only attempts marked `start_reported`. + */ +export async function runReportedCheckoutAttempt( + input: ReportedCheckoutAttemptInput, + launch: (attempt: PendingSubscriptionCheckoutAttempt) => Promise +): Promise { const telemetry = useTelemetry() - const pendingAttempt = createPendingSubscriptionCheckoutAttempt({ - tier: tierKey, - cycle: currentBillingCycle, - checkout_type: 'new', - payment_intent_source: options.paymentIntentSource, - owner_id: useAuthStore().userId ?? undefined, - workspace_id: useTeamWorkspaceStore().activeWorkspaceId, + const attempt = createPendingSubscriptionCheckoutAttempt({ + ...input, start_reported: true }) const attemptEvent = { operation: 'subscription_checkout', - checkout_attempt_id: pendingAttempt.attempt_id, - tier: tierKey, - cycle: currentBillingCycle, - checkout_type: 'new', - payment_intent_source: options.paymentIntentSource + checkout_attempt_id: attempt.attempt_id, + tier: attempt.tier, + cycle: attempt.cycle, + checkout_type: attempt.checkout_type, + payment_intent_source: attempt.payment_intent_source } as const telemetry?.trackBillingEvent({ ...attemptEvent, @@ -143,14 +180,14 @@ export async function performSubscriptionCheckout( }) try { - await initiateSubscriptionCheckout(pendingAttempt, options) + await launch(attempt) } catch (error) { telemetry?.trackBillingEvent({ ...attemptEvent, stage: 'failed', outcome: 'failure', - failure_category: categorizeBillingApiError(error), - duration_ms: Date.now() - pendingAttempt.started_at_ms + ...describeBillingFailure(error), + duration_ms: Date.now() - attempt.started_at_ms }) throw error } @@ -158,9 +195,8 @@ export async function performSubscriptionCheckout( async function initiateSubscriptionCheckout( pendingAttempt: PendingSubscriptionCheckoutAttempt, - options: PerformSubscriptionCheckoutOptions + paymentIntentSource: PaymentIntentSource | undefined ): Promise { - const { openInNewTab = true, paymentIntentSource } = options const { tier: tierKey, cycle: currentBillingCycle } = pendingAttempt const authStore = useAuthStore() @@ -201,7 +237,6 @@ async function initiateSubscriptionCheckout( tierKey, currentBillingCycle, paymentIntentSource, - openInNewTab, pendingAttempt, checkoutAttribution, telemetry @@ -212,7 +247,6 @@ interface CheckoutCompletionContext { tierKey: TierKey currentBillingCycle: BillingCycle paymentIntentSource?: PaymentIntentSource - openInNewTab: boolean pendingAttempt: PendingSubscriptionCheckoutAttempt checkoutAttribution: CheckoutAttributionMetadata telemetry: ReturnType @@ -244,20 +278,14 @@ function completeSubscriptionCheckout( checkoutUrl: string | undefined, context: CheckoutCompletionContext ) { - if (!checkoutUrl) return - - const { openInNewTab, pendingAttempt } = context + if (!checkoutUrl) throw missingCheckoutUrlError() trackBeginCheckout(context) - if (openInNewTab) { - const checkoutWindow = window.open(checkoutUrl, '_blank') - if (!checkoutWindow) { - return - } - persistPendingSubscriptionCheckoutAttempt(pendingAttempt) - } else { - persistPendingSubscriptionCheckoutAttempt(pendingAttempt) - globalThis.location.href = checkoutUrl + if (!window.open(checkoutUrl, '_blank')) { + throw new PaymentPopupBlockedError( + t('subscription.preview.paymentPopupBlocked') + ) } + persistPendingSubscriptionCheckoutAttempt(context.pendingAttempt) } diff --git a/src/platform/telemetry/utils/billingFailureCategory.test.ts b/src/platform/telemetry/utils/billingFailureCategory.test.ts index 7055d9f1e22..ff0aa63dcbd 100644 --- a/src/platform/telemetry/utils/billingFailureCategory.test.ts +++ b/src/platform/telemetry/utils/billingFailureCategory.test.ts @@ -3,7 +3,49 @@ import { describe, expect, it } from 'vitest' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { AuthStoreError } from '@/stores/authStore' -import { categorizeBillingApiError } from './billingFailureCategory' +import { + BillingFailureError, + PaymentPopupBlockedError, + categorizeBillingApiError, + describeBillingFailure +} from './billingFailureCategory' + +describe('describeBillingFailure', () => { + it.for([ + { + name: 'a blocked payment tab is a redirect with its own code', + error: new PaymentPopupBlockedError('blocked'), + failure: { + failure_category: 'redirect', + error_code: 'payment_popup_blocked' + } + }, + { + name: 'a billing failure error reports the failure it carries', + error: new BillingFailureError('no checkout URL', { + failure_category: 'unknown', + error_code: 'missing_checkout_response' + }), + failure: { + failure_category: 'unknown', + error_code: 'missing_checkout_response' + } + }, + { + name: 'a request rejection keeps its category and names no code', + error: new AuthStoreError('rejected', 400), + failure: { failure_category: 'api_rejected' } + } + ])('$name', ({ error, failure }) => { + expect(describeBillingFailure(error)).toEqual(failure) + }) + + it('shows a blocked tab as a redirect to callers that read only the category', () => { + expect( + categorizeBillingApiError(new PaymentPopupBlockedError('blocked')) + ).toBe('redirect') + }) +}) describe('categorizeBillingApiError', () => { it('categorizes a WorkspaceApiError with no status as a network failure', () => { diff --git a/src/platform/telemetry/utils/billingFailureCategory.ts b/src/platform/telemetry/utils/billingFailureCategory.ts index c8f50a42012..a4517b9a02e 100644 --- a/src/platform/telemetry/utils/billingFailureCategory.ts +++ b/src/platform/telemetry/utils/billingFailureCategory.ts @@ -3,6 +3,32 @@ import { AuthStoreError } from '@/stores/authStore' import type { BillingFailure } from '../types' +export class BillingFailureError extends Error { + constructor( + message: string, + public readonly failure: BillingFailure + ) { + super(message) + this.name = 'BillingFailureError' + } +} + +export class PaymentPopupBlockedError extends BillingFailureError { + constructor(message: string) { + super(message, { + failure_category: 'redirect', + error_code: 'payment_popup_blocked' + }) + this.name = 'PaymentPopupBlockedError' + } +} + +export function describeBillingFailure(err: unknown): BillingFailure { + return err instanceof BillingFailureError + ? err.failure + : { failure_category: categorizeBillingApiError(err) } +} + /** * A `WorkspaceApiError` that names its category keeps it. Otherwise a * `WorkspaceApiError`/`AuthStoreError` with no `status` never reached the @@ -12,6 +38,7 @@ import type { BillingFailure } from '../types' export function categorizeBillingApiError( err: unknown ): BillingFailure['failure_category'] { + if (err instanceof BillingFailureError) return err.failure.failure_category if (err instanceof WorkspaceApiError) { if (err.failureCategory) return err.failureCategory return err.status === undefined ? 'network' : 'api_rejected'