Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { TopUpCreditsDialog } from '@e2e/fixtures/components/TopUpCreditsDialog'
import { TestIds } from '@e2e/fixtures/selectors'
import { workspaceRailAuthFixture as test } from '@e2e/fixtures/workspaceRailAuthFixture'

const CHECKOUT_URL = 'https://checkout.stripe.com/c/pay/cs_test_fe1908'

/**
* Regression coverage for the 1.51 QA finding: with no payment method saved,
* the confirm step claimed "Your saved payment method is charged immediately"
Expand All @@ -32,7 +34,7 @@ test.describe('Top-up without a saved payment method', () => {
return topUpDialog
}

test('offers Manage billing and explains a refused purchase', async ({
test('offers Manage billing and recovers a refused purchase through hosted checkout', async ({
comfyPage
}) => {
const page = comfyPage.page
Expand Down Expand Up @@ -61,9 +63,16 @@ test.describe('Top-up without a saved payment method', () => {
}
})
)
await page.route('**/api/billing/topup/checkout', (route) =>
route.fulfill({ json: { checkout_url: CHECKOUT_URL } })
)
await page
.context()
.route(CHECKOUT_URL, (route) =>
route.fulfill({ contentType: 'text/html', body: 'checkout' })
)

const topUpDialog = await openTopUpDialog(page)

await topUpDialog.root
.getByRole('button', { name: 'Add credits', exact: true })
.click()
Expand All @@ -83,10 +92,25 @@ test.describe('Top-up without a saved payment method', () => {
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/)
topUpDialog.root.getByText(/no card saved for one-click top-ups/)
).toBeVisible()
await expect(comfyPage.toast.toastErrors).toHaveCount(0)

const appUrl = page.url()
const checkoutRequest = page.waitForRequest('**/api/billing/topup/checkout')
const checkoutPage = page.context().waitForEvent('page')
await topUpDialog.root
.getByRole('button', { name: 'Continue to checkout' })
.click()

const checkoutBody = (await checkoutRequest).postDataJSON()
expect(checkoutBody).toMatchObject({ amount_cents: 5000 })
expect(checkoutBody.return_url).toMatch(
/^https:\/\/(test|staging)?billing\.comfy\.org\/return\/topup$/
)
await expect(await checkoutPage).toHaveURL(CHECKOUT_URL)
await expect(page).toHaveURL(appUrl)
await expect(topUpDialog.root).toBeHidden()
})

