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
15 changes: 15 additions & 0 deletions packages/account-core/src/core/billing/billingContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BillingFailure, 'serverCode'>
): 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.
Expand Down
7 changes: 6 additions & 1 deletion packages/account-core/src/core/billing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ export type {
BillingSession,
BillingTransport
} from './billingContracts.js'
export { matchesServerCode, unwrapServerCode } from './billingContracts.js'
export {
isPurchaseRefusal,
matchesServerCode,
PURCHASE_REFUSAL_SERVER_CODES,
unwrapServerCode
} from './billingContracts.js'
export type { SessionBillingTransportOptions } from './transport.js'
export { createSessionBillingTransport } from './transport.js'
export type {
Expand Down
26 changes: 26 additions & 0 deletions src/platform/workspace/billing/sdk/topupOperationView.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion src/platform/workspace/billing/sdk/topupOperationView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,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(
Expand Down Expand Up @@ -1769,6 +1787,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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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') }}
</p>
</template>

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

Expand Down Expand Up @@ -410,6 +410,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'
Expand Down Expand Up @@ -587,6 +588,7 @@ watch(suggestedAmount, (amount) => {
const loading = ref(false)
const paymentSubmitted = ref(false)
const checkoutRecovery = ref<'refused' | 'failed' | null>(null)
const checkoutRefusal = ref<string | null>(null)
const blockedDefaultCardUrl = ref<string | null>(null)
const checkoutReopenFailed = ref(false)
const stepBeforeCheckoutBlocked = ref<'confirm' | 'checkoutOpened'>('confirm')
Expand Down Expand Up @@ -1030,6 +1032,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()
Expand Down Expand Up @@ -1060,6 +1063,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
Expand Down Expand Up @@ -1135,7 +1139,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.
Expand Down
Loading