Skip to content
125 changes: 125 additions & 0 deletions browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
3 changes: 3 additions & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -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?",
Expand Down

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we want to use i18n dict rather than raw strings?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — importing the real en dict into the test fixture also permanently kills the locale-drift problem CodeRabbit flagged. Taking it in the FE-1908 follow-up together with the composable refactor so this fix can ride the 1.51 backport now.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in dd0a851 — the test now renders the production en dict (import with { type: json }), so any copy drift fails the test directly. Dropped the 70-line hand-written fixture.

Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ 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'

import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorkspace.vue'

const mockFetchBalance = vi.fn()
const mockFetchStatus = vi.fn()
const mockManageSubscription = vi.fn<() => Promise<void>>()
const mockReportError = vi.hoisted(() => vi.fn())

vi.mock('@/platform/telemetry/reportError', () => ({
reportError: mockReportError
}))
const mockTopup =
vi.fn<(amountCents: number) => Promise<CreateTopupResponse | void>>()
const mockStartOperation = vi.fn()
Expand All @@ -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<boolean | null>(null)
return {
useHasSavedPaymentMethod: () => ({
hasSavedPaymentMethod: mockHasSavedPaymentMethod.ref
})
}
}
)

interface MockTopupOperation {
opId: string
status: 'pending' | 'reconciliation_needed'
Expand All @@ -48,6 +73,7 @@ vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: () => ({
fetchBalance: mockFetchBalance,
fetchStatus: mockFetchStatus,
manageSubscription: mockManageSubscription,
topup: (amountCents: number) => mockTopup(amountCents)
})
}))
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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' }))
Expand All @@ -222,6 +211,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => {
setTopupActionOperation(undefined)
mockFetchBalance.mockResolvedValue(undefined)
mockFetchStatus.mockResolvedValue(undefined)
setHasSavedPaymentMethod(true)
mockStartOperation.mockImplementation(() => {
setIsAddingCredits(true)
return new Promise(() => {})
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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')
})
Expand All @@ -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(
Expand Down
Loading
Loading