diff --git a/apps/billing-web/e2e/checkout-ui.spec.ts b/apps/billing-web/e2e/checkout-ui.spec.ts index 0a6c47e28f0..a42b3ecf0ed 100644 --- a/apps/billing-web/e2e/checkout-ui.spec.ts +++ b/apps/billing-web/e2e/checkout-ui.spec.ts @@ -38,11 +38,6 @@ test('with the flag on full_page, checkout is the full-page checkout', async ({ request.authorization === 'Bearer e2e-workspace-jwt' ) ).toBe(true) - expect( - cloud.requests.some( - (request) => request.path === '/billing/preview-subscribe' - ) - ).toBe(false) }) test('when the flag read fails, checkout falls back to the embedded checkout', async ({ diff --git a/apps/billing-web/e2e/fixtures/scenario.ts b/apps/billing-web/e2e/fixtures/scenario.ts index 94fa1b8c303..14919ab666e 100644 --- a/apps/billing-web/e2e/fixtures/scenario.ts +++ b/apps/billing-web/e2e/fixtures/scenario.ts @@ -67,6 +67,11 @@ export function pendingOperation(id: string): BillingOpStatusResponse { return { id, status: 'pending', started_at: new Date().toISOString() } } +/** In flight past the bank's challenge: the charge can no longer be called back. */ +export function processingOperation(id: string): BillingOpStatusResponse { + return { ...pendingOperation(id), authentication_state: 'processing' } +} + export function declinedOperation(id: string): BillingOpStatusResponse { const now = new Date().toISOString() return { diff --git a/apps/billing-web/e2e/fixtures/stripe.ts b/apps/billing-web/e2e/fixtures/stripe.ts index 9eda912ce6d..4b6cb023533 100644 --- a/apps/billing-web/e2e/fixtures/stripe.ts +++ b/apps/billing-web/e2e/fixtures/stripe.ts @@ -2,8 +2,8 @@ * A fake `js.stripe.com` at the network boundary: enough of `window.Stripe` * for `StripePaymentForm` and the embedded-challenge port to run their real * code against, without a request ever reaching Stripe. Elements are inert - * (`mount`/`on`/`destroy` no-ops); `createConfirmationToken` and - * `handleNextAction` always succeed, which is all the current specs need — + * apart from reporting `ready` on the next task; `createConfirmationToken` + * and `handleNextAction` always succeed, which is all the current specs need — * a decline or a timeout is modelled on the mocked Cloud's operation, not * on the payment provider. * @@ -22,12 +22,24 @@ const FAKE_STRIPE_JS = ` // can tell "called correctly" from "called with the wrong secret". nextActionCalls: [] } - function fakeElement() { - return { mount() {}, unmount() {}, destroy() {}, on() {} } + // A spec sets window.__e2eStripeLoadErrors before load to make that many + // payment elements report loaderror instead of ready. + function fakeElement(kind) { + const failing = kind === 'payment' && (window.__e2eStripeLoadErrors ?? 0) > 0 + if (failing) window.__e2eStripeLoadErrors -= 1 + return { + mount() {}, + unmount() {}, + destroy() {}, + on(event, handler) { + if (event === (failing ? 'loaderror' : 'ready')) + setTimeout(() => handler({ error: { code: 'e2e_load_error' } })) + } + } } function fakeElements() { return { - create: () => fakeElement(), + create: (kind) => fakeElement(kind), update: () => Promise.resolve(), submit: () => Promise.resolve({}) } @@ -35,15 +47,48 @@ const FAKE_STRIPE_JS = ` window.Stripe = function fakeStripeFactory() { return { elements: () => fakeElements(), + // A spec sets window.__e2eStripeMethodType before load to mint a + // token for a redirect method such as alipay instead of a card. createConfirmationToken: () => { window.__e2eFakeStripe.confirmationTokens += 1 return Promise.resolve({ - confirmationToken: { id: 'ctok_e2e_fake' } + confirmationToken: { + id: 'ctok_e2e_fake', + payment_method_preview: { + type: window.__e2eStripeMethodType ?? 'card' + } + } }) }, + // The intent's next step as Stripe reports it: an in-page challenge, + // or the redirect a method such as Alipay finishes on. + retrievePaymentIntent: () => + Promise.resolve({ + paymentIntent: { + status: 'requires_action', + next_action: { + type: window.__e2eStripeRedirectTo + ? 'alipay_handle_redirect' + : 'use_stripe_sdk' + } + } + }), + // A spec sets window.__e2eStripeRedirectTo before load to make the + // challenge leave the page the way a redirect method does, or + // window.__e2eStripeHoldNextAction to keep it open until the spec + // settles it through window.__e2eFakeStripe.releaseNextAction. handleNextAction: (args) => { window.__e2eFakeStripe.nextActions += 1 window.__e2eFakeStripe.nextActionCalls.push(args) + if (window.__e2eStripeRedirectTo) { + window.location.assign(window.__e2eStripeRedirectTo) + return new Promise(() => {}) + } + if (window.__e2eStripeHoldNextAction) { + return new Promise((resolve) => { + window.__e2eFakeStripe.releaseNextAction = resolve + }) + } return Promise.resolve({ paymentIntent: { status: 'succeeded' } }) } } diff --git a/apps/billing-web/e2e/full-page-authentication.spec.ts b/apps/billing-web/e2e/full-page-authentication.spec.ts new file mode 100644 index 00000000000..9e9e38aa7af --- /dev/null +++ b/apps/billing-web/e2e/full-page-authentication.spec.ts @@ -0,0 +1,336 @@ +/** + * Everything between Pay and a terminal on the full page: the two submit + * phases, the 3DS challenge and its refusal, a reload while the bank is + * still waiting, and a method that finishes paying on its own site. + */ +import type { Page } from '@playwright/test' + +import type { BillingOpStatusResponse } from '@comfyorg/ingest-types' + +import type { MockCloud } from './fixtures/cloud' +import { PORTAL_URL } from './fixtures/env' +import { + challengeRequiredOperation, + pendingOperation, + succeededOperation +} 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 OPERATION = 'op_subscribe' +const CLIENT_SECRET = 'pi_e2e_secret' +const PHASE_A = 'Nothing has been charged yet.' +const PHASE_B = "This payment is already processing and can't be canceled." +const REDIRECTING = + 'Taking you to Alipay to finish paying. Nothing has been charged yet.' + +const payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const footnote = (page: Page) => page.getByTestId('checkout-phase-footnote') +const backArrow = (page: Page) => page.getByRole('button', { name: 'Back' }) +const completeVerification = (page: Page) => + page.getByRole('button', { name: 'Complete verification' }) +const cancelPayment = (page: Page) => + page.getByRole('button', { name: 'Cancel payment' }) + +/** The operation as the mocked Cloud reports it; a spec moves it on. */ +function scriptOperation(cloud: MockCloud) { + const state = { reply: challengeRequiredOperation(OPERATION, CLIENT_SECRET) } + cloud.reply('GET', `/billing/ops/${OPERATION}`, () => ({ + body: state.reply + })) + return (reply: BillingOpStatusResponse) => { + state.reply = reply + } +} + +const processing = (): BillingOpStatusResponse => ({ + ...challengeRequiredOperation(OPERATION, CLIENT_SECRET), + authentication_state: 'processing' +}) + +function holdChallenge(page: Page) { + return page.addInitScript(() => { + Object.assign(window, { __e2eStripeHoldNextAction: true }) + }) +} + +/** Settles the held challenge the way Stripe would, with the intent's status. */ +function releaseChallenge(page: Page, intentStatus: string) { + return page.evaluate( + `window.__e2eFakeStripe.releaseNextAction({ paymentIntent: { status: '${intentStatus}' } })` + ) +} + +/** Empty until the first challenge, since the fake only loads with the card form. */ +const nextActionCalls = (page: Page): Promise => + page.evaluate('window.__e2eFakeStripe?.nextActionCalls ?? []') + +const subscribeRequests = (cloud: MockCloud) => + cloud.requests.filter((request) => request.path === '/billing/subscribe') + +test('145-4584 → 342-4767: Pay walks Phase A, locked with nothing charged, into Phase B once the bank answers, then to success', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + const moveOperation = scriptOperation(cloud) + await holdChallenge(page) + await signIn(CHECKOUT) + await expect(backArrow(page)).toBeVisible() + await expect(footnote(page)).toHaveText('') + + await payButton(page).click() + + await expect(footnote(page)).toHaveText(PHASE_A) + await expect(footnote(page)).toHaveAttribute('aria-live', 'polite') + await expect(payButton(page)).toBeDisabled() + await expect(backArrow(page)).toBeHidden() + await expect(cancelPayment(page)).toBeHidden() + expect(await nextActionCalls(page)).toEqual([{ clientSecret: CLIENT_SECRET }]) + + await releaseChallenge(page, 'succeeded') + + await expect(footnote(page)).toHaveText(PHASE_B) + await expect(cancelPayment(page)).toBeHidden() + await expect(payButton(page)).toBeDisabled() + + moveOperation(succeededOperation(OPERATION)) + + await expect( + page.getByRole('heading', { name: "You're all set" }) + ).toBeVisible() + expect(subscribeRequests(cloud)).toHaveLength(1) +}) + +test('a card Pay shows only the spinner until the server says which phase it is in', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + const moveOperation = scriptOperation(cloud) + moveOperation(pendingOperation(OPERATION)) + await signIn(CHECKOUT) + + await payButton(page).click() + + await expect(payButton(page)).toHaveAttribute('aria-busy', 'true') + await expect(backArrow(page)).toBeHidden() + await expect(footnote(page)).toHaveText('') + + moveOperation(processing()) + + await expect(footnote(page)).toHaveText(PHASE_B) +}) + +test('a saved-method Pay keeps the tabs and the list inert through Phase A', async ({ + page, + cloud, + signIn +}) => { + scriptOperation(cloud) + await holdChallenge(page) + await signIn(CHECKOUT) + await expect(page.getByRole('tab', { name: 'Saved' })).toBeEnabled() + + await payButton(page).click() + + await expect(footnote(page)).toHaveText(PHASE_A) + await expect(page.getByRole('tablist')).toHaveAttribute('inert', '') + await expect(backArrow(page)).toBeHidden() +}) + +test('314-10555: a challenge the bank refuses lands on capture with Payment not completed, the form still mounted and Pay live', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + scriptOperation(cloud) + await holdChallenge(page) + await signIn(CHECKOUT) + + await payButton(page).click() + await expect(footnote(page)).toHaveText(PHASE_A) + + await releaseChallenge(page, 'requires_action') + + const card = page.getByRole('alert') + await expect(card).toContainText('Payment not completed') + await expect(card).toContainText("you haven't been charged") + await expect(footnote(page)).toHaveText('') + await expect(payButton(page)).toBeEnabled() + await expect(backArrow(page)).toBeVisible() + await expect( + page.getByRole('link', { name: 'Contact support' }) + ).toBeVisible() + await expect( + page.getByRole('heading', { name: "You're all set" }) + ).toBeHidden() + await expect(page).toHaveURL(/\/v1\/checkout\?/) + expect(await nextActionCalls(page)).toHaveLength(1) +}) + +test('a reload during Phase A renders the verify state and re-opens the challenge from the secret the server still holds', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: OPERATION, + pending_billing_op_type: 'subscription', + payment_intent_client_secret: CLIENT_SECRET + } + const moveOperation = scriptOperation(cloud) + await holdChallenge(page) + await signIn(CHECKOUT) + + await expect(footnote(page)).toHaveText(PHASE_A) + await expect(payButton(page)).toBeDisabled() + await expect(backArrow(page)).toBeHidden() + await expect + .poll(() => nextActionCalls(page)) + .toEqual([{ clientSecret: CLIENT_SECRET }]) + expect(subscribeRequests(cloud)).toHaveLength(0) + + await releaseChallenge(page, 'succeeded') + await expect(footnote(page)).toHaveText(PHASE_B) + + moveOperation(succeededOperation(OPERATION)) + await expect( + page.getByRole('heading', { name: 'Already completed' }) + ).toBeVisible() +}) + +test('312-9930: coming back from Alipay without paying stays on the checkout and offers Complete verification instead of sending the customer straight back', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: OPERATION, + pending_billing_op_type: 'subscription', + payment_intent_client_secret: CLIENT_SECRET + } + scriptOperation(cloud) + await page.addInitScript((redirectTo) => { + Object.assign(window, { __e2eStripeRedirectTo: redirectTo }) + }, PORTAL_URL) + await signIn(CHECKOUT) + + await expect(completeVerification(page)).toBeEnabled() + await expect(footnote(page)).toHaveText(PHASE_A) + await expect(backArrow(page)).toBeHidden() + await expect(page).toHaveURL(/\/v1\/checkout\?/) + expect(await nextActionCalls(page)).toEqual([]) + + await completeVerification(page).click() + + await expect(page).toHaveURL(PORTAL_URL) + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('340-13834: coming back from an Alipay payment the server ended unpaid opens capture on Payment not completed, never a decline', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: OPERATION, + pending_billing_op_type: 'subscription' + } + const moveOperation = scriptOperation(cloud) + const now = new Date().toISOString() + moveOperation({ + id: OPERATION, + status: 'failed', + retryable: true, + recovery_action: 'retry', + started_at: now, + completed_at: now + }) + await signIn(CHECKOUT) + + const card = page.getByRole('alert') + await expect(card).toContainText('Payment not completed') + await expect(card).not.toContainText('Payment declined') + await expect(payButton(page)).toBeEnabled() + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('447-6886: a redirect method shows the pre-money line, never Phase B, and leaves for the provider with the checkout as its return', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + scriptOperation(cloud) + await page.addInitScript((redirectTo) => { + Object.assign(window, { + __e2eStripeMethodType: 'alipay', + __e2eStripeRedirectTo: redirectTo + }) + }, PORTAL_URL) + await signIn(CHECKOUT) + + await payButton(page).click() + + await expect(footnote(page)).toHaveText(REDIRECTING) + await expect(cancelPayment(page)).toBeHidden() + await expect(page).toHaveURL(PORTAL_URL) + const [subscribe] = subscribeRequests(cloud) + expect(subscribe.body).toMatchObject({ + confirmation_token: 'ctok_e2e_fake', + return_url: expect.stringMatching(/\/v1\/checkout\?/) + }) +}) + +test('446-10925: coming back from the provider is a fresh mount on Phase B, then the terminal', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: OPERATION, + pending_billing_op_type: 'subscription' + } + const moveOperation = scriptOperation(cloud) + moveOperation(processing()) + await signIn(CHECKOUT) + + await expect(footnote(page)).toHaveText(PHASE_B) + await expect(payButton(page)).toBeDisabled() + expect(await nextActionCalls(page)).toEqual([]) + + moveOperation(succeededOperation(OPERATION)) + await expect( + page.getByRole('heading', { name: 'Already completed' }) + ).toBeVisible() + expect(subscribeRequests(cloud)).toHaveLength(0) +}) diff --git a/apps/billing-web/e2e/full-page-checkout.spec.ts b/apps/billing-web/e2e/full-page-checkout.spec.ts new file mode 100644 index 00000000000..eae5187442e --- /dev/null +++ b/apps/billing-web/e2e/full-page-checkout.spec.ts @@ -0,0 +1,282 @@ +import type { Page } from '@playwright/test' + +import { declinedOperation } 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 EYEBROW = 'Subscribe to Pro Plan · Personal' +const FORM_FAILED = "The payment form couldn't load" +const SAVED_FAILED = "Your saved payment methods couldn't load" + +/** 553-9853's destructive red, the nearest palette step to Figma's #f87171. */ +const INVALID_RED = 'rgb(247, 89, 81)' + +const payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const tab = (page: Page, name: 'Saved' | 'Add new payment') => + page.getByRole('tab', { name }) + +function failPaymentElementLoads(page: Page) { + return page.addInitScript(() => { + Object.assign(window, { __e2eStripeLoadErrors: 1 }) + }) +} + +test('names the plan and the workspace, and enables Pay once the form is ready', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + await signIn(CHECKOUT) + + await expect(page.getByText(EYEBROW)).toBeVisible() + await expect(payButton(page)).toBeEnabled() + await expect(tab(page, 'Saved')).toBeHidden() + await expect( + page.getByRole('heading', { name: 'Confirm your payment' }) + ).toBeHidden() + expect( + cloud.requests.some((request) => request.path === '/billing/capabilities') + ).toBe(true) +}) + +for (const { name, query } of [ + { name: 'no return_to', query: 'product=comfyui&plan=pro_monthly' }, + { + name: 'an unapproved return_to', + query: 'product=comfyui&return_to=elsewhere&plan=pro_monthly' + } +]) { + test(`a link with ${name} still checks out, and the back arrow goes to Plan & Credits`, async ({ + page, + cloud, + signIn + }) => { + cloud.scenario.paymentMethods = [] + await signIn(`/v1/checkout?${query}`) + + await expect(page.getByText(EYEBROW)).toBeVisible() + await expect(payButton(page)).toBeEnabled() + + await page.getByRole('button', { name: 'Back' }).click() + + await expect(page).toHaveURL( + 'https://testcloud.comfy.org/?settings=plan-credits&workspace=ws_e2e' + ) + }) +} + +test('360-4874: with no saved method a failed form takes the column, and Try again remounts it', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + await failPaymentElementLoads(page) + await signIn(CHECKOUT) + + await expect(page.getByText(FORM_FAILED)).toBeVisible() + await expect(payButton(page)).toBeHidden() + await expect(page.getByText(EYEBROW)).toBeVisible() + + await page.getByRole('button', { name: 'Try again' }).click() + + await expect(payButton(page)).toBeEnabled() + await expect(page.getByText(FORM_FAILED)).toBeHidden() +}) + +test('opens on the saved method and subscribes with it, no card token', async ({ + page, + cloud, + signIn +}) => { + await signIn(CHECKOUT) + + await expect(tab(page, 'Saved')).toHaveAttribute('aria-selected', 'true') + await expect( + page.getByRole('combobox', { name: 'Choose a saved payment method' }) + ).toContainText('·· 4242') + await expect(page.getByText('Billing address')).toBeHidden() + await payButton(page).click() + + await expect + .poll(() => + cloud.requests.find((request) => request.path === '/billing/subscribe') + ) + .toMatchObject({ body: { saved_payment_method_id: 'pm_e2e' } }) + const subscribe = cloud.requests.find( + (request) => request.path === '/billing/subscribe' + ) + expect(subscribe?.body).not.toHaveProperty('confirmation_token') +}) + +test('368-15319: a failed form beside a saved method stays inside Add new, and Saved stays payable', async ({ + page, + signIn +}) => { + await failPaymentElementLoads(page) + await signIn(CHECKOUT) + + await expect(tab(page, 'Saved')).toHaveAttribute('aria-selected', 'true') + await expect(payButton(page)).toBeEnabled() + await expect(page.getByText(FORM_FAILED)).toBeHidden() + + await tab(page, 'Add new payment').click() + + await expect(page.getByText(FORM_FAILED)).toBeVisible() + await expect( + page.getByText('or pay with a saved payment method.', { exact: false }) + ).toBeVisible() + await expect(payButton(page)).toBeHidden() + + await page.getByRole('button', { name: 'Try again' }).click() + + await expect(payButton(page)).toBeEnabled() + await expect(tab(page, 'Add new payment')).toHaveAttribute( + 'aria-selected', + 'true' + ) +}) + +test('368-15401: a failed saved-methods read errors on Saved only, and Add new stays live', async ({ + page, + cloud, + signIn +}) => { + let healthy = false + cloud.reply('GET', '/billing/payment-methods', () => + healthy + ? { body: cloud.scenario.paymentMethods } + : { status: 500, body: { code: 'INTERNAL', message: 'boom' } } + ) + await signIn(CHECKOUT) + + await expect(tab(page, 'Saved')).toHaveAttribute('aria-selected', 'true') + await expect(page.getByText(SAVED_FAILED)).toBeVisible() + await expect(page.getByText('Billing address')).toBeHidden() + await expect(payButton(page)).toBeHidden() + + await tab(page, 'Add new payment').click() + await expect(payButton(page)).toBeEnabled() + + await tab(page, 'Saved').click() + healthy = true + await page.getByRole('button', { name: 'Try again' }).click() + + await expect( + page.getByRole('combobox', { name: 'Choose a saved payment method' }) + ).toContainText('·· 4242') + await expect(page.getByText(SAVED_FAILED)).toBeHidden() + await expect(payButton(page)).toBeEnabled() +}) + +test('a declined Pay leaves the card above an unchanged Pay, with support one click away', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.operations.op_subscribe = { + ...declinedOperation('op_subscribe'), + decline_reason: 'insufficient_funds' + } + await signIn(CHECKOUT) + + await payButton(page).click() + + const card = page.getByRole('alert') + await expect(card).toContainText('Payment declined') + await expect(card).toContainText('Reported issue: Insufficient funds') + await expect(payButton(page)).toBeEnabled() + const support = page.getByRole('link', { name: 'Contact support' }) + await expect(support).toHaveAttribute('href', /op_subscribe/) + await expect(support).toHaveAttribute('href', /insufficient_funds/) + await expect(page).toHaveURL(/\/v1\/checkout\?/) +}) + +test('553-9297: a plan change on a plan set to end needs the keep-subscription tick: Pay without it sends nothing, with it sends the consent', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.status = { + ...cloud.scenario.status, + cancel_at: '2026-07-28T00:00:00.000Z' + } + cloud.scenario.preview = { + ...cloud.scenario.preview, + transition_type: 'upgrade', + requires_reactivation_confirmation: true, + cost_next_period_cents: 10_000 + } + await signIn(CHECKOUT) + + const notice = page.getByTestId('keep-subscription-notice') + await expect(notice).toContainText( + 'Your plan was set to end on July 28, 2026' + ) + await expect(notice).toContainText( + 'Upgrading keeps your subscription, and it renews that day at $100.00.' + ) + const box = page.getByRole('checkbox', { + name: 'Keep my subscription and renew it' + }) + await expect(payButton(page)).toBeEnabled() + const noticeBox = await notice.boundingBox() + const payBox = await payButton(page).boundingBox() + expect( + payBox && noticeBox && payBox.y - (noticeBox.y + noticeBox.height) + ).toBe(24) + + await payButton(page).click() + + await expect(box).toHaveAttribute('aria-invalid', 'true') + await expect(box).toBeFocused() + const error = notice.getByText( + 'Check the box to keep your subscription, then pay.' + ) + await expect(error).toBeVisible() + await expect(box).toHaveAccessibleDescription( + 'Check the box to keep your subscription, then pay.' + ) + await expect(notice.getByTestId('keep-subscription-box')).toHaveCSS( + 'border-color', + INVALID_RED + ) + await expect(notice.getByText('Keep my subscription and renew it')).toHaveCSS( + 'color', + INVALID_RED + ) + await expect(error).toHaveCSS('color', INVALID_RED) + await expect(payButton(page)).toBeEnabled() + expect( + cloud.requests.some((request) => request.path === '/billing/subscribe') + ).toBe(false) + + await notice.getByText('Keep my subscription and renew it').click() + await expect(box).toHaveAttribute('aria-invalid', 'false') + await payButton(page).click() + + await expect + .poll(() => + cloud.requests.find((request) => request.path === '/billing/subscribe') + ) + .toMatchObject({ body: { confirm_reactivation: true } }) +}) 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..e586c1f4a4c --- /dev/null +++ b/apps/billing-web/e2e/full-page-cross-tab.spec.ts @@ -0,0 +1,137 @@ +/** + * 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 { declinedOperation, processingOperation } 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 = "This payment is already processing and can't be canceled." + +const payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const waiting = (page: Page) => page.getByTestId('checkout-phase-footnote') + +/** 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 = processingOperation('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)).toBeDisabled() + 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 decline shows its card only in the tab that paid; a sibling goes back to the plain payment form', async ({ + page, + context, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + pendingAfterSubscribe(cloud, 'op_subscribe') + cloud.scenario.operations.op_subscribe = processingOperation('op_subscribe') + await signIn(CHECKOUT) + const sibling = await context.newPage() + await sibling.goto(CHECKOUT) + await expect(payButton(sibling)).toBeEnabled() + + await payButton(page).click() + await expect(waiting(sibling)).toHaveText(WAITING) + + cloud.scenario.operations.op_subscribe = declinedOperation('op_subscribe') + + await expect(page.getByRole('alert')).toContainText('Payment declined') + await expect(payButton(sibling)).toBeEnabled() + await expect(sibling.getByText('Payment declined')).toBeHidden() + await expect(waiting(sibling)).toHaveText('') +}) + +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 = processingOperation('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)).toBeDisabled() + expect( + cloud.requests.filter((request) => request.path === '/billing/subscribe') + ).toHaveLength(0) +}) diff --git a/apps/billing-web/e2e/full-page-endings.spec.ts b/apps/billing-web/e2e/full-page-endings.spec.ts new file mode 100644 index 00000000000..f176e131ece --- /dev/null +++ b/apps/billing-web/e2e/full-page-endings.spec.ts @@ -0,0 +1,276 @@ +/** + * The full-page terminals, each reached the way a customer reaches it: their + * own Pay, a revisit after the money settled, a bank capture that is still + * settling, a refusal, a stale plan link and a checkout that could not load. + */ +import type { Page } from '@playwright/test' + +import type { MockCloud } from './fixtures/cloud' +import { + capabilitiesWith, + pendingOperation, + succeededOperation +} 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.paymentMethods = [] + 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 payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const heading = (page: Page, name: string) => + page.getByRole('heading', { name }) +const code = (page: Page) => page.getByTestId('checkout-ending-code') +const contactSupport = (page: Page) => + page.getByRole('link', { name: 'Contact support' }) + +function markPending(cloud: MockCloud, id: string) { + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: id, + pending_billing_op_type: 'subscription' + } +} + +const subscribeRequests = (cloud: MockCloud) => + cloud.requests.filter((request) => request.path === '/billing/subscribe') + +test('a Pay that goes through names the plan and the workspace, and Close goes back to the product with the outcome', async ({ + page, + signIn +}) => { + await signIn(CHECKOUT) + await payButton(page).click() + + await expect(heading(page, "You're all set")).toBeVisible() + await expect( + page.getByText('Your plan for Personal has been successfully updated.') + ).toBeVisible() + await expect(page.getByTestId('checkout-ending-plan')).toContainText('Pro') + await expect(code(page)).toBeHidden() + await expect(page.getByText('You can close this tab now.')).toBeVisible() + await expect(page.getByText(/Closing in/)).toBeHidden() + + await page.getByRole('button', { name: 'Close' }).click() + + await expect(heading(page, 'Host app')).toBeVisible() + const back = new URL(page.url()) + expect(back.searchParams.get('billing_result')).toBe('success') + expect(back.searchParams.get('billing_ref')).toBe('op_subscribe') +}) + +test('a revisit after the payment settled renders Already completed on every load, never a form', async ({ + page, + cloud, + signIn +}) => { + markPending(cloud, 'op_done') + cloud.scenario.operations.op_done = succeededOperation('op_done') + await signIn(CHECKOUT) + + await expect(heading(page, 'Already completed')).toBeVisible() + await expect(code(page)).toHaveText('op_done') + await expect(page.getByTestId('checkout-ending-plan')).toBeHidden() + + await page.reload() + + await expect(heading(page, 'Already completed')).toBeVisible() + await expect(payButton(page)).toBeHidden() + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('FE-2856: a capture the bank is still settling renders Payment in progress, then resolves forward to success', async ({ + page, + cloud, + signIn +}) => { + markPending(cloud, 'op_bank') + cloud.scenario.operations.op_bank = { + ...pendingOperation('op_bank'), + phase: 'in_progress', + authentication_state: 'processing' + } + await signIn(CHECKOUT) + + await expect(heading(page, 'Payment in progress')).toBeVisible() + await expect( + page.getByText("Don't pay again, you could be charged twice.") + ).toBeVisible() + await expect(code(page)).toHaveText('op_bank') + await expect(contactSupport(page)).toBeVisible() + await expect(page.getByRole('button', { name: 'Close' })).toBeHidden() + await expect(payButton(page)).toBeHidden() + + cloud.scenario.operations.op_bank = succeededOperation('op_bank') + + await expect(heading(page, "You're all set")).toBeVisible() + await expect( + page.getByText( + 'A payment on this workspace completed — check your plan in settings.' + ) + ).toBeVisible() + await expect(code(page)).toHaveText('op_bank') + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('a member the owner manages billing for sees Checkout not available with the reason code, and support only', async ({ + page, + cloud, + signIn +}) => { + const refused = capabilitiesWith({ can_subscribe_self_serve: false }) + cloud.reply('GET', '/billing/capabilities', () => ({ + body: { + ...refused, + denied_reasons: { can_subscribe_self_serve: 'not_workspace_owner' } + }, + headers: { 'x-capability-revision': String(refused.revision) } + })) + await signIn(CHECKOUT) + + await expect(heading(page, 'Checkout not available')).toBeVisible() + await expect(code(page)).toHaveText('NOT_WORKSPACE_OWNER') + await expect(contactSupport(page)).toBeVisible() + await expect( + page.getByRole('button', { name: /Close|Try again/ }) + ).toBeHidden() +}) + +test('433-6840: a link to a plan the catalog lacks renders Plan not available with PLAN_NOT_FOUND, and View plans opens the cloud pricing table', async ({ + page, + cloud, + signIn +}) => { + cloud.reply('POST', '/billing/preview-subscribe', () => ({ + status: 400, + body: { code: 'INVALID_PLAN', message: 'Plan not found: pro_monthly' } + })) + await signIn(CHECKOUT) + + await expect(heading(page, "This plan isn't available")).toBeVisible() + await expect(code(page)).toHaveText('PLAN_NOT_FOUND') + + await page.getByRole('button', { name: 'View plans' }).click() + + await expect(heading(page, 'Host app')).toBeVisible() + await expect(page).toHaveURL( + 'https://testcloud.comfy.org/?pricing=1&workspace=ws_e2e' + ) +}) + +test('433-6840: a team link without its commit stop is an invalid link, and View plans opens the pricing table on the Team tab', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.preview = { + ...cloud.scenario.preview, + new_plan: { ...cloud.scenario.preview.new_plan, tier: 'TEAM' } + } + await signIn(entryPath('checkout', { plan: 'team_per_credit_monthly' })) + + await expect(heading(page, "This plan isn't available")).toBeVisible() + await expect(code(page)).toHaveText('CHECKOUT_LINK_INVALID') + await expect(payButton(page)).toBeHidden() + expect(subscribeRequests(cloud)).toHaveLength(0) + + await page.getByRole('button', { name: 'View plans' }).click() + + await expect(heading(page, 'Host app')).toBeVisible() + await expect(page).toHaveURL( + 'https://testcloud.comfy.org/?pricing=team&workspace=ws_e2e' + ) +}) + +test("433-6840: a checkout link the contract cannot read is the checkout's 404 on the full page, and still the entry error on the embedded one", async ({ + page, + cloud, + signIn +}) => { + const unreadable = entryPath('checkout', { + product: 'spreadsheet', + plan: 'pro_monthly' + }) + await signIn(unreadable) + + await expect(heading(page, "This plan isn't available")).toBeVisible() + await expect(code(page)).toHaveText('CHECKOUT_LINK_INVALID') + await expect(payButton(page)).toBeHidden() + + cloud.scenario.checkoutUi = 'embedded' + await page.goto(unreadable) + + await expect( + heading(page, "We couldn't open that billing page") + ).toBeVisible() + await expect( + page.getByText("That link doesn't say which product sent you here.") + ).toBeVisible() +}) + +test("a checkout that couldn't load retries in place on Try again, without leaving the URL", async ({ + page, + cloud, + signIn +}) => { + let quotes = 0 + cloud.reply('POST', '/billing/preview-subscribe', () => { + quotes += 1 + return quotes === 1 + ? { status: 503, body: { code: 'UNAVAILABLE', message: 'down' } } + : { body: cloud.scenario.preview } + }) + await signIn(CHECKOUT) + + await expect(heading(page, "Couldn't load your checkout")).toBeVisible() + await expect(code(page)).toHaveText('REQUEST_FAILED') + + await page.getByRole('button', { name: 'Try again' }).click() + + await expect(payButton(page)).toBeEnabled() + await expect(page).toHaveURL(CHECKOUT) + expect(quotes).toBe(2) +}) + +test("a re-read of the workspace's payments that fails never claims nothing was charged, and Try again follows the payment once it answers", async ({ + page, + cloud, + signIn +}) => { + markPending(cloud, 'op_unread') + cloud.scenario.operations.op_unread = succeededOperation('op_unread') + let reachable = false + cloud.reply('GET', '/billing/status', () => + reachable + ? { body: cloud.scenario.status } + : { status: 503, body: { code: 'UNAVAILABLE', message: 'down' } } + ) + await signIn(CHECKOUT) + + await expect(heading(page, "Couldn't load your checkout")).toBeVisible() + await expect(page.getByText(/Nothing has been charged/)).toBeHidden() + await expect(payButton(page)).toBeHidden() + + reachable = true + await page.getByRole('button', { name: 'Try again' }).click() + + await expect(heading(page, 'Already completed')).toBeVisible() + await expect(code(page)).toHaveText('op_unread') + expect(subscribeRequests(cloud)).toHaveLength(0) +}) diff --git a/apps/billing-web/e2e/full-page-promo.spec.ts b/apps/billing-web/e2e/full-page-promo.spec.ts new file mode 100644 index 00000000000..7a6278c8c9e --- /dev/null +++ b/apps/billing-web/e2e/full-page-promo.spec.ts @@ -0,0 +1,225 @@ +import type { Page } from '@playwright/test' + +import type { MockCloud } from './fixtures/cloud' +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 EYEBROW = 'Subscribe to Pro Plan · Personal' + +/** + * Prices LAUNCH20 at 20% off the $50 plan and refuses any other code the way + * billing does, with a 400 carrying `PROMOTION_CODE_INVALID`. + */ +function quoteCodes(cloud: MockCloud, valid: () => boolean = () => true) { + cloud.reply('POST', '/billing/preview-subscribe', ({ body }) => { + const code = + typeof body === 'object' && body !== null && 'promotion_code' in body + ? String(body.promotion_code) + : undefined + if (code === undefined) return { body: cloud.scenario.preview } + if (code.toUpperCase() !== 'LAUNCH20' || !valid()) + return { + status: 400, + body: { + code: 'PROMOTION_CODE_INVALID', + message: 'promotion code is invalid, inactive, or not applicable' + } + } + return { + body: { + ...cloud.scenario.preview, + quote_id: 'quote_launch20', + amount_due_cents: 4000, + promotion_code: 'LAUNCH20', + discounts: [ + { kind: 'promotion', code: 'LAUNCH20', amount_off_cents: 1000 } + ] + } + } + }) +} + +const summary = (page: Page) => + page.getByRole('region', { name: 'Order summary' }) +const promoField = (page: Page) => + page.getByRole('textbox', { name: 'Promo code' }) + +async function enterCode(page: Page, code: string) { + await page.getByRole('button', { name: 'Add promo code' }).click() + await promoField(page).fill(code) + await page.getByRole('button', { name: 'Apply' }).click() +} + +test('applies a valid code: its row, its removable chip, and the new total', async ({ + page, + cloud, + signIn +}) => { + quoteCodes(cloud) + await signIn(CHECKOUT) + await expect(page.getByText(EYEBROW)).toBeVisible() + + await enterCode(page, 'launch20') + + await expect(summary(page)).toContainText('Promo code−$10.00') + await expect(summary(page)).toContainText('Total due today$40.00') + await expect( + page.getByRole('button', { name: 'Remove LAUNCH20' }) + ).toBeVisible() + await expect( + page.getByRole('button', { name: 'Add promo code' }) + ).toBeHidden() + + await page.getByRole('button', { name: 'Pay and subscribe' }).click() + await expect + .poll(() => + cloud.requests.find((request) => request.path === '/billing/subscribe') + ) + .toMatchObject({ + body: { promotion_code: 'LAUNCH20', quote_id: 'quote_launch20' } + }) +}) + +test('an invalid code says so under the field and leaves the total alone', async ({ + page, + cloud, + signIn +}) => { + quoteCodes(cloud) + await signIn(CHECKOUT) + await expect(page.getByText(EYEBROW)).toBeVisible() + + await enterCode(page, 'NOPE') + + await expect(page.getByText("This code isn't valid.")).toBeVisible() + await expect(promoField(page)).toHaveValue('NOPE') + await expect(summary(page)).toContainText('Total due today$50.00') + await expect(summary(page)).not.toContainText('−$') +}) + +test('a code in the URL is prefilled and priced only on Apply', async ({ + page, + cloud, + signIn +}) => { + quoteCodes(cloud) + await signIn( + entryPath('checkout', { plan: 'pro_monthly', promo: 'LAUNCH20' }) + ) + await expect(page.getByText(EYEBROW)).toBeVisible() + + await expect(promoField(page)).toHaveValue('LAUNCH20') + await expect(summary(page)).toContainText('Total due today$50.00') + const quotes = cloud.requests.filter( + (request) => request.path === '/billing/preview-subscribe' + ) + expect(quotes.map((request) => request.body)).not.toContainEqual( + expect.objectContaining({ promotion_code: expect.anything() }) + ) + + await page.getByRole('button', { name: 'Apply' }).click() + + await expect(summary(page)).toContainText('Total due today$40.00') +}) + +test('a Pay over the URL code prices it first, and the second Pay charges the new total', async ({ + page, + cloud, + signIn +}) => { + quoteCodes(cloud) + await signIn( + entryPath('checkout', { plan: 'pro_monthly', promo: 'LAUNCH20' }) + ) + await expect(promoField(page)).toHaveValue('LAUNCH20') + const pay = page.getByRole('button', { name: 'Pay and subscribe' }) + + await pay.click() + + await expect(summary(page)).toContainText('Total due today$40.00') + await expect( + page.getByRole('button', { name: 'Remove LAUNCH20' }) + ).toBeVisible() + expect( + cloud.requests.some((request) => request.path === '/billing/subscribe') + ).toBe(false) + + await pay.click() + + await expect + .poll(() => + cloud.requests.find((request) => request.path === '/billing/subscribe') + ) + .toMatchObject({ + body: { promotion_code: 'LAUNCH20', quote_id: 'quote_launch20' } + }) +}) + +test('a URL code the link cannot carry loads the checkout with the code refused in the field', async ({ + page, + cloud, + signIn +}) => { + quoteCodes(cloud) + await signIn(entryPath('checkout', { plan: 'pro_monthly', promo: 'SAVE 20' })) + + await expect(page.getByText(EYEBROW)).toBeVisible() + await expect(promoField(page)).toHaveValue('SAVE 20') + await expect(page.getByText("This code isn't valid.")).toBeVisible() + await expect(summary(page)).toContainText('Total due today$50.00') +}) + +test('a code that lapses before Pay returns to capture with the expired card', async ({ + page, + cloud, + signIn +}) => { + let stillValid = true + quoteCodes(cloud, () => stillValid) + cloud.reply('POST', '/billing/subscribe', () => ({ + status: 400, + body: { + code: 'SUBSCRIPTION_QUOTE_STALE', + message: 'subscription quote is stale or does not match this request' + } + })) + await signIn(CHECKOUT) + await enterCode(page, 'LAUNCH20') + await expect(summary(page)).toContainText('Total due today$40.00') + stillValid = false + + await page.getByRole('button', { name: 'Pay and subscribe' }).click() + + const card = page.getByRole('alert') + await expect(card).toContainText('Your promo code expired') + await expect(card).toContainText( + 'The LAUNCH20 code expired, so the total was updated.' + ) + await expect(summary(page)).toContainText('Total due today$50.00') + await expect( + page.getByRole('button', { name: 'Remove LAUNCH20' }) + ).toBeHidden() + await expect( + page.getByRole('button', { name: 'Add promo code' }) + ).toBeEnabled() + await expect( + page.getByRole('button', { name: 'Pay and subscribe' }) + ).toBeEnabled() + await expect(page.getByRole('link', { name: 'Contact support' })).toBeHidden() +}) diff --git a/apps/billing-web/e2e/full-page-reconciliation.spec.ts b/apps/billing-web/e2e/full-page-reconciliation.spec.ts new file mode 100644 index 00000000000..7ba67a1e0f1 --- /dev/null +++ b/apps/billing-web/e2e/full-page-reconciliation.spec.ts @@ -0,0 +1,237 @@ +/** + * One URL, re-read from the live operation on every mount: a reload while + * money is in flight, a Pay that collides with an operation already under + * way, and a session that expires mid-checkout all land on whatever the + * server says is true, never on a fresh form over a pending charge. + */ +import type { Page } from '@playwright/test' + +import { E2E_USER } from './fixtures/env' +import { + pendingOperation, + processingOperation, + succeededOperation +} from './fixtures/scenario' +import type { MockCloud } from './fixtures/cloud' +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 EYEBROW = 'Subscribe to Pro Plan · Personal' +const WAITING = "This payment is already processing and can't be canceled." + +const payButton = (page: Page) => + page.getByRole('button', { name: 'Pay and subscribe' }) +const waiting = (page: Page) => page.getByTestId('checkout-phase-footnote') + +function markPending(cloud: MockCloud, id: string) { + cloud.scenario.status = { + ...cloud.scenario.status, + pending_billing_op_id: id, + pending_billing_op_type: 'subscription' + } +} + +/** The server reports the operation pending only from the given status read on. */ +function pendingFromRead(cloud: MockCloud, id: string, fromRead: number) { + let reads = 0 + cloud.reply('GET', '/billing/status', () => { + reads += 1 + return { + body: + reads >= fromRead + ? { + ...cloud.scenario.status, + pending_billing_op_id: id, + pending_billing_op_type: 'subscription' + } + : cloud.scenario.status + } + }) +} + +const subscribeRequests = (cloud: MockCloud) => + cloud.requests.filter((request) => request.path === '/billing/subscribe') + +test('a reload while a payment is in flight renders the waiting state, never a form, and follows it to Already completed', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + markPending(cloud, 'op_in_flight') + cloud.scenario.operations.op_in_flight = processingOperation('op_in_flight') + await signIn(CHECKOUT) + + await expect(waiting(page)).toHaveText(WAITING) + await expect(page.getByText(EYEBROW)).toBeVisible() + await expect(payButton(page)).toBeDisabled() + await expect(page).toHaveURL(/\/v1\/checkout\?/) + + cloud.scenario.operations.op_in_flight = succeededOperation('op_in_flight') + + await expect( + page.getByRole('heading', { name: 'Already completed' }) + ).toBeVisible() + await expect(page.getByTestId('checkout-ending-code')).toHaveText( + 'op_in_flight' + ) + await expect(page.getByTestId('checkout-ending-plan')).toBeHidden() + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('an operation parked on a payment method renders capture, and Pay resubmits it', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + markPending(cloud, 'op_parked') + cloud.scenario.operations.op_parked = { + ...pendingOperation('op_parked'), + phase: 'awaiting_payment_method' + } + await signIn(CHECKOUT) + + await expect(payButton(page)).toBeEnabled() + await expect(waiting(page)).toHaveText('') + await payButton(page).click() + + await expect.poll(() => subscribeRequests(cloud)).toHaveLength(1) +}) + +test('a Pay refused for an operation already pending re-reads it and waits on it, never a decline', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + pendingFromRead(cloud, 'op_elsewhere', 2) + cloud.scenario.operations.op_elsewhere = processingOperation('op_elsewhere') + await signIn(CHECKOUT) + await expect(payButton(page)).toBeEnabled() + + await payButton(page).click() + + await expect(waiting(page)).toHaveText(WAITING) + await expect(payButton(page)).toBeDisabled() + await expect(page.getByText('Payment declined')).toBeHidden() + await expect(page.getByRole('link', { name: 'Contact support' })).toBeHidden() + expect(subscribeRequests(cloud)).toHaveLength(0) +}) + +test('a Pay the server answers 409 for lands on Already completed once the re-read finds the payment settled', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.reply('POST', '/billing/subscribe', () => ({ + status: 409, + body: { code: 'CONFLICT', message: 'operation already settled' } + })) + pendingFromRead(cloud, 'op_settled', 3) + cloud.scenario.operations.op_settled = succeededOperation('op_settled') + await signIn(CHECKOUT) + await expect(payButton(page)).toBeEnabled() + + await payButton(page).click() + + await expect( + page.getByRole('heading', { name: 'Already completed' }) + ).toBeVisible() + await expect(page.getByText('Payment declined')).toBeHidden() + await expect(page.getByRole('link', { name: 'Contact support' })).toBeHidden() + expect(subscribeRequests(cloud)).toHaveLength(1) +}) + +const REFUSED = { status: 401, body: { error: 'unauthorized' } } as const +const BILLING_READS = [ + '/billing/status', + '/billing/capabilities', + '/billing/payment-methods' +] + +for (const { name, pending, lands } of [ + { name: 'money in flight', pending: true, lands: 'waiting' }, + { name: 'nothing pending', pending: false, lands: 'capture' } +] as const) { + test(`a session that expires mid-checkout goes through sign-in and comes back to the same URL, reconciling into ${lands} for ${name}, without charging`, async ({ + page, + cloud, + signIn + }) => { + cloud.scenario.paymentMethods = [] + await signIn(CHECKOUT) + await expect(payButton(page)).toBeEnabled() + + cloud.reply('POST', '/auth/token', () => REFUSED) + for (const path of BILLING_READS) cloud.reply('GET', path, () => REFUSED) + await payButton(page).click() + + await expect(page).toHaveURL( + (url) => + url.pathname === '/sign-in' && + url.searchParams.get('returnTo') === CHECKOUT + ) + await expect(page.getByRole('alert')).toBeVisible() + + cloud.reply('POST', '/auth/token', () => ({ + body: { + token: 'e2e-workspace-jwt-2', + expires_at: new Date(Date.now() + 3_600_000).toISOString(), + permissions: ['workspace:read', 'billing:write'], + role: 'owner', + workspace: { + id: E2E_USER.workspaceId, + name: 'Personal', + type: 'personal' + } + } + })) + for (const path of BILLING_READS) { + cloud.reply('GET', path, () => ({ + body: + path === '/billing/status' + ? pending + ? { + ...cloud.scenario.status, + pending_billing_op_id: 'op_after_reauth', + pending_billing_op_type: 'subscription' + } + : cloud.scenario.status + : path === '/billing/capabilities' + ? cloud.scenario.capabilities + : cloud.scenario.paymentMethods + })) + } + cloud.scenario.operations.op_after_reauth = + processingOperation('op_after_reauth') + await page.getByRole('button', { name: 'Retry session' }).click() + + await expect(page).toHaveURL(CHECKOUT) + if (lands === 'waiting') { + await expect(waiting(page)).toHaveText(WAITING) + await expect(payButton(page)).toBeDisabled() + } else { + await expect(payButton(page)).toBeEnabled() + await expect(waiting(page)).toHaveText('') + } + expect(subscribeRequests(cloud)).toHaveLength(0) + }) +} diff --git a/apps/billing-web/e2e/full-page-summary.spec.ts b/apps/billing-web/e2e/full-page-summary.spec.ts new file mode 100644 index 00000000000..816588afb3e --- /dev/null +++ b/apps/billing-web/e2e/full-page-summary.spec.ts @@ -0,0 +1,123 @@ +import type { Page } from '@playwright/test' + +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 RENEWAL_AT = '2026-07-28T00:00:00.000Z' + +async function expectSummary(page: Page, lines: readonly string[]) { + const summary = page.getByRole('region', { name: 'Order summary' }) + await expect(summary).toHaveAttribute('aria-busy', 'false') + for (const line of lines) await expect(summary).toContainText(line) +} + +test('a new subscription reads its charge, allowance and renewal from the quote', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + cloud.scenario.preview = { + ...cloud.scenario.preview, + renewal_at: RENEWAL_AT, + renewal_amount_cents: 5000 + } + await signIn(CHECKOUT) + + await expectSummary(page, [ + 'Subscribe to Pro Plan · Personal', + '$50 USD', + '21,100 credits per month', + 'Pro Plan$50.00', + '$50 /mo, billed monthly', + 'Total due today$50.00', + 'Renews at $50.00 on July 28, 2026' + ]) +}) + +test('a tier upgrade reads the prorated charge and a dated credits delta', async ({ + page, + cloud, + signIn +}) => { + const preview = cloud.scenario.preview + cloud.scenario.preview = { + ...preview, + transition_type: 'upgrade', + proration_at: '2026-07-10T09:30:00.000Z', + amount_due_cents: 3250, + cost_today_cents: 3250, + credits_today_cents: 3250, + credits_next_period_cents: 10_000, + renewal_amount_cents: 10_000, + renewal_at: RENEWAL_AT, + current_plan: { + ...preview.new_plan, + slug: 'creator_monthly', + tier: 'CREATOR', + price_cents: 3500 + } + } + await signIn(CHECKOUT) + + await expectSummary(page, [ + 'Upgrade to Pro Plan · Personal', + '$32.50 USD', + '6,858 credits added today (expire July 28)', + 'Pro Plan - Prorated$32.50', + 'Remaining time for Pro plan, less unused time from Creator plan', + 'Credits refill to 21,100 each month', + 'Total due today$32.50', + 'Existing credits are kept', + 'Renews at $100.00 on July 28, 2026' + ]) +}) + +test('a held discount and an entered code read as rows, with no Subtotal the quote never reported', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.preview = { + ...cloud.scenario.preview, + amount_due_cents: 2000, + promotion_code: 'COMFY50', + discounts: [ + { kind: 'plan', code: 'annual_plan_discount_20', amount_off_cents: 999 }, + { + kind: 'promotion', + code: 'COMFY-EDU', + name: 'Education discount', + amount_off_cents: 1000 + }, + { kind: 'promotion', code: 'COMFY50', amount_off_cents: 2000 } + ] + } + await signIn(CHECKOUT) + + await expectSummary(page, [ + 'Pro Plan$50.00', + 'Education discount−$10.00', + 'Promo code−$20.00', + 'Total due today$20.00' + ]) + const summary = page.getByRole('region', { name: 'Order summary' }) + await expect(summary).not.toContainText('−$9.99') + await expect(summary).not.toContainText('Subtotal') +}) diff --git a/apps/billing-web/package.json b/apps/billing-web/package.json index 4c2ed8415d7..7252a8cf86d 100644 --- a/apps/billing-web/package.json +++ b/apps/billing-web/package.json @@ -19,6 +19,7 @@ "@comfyorg/account-ui": "workspace:*", "@comfyorg/billing-contract": "workspace:*", "@comfyorg/design-system": "workspace:*", + "@comfyorg/shared-frontend-utils": "workspace:*", "@comfyorg/tailwind-utils": "workspace:*", "@stripe/stripe-js": "catalog:", "@vueuse/core": "catalog:", diff --git a/apps/billing-web/src/App.vue b/apps/billing-web/src/App.vue index 0e9e054ffbc..7b87361e1dc 100644 --- a/apps/billing-web/src/App.vue +++ b/apps/billing-web/src/App.vue @@ -2,6 +2,9 @@ import { computed, watch } from 'vue' import { useRoute, useRouter } from 'vue-router' +import { billingIntentPath } from '@comfyorg/billing-contract' + +import { safeReturnTo } from '@/auth/returnTo' import BillingShell from '@/components/BillingShell.vue' import { useBillingEntry } from '@/entry/billingEntry' import { SIGN_IN_PATH } from '@/router' @@ -25,6 +28,22 @@ watch(billingWebLivePhase, (next) => { }) }) +/** + * A checkout link that cannot be read is the checkout's own 404 on the full + * page, so that route decides how to explain it once the variant is known, + * which takes a signed-in session; every other unreadable link is explained + * here, before any session. On the sign-in page the link is the one it will + * return to. + */ +const CHECKOUT_PATH = billingIntentPath('checkout') +const checkoutLink = computed(() => { + const path = + route.path === SIGN_IN_PATH + ? safeReturnTo(route.query.returnTo).split('?')[0] + : route.path + return path === CHECKOUT_PATH +}) + /** A new key is a new scope, so the shell remounts with a fresh client. */ const scopeKey = computed(() => billedScope.value @@ -35,7 +54,7 @@ const scopeKey = computed(() =>