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
13 changes: 10 additions & 3 deletions apps/billing-web/src/checkout/payVerdict.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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')
Expand All @@ -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 })
Expand Down
5 changes: 4 additions & 1 deletion apps/billing-web/src/checkout/topupRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
Expand Down
14 changes: 8 additions & 6 deletions apps/billing-web/src/composables/useHostedCopy.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -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
Expand All @@ -29,9 +30,10 @@ interface RefusedCall {
readonly serverMessage?: string
}

const STATUS_ONLY_CODES: ReadonlySet<string> = new Set([
const SERVER_WORDED_CODES: ReadonlySet<string> = new Set([
'REQUEST_FAILED',
'CONFLICT'
'CONFLICT',
...PURCHASE_REFUSAL_SERVER_CODES
])

export function useHostedCopy(): HostedCopy {
Expand All @@ -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)
}
Expand Down
48 changes: 48 additions & 0 deletions apps/billing-web/src/views/FullPageTopupView.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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,
Expand Down
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'
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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({
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 @@ -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'
Expand Down Expand Up @@ -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<string | null>(null)
const blockedDefaultCardUrl = ref<string | null>(null)
const checkoutReopenFailed = ref(false)
const stepBeforeCheckoutBlocked = ref<'confirm' | 'checkoutOpened'>('confirm')
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions src/platform/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/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
Loading