diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 618898ea9fa..247c00dcdfa 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2303,6 +2303,7 @@ "failedToCreateCustomer": "Failed to create customer: {error}", "failedToInitiateCreditPurchase": "Failed to initiate credit purchase: {error}", "failedToAccessBillingPortal": "Failed to access billing portal: {error}", + "invalidBillingPortalUrl": "Invalid portal URL", "failedToPurchaseCredits": "Failed to purchase credits: {error}", "failedToFetchSubscription": "Failed to fetch subscription status: {error}", "failedToInitiateSubscription": "Failed to initiate subscription: {error}", diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index d7756ed4122..0e16d650e49 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -1,7 +1,7 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { computed, reactive } from 'vue' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, effectScope, reactive } from 'vue' import type { PaymentIntentSource } from '@/platform/telemetry/types' import type { @@ -49,6 +49,10 @@ function allPlans(): Plan[] { return [makeStandardYearly(), makeCreatorMonthly()] } +function errorWithCode(code: string, message = 'error') { + return Object.assign(new Error(message), { code }) +} + interface ReactivationPreviewPlanInput { slug: string tier: PreviewSubscribeResponse['new_plan']['tier'] @@ -141,6 +145,9 @@ const { mockFetchPlans, mockFetchStatus, mockFetchBalance, + mockOpen, + mockGetBillingStatus, + mockGetPaymentPortalUrl, mockPlans, mockResubscribe, mockToastAdd, @@ -162,6 +169,9 @@ const { mockFetchPlans: vi.fn(), mockFetchStatus: vi.fn(), mockFetchBalance: vi.fn(), + mockOpen: vi.fn(), + mockGetBillingStatus: vi.fn(), + mockGetPaymentPortalUrl: vi.fn(), mockPlans: { value: [] as Plan[] }, mockResubscribe: vi.fn(), mockToastAdd: vi.fn(), @@ -233,7 +243,11 @@ vi.mock('@/services/dialogService', () => ({ // Shields the test from the real workspaceApi → @/scripts/api → app.ts import chain vi.mock('@/platform/workspace/api/workspaceApi', () => ({ - workspaceApi: { resubscribe: mockResubscribe } + workspaceApi: { + resubscribe: mockResubscribe, + getBillingStatus: mockGetBillingStatus, + getPaymentPortalUrl: mockGetPaymentPortalUrl + } })) vi.mock('@/platform/workspace/stores/billingOperationStore', () => ({ @@ -295,6 +309,7 @@ vi.mock('vue-i18n', async (importOriginal) => { describe('useSubscriptionCheckout', () => { let emit: ReturnType + const scopes: ReturnType[] = [] async function setup( paymentIntentSource?: PaymentIntentSource, @@ -302,9 +317,23 @@ describe('useSubscriptionCheckout', () => { ) { const { useSubscriptionCheckout } = await import('./useSubscriptionCheckout') - return useSubscriptionCheckout(emit as never, paymentIntentSource, { - tierPlanType + const scope = effectScope() + scopes.push(scope) + return scope.run(() => + useSubscriptionCheckout(emit as never, paymentIntentSource, { + tierPlanType + }) + )! + } + + async function submitRejectedPreview(code: string, message = 'error') { + const checkout = await setup() + mockPreviewSubscribe.mockRejectedValueOnce(errorWithCode(code, message)) + await checkout.handleSubscribeClick({ + tierKey: 'standard', + billingCycle: 'yearly' }) + return checkout } beforeEach(() => { @@ -321,6 +350,17 @@ describe('useSubscriptionCheckout', () => { mockShowDowngradeToPersonalDialog.mockResolvedValue(null) mockUserId.value = 'user-1' mockIsTeamPlan.value = false + mockOpen.mockReturnValue({} as Window) + mockGetBillingStatus.mockResolvedValue({ billing_status: 'paid' }) + mockGetPaymentPortalUrl.mockResolvedValue({ + url: 'https://billing.stripe.com/portal' + }) + vi.stubGlobal('location', { + href: 'https://app.test/subscribe?invite=secret#token', + origin: 'https://app.test', + pathname: '/subscribe' + }) + vi.stubGlobal('open', mockOpen) mockShouldUseWorkspaceBilling.value = true mockSetActiveWorkspaceId('workspace-1') mockPermissions.value = { @@ -332,6 +372,10 @@ describe('useSubscriptionCheckout', () => { emit = vi.fn() }) + afterEach(() => { + for (const scope of scopes.splice(0)) scope.stop() + }) + describe('handleSubscribeClick', () => { it('transitions to preview on successful preview', async () => { const checkout = await setup() @@ -379,6 +423,96 @@ describe('useSubscriptionCheckout', () => { ) }) + it.for([ + ['SUBSCRIPTION_PAYMENT_REQUIRED', null], + ['TRANSITION_NOT_ALLOWED', 'payment_failed'] + ] as const)( + 'routes %s previews to the billing portal', + async ([code, status]) => { + if (status) { + mockGetBillingStatus.mockResolvedValueOnce({ billing_status: status }) + } + await submitRejectedPreview(code) + expect(mockGetBillingStatus).toHaveBeenCalledTimes(status ? 1 : 0) + expect(mockGetPaymentPortalUrl).toHaveBeenCalledWith( + 'https://app.test/subscribe' + ) + expect(mockOpen).toHaveBeenCalledWith( + 'https://billing.stripe.com/portal', + '_blank' + ) + expect(globalThis.location.href).toBe( + 'https://app.test/subscribe?invite=secret#token' + ) + expect(mockFetchStatus).not.toHaveBeenCalled() + + window.dispatchEvent(new Event('focus')) + await vi.waitFor(() => expect(mockFetchStatus).toHaveBeenCalledOnce()) + window.dispatchEvent(new Event('focus')) + expect(mockFetchStatus).toHaveBeenCalledOnce() + } + ) + + it('preserves the checkout when the billing portal popup is blocked', async () => { + mockOpen.mockReturnValueOnce(null) + const checkout = await submitRejectedPreview( + 'SUBSCRIPTION_PAYMENT_REQUIRED' + ) + + expect(checkout.selectedTierKey.value).toBe('standard') + expect(globalThis.location.href).toBe( + 'https://app.test/subscribe?invite=secret#token' + ) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'warn', + detail: 'subscription.preview.paymentPopupBlocked' + }) + ) + }) + + it('keeps the original error path for non-payment transition failures', async () => { + await submitRejectedPreview( + 'TRANSITION_NOT_ALLOWED', + 'Plan change is unavailable' + ) + expect(mockGetPaymentPortalUrl).not.toHaveBeenCalled() + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ detail: 'Plan change is unavailable' }) + ) + }) + + it('shows the portal error when payment recovery cannot open', async () => { + mockGetPaymentPortalUrl.mockRejectedValueOnce( + new Error('Portal unavailable') + ) + await submitRejectedPreview('SUBSCRIPTION_PAYMENT_REQUIRED') + expect(globalThis.location.href).toBe( + 'https://app.test/subscribe?invite=secret#token' + ) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ detail: 'Portal unavailable' }) + ) + }) + + it.for([ + undefined, + '', + 'javascript:alert(1)', + 'https://billing.stripe.com.evil.test/portal' + ])('rejects an unsafe billing portal URL: %s', async (url) => { + mockGetPaymentPortalUrl.mockResolvedValueOnce({ url }) + await submitRejectedPreview('SUBSCRIPTION_PAYMENT_REQUIRED') + expect(globalThis.location.href).toBe( + 'https://app.test/subscribe?invite=secret#token' + ) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + detail: 'toastMessages.failedToAccessBillingPortal' + }) + ) + }) + it('shows error toast when plan slug is not found', async () => { const checkout = await setup() mockPlans.value = [] @@ -617,6 +751,26 @@ describe('useSubscriptionCheckout', () => { }) describe('handleSubscribeTeamClick', () => { + const teamStop = { + id: 'team_1400', + usd: 1400, + credits: 295_400, + discountedUsd: 1295 + } + + async function startTeamPaymentRecovery() { + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + const checkout = await setup() + const selection = checkout.handleSubscribeTeamClick({ + stop: teamStop, + billingCycle: 'monthly', + isChange: true + }) + return { checkout, selection } + } + it('transitions to preview with the selected team stop and cycle', async () => { const checkout = await setup() @@ -760,6 +914,45 @@ describe('useSubscriptionCheckout', () => { expect(checkout.isLoadingPreview.value).toBe(false) }) + it('ignores a stale Team payment recovery after returning to pricing', async () => { + let resolvePortal!: (portal: { url: string }) => void + mockGetPaymentPortalUrl.mockImplementationOnce( + () => + new Promise<{ url: string }>((resolve) => { + resolvePortal = resolve + }) + ) + const { checkout, selection } = await startTeamPaymentRecovery() + await vi.waitFor(() => expect(mockGetPaymentPortalUrl).toHaveBeenCalled()) + expect(checkout.isLoadingPreview.value).toBe(true) + + checkout.handleBackToPricing() + resolvePortal({ url: 'https://billing.stripe.com/portal' }) + await selection + + expect(globalThis.location.href).toBe( + 'https://app.test/subscribe?invite=secret#token' + ) + expect(checkout.checkoutStep.value).toBe('pricing') + expect(mockOpen).not.toHaveBeenCalled() + expect(mockToastAdd).not.toHaveBeenCalled() + }) + + it('returns a failed Team payment recovery to pricing', async () => { + mockGetPaymentPortalUrl.mockRejectedValueOnce( + new Error('Portal unavailable') + ) + const { checkout, selection } = await startTeamPaymentRecovery() + await selection + + expect(checkout.checkoutStep.value).toBe('pricing') + expect(checkout.selectedTeamStop.value).toBeNull() + expect(mockToastAdd).toHaveBeenCalledOnce() + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ detail: 'Portal unavailable' }) + ) + }) + it('falls back to the display-only confirm when the preview is a fresh subscription', async () => { const checkout = await setup() mockPreviewSubscribe.mockResolvedValueOnce({ @@ -2191,6 +2384,46 @@ describe('useSubscriptionCheckout', () => { ) }) + it('returns to pricing when reactivation payment recovery fails', async () => { + mockSubscription.value = { isCancelled: true } + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + mockGetPaymentPortalUrl.mockRejectedValueOnce( + new Error('Portal unavailable') + ) + const checkout = await setup() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + checkout.previewData.value = {} as never + + await checkout.handleConfirmTransition() + + expect(checkout.checkoutStep.value).toBe('pricing') + expect(checkout.previewData.value).toBeNull() + expect(mockSubscribe).not.toHaveBeenCalled() + }) + + it('recovers payment failure while refreshing an expired quote', async () => { + mockSubscribe.mockRejectedValueOnce( + errorWithCode('PRORATION_QUOTE_EXPIRED', 'Quote expired') + ) + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + const checkout = await setup() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + + await checkout.handleConfirmTransition() + + expect(mockOpen).toHaveBeenCalledWith( + 'https://billing.stripe.com/portal', + '_blank' + ) + expect(mockToastAdd).not.toHaveBeenCalled() + }) + it('forwards confirmReactivation true when the disclosure banner reports consent', async () => { const checkout = await setup() checkout.selectedTierKey.value = 'standard' diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index a78fee37c6c..59394e6b8e8 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -1,5 +1,6 @@ import { useToast } from 'primevue/usetoast' import { computed, ref } from 'vue' +import { useEventListener } from '@vueuse/core' import { useI18n } from 'vue-i18n' import { useBillingContext } from '@/composables/billing/useBillingContext' @@ -20,6 +21,7 @@ import type { PreviewSubscribeResponse, SubscribeResponse } from '@/platform/workspace/api/workspaceApi' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -61,6 +63,16 @@ type PreviewVariant = | 'personal-new' | null +function parseBillingPortalUrl(url: unknown): URL | null { + if (typeof url !== 'string') return null + try { + const portalUrl = new URL(url) + return portalUrl.origin === 'https://billing.stripe.com' ? portalUrl : null + } catch { + return null + } +} + /** Thrown by `assertReactivationAmountUnchanged` when a fresh preview no * longer matches the billing state the reactivation banner showed and the * user consented to. Caught by the surrounding try/catch and surfaced @@ -114,6 +126,12 @@ export function useSubscriptionCheckout( const selectedTierKey = ref(null) const selectedTeamCheckout = ref(null) let teamPreviewRequestId = 0 + let refreshStatusOnFocus = false + useEventListener(window, 'focus', () => { + if (!refreshStatusOnFocus) return + refreshStatusOnFocus = false + void fetchStatus() + }) // Some legacy-rail status reads cannot expose a scheduled cancellation even // though the subscribe authority can see it in Stripe. Once that authority // rejects an unconfirmed change, keep the consent screen in reactivation @@ -276,6 +294,53 @@ export function useSubscriptionCheckout( ) } + async function recoverOutstandingPayment( + error: unknown, + isCurrent: () => boolean = () => true + ) { + let requiresRecovery = hasErrorCode(error, 'SUBSCRIPTION_PAYMENT_REQUIRED') + if (!requiresRecovery && hasErrorCode(error, 'TRANSITION_NOT_ALLOWED')) { + try { + requiresRecovery = + (await workspaceApi.getBillingStatus()).billing_status === + 'payment_failed' + } catch { + return null + } + } + if (!requiresRecovery || !isCurrent()) return null + + try { + const returnUrl = `${globalThis.location.origin}${globalThis.location.pathname}` + const portalUrl = parseBillingPortalUrl( + (await workspaceApi.getPaymentPortalUrl(returnUrl)).url + ) + if (!isCurrent()) return null + if (!portalUrl) { + throw new Error( + t('toastMessages.failedToAccessBillingPortal', { + error: t('toastMessages.invalidBillingPortalUrl') + }) + ) + } + const paymentWindow = window.open(portalUrl.href, '_blank') + if (!paymentWindow) { + toast.add({ + severity: 'warn', + summary: t('g.warning'), + detail: t('subscription.preview.paymentPopupBlocked') + }) + return 'blocked' + } + refreshStatusOnFocus = true + return 'opened' + } catch (portalError) { + if (!isCurrent()) return null + showSubscribeError(portalError) + return 'failed' + } + } + async function refreshExpiredProrationQuote( error: unknown, planSlug: string, @@ -287,7 +352,9 @@ export function useSubscriptionCheckout( try { freshPreview = await previewSubscribe(planSlug, options) } catch (previewError) { - showSubscribeError(previewError) + if (!(await recoverOutstandingPayment(previewError))) { + showSubscribeError(previewError) + } return true } if (!isReactivationCapablePreview(freshPreview)) { @@ -332,7 +399,10 @@ export function useSubscriptionCheckout( let freshPreview: PreviewSubscribeResponse | null = null try { freshPreview = await previewSubscribe(planSlug, options) - } catch { + } catch (error) { + const recovery = await recoverOutstandingPayment(error) + if (recovery === 'failed') resetToPricing() + if (recovery) return // Treated the same as an incapable preview below. } if (isReactivationCapablePreview(freshPreview)) { @@ -459,6 +529,7 @@ export function useSubscriptionCheckout( previewData.value = response checkoutStep.value = 'preview' } catch (error) { + if (await recoverOutstandingPayment(error)) return const message = error instanceof Error ? error.message @@ -518,6 +589,15 @@ export function useSubscriptionCheckout( }) } catch (error) { previewError = error + const recovery = await recoverOutstandingPayment( + error, + () => previewRequestId === teamPreviewRequestId + ) + if (recovery === 'failed') { + resetToPricing() + return + } + if (recovery) return } finally { if (previewRequestId === teamPreviewRequestId) { isLoadingPreview.value = false @@ -626,28 +706,17 @@ export function useSubscriptionCheckout( checkoutType }) } catch (error) { - if (hasErrorCode(error, 'REACTIVATION_CONFIRMATION_REQUIRED')) { - trackSubscriptionFailure({ - tier: tierKey, - cycle: billingCycle, - checkoutType - }) - await refreshPreviewOnReactivationBlock(planSlug) - return - } - if (await refreshExpiredProrationQuote(error, planSlug)) { - trackSubscriptionFailure({ - tier: tierKey, - cycle: billingCycle, - checkoutType - }) - return - } trackSubscriptionFailure({ tier: tierKey, cycle: billingCycle, checkoutType }) + if (await recoverOutstandingPayment(error)) return + if (hasErrorCode(error, 'REACTIVATION_CONFIRMATION_REQUIRED')) { + await refreshPreviewOnReactivationBlock(planSlug) + return + } + if (await refreshExpiredProrationQuote(error, planSlug)) return showSubscribeError(error) } finally { isSubscribing.value = false @@ -837,12 +906,13 @@ export function useSubscriptionCheckout( checkoutType }) } catch (error) { + trackSubscriptionFailure({ + tier: 'team', + cycle: billingCycle, + checkoutType + }) + if (await recoverOutstandingPayment(error)) return if (hasErrorCode(error, 'REACTIVATION_CONFIRMATION_REQUIRED')) { - trackSubscriptionFailure({ - tier: 'team', - cycle: billingCycle, - checkoutType - }) await refreshPreviewOnReactivationBlock(planSlug, { teamCreditStopId: stop.id, billingCycle @@ -854,19 +924,8 @@ export function useSubscriptionCheckout( teamCreditStopId: stop.id, billingCycle }) - ) { - trackSubscriptionFailure({ - tier: 'team', - cycle: billingCycle, - checkoutType - }) + ) return - } - trackSubscriptionFailure({ - tier: 'team', - cycle: billingCycle, - checkoutType - }) showSubscribeError(error) } finally { isSubscribing.value = false