From 5049ca8258587d0ac406673aea233c7f002f0e7f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 28 Oct 2026 08:51:35 -0400 Subject: [PATCH] [backport core/1.59] FE-3647 fix(billing): show the server's message when a top-up is rate limited or purchases are paused (#22072) (cherry picked from commit d669320ec4) --- apps/billing-web/src/checkout/payVerdict.ts | 13 +++-- apps/billing-web/src/checkout/topupRequest.ts | 5 +- .../src/composables/useHostedCopy.ts | 14 +++--- .../src/views/FullPageTopupView.test.ts | 48 +++++++++++++++++++ .../src/core/billing/billingContracts.ts | 15 ++++++ .../account-core/src/core/billing/index.ts | 7 ++- ...TopUpCreditsDialogContentWorkspace.test.ts | 39 +++++++++++++++ .../TopUpCreditsDialogContentWorkspace.vue | 18 ++++++- .../billing/sdk/topupOperationView.test.ts | 26 ++++++++++ .../billing/sdk/topupOperationView.ts | 4 +- 10 files changed, 175 insertions(+), 14 deletions(-) diff --git a/apps/billing-web/src/checkout/payVerdict.ts b/apps/billing-web/src/checkout/payVerdict.ts index 8a886841dfa..8cf057c2990 100644 --- a/apps/billing-web/src/checkout/payVerdict.ts +++ b/apps/billing-web/src/checkout/payVerdict.ts @@ -4,11 +4,14 @@ import type { PaymentProjection, PaymentReasonKey, SubscriptionCommandResult, - TopupResult + TopupResult, + BillingServerCode } from '@comfyorg/account-core/billing' import { + isPurchaseRefusal, matchesServerCode, - projectPaymentStep + projectPaymentStep, + unwrapServerCode } from '@comfyorg/account-core/billing' import type { @@ -68,6 +71,7 @@ export function payVerdictOf(result: SubscriptionCommandResult): PayVerdict { */ function refusalVerdict(result: { readonly code: string + readonly serverCode?: BillingServerCode readonly serverMessage?: string }): PayVerdict { if (result.code === 'OPERATION_ALREADY_PENDING' || result.code === 'CONFLICT') @@ -76,7 +80,10 @@ function refusalVerdict(result: { kind: 'outcome', outcome: { kind: 'processing_error', - code: result.code, + code: + result.serverCode !== undefined && isPurchaseRefusal(result) + ? unwrapServerCode(result.serverCode) + : result.code, ...(result.serverMessage === undefined ? {} : { serverMessage: result.serverMessage }) diff --git a/apps/billing-web/src/checkout/topupRequest.ts b/apps/billing-web/src/checkout/topupRequest.ts index 14a2ffc657a..0c1e6f3714d 100644 --- a/apps/billing-web/src/checkout/topupRequest.ts +++ b/apps/billing-web/src/checkout/topupRequest.ts @@ -2,6 +2,7 @@ import type { InteractiveTopupPayment, TopupResult } from '@comfyorg/account-core/billing' +import { isPurchaseRefusal } from '@comfyorg/account-core/billing' import type { BillingEntry } from '@comfyorg/billing-contract' import { buildBillingEntryUrl } from '@comfyorg/billing-contract' @@ -72,11 +73,13 @@ export function isSamePayment( /** * Whether the server answered this purchase for good, so the next Pay is a * new purchase. A pending, conflicting, rate-limited, unanswered or 5xx - * attempt is resent unchanged under its key. + * attempt is resent unchanged under its key; a purchase the server refuses + * for now is answered. */ export function settlesAttempt(result: TopupResult): boolean { if (result.status === 'ok' || result.status === 'declined') return true if (result.status === 'unsettled') return false + if ('serverCode' in result && isPurchaseRefusal(result)) return true if (!('httpStatus' in result) || result.httpStatus === undefined) return STATUSLESS_ANSWERS.has(result.code) const { httpStatus } = result diff --git a/apps/billing-web/src/composables/useHostedCopy.ts b/apps/billing-web/src/composables/useHostedCopy.ts index 7e06a986160..f8a21846c75 100644 --- a/apps/billing-web/src/composables/useHostedCopy.ts +++ b/apps/billing-web/src/composables/useHostedCopy.ts @@ -1,6 +1,7 @@ import { useI18n } from 'vue-i18n' import type { BillingPlansData } from '@comfyorg/account-core/billing' +import { PURCHASE_REFUSAL_SERVER_CODES } from '@comfyorg/account-core/billing' import { unbrokenDate } from '@/checkout/longDate' @@ -15,9 +16,9 @@ export interface HostedCopy { /** A catalog plan by its tier and duration, never by its slug. */ readonly planName: (plan: CatalogPlan) => string /** - * Copy for a failed billing call. A code that only names the HTTP status - * shows the sentence the server wrote, as the app does; every other code - * keeps billing-web's own copy. + * Copy for a failed billing call. A code that only names the HTTP status, + * or a purchase the server refuses for now, shows the sentence the server + * wrote, as the app does; every other code keeps billing-web's own copy. */ readonly refusal: (failure: RefusedCall) => string readonly date: (isoDate: string) => string @@ -29,9 +30,10 @@ interface RefusedCall { readonly serverMessage?: string } -const STATUS_ONLY_CODES: ReadonlySet = new Set([ +const SERVER_WORDED_CODES: ReadonlySet = new Set([ 'REQUEST_FAILED', - 'CONFLICT' + 'CONFLICT', + ...PURCHASE_REFUSAL_SERVER_CODES ]) export function useHostedCopy(): HostedCopy { @@ -43,7 +45,7 @@ export function useHostedCopy(): HostedCopy { } function refusal({ code, serverMessage }: RefusedCall): string { - return STATUS_ONLY_CODES.has(code) && serverMessage + return SERVER_WORDED_CODES.has(code) && serverMessage ? serverMessage : coded('failure', code) } diff --git a/apps/billing-web/src/views/FullPageTopupView.test.ts b/apps/billing-web/src/views/FullPageTopupView.test.ts index 8e0d4032603..497b5359f4a 100644 --- a/apps/billing-web/src/views/FullPageTopupView.test.ts +++ b/apps/billing-web/src/views/FullPageTopupView.test.ts @@ -14,6 +14,7 @@ import type { TopupResult } from '@comfyorg/account-core/billing' import type { AccountCredential } from '@comfyorg/account-core/session' +import { readBillingErrorCode } from '@comfyorg/account-core/billing' import { BILLING_CLIENT_KEY } from '@comfyorg/account-ui/billing' import { parseBillingEntry } from '@comfyorg/billing-contract' @@ -894,6 +895,53 @@ describe('FullPageTopupView paying once', () => { expect(resent).toStrictEqual(first) }) + it.for([ + { + code: 'TOPUP_RATE_LIMITED', + httpStatus: 429, + message: + 'Too many top-ups in a short time. Try again later or contact support.' + }, + { + code: 'TOPUP_PURCHASES_PAUSED', + httpStatus: 403, + message: + 'Credit purchases are paused right now. Try again later or contact support.' + } + ])( + 'a Pay the server refuses with $code shows its sentence and the next Pay is a new purchase', + async ({ code, httpStatus, message }) => { + const fake = renderTopup({ + topupQuote: PAYS_ONCE, + paymentMethods: { status: 'ok', value: [VISA] } + }) + fake.createInteractiveTopup + .mockResolvedValueOnce({ + status: 'error', + code: httpStatus === 403 ? 'ACCESS_DENIED' : 'REQUEST_FAILED', + httpStatus, + serverCode: readBillingErrorCode({ code, message }), + serverMessage: message + }) + .mockResolvedValueOnce(SUCCEEDED) + await screen.findByText('Add credits · Acme Team') + const recoversBefore = fake.recover.mock.calls.length + + await userEvent.click(payButton()) + + expect(await screen.findByRole('alert')).toHaveTextContent(message) + expect(fake.recover.mock.calls.length).toBe(recoversBefore) + await userEvent.click(payButton()) + await waitFor(() => + expect(fake.createInteractiveTopup).toHaveBeenCalledTimes(2) + ) + const [first, next] = fake.createInteractiveTopup.mock.calls.map( + ([request]) => request + ) + expect(next).not.toStrictEqual(first) + } + ) + it('a Pay blocked by a pending operation follows that operation, never a retry card', async () => { const fake = renderTopup({ topupQuote: PAYS_ONCE, diff --git a/packages/account-core/src/core/billing/billingContracts.ts b/packages/account-core/src/core/billing/billingContracts.ts index 96534283e9e..b9d32e519b6 100644 --- a/packages/account-core/src/core/billing/billingContracts.ts +++ b/packages/account-core/src/core/billing/billingContracts.ts @@ -98,6 +98,21 @@ export function matchesServerCode( return failure.serverCode === code } +/** Server codes for a purchase the server refuses for now; its `serverMessage` is the copy to show. */ +export const PURCHASE_REFUSAL_SERVER_CODES: readonly string[] = [ + 'TOPUP_RATE_LIMITED', + 'TOPUP_PURCHASES_PAUSED' +] + +/** Whether the server refused this purchase for now, with a sentence written for the customer. */ +export function isPurchaseRefusal( + failure: Pick +): boolean { + return PURCHASE_REFUSAL_SERVER_CODES.some((code) => + matchesServerCode(failure, code) + ) +} + /** * The one widening back to `string`, for a host storing the code beside the * codes it already keeps. Rendering it is still a contract violation. diff --git a/packages/account-core/src/core/billing/index.ts b/packages/account-core/src/core/billing/index.ts index 504d32f288d..0f1ca6e3535 100644 --- a/packages/account-core/src/core/billing/index.ts +++ b/packages/account-core/src/core/billing/index.ts @@ -17,7 +17,12 @@ export type { BillingSession, BillingTransport } from './billingContracts' -export { matchesServerCode, unwrapServerCode } from './billingContracts' +export { + isPurchaseRefusal, + matchesServerCode, + PURCHASE_REFUSAL_SERVER_CODES, + unwrapServerCode +} from './billingContracts' export type { SessionBillingTransportOptions } from './transport' export { createSessionBillingTransport } from './transport' export type { diff --git a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts index b43d3958d4c..9853e264902 100644 --- a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -1365,6 +1365,24 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(useDialogStore().closeDialog).not.toHaveBeenCalled() }) + it('shows the sentence the server wrote when it refuses the checkout for now', async () => { + refuseForNoPaymentMethod() + vi.spyOn(workspaceApi, 'createTopupCheckout').mockRejectedValue( + new WorkspaceApiError( + 'Credit purchases are paused right now. Try again later or contact support.', + 403, + 'TOPUP_PURCHASES_PAUSED' + ) + ) + stubCheckoutTab() + + await userEvent.click((await payAndGetRefused()).continueButton) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Credit purchases are paused right now. Try again later or contact support.' + ) + }) + it('keeps the dialog open and explains a checkout that could not start', async () => { refuseForNoPaymentMethod() vi.spyOn(workspaceApi, 'createTopupCheckout').mockRejectedValue( @@ -1811,6 +1829,27 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ) }) + it('shows the sentence the server wrote when it rate-limits the purchase', async () => { + vi.mocked(mockBillingContext().topup).mockRejectedValue( + new WorkspaceApiError( + 'Too many top-ups in a short time. Try again later or contact support.', + 429, + 'TOPUP_RATE_LIMITED' + ) + ) + + renderDialog() + await clickAddCredits() + await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) + + await waitFor(() => + expect(useToast().error).toHaveBeenCalledWith('Purchase Failed', { + description: + 'Too many top-ups in a short time. Try again later or contact support.' + }) + ) + }) + it('returns to amount selection when a reopened operation ends', async () => { setIsAddingCredits(true) setTopupActionOperation({ diff --git a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.vue b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.vue index 14fad75765b..48bccf2e777 100644 --- a/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.vue +++ b/src/platform/billing/components/TopUpCreditsDialogContentWorkspace.vue @@ -76,7 +76,7 @@ role="alert" class="m-0 px-8 pt-4 text-sm text-destructive" > - {{ $t('credits.topUp.checkoutOpenFailed') }} + {{ checkoutRefusal ?? $t('credits.topUp.checkoutOpenFailed') }}

@@ -95,7 +95,7 @@ role="alert" class="m-0 text-sm text-destructive" > - {{ $t('credits.topUp.checkoutOpenFailed') }} + {{ checkoutRefusal ?? $t('credits.topUp.checkoutOpenFailed') }}

@@ -434,6 +434,7 @@ import { BILLING_ACTION_NAME } from '@/platform/telemetry/billingActionNames' import type { BillingOperationTerminal } from '@comfyorg/account-core/billing' import { getTopupAmountPreset, + PURCHASE_REFUSAL_SERVER_CODES, TOPUP_AMOUNT_PRESETS_USD } from '@comfyorg/account-core/billing' import { useToast } from '@/components/ui/toast/toastStore' @@ -630,6 +631,7 @@ watch(suggestedAmount, (amount) => { const loading = ref(false) const paymentSubmitted = ref(false) const checkoutRecovery = ref<'refused' | 'failed' | null>(null) +const checkoutRefusal = ref(null) const blockedDefaultCardUrl = ref(null) const checkoutReopenFailed = ref(false) const stepBeforeCheckoutBlocked = ref<'confirm' | 'checkoutOpened'>('confirm') @@ -1073,6 +1075,7 @@ async function reopenCheckout() { async function openCheckoutInReservedTab(): Promise< 'opened' | 'blocked' | 'failed' | 'abandoned' > { + checkoutRefusal.value = null const returnUrl = topupCheckoutReturnUrl() if (!returnUrl) return 'failed' const checkoutTab = reserveBillingTab() @@ -1103,6 +1106,7 @@ async function openCheckoutInReservedTab(): Promise< } catch (error) { checkoutTab.close() console.error('Hosted top-up checkout failed to open', error) + checkoutRefusal.value = purchaseRefusalMessage(error) return unmounted || scope.signal.aborted ? 'abandoned' : 'failed' } finally { if (checkoutScope === scope) checkoutScope = null @@ -1178,7 +1182,17 @@ function reportTerminal( }) } +function purchaseRefusalMessage(error: unknown): string | null { + return error instanceof WorkspaceApiError && + error.code !== undefined && + PURCHASE_REFUSAL_SERVER_CODES.includes(error.code) + ? error.message + : null +} + function purchaseErrorDetail(error?: unknown): string { + const refusal = purchaseRefusalMessage(error) + if (refusal !== null) return refusal const code = error instanceof WorkspaceApiError ? error.code : undefined // Only one billing operation is open at a time, so this refusal means the // previous purchase has not settled or expired yet — not that anything failed. diff --git a/src/platform/billing/sdk/topupOperationView.test.ts b/src/platform/billing/sdk/topupOperationView.test.ts index 74e551cf21a..910428a5cc8 100644 --- a/src/platform/billing/sdk/topupOperationView.test.ts +++ b/src/platform/billing/sdk/topupOperationView.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' +import { readBillingErrorCode } from '@comfyorg/account-core/billing' + import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { failedTopup, pendingTopup, settledTopup } from './billingSdkTestUtils' @@ -137,6 +139,30 @@ describe('projectTopupResult', () => { ) }) + it('carries the sentence the server wrote for a refused purchase', () => { + expect(() => + projectTopupResult( + { + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 429, + serverCode: readBillingErrorCode({ + code: 'TOPUP_RATE_LIMITED', + message: 'Too many top-ups in a short time.' + }), + serverMessage: 'Too many top-ups in a short time.' + }, + 1000 + ) + ).toThrow( + expect.objectContaining({ + name: 'WorkspaceApiError', + code: 'TOPUP_RATE_LIMITED', + message: 'Too many top-ups in a short time.' + }) + ) + }) + it('carries the HTTP status of a transport failure', () => { let thrown: unknown try { diff --git a/src/platform/billing/sdk/topupOperationView.ts b/src/platform/billing/sdk/topupOperationView.ts index 4284b3b8b9c..dc2611ae8d3 100644 --- a/src/platform/billing/sdk/topupOperationView.ts +++ b/src/platform/billing/sdk/topupOperationView.ts @@ -104,8 +104,10 @@ function topupFailureError( ) } const serverCode = 'serverCode' in failure ? failure.serverCode : undefined + const serverMessage = + 'serverMessage' in failure ? failure.serverMessage : undefined return new WorkspaceApiError( - t('credits.topUp.unknownError'), + serverMessage ?? t('credits.topUp.unknownError'), 'httpStatus' in failure ? failure.httpStatus : undefined, serverCode === undefined ? failure.code : unwrapServerCode(serverCode), topupFailureCategory(failure)