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
36 changes: 36 additions & 0 deletions apps/billing-web/e2e/checkout.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,42 @@ test('submitting payment carries the idempotency key and plan, and settles as su
expect(await fakeStripeCalls(page, 'nextActions')).toBe(0)
})

test('a scheduled plan change confirms against the saved payment method, no card form', async ({
page,
cloud,
signIn
}) => {
cloud.scenario.preview = {
...cloud.scenario.preview,
transition_type: 'duration_change',
is_immediate: false,
cost_today_cents: 0,
amount_due_cents: 0
}
await signIn(CHECKOUT)

await expect(
page.getByRole('button', { name: 'Pay and subscribe' })
).toBeVisible()
await expect(page.getByText('Pro · Monthly')).toBeVisible()

await page.getByRole('button', { name: 'Pay and subscribe' }).click()

await expect(
page.getByRole('heading', { name: "You're all set" })
).toBeVisible()

const subscribe = cloud.requests.find(
(request) => request.path === '/billing/subscribe'
)
expect(subscribe?.body).toMatchObject({ plan_slug: 'pro_monthly' })
expect(subscribe?.body).not.toHaveProperty('confirmation_token')

// The fake only installs itself once the app requests js.stripe.com, so
// its absence proves Stripe.js was never loaded for this path.
expect(await page.evaluate('window.__e2eFakeStripe')).toBeUndefined()
})