test('keeps the saved-card note when a payment method is on file', async ({
Expand Down
35 changes: 33 additions & 2 deletions src/composables/auth/useAuthActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ let mockWorkflowStore: ReturnType<typeof useWorkflowStore>
const mockToastErrorHandler = vi.hoisted(() => vi.fn())

const mockStartPendingTopup = vi.hoisted(() => vi.fn())
const mockDistributionState = vi.hoisted(() => ({ isCloud: false }))
const mockClearPendingTopup = vi.hoisted(() => vi.fn())
const mockDistributionState = vi.hoisted(() => ({
isCloud: false,
isDesktop: false
}))
const mockClearAllWorkspaceStorage = vi.hoisted(() => vi.fn())
const mockPrepareWorkflowLogoutTransition = vi.hoisted(() => vi.fn())

Expand Down Expand Up @@ -62,13 +66,19 @@ vi.mock(import('@/platform/auth/sso/ssoRequired'))
vi.mock(import('@/platform/distribution/types'), () => ({
get isCloud() {
return mockDistributionState.isCloud
},
get isDesktop() {
return mockDistributionState.isDesktop
}
}))

vi.mock(import('@/platform/telemetry'))

vi.mock<unknown>(import('@/composables/billing/usePendingTopup'), () => ({
usePendingTopup: () => ({ startPendingTopup: mockStartPendingTopup })
usePendingTopup: () => ({
startPendingTopup: mockStartPendingTopup,
clearPendingTopup: mockClearPendingTopup
})
}))

vi.mock(import('@/platform/workflow/persistence/base/storageIO'), () => ({
Expand Down Expand Up @@ -131,6 +141,7 @@ beforeEach(() => {
vi.mocked(mockAuthStore.register).mockResolvedValue(credential)
vi.mocked(mockAuthStore.loginWithGoogle).mockResolvedValue(credential)
mockDistributionState.isCloud = false
mockDistributionState.isDesktop = false
})

describe('useAuthActions.purchaseCreditsDirect', () => {
Expand Down Expand Up @@ -174,6 +185,26 @@ describe('useAuthActions.purchaseCreditsDirect', () => {
expect(mockStartPendingTopup).not.toHaveBeenCalled()
expect(open).not.toHaveBeenCalled()
})

it('reports a blocked checkout popup on the web', async () => {
vi.spyOn(window, 'open').mockImplementation(() => null)
const { purchaseCreditsDirect } = useAuthActions()

await expect(purchaseCreditsDirect(25)).rejects.toThrow()

expect(mockClearPendingTopup).toHaveBeenCalledOnce()
})

it('keeps tracking the top-up when Desktop hands checkout to the system browser', async () => {
mockDistributionState.isDesktop = true
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
const { purchaseCreditsDirect } = useAuthActions()

await purchaseCreditsDirect(25)

expect(open).toHaveBeenCalledWith('https://checkout.stripe.test', '_blank')
expect(mockClearPendingTopup).not.toHaveBeenCalled()
})
})

describe('useAuthActions.logout', () => {
Expand Down
3 changes: 2 additions & 1 deletion src/composables/auth/useAuthActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import type {
SocialSignInOptions
} from '@/stores/authStore'
import { usdToMicros } from '@/utils/formatUtil'
import { openBillingUrl } from '@/platform/workspace/billing/billingTab'

/**
* The app's own auth.errors table, read through vue-i18n at resolution time.
Expand Down Expand Up @@ -225,7 +226,7 @@ export const useAuthActions = () => {
// refresh on return still fires when telemetry consent is off.
const pendingTopup = usePendingTopup()
pendingTopup.startPendingTopup()
if (!window.open(response.checkout_url, '_blank')) {
if (!openBillingUrl(response.checkout_url)) {
pendingTopup.clearPendingTopup()
throw new PaymentPopupBlockedError(
t('subscription.preview.paymentPopupBlocked')
Expand Down
22 changes: 16 additions & 6 deletions src/composables/billing/topupBalanceRefresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,32 @@ const MAX_SCHEDULED_RUNS = 5

let stopActiveWatch: (() => void) | null = null

interface TopupBalanceSource {
current: () => number | null
fetch: () => Promise<number | null>
}

const customerBalanceSource: TopupBalanceSource = {
current: () => useAuthStore().balance?.amount_micros ?? null,
fetch: async () =>
(await useAuthStore().fetchBalance())?.amount_micros ?? null
}

/**
* Watch for the user returning from a Stripe top-up and refresh the balance.
* Safe to call repeatedly: a new call replaces any watch still pending.
*/
export function watchForTopupBalanceUpdate(): void {
export function watchForTopupBalanceUpdate(
source: TopupBalanceSource = customerBalanceSource
): void {
if (typeof window === 'undefined' || typeof document === 'undefined') return

stopActiveWatch?.()

const authStore = useAuthStore()

// Null until a balance is known: treating "not loaded yet" as 0 would let the
// first read of the *pre-purchase* balance count as the increase we are
// waiting for, stopping the watch on the stale amount.
let baselineMicros: number | null = authStore.balance?.amount_micros ?? null
let baselineMicros: number | null = source.current()

const timeouts = new Set<ReturnType<typeof setTimeout>>()
let stopped = false
Expand Down Expand Up @@ -62,8 +73,7 @@ export function watchForTopupBalanceUpdate(): void {
/** Fetch the balance; true once it has risen above the arming baseline. */
const refresh = async (): Promise<boolean> => {
try {
const balance = await authStore.fetchBalance()
const amountMicros = balance?.amount_micros ?? 0
const amountMicros = (await source.fetch()) ?? 0
if (baselineMicros === null) {
baselineMicros = amountMicros
return false
Expand Down
7 changes: 6 additions & 1 deletion src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -2893,8 +2893,13 @@
"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.",
"noPaymentMethodCheckoutHint": "This workspace has no card saved for one-click top-ups. Pay on a checkout page instead.",
"continueToCheckout": "Continue to checkout",
"checkoutBlockedTitle": "Checkout didn't open",
"checkoutBlockedBody": "Your browser blocked the new tab. Open checkout to finish paying.",
"openCheckout": "Open checkout",
"checkoutOpenFailed": "The payment page couldn't open. Nothing was charged. 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
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ vi.mock(import('@/composables/useErrorHandling'))
vi.mock(import('@/platform/distribution/types'), () => ({
get isCloud() {
return mockIsCloud.value
}
},
isDesktop: false
}))

vi.mock<unknown>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import {
runReportedCheckoutAttempt
} from '@/platform/cloud/subscription/utils/subscriptionCheckoutUtil'
import { useSubscriptionCancellationWatcher } from './useSubscriptionCancellationWatcher'
import { openBillingUrl } from '@/platform/workspace/billing/billingTab'

type CloudSubscriptionCheckoutResponse = NonNullable<
operations['createCloudSubscriptionCheckout']['responses']['201']['content']['application/json']
Expand Down Expand Up @@ -554,7 +555,7 @@ function useSubscriptionInternal() {

if (!response.checkout_url) throw missingCheckoutUrlError()

if (!window.open(response.checkout_url, '_blank')) {
if (!openBillingUrl(response.checkout_url)) {
throw new PaymentPopupBlockedError(
t('subscription.preview.paymentPopupBlocked')
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ vi.mock(import('@/platform/telemetry/reportError'))
vi.mock(import('@/platform/distribution/types'), () => ({
get isCloud() {
return mockIsCloud.value
}
},
isDesktop: false
}))

vi.mock(import('./checkoutAttributionLoader'), () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { AuthStoreError, useAuthStore } from '@/stores/authStore'

import type { BillingCycle } from './subscriptionTierRank'
import { loadCheckoutAttributionModule } from './checkoutAttributionLoader'
import { openBillingUrl } from '@/platform/workspace/billing/billingTab'

type CheckoutTier = TierKey | `${TierKey}-yearly`

Expand Down Expand Up @@ -282,7 +283,7 @@ function completeSubscriptionCheckout(

trackBeginCheckout(context)

if (!window.open(checkoutUrl, '_blank')) {
if (!openBillingUrl(checkoutUrl)) {
throw new PaymentPopupBlockedError(
t('subscription.preview.paymentPopupBlocked')
)
Expand Down
3 changes: 3 additions & 0 deletions src/platform/workspace/api/__mocks__/workspaceApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ export const workspaceApi = vi.mockObject<typeof realWorkspaceApi>(
topup_id: 'op-1',
status: 'completed'
}),
createTopupCheckout: async () => ({
checkout_url: 'https://checkout.stripe.com/c/pay/cs_mock'
}),
getBillingEvents: async () => ({
events: [],
limit: 20,
Expand Down
28 changes: 28 additions & 0 deletions src/platform/workspace/api/workspaceApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import type {
CancelSubscriptionRequest,
CancelSubscriptionResponse,
CreateInviteRequest,
CreateTopupCheckoutRequest,
CreateTopupCheckoutResponse,
CreateTopupRequest,
CreateTopupResponse,
CreateWorkspaceRequest,
Expand Down Expand Up @@ -897,6 +899,32 @@ export const workspaceApi = {
}
},

/**
* Create a Stripe-hosted credit top-up checkout session
* POST /api/billing/topup/checkout
*/
async createTopupCheckout(
amountCents: number,
returnUrl: string
): Promise<CreateTopupCheckoutResponse> {
const auth = await requestAuth()
try {
const response =
await workspaceApiClient.post<CreateTopupCheckoutResponse>(
workspaceApiUrl('/billing/topup/checkout'),
{
amount_cents: amountCents,
return_url: returnUrl,
idempotency_key: crypto.randomUUID()
} satisfies CreateTopupCheckoutRequest,
auth
)
return response.data
} catch (err) {
handleAxiosError(err, 'createTopupCheckout')
}
},

/**
* Get billing events
* GET /api/billing/events
Expand Down
Loading
Loading