diff --git a/apps/billing-web/e2e/fixtures/stripe.ts b/apps/billing-web/e2e/fixtures/stripe.ts index 52a6827349d..18010ab37f3 100644 --- a/apps/billing-web/e2e/fixtures/stripe.ts +++ b/apps/billing-web/e2e/fixtures/stripe.ts @@ -18,6 +18,9 @@ const FAKE_STRIPE_JS = ` window.__e2eFakeStripe = { confirmationTokens: 0, nextActions: 0, + // Payment elements taken off the page, so a spec can tell a form kept as + // typed from one mounted afresh. + unmounts: 0, // Every argument the app actually passed to handleNextAction, so a spec // can tell "called correctly" from "called with the wrong secret". nextActionCalls: [] @@ -29,8 +32,12 @@ const FAKE_STRIPE_JS = ` if (failing) window.__e2eStripeLoadErrors -= 1 return { mount() {}, - unmount() {}, - destroy() {}, + unmount() { + window.__e2eFakeStripe.unmounts += 1 + }, + destroy() { + window.__e2eFakeStripe.unmounts += 1 + }, on(event, handler) { if (event === (failing ? 'loaderror' : 'ready')) setTimeout(() => handler({ error: { code: 'e2e_load_error' } })) diff --git a/apps/billing-web/e2e/full-page-authentication.spec.ts b/apps/billing-web/e2e/full-page-authentication.spec.ts index fae733ef415..2161fe9b37b 100644 --- a/apps/billing-web/e2e/full-page-authentication.spec.ts +++ b/apps/billing-web/e2e/full-page-authentication.spec.ts @@ -85,6 +85,39 @@ const nextActionCalls = (page: Page): Promise => const subscribeRequests = (cloud: MockCloud) => cloud.requests.filter((request) => request.path === '/billing/subscribe') +const CANCEL_PATH = `/billing/ops/${OPERATION}/cancel` + +const cancelRequests = (cloud: MockCloud) => + cloud.requests.filter((request) => request.path === CANCEL_PATH) + +const elementUnmounts = (page: Page): Promise => + page.evaluate('window.__e2eFakeStripe.unmounts') + +/** The operation as the server reads it back once a cancel discarded it. */ +const canceledOperation = (): BillingOpStatusResponse => { + const now = new Date().toISOString() + return { + id: OPERATION, + status: 'failed', + decline_reason: 'authentication_failed', + retryable: true, + recovery_action: 'retry', + started_at: now, + completed_at: now + } +} + +/** Pay with a new card, held on the bank's challenge in Phase A. */ +async function payIntoChallenge( + page: Page, + signIn: (path: string) => Promise +) { + await holdChallenge(page) + await signIn(CHECKOUT) + await payButton(page).click() + await expect(footnote(page)).toHaveText(PHASE_A) +} + 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, @@ -103,7 +136,7 @@ test('145-4584 → 342-4767: Pay walks Phase A, locked with nothing charged, int await expect(footnote(page)).toHaveAttribute('aria-live', 'polite') await expect(payButton(page)).toBeDisabled() await expect(backArrow(page)).toBeHidden() - await expect(cancelPayment(page)).toBeHidden() + await expect(cancelPayment(page)).toBeEnabled() expect(await nextActionCalls(page)).toEqual([{ clientSecret: CLIENT_SECRET }]) await releaseChallenge(page, 'succeeded') @@ -450,3 +483,127 @@ test('446-10925: coming back from the provider is a fresh mount on Phase B, then ).toBeVisible() expect(subscribeRequests(cloud)).toHaveLength(0) }) + +test('145-4326: Cancel payment during Phase A goes back to the form as typed, with no card, and Pay live once the challenge closes', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + const moveOperation = scriptOperation(cloud) + cloud.reply('POST', CANCEL_PATH, () => { + moveOperation(canceledOperation()) + return { body: { billing_op_id: OPERATION, status: 'canceled' } } + }) + await payIntoChallenge(page, signIn) + + await cancelPayment(page).click() + + await expect(cancelPayment(page)).toBeHidden() + await expect(footnote(page)).toHaveText('') + await expect(backArrow(page)).toBeVisible() + await expect(page.getByRole('alert')).toBeHidden() + expect(await elementUnmounts(page)).toBe(0) + + await releaseChallenge(page, 'requires_action') + + await expect(payButton(page)).toBeEnabled() + await expect(page.getByRole('alert')).toBeHidden() + expect(cancelRequests(cloud)).toHaveLength(1) + expect(subscribeRequests(cloud)).toHaveLength(1) +}) + +test('342-4767: a cancel the payment won the race against shows Phase B and follows the payment to success', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + const moveOperation = scriptOperation(cloud) + cloud.reply('POST', CANCEL_PATH, () => { + moveOperation(processing()) + return { + status: 409, + body: { + code: 'PAYMENT_IN_FLIGHT', + message: 'billing operation has applied or its payment is in progress' + } + } + }) + await payIntoChallenge(page, signIn) + + await cancelPayment(page).click() + + await expect(footnote(page)).toHaveText(PHASE_B) + await expect(cancelPayment(page)).toBeHidden() + await expect(payButton(page)).toBeDisabled() + await expect(backArrow(page)).toBeHidden() + + await releaseChallenge(page, 'succeeded') + moveOperation(succeededOperation(OPERATION)) + + await expect( + page.getByRole('heading', { name: "You're all set" }) + ).toBeVisible() + expect(cancelRequests(cloud)).toHaveLength(1) +}) + +test('786-16245: a second click while the cancel is settling sends nothing more, and the page asks again until it settles', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + const moveOperation = scriptOperation(cloud) + const asked = { times: 0 } + cloud.reply('POST', CANCEL_PATH, () => { + asked.times += 1 + if (asked.times === 1) + return { + status: 202, + body: { billing_op_id: OPERATION, status: 'cancel_requested' } + } + moveOperation(canceledOperation()) + return { body: { billing_op_id: OPERATION, status: 'canceled' } } + }) + await payIntoChallenge(page, signIn) + + await cancelPayment(page).dblclick() + + await expect(page.getByRole('button', { name: 'Canceling…' })).toBeDisabled() + await expect(footnote(page)).toHaveText(PHASE_A) + await expect(cancelPayment(page)).toBeHidden() + await expect(footnote(page)).toHaveText('') + await expect(page.getByRole('alert')).toBeHidden() + expect(cancelRequests(cloud)).toHaveLength(2) +}) + +test('786-16314: a payment the server will not cancel hides Cancel payment and says why', async ({ + page, + cloud, + signIn +}) => { + cloud.scenario.paymentMethods = [] + scriptOperation(cloud) + cloud.reply('POST', CANCEL_PATH, () => ({ + status: 409, + body: { + code: 'NOT_CANCELABLE', + message: 'billing operation is not waiting on authentication' + } + })) + await payIntoChallenge(page, signIn) + + await cancelPayment(page).click() + + await expect( + page.getByText( + "This payment can't be canceled right now. Finish verifying, or contact support if it doesn't go through." + ) + ).toBeVisible() + await expect(cancelPayment(page)).toBeHidden() + await expect(footnote(page)).toHaveText(PHASE_A) + await expect( + page.getByRole('heading', { name: "You're all set" }) + ).toBeHidden() +}) diff --git a/apps/billing-web/src/checkout/checkoutPage.test.ts b/apps/billing-web/src/checkout/checkoutPage.test.ts index 7d7dcb5bf50..c607d005a90 100644 --- a/apps/billing-web/src/checkout/checkoutPage.test.ts +++ b/apps/billing-web/src/checkout/checkoutPage.test.ts @@ -19,6 +19,7 @@ import type { import { RESOLVING, awaitingServer, + cancelTarget, challengeToReopen, isChallengeReopenable, isLocked, @@ -1514,7 +1515,11 @@ describe('submitPhaseOf', () => { { name: 'a Pay whose operation asks for a challenge', page: capturing({ kind: 'sent', operation: challengedOperation() }), - phase: { kind: 'challenge', operation: challengedOperation() } + phase: { + kind: 'challenge', + operation: challengedOperation(), + cancel: 'offered' + } }, { name: 'a Pay whose operation is processing', @@ -1536,7 +1541,57 @@ describe('submitPhaseOf', () => { { name: 'waiting over a challenge', page: { kind: 'waiting', operation: challengedOperation() }, - phase: { kind: 'challenge', operation: challengedOperation() } + phase: { + kind: 'challenge', + operation: challengedOperation(), + cancel: 'offered' + } + }, + { + name: 'a top-up waiting over a challenge, which the server never cancels', + page: { + kind: 'waiting', + operation: { ...challengedOperation(), kind: 'topup' } + }, + phase: { + kind: 'challenge', + operation: { ...challengedOperation(), kind: 'topup' } + } + }, + { + name: 'a challenge whose cancel the server is settling', + page: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: 'canceling' + }), + phase: { + kind: 'challenge', + operation: challengedOperation(), + cancel: 'canceling' + } + }, + { + name: 'a challenge the server would not cancel', + page: { + kind: 'waiting', + operation: challengedOperation(), + cancel: 'NOT_CANCELABLE' + }, + phase: { + kind: 'challenge', + operation: challengedOperation(), + cancel: 'not_cancelable' + } + }, + { + name: 'a challenge whose payment won the race to cancel it', + page: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: 'PAYMENT_IN_FLIGHT' + }), + phase: { kind: 'processing' } }, { name: 'waiting over money the bank has not answered for', @@ -1800,3 +1855,228 @@ describe('reduceCheckoutPage through a challenge', () => { expect(railAcceptsPay(replay(events))).toBe(pay) }) }) + +describe('reduceCheckoutPage through Cancel payment', () => { + const challenged = [...live, submitted, changed(challengedOperation())] + const cancel: CheckoutPageEvent = { type: 'cancelRequested' } + const canceledHere: CheckoutPageEvent = { + type: 'paymentCanceled', + operationId: 'op_3ds' + } + const refusedAs = ( + code: 'NOT_CANCELABLE' | 'PAYMENT_IN_FLIGHT' + ): CheckoutPageEvent => ({ type: 'cancelRefused', code }) + + it.for<{ name: string; events: CheckoutPageEvent[]; expected: CheckoutPage }>( + [ + { + name: "this page's own Pay holds Cancel until the server answers", + events: [...challenged, cancel], + expected: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: 'canceling' + }) + }, + { + name: 'a second click while a cancel is unanswered', + events: [...challenged, cancel, cancel], + expected: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: 'canceling' + }) + }, + { + name: 'a cancel the server settled goes back to the form, as typed, with no card', + events: [...challenged, cancel, canceledHere], + expected: { ...capturing({ kind: 'idle' }), canceled: 'op_3ds' } + }, + { + name: 'a read of the canceled operation taken before the cancel committed keeps the form', + events: [ + ...challenged, + cancel, + canceledHere, + changed(challengedOperation()) + ], + expected: { ...capturing({ kind: 'idle' }), canceled: 'op_3ds' } + }, + { + name: "the canceled operation's unpaid end is not a card", + events: [ + ...challenged, + cancel, + canceledHere, + changed( + failedOperation('authentication_failed', 'op_3ds'), + notCompleted + ) + ], + expected: { ...capturing({ kind: 'idle' }), canceled: 'op_3ds' } + }, + { + name: "a cancel settled after the operation's own verdict drops that card", + events: [ + ...challenged, + cancel, + changed(refusedChallenge(), notCompleted), + canceledHere + ], + expected: { ...capturing({ kind: 'idle' }), canceled: 'op_3ds' } + }, + { + name: 'a verdict the operation reaches while the cancel is unanswered shows once the server refuses the cancel', + events: [ + ...challenged, + cancel, + changed(refusedChallenge(), notCompleted), + refusedAs('NOT_CANCELABLE'), + reconciled(refusedChallenge(), notCompleted) + ], + expected: { ...capturing({ kind: 'idle' }), outcome: notCompleted } + }, + { + name: 'a payment that won the race keeps the form locked and follows the operation', + events: [...challenged, cancel, refusedAs('PAYMENT_IN_FLIGHT')], + expected: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: 'PAYMENT_IN_FLIGHT' + }) + }, + { + name: 'a payment that won the race still lands on its success', + events: [ + ...challenged, + cancel, + refusedAs('PAYMENT_IN_FLIGHT'), + changed(succeededOperation('op_3ds')) + ], + expected: { + kind: 'terminal', + operation: succeededOperation('op_3ds'), + attribution: 'started' + } + }, + { + name: 'a cancel that got no answer offers Cancel again', + events: [...challenged, cancel, { type: 'cancelFailed' }], + expected: capturing({ + kind: 'sent', + operation: challengedOperation(), + cancel: undefined + }) + }, + { + name: 'a page that arrived on the challenge resolves a fresh form once canceled', + events: [reconciled(challengedOperation()), cancel, canceledHere], + expected: { kind: 'resolving', canceled: 'op_3ds' } + }, + { + name: 'a page that arrived on the challenge holds its verdict while the cancel is unanswered', + events: [ + reconciled(challengedOperation()), + cancel, + changed( + failedOperation('authentication_failed', 'op_3ds'), + notCompleted + ) + ], + expected: { + kind: 'waiting', + operation: challengedOperation(), + cancel: 'canceling' + } + }, + { + name: 'a fresh form after a cancel opens with no card for the canceled operation', + events: [ + reconciled(challengedOperation()), + cancel, + canceledHere, + reconciled( + failedOperation('authentication_failed', 'op_3ds'), + notCompleted + ), + quoted(0) + ], + expected: { + kind: 'capture', + rail: { + method: 'collect', + element: 'loading', + saved: 'none', + tab: 'new' + }, + reactivation: 'not_required', + attempt: { kind: 'idle' }, + canceled: 'op_3ds' + } + }, + { + name: 'a refusal keeps a page that arrived on the challenge waiting', + events: [ + reconciled(challengedOperation()), + cancel, + refusedAs('NOT_CANCELABLE') + ], + expected: { + kind: 'waiting', + operation: challengedOperation(), + cancel: 'NOT_CANCELABLE' + } + }, + { + name: 'Cancel on a top-up challenge sends nothing', + events: [ + reconciled({ ...challengedOperation(), kind: 'topup' }), + cancel + ], + expected: { + kind: 'waiting', + operation: { ...challengedOperation(), kind: 'topup' } + } + }, + { + name: 'Cancel once the bank has moved on to processing sends nothing', + events: [ + ...live, + submitted, + changed({ + ...pendingOperation('op_3ds'), + authenticationState: 'processing' + }), + cancel + ], + expected: capturing({ + kind: 'sent', + operation: { + ...pendingOperation('op_3ds'), + authenticationState: 'processing' + } + }) + } + ] + )('$name', ({ events, expected }) => { + expect(replay(events)).toEqual(expected) + }) + + it.for<{ name: string; events: CheckoutPageEvent[]; target?: string }>([ + { name: 'a challenge still pending', events: challenged, target: 'op_3ds' }, + { name: 'a cancel already asked', events: [...challenged, cancel] }, + { + name: 'a cancel the server refused', + events: [...challenged, cancel, refusedAs('NOT_CANCELABLE')] + }, + { name: 'a Pay with no operation yet', events: [...live, submitted] } + ])('cancels $target on $name', ({ events, target }) => { + expect(cancelTarget(replay(events))).toBe(target) + }) + + it('accepts Pay again once the server canceled the challenge', () => { + expect(railAcceptsPay(replay([...challenged, cancel, canceledHere]))).toBe( + true + ) + }) +}) diff --git a/apps/billing-web/src/checkout/checkoutPage.ts b/apps/billing-web/src/checkout/checkoutPage.ts index 2c829d0173b..a4e86df5ad5 100644 --- a/apps/billing-web/src/checkout/checkoutPage.ts +++ b/apps/billing-web/src/checkout/checkoutPage.ts @@ -1,6 +1,7 @@ import type { BillingOperationState, BillingPlansData, + CancelRefusalCode, CapabilityDenialReason, PaymentReasonKey, PendingBillingOperation, @@ -72,6 +73,12 @@ export type InlineOutcome = */ export type Reactivation = 'not_required' | 'required' | 'invalid' | 'confirmed' +/** + * Cancel payment on a challenge still pending. `canceling` from the click + * until the server settles it, the code once the server kept the payment. + */ +type PaymentCancel = 'canceling' | CancelRefusalCode + /** * `sent` from the Pay click until the attempt settles, so an operation the * lifecycle publishes meanwhile is known to be this page's own and is kept @@ -85,6 +92,7 @@ export type Attempt = readonly kind: 'sent' readonly redirectMethod?: string readonly operation?: PendingBillingOperation + readonly cancel?: PaymentCancel } const IDLE: Attempt = { kind: 'idle' } @@ -95,6 +103,8 @@ type Capture = { readonly reactivation: Reactivation readonly attempt: Attempt readonly outcome?: InlineOutcome + /** The operation the server canceled from here; a later read of it is stale. */ + readonly canceled?: string } /** @@ -142,6 +152,7 @@ export type CheckoutPage = readonly kind: 'resolving' readonly outcome?: InlineOutcome readonly settled?: TerminalBillingOperation + readonly canceled?: string } | { readonly kind: 'refused' @@ -163,6 +174,7 @@ export type CheckoutPage = readonly operation: PendingBillingOperation readonly sibling?: true readonly rail?: PaymentRail + readonly cancel?: PaymentCancel } | { readonly kind: 'unconfirmed' @@ -263,6 +275,14 @@ export type CheckoutPageEvent = readonly operation: BillingOperationState readonly outcome?: OperationOutcome } + /** Cancel payment clicked on a challenge still pending. */ + | { readonly type: 'cancelRequested' } + /** The server dropped the operation; nothing was charged. */ + | { readonly type: 'paymentCanceled'; readonly operationId: string } + /** The server kept the payment it was asked to cancel. */ + | { readonly type: 'cancelRefused'; readonly code: CancelRefusalCode } + /** The cancel got no answer that names the payment's fate. */ + | { readonly type: 'cancelFailed' } export const RESOLVING: CheckoutPage = { kind: 'resolving' } @@ -409,6 +429,7 @@ export function reduceCheckoutPage( ): CheckoutPage { if (isRailEvent(event)) return reduceRail(page, event) if (isAttemptEvent(event)) return reduceAttempt(page, event) + if (isCancelEvent(event)) return reduceCancel(page, event) if (isStopEvent(event)) return page.kind === 'resolving' ? stoppedOn(page, event) : page switch (event.type) { @@ -435,6 +456,142 @@ export function reduceCheckoutPage( } } +type CancelEvent = Extract< + CheckoutPageEvent, + { + type: + | 'cancelRequested' + | 'cancelRefused' + | 'cancelFailed' + | 'paymentCanceled' + } +> + +const CANCEL_EVENT: Readonly> = { + cancelRequested: true, + cancelRefused: true, + cancelFailed: true, + paymentCanceled: true +} + +function isCancelEvent(event: CheckoutPageEvent): event is CancelEvent { + return Object.hasOwn(CANCEL_EVENT, event.type) +} + +/** Cancel payment on a challenge, from the click to the server's answer. */ +function reduceCancel(page: CheckoutPage, event: CancelEvent): CheckoutPage { + switch (event.type) { + case 'cancelRequested': + return cancelTarget(page) === undefined + ? page + : withCancel(page, 'canceling') + case 'cancelRefused': + return isCanceling(page) ? withCancel(page, event.code) : page + case 'cancelFailed': + return isCanceling(page) ? withCancel(page, undefined) : page + case 'paymentCanceled': + return canceled(page, event.operationId) + } +} + +function cancelOf(page: CheckoutPage): PaymentCancel | undefined { + if (page.kind === 'waiting') return page.cancel + return page.kind === 'capture' && page.attempt.kind === 'sent' + ? page.attempt.cancel + : undefined +} + +export const isCanceling = (page: CheckoutPage) => + cancelOf(page) === 'canceling' + +function withCancel( + page: CheckoutPage, + cancel: PaymentCancel | undefined +): CheckoutPage { + if (page.kind === 'waiting') return { ...page, cancel } + if (page.kind !== 'capture' || page.attempt.kind !== 'sent') return page + return { ...page, attempt: { ...page.attempt, cancel } } +} + +/** + * The operation Cancel payment would cancel: a plan payment whose challenge + * is still pending, with no cancel already asked or refused. + */ +export function cancelTarget(page: CheckoutPage): string | undefined { + if (page.kind !== 'capture' && page.kind !== 'waiting') return undefined + const phase = submitPhaseOf(page) + return phase.kind === 'challenge' && phase.cancel === 'offered' + ? phase.operation.id + : undefined +} + +/** A card the canceled operation earned on its way out is not a verdict to show. */ +function namesOperation( + outcome: InlineOutcome | undefined, + operationId: string +): boolean { + return ( + outcome !== undefined && + 'operationId' in outcome && + outcome.operationId === operationId + ) +} + +/** + * Cancel is navigation, never an outcome: this page's own Pay goes back to + * the form it was sent from, as typed; a page that arrived on the money + * resolves a fresh one. + */ +function canceled(page: CheckoutPage, operationId: string): CheckoutPage { + switch (page.kind) { + case 'waiting': + return page.operation.id === operationId + ? { kind: 'resolving', canceled: operationId } + : page + case 'resolving': + return namesOperation(page.outcome, operationId) + ? { kind: 'resolving', canceled: operationId } + : { ...page, canceled: operationId } + case 'capture': + return { ...canceledInCapture(page, operationId), canceled: operationId } + default: + return page + } +} + +function canceledInCapture(page: Capture, operationId: string): Capture { + if ( + page.attempt.kind === 'sent' && + page.attempt.operation?.id === operationId + ) + return { ...page, attempt: IDLE } + return namesOperation(page.outcome, operationId) + ? { ...page, outcome: undefined } + : page +} + +/** A verdict reached while the server settles a cancel waits for its answer. */ +const heldForCancel = ( + page: CheckoutPage, + outcome: OperationOutcome | undefined +) => outcome !== undefined && isCanceling(page) + +/** + * A read of a canceled operation still short of its end, or ending unpaid, + * says nothing new: a poll taken before the cancel committed can land after + * it, and the unpaid end is the cancel itself, not a verdict. + */ +function isCanceledHere( + page: CheckoutPage, + operation: BillingOperationState +): boolean { + return ( + (page.kind === 'capture' || page.kind === 'resolving') && + page.canceled === operation.id && + operation.phase !== 'succeeded' + ) +} + /** A lapsed code changed the price, so its card outranks a carried verdict. */ function arrivedOutcome( page: Extract, @@ -473,7 +630,8 @@ function arrived( rail: quotedRail(event), reactivation: reactivationOf(event.reactivation), attempt: IDLE, - ...(outcome === undefined ? {} : { outcome }) + ...(outcome === undefined ? {} : { outcome }), + ...(page.canceled === undefined ? {} : { canceled: page.canceled }) } } @@ -759,6 +917,8 @@ function followed( operation: BillingOperationState, outcome: OperationOutcome | undefined ): CheckoutPage { + if (isCanceledHere(page, operation) || heldForCancel(page, outcome)) + return page if (page.kind === 'terminal') return withSettled(page, operation) if (page.kind === 'resolving') return arrivedOn(page, operation, outcome) if (page.kind === 'capture') @@ -940,26 +1100,63 @@ export type SubmitPhase = | { readonly kind: 'capture' } | { readonly kind: 'unknown' } | { readonly kind: 'processing' } - | { readonly kind: 'challenge'; readonly operation: PendingBillingOperation } + | { + readonly kind: 'challenge' + readonly operation: PendingBillingOperation + readonly cancel?: CancelOffer + } | { readonly kind: 'redirecting'; readonly method: string } +/** + * What Cancel payment offers on a challenge. Absent for an operation the + * server never cancels (a top-up), so the button never shows there. + */ +export type CancelOffer = 'offered' | 'canceling' | 'not_cancelable' + export function submitPhaseOf( page: Extract ): SubmitPhase { - if (page.kind === 'waiting') return phaseOver(page.operation) + if (page.kind === 'waiting') return phaseOver(page.operation, page.cancel) if (page.kind !== 'capture' || page.attempt.kind === 'idle') return { kind: 'capture' } - const { redirectMethod, operation } = page.attempt + const { redirectMethod, operation, cancel } = page.attempt if (redirectMethod !== undefined) return { kind: 'redirecting', method: redirectMethod } - return operation === undefined ? { kind: 'unknown' } : phaseOver(operation) + return operation === undefined + ? { kind: 'unknown' } + : phaseOver(operation, cancel) } -function phaseOver(operation: PendingBillingOperation): SubmitPhase { - if (isChallengePending(operation)) return { kind: 'challenge', operation } +/** A payment the server would not cancel because it is already moving is Phase B on its word. */ +function phaseOver( + operation: PendingBillingOperation, + cancel: PaymentCancel | undefined +): SubmitPhase { + if (cancel === 'PAYMENT_IN_FLIGHT') return { kind: 'processing' } + if (isChallengePending(operation)) + return { + kind: 'challenge', + operation, + ...cancelOfferOf(operation, cancel) + } return isProcessing(operation) ? { kind: 'processing' } : { kind: 'unknown' } } +const CANCEL_OFFER: Readonly< + Record, CancelOffer> +> = { + canceling: 'canceling', + NOT_CANCELABLE: 'not_cancelable' +} + +function cancelOfferOf( + operation: PendingBillingOperation, + cancel: Exclude | undefined +): { readonly cancel?: CancelOffer } { + if (operation.kind !== 'subscription') return {} + return { cancel: cancel === undefined ? 'offered' : CANCEL_OFFER[cancel] } +} + /** Past the bank's challenge on the server's word, so it can no longer be called back. */ function isProcessing(operation: PendingBillingOperation): boolean { return ( @@ -1007,13 +1204,6 @@ export function challengeToReopen(page: CheckoutPage): string | undefined { : undefined } -/** - * No endpoint cancels a pending payment yet (BE gap named on FE-3022), so - * Cancel payment stays hidden rather than claiming a cancel the server - * never made. Flip this once the endpoint lands and wire the click to it. - */ -export const PENDING_PAYMENT_CANCEL_AVAILABLE = false - /** * What the payment column shows for a rail. With no saved method to fall * back on, a failed element takes the whole column; otherwise each failure diff --git a/apps/billing-web/src/components/fullPage/CancelPaymentControl.vue b/apps/billing-web/src/components/fullPage/CancelPaymentControl.vue new file mode 100644 index 00000000000..00e9fc2ce23 --- /dev/null +++ b/apps/billing-web/src/components/fullPage/CancelPaymentControl.vue @@ -0,0 +1,37 @@ + + + diff --git a/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts b/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts index f5dde5c15f6..80fd730259e 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts +++ b/apps/billing-web/src/components/fullPage/CheckoutPayAction.test.ts @@ -19,7 +19,6 @@ const challenge = ( function renderPayAction( props: { phase?: SubmitPhase - canCancel?: boolean loading?: boolean disabled?: boolean onCancel?: () => void @@ -40,82 +39,130 @@ 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: ['Pay and subscribe'] }, { name: 'a Pay the bank has not answered yet', phase: { kind: 'unknown' }, - canCancel: true, line: '', buttons: ['Pay and subscribe'] }, { name: 'a charge processing', phase: { kind: 'processing' }, - canCancel: true, line: "This payment is already processing and can't be canceled.", buttons: ['Pay and subscribe'] }, { - name: 'a challenge the customer can reopen', + name: 'a challenge the server never cancels', phase: { kind: 'challenge', operation: challenge('required') }, - canCancel: false, line: 'Nothing has been charged yet.', buttons: ['Complete verification'] }, { - name: 'a challenge this tab is showing', + name: 'a challenge this tab is showing, with no cancel to offer', phase: { kind: 'challenge', operation: challenge('in_progress') }, - canCancel: false, line: 'Nothing has been charged yet.', buttons: ['Pay and subscribe'] }, { - name: 'a reopenable challenge once the server can cancel it', - phase: { kind: 'challenge', operation: challenge('required') }, - canCancel: true, + name: 'a reopenable challenge the server can cancel', + phase: { + kind: 'challenge', + operation: challenge('required'), + cancel: 'offered' + }, line: 'Nothing has been charged yet.', buttons: ['Complete verification', 'Cancel payment'] }, { - name: 'a challenge on screen once the server can cancel it', - phase: { kind: 'challenge', operation: challenge('in_progress') }, - canCancel: true, + name: 'a challenge on screen the server can cancel', + phase: { + kind: 'challenge', + operation: challenge('in_progress'), + cancel: 'offered' + }, line: 'Nothing has been charged yet.', buttons: ['Pay and subscribe', 'Cancel payment'] }, + { + name: 'a challenge whose cancel the server is settling', + phase: { + kind: 'challenge', + operation: challenge('required'), + cancel: 'canceling' + }, + line: 'Nothing has been charged yet.', + buttons: ['Complete verification', 'Canceling…'] + }, + { + name: 'a challenge the server would not cancel', + phase: { + kind: 'challenge', + operation: challenge('required'), + cancel: 'not_cancelable' + }, + line: 'Nothing has been charged yet.', + buttons: ['Complete verification'] + }, { 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: ['Pay and subscribe'] }, { 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: ['Pay and subscribe'] } - ])( - 'shows $name with its line and buttons', - ({ phase, canCancel, line, buttons }) => { - renderPayAction({ phase, canCancel }) + ])('shows $name with its line and buttons', ({ phase, line, buttons }) => { + renderPayAction({ phase }) - expect(footnote().textContent.trim()).toBe(line) - expect(buttonNames()).toEqual(buttons) - } - ) + expect(footnote().textContent.trim()).toBe(line) + expect(buttonNames()).toEqual(buttons) + }) + + it('holds both buttons while the server settles a cancel', () => { + renderPayAction({ + phase: { + kind: 'challenge', + operation: challenge('required'), + cancel: 'canceling' + } + }) + + expect( + screen.getByRole('button', { name: 'Complete verification' }) + ).toBeDisabled() + const canceling = screen.getByRole('button', { name: 'Canceling…' }) + expect(canceling).toBeDisabled() + expect(canceling).toHaveAttribute('aria-busy', 'true') + }) + + it('says why a payment the server would not cancel has no Cancel payment', () => { + renderPayAction({ + phase: { + kind: 'challenge', + operation: challenge('required'), + cancel: 'not_cancelable' + } + }) + + expect( + screen.getByText( + "This payment can't be canceled right now. Finish verifying, or contact support if it doesn't go through." + ) + ).toBeVisible() + }) it('keeps Complete verification live while the page is locked', async () => { const onContinueVerification = vi.fn() @@ -153,8 +200,11 @@ describe('CheckoutPayAction', () => { it('emits cancel from Cancel payment', async () => { const onCancel = vi.fn() renderPayAction({ - phase: { kind: 'challenge', operation: challenge('in_progress') }, - canCancel: true, + phase: { + kind: 'challenge', + operation: challenge('in_progress'), + cancel: 'offered' + }, onCancel }) diff --git a/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue b/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue index 876de8b69e5..a16bb4574d6 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue +++ b/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue @@ -9,6 +9,7 @@ import { cn } from '@comfyorg/tailwind-utils' import type { InlineOutcome, SubmitPhase } from '@/checkout/checkoutPage' import { isChallengeReopenable } from '@/checkout/checkoutPage' import { supportLinkFor } from '@/checkout/payVerdict' +import CancelPaymentControl from '@/components/fullPage/CancelPaymentControl.vue' import InlineOutcomeCard from '@/components/fullPage/InlineOutcomeCard.vue' import type { KeepSubscriptionConsent } from '@/components/fullPage/KeepSubscriptionNotice.vue' import KeepSubscriptionNotice from '@/components/fullPage/KeepSubscriptionNotice.vue' @@ -23,7 +24,6 @@ const { disabled, loading = false, phase, - canCancel = false, locked = false, reopening = false, outcome, @@ -37,8 +37,6 @@ const { 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 /** Money is on its way, so the consent it was sent with stands. */ locked?: boolean /** The page is re-opening the challenge on its own; offering it too would flash. */ @@ -115,6 +113,12 @@ const challenge = computed(() => phase?.kind === 'challenge' ? phase.operation : undefined ) +const cancel = computed(() => + phase?.kind === 'challenge' ? phase.cancel : undefined +) + +const canceling = computed(() => cancel.value === 'canceling') + /** A challenge the page is not showing, and is not about to, turns Pay into the one way back to it. */ const reopenable = computed( () => @@ -125,9 +129,6 @@ const reopenable = computed( const PRIMARY_BUTTON = 'flex h-10 w-full cursor-pointer items-center justify-center gap-2 rounded-lg bg-base-foreground px-4 text-sm font-semibold text-base-background transition-opacity hover:opacity-90 focus-visible:ring-2 focus-visible:ring-base-foreground focus-visible:ring-offset-2 focus-visible:ring-offset-secondary-background focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-40' - -const SECONDARY_BUTTON = - 'flex h-10 w-full cursor-pointer items-center justify-center rounded-lg bg-tertiary-background px-4 text-sm font-semibold text-base-foreground hover:bg-tertiary-background-hover focus-visible:ring-2 focus-visible:ring-base-foreground focus-visible:outline-none'