From 8acb684ce0510dedf0f3caf0d7d0cb1c795ce08c Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Mon, 28 Sep 2026 14:53:30 -0400 Subject: [PATCH 1/2] feat(billing-web): re-reconcile the full-page checkout on bfcache restore and on a sibling tab's payment A page restored from the back-forward cache re-reads the live operation on pageshow. Tabs on the same checkout share an operation channel scoped to the user and workspace (BroadcastChannel, or the storage event where it is missing): this page's own Pay announces its operation starting and settling, and a sibling that hears it re-reads the server for itself. A notice is a nudge, never state. --- .../e2e/full-page-cross-tab.spec.ts | 112 +++++++++++ .../src/checkout/operationChannel.test.ts | 177 ++++++++++++++++++ .../src/checkout/operationChannel.ts | 149 +++++++++++++++ .../src/composables/useFullPageCheckout.ts | 38 ++++ .../src/views/FullPageCheckoutView.test.ts | 177 +++++++++++++++++- .../src/views/FullPageCheckoutView.vue | 10 +- 6 files changed, 661 insertions(+), 2 deletions(-) create mode 100644 apps/billing-web/e2e/full-page-cross-tab.spec.ts create mode 100644 apps/billing-web/src/checkout/operationChannel.test.ts create mode 100644 apps/billing-web/src/checkout/operationChannel.ts diff --git a/apps/billing-web/e2e/full-page-cross-tab.spec.ts b/apps/billing-web/e2e/full-page-cross-tab.spec.ts new file mode 100644 index 00000000000..2dabe30090e --- /dev/null +++ b/apps/billing-web/e2e/full-page-cross-tab.spec.ts @@ -0,0 +1,112 @@ +/** + * The full-page checkout after the page it rendered is no longer the truth: + * a sibling tab paid, or the page came back from the back-forward cache. Both + * re-read the server rather than trusting what they last rendered. + * + * Playwright's Chromium disables the back-forward cache, so the restore is + * modelled by dispatching `pageshow` with `persisted: true`, the event the + * browser fires on a real restore. + */ +import type { Page } from '@playwright/test' + +import type { MockCloud } from './fixtures/cloud' +import { pendingOperation } from './fixtures/scenario' +import { installFakeStripe } from './fixtures/stripe' +import { entryPath, expect, test as base } from './fixtures/test' + +const test = base.extend<{ fullPage: void }>({ + fullPage: [ + async ({ context, cloud }, use) => { + await installFakeStripe(context) + cloud.scenario.checkoutUi = 'full_page' + cloud.scenario.preview = { + ...cloud.scenario.preview, + payment_method_configuration_id: 'pmc_e2e' + } + await use(undefined) + }, + { auto: true } + ] +}) + +const CHECKOUT = entryPath('checkout', { plan: 'pro_monthly' }) +const WAITING = 'Finishing your payment…' + +const payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const waiting = (page: Page) => page.getByRole('status') + +/** The server reports the operation pending once a subscribe has been issued. */ +function pendingAfterSubscribe(cloud: MockCloud, id: string) { + cloud.reply('GET', '/billing/status', () => ({ + body: cloud.requests.some( + (request) => request.path === '/billing/subscribe' + ) + ? { + ...cloud.scenario.status, + pending_billing_op_id: id, + pending_billing_op_type: 'subscription' + } + : cloud.scenario.status + })) +} + +test('a Pay in one tab takes a sibling tab on the same checkout to the waiting state without any interaction', async ({ + page, + context, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + pendingAfterSubscribe(cloud, 'op_subscribe') + cloud.scenario.operations.op_subscribe = pendingOperation('op_subscribe') + await signIn(CHECKOUT) + // The same signed-in identity, so the sibling lands on the checkout directly. + const sibling = await context.newPage() + await sibling.goto(CHECKOUT) + await expect(sibling).toHaveURL(CHECKOUT) + await expect(payButton(sibling)).toBeEnabled() + const statusReadsBefore = cloud.requests.filter( + (request) => request.path === '/billing/status' + ).length + + await payButton(page).click() + + await expect(waiting(sibling)).toHaveText(WAITING) + await expect(payButton(sibling)).toBeHidden() + expect( + cloud.requests.filter((request) => request.path === '/billing/status') + .length + ).toBeGreaterThan(statusReadsBefore) + expect( + cloud.requests.filter((request) => request.path === '/billing/subscribe') + ).toHaveLength(1) +}) + +test('a page restored from the back-forward cache re-reads the operation instead of showing the form it left with', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + await signIn(CHECKOUT) + await expect(payButton(page)).toBeEnabled() + + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: 'op_meanwhile', + pending_billing_op_type: 'subscription' + } + cloud.scenario.operations.op_meanwhile = pendingOperation('op_meanwhile') + await page.evaluate(() => { + const event = new Event('pageshow') + Object.defineProperty(event, 'persisted', { value: true }) + window.dispatchEvent(event) + }) + + await expect(waiting(page)).toHaveText(WAITING) + await expect(payButton(page)).toBeHidden() + expect( + cloud.requests.filter((request) => request.path === '/billing/subscribe') + ).toHaveLength(0) +}) diff --git a/apps/billing-web/src/checkout/operationChannel.test.ts b/apps/billing-web/src/checkout/operationChannel.test.ts new file mode 100644 index 00000000000..3040f3650c3 --- /dev/null +++ b/apps/billing-web/src/checkout/operationChannel.test.ts @@ -0,0 +1,177 @@ +import type { OperationNotice } from '@/checkout/operationChannel' +import { + createOperationChannel, + operationChannelName +} from '@/checkout/operationChannel' + +/** An in-memory BroadcastChannel: every other instance on the same name hears a post. */ +class FakeBroadcastChannel extends EventTarget { + static readonly open = new Set() + constructor(readonly name: string) { + super() + FakeBroadcastChannel.open.add(this) + } + postMessage(data: unknown) { + for (const other of FakeBroadcastChannel.open) { + if (other !== this && other.name === this.name) + other.dispatchEvent(new MessageEvent('message', { data })) + } + } + close() { + FakeBroadcastChannel.open.delete(this) + } +} + +const NOTICE: OperationNotice = { + workspaceId: 'ws-1', + operationId: 'op_1', + kind: 'started' +} + +const FOREIGN: readonly { name: string; value: unknown }[] = [ + { name: 'another workspace', value: { ...NOTICE, workspaceId: 'ws-2' } }, + { name: 'an unknown kind', value: { ...NOTICE, kind: 'exploded' } }, + { name: 'no operation id', value: { workspaceId: 'ws-1', kind: 'started' } }, + { name: 'a string', value: 'started' }, + { name: 'null', value: null } +] + +describe('createOperationChannel over BroadcastChannel', () => { + beforeEach(() => { + vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel) + }) + afterEach(() => { + FakeBroadcastChannel.open.clear() + }) + + it("delivers a sibling tab's notice for the same user and workspace, never its own", () => { + const publisher = createOperationChannel('uid-1', 'ws-1') + const sibling = createOperationChannel('uid-1', 'ws-1') + const heardByPublisher = vi.fn() + const heardBySibling = vi.fn() + publisher?.subscribe(heardByPublisher) + sibling?.subscribe(heardBySibling) + + publisher?.publish(NOTICE) + + expect(heardBySibling).toHaveBeenCalledExactlyOnceWith(NOTICE) + expect(heardByPublisher).not.toHaveBeenCalled() + }) + + it.for([ + { name: 'user', uid: 'uid-2', workspaceId: 'ws-1' }, + { name: 'workspace', uid: 'uid-1', workspaceId: 'ws-9' } + ])('stays silent to a tab on another $name', ({ uid, workspaceId }) => { + const publisher = createOperationChannel('uid-1', 'ws-1') + const elsewhere = createOperationChannel(uid, workspaceId) + const heard = vi.fn() + elsewhere?.subscribe(heard) + + publisher?.publish(NOTICE) + + expect(heard).not.toHaveBeenCalled() + }) + + it.for(FOREIGN)('drops $name arriving on the channel', ({ value }) => { + const sibling = createOperationChannel('uid-1', 'ws-1') + const heard = vi.fn() + sibling?.subscribe(heard) + + new FakeBroadcastChannel(operationChannelName('uid-1', 'ws-1')).postMessage( + value + ) + + expect(heard).not.toHaveBeenCalled() + }) + + it('stops delivering once unsubscribed or closed', () => { + const publisher = createOperationChannel('uid-1', 'ws-1') + const sibling = createOperationChannel('uid-1', 'ws-1') + const unsubscribed = vi.fn() + const closed = vi.fn() + sibling?.subscribe(unsubscribed)() + const another = createOperationChannel('uid-1', 'ws-1') + another?.subscribe(closed) + another?.close() + + publisher?.publish(NOTICE) + + expect(unsubscribed).not.toHaveBeenCalled() + expect(closed).not.toHaveBeenCalled() + }) +}) + +describe('createOperationChannel over the storage event', () => { + beforeEach(() => { + vi.stubGlobal('BroadcastChannel', undefined) + localStorage.clear() + }) + + function arrive(key: string, newValue: string | null) { + window.dispatchEvent(new StorageEvent('storage', { key, newValue })) + } + + it('writes a stamped notice under the scoped key, so every publish fires the event', () => { + const channel = createOperationChannel('uid-1', 'ws-1') + + channel?.publish(NOTICE) + const first = localStorage.getItem(operationChannelName('uid-1', 'ws-1')) + channel?.publish(NOTICE) + const second = localStorage.getItem(operationChannelName('uid-1', 'ws-1')) + + expect(JSON.parse(first ?? '{}')).toMatchObject(NOTICE) + expect(first).not.toBe(second) + }) + + it('delivers a notice another tab wrote under the scoped key', () => { + const channel = createOperationChannel('uid-1', 'ws-1') + const heard = vi.fn() + channel?.subscribe(heard) + + arrive(operationChannelName('uid-1', 'ws-1'), JSON.stringify(NOTICE)) + + expect(heard).toHaveBeenCalledExactlyOnceWith(NOTICE) + }) + + it.for([ + { + name: 'another key', + key: 'comfy:billing:op:uid-1:ws-2', + value: JSON.stringify(NOTICE) + }, + { + name: 'a removal', + key: operationChannelName('uid-1', 'ws-1'), + value: null + }, + { + name: 'unparseable text', + key: operationChannelName('uid-1', 'ws-1'), + value: '{not json' + }, + ...FOREIGN.map(({ name, value }) => ({ + name, + key: operationChannelName('uid-1', 'ws-1'), + value: JSON.stringify(value) + })) + ])('drops $name', ({ key, value }) => { + const channel = createOperationChannel('uid-1', 'ws-1') + const heard = vi.fn() + channel?.subscribe(heard) + + arrive(key, value) + + expect(heard).not.toHaveBeenCalled() + }) + + it('stops delivering once closed', () => { + const channel = createOperationChannel('uid-1', 'ws-1') + const heard = vi.fn() + channel?.subscribe(heard) + channel?.close() + + arrive(operationChannelName('uid-1', 'ws-1'), JSON.stringify(NOTICE)) + + expect(heard).not.toHaveBeenCalled() + }) +}) diff --git a/apps/billing-web/src/checkout/operationChannel.ts b/apps/billing-web/src/checkout/operationChannel.ts new file mode 100644 index 00000000000..e46838255f6 --- /dev/null +++ b/apps/billing-web/src/checkout/operationChannel.ts @@ -0,0 +1,149 @@ +/** + * How sibling tabs on the same checkout hear that an operation started or + * settled. A notice is a nudge, never state: a tab that receives one re-reads + * the server, so a forged or stale notice can at worst cost a read. The + * channel is scoped to one signed-in user and one workspace, like the + * operation pointer, and a notice for any other workspace is dropped. + * + * BroadcastChannel where the browser has it; otherwise the `storage` event on + * a localStorage key, which also fires only in other tabs. Feature detection + * follows `crossTabRefresh.ts`: a present API can still refuse construction, + * so it is probed once and the fallback used whenever it does. + */ +export interface OperationNotice { + readonly workspaceId: string + readonly operationId: string + readonly kind: 'started' | 'settled' +} + +export interface OperationChannel { + readonly publish: (notice: OperationNotice) => void + /** Hands over a sibling's notice for this workspace; returns the unsubscribe. */ + readonly subscribe: ( + listener: (notice: OperationNotice) => void + ) => () => void + readonly close: () => void +} + +export function operationChannelName(uid: string, workspaceId: string): string { + return `comfy:billing:op:${uid}:${workspaceId}` +} + +const NOTICE_KIND: Readonly> = { + started: true, + settled: true +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function isNotice(value: unknown): value is OperationNotice { + if (!isRecord(value)) return false + return ( + typeof value.workspaceId === 'string' && + typeof value.operationId === 'string' && + Object.hasOwn(NOTICE_KIND, String(value.kind)) + ) +} + +/** Only a notice for the workspace this channel is scoped to reaches the listener. */ +function scopedListener( + workspaceId: string, + listener: (notice: OperationNotice) => void +): (value: unknown) => void { + return (value) => { + if (isNotice(value) && value.workspaceId === workspaceId) listener(value) + } +} + +function broadcastChannelAvailable(): boolean { + if (typeof BroadcastChannel === 'undefined') return false + try { + new BroadcastChannel('@comfyorg/billing-web op-channel probe').close() + return true + } catch { + return false + } +} + +function broadcastChannelOf( + name: string, + workspaceId: string +): OperationChannel { + const channel = new BroadcastChannel(name) + return { + publish: (notice) => channel.postMessage(notice), + subscribe: (listener) => { + const scoped = scopedListener(workspaceId, listener) + const handler = (event: MessageEvent) => scoped(event.data) + channel.addEventListener('message', handler) + return () => channel.removeEventListener('message', handler) + }, + close: () => channel.close() + } +} + +function parsed(value: string): unknown { + try { + return JSON.parse(value) + } catch { + return undefined + } +} + +function storageChannelOf( + name: string, + workspaceId: string, + storage: Storage, + target: Window +): OperationChannel { + const handlers = new Set<(event: StorageEvent) => void>() + return { + publish: (notice) => { + // The event fires only when the value changes, so each notice is stamped. + storage.setItem( + name, + JSON.stringify({ ...notice, at: Date.now(), nonce: Math.random() }) + ) + }, + subscribe: (listener) => { + const scoped = scopedListener(workspaceId, listener) + const handler = (event: StorageEvent) => { + if (event.key === name && event.newValue !== null) + scoped(parsed(event.newValue)) + } + handlers.add(handler) + target.addEventListener('storage', handler) + return () => { + handlers.delete(handler) + target.removeEventListener('storage', handler) + } + }, + close: () => { + for (const handler of handlers) + target.removeEventListener('storage', handler) + handlers.clear() + } + } +} + +function localStorageOf(): Storage | undefined { + try { + return globalThis.localStorage + } catch { + return undefined + } +} + +/** Undefined where neither transport exists, such as a non-browser environment. */ +export function createOperationChannel( + uid: string, + workspaceId: string +): OperationChannel | undefined { + const name = operationChannelName(uid, workspaceId) + if (broadcastChannelAvailable()) return broadcastChannelOf(name, workspaceId) + const storage = localStorageOf() + if (storage === undefined || typeof window === 'undefined') return undefined + return storageChannelOf(name, workspaceId, storage, window) +} diff --git a/apps/billing-web/src/composables/useFullPageCheckout.ts b/apps/billing-web/src/composables/useFullPageCheckout.ts index b9165cdbdd5..f7bf96c845e 100644 --- a/apps/billing-web/src/composables/useFullPageCheckout.ts +++ b/apps/billing-web/src/composables/useFullPageCheckout.ts @@ -1,3 +1,4 @@ +import { tryOnScopeDispose } from '@vueuse/core' import { computed, shallowReadonly, shallowRef, watch } from 'vue' import { @@ -30,6 +31,7 @@ import { reduceCheckoutPage } from '@/checkout/checkoutPage' import { planCreditsSettingsUrl } from '@/checkout/cloudLinks' +import { createOperationChannel } from '@/checkout/operationChannel' import type { PayVerdict } from '@/checkout/payVerdict' import { operationOutcomeOf, payVerdictOf } from '@/checkout/payVerdict' import { @@ -40,6 +42,7 @@ import { useBilledWorkspace } from '@/composables/useBilledWorkspace' import { BILLING_WEB_ENV } from '@/config/env' import { awaitBillingWebStripeKey } from '@/config/stripeKey' import { useBillingEntry } from '@/entry/billingEntry' +import { useBillingWebSession } from '@/session/billingWebSession' import { createDeferredStripeChallengePort } from '@/session/stripeChallengePort' /** What Pay charges: a new card's token, a saved method, or the method on file. */ @@ -63,9 +66,15 @@ type PlannedEntry = BillingEntry & { plan: string } * that a later one overtook drops its answer, so a reload, a return from a * provider page, a restore from the back-forward cache and a sibling tab's * nudge all land on the same page for the same server state. + * + * Sibling tabs on this checkout hear when this page's own Pay starts an + * operation and when it settles, and re-read the server for themselves. The + * notice carries no state, and only an operation this page sent is announced, + * so no tab ever re-broadcasts what it merely heard. */ export function useFullPageCheckout() { const { entry } = useBillingEntry() + const { session } = useBillingWebSession() const billedWorkspace = useBilledWorkspace() const { capabilities, lifecycle, status } = useBillingClient< 'capabilities' | 'lifecycle' | 'status' @@ -211,13 +220,42 @@ export function useFullPageCheckout() { void readCapture() } + const scope = session.value + const channel = + scope === undefined + ? undefined + : createOperationChannel(scope.uid, scope.workspace.id) + const unsubscribe = channel?.subscribe(() => void reconcile()) + tryOnScopeDispose(() => { + unsubscribe?.() + channel?.close() + }) + + const announced = new Set() + + /** Tells sibling tabs about this page's own operation, once per step. */ + function announce(operation: BillingOperationState) { + if (scope === undefined || channel === undefined) return + const settled = page.value.kind === 'terminal' + const notice = `${operation.id}:${settled ? 'settled' : 'started'}` + if (announced.has(notice)) return + announced.add(notice) + channel.publish({ + workspaceId: scope.workspace.id, + operationId: operation.id, + kind: settled ? 'settled' : 'started' + }) + } + watch(checkout.operation, (operation) => { if (operation === undefined) return + const own = page.value.kind === 'capture' && page.value.attempt === 'sent' dispatch({ type: 'operationChanged', operation, ...outcomeFor(operation) }) + if (own) announce(operation) }) function onPaymentPhase(phase: StripePaymentPhase) { diff --git a/apps/billing-web/src/views/FullPageCheckoutView.test.ts b/apps/billing-web/src/views/FullPageCheckoutView.test.ts index d7e34580a5c..bb8c4465038 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.test.ts +++ b/apps/billing-web/src/views/FullPageCheckoutView.test.ts @@ -1,5 +1,5 @@ import userEvent from '@testing-library/user-event' -import { render, screen, waitFor } from '@testing-library/vue' +import { cleanup, render, screen, waitFor } from '@testing-library/vue' import { nextTick, ref } from 'vue' import type { VNode } from 'vue' @@ -15,6 +15,8 @@ import { BILLING_CLIENT_KEY } from '@comfyorg/account-ui/billing' import type { StripePaymentPhase } from '@comfyorg/account-ui/billing/stripe' import { parseBillingEntry } from '@comfyorg/billing-contract' +import type { OperationNotice } from '@/checkout/operationChannel' + import { recordBillingEntry } from '@/entry/billingEntry' import { createBillingI18n } from '@/i18n' import type { @@ -54,6 +56,41 @@ vi.mock(import('@/entry/workspaceBinding'), () => ({ bindEntryWorkspace: () => false })) +/** The cross-tab channel, held so a test can play a sibling tab. */ +const siblings = vi.hoisted(() => ({ + scope: undefined as { uid: string; workspaceId: string } | undefined, + listeners: new Set<(notice: OperationNotice) => void>(), + published: [] as OperationNotice[], + closed: 0, + nudge(notice: OperationNotice) { + for (const listener of this.listeners) listener(notice) + }, + reset() { + this.scope = undefined + this.listeners.clear() + this.published = [] + this.closed = 0 + } +})) + +vi.mock(import('@/checkout/operationChannel'), () => ({ + createOperationChannel: (uid: string, workspaceId: string) => { + siblings.scope = { uid, workspaceId } + return { + publish: (notice: OperationNotice) => { + siblings.published.push(notice) + }, + subscribe: (listener: (notice: OperationNotice) => void) => { + siblings.listeners.add(listener) + return () => siblings.listeners.delete(listener) + }, + close: () => { + siblings.closed += 1 + } + } + } +})) + const SESSION: AccountCredential = { token: 'jwt-1', permissions: [], @@ -1038,3 +1075,141 @@ describe('FullPageCheckoutView mount reconciliation', () => { expect(form.mounts).toBe(0) }) }) + +function pageShow(persisted: boolean): Event { + const event = new Event('pageshow') + Object.defineProperty(event, 'persisted', { value: persisted }) + return event +} + +describe('FullPageCheckoutView re-reconciliation', () => { + beforeEach(() => { + form.mounts = 0 + siblings.reset() + }) + + it('re-reads the operation when the page is restored from the back-forward cache, and lands on what it finds', async () => { + const fake = await payReady() + fake.recover.mockImplementationOnce(async () => { + fake.publishOperation(pendingOperation('op_moved_on')) + return { status: 'ok', value: pendingOperation('op_moved_on') } + }) + + window.dispatchEvent(pageShow(true)) + + expect(await waitingStatus()).toBeInTheDocument() + expect(fake.recover).toHaveBeenCalledTimes(2) + expect( + screen.queryByRole('button', { name: 'Pay and subscribe' }) + ).not.toBeInTheDocument() + }) + + it('leaves a fresh navigation alone', async () => { + const fake = await payReady() + + window.dispatchEvent(pageShow(false)) + await nextTick() + + expect(fake.recover).toHaveBeenCalledOnce() + expect(payButton()).toBeEnabled() + }) + + it('lets the newest reconciliation win over a slower, older one', async () => { + let answerFirst: ( + result: BillingResult + ) => void = () => {} + const fake = await renderCheckout({}, (fake) => + fake.recover.mockImplementationOnce( + () => new Promise((resolve) => (answerFirst = resolve)) + ) + ) + await waitFor(() => expect(fake.recover).toHaveBeenCalledOnce()) + fake.recover.mockImplementationOnce(async () => { + fake.publishOperation(pendingOperation('op_newer')) + return { status: 'ok', value: pendingOperation('op_newer') } + }) + + window.dispatchEvent(pageShow(true)) + await waitingStatus() + answerFirst({ status: 'ok', value: undefined }) + await capturePromisesFlushed() + + expect(screen.getByRole('status')).toBeInTheDocument() + expect(form.mounts).toBe(0) + }) + + it('listens on a channel scoped to the signed-in user and the workspace, and lets go on unmount', async () => { + await renderQuoted() + + expect(siblings.scope).toEqual({ uid: 'uid-1', workspaceId: 'ws-team' }) + expect(siblings.listeners.size).toBe(1) + + cleanup() + + expect(siblings.listeners.size).toBe(0) + expect(siblings.closed).toBe(1) + }) + + it("re-reads the server on a sibling tab's nudge, trusting nothing in the notice itself", async () => { + const fake = await payReady() + fake.recover.mockImplementationOnce(async () => { + fake.publishOperation(succeededOperation('op_from_server')) + return { status: 'ok', value: succeededOperation('op_from_server') } + }) + + siblings.nudge({ + workspaceId: 'ws-team', + operationId: 'op_claimed_by_notice', + kind: 'settled' + }) + + expect( + await screen.findByRole('heading', { name: 'Already completed' }) + ).toBeInTheDocument() + expect(screen.getByText('Reference: op_from_server')).toBeInTheDocument() + expect(fake.recover).toHaveBeenCalledTimes(2) + }) + + it('tells sibling tabs when its own Pay starts an operation and when it settles, once each', async () => { + const fake = await payReady({ + subscribe: { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation('op_mine') } + } + }) + fake.subscribe.mockImplementationOnce(async () => { + fake.publishOperation(pendingOperation('op_mine')) + await nextTick() + fake.publishOperation({ + ...pendingOperation('op_mine'), + serverPhase: 'in_progress' + }) + await nextTick() + fake.publishOperation(succeededOperation('op_mine')) + return { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation('op_mine') } + } + }) + + form.emit('confirm', 'ctoken_1') + + await screen.findByRole('heading', { name: "You're all set" }) + expect(siblings.published).toEqual([ + { workspaceId: 'ws-team', operationId: 'op_mine', kind: 'started' }, + { workspaceId: 'ws-team', operationId: 'op_mine', kind: 'settled' } + ]) + }) + + it('never announces an operation it only heard about', async () => { + const fake = await renderCheckout({ + recover: { status: 'ok', value: pendingOperation('op_theirs') } + }) + await waitingStatus() + + fake.publishOperation(succeededOperation('op_theirs')) + await screen.findByRole('heading', { name: 'Already completed' }) + + expect(siblings.published).toEqual([]) + }) +}) diff --git a/apps/billing-web/src/views/FullPageCheckoutView.vue b/apps/billing-web/src/views/FullPageCheckoutView.vue index b6dbfb36a8f..4215e92a0e6 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.vue +++ b/apps/billing-web/src/views/FullPageCheckoutView.vue @@ -1,4 +1,5 @@ + + diff --git a/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts b/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts new file mode 100644 index 00000000000..6421522febd --- /dev/null +++ b/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts @@ -0,0 +1,166 @@ +import userEvent from '@testing-library/user-event' +import { render, screen } from '@testing-library/vue' + +import type { PendingBillingOperation } from '@comfyorg/account-core/billing' + +import type { SubmitPhase } from '@/checkout/checkoutPage' +import CheckoutPayAction from '@/components/fullPage/CheckoutPayAction.vue' +import { createBillingI18n } from '@/i18n' +import { pendingOperation } from '@/test/fakeBillingClient' + +const challenge = ( + status: 'required' | 'in_progress' +): PendingBillingOperation => ({ + ...pendingOperation('op_3ds'), + authenticationState: 'requires_action', + challenge: { clientSecret: 'cs', status } +}) + +function renderPayAction( + props: { + phase?: SubmitPhase + canCancel?: boolean + loading?: boolean + disabled?: boolean + onCancel?: () => void + onContinueVerification?: () => void + } = {} +) { + return render(CheckoutPayAction, { + props: { disabled: false, ...props }, + global: { plugins: [createBillingI18n()] } + }) +} + +const footnote = () => screen.getByTestId('checkout-phase-footnote') +const ghostButtons = () => + screen + .getAllByRole('button') + .map((button) => button.textContent.trim()) + .filter((name) => name !== 'Pay and subscribe') + +describe('CheckoutPayAction', () => { + it.for<{ + name: string + phase: SubmitPhase + canCancel: boolean + line: string + buttons: string[] + }>([ + { + name: 'Pay at rest', + phase: { kind: 'capture' }, + canCancel: true, + line: '', + buttons: [] + }, + { + name: 'a charge processing', + phase: { kind: 'processing' }, + canCancel: true, + line: "This payment is already processing and can't be canceled.", + buttons: [] + }, + { + name: 'a challenge the customer can reopen', + phase: { kind: 'challenge', operation: challenge('required') }, + canCancel: false, + line: 'Nothing has been charged yet.', + buttons: ['Continue verification'] + }, + { + name: 'a challenge this tab is showing', + phase: { kind: 'challenge', operation: challenge('in_progress') }, + canCancel: false, + line: 'Nothing has been charged yet.', + buttons: [] + }, + { + name: 'a challenge once the server can cancel it', + phase: { kind: 'challenge', operation: challenge('required') }, + canCancel: true, + line: 'Nothing has been charged yet.', + buttons: ['Continue verification', 'Cancel payment'] + }, + { + name: 'an Alipay redirect', + phase: { kind: 'redirecting', method: 'alipay' }, + canCancel: true, + line: 'Taking you to Alipay to finish paying. Nothing has been charged yet.', + buttons: [] + }, + { + name: 'a redirect to a method with no name', + phase: { kind: 'redirecting', method: 'klarna' }, + canCancel: true, + line: 'Taking you to your payment provider to finish paying. Nothing has been charged yet.', + buttons: [] + } + ])( + 'shows $name with its line and ghost buttons', + ({ phase, canCancel, line, buttons }) => { + renderPayAction({ phase, canCancel }) + + expect(footnote().textContent.trim()).toBe(line) + expect(ghostButtons()).toEqual(buttons) + } + ) + + it('keeps an empty polite status region mounted at rest', () => { + renderPayAction({ phase: { kind: 'capture' } }) + + const region = screen.getByRole('status') + expect(region).toBe(footnote()) + expect(region).toHaveAttribute('aria-live', 'polite') + expect(region).toBeEmptyDOMElement() + }) + + it('leaves the live region to the visible pay action when given no phase', () => { + renderPayAction() + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('emits cancel from Cancel payment', async () => { + const onCancel = vi.fn() + renderPayAction({ + phase: { kind: 'challenge', operation: challenge('in_progress') }, + canCancel: true, + onCancel + }) + + await userEvent.click( + screen.getByRole('button', { name: 'Cancel payment' }) + ) + + expect(onCancel).toHaveBeenCalledOnce() + }) + + it('emits continueVerification from Continue verification', async () => { + const onContinueVerification = vi.fn() + renderPayAction({ + phase: { kind: 'challenge', operation: challenge('required') }, + onContinueVerification + }) + + await userEvent.click( + screen.getByRole('button', { name: 'Continue verification' }) + ) + + expect(onContinueVerification).toHaveBeenCalledOnce() + }) + + it.for<{ name: string; loading: boolean; disabled: boolean; busy: string }>([ + { name: 'while loading', loading: true, disabled: true, busy: 'true' }, + { name: 'at rest', loading: false, disabled: false, busy: 'false' } + ])( + 'marks Pay busy and disabled only $name', + ({ loading, disabled, busy }) => { + renderPayAction({ loading }) + + const pay = screen.getByRole('button', { name: 'Pay and subscribe' }) + expect(pay).toHaveAttribute('aria-busy', busy) + expect(pay).toHaveProperty('disabled', disabled) + } + ) +}) diff --git a/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue b/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue index aabaf3f9bc0..fc9e7a14f71 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue +++ b/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue @@ -3,8 +3,10 @@ import { computed } from 'vue' import { useI18n } from 'vue-i18n' import { CheckoutTermsNote } from '@comfyorg/account-ui/billing/checkout' +import { cn } from '@comfyorg/tailwind-utils' -import type { InlineOutcome } from '@/checkout/checkoutPage' +import type { InlineOutcome, SubmitPhase } from '@/checkout/checkoutPage' +import { isChallengeReopenable } from '@/checkout/checkoutPage' import { supportLinkFor } from '@/checkout/payVerdict' import InlineOutcomeCard from '@/components/fullPage/InlineOutcomeCard.vue' import type { KeepSubscriptionConsent } from '@/components/fullPage/KeepSubscriptionNotice.vue' @@ -20,6 +22,8 @@ export interface PayContext { const { disabled, loading = false, + phase, + canCancel = false, failure, outcome, consent @@ -27,15 +31,21 @@ const { PayContext & { disabled: boolean loading?: boolean + /** The submit area's phase; only the visible pay action carries one, so the page has one live region. */ + phase?: SubmitPhase + /** Cancel payment renders only once the server can cancel a pending payment. */ + canCancel?: boolean } >() const emit = defineEmits<{ confirmReactivation: [confirmed: boolean] consentMissing: [] + cancel: [] + continueVerification: [] }>() -const { t } = useI18n() +const { t, te } = useI18n() /** Support is for a payment that failed; a notice over a fresh price is not one. */ const supportLink = computed(() => @@ -50,6 +60,25 @@ function guardConsent(event: Event) { event.preventDefault() emit('consentMissing') } + +/** The line above Pay for a phase in flight; empty at rest so the live region stays mounted. */ +const footnote = computed(() => { + if (phase === undefined || phase.kind === 'capture') return '' + if (phase.kind === 'challenge') return t('checkout.fullPage.phase.challenge') + if (phase.kind === 'processing') + return t('checkout.fullPage.phase.processing') + const named = `checkout.fullPage.phase.methods.${phase.method}` + return te(named) + ? t('checkout.fullPage.phase.redirecting', { method: t(named) }) + : t('checkout.fullPage.phase.redirectingUnnamed') +}) + +const challenge = computed(() => + phase?.kind === 'challenge' ? phase.operation : undefined +) + +const GHOST_BUTTON = + 'flex h-10 w-full cursor-pointer items-center justify-center rounded-lg px-4 text-sm font-semibold text-base-foreground hover:bg-secondary-background-hover focus-visible:ring-2 focus-visible:ring-base-foreground focus-visible:outline-none' diff --git a/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue b/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue new file mode 100644 index 00000000000..348e62285cd --- /dev/null +++ b/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue @@ -0,0 +1,121 @@ + + + diff --git a/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.test.ts b/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.test.ts new file mode 100644 index 00000000000..7d1aa8085c9 --- /dev/null +++ b/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.test.ts @@ -0,0 +1,112 @@ +import { render, screen } from '@testing-library/vue' + +import type { PromoEntry, PromoRejection } from '@/checkout/promoEntry' +import type { PromoChip } from '@/checkout/summaryLedger' +import PromoCodeEntry from '@/components/fullPage/summary/PromoCodeEntry.vue' +import { createBillingI18n } from '@/i18n' + +function renderEntry({ + chips = [], + entry = { kind: 'idle' }, + accepts = true, + live = true +}: { + chips?: PromoChip[] + entry?: PromoEntry + accepts?: boolean + live?: boolean +}) { + return render(PromoCodeEntry, { + props: { chips, entry, accepts, live }, + global: { plugins: [createBillingI18n()] } + }) +} + +const HELD: PromoChip = { code: 'COMFY-EDU', removable: false } +const ENTERED: PromoChip = { code: 'COMFY50', removable: true } + +describe('PromoCodeEntry', () => { + it('shows a held chip with no remove beside the Add control, which it does not count against', () => { + renderEntry({ chips: [HELD] }) + + expect(screen.getByText('COMFY-EDU')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: /Remove/ }) + ).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Add promo code' })).toBeEnabled() + }) + + it('hides the Add control while the quote carries the one entered code', () => { + renderEntry({ chips: [HELD, ENTERED] }) + + expect(screen.getByRole('button', { name: 'Remove COMFY50' })).toBeEnabled() + expect( + screen.queryByRole('button', { name: 'Add promo code' }) + ).not.toBeInTheDocument() + }) + + it.for<{ + name: string + chips: PromoChip[] + entry: PromoEntry + control: string + }>([ + { + name: 'the Add control', + chips: [], + entry: { kind: 'idle' }, + control: 'Add promo code' + }, + { + name: 'Apply', + chips: [], + entry: { kind: 'editing', draft: 'X' }, + control: 'Apply' + }, + { + name: 'a chip remove', + chips: [ENTERED], + entry: { kind: 'applied', code: 'COMFY50' }, + control: 'Remove COMFY50' + } + ])( + 'locks $name while promo entry is not live', + ({ chips, entry, control }) => { + renderEntry({ chips, entry, live: false }) + + expect(screen.getByRole('button', { name: control })).toBeDisabled() + } + ) + + it.for<{ reason: PromoRejection; message: string }>([ + { reason: 'invalid', message: "This code isn't valid." }, + { reason: 'unchecked', message: "We couldn't check this code. Try again." } + ])( + 'announces the $reason result of Apply as an alert and keeps the code typed', + async ({ reason, message }) => { + const { rerender } = renderEntry({ + entry: { kind: 'applying', draft: 'LAUNCH20' } + }) + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + + await rerender({ + chips: [], + entry: { kind: 'rejected', draft: 'LAUNCH20', reason }, + accepts: true, + live: true + }) + + expect(screen.getByRole('alert')).toHaveTextContent(message) + expect(screen.getByRole('textbox', { name: 'Promo code' })).toHaveValue( + 'LAUNCH20' + ) + } + ) + + it('renders no entry anywhere on a charge that takes no code', () => { + renderEntry({ accepts: false }) + + expect(screen.queryByRole('button')).not.toBeInTheDocument() + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + }) +}) diff --git a/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.vue b/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.vue new file mode 100644 index 00000000000..e38c72b811f --- /dev/null +++ b/apps/billing-web/src/components/fullPage/summary/PromoCodeEntry.vue @@ -0,0 +1,89 @@ + + + diff --git a/apps/billing-web/src/components/fullPage/summary/PromoCodeField.vue b/apps/billing-web/src/components/fullPage/summary/PromoCodeField.vue new file mode 100644 index 00000000000..48cd6f410dc --- /dev/null +++ b/apps/billing-web/src/components/fullPage/summary/PromoCodeField.vue @@ -0,0 +1,77 @@ + + + diff --git a/apps/billing-web/src/composables/useCheckoutPromo.test.ts b/apps/billing-web/src/composables/useCheckoutPromo.test.ts new file mode 100644 index 00000000000..0b46b4ed611 --- /dev/null +++ b/apps/billing-web/src/composables/useCheckoutPromo.test.ts @@ -0,0 +1,41 @@ +import type { PreviewSubscribeResult } from '@comfyorg/account-core/billing' + +import { useCheckoutPromo } from '@/composables/useCheckoutPromo' +import { previewOf } from '@/test/fakeBillingClient' + +/** Mirrors `usePreviewSubscribe.quote()`: a newer quote supersedes the pending one. */ +function supersedingRequote() { + const pending: ((result: PreviewSubscribeResult) => void)[] = [] + const requote = vi.fn( + (_code?: string) => + new Promise((resolve) => { + pending.at(-1)?.({ status: 'error', code: 'SUPERSEDED' }) + pending.push(resolve) + }) + ) + const answerLatest = (result: PreviewSubscribeResult) => + pending.at(-1)?.(result) + return { requote, answerLatest } +} + +describe('useCheckoutPromo', () => { + it('ignores a second Apply while the first code is still being priced', async () => { + const { requote, answerLatest } = supersedingRequote() + const promo = useCheckoutPromo({ + prefill: 'LAUNCH20', + live: () => true, + requote + }) + + const first = promo.apply() + const second = promo.apply() + answerLatest({ + status: 'ok', + value: previewOf({ promotion_code: 'LAUNCH20' }) + }) + await Promise.all([first, second]) + + expect(promo.entry.value).toEqual({ kind: 'applied', code: 'LAUNCH20' }) + expect(requote).toHaveBeenCalledOnce() + }) +}) diff --git a/apps/billing-web/src/composables/useCheckoutPromo.ts b/apps/billing-web/src/composables/useCheckoutPromo.ts new file mode 100644 index 00000000000..8a20c235488 --- /dev/null +++ b/apps/billing-web/src/composables/useCheckoutPromo.ts @@ -0,0 +1,86 @@ +import { computed, shallowReadonly, shallowRef } from 'vue' + +import type { PreviewSubscribeResult } from '@comfyorg/account-core/billing' + +import type { PromoEntry, PromoEntryEvent } from '@/checkout/promoEntry' +import { + initialPromoEntry, + promoRejectionOf, + reducePromoEntry +} from '@/checkout/promoEntry' + +interface CheckoutPromoOptions { + /** A code the entry URL carried; it opens the field and waits for Apply. */ + readonly prefill: string | undefined + /** Whether the customer may change the code right now. */ + readonly live: () => boolean + /** Prices the plan again, with the code or, when omitted, without one. */ + readonly requote: (promotionCode?: string) => Promise +} + +/** + * The promo entry's effects: every intent is a re-quote, and every answer goes + * through `reducePromoEntry`. A refused code never touches the quote, because + * a failed quote leaves the last one standing. + */ +export function useCheckoutPromo({ + prefill, + live, + requote +}: CheckoutPromoOptions) { + const entry = shallowRef(initialPromoEntry(prefill)) + + function dispatch(event: PromoEntryEvent) { + entry.value = reducePromoEntry(entry.value, event) + } + + function intend(event: PromoEntryEvent) { + if (live()) dispatch(event) + } + + async function apply() { + const typed = entry.value + if (!live() || (typed.kind !== 'editing' && typed.kind !== 'rejected')) + return + dispatch({ type: 'applyRequested' }) + const current = entry.value + if (current.kind !== 'applying') return + const result = await requote(current.draft) + if (result.status === 'error') { + dispatch({ type: 'applyRejected', reason: promoRejectionOf(result) }) + return + } + const code = result.value.promotion_code + dispatch( + code === undefined + ? { type: 'applyRejected', reason: 'invalid' } + : { type: 'applyAccepted', code } + ) + } + + async function remove() { + if (!live() || entry.value.kind !== 'applied') return + dispatch({ type: 'removeRequested' }) + const result = await requote() + dispatch({ + type: result.status === 'ok' ? 'removeSettled' : 'removeFailed' + }) + } + + return { + entry: shallowReadonly(entry), + /** A re-quote for the code is in flight, so the price on screen is not final. */ + busy: computed( + () => entry.value.kind === 'applying' || entry.value.kind === 'removing' + ), + appliedCode: computed(() => + entry.value.kind === 'applied' ? entry.value.code : undefined + ), + open: () => intend({ type: 'opened' }), + edit: (draft: string) => intend({ type: 'edited', draft }), + dismiss: () => intend({ type: 'dismissed' }), + apply, + remove, + expire: () => dispatch({ type: 'expired' }) + } +} diff --git a/apps/billing-web/src/composables/useFullPageCheckout.ts b/apps/billing-web/src/composables/useFullPageCheckout.ts index f7bf96c845e..82e561c109f 100644 --- a/apps/billing-web/src/composables/useFullPageCheckout.ts +++ b/apps/billing-web/src/composables/useFullPageCheckout.ts @@ -11,9 +11,11 @@ import type { StripePaymentPhase } from '@comfyorg/account-ui/billing/stripe' import type { BillingOperationState, BillingResult, + CapabilitiesSnapshot, SubscribeInput, SubscriptionPreview } from '@comfyorg/account-core/billing' +import { matchesServerCode } from '@comfyorg/account-core/billing' import type { BillingEntry } from '@comfyorg/billing-contract' import { buildReturnUrl } from '@comfyorg/billing-contract' @@ -25,34 +27,66 @@ import type { } from '@/checkout/checkoutPage' import { RESOLVING, + UNREADABLE_LINK, isParked, needsConsent, railAcceptsPay, reduceCheckoutPage } from '@/checkout/checkoutPage' -import { planCreditsSettingsUrl } from '@/checkout/cloudLinks' +import { planCreditsSettingsUrl, pricingTableUrl } from '@/checkout/cloudLinks' import { createOperationChannel } from '@/checkout/operationChannel' +import { promoEntryLive, promoRejectionOf } from '@/checkout/promoEntry' import type { PayVerdict } from '@/checkout/payVerdict' import { operationOutcomeOf, payVerdictOf } from '@/checkout/payVerdict' import { buildSubscribeRequest, - checkoutResultUrl + checkoutReturnUrl } from '@/checkout/subscribeRequest' import { useBilledWorkspace } from '@/composables/useBilledWorkspace' +import { useCheckoutPromo } from '@/composables/useCheckoutPromo' import { BILLING_WEB_ENV } from '@/config/env' import { awaitBillingWebStripeKey } from '@/config/stripeKey' import { useBillingEntry } from '@/entry/billingEntry' import { useBillingWebSession } from '@/session/billingWebSession' import { createDeferredStripeChallengePort } from '@/session/stripeChallengePort' -/** What Pay charges: a new card's token, a saved method, or the method on file. */ +/** + * What Pay charges: a new method's token, a saved method, or the method on + * file. `methodType` is the provider's type (`card`, `alipay`, …); any + * non-card type finishes paying on its own site. + */ export type PayChoice = - | { readonly confirmationToken: string } - | { readonly savedMethodId: string } + | { readonly confirmationToken: string; readonly methodType: string } + | { readonly savedMethodId: string; readonly methodType: string } | undefined +const CARD_METHOD_TYPE = 'card' + +/** The method's type when it authenticates away from this page, else nothing. */ +function redirectMethodOf(choice: PayChoice): string | undefined { + if (choice === undefined || choice.methodType === CARD_METHOD_TYPE) + return undefined + return choice.methodType +} + type PlannedEntry = BillingEntry & { plan: string } +/** What the quote answers for a plan slug the catalog does not have. */ +const UNKNOWN_PLAN_SERVER_CODE = 'INVALID_PLAN' + +/** A capability read that ends the page before any quote: unreadable, or refused. */ +function capabilityStop( + allowed: BillingResult +): CheckoutPageEvent | undefined { + if (allowed.status === 'error') + return { type: 'unavailable', code: allowed.code } + if (allowed.value.capabilities.can_subscribe_self_serve) return undefined + return { + type: 'refused', + reason: allowed.value.denials.can_subscribe_self_serve ?? 'unspecified' + } +} + /** * The full-page checkout's effects around one `CheckoutPage` state: the * reconciliation with whatever operation the workspace is already waiting @@ -73,7 +107,7 @@ type PlannedEntry = BillingEntry & { plan: string } * so no tab ever re-broadcasts what it merely heard. */ export function useFullPageCheckout() { - const { entry } = useBillingEntry() + const { entry, error: unreadableLink } = useBillingEntry() const { session } = useBillingWebSession() const billedWorkspace = useBilledWorkspace() const { capabilities, lifecycle, status } = useBillingClient< @@ -87,7 +121,9 @@ export function useFullPageCheckout() { challengePort: createDeferredStripeChallengePort(awaitBillingWebStripeKey) }) - const page = shallowRef(RESOLVING) + const page = shallowRef( + unreadableLink.value === undefined ? RESOLVING : UNREADABLE_LINK + ) /** A page sent back to resolving by the lifecycle reads its capture again. */ function dispatch(event: CheckoutPageEvent) { @@ -122,12 +158,13 @@ export function useFullPageCheckout() { } } - function quoteArrival(arrival: PlannedEntry) { + function quoteArrival(arrival: PlannedEntry, promotionCode?: string) { return quote({ planSlug: arrival.plan, ...(arrival.teamCreditStopId === undefined ? {} - : { teamCreditStopId: arrival.teamCreditStopId }) + : { teamCreditStopId: arrival.teamCreditStopId }), + ...(promotionCode === undefined ? {} : { promotionCode }) }) } @@ -140,6 +177,27 @@ export function useFullPageCheckout() { read.status === 'ok' ? read.value.status.cancel_at : undefined } + /** An operation parked on a card is what a Pay resubmits, so it is not money in flight. */ + const moneyInFlight = computed(() => { + const operation = checkout.operation.value + return operation?.phase === 'pending' && !isParked(operation) + }) + + const promoLive = computed(() => + promoEntryLive(page.value, checkout.submitting.value || moneyInFlight.value) + ) + + const promo = useCheckoutPromo({ + prefill: entry.value?.promotionCode, + live: () => promoLive.value, + requote: (promotionCode) => { + const arrival = entry.value + return arrival?.plan === undefined + ? Promise.resolve({ status: 'error', code: 'REQUEST_FAILED' }) + : quoteArrival({ ...arrival, plan: arrival.plan }, promotionCode) + } + }) + const asksReactivation = (quoted: SubscriptionPreview) => quoted.requires_reactivation_confirmation === true @@ -148,24 +206,30 @@ export function useFullPageCheckout() { return asked } + /** A capture read again after the page went back to resolving keeps the applied code. */ async function captureEvent( arrival: PlannedEntry ): Promise { - const [allowed, quoted, methods] = await Promise.all([ - capabilities.read(), - quoteArrival(arrival), - saved.refresh(), - awaitBillingWebStripeKey() - ]) - if (allowed.status === 'error') - return { type: 'unavailable', code: allowed.code } - if (!allowed.value.capabilities.can_subscribe_self_serve) - return { - type: 'refused', - reason: allowed.value.denials.can_subscribe_self_serve ?? 'unspecified' - } + const [allowed, { requoted: quoted, expiredPromo }, methods] = + await Promise.all([ + capabilities.read(), + requoteWithPromo(arrival), + saved.refresh(), + awaitBillingWebStripeKey() + ]) + if (expiredPromo !== undefined) promo.expire() + const stopped = capabilityStop(allowed) + if (stopped !== undefined) return stopped if (quoted.status === 'error') - return { type: 'unavailable', code: quoted.code } + return 'serverCode' in quoted && + matchesServerCode(quoted, UNKNOWN_PLAN_SERVER_CODE) + ? { type: 'planUnavailable', reason: 'retired' } + : { type: 'unavailable', code: quoted.code } + if ( + quoted.value.new_plan.tier === 'TEAM' && + arrival.teamCreditStopId === undefined + ) + return { type: 'planUnavailable', reason: 'team_stop_missing' } const reactivation = consentAsked(asksReactivation(quoted.value)) return quoted.value.transition_type === 'new_subscription' ? { @@ -249,15 +313,27 @@ export function useFullPageCheckout() { watch(checkout.operation, (operation) => { if (operation === undefined) return - const own = page.value.kind === 'capture' && page.value.attempt === 'sent' + const own = + page.value.kind === 'capture' && page.value.attempt.kind === 'sent' dispatch({ type: 'operationChanged', operation, ...outcomeFor(operation) }) if (own) announce(operation) + if (operation.phase === 'timed_out' && watchingMoney()) void reconcile() }) + /** + * A watch whose poll budget ran out re-reads the server, which follows the + * operation afresh: these screens promise to update on their own, and a + * bank debit can take hours to settle. + */ + function watchingMoney() { + const kind = page.value.kind + return kind === 'waiting' || kind === 'unconfirmed' + } + function onPaymentPhase(phase: StripePaymentPhase) { if (phase.phase === 'payment_element_ready' && phase.element === 'payment') dispatch({ type: 'elementReady' }) @@ -267,15 +343,15 @@ export function useFullPageCheckout() { /** * Money in flight keeps Pay locked, so a second click cannot charge twice. - * An operation parked on a card is what a Pay resubmits, so it does not. + * A re-quote for a promo code holds Pay until the price settles. */ - const canPay = computed(() => { - const operation = checkout.operation.value - const inFlight = operation?.phase === 'pending' && !isParked(operation) - return ( - railAcceptsPay(page.value) && preview.value?.allowed === true && !inFlight - ) - }) + const canPay = computed( + () => + railAcceptsPay(page.value) && + preview.value?.allowed === true && + !moneyInFlight.value && + !promo.busy.value + ) const payFailure = computed(() => { const result = checkout.result.value @@ -284,20 +360,53 @@ export function useFullPageCheckout() { return verdict.kind === 'failure' ? verdict.code : undefined }) - /** Back to the product, or to the workspace's Plan & Credits settings when this family has no destination for the link's target. */ + /** + * Back to the product, with a settled payment's outcome and reference, or + * to the workspace's Plan & Credits settings when this family has no + * destination for the link's target. + */ const returnLink = computed(() => { const workspace = billedWorkspace() const arrival = entry.value + const current = page.value const host = arrival && buildReturnUrl({ target: arrival.returnTo, environment: BILLING_WEB_ENV, - workspace + workspace, + ...(current.kind === 'terminal' + ? { result: 'success', reference: current.operation?.id } + : {}) })?.href return host ?? planCreditsSettingsUrl(workspace) }) + /** Only a tab a script opened can close itself; any other goes back to `returnLink`. */ + const openedByScript = Boolean(window.opener) + + function close() { + if (openedByScript) window.close() + else window.location.assign(returnLink.value) + } + + /** The live catalog, on the Team tab when the link asked for a team plan. */ + const viewPlansLink = computed(() => + pricingTableUrl( + page.value.kind === 'plan_unavailable' && + page.value.reason === 'team_stop_missing' + ? 'team' + : 'default', + billedWorkspace() + ) + ) + + /** Try again re-runs the whole resolve in place: the re-read and the capture read. */ + function retryLoad() { + void reconcile() + dispatch({ type: 'retried' }) + } + function requestFor( arrival: PlannedEntry, quoted: SubscriptionPreview, @@ -317,7 +426,7 @@ export function useFullPageCheckout() { : {}), confirmReactivation: current.kind === 'capture' && current.reactivation === 'confirmed', - returnUrl: checkoutResultUrl( + returnUrl: checkoutReturnUrl( arrival, billedWorkspace(), window.location.origin @@ -325,6 +434,19 @@ export function useFullPageCheckout() { }) } + /** A code the server now refuses has lapsed since Apply, so the plan is priced without it. */ + async function requoteWithPromo(arrival: PlannedEntry) { + const code = promo.appliedCode.value + const withCode = await quoteArrival(arrival, code) + if ( + code === undefined || + withCode.status === 'ok' || + promoRejectionOf(withCode) !== 'invalid' + ) + return { requoted: withCode } + return { requoted: await quoteArrival(arrival), expiredPromo: code } + } + /** A Pay the server refused for an operation already under way re-reads it, never a decline (rule 18). */ async function settle(verdict: PayVerdict, arrival: PlannedEntry) { if (verdict.kind === 'settled') { @@ -347,17 +469,19 @@ export function useFullPageCheckout() { because: Extract['because'], arrival: BillingEntry & { plan: string } ) { - const requoted = await quoteArrival(arrival) + const { requoted, expiredPromo } = await requoteWithPromo(arrival) if (requoted.status !== 'ok') { dispatch({ type: 'requoteFailed', code: requoted.code }) return } + if (expiredPromo !== undefined) promo.expire() dispatch({ type: 'requoted', reactivation: consentAsked( because === 'reactivation_required' || asksReactivation(requoted.value) ), - priceUpdated: because === 'quote_expired' + priceUpdated: because === 'quote_expired', + ...(expiredPromo === undefined ? {} : { expiredPromo }) }) } @@ -366,24 +490,46 @@ export function useFullPageCheckout() { dispatch({ type: 'consentMissing' }) } + let payGeneration = 0 + + /** + * A challenge the bank refused leaves the operation pending, so the + * subscribe never resolves for that attempt; the page has already moved on + * from the operation's own verdict, and a later Pay owns the form. Only + * the newest Pay's result may settle it. + */ async function pay(choice: PayChoice) { const arrival = entry.value const quoted = preview.value if (arrival?.plan === undefined || !quoted || !canPay.value) return if (needsConsent(page.value)) return payWithoutConsent() const planned = { ...arrival, plan: arrival.plan } - dispatch({ type: 'paySubmitted' }) + const mine = ++payGeneration + const redirectMethod = redirectMethodOf(choice) + dispatch({ + type: 'paySubmitted', + ...(redirectMethod === undefined ? {} : { redirectMethod }) + }) const result = await checkout.subscribe(requestFor(planned, quoted, choice)) + if (mine !== payGeneration) return await settle(payVerdictOf(result), planned) } + /** Busy from the Pay click until the attempt resolves, whatever the lifecycle's promise does. */ + const submitting = computed( + () => page.value.kind === 'capture' && page.value.attempt.kind === 'sent' + ) + return { page: shallowReadonly(page), preview, canPay, - submitting: checkout.submitting, + submitting, payFailure, returnLink, + viewPlansLink, + close, + retryLoad, onPaymentPhase, savedMethods: saved.methods, reconcile, @@ -395,7 +541,10 @@ export function useFullPageCheckout() { dispatch({ type: 'reactivationConfirmed', confirmed }), payWithoutConsent, cancelAt: shallowReadonly(cancelAt), - pay + promo, + promoLive, + pay, + continueVerification: checkout.continueVerification } } diff --git a/apps/billing-web/src/locales/en/main.json b/apps/billing-web/src/locales/en/main.json index a24e8890203..271b08507fa 100644 --- a/apps/billing-web/src/locales/en/main.json +++ b/apps/billing-web/src/locales/en/main.json @@ -171,8 +171,6 @@ "unavailable": "The payment form isn't available right now. Please try again later.", "fullPage": { "logo": "Comfy", - "eyebrow": "Subscribe to {plan} · {workspace}", - "eyebrowPlanOnly": "Subscribe to {plan}", "planName": "{tier} Plan", "terms": { "agreement": "By continuing, you agree to Comfy Org's {terms} and {privacy}, and authorize Comfy Org to charge your payment method each billing period until you cancel.", @@ -205,10 +203,6 @@ }, "retry": "Try again" }, - "refused": { - "title": "You can't subscribe from this account", - "body": "This account can't start or change a subscription for this workspace. Ask the workspace owner, or go back and choose another workspace." - }, "outcome": { "declined": { "title": "Payment declined", @@ -222,6 +216,10 @@ "title": "Payment not completed", "body": "Your payment wasn't completed, so you haven't been charged. Pay to try again, or use a different payment method." }, + "promo_expired": { + "title": "Your promo code expired", + "body": "The {code} code expired, so the total was updated. Review the new total before paying — you have not been charged." + }, "price_updated": { "title": "The price has updated", "body": "Your quote expired, so the numbers were refreshed. Review the new total before paying — you have not been charged." @@ -254,21 +252,135 @@ "other": "This change keeps your subscription, and it renews that day at {amount}." } }, - "waiting": { - "status": "Finishing your payment…", - "body": "A payment for this workspace is still going through. This page will update on its own; nothing more is needed from you." + "phase": { + "challenge": "Nothing has been charged yet.", + "processing": "This payment is already processing and can't be canceled.", + "redirecting": "Taking you to {method} to finish paying. Nothing has been charged yet.", + "redirectingUnnamed": "Taking you to your payment provider to finish paying. Nothing has been charged yet.", + "methods": { + "alipay": "Alipay" + }, + "continueVerification": "Continue verification", + "cancel": "Cancel payment" }, - "terminal": { + "ending": { + "thisWorkspace": "this workspace", + "perMonth": "{currency} / mo", + "perYear": "{currency} / yr", + "copy": "Copy code", + "copied": "Copied", + "closeLine": "You can close this page. We'll email your invoice once this goes through and this page will automatically update.", + "actions": { + "close": "Close", + "retry": "Try again", + "view_plans": "View plans" + }, "success": { "title": "You're all set", - "body": "Your payment for {workspace} went through.", - "bodyPlan": "Your {plan} subscription for {workspace} is active." + "body": "Your plan for {workspace} has been successfully updated." }, "completed": { + "title": "You're all set", + "body": "A payment on this workspace completed — check your plan in settings.", + "codeLabel": "Your reference for this payment:" + }, + "already_completed": { "title": "Already completed", - "body": "This payment for {workspace} already went through. You won't be charged again." + "body": "This payment for {workspace} already went through. You won't be charged again.", + "codeLabel": "Your reference for this payment:" + }, + "in_progress": { + "title": "Payment in progress", + "body": "Your bank is still settling this payment — this can take up to a day. Nothing more is needed from you, and don't pay again: you could be charged twice.", + "codeLabel": "If nothing has changed after 24 hours, contact support with this code:" + }, + "received": { + "title": "Payment received", + "body": "Your payment went through and you should receive your credits or subscription soon. You won't be charged again.", + "codeLabel": "If nothing has changed after 24 hours, contact support with this code:" + }, + "unconfirmed": { + "title": "We couldn't confirm your payment", + "body": "Your payment may or may not have gone through. Don't pay again yet, you could be charged twice.", + "codeLabel": "If this page still can't confirm it after a few minutes, contact support with this code:" + }, + "refused": { + "title": "Checkout not available", + "body": "Billing for this workspace is managed by its owner. Ask them to make this change.", + "codeLabel": "If this is an error, contact support with this code:" + }, + "plan_unavailable": { + "title": "This plan isn't available", + "body": "The plan in your link isn't available. Nothing has been charged. See our current plans instead.", + "codeLabel": "If you think this is a mistake, contact support with this code:" }, - "reference": "Reference: {operationId}" + "load_failed": { + "title": "Couldn't load your checkout", + "body": "We couldn't load your quote. Nothing has been charged. Try again, or contact support if this keeps happening.", + "codeLabel": "If this keeps happening, contact support with this code:" + } + }, + "summary": { + "label": "Order summary", + "verb": { + "subscribe": "Subscribe to {plan}", + "upgrade": "Upgrade to {plan}", + "switch": "Switch to {plan}", + "change": "Change to {plan}" + }, + "scoped": "{action} · {workspace}", + "planWithCadence": "{tier} {cadence}", + "cadence": { + "monthly": "Monthly", + "yearly": "Yearly" + }, + "rate": { + "monthly": "/ mo", + "yearly": "/ yr" + }, + "credits": { + "perMonth": "credits per month", + "perYear": "credits per year", + "bare": "credits", + "addedToday": "credits added today", + "addedTodayExpire": "credits added today (expire {date})", + "refillMonthlyAfter": "credits refill monthly after {date}", + "refillYearlyAfter": "credits refill yearly after {date}" + }, + "item": { + "prorated": "{plan} - Prorated", + "remainingTime": "Remaining time for {plan} plan, less unused time from {current} plan", + "billedMonthly": "{amount} /mo, billed monthly", + "billedYearly": "Billed yearly", + "rateMonthly": "{amount} /mo", + "rateYearly": "{amount} /yr", + "refillsMonthly": "Credits refill to {credits} each month", + "refillsYearly": "Credits refill to {credits} each year", + "startsMonthly": "Starts {date}, billed monthly", + "startsYearly": "Starts {date}, billed yearly" + }, + "subtotal": "Subtotal", + "discount": { + "fallbackLabel": "Promo code", + "amount": "−{amount}" + }, + "promo": { + "add": "Add promo code", + "field": "Promo code", + "apply": "Apply", + "dismiss": "Close promo code", + "remove": "Remove {code}", + "invalid": "This code isn't valid.", + "unchecked": "We couldn't check this code. Try again." + }, + "trailing": { + "renewsAt": "Renews at {amount} on {date}", + "renewsAtAmount": "Renews at {amount}", + "creditsKept": "Existing credits are kept", + "creditsOverlap": "This month's credits stay valid until {date}", + "keepUntil": "You'll keep {plan} until {date}", + "zeroDue": "You won't be charged today. Your payment method renews the plan at {amount} on {date}." + } } } }, @@ -304,7 +416,8 @@ "INVALID_PLAN": "That link names a plan we can't read.", "INVALID_CORRELATION_ID": "That link carries a reference we can't read.", "INVALID_WORKSPACE_ID": "That link names a workspace we can't read.", - "INVALID_TEAM_CREDIT_STOP_ID": "That link names a credit amount we can't read." + "INVALID_TEAM_CREDIT_STOP_ID": "That link names a credit amount we can't read.", + "INVALID_PROMOTION_CODE": "That link carries a promo code we can't read." }, "failure": { "unknown": "Something went wrong. Please try again.", diff --git a/apps/billing-web/src/views/CheckoutRouteView.test.ts b/apps/billing-web/src/views/CheckoutRouteView.test.ts index 8f028126ac3..8a3b5aa0e2f 100644 --- a/apps/billing-web/src/views/CheckoutRouteView.test.ts +++ b/apps/billing-web/src/views/CheckoutRouteView.test.ts @@ -3,6 +3,7 @@ import { nextTick } from 'vue' import type { CheckoutUiVariant } from '@/config/checkoutUi' import { awaitCheckoutUiVariant } from '@/config/checkoutUi' +import { recordBillingEntry } from '@/entry/billingEntry' import { createBillingI18n } from '@/i18n' import CheckoutRouteView from '@/views/CheckoutRouteView.vue' @@ -22,6 +23,13 @@ vi.mock(import('@/views/FullPageCheckoutView.vue'), async () => { } }) +vi.mock(import('@/views/EntryErrorView.vue'), async () => { + const { defineComponent, h } = await import('vue') + return { + default: defineComponent({ render: () => h('h1', 'Entry error') }) + } +}) + const HEADINGS: Record = { embedded: 'Embedded checkout', full_page: 'Full-page checkout' @@ -32,6 +40,10 @@ function renderRoute() { } describe('CheckoutRouteView', () => { + beforeEach(() => { + recordBillingEntry(undefined) + }) + it('shows only the loading frame until the variant is known', async () => { vi.mocked(awaitCheckoutUiVariant).mockReturnValue( new Promise(() => undefined) @@ -61,4 +73,20 @@ describe('CheckoutRouteView', () => { expect(screen.queryByText('Loading…')).not.toBeInTheDocument() } ) + + it.for<{ variant: CheckoutUiVariant; heading: string }>([ + { variant: 'embedded', heading: 'Entry error' }, + { variant: 'full_page', heading: 'Full-page checkout' } + ])( + 'explains an unreadable checkout link as $heading on the $variant checkout', + async ({ variant, heading }) => { + recordBillingEntry({ status: 'error', code: 'INVALID_PLAN' }) + vi.mocked(awaitCheckoutUiVariant).mockResolvedValue(variant) + renderRoute() + + expect( + await screen.findByRole('heading', { name: heading }) + ).toBeInTheDocument() + } + ) }) diff --git a/apps/billing-web/src/views/CheckoutRouteView.vue b/apps/billing-web/src/views/CheckoutRouteView.vue index ae79d1c90a7..fdbe728668f 100644 --- a/apps/billing-web/src/views/CheckoutRouteView.vue +++ b/apps/billing-web/src/views/CheckoutRouteView.vue @@ -4,10 +4,13 @@ import { useI18n } from 'vue-i18n' import type { CheckoutUiState } from '@/config/checkoutUi' import { awaitCheckoutUiVariant, settleCheckoutUi } from '@/config/checkoutUi' +import { useBillingEntry } from '@/entry/billingEntry' import CheckoutView from '@/views/CheckoutView.vue' +import EntryErrorView from '@/views/EntryErrorView.vue' import FullPageCheckoutView from '@/views/FullPageCheckoutView.vue' const { t } = useI18n() +const { error: unreadableLink } = useBillingEntry() const state = shallowRef({ phase: 'resolving' }) void awaitCheckoutUiVariant().then((variant) => { @@ -19,6 +22,7 @@ void awaitCheckoutUiVariant().then((variant) => { +
{ /** The provider form is covered in its package; here it reports phases and hands back a token. */ const form = vi.hoisted(() => ({ mounts: 0, - emit: (() => {}) as (event: string, payload: unknown) => void + emit: (() => {}) as (event: string, ...payload: unknown[]) => void, + locked: (): boolean => false })) vi.mock(import('@comfyorg/account-ui/billing/stripe'), async () => { @@ -125,21 +130,23 @@ vi.mock(import('@comfyorg/account-ui/billing/stripe'), async () => { name: 'StripePaymentForm', props: { canSubmit: { type: Boolean, default: true }, - isLoading: { type: Boolean, default: false } + isLoading: { type: Boolean, default: false }, + locked: { type: Boolean, default: false } }, emits: ['confirm', 'phase'], setup( - props: { canSubmit: boolean; isLoading: boolean }, + props: { canSubmit: boolean; isLoading: boolean; locked: boolean }, { emit, slots }: { - emit: (event: string, payload: unknown) => void + emit: (event: string, ...payload: unknown[]) => void slots: { submit?: (slotProps: Record) => VNode[] } } ) { form.mounts += 1 form.emit = emit + form.locked = () => props.locked return () => h( 'div', @@ -241,7 +248,7 @@ describe('FullPageCheckoutView', () => { value: previewOf({ transition_type: 'upgrade' }) } }) - await screen.findByText('Subscribe to Creator Plan · Acme Team') + await screen.findByText('Upgrade to Creator Plan · Acme Team') expect(form.mounts).toBe(0) await userEvent.click(payButton()) @@ -328,19 +335,18 @@ describe('FullPageCheckoutView', () => { value: previewOf({ transition_type: 'upgrade' }) } }) - await screen.findByText('Subscribe to Creator Plan · Acme Team') + await screen.findByText('Upgrade to Creator Plan · Acme Team') expect(payButton()).toBeEnabled() fake.publishOperation(pendingOperation()) - expect(await screen.findByRole('status')).toHaveTextContent( - 'Finishing your payment…' + await screen.findByTestId('checkout-waiting') + expect(screen.getByRole('status')).toHaveTextContent( + "This payment is already processing and can't be canceled." ) + expect(payButton()).toBeDisabled() expect( - screen.queryByRole('button', { name: 'Pay and subscribe' }) - ).not.toBeInTheDocument() - expect( - screen.getByText('Subscribe to Creator Plan · Acme Team') + screen.getByText('Upgrade to Creator Plan · Acme Team') ).toBeInTheDocument() }) @@ -369,10 +375,13 @@ describe('FullPageCheckoutView', () => { await renderCheckout(options, arrange) expect( - await screen.findByText( - "We couldn't reach the billing service. Please try again." - ) + await screen.findByRole('heading', { + name: "Couldn't load your checkout" + }) ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'REQUEST_FAILED' + ) expect( screen.queryByRole('button', { name: 'Pay and subscribe' }) ).not.toBeInTheDocument() @@ -383,10 +392,12 @@ describe('FullPageCheckoutView', () => { await renderCheckout({ capabilities: {} }) expect( - await screen.findByRole('heading', { - name: "You can't subscribe from this account" - }) + await screen.findByRole('heading', { name: 'Checkout not available' }) ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'UNSPECIFIED' + ) + expect(screen.getByRole('link', { name: 'Contact support' })).toBeVisible() expect( screen.queryByRole('button', { name: 'Pay and subscribe' }) ).not.toBeInTheDocument() @@ -419,6 +430,101 @@ describe('FullPageCheckoutView', () => { expect(assign).toHaveBeenCalledWith(href) }) + + it.for<{ name: string; serverCode: string; heading: string }>([ + { + name: 'a plan the catalog lacks is Plan not available', + serverCode: 'INVALID_PLAN', + heading: "This plan isn't available" + }, + { + name: 'any other refused quote is a load failure', + serverCode: 'TRANSITION_NOT_ALLOWED', + heading: "Couldn't load your checkout" + } + ])('$name', async ({ serverCode, heading }) => { + await renderCheckout({ + preview: { + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 400, + serverCode: readBillingErrorCode({ code: serverCode, message: 'no' }) + } + }) + + expect( + await screen.findByRole('heading', { name: heading }) + ).toBeInTheDocument() + expect(form.mounts).toBe(0) + }) + + it.for<{ + name: string + path: string + options: FakeBillingClientOptions + code: string + plans: string + }>([ + { + name: 'a retired plan', + path: CHECKOUT_PATH, + options: { + preview: { + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 400, + serverCode: readBillingErrorCode({ + code: 'INVALID_PLAN', + message: 'no' + }) + } + }, + code: 'PLAN_NOT_FOUND', + plans: 'https://testcloud.comfy.org/?pricing=1&workspace=ws-team' + }, + { + name: 'a team plan named without its commit stop', + path: '/v1/checkout?product=comfyui&return_to=comfyui_workspace&plan=team_per_credit_monthly', + options: { + preview: { + status: 'ok', + value: previewOf({ + new_plan: { ...previewOf().new_plan, tier: 'TEAM' } + }) + } + }, + code: 'CHECKOUT_LINK_INVALID', + plans: 'https://testcloud.comfy.org/?pricing=team&workspace=ws-team' + }, + { + name: 'a link the contract cannot read', + path: '/v1/checkout?product=comfyui&return_to=comfyui_workspace&plan=creator/monthly', + options: {}, + code: 'CHECKOUT_LINK_INVALID', + plans: 'https://testcloud.comfy.org/?pricing=1&workspace=ws-team' + } + ])( + '$name is Plan not available, coded for support, and View plans opens the live catalog', + async ({ path, options, code, plans }) => { + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + const fake = await renderCheckout(options, () => {}, path) + + expect( + await screen.findByRole('heading', { + name: "This plan isn't available" + }) + ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent(code) + expect(form.mounts).toBe(0) + expect(fake.subscribe).not.toHaveBeenCalled() + + await userEvent.click(screen.getByRole('button', { name: 'View plans' })) + + expect(assign).toHaveBeenCalledWith(plans) + } + ) }) const VISA: SavedPaymentMethod = { @@ -670,22 +776,25 @@ describe('FullPageCheckoutView outcomes after Pay', () => { code: 'OPERATION_ALREADY_PENDING' | 'CONFLICT' found: BillingOperationState lands: string + pay: 'disabled' | 'absent' }>([ { name: 'an operation already pending, still in flight', code: 'OPERATION_ALREADY_PENDING', found: pendingOperation('op_elsewhere'), - lands: 'Finishing your payment…' + lands: "This payment is already processing and can't be canceled.", + pay: 'disabled' }, { name: 'a server conflict over a payment that went through', code: 'CONFLICT', found: succeededOperation('op_elsewhere'), - lands: 'Already completed' + lands: 'Already completed', + pay: 'absent' } ])( 'never shows a decline for $name: it re-reads the operation and lands on it', - async ({ code, found, lands }) => { + async ({ code, found, lands, pay }) => { const fake = await payReady({ subscribe: { status: 'error', code } }) fake.recover.mockImplementationOnce(async () => { fake.publishOperation(found) @@ -698,9 +807,9 @@ describe('FullPageCheckoutView outcomes after Pay', () => { expect(fake.subscribe).toHaveBeenCalledOnce() expect(fake.recover).toHaveBeenCalledTimes(2) expect(screen.queryByRole('alert')).not.toBeInTheDocument() - expect( - screen.queryByRole('button', { name: 'Pay and subscribe' }) - ).not.toBeInTheDocument() + const button = screen.queryByRole('button', { name: 'Pay and subscribe' }) + if (pay === 'absent') expect(button).not.toBeInTheDocument() + else expect(button).toBeDisabled() expect( screen.queryByRole('link', { name: 'Contact support' }) ).not.toBeInTheDocument() @@ -733,22 +842,101 @@ describe('FullPageCheckoutView outcomes after Pay', () => { await screen.findByRole('heading', { name: "You're all set" }) ).toBeInTheDocument() expect( - screen.getByText( - 'Your Creator Plan subscription for Acme Team is active.' - ) + screen.getByText('Your plan for Acme Team has been successfully updated.') ).toBeInTheDocument() - expect(screen.queryByText(/Reference:/)).not.toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-plan')).toHaveTextContent( + 'Creator$28.00 USD / mo' + ) + expect(screen.queryByTestId('checkout-ending-code')).not.toBeInTheDocument() expect(fake.subscribe).toHaveBeenCalledOnce() }) + describe('Close', () => { + const SETTLED: FakeBillingClientOptions = { + subscribe: { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation('op_mine') } + } + } + + afterEach(() => { + Reflect.deleteProperty(window, 'opener') + }) + + it('goes back to return_to with the outcome and reference when no script opened the tab', async () => { + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + const close = vi.spyOn(window, 'close').mockImplementation(() => {}) + await payReady(SETTLED) + form.emit('confirm', 'ctoken_1') + + await userEvent.click( + await screen.findByRole('button', { name: 'Close' }) + ) + + expect(close).not.toHaveBeenCalled() + expect(assign).toHaveBeenCalledOnce() + expect(parseReturnResult(String(assign.mock.calls[0][0]))).toEqual({ + result: 'success', + reference: 'op_mine' + }) + }) + + it("goes to the workspace's Plan & Credits settings when this family has no destination for return_to", async () => { + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + await renderCheckout( + SETTLED, + () => {}, + '/v1/checkout?product=comfyui&return_to=platform_account&plan=creator_monthly' + ) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + await waitFor(() => expect(payButton()).toBeEnabled()) + form.emit('confirm', 'ctoken_1') + + await userEvent.click( + await screen.findByRole('button', { name: 'Close' }) + ) + + expect(assign).toHaveBeenCalledWith( + 'https://testcloud.comfy.org/?settings=plan-credits&workspace=ws-team' + ) + }) + + it('closes a tab a script opened, and navigates nowhere', async () => { + Object.defineProperty(window, 'opener', { + value: {}, + configurable: true + }) + const assign = vi + .spyOn(window.location, 'assign') + .mockImplementation(() => {}) + const close = vi.spyOn(window, 'close').mockImplementation(() => {}) + await payReady(SETTLED) + form.emit('confirm', 'ctoken_1') + + await userEvent.click( + await screen.findByRole('button', { name: 'Close' }) + ) + + expect(close).toHaveBeenCalledOnce() + expect(assign).not.toHaveBeenCalled() + }) + }) + it('lands on the terminal for a plan the server activated with no operation to follow', async () => { - await payReady({ + await renderCheckout({ preview: { status: 'ok', value: previewOf({ transition_type: 'upgrade' }) }, subscribe: { status: 'ok', value: { phase: 'succeeded' } } }) + await screen.findByText('Upgrade to Creator Plan · Acme Team') + await waitFor(() => expect(payButton()).toBeEnabled()) await userEvent.click(payButton()) @@ -781,6 +969,9 @@ describe('FullPageCheckoutView outcomes after Pay', () => { expect(fake.previewSubscribe).toHaveBeenCalledTimes(2) expect(form.mounts).toBe(1) expect(payButton()).toBeEnabled() + expect( + screen.queryByRole('link', { name: 'Contact support' }) + ).not.toBeInTheDocument() }) it('553-9297: a plan change on a plan set to end asks to keep it; Pay without the tick sends nothing, with it sends the consent', async () => { @@ -804,7 +995,7 @@ describe('FullPageCheckoutView outcomes after Pay', () => { cancel_at: '2026-07-28T00:00:00.000Z' } }) - await screen.findByText('Subscribe to Creator Plan · Acme Team') + await screen.findByText('Upgrade to Creator Plan · Acme Team') expect( await screen.findByText('Your plan was set to end on July 28, 2026') @@ -889,7 +1080,7 @@ describe('FullPageCheckoutView outcomes after Pay', () => { subscribe: { status: 'error', code: 'REACTIVATION_CONFIRMATION_REQUIRED' } } ])( - 'leaves no Pay over the refused price when re-quoting $name fails', + 'leaves no Pay over the refused price when re-quoting $name fails, and Try again prices again in place', async ({ subscribe }) => { const fake = await payReady({ subscribe }) fake.previewSubscribe.mockResolvedValueOnce({ @@ -900,20 +1091,37 @@ describe('FullPageCheckoutView outcomes after Pay', () => { form.emit('confirm', 'ctoken_1') expect( - await screen.findByText( - "We couldn't reach the billing service. Please try again." - ) + await screen.findByRole('heading', { + name: "Couldn't load your checkout" + }) ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'REQUEST_FAILED' + ) expect(fake.previewSubscribe).toHaveBeenCalledTimes(2) expect(fake.subscribe).toHaveBeenCalledOnce() expect( screen.queryByRole('button', { name: 'Pay and subscribe' }) ).not.toBeInTheDocument() + + await userEvent.click(screen.getByRole('button', { name: 'Try again' })) + + expect( + await screen.findByText('Subscribe to Creator Plan · Acme Team') + ).toBeInTheDocument() + expect(fake.previewSubscribe).toHaveBeenCalledTimes(3) + expect(fake.subscribe).toHaveBeenCalledOnce() } ) }) -const waitingStatus = () => screen.findByRole('status') +const waitingStatus = () => screen.findByTestId('checkout-waiting') + +const settlingOperation = (id: string): PendingBillingOperation => ({ + ...pendingOperation(id), + authenticationState: 'processing', + serverPhase: 'in_progress' +}) /** Every read the capture needs has answered by the next macrotask. */ const capturePromisesFlushed = () => @@ -955,14 +1163,15 @@ describe('FullPageCheckoutView mount reconciliation', () => { recover: { status: 'ok', value: pendingOperation('op_reloaded') } }) - expect(await waitingStatus()).toHaveTextContent('Finishing your payment…') + await waitingStatus() + expect(screen.getByRole('status')).toHaveTextContent( + "This payment is already processing and can't be canceled." + ) expect( screen.getByText('Subscribe to Creator Plan · Acme Team') ).toBeInTheDocument() expect(form.mounts).toBe(0) - expect( - screen.queryByRole('button', { name: 'Pay and subscribe' }) - ).not.toBeInTheDocument() + expect(payButton()).toBeDisabled() fake.publishOperation(succeededOperation('op_reloaded')) @@ -974,8 +1183,10 @@ describe('FullPageCheckoutView mount reconciliation', () => { "This payment for Acme Team already went through. You won't be charged again." ) ).toBeInTheDocument() - expect(screen.getByText('Reference: op_reloaded')).toBeInTheDocument() - expect(screen.queryByText(/Creator Plan/)).not.toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'op_reloaded' + ) + expect(screen.queryByTestId('checkout-ending-plan')).not.toBeInTheDocument() expect(form.mounts).toBe(0) }) @@ -1014,7 +1225,7 @@ describe('FullPageCheckoutView mount reconciliation', () => { reportPhase({ phase: 'payment_element_ready', element: 'payment' }) await waitFor(() => expect(payButton()).toBeEnabled()) - expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(screen.queryByTestId('checkout-waiting')).not.toBeInTheDocument() form.emit('confirm', 'ctoken_1') await waitFor(() => expect(fake.subscribe).toHaveBeenCalledOnce()) @@ -1062,18 +1273,95 @@ describe('FullPageCheckoutView mount reconciliation', () => { expect(form.mounts).toBe(1) }) - it('says so instead of a form when the recovery itself fails', async () => { - await renderCheckout({ + it('says so instead of a form when the recovery itself fails, and Try again resolves again in place', async () => { + const fake = await renderCheckout({ recover: { status: 'error', code: 'REQUEST_FAILED' } }) expect( - await screen.findByText( - "We couldn't reach the billing service. Please try again." - ) + await screen.findByRole('heading', { + name: "Couldn't load your checkout" + }) ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'REQUEST_FAILED' + ) expect(form.mounts).toBe(0) + + fake.recover.mockResolvedValue({ status: 'ok', value: undefined }) + await userEvent.click(screen.getByRole('button', { name: 'Try again' })) + + expect( + await screen.findByText('Subscribe to Creator Plan · Acme Team') + ).toBeInTheDocument() + expect(fake.recover).toHaveBeenCalledTimes(2) + expect(fake.previewSubscribe).toHaveBeenCalledTimes(2) + expect(form.mounts).toBe(1) }) + + it('renders Payment in progress for a capture the bank is still settling, then follows it to a card-less success', async () => { + const fake = await renderCheckout({ + recover: { status: 'ok', value: settlingOperation('op_bank') } + }) + + expect( + await screen.findByRole('heading', { name: 'Payment in progress' }) + ).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'op_bank' + ) + expect(screen.getByRole('link', { name: 'Contact support' })).toBeVisible() + expect( + screen.queryByRole('button', { name: 'Close' }) + ).not.toBeInTheDocument() + expect(form.mounts).toBe(0) + + fake.publishOperation({ + ...settlingOperation('op_bank'), + authenticationState: 'succeeded' + }) + expect( + await screen.findByRole('heading', { name: 'Payment received' }) + ).toBeInTheDocument() + + fake.publishOperation(succeededOperation('op_bank')) + expect( + await screen.findByRole('heading', { name: "You're all set" }) + ).toBeInTheDocument() + expect(fake.subscribe).not.toHaveBeenCalled() + }) + + it.for<{ name: string; watched: PendingBillingOperation; heading: string }>([ + { + name: 'a settling capture keeps Payment in progress', + watched: settlingOperation('op_lapsed'), + heading: 'Payment in progress' + }, + { + name: 'money still being verified says it could not confirm', + watched: pendingOperation('op_lapsed'), + heading: "We couldn't confirm your payment" + } + ])( + 'follows a watch whose poll budget ran out afresh: $name', + async ({ watched, heading }) => { + const fake = await renderCheckout({ + recover: { status: 'ok', value: watched } + }) + await waitFor(() => expect(fake.recover).toHaveBeenCalledOnce()) + + fake.publishOperation({ + ...succeededOperation('op_lapsed'), + phase: 'timed_out' + }) + + expect( + await screen.findByRole('heading', { name: heading }) + ).toBeInTheDocument() + await waitFor(() => expect(fake.recover).toHaveBeenCalledTimes(2)) + expect(form.mounts).toBe(0) + } + ) }) function pageShow(persisted: boolean): Event { @@ -1099,9 +1387,7 @@ describe('FullPageCheckoutView re-reconciliation', () => { expect(await waitingStatus()).toBeInTheDocument() expect(fake.recover).toHaveBeenCalledTimes(2) - expect( - screen.queryByRole('button', { name: 'Pay and subscribe' }) - ).not.toBeInTheDocument() + expect(payButton()).toBeDisabled() }) it('leaves a fresh navigation alone', async () => { @@ -1134,7 +1420,7 @@ describe('FullPageCheckoutView re-reconciliation', () => { answerFirst({ status: 'ok', value: undefined }) await capturePromisesFlushed() - expect(screen.getByRole('status')).toBeInTheDocument() + expect(screen.getByTestId('checkout-waiting')).toBeInTheDocument() expect(form.mounts).toBe(0) }) @@ -1166,7 +1452,9 @@ describe('FullPageCheckoutView re-reconciliation', () => { expect( await screen.findByRole('heading', { name: 'Already completed' }) ).toBeInTheDocument() - expect(screen.getByText('Reference: op_from_server')).toBeInTheDocument() + expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent( + 'op_from_server' + ) expect(fake.recover).toHaveBeenCalledTimes(2) }) @@ -1213,3 +1501,469 @@ describe('FullPageCheckoutView re-reconciliation', () => { expect(siblings.published).toEqual([]) }) }) + +const challengedOperation = ( + id: string, + status: 'required' | 'in_progress' +): PendingBillingOperation => ({ + ...pendingOperation(id), + authenticationState: 'requires_action', + challenge: { clientSecret: 'cs', status } +}) + +const PHASE_A = 'Nothing has been charged yet.' +const PHASE_B = "This payment is already processing and can't be canceled." +const ALIPAY = + 'Taking you to Alipay to finish paying. Nothing has been charged yet.' + +const footnote = () => screen.getByTestId('checkout-phase-footnote') + +/** A Pay whose subscribe never answers, so the page follows only what the lifecycle publishes. */ +async function payHeld(methodType?: string) { + const fake = await payReady() + fake.subscribe.mockImplementation(() => new Promise(() => {})) + form.emit('confirm', 'ctoken_1', methodType) + await waitFor(() => expect(fake.subscribe).toHaveBeenCalledOnce()) + return fake +} + +describe('FullPageCheckoutView payment authentication', () => { + beforeEach(() => { + form.mounts = 0 + }) + + it('locks its own Pay through a challenge, then processing, then lands on the success', async () => { + const fake = await payReady() + expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument() + fake.subscribe.mockImplementation(() => new Promise(() => {})) + form.emit('confirm', 'ctoken_1') + + fake.publishOperation(challengedOperation('op_3ds', 'in_progress')) + + await waitFor(() => expect(footnote()).toHaveTextContent(PHASE_A)) + expect(payButton()).toBeDisabled() + expect(payButton()).toHaveAttribute('aria-busy', 'true') + expect(form.locked()).toBe(true) + expect( + screen.queryByRole('button', { name: 'Back' }) + ).not.toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Cancel payment' }) + ).not.toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Continue verification' }) + ).not.toBeInTheDocument() + + fake.publishOperation({ + ...pendingOperation('op_3ds'), + authenticationState: 'processing' + }) + + await waitFor(() => expect(footnote()).toHaveTextContent(PHASE_B)) + expect(payButton()).toBeDisabled() + + fake.publishOperation(succeededOperation('op_3ds')) + + expect( + await screen.findByRole('heading', { name: "You're all set" }) + ).toBeInTheDocument() + }) + + it('makes the payment tabs inert while its own Pay is in flight', async () => { + const fake = await renderQuoted({ + paymentMethods: { status: 'ok', value: [VISA] } + }) + fake.subscribe.mockImplementation(() => new Promise(() => {})) + expect(screen.getByRole('tablist')).not.toHaveAttribute('inert') + + await userEvent.click(payButton()) + + await waitFor(() => expect(footnote()).toHaveTextContent(PHASE_B)) + expect(screen.getByRole('tablist')).toHaveAttribute('inert') + }) + + it('puts a challenge the bank refused on its card and frees Pay for the retry, on the same form', async () => { + const fake = await payHeld() + fake.publishOperation(challengedOperation('op_3ds', 'in_progress')) + await waitFor(() => expect(footnote()).toHaveTextContent(PHASE_A)) + + fake.publishOperation({ + ...pendingOperation('op_3ds'), + authenticationState: 'failed_retryable', + challenge: { clientSecret: 'cs', status: 'failed' } + }) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Payment not completed' + ) + await waitFor(() => expect(payButton()).toBeEnabled()) + expect(footnote()).toBeEmptyDOMElement() + expect(form.locked()).toBe(false) + expect(form.mounts).toBe(1) + + form.emit('confirm', 'ctoken_2') + + await waitFor(() => expect(fake.subscribe).toHaveBeenCalledTimes(2)) + expect(fake.subscribe.mock.calls[1][0]).toMatchObject({ + confirmation_token: 'ctoken_2' + }) + }) + + it.for<{ + name: string + methodType: string + sent: string + challenged: string + }>([ + { + name: 'an Alipay Pay names where it is going, even over a challenge', + methodType: 'alipay', + sent: ALIPAY, + challenged: ALIPAY + }, + { + name: 'a card Pay is processing until the bank asks for a challenge', + methodType: 'card', + sent: PHASE_B, + challenged: PHASE_A + } + ])('$name', async ({ methodType, sent, challenged }) => { + const fake = await payHeld(methodType) + + await waitFor(() => expect(footnote()).toHaveTextContent(sent)) + + fake.publishOperation(challengedOperation('op_3ds', 'in_progress')) + + await waitFor(() => expect(footnote()).toHaveTextContent(challenged)) + }) + + it('offers Continue verification after a reload mid-challenge, and drives the challenge again on click', async () => { + const fake = await renderCheckout({ + recover: { + status: 'ok', + value: challengedOperation('op_reload', 'required') + } + }) + + await waitFor(() => expect(footnote()).toHaveTextContent(PHASE_A)) + expect(payButton()).toBeDisabled() + expect( + screen.queryByRole('button', { name: 'Back' }) + ).not.toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Cancel payment' }) + ).not.toBeInTheDocument() + await capturePromisesFlushed() + fake.reportChallengeStarted.mockClear() + fake.reportChallengeSettled.mockClear() + + await userEvent.click( + screen.getByRole('button', { name: 'Continue verification' }) + ) + + expect(fake.reportChallengeStarted).toHaveBeenCalledExactlyOnceWith( + 'op_reload' + ) + await waitFor(() => + expect(fake.reportChallengeSettled).toHaveBeenCalledExactlyOnceWith( + 'op_reload', + 'completed' + ) + ) + }) + + it('returns a challenge to this checkout, not the result page', async () => { + const fake = await payHeld() + + const request = fake.subscribe.mock.calls[0][0] + expect(request.return_url).toContain('/v1/checkout') + expect(request.return_url).not.toContain('/v1/result') + }) +}) + +const LAUNCH20_QUOTE = previewOf({ + quote_id: 'q_promo', + amount_due_cents: 2240, + promotion_code: 'LAUNCH20', + discounts: [{ kind: 'promotion', code: 'LAUNCH20', amount_off_cents: 560 }] +}) + +function refusedWith(serverCode: string): PreviewSubscribeResult { + return { + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 400, + serverCode: readBillingErrorCode({ code: serverCode, message: 'refused' }) + } +} + +/** Answers a quote by the code it was asked for: none, LAUNCH20, or anything else. */ +function quotesByCode( + fake: FakeBillingClient, + launch20: PreviewSubscribeResult = { status: 'ok', value: LAUNCH20_QUOTE } +) { + fake.previewSubscribe.mockImplementation(async ({ promotionCode }) => { + if (promotionCode === undefined) + return { status: 'ok', value: previewOf({ quote_id: 'q_1' }) } + return promotionCode.toUpperCase() === 'LAUNCH20' + ? launch20 + : refusedWith('PROMOTION_CODE_INVALID') + }) +} + +const promoField = () => screen.getByRole('textbox', { name: 'Promo code' }) +const orderSummary = () => screen.getByRole('region', { name: 'Order summary' }) + +async function enterCode(code: string) { + await userEvent.click(screen.getByRole('button', { name: 'Add promo code' })) + await userEvent.type(promoField(), code) + await userEvent.click(screen.getByRole('button', { name: 'Apply' })) +} + +describe('FullPageCheckoutView promo codes', () => { + beforeEach(() => { + form.mounts = 0 + }) + + it('applies a code: its row, its removable chip, the new total, and Pay binds the code', async () => { + const fake = await renderCheckout({}, quotesByCode) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + + await enterCode('launch20') + + expect(await screen.findByText('Promo code')).toBeInTheDocument() + expect(screen.getByText('−$5.60')).toBeInTheDocument() + expect(screen.getAllByText('$22.40')).toHaveLength(2) + expect( + screen.getByRole('button', { name: 'Remove LAUNCH20' }) + ).toBeEnabled() + expect( + screen.queryByRole('button', { name: 'Add promo code' }) + ).not.toBeInTheDocument() + expect(fake.previewSubscribe).toHaveBeenLastCalledWith( + expect.objectContaining({ promotionCode: 'launch20' }), + expect.anything() + ) + + await waitFor(() => expect(payButton()).toBeEnabled()) + form.emit('confirm', 'ctoken_1') + await waitFor(() => + expect(fake.subscribe).toHaveBeenCalledWith( + expect.objectContaining({ + promotion_code: 'LAUNCH20', + quote_id: 'q_promo' + }) + ) + ) + }) + + it('removing the chip re-quotes without the code', async () => { + const fake = await renderCheckout({}, quotesByCode) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + await enterCode('LAUNCH20') + await screen.findByText('−$5.60') + + await userEvent.click( + screen.getByRole('button', { name: 'Remove LAUNCH20' }) + ) + + expect( + await screen.findByRole('button', { name: 'Add promo code' }) + ).toBeInTheDocument() + expect(screen.queryByText('−$5.60')).not.toBeInTheDocument() + expect(screen.getAllByText('$28.00')).toHaveLength(2) + expect(fake.previewSubscribe).toHaveBeenLastCalledWith( + expect.not.objectContaining({ promotionCode: expect.anything() }), + expect.anything() + ) + }) + + it('says an invalid code under the field, keeps it typed, and leaves the total alone', async () => { + await renderCheckout({}, quotesByCode) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + + await enterCode('NOPE') + + expect(await screen.findByRole('alert')).toHaveTextContent( + "This code isn't valid." + ) + expect(promoField()).toHaveValue('NOPE') + expect(promoField()).toHaveAttribute('aria-invalid', 'true') + expect(screen.getAllByText('$28.00')).toHaveLength(2) + expect(screen.queryByText('Promo code')).not.toBeInTheDocument() + }) + + it('prefills a code from the URL without pricing it until Apply', async () => { + const fake = await renderCheckout( + {}, + quotesByCode, + `${CHECKOUT_PATH}&promo=LAUNCH20` + ) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + + expect(promoField()).toHaveValue('LAUNCH20') + expect(screen.getAllByText('$28.00')).toHaveLength(2) + expect(fake.previewSubscribe).toHaveBeenCalledOnce() + expect(fake.previewSubscribe).toHaveBeenCalledWith( + expect.not.objectContaining({ promotionCode: expect.anything() }), + expect.anything() + ) + + await userEvent.click(screen.getByRole('button', { name: 'Apply' })) + expect(await screen.findByText('−$5.60')).toBeInTheDocument() + }) + + it('lets the URL prefill be removed before it is applied', async () => { + await renderCheckout({}, quotesByCode, `${CHECKOUT_PATH}&promo=LAUNCH20`) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + + await userEvent.click( + screen.getByRole('button', { name: 'Close promo code' }) + ) + + expect( + screen.getByRole('button', { name: 'Add promo code' }) + ).toBeInTheDocument() + expect( + screen.queryByRole('textbox', { name: 'Promo code' }) + ).not.toBeInTheDocument() + }) + + it('a code that lapsed before Pay: back to capture, chip gone, the expired card instead of a decline', async () => { + const fake = await renderCheckout( + { + subscribe: { + status: 'error', + code: 'REQUEST_FAILED', + serverCode: readBillingErrorCode({ + code: 'SUBSCRIPTION_QUOTE_STALE', + message: 'stale' + }) + } + }, + quotesByCode + ) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + await enterCode('LAUNCH20') + await screen.findByText('−$5.60') + quotesByCode(fake, refusedWith('PROMOTION_CODE_INVALID')) + + form.emit('confirm', 'ctoken_1') + + const card = await screen.findByRole('alert') + expect(card).toHaveTextContent('Your promo code expired') + expect(card).toHaveTextContent( + 'The LAUNCH20 code expired, so the total was updated.' + ) + expect(card).not.toHaveTextContent('declined') + expect( + screen.queryByRole('button', { name: 'Remove LAUNCH20' }) + ).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Add promo code' })).toBeEnabled() + expect(screen.getAllByText('$28.00')).toHaveLength(2) + expect(payButton()).toBeEnabled() + expect( + screen.queryByRole('link', { name: 'Contact support' }) + ).not.toBeInTheDocument() + }) + + it('locks promo entry from the Pay click until the attempt resolves', async () => { + let settle: () => void = () => {} + const fake = await renderCheckout({}, (scripted) => { + quotesByCode(scripted) + scripted.subscribe.mockImplementation( + () => + new Promise((resolve) => { + settle = () => + resolve({ + status: 'ok', + value: { + phase: 'failed', + operation: failedOperation('card_declined') + } + }) + }) + ) + }) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + await waitFor(() => expect(payButton()).toBeEnabled()) + + form.emit('confirm', 'ctoken_1') + + await waitFor(() => expect(fake.subscribe).toHaveBeenCalledOnce()) + expect( + screen.getByRole('button', { name: 'Add promo code' }) + ).toBeDisabled() + + settle() + + await waitFor(() => + expect( + screen.getByRole('button', { name: 'Add promo code' }) + ).toBeEnabled() + ) + }) + + it('holds Pay while a code is being priced, so the old total cannot be charged', async () => { + let answer: (result: PreviewSubscribeResult) => void = () => {} + const fake = await renderCheckout({}, quotesByCode) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + await waitFor(() => expect(payButton()).toBeEnabled()) + fake.previewSubscribe.mockImplementationOnce( + () => new Promise((resolve) => (answer = resolve)) + ) + + await enterCode('LAUNCH20') + + expect(payButton()).toBeDisabled() + expect(orderSummary()).toHaveAttribute('aria-busy', 'true') + answer({ status: 'ok', value: LAUNCH20_QUOTE }) + await waitFor(() => expect(payButton()).toBeEnabled()) + expect(orderSummary()).toHaveAttribute('aria-busy', 'false') + }) + + it('keeps an applied code through a fresh capture after money it was watching declined', async () => { + const fake = await renderCheckout({}, quotesByCode) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + await enterCode('LAUNCH20') + await screen.findByText('−$5.60') + fake.recover.mockImplementationOnce(async () => { + fake.publishOperation(pendingOperation('op_watched')) + return { status: 'ok', value: pendingOperation('op_watched') } + }) + window.dispatchEvent(pageShow(true)) + await screen.findByTestId('checkout-waiting') + + fake.publishOperation(failedOperation('card_declined', 'op_watched')) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Payment declined' + ) + expect(fake.previewSubscribe).toHaveBeenLastCalledWith( + expect.objectContaining({ promotionCode: 'LAUNCH20' }), + expect.anything() + ) + expect(screen.getByText('−$5.60')).toBeInTheDocument() + expect( + screen.getByRole('button', { name: 'Remove LAUNCH20' }) + ).toBeEnabled() + }) + + it('offers no promo entry on a change that charges nothing today', async () => { + await renderCheckout({ + preview: { + status: 'ok', + value: previewOf({ transition_type: 'downgrade', is_immediate: false }) + } + }) + await screen.findByText(/Switch to Creator Plan/) + + expect( + screen.queryByRole('button', { name: 'Add promo code' }) + ).not.toBeInTheDocument() + }) +}) diff --git a/apps/billing-web/src/views/FullPageCheckoutView.vue b/apps/billing-web/src/views/FullPageCheckoutView.vue index 4215e92a0e6..fc1263011d9 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.vue +++ b/apps/billing-web/src/views/FullPageCheckoutView.vue @@ -3,24 +3,31 @@ import { useEventListener } from '@vueuse/core' import { computed } from 'vue' import { useI18n } from 'vue-i18n' -import { formatQuoteMoney } from '@comfyorg/account-ui/billing/checkout' +import { + formatQuoteMoney, + isAnnualDuration +} from '@comfyorg/account-ui/billing/checkout' +import { + PENDING_PAYMENT_CANCEL_AVAILABLE, + isLocked +} from '@/checkout/checkoutPage' +import { endingOf } from '@/checkout/endingScreen' +import type { EndingPlan } from '@/components/fullPage/CheckoutEnding.vue' +import CheckoutEnding from '@/components/fullPage/CheckoutEnding.vue' import type { CheckoutCharge } from '@/components/fullPage/CheckoutPaymentColumn.vue' import CheckoutPaymentColumn from '@/components/fullPage/CheckoutPaymentColumn.vue' -import type { CheckoutSummary } from '@/components/fullPage/CheckoutSummaryColumn.vue' +import { buildSummaryLedger } from '@/checkout/summaryLedger' import CheckoutSummaryColumn from '@/components/fullPage/CheckoutSummaryColumn.vue' import { keepSubscriptionCopy } from '@/checkout/keepSubscription' -import CheckoutTerminalCard from '@/components/fullPage/CheckoutTerminalCard.vue' -import CheckoutWaitingColumn from '@/components/fullPage/CheckoutWaitingColumn.vue' +import PromoCodeEntry from '@/components/fullPage/summary/PromoCodeEntry.vue' import { useFullPageCheckout } from '@/composables/useFullPageCheckout' import { useHostedCopy } from '@/composables/useHostedCopy' import { useBillingWebStripeKey } from '@/config/stripeKey' -import { useBillingEntry } from '@/entry/billingEntry' import { useBillingWebSession } from '@/session/billingWebSession' const { t, locale } = useI18n() const { coded } = useHostedCopy() -const { entry } = useBillingEntry() const { session } = useBillingWebSession() const stripeKey = useBillingWebStripeKey() const { @@ -30,6 +37,9 @@ const { submitting, payFailure, returnLink, + viewPlansLink, + close, + retryLoad, onPaymentPhase, savedMethods, retryElement, @@ -39,7 +49,10 @@ const { confirmReactivation, payWithoutConsent, cancelAt, + promo, + promoLive, pay, + continueVerification, reconcile } = useFullPageCheckout() @@ -55,31 +68,15 @@ const quote = computed(() => : undefined ) -const planName = computed(() => - preview.value === undefined - ? undefined - : t('checkout.fullPage.planName', { - tier: coded('tier', preview.value.new_plan.tier) - }) -) - -const summary = computed(() => { +const ledger = computed(() => { const quoted = quote.value if (!quoted) return undefined - const currency = quoted.currency ?? 'usd' - const money = (cents: number) => - formatQuoteMoney(cents, currency, locale.value) - const plan = planName.value ?? '' - const workspace = session.value?.workspace.name - return { - eyebrow: - workspace === undefined - ? t('checkout.fullPage.eyebrowPlanOnly', { plan }) - : t('checkout.fullPage.eyebrow', { plan, workspace }), - price: money(quoted.new_plan.price_cents), - currency: currency.toUpperCase(), - total: money(quoted.amount_due_cents ?? quoted.cost_today_cents) - } + return buildSummaryLedger(quoted, { + workspace: session.value?.workspace.name, + tierName: (tier) => coded('tier', tier), + t, + locale: locale.value + }) }) const charge = computed(() => { @@ -108,71 +105,91 @@ const payFailureCopy = computed(() => : coded('failure', payFailure.value) ) -const productName = computed(() => coded('product', entry.value?.product)) -const returnLabel = computed(() => - returnLink.value === undefined - ? undefined - : t('hosted.returnTo', { product: productName.value }) -) +const ending = computed(() => endingOf(page.value)) + +const locked = computed(() => isLocked(page.value)) + +/** The server cannot cancel a pending payment yet; the click has nowhere honest to go. */ +function cancelPayment() {} + +/** The plan this page's own Pay bought, as its quote priced it. */ +const endingPlan = computed(() => { + const quoted = preview.value + if (!quoted) return undefined + return { + name: coded('tier', quoted.new_plan.tier), + price: formatQuoteMoney( + quoted.new_plan.price_cents, + quoted.currency ?? 'usd', + locale.value + ), + period: t( + isAnnualDuration(quoted.new_plan.duration) + ? 'checkout.fullPage.ending.perYear' + : 'checkout.fullPage.ending.perMonth', + { currency: (quoted.currency ?? 'usd').toUpperCase() } + ) + } +}) function returnToProduct() { window.location.assign(returnLink.value) } + +function viewPlans() { + window.location.assign(viewPlansLink.value) +}