test('a declined payment shows the reason and stays on checkout', async ({
page,
cloud,
Expand Down
2 changes: 1 addition & 1 deletion apps/billing-web/e2e/fixtures/scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export function defaultScenario(): CloudScenario {
],
preview: {
allowed: true,
transition_type: 'upgrade',
transition_type: 'new_subscription',
is_immediate: true,
effective_at: new Date().toISOString(),
renewal_at: inAnHour(),
Expand Down
14 changes: 11 additions & 3 deletions apps/billing-web/e2e/subscription.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ test('choosing a plan quotes it from the server and continues to checkout', asyn
cloud,
signIn
}) => {
cloud.scenario.preview = {
...cloud.scenario.preview,
transition_type: 'upgrade'
}
await signIn(SUBSCRIPTION)

await page.getByRole('button', { name: 'Choose Pro · Monthly' }).click()
Expand All @@ -54,11 +58,15 @@ test('choosing a plan quotes it from the server and continues to checkout', asyn
).toBeVisible()
await expect(page.getByText('Pro · Monthly')).toBeVisible()
await expect(page.getByText('Total due today')).toBeVisible()
// An upgrade on an existing subscription charges the saved payment method
// server-side, so no card form is needed here — see checkout.spec.ts for
// that path's full coverage.
await expect(
page.getByText("The payment form isn't available right now.", {
exact: false
})
page.getByRole('button', { name: 'Pay and subscribe' })
).toBeVisible()
await expect(
page.getByText("The payment form isn't available right now.")
).not.toBeVisible()
})

test('a checkout link naming a team credit stop quotes it along with the plan', async ({
Expand Down
80 changes: 80 additions & 0 deletions apps/billing-web/src/components/CheckoutPayment.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<script setup lang="ts">
/**
* The payment step before a subscribe: the Stripe card form when the plan
* needs a new payment method, otherwise just the pay action, which the server
* charges to the saved method on file.
*/
import type { StripePaymentCopy } from '@comfyorg/account-ui/billing/stripe'
import { StripePaymentForm } from '@comfyorg/account-ui/billing/stripe'

import CheckoutSubmit from '@/components/CheckoutSubmit.vue'

const {
needsPaymentMethod,
publishableKey,
amountCents,
currency,
copy,
paymentMethodConfigurationId,
submitting,
canSubmit,
reactivationRequired,
failure
} = defineProps<{
needsPaymentMethod: boolean
publishableKey: string
amountCents: number
currency: string
copy: StripePaymentCopy
paymentMethodConfigurationId: string
submitting: boolean
canSubmit: boolean
reactivationRequired: boolean
failure?: string
}>()

const confirmed = defineModel<boolean>('confirmed', { required: true })

const emit = defineEmits<{
confirm: [confirmationToken?: string]
}>()
</script>

<template>
<StripePaymentForm
v-if="needsPaymentMethod"
:publishable-key="publishableKey"
:amount-cents="amountCents"
:currency="currency"
:copy="copy"
:payment-method-configuration-id="paymentMethodConfigurationId"
:is-loading="submitting"
:can-submit="canSubmit"
@confirm="emit('confirm', $event)"
>
<template #submit="{ disabled, loading }">
<CheckoutSubmit
v-model:confirmed="confirmed"
:amount-cents="amountCents"
:disabled="disabled"
:submitting="loading"
:reactivation-required="reactivationRequired"
:failure="failure"
/>
</template>
</StripePaymentForm>
<form
v-else
class="flex min-h-0 flex-col gap-6 xl:flex-1"
@submit.prevent="emit('confirm')"
>
<CheckoutSubmit
v-model:confirmed="confirmed"
:amount-cents="amountCents"
:disabled="!canSubmit"
:submitting="submitting"
:reactivation-required="reactivationRequired"
:failure="failure"
/>
</form>
</template>
2 changes: 1 addition & 1 deletion apps/billing-web/src/test/fakeBillingClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ export function previewOf(
credits_next_period_cents: 6900,
effective_at: '2026-10-01T00:00:00.000Z',
is_immediate: true,
transition_type: 'upgrade',
transition_type: 'new_subscription',
new_plan: {
credits_cents: 6900,
duration: 'MONTHLY',
Expand Down
43 changes: 42 additions & 1 deletion apps/billing-web/src/views/CheckoutView.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ vi.mock(import('@/session/stripeChallengePort'), () => ({
* The provider form is covered in the package against the real Stripe mocks.
* Here it records what it was handed and lets a test hand back a token.
*/
const formProps = vi.hoisted(() => ({ value: {} as Record<string, unknown> }))
const formProps = vi.hoisted(() => ({
value: {} as Record<string, unknown>,
mounted: false
}))
let reportConfirm: (confirmationToken: string) => void = () => {}

vi.mock<unknown>(import('@comfyorg/account-ui/billing/stripe'), () => ({
Expand All @@ -117,6 +120,7 @@ vi.mock<unknown>(import('@comfyorg/account-ui/billing/stripe'), () => ({
}
) {
formProps.value = props
formProps.mounted = true
reportConfirm = (token) => emit('confirm', token)
return () =>
slots.submit?.({ disabled: !props.canSubmit, loading: props.isLoading })
Expand Down Expand Up @@ -167,6 +171,7 @@ describe('CheckoutView', () => {
beforeEach(() => {
workspace.session = undefined
workspace.bound = undefined
formProps.mounted = false
})

it('quotes the plan the link names and prices the summary from it', async () => {
Expand Down Expand Up @@ -628,6 +633,42 @@ describe('CheckoutView', () => {
)
})

it.for([
['upgrade', true, 2800] as const,
['downgrade', true, 1400] as const,
['duration_change', false, 0] as const
])(
'confirms a %s plan change against the saved payment method, no card form',
async ([transitionType, isImmediate, costTodayCents]) => {
const fake = await renderCheckout(CHECKOUT_PATH, {
preview: {
status: 'ok',
value: previewOf({
transition_type: transitionType,
is_immediate: isImmediate,
cost_today_cents: costTodayCents,
amount_due_cents: costTodayCents
})
}
})
const pay = await screen.findByRole('button', {
name: 'Pay and subscribe'
})
expect(formProps.mounted).toBe(false)

await userEvent.click(pay)

await waitFor(() =>
expect(fake.subscribe).toHaveBeenCalledWith(
expect.objectContaining({ plan_slug: 'creator_monthly' })
)
)
expect(fake.subscribe.mock.calls[0][0]).not.toHaveProperty(
'confirmation_token'
)
}
)

it('explains a quote the server refused and offers the way back', async () => {
await renderCheckout(CHECKOUT_PATH, {
preview: { status: 'error', code: 'NO_ACTIVE_SUBSCRIPTION' }
Expand Down
50 changes: 30 additions & 20 deletions apps/billing-web/src/views/CheckoutView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ import {
usePreviewSubscribe
} from '@comfyorg/account-ui/billing'
import type { StripePaymentCopy } from '@comfyorg/account-ui/billing/stripe'
import { StripePaymentForm } from '@comfyorg/account-ui/billing/stripe'
import {
billingIntentPath,
buildBillingEntryUrl,
buildReturnUrl
} from '@comfyorg/billing-contract'

import CheckoutSubmit from '@/components/CheckoutSubmit.vue'
import CheckoutPayment from '@/components/CheckoutPayment.vue'
import EmbeddedCheckout from '@/components/EmbeddedCheckout.vue'
import HostedSurface from '@/components/HostedSurface.vue'
import { useBilledWorkspace } from '@/composables/useBilledWorkspace'
Expand Down Expand Up @@ -168,6 +167,17 @@ const paymentMethodConfigurationId = computed(
() => preview.value?.payment_method_configuration_id ?? ''
)

/**
* A plan change on an existing subscription charges its saved default
* payment method server-side and never accepts a new one (the ingest
* `subscribeAcceptsSavedMethod` comment in useSubscriptionCheckout.ts states
* this outright); only a genuine new subscription has no saved method yet,
* so only that transition needs the card form.
*/
const needsPaymentMethod = computed(
() => preview.value?.transition_type === 'new_subscription'
)

const publishableKey = computed(() => stripeKey.value ?? '')

const quoting = computed(() => loading.value && summary.value === undefined)
Expand Down Expand Up @@ -210,16 +220,23 @@ function resultUrl(): string | undefined {
return built.status === 'ok' ? built.url.href : undefined
}

/** The quote's identity travels with the charge, so the server prices what the customer saw. */
/**
* The quote's identity travels with the charge, so the server prices what
* the customer saw. A plan change on an existing subscription (see
* `needsPaymentMethod`) has no `confirmationToken` — the server charges the
* saved method on file instead.
*/
function subscribeRequest(
plan: string,
confirmationToken: string,
confirmationToken: string | undefined,
quoted: SubscriptionPreview
): SubscribeInput {
const returnUrl = resultUrl()
return {
plan_slug: plan,
confirmation_token: confirmationToken,
...(confirmationToken === undefined
? {}
: { confirmation_token: confirmationToken }),
...(teamCreditStopId.value === undefined
? {}
: { team_credit_stop_id: teamCreditStopId.value }),
Expand All @@ -235,7 +252,7 @@ function subscribeRequest(
}
}

async function confirm(confirmationToken: string) {
async function confirm(confirmationToken?: string) {
const quoted = preview.value
if (planSlug.value === undefined || !quoted || loading.value) return
submitFailure.value = undefined
Expand Down Expand Up @@ -336,28 +353,21 @@ const subscriptionPath = computed(() => ({
@cancel="checkout.cancel()"
@continue-verification="checkout.continueVerification()"
/>
<StripePaymentForm
<CheckoutPayment
v-else
v-model:confirmed="reactivationConfirmed"
:needs-payment-method="needsPaymentMethod"
:publishable-key="publishableKey"
:amount-cents="amountCents"
:currency="currency"
:copy="paymentCopy"
:payment-method-configuration-id="paymentMethodConfigurationId"
:is-loading="checkout.submitting.value"
:submitting="checkout.submitting.value"
:can-submit="canSubmit"
:reactivation-required="reactivationRequired"
:failure="submitFailure"
@confirm="confirm"
>
<template #submit="{ disabled, loading: submitting }">
<CheckoutSubmit
v-model:confirmed="reactivationConfirmed"
:amount-cents="amountCents"
:disabled="disabled"
:submitting="submitting"
:reactivation-required="reactivationRequired"
:failure="submitFailure"
/>
</template>
</StripePaymentForm>
/>
</template>
<template #done>
<a
Expand Down
7 changes: 6 additions & 1 deletion apps/billing-web/src/views/SubscriptionView.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,12 @@ describe('SubscriptionView', () => {
})

it('quotes the chosen plan and carries it into checkout', async () => {
const fake = await renderSubscription()
const fake = await renderSubscription({
preview: {
status: 'ok',
value: previewOf({ transition_type: 'upgrade' })
}
})

await userEvent.click(
await screen.findByRole('button', { name: 'Choose Creator · Monthly' })
Expand Down
Loading