diff --git a/browser_tests/tests/vueNodes/interactions/canvas/pan.spec.ts-snapshots/vue-nodes-paned-with-touch-mobile-chrome-linux.png b/browser_tests/tests/vueNodes/interactions/canvas/pan.spec.ts-snapshots/vue-nodes-paned-with-touch-mobile-chrome-linux.png index d0ee9d817e1..83e762bb06c 100644 Binary files a/browser_tests/tests/vueNodes/interactions/canvas/pan.spec.ts-snapshots/vue-nodes-paned-with-touch-mobile-chrome-linux.png and b/browser_tests/tests/vueNodes/interactions/canvas/pan.spec.ts-snapshots/vue-nodes-paned-with-touch-mobile-chrome-linux.png differ diff --git a/src/locales/en/main.json b/src/locales/en/main.json index e57c994772e..c972366461c 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2218,6 +2218,7 @@ "failedToCreateCustomer": "Failed to create customer: {error}", "failedToInitiateCreditPurchase": "Failed to initiate credit purchase: {error}", "failedToAccessBillingPortal": "Failed to access billing portal: {error}", + "invalidBillingPortalUrl": "The billing portal returned an invalid 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 d852155604f..4446952f75c 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 { Plan } from '@/platform/workspace/api/workspaceApi' @@ -46,6 +46,10 @@ function allPlans(): Plan[] { return [makeStandardYearly(), makeCreatorMonthly()] } +function errorWithCode(code: string, message = 'error') { + return Object.assign(new Error(message), { code }) +} + describe('findPlanSlug', () => { it('finds an annual plan by tier key and yearly billing cycle', () => { expect(findPlanSlug(allPlans(), 'standard', 'yearly')).toBe( @@ -73,6 +77,9 @@ const { mockPreviewSubscribe, mockFetchStatus, mockFetchBalance, + mockOpen, + mockGetBillingStatus, + mockGetPaymentPortalUrl, mockPlans, mockResubscribe, mockToastAdd, @@ -84,6 +91,9 @@ const { mockPreviewSubscribe: 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(), @@ -105,7 +115,11 @@ vi.mock('@/composables/billing/useBillingContext', () => ({ // 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', () => ({ @@ -149,11 +163,26 @@ vi.mock('vue-i18n', async (importOriginal) => { describe('useSubscriptionCheckout', () => { let emit: ReturnType + const scopes: ReturnType[] = [] async function setup(paymentIntentSource?: PaymentIntentSource) { const { useSubscriptionCheckout } = await import('./useSubscriptionCheckout') - return useSubscriptionCheckout(emit as never, paymentIntentSource) + const scope = effectScope() + scopes.push(scope) + return scope.run(() => + useSubscriptionCheckout(emit as never, paymentIntentSource) + )! + } + + 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(() => { @@ -162,9 +191,24 @@ describe('useSubscriptionCheckout', () => { mockPlans.value = allPlans() mockStartOperation.mockResolvedValue({ status: 'succeeded' }) mockUserId.value = 'user-1' + 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) 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() @@ -245,6 +289,81 @@ 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 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(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'warn', + detail: 'subscription.preview.paymentPopupBlocked' + }) + ) + }) + + 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(mockOpen).not.toHaveBeenCalled() + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + detail: 'toastMessages.failedToAccessBillingPortal' + }) + ) + }) + + it('keeps the original error for a non-payment transition failure', async () => { + await submitRejectedPreview( + 'TRANSITION_NOT_ALLOWED', + 'Plan change unavailable' + ) + + expect(mockGetPaymentPortalUrl).not.toHaveBeenCalled() + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ detail: 'Plan change unavailable' }) + ) + }) + it('resolves monthly billing cycle to correct plan slug', async () => { const checkout = await setup() mockPreviewSubscribe.mockResolvedValueOnce({ @@ -351,6 +470,90 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('preview') }) + it('routes a Team preview payment failure to the billing portal', async () => { + const checkout = await setup() + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + + await checkout.handleSubscribeTeamClick({ + stop: { + id: 'team_1400', + usd: 1400, + credits: 295_400, + discountedUsd: 1295 + }, + billingCycle: 'monthly', + isChange: true + }) + + expect(mockOpen).toHaveBeenCalledWith( + 'https://billing.stripe.com/portal', + '_blank' + ) + expect(checkout.checkoutStep.value).toBe('preview') + }) + + it('ignores stale Team recovery after returning to pricing', async () => { + let resolvePortal!: (portal: { url: string }) => void + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + mockGetPaymentPortalUrl.mockImplementationOnce( + () => + new Promise<{ url: string }>((resolve) => { + resolvePortal = resolve + }) + ) + const checkout = await setup() + const selection = checkout.handleSubscribeTeamClick({ + stop: { + id: 'team_1400', + usd: 1400, + credits: 295_400, + discountedUsd: 1295 + }, + billingCycle: 'monthly', + isChange: true + }) + await vi.waitFor(() => expect(mockGetPaymentPortalUrl).toHaveBeenCalled()) + + checkout.handleBackToPricing() + resolvePortal({ url: 'https://billing.stripe.com/portal' }) + await selection + + expect(checkout.checkoutStep.value).toBe('pricing') + expect(mockOpen).not.toHaveBeenCalled() + expect(mockToastAdd).not.toHaveBeenCalled() + }) + + it('returns to pricing when Team payment recovery fails', async () => { + mockPreviewSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + mockGetPaymentPortalUrl.mockRejectedValueOnce( + new Error('Portal unavailable') + ) + const checkout = await setup() + + await checkout.handleSubscribeTeamClick({ + stop: { + id: 'team_1400', + usd: 1400, + credits: 295_400, + discountedUsd: 1295 + }, + billingCycle: 'monthly', + isChange: true + }) + + expect(checkout.checkoutStep.value).toBe('pricing') + expect(checkout.selectedTeamStop.value).toBeNull() + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ detail: 'Portal unavailable' }) + ) + }) + it('does not preview a fresh team subscribe (nothing to prorate)', async () => { const checkout = await setup() @@ -853,6 +1056,23 @@ describe('useSubscriptionCheckout', () => { }) ) }) + + it('routes a payment-required submission to the billing portal', async () => { + const checkout = await setup() + checkout.selectedTierKey.value = 'standard' + checkout.selectedBillingCycle.value = 'yearly' + mockSubscribe.mockRejectedValueOnce( + errorWithCode('SUBSCRIPTION_PAYMENT_REQUIRED') + ) + + await checkout.handleConfirmTransition() + + expect(mockOpen).toHaveBeenCalledWith( + 'https://billing.stripe.com/portal', + '_blank' + ) + expect(mockToastAdd).not.toHaveBeenCalled() + }) }) describe('handleResubscribe', () => { diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index 959d0067b6b..88c044049d2 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' @@ -18,6 +19,7 @@ import type { PreviewSubscribeResponse, SubscribeResponse } from '@/platform/workspace/api/workspaceApi' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { trackWorkspaceCheckoutStarted } from '@/platform/workspace/utils/workspaceCheckoutTelemetry' @@ -42,6 +44,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 + } +} + export function findPlanSlug( plans: Plan[], tierKey: CheckoutTierKey, @@ -82,6 +94,13 @@ export function useSubscriptionCheckout( const previewData = ref(null) const selectedTierKey = ref(null) const selectedTeamCheckout = ref(null) + let teamPreviewRequestId = 0 + let refreshStatusOnFocus = false + useEventListener(window, 'focus', () => { + if (!refreshStatusOnFocus) return + refreshStatusOnFocus = false + void fetchStatus() + }) const selectedBillingCycle = ref('yearly') const isPolling = computed(() => billingOperationStore.hasPendingOperations) const selectedTeamStop = computed( @@ -108,6 +127,62 @@ export function useSubscriptionCheckout( return findPlanSlug(plans.value, tierKey, billingCycle) } + function hasErrorCode(error: unknown, code: string): boolean { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === code + ) + } + + 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 handleSubscribeClick(payload: { tierKey: CheckoutTierKey billingCycle: BillingCycle @@ -143,6 +218,7 @@ export function useSubscriptionCheckout( previewData.value = response checkoutStep.value = 'preview' } catch (error) { + if (await recoverOutstandingPayment(error)) return const message = error instanceof Error ? error.message @@ -170,6 +246,7 @@ export function useSubscriptionCheckout( billingCycle: BillingCycle isChange?: boolean }) { + const previewRequestId = ++teamPreviewRequestId selectedTeamCheckout.value = { stop: payload.stop, checkoutType: payload.isChange ? 'change' : 'new' @@ -186,6 +263,7 @@ export function useSubscriptionCheckout( teamCreditStopId: payload.stop.id, billingCycle: payload.billingCycle }) + if (previewRequestId !== teamPreviewRequestId) return if ( response?.allowed && response.is_immediate && @@ -193,12 +271,17 @@ export function useSubscriptionCheckout( ) { previewData.value = response } - } catch { - // Preview is best-effort; keep the display-only confirm on any failure. + } catch (error) { + const recovery = await recoverOutstandingPayment( + error, + () => previewRequestId === teamPreviewRequestId + ) + if (recovery === 'failed') handleBackToPricing() } } function handleBackToPricing() { + teamPreviewRequestId += 1 checkoutStep.value = 'pricing' previewData.value = null selectedTeamCheckout.value = null @@ -239,6 +322,7 @@ export function useSubscriptionCheckout( } await handleSubscribeResponse(response) } catch (error) { + if (await recoverOutstandingPayment(error)) return showSubscribeError(error) } finally { isSubscribing.value = false @@ -336,6 +420,7 @@ export function useSubscriptionCheckout( } await handleSubscribeResponse(response) } catch (error) { + if (await recoverOutstandingPayment(error)) return showSubscribeError(error) } finally { isSubscribing.value = false