diff --git a/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts new file mode 100644 index 00000000000..8961c770fb8 --- /dev/null +++ b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts @@ -0,0 +1,125 @@ +import { expect } from '@playwright/test' +import type { Page } from '@playwright/test' + +import type { + PaymentPortalResponse, + SavedPaymentMethod +} from '@comfyorg/ingest-types' + +import { TopUpCreditsDialog } from '@e2e/fixtures/components/TopUpCreditsDialog' +import { TestIds } from '@e2e/fixtures/selectors' +import { workspaceRailAuthFixture as test } from '@e2e/fixtures/workspaceRailAuthFixture' + +/** + * Regression coverage for the 1.51 QA finding: with no payment method saved, + * the confirm step claimed "Your saved payment method is charged immediately" + * and a refused purchase surfaced the raw NO_PAYMENT_METHOD server error with + * no path forward (FE-1908). + * + * Entered through the user popover like a real user: workspace-rail routing + * needs the billing context loaded before the dialog opens, and the popover's + * Add credits button only renders once it is. + */ +test.describe('Top-up without a saved payment method', () => { + async function openTopUpDialog(page: Page) { + const topUpDialog = new TopUpCreditsDialog(page) + await page.getByTestId(TestIds.user.currentUserButton).click() + await page + .getByTestId(TestIds.user.currentUserPopover) + .getByTestId('add-credits-button') + .click() + await expect(topUpDialog.heading).toBeVisible() + return topUpDialog + } + + test('offers Manage billing and explains a refused purchase', async ({ + comfyPage + }) => { + const page = comfyPage.page + await page.route('**/api/billing/payment-methods', (route) => + route.fulfill({ json: [] satisfies SavedPaymentMethod[] }) + ) + await page.route('**/api/billing/payment-portal', (route) => + route.fulfill({ + json: { + url: 'https://billing.example/portal' + } satisfies PaymentPortalResponse + }) + ) + await page + .context() + .route('https://billing.example/**', (route) => + route.fulfill({ contentType: 'text/html', body: 'portal stub' }) + ) + await page.route('**/api/billing/topup', (route) => + route.fulfill({ + status: 400, + json: { + code: 'NO_PAYMENT_METHOD', + message: + 'No default payment method is selected. Please select one in the payment portal.' + } + }) + ) + + const topUpDialog = await openTopUpDialog(page) + + await topUpDialog.root + .getByRole('button', { name: 'Add credits', exact: true }) + .click() + + await expect( + topUpDialog.root.getByText( + "You'll be asked to add a payment method to complete this purchase." + ) + ).toBeVisible() + const [portalPage] = await Promise.all([ + page.context().waitForEvent('page'), + topUpDialog.root.getByRole('button', { name: 'Manage billing' }).click() + ]) + await expect(portalPage).toHaveURL('https://billing.example/portal') + await portalPage.close() + + await topUpDialog.root.getByRole('button', { name: 'Pay $50.00' }).click() + + await expect( + page + .locator('.p-toast-message.p-toast-message-error') + .getByText(/Add one via Settings → Plan & Credits → Manage billing/) + ).toBeVisible() + }) + + test('keeps the saved-card note when a payment method is on file', async ({ + comfyPage + }) => { + const page = comfyPage.page + await page.route('**/api/billing/payment-methods', (route) => + route.fulfill({ + json: [ + { + id: 'pm-1', + type: 'card', + brand: 'visa', + last4: '4242', + is_default: true + } + ] satisfies SavedPaymentMethod[] + }) + ) + + const topUpDialog = await openTopUpDialog(page) + + await topUpDialog.root + .getByRole('button', { name: 'Add credits', exact: true }) + .click() + + await expect( + topUpDialog.root.getByText( + 'Your saved payment method is charged immediately.' + ) + ).toBeVisible() + await expect( + topUpDialog.root.getByRole('button', { name: 'Manage billing' }) + ).toHaveCount(0) + }) +}) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 1774969d2f7..e27692e65ba 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -2687,6 +2687,9 @@ "insufficientWorkflowMessage": "You don't have enough credits to run this workflow.", "creditsDescription": "Credits are used to run workflows or partner nodes.", "chargedImmediatelyNote": "Your saved payment method is charged immediately.", + "paymentDetailsRequiredNote": "You'll be asked to add a payment method to complete this purchase.", + "noPaymentMethodError": "No payment method is saved for this workspace. Add one via Settings → Plan & Credits → Manage billing, then retry the top-up.", + "manageBillingError": "Failed to open the billing portal. Please try again.", "confirmSubtitle": "Credits are added to this workspace as soon as payment completes.", "confirmTitle": "Confirm", "howManyCredits": "How many credits would you like to add?", diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index 5e1c58aa455..1ec9222b7c2 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' import { createI18n } from 'vue-i18n' +import enMessages from '@/locales/en/main.json' with { type: 'json' } + import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' @@ -11,6 +13,12 @@ import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorks const mockFetchBalance = vi.fn() const mockFetchStatus = vi.fn() +const mockManageSubscription = vi.fn<() => Promise>() +const mockReportError = vi.hoisted(() => vi.fn()) + +vi.mock('@/platform/telemetry/reportError', () => ({ + reportError: mockReportError +})) const mockTopup = vi.fn<(amountCents: number) => Promise>() const mockStartOperation = vi.fn() @@ -27,6 +35,23 @@ const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) vi.mock('@/platform/distribution/types', () => mockDistributionTypes) +const mockHasSavedPaymentMethod = vi.hoisted(() => ({ + ref: undefined as { value: boolean | null } | undefined +})) + +vi.mock( + '@/platform/workspace/composables/useHasSavedPaymentMethod', + async () => { + const { ref } = await import('vue') + mockHasSavedPaymentMethod.ref = ref(null) + return { + useHasSavedPaymentMethod: () => ({ + hasSavedPaymentMethod: mockHasSavedPaymentMethod.ref + }) + } + } +) + interface MockTopupOperation { opId: string status: 'pending' | 'reconciliation_needed' @@ -48,6 +73,7 @@ vi.mock('@/composables/billing/useBillingContext', () => ({ useBillingContext: () => ({ fetchBalance: mockFetchBalance, fetchStatus: mockFetchStatus, + manageSubscription: mockManageSubscription, topup: (amountCents: number) => mockTopup(amountCents) }) })) @@ -117,51 +143,7 @@ vi.mock('@/base/credits/comfyCredits', () => ({ const i18n = createI18n({ legacy: false, locale: 'en', - messages: { - en: { - g: { back: 'Back', close: 'Close' }, - subscription: { - addCredits: 'Add credits', - preview: { - completeVerification: 'Complete verification', - totalDueToday: 'Total due today' - } - }, - credits: { - topUp: { - addMoreCredits: 'Add more credits', - addMoreCreditsToRun: 'Add more credits to run', - selectAmount: 'Select amount', - youPay: 'You pay', - youGet: 'You get', - purchaseSuccess: 'Credits added successfully!', - purchaseError: 'Purchase Failed', - purchaseErrorDetail: 'Failed to purchase credits: {error}', - unknownError: 'An unknown error occurred', - minRequired: 'Minimum required', - maxAllowed: 'Maximum allowed', - needMore: 'Need more?', - contactUs: 'Contact us', - viewPricing: 'View pricing', - insufficientWorkflowMessage: 'Insufficient credits', - chargedImmediatelyNote: 'Your saved card is charged immediately.', - confirmSubtitle: - 'Credits are added to this workspace as soon as payment completes.', - confirmTitle: 'Confirm', - payAmount: 'Pay {amount}', - verifyBody: - 'Your bank requires additional verification to complete this payment.', - verifyTitle: 'Verify your payment' - } - }, - billingOperation: { - authenticationFailedDetail: 'Verification failed.', - authenticationManagerRequired: 'Ask a workspace manager for help.', - retryVerification: 'Try verification again', - reconciliationDetail: 'Contact support with operation ID' - } - } - } + messages: { en: enMessages } }) function topupResponse( @@ -209,6 +191,13 @@ function setTopupActionOperation(operation: MockTopupOperation | undefined) { mockBillingOperationState.topupActionOperation.value = operation } +function setHasSavedPaymentMethod(value: boolean | null) { + if (!mockHasSavedPaymentMethod.ref) { + throw new Error('Payment method mock not initialized') + } + mockHasSavedPaymentMethod.ref.value = value +} + async function clickAddCredits() { const user = userEvent.setup() await user.click(screen.getByRole('button', { name: 'Add credits' })) @@ -222,6 +211,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { setTopupActionOperation(undefined) mockFetchBalance.mockResolvedValue(undefined) mockFetchStatus.mockResolvedValue(undefined) + setHasSavedPaymentMethod(true) mockStartOperation.mockImplementation(() => { setIsAddingCredits(true) return new Promise(() => {}) @@ -286,6 +276,93 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(mockTopup).not.toHaveBeenCalled() }) + it('shows the saved-card note when a payment method is on file', async () => { + renderDialog() + + await clickAddCredits() + + expect( + await screen.findByText( + 'Your saved payment method is charged immediately.' + ) + ).toBeInTheDocument() + }) + + it('asks for payment details when no payment method is saved', async () => { + setHasSavedPaymentMethod(false) + + renderDialog() + await clickAddCredits() + + expect( + await screen.findByText( + "You'll be asked to add a payment method to complete this purchase." + ) + ).toBeInTheDocument() + }) + + it('opens the billing portal from the no-payment-method note', async () => { + setHasSavedPaymentMethod(false) + mockManageSubscription.mockResolvedValue(undefined) + + renderDialog() + await clickAddCredits() + + await userEvent.click( + await screen.findByRole('button', { name: 'Manage billing' }) + ) + + expect(mockManageSubscription).toHaveBeenCalledTimes(1) + }) + + it('reports and surfaces a billing-portal opening failure', async () => { + setHasSavedPaymentMethod(false) + const failure = new Error('portal down') + mockManageSubscription.mockRejectedValue(failure) + + renderDialog() + await clickAddCredits() + + await userEvent.click( + await screen.findByRole('button', { name: 'Manage billing' }) + ) + + await waitFor(() => + expect(mockReportError).toHaveBeenCalledWith(failure, { + errorType: 'billing_portal_open_failure' + }) + ) + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + summary: 'Failed to open the billing portal. Please try again.' + }) + ) + }) + + it('explains how to add a payment method when the purchase is refused', async () => { + setHasSavedPaymentMethod(false) + mockTopup.mockRejectedValue( + new WorkspaceApiError( + 'No default payment method is selected.', + 400, + 'NO_PAYMENT_METHOD' + ) + ) + + renderDialog() + await clickAddCredits() + await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + + await waitFor(() => + expect(mockToastAdd).toHaveBeenCalledWith( + expect.objectContaining({ + detail: + 'No payment method is saved for this workspace. Add one via Settings → Plan & Credits → Manage billing, then retry the top-up.' + }) + ) + ) + }) + it('allows returning to amount selection before payment', async () => { renderDialog() await clickAddCredits() @@ -389,7 +466,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { screen.getByText('Your bank rejected the verification.') ).toBeInTheDocument() await userEvent.click( - screen.getByRole('button', { name: 'Try verification again' }) + screen.getByRole('button', { name: 'Retry verification' }) ) expect(mockRetryPaymentAuthentication).toHaveBeenCalledWith('op-retry') }) @@ -404,7 +481,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { renderDialog() expect( - screen.getByText('Contact support with operation ID') + screen.getByText(/Contact support and include this operation ID/) ).toBeInTheDocument() expect(screen.getByText('op-reconcile')).toBeInTheDocument() expect( diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue index c6ce2593618..cb03419f815 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue @@ -65,8 +65,18 @@ {{ displayTotal }} -

- {{ $t('credits.topUp.chargedImmediatelyNote') }} +

+ {{ paymentNote }} +

@@ -280,7 +290,10 @@ import { isCloud } from '@/platform/distribution/types' import { clearTopupTracking } from '@/platform/telemetry/topupTracker' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' +import { reportError } from '@/platform/telemetry/reportError' +import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useHasSavedPaymentMethod } from '@/platform/workspace/composables/useHasSavedPaymentMethod' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useDialogStore } from '@/stores/dialogStore' import { cn } from '@comfyorg/tailwind-utils' @@ -295,7 +308,8 @@ const settingsDialog = useSettingsDialog() const telemetry = useTelemetry() const toast = useToast() const { buildDocsUrl, docsPaths } = useExternalLink() -const { fetchBalance, fetchStatus, topup } = useBillingContext() +const { fetchBalance, fetchStatus, manageSubscription, topup } = + useBillingContext() const { canTopUp } = useBillingCapabilities() const billingOperationStore = useBillingOperationStore() @@ -334,11 +348,19 @@ const step = ref<'amount' | 'confirm' | 'verifying'>( topupOperation.value && canTopUp.value ? 'verifying' : 'amount' ) +const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + // Computed const pricingUrl = computed(() => buildDocsUrl(docsPaths.partnerNodesPricing, { includeLocale: true }) ) +const paymentNote = computed(() => + hasSavedPaymentMethod.value + ? t('credits.topUp.chargedImmediatelyNote') + : t('credits.topUp.paymentDetailsRequiredNote') +) + const creditsModel = computed({ get: () => usdToCredits(payAmount.value), set: (newCredits: number) => { @@ -424,6 +446,17 @@ function handlePrimaryAction() { void handleBuy() } +function openManageBilling() { + void manageSubscription().catch((error) => { + reportError(error, { errorType: 'billing_portal_open_failure' }) + toast.add({ + severity: 'error', + summary: t('credits.topUp.manageBillingError'), + life: 5000 + }) + }) +} + function openTopupVerification() { if (!topupActionUrl.value) return window.open(topupActionUrl.value, '_blank', 'noopener,noreferrer') @@ -582,13 +615,19 @@ function reportPurchaseError( error === undefined ? 'unknown' : categorizeBillingApiError(error), duration_ms: Date.now() - attemptStartedAt }) + const missingPaymentMethod = + error instanceof WorkspaceApiError && error.code === 'NO_PAYMENT_METHOD' toast.add({ severity: 'error', summary: t('credits.topUp.purchaseError'), - detail: t('credits.topUp.purchaseErrorDetail', { - error: - error instanceof Error ? error.message : t('credits.topUp.unknownError') - }) + detail: missingPaymentMethod + ? t('credits.topUp.noPaymentMethodError') + : t('credits.topUp.purchaseErrorDetail', { + error: + error instanceof Error + ? error.message + : t('credits.topUp.unknownError') + }) }) } diff --git a/src/platform/workspace/composables/useHasSavedPaymentMethod.test.ts b/src/platform/workspace/composables/useHasSavedPaymentMethod.test.ts new file mode 100644 index 00000000000..ff1e20590cc --- /dev/null +++ b/src/platform/workspace/composables/useHasSavedPaymentMethod.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' + +import type { reportError } from '@/platform/telemetry/reportError' +import type { SavedPaymentMethod } from '@/platform/workspace/api/workspaceApi' + +import { useHasSavedPaymentMethod } from './useHasSavedPaymentMethod' + +const mockListSavedPaymentMethods = vi.hoisted(() => + vi.fn<() => Promise>() +) +const mockReportError = vi.hoisted(() => vi.fn()) + +vi.mock('@/platform/workspace/api/workspaceApi', () => ({ + workspaceApi: { + listSavedPaymentMethods: mockListSavedPaymentMethods + } +})) + +vi.mock('@/platform/telemetry/reportError', () => ({ + reportError: mockReportError +})) + +async function flushLookup() { + await Promise.resolve() + await Promise.resolve() + await nextTick() +} + +describe('useHasSavedPaymentMethod', () => { + it('starts unknown before the lookup resolves', () => { + mockListSavedPaymentMethods.mockResolvedValue([]) + + const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + + expect(hasSavedPaymentMethod.value).toBeNull() + }) + + it('resolves true when a payment method is on file', async () => { + mockListSavedPaymentMethods.mockResolvedValue([ + { id: 'pm-1', type: 'card', is_default: true } + ]) + + const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + await flushLookup() + + expect(hasSavedPaymentMethod.value).toBe(true) + }) + + it('resolves false when only non-default methods are saved', async () => { + mockListSavedPaymentMethods.mockResolvedValue([ + { id: 'pm-1', type: 'card', is_default: false } + ]) + + const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + await flushLookup() + + expect(hasSavedPaymentMethod.value).toBe(false) + }) + + it('resolves false when no payment methods are saved', async () => { + mockListSavedPaymentMethods.mockResolvedValue([]) + + const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + await flushLookup() + + expect(hasSavedPaymentMethod.value).toBe(false) + }) + + it('stays unknown and reports when the lookup fails', async () => { + const failure = new Error('network') + mockListSavedPaymentMethods.mockRejectedValue(failure) + + const { hasSavedPaymentMethod } = useHasSavedPaymentMethod() + await flushLookup() + + expect(hasSavedPaymentMethod.value).toBeNull() + expect(mockReportError).toHaveBeenCalledWith(failure, { + errorType: 'saved_payment_methods_read_failure' + }) + }) +}) diff --git a/src/platform/workspace/composables/useHasSavedPaymentMethod.ts b/src/platform/workspace/composables/useHasSavedPaymentMethod.ts new file mode 100644 index 00000000000..2f904cecdc6 --- /dev/null +++ b/src/platform/workspace/composables/useHasSavedPaymentMethod.ts @@ -0,0 +1,30 @@ +import { useAsyncState } from '@vueuse/core' +import { computed } from 'vue' + +import { reportError } from '@/platform/telemetry/reportError' +import { workspaceApi } from '@/platform/workspace/api/workspaceApi' + +/** + * Reports whether the active workspace has a usable (default) saved payment + * method — the same predicate the top-up endpoint enforces. It is `null` + * until the lookup resolves, and stays `null` when it fails so callers can + * withhold payment-method claims instead of asserting one. + */ +export function useHasSavedPaymentMethod() { + const { state, error, isLoading, isReady, execute } = useAsyncState( + () => workspaceApi.listSavedPaymentMethods(), + null, + { + onError: (lookupError) => + reportError(lookupError, { + errorType: 'saved_payment_methods_read_failure' + }) + } + ) + const hasSavedPaymentMethod = computed(() => + state.value === null + ? null + : state.value.some((method) => method.is_default) + ) + return { hasSavedPaymentMethod, error, isLoading, isReady, refresh: execute } +}