diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index b69ddb889f8..cb8c5db563b 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -48,6 +48,12 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ }) })) +const mockReportError = vi.hoisted(() => vi.fn()) + +vi.mock(import('@/platform/telemetry/reportError'), () => ({ + reportError: mockReportError +})) + vi.mock(import('@/platform/workspace/api/workspaceApi'), () => ({ workspaceApi: { getBillingOpStatus: vi.fn() @@ -755,6 +761,70 @@ describe('billingOperationStore', () => { expect(useToastStore().remove).toHaveBeenCalledWith(receivedToast) }) + + it('resolves the terminal promise even if a success side effect throws', async () => { + vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ + id: 'op-1', + status: 'succeeded', + started_at: new Date().toISOString() + }) + const error = new Error('toast rendering failed') + vi.mocked(useToastStore().add).mockImplementation((toast) => { + if (toast.severity === 'success') throw error + }) + + const store = useBillingOperationStore() + const terminal = store.startOperation('op-1', 'topup') + + await vi.advanceTimersByTimeAsync(0) + + await expect(terminal).resolves.toMatchObject({ status: 'succeeded' }) + expect(mockReportError).toHaveBeenCalledWith(error, { + errorType: 'failure_handling_billing_operation_success', + context: { billing_op_id: 'op-1' } + }) + }) + + it('resolves the terminal promise even if cleanup throws', async () => { + vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ + id: 'op-1', + status: 'succeeded', + started_at: new Date().toISOString() + }) + const error = new Error('toast cleanup failed') + vi.mocked(useToastStore().remove).mockImplementationOnce(() => { + throw error + }) + + const store = useBillingOperationStore() + const terminal = store.startOperation('op-1', 'subscription') + + await vi.advanceTimersByTimeAsync(0) + + await expect(terminal).resolves.toMatchObject({ status: 'succeeded' }) + expect(mockReportError).toHaveBeenCalledWith(error, { + errorType: 'failure_handling_billing_operation_success', + context: { billing_op_id: 'op-1' } + }) + }) + + it('resolves the terminal promise even if reconciliation throws synchronously', async () => { + vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ + id: 'op-1', + status: 'succeeded', + started_at: new Date().toISOString() + }) + mockReconcileSubscriptionSuccess.mockImplementationOnce(() => { + throw new Error('reconcile failed') + }) + + const store = useBillingOperationStore() + const terminal = store.startOperation('op-1', 'subscription') + + await vi.advanceTimersByTimeAsync(0) + + await expect(terminal).resolves.toMatchObject({ status: 'succeeded' }) + }) }) describe('polling failure', () => { diff --git a/src/platform/workspace/stores/billingOperationStore.ts b/src/platform/workspace/stores/billingOperationStore.ts index 0b1288df4de..939bc1988a0 100644 --- a/src/platform/workspace/stores/billingOperationStore.ts +++ b/src/platform/workspace/stores/billingOperationStore.ts @@ -13,6 +13,7 @@ import type { BillingCycle } from '@/platform/cloud/subscription/utils/subscript import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' +import { reportError } from '@/platform/telemetry/reportError' import type { BillingFailure, PaymentIntentSource, @@ -670,121 +671,130 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { if (!operation) return updateOperationStatus(opId, 'succeeded', null) - cleanup(opId) - const telemetry = useTelemetry() - const now = Date.now() - const operationDurationMs = now - operation.operationStartedAt - telemetry?.trackBillingEvent({ - operation: 'operation', - stage: 'succeeded', - outcome: 'success', - billing_op_id: opId, - operation_type: operation.type, - tier: operation.tier, - cycle: operation.cycle, - checkout_type: operation.checkoutType, - payment_intent_source: operation.paymentIntentSource, - duration_ms: operationDurationMs - }) + try { + cleanup(opId) - if ( - operation.type === 'subscription' && - operation.businessAttemptStartedAt !== undefined - ) { - const durationMs = now - operation.businessAttemptStartedAt + const telemetry = useTelemetry() + const now = Date.now() + const operationDurationMs = now - operation.operationStartedAt telemetry?.trackBillingEvent({ - operation: 'subscription_checkout', + operation: 'operation', stage: 'succeeded', outcome: 'success', + billing_op_id: opId, + operation_type: operation.type, tier: operation.tier, cycle: operation.cycle, checkout_type: operation.checkoutType, payment_intent_source: operation.paymentIntentSource, - billing_op_id: opId, - duration_ms: durationMs + duration_ms: operationDurationMs }) - // Also fires the legacy event for providers (Mixpanel, GTM) that don't - // implement trackBillingEvent. Gated to actual new/upgraded - // subscriptions — a downgrade-to-personal is churn, not a conversion, - // and this event drives a GA4 "subscription succeeded" conversion goal. - if (!operation.downgradeToPersonal) { - telemetry?.trackMonthlySubscriptionSucceeded({ + + if ( + operation.type === 'subscription' && + operation.businessAttemptStartedAt !== undefined + ) { + const durationMs = now - operation.businessAttemptStartedAt + telemetry?.trackBillingEvent({ + operation: 'subscription_checkout', + stage: 'succeeded', + outcome: 'success', tier: operation.tier, cycle: operation.cycle, checkout_type: operation.checkoutType, payment_intent_source: operation.paymentIntentSource, - billing_op_id: opId + billing_op_id: opId, + duration_ms: durationMs + }) + // Also fires the legacy event for providers (Mixpanel, GTM) that don't + // implement trackBillingEvent. Gated to actual new/upgraded + // subscriptions — a downgrade-to-personal is churn, not a conversion, + // and this event drives a GA4 "subscription succeeded" conversion goal. + if (!operation.downgradeToPersonal) { + telemetry?.trackMonthlySubscriptionSucceeded({ + tier: operation.tier, + cycle: operation.cycle, + checkout_type: operation.checkoutType, + payment_intent_source: operation.paymentIntentSource, + billing_op_id: opId + }) + } + } else if ( + operation.type === 'topup' && + operation.businessAttemptStartedAt !== undefined + ) { + telemetry?.trackBillingEvent({ + operation: 'topup', + stage: 'succeeded', + outcome: 'success', + billing_op_id: opId, + duration_ms: now - operation.businessAttemptStartedAt + }) + } + // Mirrors handleFailure's structure: not gated on businessAttemptStartedAt, + // since a downgrade always has its own startedAt for duration_ms below. + if (operation.downgradeToPersonal) { + telemetry?.trackBillingEvent({ + operation: 'downgrade_to_personal', + stage: 'succeeded', + outcome: 'success', + member_removal_count: + operation.downgradeToPersonal.memberRemovalCount, + member_removal_failures: + operation.downgradeToPersonal.memberRemovalFailures, + target_tier: operation.downgradeToPersonal.targetTier, + duration_ms: now - operation.downgradeToPersonal.startedAt }) } - } else if ( - operation.type === 'topup' && - operation.businessAttemptStartedAt !== undefined - ) { - telemetry?.trackBillingEvent({ - operation: 'topup', - stage: 'succeeded', - outcome: 'success', - billing_op_id: opId, - duration_ms: now - operation.businessAttemptStartedAt - }) - } - // Mirrors handleFailure's structure: not gated on businessAttemptStartedAt, - // since a downgrade always has its own startedAt for duration_ms below. - if (operation.downgradeToPersonal) { - telemetry?.trackBillingEvent({ - operation: 'downgrade_to_personal', - stage: 'succeeded', - outcome: 'success', - member_removal_count: operation.downgradeToPersonal.memberRemovalCount, - member_removal_failures: - operation.downgradeToPersonal.memberRemovalFailures, - target_tier: operation.downgradeToPersonal.targetTier, - duration_ms: now - operation.downgradeToPersonal.startedAt - }) - } - - const billingContext = useBillingContext() - const capabilities = useBillingCapabilities() - if (operation.type === 'subscription') { - await Promise.allSettled([ - billingContext.reconcileSubscriptionSuccess(), - capabilities.refresh() - ]) - } else { - await Promise.allSettled([ - billingContext.fetchStatus(), - billingContext.fetchBalance(), - capabilities.refresh() - ]) - } - if (operation.type === 'cancel') { - useTeamWorkspaceStore().updateActiveWorkspace({ isSubscribed: false }) - resolveTerminal(opId) - return - } + const billingContext = useBillingContext() + const capabilities = useBillingCapabilities() + if (operation.type === 'subscription') { + await Promise.allSettled([ + billingContext.reconcileSubscriptionSuccess(), + capabilities.refresh() + ]) + } else { + await Promise.allSettled([ + billingContext.fetchStatus(), + billingContext.fetchBalance(), + capabilities.refresh() + ]) + } - // A subscription checkout shows its own success step in the pricing dialog, - // so leave it open. Top-ups have no such step: close and surface settings. - if (operation.type === 'topup') { - useDialogStore().closeDialog({ key: 'top-up-credits' }) - useSettingsDialog().show(isCloud ? 'workspace' : 'credits') - } + if (operation.type === 'cancel') { + useTeamWorkspaceStore().updateActiveWorkspace({ isSubscribed: false }) + return + } - const toastStore = useToastStore() - const messageKey = - operation.type === 'subscription' - ? 'billingOperation.subscriptionSuccess' - : 'billingOperation.topupSuccess' + // A subscription checkout shows its own success step in the pricing dialog, + // so leave it open. Top-ups have no such step: close and surface settings. + if (operation.type === 'topup') { + useDialogStore().closeDialog({ key: 'top-up-credits' }) + useSettingsDialog().show(isCloud ? 'workspace' : 'credits') + } - toastStore.add({ - severity: 'success', - summary: t(messageKey), - life: 5000 - }) + const toastStore = useToastStore() + const messageKey = + operation.type === 'subscription' + ? 'billingOperation.subscriptionSuccess' + : 'billingOperation.topupSuccess' - resolveTerminal(opId) + toastStore.add({ + severity: 'success', + summary: t(messageKey), + life: 5000 + }) + } catch (error) { + reportError(error, { + errorType: 'failure_handling_billing_operation_success', + context: { billing_op_id: opId } + }) + throw error + } finally { + resolveTerminal(opId) + } } function handleFailure(opId: string, errorMessage: string | null) {