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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useAuthStore } from '@/stores/authStore'
import { beforeEach, describe, expect, it, vi } from 'vitest'

import { useTelemetry } from '@/platform/telemetry'
import type { SubscriptionRail } from '@/platform/workspace/billing/sdk/subscriptionOperationView'

const { mockIsCloud, mockSubscribe } = vi.hoisted(() => ({
mockIsCloud: { value: true },
Expand Down Expand Up @@ -31,6 +32,18 @@ vi.mock<unknown>(import('@/platform/workspace/api/workspaceApi'), () => ({
}))
vi.mock(import('@/platform/telemetry'))

const { mockRailSubscribe, railState } = vi.hoisted(() => ({
mockRailSubscribe: vi.fn<SubscriptionRail['subscribe']>(),
railState: { on: false }
}))
vi.mock<unknown>(
import('@/platform/workspace/composables/useSubscriptionRail'),
() => ({
useSubscriptionRail: () =>
railState.on ? { subscribe: mockRailSubscribe } : null
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)

import { performTeamSubscriptionCheckout } from './teamSubscriptionCheckoutUtil'

beforeEach(() => {
Expand All @@ -42,6 +55,7 @@ describe('performTeamSubscriptionCheckout', () => {

beforeEach(() => {
mockIsCloud.value = true
railState.on = false
assignedHref = undefined
Object.defineProperty(globalThis, 'location', {
configurable: true,
Expand Down Expand Up @@ -143,6 +157,78 @@ describe('performTeamSubscriptionCheckout', () => {
})
})

describe('on the subscription rail', () => {
const SUBSCRIBED = {
status: 'subscribed' as const,
billing_op_id: 'op_rail'
}

beforeEach(() => {
railState.on = true
})

it('issues the generated body through the SDK and lands back in the app', async () => {
mockRailSubscribe.mockResolvedValue({
status: 'ok',
value: SUBSCRIBED
})

await performTeamSubscriptionCheckout('team_700', 'yearly', {
paymentIntentSource: 'deep_link'
})

expect(mockRailSubscribe).toHaveBeenCalledWith(
expect.objectContaining({
plan_slug: 'team_per_credit_annual',
team_credit_stop_id: 'team_700',
return_url: 'https://app.test/payment/success',
cancel_url: 'https://app.test/payment/failed'
})
)
expect(mockSubscribe).not.toHaveBeenCalled()
expect(assignedHref).toBe('/')
// The operation id the rail settled is the one the checkout reports.
expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith(
expect.objectContaining({ billing_op_id: 'op_rail' })
)
})

it('runs the legacy call when the SDK route is not deployed', async () => {
mockRailSubscribe.mockResolvedValue({ status: 'unavailable' })
mockSubscribe.mockResolvedValue({
status: 'needs_payment_method',
payment_method_url: 'https://stripe.test/pay',
billing_op_id: 'op_legacy'
})

await performTeamSubscriptionCheckout('team_700', 'yearly')

expect(mockSubscribe).toHaveBeenCalledWith('team_per_credit_annual', {
returnUrl: 'https://app.test/payment/success',
cancelUrl: 'https://app.test/payment/failed',
teamCreditStopId: 'team_700'
})
expect(assignedHref).toBe('https://stripe.test/pay')
})

it('reports a rail refusal as the checkout failure, without a legacy retry', async () => {
mockRailSubscribe.mockResolvedValue({
status: 'error',
error: new Error('card declined')
})

await expect(
performTeamSubscriptionCheckout('team_700', 'yearly')
).rejects.toThrow('card declined')

expect(mockSubscribe).not.toHaveBeenCalled()
expect(assignedHref).toBeUndefined()
expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith(
expect.objectContaining({ stage: 'failed', tier: 'team' })
)
})
})

it('does nothing off cloud', async () => {
mockIsCloud.value = false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { isCloud } from '@/platform/distribution/types'
import { useTelemetry } from '@/platform/telemetry'
import type { PaymentIntentSource } from '@/platform/telemetry/types'
import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory'
import type { SubscribeOptions } from '@/platform/workspace/api/workspaceApi'
import { workspaceApi } from '@/platform/workspace/api/workspaceApi'
import { subscribeInputFrom } from '@/platform/workspace/billing/subscribeInput'
import type { SettledSubscribeResponse } from '@/platform/workspace/billing/sdk/subscriptionOperationView'
import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail'
import { trackWorkspaceCheckoutStarted } from '@/platform/workspace/utils/workspaceCheckoutTelemetry'

import { paymentReturnUrl } from './paymentReturnUrl'
Expand Down Expand Up @@ -57,13 +61,32 @@ export async function performTeamSubscriptionCheckout(
}
}

/**
* The subscribe on whichever rail is on. The SDK settles the operation before
* it returns, so `subscribed` here means the same thing the legacy `pending`
* statuses mean once their poller finishes. `unavailable` is the backend gate
* still closed on these routes — the legacy call runs, as everywhere else.
*/
async function issueTeamSubscribe(
planSlug: string,
options: SubscribeOptions
): Promise<SettledSubscribeResponse> {
const rail = useSubscriptionRail()
if (rail) {
const outcome = await rail.subscribe(subscribeInputFrom(planSlug, options))
if (outcome.status === 'error') throw outcome.error
if (outcome.status === 'ok') return outcome.value
}
return workspaceApi.subscribe(planSlug, options)
}

async function initiateTeamSubscriptionCheckout(
teamCreditStopId: string,
billingCycle: BillingCycle,
options: PerformTeamSubscriptionCheckoutOptions
): Promise<void> {
const planSlug = getTeamPlanSlug(billingCycle)
const response = await workspaceApi.subscribe(planSlug, {
const response = await issueTeamSubscribe(planSlug, {
returnUrl: paymentReturnUrl(),
cancelUrl: `${getComfyPlatformBaseUrl()}/payment/failed`,
teamCreditStopId
Expand Down
37 changes: 37 additions & 0 deletions src/platform/workspace/billing/subscribeInput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* The host's subscribe options as the generated request body, field for field,
* including the two the workspace client drops when they arrive empty: JSON
* keeps `''`, so an empty credential would reach the server as present but
* meaningless.
*
* `SubscribeOptions` carries nothing the generated body lacks. `SubscribeInput`
* also has `checkout_attempt_id` and `idempotency_key`, which no host caller
* sets: the SDK mints the key itself, and the checkout attempt is carried on
* the quote rather than the subscribe.
*
* Shared so the two call sites that issue a subscribe on the rail — the
* workspace billing adapter and the team deep-link checkout — send one body.
*/
import type { SubscribeInput } from '@comfyorg/account-core/billing'

import type { SubscribeOptions } from '@/platform/workspace/api/workspaceApi'

export function subscribeInputFrom(
planSlug: string,
options: SubscribeOptions = {}
): SubscribeInput {
return {
plan_slug: planSlug,
confirmation_token: options.confirmationToken || undefined,
saved_payment_method_id: options.savedPaymentMethodId || undefined,
promotion_code: options.promotionCode,
quote_id: options.quoteId,
quote_version: options.quoteVersion,
return_url: options.returnUrl,
cancel_url: options.cancelUrl,
team_credit_stop_id: options.teamCreditStopId,
billing_cycle: options.billingCycle,
confirm_reactivation: options.confirmReactivation,
proration_at: options.prorationAt
}
}
36 changes: 2 additions & 34 deletions src/platform/workspace/composables/useWorkspaceBilling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ import {
watch
} from 'vue'

import type {
PreviewSubscribeInput,
SubscribeInput
} from '@comfyorg/account-core/billing'
import type { PreviewSubscribeInput } from '@comfyorg/account-core/billing'

import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans'
Expand Down Expand Up @@ -43,6 +40,7 @@ import type { BillingReadRail } from '@/platform/workspace/composables/useBillin
import { useBillingReadRail } from '@/platform/workspace/composables/useBillingReadRail'
import { useSubscriptionRail } from '@/platform/workspace/composables/useSubscriptionRail'
import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore'
import { subscribeInputFrom } from '@/platform/workspace/billing/subscribeInput'
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'

import type {
Expand Down Expand Up @@ -126,36 +124,6 @@ async function resyncQuietly(refresh: () => Promise<unknown>): Promise<void> {
/** The SDK rail refusing an action, distinct from any value it could return. */
const DECLINED = Symbol('subscription rail declined')

/**
* The host's options as the generated request body, field for field, including
* the two the workspace client drops when they arrive empty: JSON keeps `''`,
* so an empty credential would reach the server as present but meaningless.
*
* `SubscribeOptions` carries nothing the generated body lacks. `SubscribeInput`
* also has `checkout_attempt_id` and `idempotency_key`, which no host caller
* sets: the SDK mints the key itself, and the checkout attempt is carried on
* the quote rather than the subscribe.
*/
function subscribeInputFrom(
planSlug: string,
options: SubscribeOptions = {}
): SubscribeInput {
return {
plan_slug: planSlug,
confirmation_token: options.confirmationToken || undefined,
saved_payment_method_id: options.savedPaymentMethodId || undefined,
promotion_code: options.promotionCode,
quote_id: options.quoteId,
quote_version: options.quoteVersion,
return_url: options.returnUrl,
cancel_url: options.cancelUrl,
team_credit_stop_id: options.teamCreditStopId,
billing_cycle: options.billingCycle,
confirm_reactivation: options.confirmReactivation,
proration_at: options.prorationAt
}
}

function previewSubscribeInputFrom(
planSlug: string,
options: PreviewSubscribeOptions = {}
Expand Down
Loading