From 3152715cde08b86c116e4406e19c196b7c76a9be Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 17:10:52 -0400 Subject: [PATCH 1/7] feat(account-core): cancel a billing operation waiting on authentication --- .../billing-web/src/test/fakeBillingClient.ts | 1 + .../account-core/src/core/billing/index.ts | 2 + .../core/billing/subscriptionCommands.test.ts | 87 +++++++++++++++++++ .../src/core/billing/subscriptionCommands.ts | 54 ++++++++++++ .../billing/sdk/billingSdkTestUtils.ts | 1 + 5 files changed, 145 insertions(+) diff --git a/apps/billing-web/src/test/fakeBillingClient.ts b/apps/billing-web/src/test/fakeBillingClient.ts index fbd1d3ceb60..958f3cd9dcf 100644 --- a/apps/billing-web/src/test/fakeBillingClient.ts +++ b/apps/billing-web/src/test/fakeBillingClient.ts @@ -310,6 +310,7 @@ export function createFakeBillingClient( previewSubscribe, resubscribe, cancelSubscription, + cancelOperation: unusedByHostedSurfaces('commands.cancelOperation'), openPaymentPortal } } diff --git a/packages/account-core/src/core/billing/index.ts b/packages/account-core/src/core/billing/index.ts index 8a6e1905a0c..6e8410e5252 100644 --- a/packages/account-core/src/core/billing/index.ts +++ b/packages/account-core/src/core/billing/index.ts @@ -183,6 +183,8 @@ export { export type { BillingCommands, BillingCommandsOptions, + CancelOperationResult, + CancelRefusalCode, PaymentPortalResult, PreviewSubscribeInput, PreviewSubscribeOptions, diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts index b13cffd27a4..c9365afd6fc 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts @@ -41,6 +41,7 @@ import { PREVIEW_SUBSCRIBE_ROUTE, RESUBSCRIBE_ROUTE, SUBSCRIBE_ROUTE, + cancelOperationRoute, createBillingCommands } from './subscriptionCommands.js' @@ -246,6 +247,7 @@ const POST_CANCEL = `POST ${CANCEL_SUBSCRIPTION_ROUTE}` const POST_PORTAL = `POST ${PAYMENT_PORTAL_ROUTE}` const POST_PREVIEW = `POST ${PREVIEW_SUBSCRIBE_ROUTE}` const GET_OP = `GET ${operationRoute('op-1')}` +const POST_CANCEL_OP = `POST ${cancelOperationRoute('op-1')}` const subscribed = http(200, { billing_op_id: 'op-1', status: 'subscribed' }) const pendingPayment = http(200, { @@ -1310,6 +1312,91 @@ describe('createBillingCommands', () => { }) }) + describe('cancelOperation', () => { + it.for([ + { + answer: http(200, { billing_op_id: 'op-1', status: 'canceled' }), + result: { status: 'canceled' } + }, + { + answer: http(202, { + billing_op_id: 'op-1', + status: 'cancel_requested' + }), + result: { status: 'cancel_requested' } + }, + { + answer: serverError(409, 'NOT_CANCELABLE'), + result: { status: 'not_canceled', code: 'NOT_CANCELABLE' } + }, + { + answer: serverError(409, 'PAYMENT_IN_FLIGHT'), + result: { status: 'not_canceled', code: 'PAYMENT_IN_FLIGHT' } + }, + { + answer: serverError(404, 'NOT_FOUND'), + result: { status: 'error', code: 'NOT_FOUND', httpStatus: 404 } + }, + { + answer: serverError(502, 'PAYMENT_IN_FLIGHT'), + result: { status: 'error', code: 'REQUEST_FAILED', httpStatus: 502 } + }, + { + answer: http(200, { billing_op_id: 'op-1', status: 'charged' }), + result: { status: 'error', code: 'MALFORMED_RESPONSE' } + } + ])( + 'answers $result.status ($result.code) for a $answer.value.httpStatus', + async ({ answer, result }) => { + const h = harness({ + status: PRO_ACTIVE, + script: { [POST_CANCEL_OP]: [answer] } + }) + + await expect(h.commands.cancelOperation('op-1')).resolves.toMatchObject( + result + ) + expect(h.posts()).toEqual([ + expect.objectContaining({ route: cancelOperationRoute('op-1') }) + ]) + } + ) + + it('reads the followed operation back at once after the server cancels it', async () => { + const h = harness({ + status: FREE, + script: { + [POST_SUBSCRIBE]: [pendingPayment], + [POST_CANCEL_OP]: [ + http(200, { billing_op_id: 'op-1', status: 'canceled' }) + ], + [GET_OP]: [ + http(200, opStatus({ authentication_state: 'requires_action' })), + http( + 200, + opStatus({ + status: 'failed', + decline_reason: 'authentication_failed' + }) + ) + ] + } + }) + const subscribed = h.commands.subscribe(PLAN) + await flush() + expect(h.lifecycle.get('op-1')).toMatchObject({ phase: 'pending' }) + + await h.commands.cancelOperation('op-1') + await flush() + + expect(h.lifecycle.get('op-1')).toMatchObject({ phase: 'failed' }) + await expect(subscribed).resolves.toMatchObject({ + status: 'ok', + value: { phase: 'failed' } + }) + }) + }) + describe('unexpected errors', () => { it('passes a transport failure through without adopting anything', async () => { const h = harness({ diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts index b19bfc4b9b8..9e244c653f0 100644 --- a/packages/account-core/src/core/billing/subscriptionCommands.ts +++ b/packages/account-core/src/core/billing/subscriptionCommands.ts @@ -12,6 +12,7 @@ * as the transport's coded failure. */ import { + zCancelBillingOpResponse, zCancelSubscriptionResponse2, zPaymentPortalResponse, zPreviewPlanInfo, @@ -31,6 +32,7 @@ import type { BillingOperationLifecycle, IssuedBillingOperation } from './operationLifecycle.js' +import { operationRoute } from './operationLifecycle.js' import type { BillingOperationKind, BillingOperationState, @@ -48,6 +50,10 @@ export const CANCEL_SUBSCRIPTION_ROUTE = '/billing/subscription/cancel' export const PAYMENT_PORTAL_ROUTE = '/billing/payment-portal' export const PREVIEW_SUBSCRIBE_ROUTE = '/billing/preview-subscribe' +export function cancelOperationRoute(operationId: string): string { + return `${operationRoute(operationId)}/cancel` +} + /** The closed set of `serverCode` values these commands act on. */ const NO_ACTIVE_SUBSCRIPTION_SERVER_CODE = 'NO_ACTIVE_SUBSCRIPTION' const REACTIVATION_CONFIRMATION_REQUIRED_SERVER_CODE = @@ -58,6 +64,10 @@ const ALREADY_CANCELED_SERVER_CODE = 'ALREADY_CANCELED' const SUBSCRIPTION_QUOTE_STALE_SERVER_CODE = 'SUBSCRIPTION_QUOTE_STALE' const SUBSCRIPTION_CHANGE_IN_PROGRESS_SERVER_CODE = 'SUBSCRIPTION_CHANGE_IN_PROGRESS' +const CANCEL_REFUSAL_SERVER_CODES = [ + 'NOT_CANCELABLE', + 'PAYMENT_IN_FLIGHT' +] as const export type SubscribeInput = z.infer @@ -108,6 +118,23 @@ export type SubscriptionCommandResult = | { readonly status: 'ok'; readonly value: SubscriptionCommandOutcome } | SubscriptionCommandFailure +/** + * Why the server kept a payment it was asked to cancel. `PAYMENT_IN_FLIGHT`: + * the payment won the race and the operation will settle on its own. + * `NOT_CANCELABLE`: the operation is not one waiting on authentication. + */ +export type CancelRefusalCode = (typeof CANCEL_REFUSAL_SERVER_CODES)[number] + +/** + * The server's answer to cancelling a pending operation. `canceled`: dropped, + * nothing charged, also for one already discarded. `cancel_requested`: the + * cancel was delivered but has not settled; asking again is safe. + */ +export type CancelOperationResult = + | { readonly status: 'canceled' | 'cancel_requested' } + | { readonly status: 'not_canceled'; readonly code: CancelRefusalCode } + | BillingFailure + export type PaymentPortalResult = | { readonly status: 'ok'; readonly value: { readonly url: string } } | BillingFailure @@ -190,6 +217,12 @@ export interface BillingCommands { ) => Promise resubscribe: () => Promise cancelSubscription: () => Promise + /** + * Asks the server to drop an operation still waiting on the customer's + * authentication. Any answer that names the operation's fate wakes the + * lifecycle, so the operation it follows catches up with the server. + */ + cancelOperation: (operationId: string) => Promise /** Returns the portal URL; the host decides how to open it. */ openPaymentPortal: (input: { readonly returnUrl?: string @@ -494,11 +527,32 @@ export function createBillingCommands( return { status: 'ok', value: { url } } } + async function cancelOperation( + operationId: string + ): Promise { + const response = await post( + cancelOperationRoute(operationId), + undefined, + (body) => zCancelBillingOpResponse.safeParse(body) + ) + if (response.status === 'error') { + const refusal = CANCEL_REFUSAL_SERVER_CODES.find((code) => + refusedWith(response, code) + ) + if (refusal === undefined) return response + lifecycle.wake() + return { status: 'not_canceled', code: refusal } + } + lifecycle.wake() + return { status: response.value.data.status } + } + return { subscribe, previewSubscribe, resubscribe, cancelSubscription: () => settle('cancel', issueCancel), + cancelOperation, openPaymentPortal } } diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index cc5a2f4def8..634df21a10f 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -149,6 +149,7 @@ export function fakeBillingSdk() { previewSubscribe: vi.fn(), resubscribe: vi.fn(), cancelSubscription: vi.fn(), + cancelOperation: vi.fn(), openPaymentPortal: vi.fn() }, driveChallenge: vi.fn(async () => 'completed' as const), From 8ae44953c3797271af90149a65c9326ed5cc6f5f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 17:19:23 -0400 Subject: [PATCH 2/7] feat(billing-web): cancel a payment while its 3DS challenge is pending --- apps/billing-web/e2e/fixtures/stripe.ts | 11 +- .../e2e/full-page-authentication.spec.ts | 159 ++++++++++++- .../src/checkout/checkoutPage.test.ts | 209 +++++++++++++++++- apps/billing-web/src/checkout/checkoutPage.ts | 150 +++++++++++-- .../fullPage/CheckoutPayAction.test.ts | 104 ++++++--- .../components/fullPage/CheckoutPayAction.vue | 35 ++- .../fullPage/CheckoutPaymentColumn.vue | 6 - .../src/composables/useFullPageCheckout.ts | 57 ++++- apps/billing-web/src/locales/en/main.json | 4 +- .../billing-web/src/test/fakeBillingClient.ts | 11 +- .../src/views/FullPageCheckoutView.test.ts | 34 ++- .../src/views/FullPageCheckoutView.vue | 11 +- 12 files changed, 713 insertions(+), 78 deletions(-) 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..9df9b0e479b 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,153 @@ 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' }) + }, + { + name: "a cancel settled after the operation's own verdict drops that card", + events: [ + ...challenged, + cancel, + changed(refusedChallenge(), notCompleted), + canceledHere + ], + expected: capturing({ kind: 'idle' }) + }, + { + 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: RESOLVING + }, + { + 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..0bf42a02765 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. + */ +export 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' } @@ -163,6 +171,7 @@ export type CheckoutPage = readonly operation: PendingBillingOperation readonly sibling?: true readonly rail?: PaymentRail + readonly cancel?: PaymentCancel } | { readonly kind: 'unconfirmed' @@ -263,6 +272,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' } @@ -432,6 +449,83 @@ export function reduceCheckoutPage( : followed(page, event.operation, event.outcome) case 'operationChanged': return followed(page, event.operation, event.outcome) + 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 +} + +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 ? RESOLVING : page + case 'resolving': + return namesOperation(page.outcome, operationId) ? RESOLVING : page + case 'capture': + if ( + page.attempt.kind === 'sent' && + page.attempt.operation?.id === operationId + ) + return { ...page, attempt: IDLE } + return namesOperation(page.outcome, operationId) + ? { ...page, outcome: undefined } + : page + default: + return page } } @@ -940,26 +1034,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 +1138,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/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..d0cf38b7984 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue +++ b/apps/billing-web/src/components/fullPage/CheckoutPayAction.vue @@ -23,7 +23,6 @@ const { disabled, loading = false, phase, - canCancel = false, locked = false, reopening = false, outcome, @@ -37,8 +36,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 +112,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( () => @@ -127,7 +130,7 @@ 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' + 'flex h-10 w-full cursor-pointer items-center justify-center gap-2 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 disabled:cursor-not-allowed disabled:opacity-40'