From 5ae4c8d1b6483092c1d63d32e397ae85d4b9ff64 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 17:55:39 -0400 Subject: [PATCH 01/19] feat(billing): add the checkout challenge events to the shared telemetry contract --- .../account-core/src/core/billing/index.ts | 5 +- .../src/core/billing/operationLifecycle.ts | 12 +++- .../telemetry/billingTelemetryEvent.ts | 2 + .../telemetry/checkoutChallengeEvent.ts | 27 ++++++++ .../telemetry/operationLifecycleEvent.test.ts | 62 +++++++++++++++++++ .../telemetry/operationLifecycleEvent.ts | 28 ++++++++- packages/account-core/src/telemetry.ts | 10 +++ 7 files changed, 141 insertions(+), 5 deletions(-) create mode 100644 packages/account-core/src/core/billing/telemetry/checkoutChallengeEvent.ts diff --git a/packages/account-core/src/core/billing/index.ts b/packages/account-core/src/core/billing/index.ts index 8a6e1905a0c..0c4843c662c 100644 --- a/packages/account-core/src/core/billing/index.ts +++ b/packages/account-core/src/core/billing/index.ts @@ -169,7 +169,10 @@ export { createBillingOperationLifecycle, operationRoute } from './operationLifecycle.js' -export { BILLING_OPERATION_TELEMETRY_EVENT } from '../../telemetry.js' +export { + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT, + BILLING_OPERATION_TELEMETRY_EVENT +} from '../../telemetry.js' export * from './telemetry/index.js' export type { EmbeddedChallengeOutcome, diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index 27323ac6b12..2844f8ee91a 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -17,7 +17,11 @@ * contract is new. */ -import { BILLING_OPERATION_TELEMETRY_EVENT } from '../../telemetry.js' +import type { + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT} from '../../telemetry.js'; +import { + BILLING_OPERATION_TELEMETRY_EVENT +} from '../../telemetry.js' import type { BillingFailure, BillingResult, @@ -90,8 +94,12 @@ export type BillingOperationFailureCategory = | 'reconciliation_needed' | 'stale_operation' +type BillingOperationTelemetryEventName = + | (typeof BILLING_OPERATION_TELEMETRY_EVENT)[keyof typeof BILLING_OPERATION_TELEMETRY_EVENT] + | (typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT)[keyof typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT] + export interface BillingOperationTelemetryEvent { - readonly name: (typeof BILLING_OPERATION_TELEMETRY_EVENT)[keyof typeof BILLING_OPERATION_TELEMETRY_EVENT] + readonly name: BillingOperationTelemetryEventName readonly billing_op_id: string readonly operation_type: BillingOperationKind readonly presentation: BillingPresentation diff --git a/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts b/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts index 631b65aecae..e12def8cdb0 100644 --- a/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts +++ b/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts @@ -1,4 +1,5 @@ import type { CapabilityReadBillingEvent } from './capabilityReadEvent.js' +import type { CheckoutChallengeBillingEvent } from './checkoutChallengeEvent.js' import type { DowngradeToPersonalBillingEvent } from './downgradeToPersonalEvent.js' import type { BillingOperationBillingEvent } from './operationEvent.js' import type { ResubscribeBillingEvent } from './resubscribeEvent.js' @@ -27,6 +28,7 @@ export type BillingTelemetryEvent = { | WebHandoffBillingEvent | WebReturnBillingEvent | WebSessionBillingEvent + | CheckoutChallengeBillingEvent ) type BillingTelemetryEventNameFor = diff --git a/packages/account-core/src/core/billing/telemetry/checkoutChallengeEvent.ts b/packages/account-core/src/core/billing/telemetry/checkoutChallengeEvent.ts new file mode 100644 index 00000000000..70d32359b9f --- /dev/null +++ b/packages/account-core/src/core/billing/telemetry/checkoutChallengeEvent.ts @@ -0,0 +1,27 @@ +import type { + BillingDeclineReason, + BillingOperationKind, + BillingPresentation +} from '../operationState.js' + +/** + * Payment friction inside one operation: a bank challenge the customer must + * complete, the verdict this tab saw, and each retryable decline the server + * reports while the operation stays open. None of these settle the + * operation, so every stage stays `pending`. A failure with a + * `decline_reason` is the server's retryable decline; one without is this + * tab's own challenge verdict. + */ +export type CheckoutChallengeBillingEvent = { + operation: 'checkout' + outcome: 'pending' + billing_op_id: string + operation_type: BillingOperationKind + presentation: BillingPresentation + /** True when this tab reattached to an operation it did not issue. */ + resumed?: boolean +} & ( + | { stage: 'challenge_required' } + | { stage: 'challenge_completed' } + | { stage: 'challenge_failed'; decline_reason?: BillingDeclineReason } +) diff --git a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts index 33c55d5908b..1b8a67f7f41 100644 --- a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts +++ b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts @@ -124,6 +124,68 @@ describe('toBillingTelemetryEvent', () => { failure_category: 'poll_timeout', duration_ms: 600_000 } + }, + { + name: 'a required challenge onto the checkout, never as an operation stage', + event: { + name: 'billing.checkout.challenge_required', + billing_op_id: 'op-challenge', + operation_type: 'subscription', + presentation: 'embedded', + resumed: false + }, + expected: { + operation: 'checkout', + billing_client: 'sdk', + stage: 'challenge_required', + outcome: 'pending', + operation_type: 'subscription', + billing_op_id: 'op-challenge', + presentation: 'embedded', + resumed: false + } + }, + { + name: 'a completed challenge as still pending, since the server settles the payment', + event: { + name: 'billing.checkout.challenge_completed', + billing_op_id: 'op-challenge', + operation_type: 'topup', + presentation: 'embedded', + resumed: true + }, + expected: { + operation: 'checkout', + billing_client: 'sdk', + stage: 'challenge_completed', + outcome: 'pending', + operation_type: 'topup', + billing_op_id: 'op-challenge', + presentation: 'embedded', + resumed: true + } + }, + { + name: 'a retryable decline with its reason', + event: { + name: 'billing.checkout.challenge_failed', + billing_op_id: 'op-retry', + operation_type: 'subscription', + presentation: 'hosted', + resumed: false, + decline_reason: 'card_declined' + }, + expected: { + operation: 'checkout', + billing_client: 'sdk', + stage: 'challenge_failed', + outcome: 'pending', + operation_type: 'subscription', + billing_op_id: 'op-retry', + presentation: 'hosted', + resumed: false, + decline_reason: 'card_declined' + } } ])('maps $name', ({ event, expected }) => { expect(toBillingTelemetryEvent(event)).toEqual(expected) diff --git a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts index f98e33ba7d7..0df58612b3e 100644 --- a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts +++ b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts @@ -1,15 +1,27 @@ -import { BILLING_OPERATION_TELEMETRY_EVENT } from '../../../telemetry.js' +import { + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT, + BILLING_OPERATION_TELEMETRY_EVENT +} from '../../../telemetry.js' import type { BillingOperationTelemetryEvent } from '../operationLifecycle.js' import type { BillingTelemetryEvent } from './billingTelemetryEvent.js' /** * The lifecycle's event onto the poller's `billing.operation.*` stages, so * both rails count in one funnel; only this rail sets `presentation` and - * `resumed`. + * `resumed`. Friction inside the operation maps onto `billing.checkout.*`. */ export function toBillingTelemetryEvent( event: BillingOperationTelemetryEvent ): BillingTelemetryEvent { + const friction = { + operation: 'checkout', + outcome: 'pending', + billing_client: 'sdk', + operation_type: event.operation_type, + billing_op_id: event.billing_op_id, + presentation: event.presentation, + resumed: event.resumed + } as const const shared = { operation: 'operation', billing_client: 'sdk', @@ -42,5 +54,17 @@ export function toBillingTelemetryEvent( failure_category: event.failure_category ?? 'provider_decline', decline_reason: event.decline_reason } + case BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeRequired: + return { ...friction, stage: 'challenge_required' } + case BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeCompleted: + return { ...friction, stage: 'challenge_completed' } + case BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeFailed: + return { + ...friction, + stage: 'challenge_failed', + ...(event.decline_reason === undefined + ? {} + : { decline_reason: event.decline_reason }) + } } } diff --git a/packages/account-core/src/telemetry.ts b/packages/account-core/src/telemetry.ts index 7497b3f872a..a373874ff5a 100644 --- a/packages/account-core/src/telemetry.ts +++ b/packages/account-core/src/telemetry.ts @@ -21,6 +21,16 @@ export const BILLING_OPERATION_TELEMETRY_EVENT = { timeout: 'billing.operation.timeout' } as const +/** + * Payment friction the lifecycle observes inside one operation: a bank + * challenge and its verdict, and each retryable decline. + */ +export const BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT = { + challengeRequired: 'billing.checkout.challenge_required', + challengeCompleted: 'billing.checkout.challenge_completed', + challengeFailed: 'billing.checkout.challenge_failed' +} as const + export const AUTH_TELEMETRY_EVENT = { signUpOpened: 'app:user_sign_up_opened', authCompleted: 'app:user_auth_completed', From c8d44b5db0b5e85deb379010dddb247dbaa438a5 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 17:56:42 -0400 Subject: [PATCH 02/19] test(billing): expect the lifecycle to report challenges and retryable declines --- .../core/billing/operationLifecycle.test.ts | 186 ++++++++++++++++++ .../billing/sdk/billingSdkStore.test.ts | 28 +++ 2 files changed, 214 insertions(+) diff --git a/packages/account-core/src/core/billing/operationLifecycle.test.ts b/packages/account-core/src/core/billing/operationLifecycle.test.ts index 1a41c674c9a..12439defd66 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.test.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.test.ts @@ -1553,3 +1553,189 @@ describe('createBillingOperationLifecycle', () => { }) }) }) + +describe('payment friction telemetry', () => { + function frictionOf(telemetry: BillingOperationTelemetryEvent[]) { + return telemetry + .filter((event) => event.name.startsWith('billing.checkout.')) + .map(({ name, presentation, decline_reason }) => + decline_reason === undefined + ? { name, presentation } + : { name, presentation, decline_reason } + ) + } + + const challengeRequired = (clientSecret: string) => + httpOk( + opStatus({ + authentication_state: 'requires_action', + payment_intent_client_secret: clientSecret + }) + ) + + it('reports a challenge the issued command already carried, with its operation', async () => { + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [challengeRequired('pi_secret')] + }) + + await lifecycle.begin( + 'subscription', + issued({ operationId: 'op-1', clientSecret: 'pi_secret' }) + ) + await flush() + + expect( + telemetry.filter((event) => event.name.startsWith('billing.checkout.')) + ).toEqual([ + { + name: 'billing.checkout.challenge_required', + billing_op_id: 'op-1', + operation_type: 'subscription', + presentation: 'embedded', + resumed: false + } + ]) + }) + + it('reports a challenge a status read surfaces once, however often it is echoed', async () => { + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [httpOk(opStatus()), challengeRequired('pi_secret')] + }) + + await lifecycle.begin('topup', issued()) + await flush() + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs * 3) + + expect(frictionOf(telemetry)).toEqual([ + { name: 'billing.checkout.challenge_required', presentation: 'embedded' } + ]) + }) + + it.for([ + { outcome: 'completed', expected: 'billing.checkout.challenge_completed' }, + { outcome: 'failed', expected: 'billing.checkout.challenge_failed' } + ] as const)( + 'reports the challenge this tab drove as $outcome', + async ({ outcome, expected }) => { + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [challengeRequired('pi_secret')] + }) + await lifecycle.begin( + 'topup', + issued({ operationId: 'op-1', clientSecret: 'pi_secret' }) + ) + await flush() + + lifecycle.reportChallengeStarted('op-1') + lifecycle.reportChallengeSettled('op-1', outcome) + + expect(frictionOf(telemetry)).toEqual([ + { + name: 'billing.checkout.challenge_required', + presentation: 'embedded' + }, + { name: expected, presentation: 'embedded' } + ]) + } + ) + + it('reports a failed challenge once when the server then echoes it as a retryable decline', async () => { + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [ + challengeRequired('pi_secret'), + httpOk( + opStatus({ + authentication_state: 'failed_retryable', + decline_reason: 'authentication_failed', + payment_intent_client_secret: 'pi_secret' + }) + ) + ] + }) + await lifecycle.begin( + 'topup', + issued({ operationId: 'op-1', clientSecret: 'pi_secret' }) + ) + await flush() + + lifecycle.reportChallengeStarted('op-1') + lifecycle.reportChallengeSettled('op-1', 'failed') + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs * 2) + + expect(lifecycle.get('op-1')).toMatchObject({ + declineReason: 'authentication_failed' + }) + expect(frictionOf(telemetry)).toEqual([ + { name: 'billing.checkout.challenge_required', presentation: 'embedded' }, + { name: 'billing.checkout.challenge_failed', presentation: 'embedded' } + ]) + }) + + it('reports each retryable decline inside one hosted operation with its reason, once per decline', async () => { + const declined = (reason: BillingOpStatus['decline_reason']) => + httpOk( + opStatus({ + authentication_state: 'failed_retryable', + decline_reason: reason, + action_url: 'https://billing.example/continue' + }) + ) + const { lifecycle, telemetry } = harness({ + answers: [ + declined('card_declined'), + declined('card_declined'), + declined('insufficient_funds') + ] + }) + + await lifecycle.begin('subscription', issued()) + await flush() + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs * 3) + + expect(frictionOf(telemetry)).toEqual([ + { + name: 'billing.checkout.challenge_failed', + presentation: 'hosted', + decline_reason: 'card_declined' + }, + { + name: 'billing.checkout.challenge_failed', + presentation: 'hosted', + decline_reason: 'insufficient_funds' + } + ]) + }) + + it('does not report the same challenge again when it returns from the hosted page', async () => { + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [ + challengeRequired('pi_secret'), + httpOk( + opStatus({ + authentication_state: 'requires_action', + payment_intent_client_secret: 'pi_secret', + action_url: 'https://billing.example/continue' + }) + ) + ] + }) + await lifecycle.begin( + 'topup', + issued({ operationId: 'op-1', clientSecret: 'pi_secret' }) + ) + await flush() + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs) + + lifecycle.switchPresentation('op-1', 'hosted') + lifecycle.switchPresentation('op-1', 'embedded') + + expect(frictionOf(telemetry)).toEqual([ + { name: 'billing.checkout.challenge_required', presentation: 'embedded' } + ]) + }) +}) diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index edfa60172ed..5781915da84 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -1070,6 +1070,34 @@ describe('useBillingSdkStore telemetry ownership', () => { } ) + it.for(['topup', 'subscription'] as const)( + 'reports the payment friction of a %s this tab issued, which no dialog reports', + (kind) => { + useBillingSdkStore() + + options.onTelemetry({ + name: 'billing.checkout.challenge_failed', + billing_op_id: 'op-1', + operation_type: kind, + presentation: 'embedded', + resumed: false, + decline_reason: 'authentication_failed' + }) + + expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ + operation: 'checkout', + billing_client: 'sdk', + stage: 'challenge_failed', + outcome: 'pending', + operation_type: kind, + billing_op_id: 'op-1', + presentation: 'embedded', + resumed: false, + decline_reason: 'authentication_failed' + }) + } + ) + it('reports a started that arrives once the announced command has settled', async () => { const store = useBillingSdkStore() vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue( From 8c37a94b48c63875b491c6b4862d7a295dece98f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 17:59:29 -0400 Subject: [PATCH 03/19] feat(billing): report 3DS challenges and retryable declines from the operation lifecycle --- .../src/session/billingWebClient.test.ts | 30 ++++++++++ .../src/core/billing/operationLifecycle.ts | 39 ++++++++++-- .../src/core/billing/paymentFriction.ts | 60 +++++++++++++++++++ .../workspace/billing/sdk/billingSdkStore.ts | 14 +++++ 4 files changed, 139 insertions(+), 4 deletions(-) create mode 100644 packages/account-core/src/core/billing/paymentFriction.ts diff --git a/apps/billing-web/src/session/billingWebClient.test.ts b/apps/billing-web/src/session/billingWebClient.test.ts index a521cb932db..34fae25016c 100644 --- a/apps/billing-web/src/session/billingWebClient.test.ts +++ b/apps/billing-web/src/session/billingWebClient.test.ts @@ -252,6 +252,36 @@ describe('SDK operation telemetry', () => { } ) + it('reports a retryable decline inside an issued operation, as the SDK on billing web', async () => { + stubBillingRoutes({ + status: 'pending', + authentication_state: 'failed_retryable', + decline_reason: 'card_declined' + }) + const client = createBillingWebClient(authenticatedSession()) + onTestFinished(() => disposeBillingClient(client)) + + await client.lifecycle.begin('subscription', issueOperation) + + await vi.waitFor(() => + expect(datadogRum.addAction).toHaveBeenCalledWith( + 'billing.checkout.challenge_failed', + { + operation: 'checkout', + stage: 'challenge_failed', + outcome: 'pending', + operation_type: 'subscription', + billing_op_id: 'op_1', + presentation: 'hosted', + resumed: false, + decline_reason: 'card_declined', + billing_client: 'sdk', + billing_surface: 'billing_web' + } + ) + ) + }) + it.for<{ name: string run: (client: BillingClient) => Promise diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index 2844f8ee91a..fe1503427f7 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -17,9 +17,8 @@ * contract is new. */ -import type { - BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT} from '../../telemetry.js'; import { + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT, BILLING_OPERATION_TELEMETRY_EVENT } from '../../telemetry.js' import type { @@ -65,6 +64,8 @@ import { reduceBillingOperation, validateActionUrl } from './operationState.js' +import type { PaymentFrictionSignal } from './paymentFriction.js' +import { paymentFrictionBetween } from './paymentFriction.js' import { selectBillingPresentation } from './presentation.js' import { readValidatedBillingResponse } from './sharedRead.js' import type { BillingStatusData, BillingStatusReader } from './status.js' @@ -319,6 +320,14 @@ function failureCategoryFor( } } +const FRICTION_EVENT_NAME = { + challenge_required: + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeRequired, + challenge_completed: + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeCompleted, + challenge_failed: BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeFailed +} as const satisfies Record + /** The pause is this tab's own challenge on screen; a hosted page never pauses. */ function isDrivingChallenge(state: PendingBillingOperation): boolean { return ( @@ -398,10 +407,31 @@ export function createBillingOperationLifecycle( }) } + function emitFrictionTelemetry( + record: OperationRecord, + before: BillingOperationState | undefined + ) { + const state = record.state + for (const signal of paymentFrictionBetween(before, state)) { + onTelemetry?.({ + name: FRICTION_EVENT_NAME[signal.stage], + billing_op_id: state.id, + operation_type: state.kind, + presentation: state.presentation, + resumed: record.resumed, + ...('declineReason' in signal && signal.declineReason !== undefined + ? { decline_reason: signal.declineReason } + : {}) + }) + } + } + function dispatch(record: OperationRecord, event: BillingOperationEvent) { - const next = reduceBillingOperation(record.state, event) - if (next === record.state) return + const before = record.state + const next = reduceBillingOperation(before, event) + if (next === before) return record.state = next + emitFrictionTelemetry(record, before) if (isTerminal(next)) { stopTimer(record) pointers.settle(next) @@ -574,6 +604,7 @@ export function createBillingOperationLifecycle( presentation: input.presentation, resumed: input.resumed }) + emitFrictionTelemetry(record, undefined) startObserving(record, input, state) return record } diff --git a/packages/account-core/src/core/billing/paymentFriction.ts b/packages/account-core/src/core/billing/paymentFriction.ts new file mode 100644 index 00000000000..6eb0c5e78ab --- /dev/null +++ b/packages/account-core/src/core/billing/paymentFriction.ts @@ -0,0 +1,60 @@ +import type { + BillingDeclineReason, + BillingOperationState, + EmbeddedChallenge, + PendingBillingOperation +} from './operationState.js' + +export type PaymentFrictionSignal = + | { readonly stage: 'challenge_required' } + | { readonly stage: 'challenge_completed' } + | { + readonly stage: 'challenge_failed' + readonly declineReason?: BillingDeclineReason + } + +/** + * What one transition of a pending operation put in the customer's way: a + * challenge first required under a client secret, this tab's verdict on it, + * or a retryable decline with a reason the operation did not hold before. + * A decline the server reports for a challenge this tab already saw fail is + * the same failure, so it is not reported twice. + */ +export function paymentFrictionBetween( + before: BillingOperationState | undefined, + after: BillingOperationState +): readonly PaymentFrictionSignal[] { + if (after.phase !== 'pending') return [] + const earlier = before?.phase === 'pending' ? before : undefined + return [ + ...challengeSignals(earlier?.challenge, after.challenge), + ...declineSignals(earlier, after) + ] +} + +function challengeSignals( + before: EmbeddedChallenge | undefined, + after: EmbeddedChallenge | undefined +): readonly PaymentFrictionSignal[] { + if (after === undefined) return [] + if (after.clientSecret !== before?.clientSecret) { + return after.status === 'required' ? [{ stage: 'challenge_required' }] : [] + } + if (after.status === before.status) return [] + if (after.status === 'completed') return [{ stage: 'challenge_completed' }] + if (after.status === 'failed') return [{ stage: 'challenge_failed' }] + return [] +} + +function declineSignals( + before: PendingBillingOperation | undefined, + after: PendingBillingOperation +): readonly PaymentFrictionSignal[] { + const reason = after.declineReason + if (reason === undefined || reason === before?.declineReason) return [] + const echoesFailedChallenge = + after.presentation === 'embedded' && after.challenge?.status === 'failed' + return echoesFailedChallenge + ? [] + : [{ stage: 'challenge_failed', declineReason: reason }] +} diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index e25448663df..d1885df90c2 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -18,6 +18,7 @@ import type { SubscribeInput } from '@comfyorg/account-core/billing' import { + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT, BILLING_OPERATION_TELEMETRY_EVENT, toBillingTelemetryEvent, validateActionUrl @@ -95,6 +96,14 @@ const PROGRESS_SUMMARY = { } as const satisfies Record> type ToastMessage = Parameters['add']>[0] +const FRICTION_EVENT_NAMES: ReadonlySet = new Set( + Object.values(BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT) +) + +function isFrictionEvent(event: BillingOperationTelemetryEvent): boolean { + return FRICTION_EVENT_NAMES.has(event.name) +} + async function loadChallengePort(): Promise { const publishableKey = resolveStripePublishableKey() const stripe = publishableKey @@ -242,7 +251,12 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { // forwarded, since only the lifecycle holds the operation's id, category // and timing. A command no caller announced — a resubscribe, a checkout // that reports nothing — is reported at both ends by the lifecycle. + // Friction inside an operation has no other reporter, so it always goes. function reportTelemetry(event: BillingOperationTelemetryEvent) { + if (isFrictionEvent(event)) { + useTelemetry()?.trackBillingEvent(toBillingTelemetryEvent(event)) + return + } if (event.operation_type === 'topup' && !event.resumed) return const started = event.name === BILLING_OPERATION_TELEMETRY_EVENT.started if (started && event.resumed) resumedOperations.add(event.billing_op_id) From 70fb0513ff7e5b725c303e15ff17c09bd7a2ae56 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 18:07:24 -0400 Subject: [PATCH 04/19] feat(billing): add the hosted redirect events to the shared telemetry contract --- .../billing-web/src/test/fakeBillingClient.ts | 8 +++ .../src/core/billing/operationLifecycle.ts | 53 +++++++++++++++--- .../telemetry/billingTelemetryEvent.ts | 2 + .../core/billing/telemetry/checkoutJourney.ts | 2 +- .../telemetry/checkoutRedirectEvent.ts | 37 +++++++++++++ .../src/core/billing/telemetry/index.ts | 5 ++ .../telemetry/operationLifecycleEvent.test.ts | 54 +++++++++++++++++++ .../telemetry/operationLifecycleEvent.ts | 24 +++++++-- .../src/core/billing/telemetry/payload.ts | 4 ++ packages/account-core/src/telemetry.ts | 7 ++- .../billing/__fixtures__/billingHarness.ts | 6 ++- .../src/billing/usePaymentAttempt.ts | 3 ++ .../billing/sdk/billingSdkTestUtils.ts | 1 + 13 files changed, 191 insertions(+), 15 deletions(-) create mode 100644 packages/account-core/src/core/billing/telemetry/checkoutRedirectEvent.ts diff --git a/apps/billing-web/src/test/fakeBillingClient.ts b/apps/billing-web/src/test/fakeBillingClient.ts index fbd1d3ceb60..c0c22da0170 100644 --- a/apps/billing-web/src/test/fakeBillingClient.ts +++ b/apps/billing-web/src/test/fakeBillingClient.ts @@ -78,6 +78,9 @@ export interface FakeBillingClient { readonly reportChallengeStarted: Mock< BillingClient['lifecycle']['reportChallengeStarted'] > + readonly reportHostedStepOpened: Mock< + BillingClient['lifecycle']['reportHostedStepOpened'] + > readonly reportChallengeSettled: Mock< BillingClient['lifecycle']['reportChallengeSettled'] > @@ -173,6 +176,9 @@ export function createFakeBillingClient( const reportChallengeStarted: Mock< BillingClient['lifecycle']['reportChallengeStarted'] > = vi.fn() + const reportHostedStepOpened: Mock< + BillingClient['lifecycle']['reportHostedStepOpened'] + > = vi.fn() const reportChallengeSettled: Mock< BillingClient['lifecycle']['reportChallengeSettled'] > = vi.fn() @@ -255,6 +261,7 @@ export function createFakeBillingClient( switchPresentation: unusedByHostedSurfaces( 'lifecycle.switchPresentation' ), + reportHostedStepOpened, reportChallengeStarted, reportChallengeSettled, get: (id) => operations.get(id), @@ -337,6 +344,7 @@ export function createFakeBillingClient( readPlans, readPaymentMethods, invalidatePaymentMethods, + reportHostedStepOpened, reportChallengeStarted, reportChallengeSettled, previewSubscribe, diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index fe1503427f7..9fe68c3d92a 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -65,6 +65,11 @@ import { validateActionUrl } from './operationState.js' import type { PaymentFrictionSignal } from './paymentFriction.js' +import type { + CheckoutHostedStep, + CheckoutRedirectNavigation +} from './telemetry/checkoutRedirectEvent.js' +import type { CheckoutMethodKind } from './telemetry/checkoutJourney.js' import { paymentFrictionBetween } from './paymentFriction.js' import { selectBillingPresentation } from './presentation.js' import { readValidatedBillingResponse } from './sharedRead.js' @@ -95,23 +100,44 @@ export type BillingOperationFailureCategory = | 'reconciliation_needed' | 'stale_operation' -type BillingOperationTelemetryEventName = +type HostedStepEventName = + | typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.redirectStarted + | typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned + +type BillingOperationTelemetryEventName = Exclude< | (typeof BILLING_OPERATION_TELEMETRY_EVENT)[keyof typeof BILLING_OPERATION_TELEMETRY_EVENT] - | (typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT)[keyof typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT] + | (typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT)[keyof typeof BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT], + HostedStepEventName +> + +/** A hosted step this tab handed the customer to. */ +export interface HostedStepVisit { + readonly destination: HostedBillingDestination + readonly step: CheckoutHostedStep + readonly navigation: CheckoutRedirectNavigation + readonly method_kind?: CheckoutMethodKind +} -export interface BillingOperationTelemetryEvent { - readonly name: BillingOperationTelemetryEventName +interface BillingOperationTelemetryBase { readonly billing_op_id: string readonly operation_type: BillingOperationKind readonly presentation: BillingPresentation /** True when this tab reattached to an operation it did not issue. */ readonly resumed: boolean - readonly failure_category?: BillingOperationFailureCategory - readonly decline_reason?: BillingDeclineReason - /** From the attempt's start, so a resumed operation reports its whole life. */ - readonly duration_ms?: number } +export type BillingOperationTelemetryEvent = BillingOperationTelemetryBase & + ( + | { + readonly name: BillingOperationTelemetryEventName + readonly failure_category?: BillingOperationFailureCategory + readonly decline_reason?: BillingDeclineReason + /** From the attempt's start, so a resumed operation reports its whole life. */ + readonly duration_ms?: number + } + | (HostedStepVisit & { readonly name: HostedStepEventName }) + ) + export type PresentationSwitchOutcome = | 'switched' | 'unchanged' @@ -182,6 +208,16 @@ export interface BillingOperationLifecycle { operationId: string, presentation: BillingPresentation ) => PresentationSwitchOutcome + /** + * The host opened the operation's hosted step. A redirect is remembered in + * the pointer, so the page it returns to reports the return; a new tab + * reports it on the next wake. + */ + reportHostedStepOpened: ( + operationId: string, + navigation: CheckoutRedirectNavigation, + methodKind?: CheckoutMethodKind + ) => void /** The host began driving the operation's challenge; polling pauses until it settles. */ reportChallengeStarted: (operationId: string) => void reportChallengeSettled: ( @@ -980,6 +1016,7 @@ export function createBillingOperationLifecycle( recover, wake, switchPresentation, + reportHostedStepOpened: () => {}, reportChallengeStarted, reportChallengeSettled, get: (operationId) => operations.get(operationId)?.state, diff --git a/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts b/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts index e12def8cdb0..13111ff7fd0 100644 --- a/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts +++ b/packages/account-core/src/core/billing/telemetry/billingTelemetryEvent.ts @@ -1,5 +1,6 @@ import type { CapabilityReadBillingEvent } from './capabilityReadEvent.js' import type { CheckoutChallengeBillingEvent } from './checkoutChallengeEvent.js' +import type { CheckoutRedirectBillingEvent } from './checkoutRedirectEvent.js' import type { DowngradeToPersonalBillingEvent } from './downgradeToPersonalEvent.js' import type { BillingOperationBillingEvent } from './operationEvent.js' import type { ResubscribeBillingEvent } from './resubscribeEvent.js' @@ -29,6 +30,7 @@ export type BillingTelemetryEvent = { | WebReturnBillingEvent | WebSessionBillingEvent | CheckoutChallengeBillingEvent + | CheckoutRedirectBillingEvent ) type BillingTelemetryEventNameFor = diff --git a/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts b/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts index e3db253225d..b3e648d0417 100644 --- a/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts +++ b/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts @@ -100,7 +100,7 @@ type CheckoutJourneyPaymentSubmitFailed = { error_code?: string } type CheckoutPaymentRail = 'saved' | 'new' | 'on_file' -type CheckoutMethodKind = 'card' | 'alipay' | 'other' +export type CheckoutMethodKind = 'card' | 'alipay' | 'other' type CheckoutPromoResult = 'applied' | 'rejected' | 'removed' | 'expired' type CheckoutPayBlockedReason = 'reactivation_unconfirmed' | 'promo_unapplied' diff --git a/packages/account-core/src/core/billing/telemetry/checkoutRedirectEvent.ts b/packages/account-core/src/core/billing/telemetry/checkoutRedirectEvent.ts new file mode 100644 index 00000000000..226183b6644 --- /dev/null +++ b/packages/account-core/src/core/billing/telemetry/checkoutRedirectEvent.ts @@ -0,0 +1,37 @@ +import type { + BillingOperationKind, + BillingPresentation, + HostedBillingDestination +} from '../operationState.js' +import type { CheckoutMethodKind } from './checkoutJourney.js' + +/** What the hosted page asks of the customer, from what the server waits on. */ +export type CheckoutHostedStep = + | 'authentication' + | 'payment_method' + | 'invoice_payment' + | 'checkout' + +/** The hosted page replaced this page, or opened beside it. */ +export type CheckoutRedirectNavigation = 'redirect' | 'new_tab' + +/** + * A hosted step this tab handed the customer to, and the customer back on the + * tab that handed it. Neither settles the operation; the pair joins on + * `billing_op_id`, and a start with no return is a customer who did not come + * back. + */ +export type CheckoutRedirectBillingEvent = { + operation: 'checkout' + outcome: 'pending' + billing_op_id: string + operation_type: BillingOperationKind + presentation: BillingPresentation + /** True when this tab reattached to an operation it did not issue. */ + resumed?: boolean + destination: HostedBillingDestination + step: CheckoutHostedStep + navigation: CheckoutRedirectNavigation + /** The method the customer chose, when the host knows it. */ + method_kind?: CheckoutMethodKind +} & ({ stage: 'redirect_started' } | { stage: 'returned' }) diff --git a/packages/account-core/src/core/billing/telemetry/index.ts b/packages/account-core/src/core/billing/telemetry/index.ts index e7949d9fea6..0858e823e93 100644 --- a/packages/account-core/src/core/billing/telemetry/index.ts +++ b/packages/account-core/src/core/billing/telemetry/index.ts @@ -18,6 +18,10 @@ export { } from './payload.js' export { BILLING_TELEMETRY_EVENTS } from './eventNames.js' export { toBillingTelemetryEvent } from './operationLifecycleEvent.js' +export type { + CheckoutHostedStep, + CheckoutRedirectNavigation +} from './checkoutRedirectEvent.js' export type { SubscriptionCheckoutUi } from './subscriptionCheckoutEvent.js' export type { WebEntryBillingEvent, @@ -44,6 +48,7 @@ export type { CheckoutJourneyTelemetryEvent, CheckoutJourneyTelemetryEventName, CheckoutJourneyTelemetryEventPayload, + CheckoutMethodKind, CheckoutUiMode } from './checkoutJourney.js' export { diff --git a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts index 1b8a67f7f41..28532d1a2d0 100644 --- a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts +++ b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.test.ts @@ -186,6 +186,60 @@ describe('toBillingTelemetryEvent', () => { resumed: false, decline_reason: 'card_declined' } + }, + { + name: 'a hosted step opened, with where it leads and the method', + event: { + name: 'billing.checkout.redirect_started', + billing_op_id: 'op-redirect', + operation_type: 'subscription', + presentation: 'hosted', + resumed: false, + destination: 'stripe', + step: 'payment_method', + navigation: 'redirect', + method_kind: 'alipay' + }, + expected: { + operation: 'checkout', + billing_client: 'sdk', + stage: 'redirect_started', + outcome: 'pending', + operation_type: 'subscription', + billing_op_id: 'op-redirect', + presentation: 'hosted', + resumed: false, + destination: 'stripe', + step: 'payment_method', + navigation: 'redirect', + method_kind: 'alipay' + } + }, + { + name: 'a return from a hosted step, without a method the host never knew', + event: { + name: 'billing.checkout.returned', + billing_op_id: 'op-redirect', + operation_type: 'topup', + presentation: 'hosted', + resumed: true, + destination: 'billing_web', + step: 'authentication', + navigation: 'new_tab' + }, + expected: { + operation: 'checkout', + billing_client: 'sdk', + stage: 'returned', + outcome: 'pending', + operation_type: 'topup', + billing_op_id: 'op-redirect', + presentation: 'hosted', + resumed: true, + destination: 'billing_web', + step: 'authentication', + navigation: 'new_tab' + } } ])('maps $name', ({ event, expected }) => { expect(toBillingTelemetryEvent(event)).toEqual(expected) diff --git a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts index 0df58612b3e..72d1c8007be 100644 --- a/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts +++ b/packages/account-core/src/core/billing/telemetry/operationLifecycleEvent.ts @@ -22,6 +22,24 @@ export function toBillingTelemetryEvent( presentation: event.presentation, resumed: event.resumed } as const + if ( + event.name === BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.redirectStarted || + event.name === BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned + ) { + return { + ...friction, + stage: + event.name === BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned + ? 'returned' + : 'redirect_started', + destination: event.destination, + step: event.step, + navigation: event.navigation, + ...(event.method_kind === undefined + ? {} + : { method_kind: event.method_kind }) + } + } const shared = { operation: 'operation', billing_client: 'sdk', @@ -29,9 +47,9 @@ export function toBillingTelemetryEvent( billing_op_id: event.billing_op_id, presentation: event.presentation, resumed: event.resumed, - ...(event.duration_ms === undefined - ? {} - : { duration_ms: event.duration_ms }) + ...('duration_ms' in event && event.duration_ms !== undefined + ? { duration_ms: event.duration_ms } + : {}) } as const switch (event.name) { diff --git a/packages/account-core/src/core/billing/telemetry/payload.ts b/packages/account-core/src/core/billing/telemetry/payload.ts index f7dd0167780..86848b1d827 100644 --- a/packages/account-core/src/core/billing/telemetry/payload.ts +++ b/packages/account-core/src/core/billing/telemetry/payload.ts @@ -16,18 +16,21 @@ export const BILLING_PAYLOAD_FIELD_HANDLING = { checkout_status: 'required', control: 'required', correlation_id: 'required', + destination: 'required', failure_category: 'required', has_plan: 'required', intent: 'required', member_removal_count: 'required', member_removal_failures: 'required', mode: 'required', + navigation: 'required', operation_type: 'required', origin: 'required', product: 'required', reason: 'required', result: 'required', source: 'required', + step: 'required', to: 'required', billing_client: 'optional', billing_op_id: 'optional', @@ -38,6 +41,7 @@ export const BILLING_PAYLOAD_FIELD_HANDLING = { decline_reason: 'optional', duration_ms: 'optional', error_code: 'optional', + method_kind: 'optional', payment_intent_source: 'optional', presentation: 'optional', recovery_outcome: 'optional', diff --git a/packages/account-core/src/telemetry.ts b/packages/account-core/src/telemetry.ts index a373874ff5a..e55310f7eca 100644 --- a/packages/account-core/src/telemetry.ts +++ b/packages/account-core/src/telemetry.ts @@ -23,12 +23,15 @@ export const BILLING_OPERATION_TELEMETRY_EVENT = { /** * Payment friction the lifecycle observes inside one operation: a bank - * challenge and its verdict, and each retryable decline. + * challenge and its verdict, each retryable decline, and a hosted step the + * customer was sent to and came back from. */ export const BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT = { challengeRequired: 'billing.checkout.challenge_required', challengeCompleted: 'billing.checkout.challenge_completed', - challengeFailed: 'billing.checkout.challenge_failed' + challengeFailed: 'billing.checkout.challenge_failed', + redirectStarted: 'billing.checkout.redirect_started', + returned: 'billing.checkout.returned' } as const export const AUTH_TELEMETRY_EVENT = { diff --git a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts index 6a5a381fa0a..de79d444e5d 100644 --- a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts +++ b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts @@ -7,6 +7,7 @@ import { vi } from 'vitest' import type { BillingHttpResponse, + BillingOperationTelemetryEvent, BillingOpStatus, BillingRequest, BillingResult, @@ -239,11 +240,13 @@ export function createBillingHarness(options: HarnessOptions = {}) { const plans = createPlansReader(readerOptions) const paymentMethods = createPaymentMethodsReader(readerOptions) const events = createBillingEventsReader(readerOptions) + const telemetry: BillingOperationTelemetryEvent[] = [] const lifecycle = createBillingOperationLifecycle({ transport, scopeSource, statusReader, - embeddedCheckoutAvailable: () => options.embedded === true + embeddedCheckoutAvailable: () => options.embedded === true, + onTelemetry: (event) => telemetry.push(event) }) let attempts = 0 const idempotencyKey = () => `key-${++attempts}` @@ -308,6 +311,7 @@ export function createBillingHarness(options: HarnessOptions = {}) { calls, answer, routes, + telemetry, /** Moves the host to another workspace, as the switcher does. */ moveToWorkspace: (id: string) => host.moveTo({ id, name: 'Team', type: 'team' }) diff --git a/packages/account-ui/src/billing/usePaymentAttempt.ts b/packages/account-ui/src/billing/usePaymentAttempt.ts index ac944bc8d46..4f822963aeb 100644 --- a/packages/account-ui/src/billing/usePaymentAttempt.ts +++ b/packages/account-ui/src/billing/usePaymentAttempt.ts @@ -12,6 +12,7 @@ import type { Ref } from 'vue' import type { BillingOperationKind, BillingOperationState, + CheckoutMethodKind, EmbeddedChallengePort, HostPaymentStep, PaymentProjection, @@ -43,6 +44,8 @@ export interface PaymentNavigation { * that declines one runs it later through `continueVerification`. */ readonly autoContinue?: (state: PendingBillingOperation) => boolean + /** The method the customer chose, reported with the hosted step it leads to. */ + readonly methodKind?: () => CheckoutMethodKind | undefined } export interface PaymentAttempt { diff --git a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts index cc5a2f4def8..d64e036ae54 100644 --- a/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts +++ b/src/platform/workspace/billing/sdk/billingSdkTestUtils.ts @@ -119,6 +119,7 @@ export function fakeBillingSdk() { recover: vi.fn(async () => ({ status: 'ok' as const, value: undefined })), wake: vi.fn(), switchPresentation: vi.fn(() => 'unchanged' as const), + reportHostedStepOpened: vi.fn(), reportChallengeStarted: vi.fn(), reportChallengeSettled: vi.fn(), get: (operationId) => snapshot.find((state) => state.id === operationId), From 6de149d5e6e685b21a9867517e4580cf7712c871 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 18:07:30 -0400 Subject: [PATCH 05/19] test(billing): expect hosted steps and the return from them to be reported --- .../src/views/FullPageCheckoutView.test.ts | 17 ++ .../core/billing/operationLifecycle.test.ts | 163 +++++++++++++++++- .../src/billing/useCheckout.test.ts | 55 ++++++ .../billing/sdk/billingSdkStore.test.ts | 19 ++ 4 files changed, 249 insertions(+), 5 deletions(-) diff --git a/apps/billing-web/src/views/FullPageCheckoutView.test.ts b/apps/billing-web/src/views/FullPageCheckoutView.test.ts index 384e60dc78d..b473439aeac 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.test.ts +++ b/apps/billing-web/src/views/FullPageCheckoutView.test.ts @@ -2059,6 +2059,23 @@ describe('FullPageCheckoutView payment authentication', () => { nextStep.asked = 0 }) + it.for([ + { methodType: 'alipay', reported: [['op_3ds', 'redirect', 'alipay']] }, + { methodType: 'card', reported: [] } + ])( + 'reports the challenge a $methodType Pay drives as a redirect only when it finishes on another site', + async ({ methodType, reported }) => { + const fake = await payHeld(methodType) + + fake.publishOperation(challengedOperation('op_3ds', 'required')) + + await waitFor(() => + expect(fake.reportChallengeStarted).toHaveBeenCalledWith('op_3ds') + ) + expect(fake.reportHostedStepOpened.mock.calls).toEqual(reported) + } + ) + it('locks its own Pay through a challenge, then processing, then lands on the success', async () => { const fake = await payReady() expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument() diff --git a/packages/account-core/src/core/billing/operationLifecycle.test.ts b/packages/account-core/src/core/billing/operationLifecycle.test.ts index 12439defd66..24cfee4c14c 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.test.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.test.ts @@ -1557,11 +1557,15 @@ describe('createBillingOperationLifecycle', () => { describe('payment friction telemetry', () => { function frictionOf(telemetry: BillingOperationTelemetryEvent[]) { return telemetry - .filter((event) => event.name.startsWith('billing.checkout.')) - .map(({ name, presentation, decline_reason }) => - decline_reason === undefined - ? { name, presentation } - : { name, presentation, decline_reason } + .filter((event) => event.name.startsWith('billing.checkout.challenge')) + .map((event) => + 'decline_reason' in event && event.decline_reason !== undefined + ? { + name: event.name, + presentation: event.presentation, + decline_reason: event.decline_reason + } + : { name: event.name, presentation: event.presentation } ) } @@ -1739,3 +1743,152 @@ describe('payment friction telemetry', () => { ]) }) }) + +describe('hosted redirect telemetry', () => { + const PAYMENT_PAGE = 'https://billing.example/continue' + + function redirectsOf(telemetry: BillingOperationTelemetryEvent[]) { + return telemetry.filter( + (event) => + event.name === 'billing.checkout.redirect_started' || + event.name === 'billing.checkout.returned' + ) + } + + it('reports the hosted step the host opened, where it leads and how', async () => { + const { lifecycle, telemetry } = harness({ + destination: 'billing_web', + answers: [ + httpOk( + opStatus({ + phase: 'awaiting_payment_method', + action_url: PAYMENT_PAGE + }) + ) + ] + }) + await lifecycle.begin( + 'subscription', + issued({ operationId: 'op-1', actionUrl: PAYMENT_PAGE }) + ) + await flush() + + lifecycle.reportHostedStepOpened('op-1', 'redirect', 'alipay') + + expect(redirectsOf(telemetry)).toEqual([ + { + name: 'billing.checkout.redirect_started', + billing_op_id: 'op-1', + operation_type: 'subscription', + presentation: 'hosted', + resumed: false, + destination: 'billing_web', + step: 'payment_method', + navigation: 'redirect', + method_kind: 'alipay' + } + ]) + }) + + it.for([ + { + server: { authentication_state: 'requires_action' }, + step: 'authentication' + }, + { server: { phase: 'awaiting_invoice_payment' }, step: 'invoice_payment' }, + { server: { phase: 'in_progress' }, step: 'checkout' } + ] as const)( + 'names the hosted step $step from what the server waits on', + async ({ server, step }) => { + const { lifecycle, telemetry } = harness({ + answers: [httpOk(opStatus({ ...server, action_url: PAYMENT_PAGE }))] + }) + await lifecycle.begin('topup', issued()) + await flush() + + lifecycle.reportHostedStepOpened('op-1', 'new_tab') + + expect(redirectsOf(telemetry)).toEqual([ + expect.objectContaining({ step, destination: 'stripe' }) + ]) + } + ) + + it('reports the return once when the page the redirect left recovers the operation', async () => { + const storage = memoryStorage() + const left = harness({ + storage, + answers: [ + httpOk( + opStatus({ + phase: 'awaiting_payment_method', + action_url: PAYMENT_PAGE + }) + ) + ] + }) + await left.lifecycle.begin( + 'subscription', + issued({ operationId: 'op-1', actionUrl: PAYMENT_PAGE }) + ) + await flush() + left.lifecycle.reportHostedStepOpened('op-1', 'redirect', 'alipay') + left.lifecycle.dispose() + + const pending = statusSnapshot({ + pending_billing_op_id: 'op-1', + pending_billing_op_type: 'subscription' + }) + const back = harness({ storage, status: pending }) + await back.lifecycle.recover() + const reloaded = harness({ storage, status: pending }) + await reloaded.lifecycle.recover() + + expect(redirectsOf(back.telemetry)).toEqual([ + { + name: 'billing.checkout.returned', + billing_op_id: 'op-1', + operation_type: 'subscription', + presentation: 'hosted', + resumed: true, + destination: 'stripe', + step: 'payment_method', + navigation: 'redirect', + method_kind: 'alipay' + } + ]) + expect(redirectsOf(reloaded.telemetry)).toEqual([]) + }) + + it('reports the return once when the customer comes back to this tab from a new one', async () => { + const { lifecycle, telemetry } = harness({ + answers: [httpOk(opStatus({ action_url: PAYMENT_PAGE }))] + }) + await lifecycle.begin('topup', issued()) + await flush() + lifecycle.reportHostedStepOpened('op-1', 'new_tab') + + lifecycle.wake() + lifecycle.wake() + + expect(redirectsOf(telemetry).map((event) => event.name)).toEqual([ + 'billing.checkout.redirect_started', + 'billing.checkout.returned' + ]) + }) + + it('reports no return for a page that redirected away and was never reloaded', async () => { + const { lifecycle, telemetry } = harness({ + answers: [httpOk(opStatus({ action_url: PAYMENT_PAGE }))] + }) + await lifecycle.begin('topup', issued()) + await flush() + lifecycle.reportHostedStepOpened('op-1', 'redirect') + + lifecycle.wake() + + expect(redirectsOf(telemetry).map((event) => event.name)).toEqual([ + 'billing.checkout.redirect_started' + ]) + }) +}) diff --git a/packages/account-ui/src/billing/useCheckout.test.ts b/packages/account-ui/src/billing/useCheckout.test.ts index fdadc0bea85..6ca2dcf81f8 100644 --- a/packages/account-ui/src/billing/useCheckout.test.ts +++ b/packages/account-ui/src/billing/useCheckout.test.ts @@ -59,6 +59,61 @@ describe('useCheckout', () => { expect(openUrl).toHaveBeenCalledExactlyOnceWith(PAYMENT_PAGE, 'new_tab') }) + it.for([ + { navigationMode: 'redirect', navigation: 'redirect' }, + { navigationMode: 'new_tab', navigation: 'new_tab' }, + { navigationMode: 'preopened', navigation: 'new_tab' } + ] as const)( + 'reports the hosted step as a $navigation, with the host method, before the host leaves for it ($navigationMode)', + async ({ navigationMode, navigation }) => { + const { client, answer, telemetry } = createBillingHarness() + answer( + 'POST', + SUBSCRIBE_ROUTE, + httpOk({ + billing_op_id: 'op-1', + status: 'needs_payment_method', + payment_method_url: PAYMENT_PAGE + }) + ) + answer( + 'GET', + operationRoute('op-1'), + httpOk( + opStatus({ + phase: 'awaiting_payment_method', + action_url: PAYMENT_PAGE + }) + ) + ) + const reportedWhenOpened: string[][] = [] + const openUrl = vi.fn(() => { + reportedWhenOpened.push(telemetry.map((event) => event.name)) + }) + + const checkout = useCheckout({ + client, + openUrl, + navigationMode, + autoContinue: () => false, + methodKind: () => 'alipay' + }) + void checkout.subscribe(PLAN) + await vi.advanceTimersByTimeAsync(0) + checkout.continueVerification() + + expect(reportedWhenOpened).toEqual([ + ['billing.operation.started', 'billing.checkout.redirect_started'] + ]) + expect(telemetry[1]).toMatchObject({ + destination: 'stripe', + step: 'payment_method', + navigation, + method_kind: 'alipay' + }) + } + ) + it('hands the hosted payment page the server offered to the host and settles the subscription', async () => { const { client, answer, calls } = createBillingHarness() answer( diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index 5781915da84..990da968375 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -819,6 +819,25 @@ describe('useBillingSdkStore subscription commands', () => { ) }) + it.for([ + { page: 'opened', window: {} as Window, reported: [['op-1', 'new_tab']] }, + { page: 'had blocked', window: null, reported: [] } + ])( + 'reports to the lifecycle a hosted page it $page in a new tab', + ({ window: opened, reported }) => { + vi.spyOn(window, 'open').mockReturnValue(opened) + useBillingSdkStore() + + harness.publish( + pendingSubscription({ actionUrl: 'https://pay.example/first' }) + ) + + expect( + vi.mocked(harness.sdk.lifecycle.reportHostedStepOpened).mock.calls + ).toEqual(reported) + } + ) + it('offers the next hosted page the same subscribe moves to', () => { const openPage = vi.spyOn(window, 'open').mockReturnValue(null) const store = useBillingSdkStore() From 62e449c2e2c0a3d3553ffad77382aa165f8e8f7c Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 18:09:22 -0400 Subject: [PATCH 06/19] feat(billing): report hosted redirects and the return from them on both hosts --- .../src/checkout/checkoutJourney.ts | 2 +- .../src/composables/useFullPageCheckout.ts | 7 +- .../src/core/billing/operationLifecycle.ts | 99 ++++++++++++++++++- .../src/core/billing/operationPointer.ts | 15 ++- .../src/billing/usePaymentAttempt.ts | 17 +++- .../workspace/billing/sdk/billingSdkStore.ts | 5 +- 6 files changed, 135 insertions(+), 10 deletions(-) diff --git a/apps/billing-web/src/checkout/checkoutJourney.ts b/apps/billing-web/src/checkout/checkoutJourney.ts index ae5e3ede733..30a6b557947 100644 --- a/apps/billing-web/src/checkout/checkoutJourney.ts +++ b/apps/billing-web/src/checkout/checkoutJourney.ts @@ -119,7 +119,7 @@ type PromoPhase = Extract export type PaymentRail = MethodSelectedPhase['rail'] export type PromoResult = PromoPhase['result'] -function methodKindOf( +export function methodKindOf( methodType: string | undefined ): MethodSelectedPhase['method_kind'] { if (methodType === undefined || methodType === '') return undefined diff --git a/apps/billing-web/src/composables/useFullPageCheckout.ts b/apps/billing-web/src/composables/useFullPageCheckout.ts index 03d5f1d4d91..79b5512eaf7 100644 --- a/apps/billing-web/src/composables/useFullPageCheckout.ts +++ b/apps/billing-web/src/composables/useFullPageCheckout.ts @@ -39,6 +39,7 @@ import { reduceCheckoutPage, settledPlanSource } from '@/checkout/checkoutPage' +import { methodKindOf } from '@/checkout/checkoutJourney' import { pricingTableUrl } from '@/checkout/cloudLinks' import { createOperationChannel } from '@/checkout/operationChannel' import { promoEntryLive, promoRejectionOf } from '@/checkout/promoEntry' @@ -208,7 +209,11 @@ export function useFullPageCheckout() { openUrl: (url) => window.location.assign(url), navigationMode: 'redirect', challengePort, - autoContinue: () => submitting.value + autoContinue: () => submitting.value, + methodKind: () => + page.value.kind === 'capture' && page.value.attempt.kind === 'sent' + ? methodKindOf(page.value.attempt.redirectMethod) + : undefined }) const attempts = createSubscriptionCheckoutTelemetry({ ui: 'full_page' }) diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index 9fe68c3d92a..b60f0162867 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -262,6 +262,8 @@ interface OperationRecord { waitingWithoutActionSince: number | undefined timer: ReturnType | undefined inFlightPoll: Promise | undefined + /** A hosted step this tab opened in a new tab; the next wake is the customer back. */ + awaitingReturn: HostedStepVisit | undefined readonly settled: Promise resolveSettled: (state: BillingOperationState) => void } @@ -278,6 +280,8 @@ interface AdoptInput { readonly awaitedHere: boolean /** A status already read for this operation; observed from it instead of polled again. */ readonly initialStatus?: BillingOpStatus + /** The hosted step a redirect left this page for; adopting it is the return. */ + readonly returnedFrom?: BillingOperationPointer['redirect'] } interface ServerPendingOperation { @@ -364,6 +368,19 @@ const FRICTION_EVENT_NAME = { challenge_failed: BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.challengeFailed } as const satisfies Record +/** What the hosted page asks of the customer, from what the server waits on. */ +function hostedStepOf(state: PendingBillingOperation): CheckoutHostedStep { + if ( + state.authenticationState === 'requires_action' || + (state.presentation === 'embedded' && state.challenge !== undefined) + ) { + return 'authentication' + } + if (state.serverPhase === 'awaiting_payment_method') return 'payment_method' + if (state.serverPhase === 'awaiting_invoice_payment') return 'invoice_payment' + return 'checkout' +} + /** The pause is this tab's own challenge on screen; a hosted page never pauses. */ function isDrivingChallenge(state: PendingBillingOperation): boolean { return ( @@ -510,13 +527,33 @@ export function createBillingOperationLifecycle( return request } - function writePointer(scope: BillingScope, state: BillingOperationState) { + function writePointer( + scope: BillingScope, + state: BillingOperationState, + redirect?: BillingOperationPointer['redirect'] + ) { pointers.write(scope, { operationId: state.id, kind: state.kind, presentation: state.presentation, attemptStartedAt: state.attemptStartedAt, - ...(state.awaitedHere ? { awaited: true } : {}) + ...(state.awaitedHere ? { awaited: true } : {}), + ...(redirect === undefined ? {} : { redirect }) + }) + } + + function emitHostedStepTelemetry( + record: OperationRecord, + name: HostedStepEventName, + visit: HostedStepVisit + ) { + onTelemetry?.({ + name, + billing_op_id: record.state.id, + operation_type: record.state.kind, + presentation: record.state.presentation, + resumed: record.resumed, + ...visit }) } @@ -628,6 +665,7 @@ export function createBillingOperationLifecycle( waitingWithoutActionSince: undefined, timer: undefined, inFlightPoll: undefined, + awaitingReturn: undefined, settled, resolveSettled } @@ -641,6 +679,12 @@ export function createBillingOperationLifecycle( resumed: input.resumed }) emitFrictionTelemetry(record, undefined) + if (input.returnedFrom !== undefined) { + emitHostedStepTelemetry(record, BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned, { + ...input.returnedFrom, + navigation: 'redirect' + }) + } startObserving(record, input, state) return record } @@ -832,7 +876,10 @@ export function createBillingOperationLifecycle( presentation: pointer.presentation, attemptStartedAt: pointer.attemptStartedAt, resumed: true, - awaitedHere: pointer.awaited === true + awaitedHere: pointer.awaited === true, + ...(pointer.redirect === undefined + ? {} + : { returnedFrom: pointer.redirect }) } } @@ -866,7 +913,10 @@ export function createBillingOperationLifecycle( presentation: known?.presentation ?? routeFor(rail, pending), attemptStartedAt: known?.attemptStartedAt ?? now(), resumed: true, - awaitedHere: known?.awaited === true + awaitedHere: known?.awaited === true, + ...(known?.redirect === undefined + ? {} + : { returnedFrom: known.redirect }) }, includeSettled ) @@ -939,6 +989,7 @@ export function createBillingOperationLifecycle( function wake() { for (const record of operations.values()) { + reportReturnFromNewTab(record) if (record.state.phase !== 'pending') continue if (isDrivingChallenge(record.state)) continue void poll(record) @@ -987,6 +1038,44 @@ export function createBillingOperationLifecycle( return 'switched' } + function reportReturnFromNewTab(record: OperationRecord) { + const visit = record.awaitingReturn + if (visit === undefined) return + record.awaitingReturn = undefined + emitHostedStepTelemetry( + record, + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned, + visit + ) + } + + function reportHostedStepOpened( + operationId: string, + navigation: CheckoutRedirectNavigation, + methodKind?: CheckoutMethodKind + ) { + const record = operations.get(operationId) + if (record === undefined || record.state.phase !== 'pending') return + const state = record.state + const redirect = { + destination: + state.presentation === 'hosted' ? state.hostedDestination : 'stripe', + step: hostedStepOf(state), + ...(methodKind === undefined ? {} : { method_kind: methodKind }) + } as const + const visit = { ...redirect, navigation } + if (navigation === 'redirect') { + writePointer(record.context.scope, state, redirect) + } else { + record.awaitingReturn = visit + } + emitHostedStepTelemetry( + record, + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.redirectStarted, + visit + ) + } + function reportChallengeStarted(operationId: string) { const record = operations.get(operationId) if (record === undefined) return @@ -1016,7 +1105,7 @@ export function createBillingOperationLifecycle( recover, wake, switchPresentation, - reportHostedStepOpened: () => {}, + reportHostedStepOpened, reportChallengeStarted, reportChallengeSettled, get: (operationId) => operations.get(operationId)?.state, diff --git a/packages/account-core/src/core/billing/operationPointer.ts b/packages/account-core/src/core/billing/operationPointer.ts index 368e26014f3..f872c416b6c 100644 --- a/packages/account-core/src/core/billing/operationPointer.ts +++ b/packages/account-core/src/core/billing/operationPointer.ts @@ -31,7 +31,20 @@ const PointerSchema = z.object({ /** This tab issued the operation and has not yet seen it succeed. */ awaited: z.literal(true).optional(), /** The end this tab saw it reach, kept only by a store that retains settled pointers. */ - settled: z.enum(['succeeded', 'reconciliation_needed']).optional() + settled: z.enum(['succeeded', 'reconciliation_needed']).optional(), + /** The hosted step this page redirected to; the page it returns to reports the return. */ + redirect: z + .object({ + destination: z.enum(['stripe', 'billing_web']), + step: z.enum([ + 'authentication', + 'payment_method', + 'invoice_payment', + 'checkout' + ]), + method_kind: z.enum(['card', 'alipay', 'other']).optional() + }) + .optional() }) export type BillingOperationPointer = z.infer diff --git a/packages/account-ui/src/billing/usePaymentAttempt.ts b/packages/account-ui/src/billing/usePaymentAttempt.ts index 4f822963aeb..e384790de05 100644 --- a/packages/account-ui/src/billing/usePaymentAttempt.ts +++ b/packages/account-ui/src/billing/usePaymentAttempt.ts @@ -83,7 +83,8 @@ export function usePaymentAttempt( openUrl, navigationMode = 'new_tab', challengePort, - autoContinue = () => true + autoContinue = () => true, + methodKind = () => undefined } = navigation const tracked = useBillingOperation({ kind }, client) const dismissedId = ref() @@ -103,13 +104,27 @@ export function usePaymentAttempt( function continueVerification() { const state = operation.value if (state?.phase !== 'pending') return + const method = methodKind() if (state.presentation === 'hosted') { if (state.actionUrl !== undefined) { + client.lifecycle.reportHostedStepOpened( + state.id, + navigationMode === 'redirect' ? 'redirect' : 'new_tab', + method + ) openUrl(state.actionUrl, navigationMode) } return } if (challengePort === undefined) return + // A non-card method finishes its challenge on the provider's site. + if ( + state.challenge?.status === 'required' && + method !== undefined && + method !== 'card' + ) { + client.lifecycle.reportHostedStepOpened(state.id, 'redirect', method) + } void driveEmbeddedChallenge(client.lifecycle, state.id, challengePort) } diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.ts b/src/platform/workspace/billing/sdk/billingSdkStore.ts index d1885df90c2..35771c4690f 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.ts @@ -367,7 +367,10 @@ export const useBillingSdkStore = defineStore('billingSdk', () => { const offered = offeredActions.get(state.id) ?? new Set() if (offered.has(actionUrl)) return offeredActions.set(state.id, offered.add(actionUrl)) - if (window.open(actionUrl, '_blank')) return + if (window.open(actionUrl, '_blank')) { + sdk.lifecycle.reportHostedStepOpened(state.id, 'new_tab') + return + } toastStore.add({ severity: 'warn', summary: t('g.warning'), From 203943a7eabc4655d3e2ebe0e2a20082e5062052 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 18:20:00 -0400 Subject: [PATCH 07/19] style(billing): format the hosted step return report --- .../src/core/billing/operationLifecycle.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index b60f0162867..a2edfef4727 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -680,10 +680,14 @@ export function createBillingOperationLifecycle( }) emitFrictionTelemetry(record, undefined) if (input.returnedFrom !== undefined) { - emitHostedStepTelemetry(record, BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned, { - ...input.returnedFrom, - navigation: 'redirect' - }) + emitHostedStepTelemetry( + record, + BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT.returned, + { + ...input.returnedFrom, + navigation: 'redirect' + } + ) } startObserving(record, input, state) return record From 67d5cf89205fe3f66b925a1ed89851420d731e17 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 20:50:19 -0400 Subject: [PATCH 08/19] fix(billing): report a later decline after an echoed failed challenge --- .../core/billing/operationLifecycle.test.ts | 38 +++++++++++++++++++ .../src/core/billing/paymentFriction.ts | 8 ++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/packages/account-core/src/core/billing/operationLifecycle.test.ts b/packages/account-core/src/core/billing/operationLifecycle.test.ts index 12439defd66..63388563a05 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.test.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.test.ts @@ -1675,6 +1675,44 @@ describe('payment friction telemetry', () => { ]) }) + it('reports a later, different decline after the failed challenge was echoed', async () => { + const declined = (reason: BillingOpStatus['decline_reason']) => + httpOk( + opStatus({ + authentication_state: 'failed_retryable', + decline_reason: reason, + payment_intent_client_secret: 'pi_secret' + }) + ) + const { lifecycle, telemetry } = harness({ + embedded: true, + answers: [ + challengeRequired('pi_secret'), + declined('authentication_failed'), + declined('card_declined') + ] + }) + await lifecycle.begin( + 'topup', + issued({ operationId: 'op-1', clientSecret: 'pi_secret' }) + ) + await flush() + + lifecycle.reportChallengeStarted('op-1') + lifecycle.reportChallengeSettled('op-1', 'failed') + await vi.advanceTimersByTimeAsync(OPERATION_POLL_TIMING.parkedMs * 3) + + expect(frictionOf(telemetry)).toEqual([ + { name: 'billing.checkout.challenge_required', presentation: 'embedded' }, + { name: 'billing.checkout.challenge_failed', presentation: 'embedded' }, + { + name: 'billing.checkout.challenge_failed', + presentation: 'embedded', + decline_reason: 'card_declined' + } + ]) + }) + it('reports each retryable decline inside one hosted operation with its reason, once per decline', async () => { const declined = (reason: BillingOpStatus['decline_reason']) => httpOk( diff --git a/packages/account-core/src/core/billing/paymentFriction.ts b/packages/account-core/src/core/billing/paymentFriction.ts index 6eb0c5e78ab..c2812bf4b29 100644 --- a/packages/account-core/src/core/billing/paymentFriction.ts +++ b/packages/account-core/src/core/billing/paymentFriction.ts @@ -17,8 +17,8 @@ export type PaymentFrictionSignal = * What one transition of a pending operation put in the customer's way: a * challenge first required under a client secret, this tab's verdict on it, * or a retryable decline with a reason the operation did not hold before. - * A decline the server reports for a challenge this tab already saw fail is - * the same failure, so it is not reported twice. + * The first decline the server reports for a challenge this tab already saw + * fail is the same failure, so it is not reported twice. */ export function paymentFrictionBetween( before: BillingOperationState | undefined, @@ -53,7 +53,9 @@ function declineSignals( const reason = after.declineReason if (reason === undefined || reason === before?.declineReason) return [] const echoesFailedChallenge = - after.presentation === 'embedded' && after.challenge?.status === 'failed' + after.presentation === 'embedded' && + after.challenge?.status === 'failed' && + before?.declineReason === undefined return echoesFailedChallenge ? [] : [{ stage: 'challenge_failed', declineReason: reason }] From 38f5b4dcff5e171230f264686989146a5a27586f Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 20:52:20 -0400 Subject: [PATCH 09/19] refactor(billing): split hosted-step reporting branches and unexport HostedStepVisit --- .../src/core/billing/operationLifecycle.ts | 47 ++++++++++----- .../src/billing/usePaymentAttempt.ts | 59 ++++++++++++------- 2 files changed, 70 insertions(+), 36 deletions(-) diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index a2edfef4727..6ee159394dc 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -111,7 +111,7 @@ type BillingOperationTelemetryEventName = Exclude< > /** A hosted step this tab handed the customer to. */ -export interface HostedStepVisit { +interface HostedStepVisit { readonly destination: HostedBillingDestination readonly step: CheckoutHostedStep readonly navigation: CheckoutRedirectNavigation @@ -284,6 +284,28 @@ interface AdoptInput { readonly returnedFrom?: BillingOperationPointer['redirect'] } +type ResumedAttempt = Pick< + AdoptInput, + | 'presentation' + | 'attemptStartedAt' + | 'resumed' + | 'awaitedHere' + | 'returnedFrom' +> + +/** The attempt a pointer remembers, picked up again by this tab. */ +function resumedFrom(pointer: BillingOperationPointer): ResumedAttempt { + return { + presentation: pointer.presentation, + attemptStartedAt: pointer.attemptStartedAt, + resumed: true, + awaitedHere: pointer.awaited === true, + ...(pointer.redirect === undefined + ? {} + : { returnedFrom: pointer.redirect }) + } +} + interface ServerPendingOperation { readonly id: string readonly kind: BillingOperationKind @@ -877,13 +899,7 @@ export function createBillingOperationLifecycle( id: pointer.operationId, kind: pointer.kind, context, - presentation: pointer.presentation, - attemptStartedAt: pointer.attemptStartedAt, - resumed: true, - awaitedHere: pointer.awaited === true, - ...(pointer.redirect === undefined - ? {} - : { returnedFrom: pointer.redirect }) + ...resumedFrom(pointer) } } @@ -914,13 +930,14 @@ export function createBillingOperationLifecycle( { ...pending, context, - presentation: known?.presentation ?? routeFor(rail, pending), - attemptStartedAt: known?.attemptStartedAt ?? now(), - resumed: true, - awaitedHere: known?.awaited === true, - ...(known?.redirect === undefined - ? {} - : { returnedFrom: known.redirect }) + ...(known === undefined + ? { + presentation: routeFor(rail, pending), + attemptStartedAt: now(), + resumed: true, + awaitedHere: false + } + : resumedFrom(known)) }, includeSettled ) diff --git a/packages/account-ui/src/billing/usePaymentAttempt.ts b/packages/account-ui/src/billing/usePaymentAttempt.ts index e384790de05..9bc290cd8c6 100644 --- a/packages/account-ui/src/billing/usePaymentAttempt.ts +++ b/packages/account-ui/src/billing/usePaymentAttempt.ts @@ -74,6 +74,18 @@ function continuationKey( : undefined } +/** A non-card method finishes its challenge on the provider's site. */ +function leavesForProvider( + state: PendingBillingOperation, + method: CheckoutMethodKind | undefined +): boolean { + return ( + state.challenge?.status === 'required' && + method !== undefined && + method !== 'card' + ) +} + export function usePaymentAttempt( kind: BillingOperationKind, client: Pick, @@ -101,33 +113,38 @@ export function usePaymentAttempt( projectPaymentStep(operation.value, hostStep.value) ) - function continueVerification() { - const state = operation.value - if (state?.phase !== 'pending') return - const method = methodKind() - if (state.presentation === 'hosted') { - if (state.actionUrl !== undefined) { - client.lifecycle.reportHostedStepOpened( - state.id, - navigationMode === 'redirect' ? 'redirect' : 'new_tab', - method - ) - openUrl(state.actionUrl, navigationMode) - } - return - } + function openHostedStep( + state: PendingBillingOperation, + method: CheckoutMethodKind | undefined + ) { + if (state.actionUrl === undefined) return + client.lifecycle.reportHostedStepOpened( + state.id, + navigationMode === 'redirect' ? 'redirect' : 'new_tab', + method + ) + openUrl(state.actionUrl, navigationMode) + } + + function driveChallenge( + state: PendingBillingOperation, + method: CheckoutMethodKind | undefined + ) { if (challengePort === undefined) return - // A non-card method finishes its challenge on the provider's site. - if ( - state.challenge?.status === 'required' && - method !== undefined && - method !== 'card' - ) { + if (leavesForProvider(state, method)) { client.lifecycle.reportHostedStepOpened(state.id, 'redirect', method) } void driveEmbeddedChallenge(client.lifecycle, state.id, challengePort) } + function continueVerification() { + const state = operation.value + if (state?.phase !== 'pending') return + const method = methodKind() + if (state.presentation === 'hosted') openHostedStep(state, method) + else driveChallenge(state, method) + } + // Once per continuation the server offers; a resumed operation is not // re-entered on mount, since nothing the customer did asked for it. watch( From 8814fe1edcadcb46db198423465c15e1339cd350 Mon Sep 17 00:00:00 2001 From: Dante Date: Fri, 2 Oct 2026 21:21:03 -0400 Subject: [PATCH 10/19] FE-3119 feat(billing-web): report an abandoned checkout and the ending screen (#19948) ## Summary Report an abandoned checkout and the ending screen on the billing web full-page checkout, and send the abandon to PostHog by beacon (E24, E25). ## Why customer_abandoned is the largest failure class on the backend, and the browser had no event for a customer who closes the tab or goes back with an unresolved checkout. The ending screen the customer saw was not reported either, so a funnel could not tell a success screen from a refusal. ## How The shared journey contract gains two phases, billing.checkout.abandoned (last_phase, exit) and billing.checkout.ended (ending_kind, attribution), as union lines in checkoutJourney.ts with their payload fields. They carry the journey context, so they join entered and operation_linked on checkout_journey_id and billing_op_id. useCheckoutJourney remembers the last progress phase, reports each new ending kind once, and reports abandoned once, only before any ending. The full-page checkout reports ended from its existing endingOf screen and terminal attribution. It reports abandoned with exit page_exit on pagehide, and with exit back from the Back control. It reports no abandon when the page handed itself to a hosted step or a method's own site. The billing web telemetry facade sends abandoned to PostHog with transport sendBeacon. PostHog drains its queue on its own pagehide listener, which runs before ours, so a plain capture there would be queued and lost. There is no user-visible change. ## Review Focus - Flush check: Datadog RUM 6.33 flushes by sendBeacon on visibilitychange hidden, freeze and beforeunload. It has no pagehide listener, but the browser fires visibilitychange after pagehide on unload, so an action added in pagehide is sent. PostHog 1.402 drains by beacon on pagehide, so only an event captured inside pagehide needs the sendBeacon option. - leftForPayment: a redirect to a hosted step or a non-card method's site is a redirect_started, not an abandon. - Existing journey tests now expect billing.checkout.ended after a preview failure and after a success. - Known gaps: the embedded billing web CheckoutView reports neither phase. The cloud app reports no abandoned event, because its journey is kept in session storage across dialogs and reloads, and whether a dialog close ends it needs a product decision. A tab closed while already in the background may not flush its RUM action, because visibilitychange already fired; the derived count of starts without terminals covers it (D8). ## AS IS / TO BE Telemetry change, so the evidence is the captured events instead of a screenshot: the real SDK lifecycle and the billing web checkout with only the network edge and the telemetry SDKs (Datadog RUM, posthog-js) stubbed. AS IS = origin/main, TO BE = this stack. | Path | AS IS | TO BE | | --- | --- | --- | | E24 tab closed at the quote | `entered`, `preview_ready` | adds `abandoned` (last_phase preview_ready, exit page_exit); PostHog copy sent with `{transport: 'sendBeacon'}` | | E24 Back control | `entered`, `preview_ready`, `web_return.clicked` | adds `abandoned` (exit back), once, even though the page then unloads | | E24 Alipay Pay leaving for its own site | no abandon | still no abandon (it is a redirect) | | E25 own payment succeeds | no ending event | `ended` (ending_kind success, attribution started); no abandon when the tab closes after it | | E25 refused workspace | no ending event | `ended` (ending_kind refused), no attribution | No payload carries an email, URL, client secret, promo code or provider id; every new field is a bounded enum. evidence-fe3119/as-is-billing-web.json shows the tab-close, Back, success and refusal paths with no abandoned or ended event on main, and to-be-billing-web.json shows abandoned with last_phase and exit to RUM and to PostHog with transport sendBeacon, ended with ending_kind and attribution, and no abandon for an Alipay Pay that left for its own site. ## Where this sits in the plan Linear: [FE-3119](https://linear.app/comfyorg/issue/FE-3119), part of [FE-3105](https://linear.app/comfyorg/issue/FE-3105/billing-web-and-sdk-rollout-telemetry-events-fixes-and-dashboards). Plan, event catalog and dependency graph: [action items](https://app.notion.com/p/3ea6d73d3650814ba248d4d1431b8a89). | Task | Ticket | What | Status | | --- | --- | --- | --- | | T1 | FE-3107 | Decide vocabulary and dimensions | done, in the SSOT | | T2 | FE-3108 | Decide RUM application and env mapping | decided | | T3 | FE-3109 | Billing web telemetry bootstrap (RUM and PostHog) | [PR 19688](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19688), merged | | T3+ | FE-3156 | Opaque RUM user id on billing web | [PR 19794](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19794), merged | | T4, F1 | FE-3106 | SDK-rail ownership | [PR 19620](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19620), merged | | T4, F2 | FE-3110 | Keep operation id and fields in the mapper | [PR 19623](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19623), merged | | T4, F3 | FE-3111 | Stamp billing_surface and billing_client | [PR 19685](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19685), merged | | T4, F5 | FE-3112 | SDK top-up terminals | [PR 19628](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19628), merged | | T4, F6 | FE-3113 | Downgrade reconciliation terminal | [PR 19622](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19622), merged | | T4, F7 | FE-3114 | Legacy personal-rail events, first slice | [PR 19627](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19627), merged | | T4, F7+ | FE-3131 | Legacy personal-rail events, remaining slices | [PR 19686](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19686), merged | | T4+ | FE-3140 | Move the billing event contract to a shared package | [PR 19798](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19798), merged | | T5 | FE-3115 | Cloud entry fidelity and Datadog parity | [PR 19815](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19815) (four parts), in review | | T6 | FE-3116 | Handoff contract and event | [PR 19687](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19687), merged | | T7 | FE-3117 | Billing web attempt lifecycle | [PR 19809](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19809), [PR 19810](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19810), [PR 19811](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19811) merged, billing web cancel [PR 19945](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19945) in review | | T8 | FE-3118 | Billing web journey and choices | [PR 19819](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19819) (three parts), merged | | T9 | FE-3119 | Payment friction events | this PR | | T10 | FE-3120 | Billing web entry, session and return | [PR 19804](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19804), [PR 19806](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19806) and [PR 19807](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19807), merged in [PR 19798](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19798) | | T11 | FE-3121 | Portal events | [PR 19944](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19944), in review | | T12 | FE-3122 | Flag coverage check | [PR 19942](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19942), in review | | T13 | FE-3123 | PostHog rollout dashboard | specified, blocked on PostHog key scopes | | T14 | FE-3124 | Datadog tiles in the Frontend RUM dashboard | [comfy-infra PR 1597](https://github.com/Comfy-Org/comfy-infra/pull/1597), in review | | T4+ | FE-3162 | Move the payload-helper tests to account-core | [PR 19940](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19940), in review | | T10+ | FE-3158 | Billing web Try again after session creation fails | [PR 19941](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19941), in review | | T15 | FE-3125 | Verification per flow | todo | | T16 | FE-3126 | Rollout plan | todo | ```mermaid flowchart LR subgraph DEC["Decided"] T1["FE-3107 T1 vocabulary"] T2["FE-3108 T2 RUM app and env"] end subgraph FIX["Existing events (T4)"] F1["FE-3106 F1 SDK-rail ownership"] F2["FE-3110 F2 mapper fields"] F3["FE-3111 F3 surface and client"] F5["FE-3112 F5 top-up terminals"] F6["FE-3113 F6 downgrade terminal"] F7["FE-3114 F7 legacy personal, first slice"] F7B["FE-3131 F7 remaining slices"] C140["FE-3140 event contract to shared package"] end subgraph EMIT["New events"] T3["FE-3109 T3 billing web bootstrap"] T3b["FE-3156 T3+ opaque RUM user id"] T5["FE-3115 T5 cloud entry and parity"] T6["FE-3116 T6 handoff contract"] T7["FE-3117 T7 attempt lifecycle"] T8["FE-3118 T8 journey and choices"] T9["FE-3119 T9 friction"] T10["FE-3120 T10 entry, session, return"] T11["FE-3121 T11 portal"] T12["FE-3122 T12 flag coverage"] end subgraph DASH["Dashboards"] T13["FE-3123 T13 PostHog rollout"] T14["FE-3124 T14 Frontend RUM tiles"] end T15["FE-3125 T15 verification"] T16["FE-3126 T16 rollout plan"] T2 --> T3 T3 --> T3b F3 --> C140 T3 --> C140 C140 --> T7 C140 --> T8 C140 --> T10 C140 --> T11 T1 --> F3 T1 --> T5 T1 --> T6 T1 --> T13 T1 --> T14 T2 --> T14 F2 --> T7 T3 --> T7 T3 --> T8 T3 --> T10 T3 --> T11 T3 --> T12 T5 --> T11 T6 --> T8 T6 --> T10 T7 --> T9 T8 --> T9 F1 --> T13 F3 --> T13 FIX --> T15 T5 --> T15 T9 --> T15 T10 --> T15 T11 --> T15 T12 --> T15 T13 --> T15 T14 --> T15 T13 --> T16 T15 --> T16 style T9 stroke-width:3px ``` --- .../src/composables/useCheckoutJourney.ts | 34 +++++ .../src/composables/useFullPageCheckout.ts | 57 +++++++-- .../src/telemetry/billingWebTelemetry.test.ts | 21 ++++ .../src/telemetry/billingWebTelemetry.ts | 13 +- .../FullPageCheckoutView.journey.test.ts | 116 +++++++++++++++++- .../src/views/FullPageCheckoutView.vue | 2 + .../billing/telemetry/checkoutJourney.test.ts | 37 ++++++ .../core/billing/telemetry/checkoutJourney.ts | 59 ++++++++- .../src/core/billing/telemetry/index.ts | 4 + 9 files changed, 326 insertions(+), 17 deletions(-) diff --git a/apps/billing-web/src/composables/useCheckoutJourney.ts b/apps/billing-web/src/composables/useCheckoutJourney.ts index 5e085de2345..a0357ae4716 100644 --- a/apps/billing-web/src/composables/useCheckoutJourney.ts +++ b/apps/billing-web/src/composables/useCheckoutJourney.ts @@ -1,5 +1,9 @@ import type { + CheckoutEndingAttribution, + CheckoutEndingKind, CheckoutEntryFlow, + CheckoutExit, + CheckoutJourneyPhase, CheckoutJourneyPhaseEvent, PreviewSubscribeResult, SubscriptionPreview @@ -38,8 +42,15 @@ export function useCheckoutJourney(uiMode: 'embedded' | 'full_page') { let presses = 0 let linkingPress: number | undefined let billingOpId: string | undefined + let lastPhase: + | Exclude + | undefined + let lastEnding: CheckoutEndingKind | undefined + let left = false function track(phase: CheckoutJourneyPhaseEvent) { + if (phase.phase !== 'abandoned' && phase.phase !== 'ended') + lastPhase = phase.phase billingWebTelemetry.trackCheckoutJourneyEvent({ checkout_journey_id: journeyId, checkout_entered_at: enteredAt, @@ -143,9 +154,32 @@ export function useCheckoutJourney(uiMode: 'embedded' | 'full_page') { if (failed) track(failed) } + /** Once per ending screen shown; an ending resolves the journey. */ + function ended( + kind: CheckoutEndingKind, + attribution: CheckoutEndingAttribution | undefined + ) { + if (kind === lastEnding) return + lastEnding = kind + track({ + phase: 'ended', + ending_kind: kind, + ...(attribution !== undefined && { attribution }) + }) + } + + /** The customer left a journey no ending resolved; only the first way out counts. */ + function abandoned(exit: CheckoutExit) { + if (left || lastEnding !== undefined || lastPhase === undefined) return + left = true + track({ phase: 'abandoned', last_phase: lastPhase, exit }) + } + return { enter, track, + ended, + abandoned, submitted, submitSettled, operationIssued, diff --git a/apps/billing-web/src/composables/useFullPageCheckout.ts b/apps/billing-web/src/composables/useFullPageCheckout.ts index 79b5512eaf7..052629273d7 100644 --- a/apps/billing-web/src/composables/useFullPageCheckout.ts +++ b/apps/billing-web/src/composables/useFullPageCheckout.ts @@ -1,4 +1,8 @@ -import { tryOnScopeDispose, useIntervalFn } from '@vueuse/core' +import { + tryOnScopeDispose, + useEventListener, + useIntervalFn +} from '@vueuse/core' import { computed, shallowReadonly, shallowRef, watch } from 'vue' import { @@ -37,9 +41,11 @@ import { needsConsent, railAcceptsPay, reduceCheckoutPage, - settledPlanSource + settledPlanSource, + submitPhaseOf } from '@/checkout/checkoutPage' import { methodKindOf } from '@/checkout/checkoutJourney' +import { endingOf } from '@/checkout/endingScreen' import { pricingTableUrl } from '@/checkout/cloudLinks' import { createOperationChannel } from '@/checkout/operationChannel' import { promoEntryLive, promoRejectionOf } from '@/checkout/promoEntry' @@ -61,6 +67,7 @@ import { useCheckoutJourney } from '@/composables/useCheckoutJourney' import { useCheckoutPromo } from '@/composables/useCheckoutPromo' import { awaitBillingWebStripeKey } from '@/config/stripeKey' import { useBillingEntry } from '@/entry/billingEntry' +import type { BillingEntryState } from '@/entry/billingEntry' import { useBillingWebSession } from '@/session/billingWebSession' import { createDeferredStripeChallengePort } from '@/session/stripeChallengePort' import { @@ -154,6 +161,13 @@ function railOf( } as const } +/** A link that names no plan has nothing to quote, so it is as unreadable as a malformed one. */ +function arrivalPage({ entry, error }: BillingEntryState): CheckoutPage { + return error.value === undefined && entry.value?.plan !== undefined + ? RESOLVING + : UNREADABLE_LINK +} + /** * The full-page checkout's effects around one `CheckoutPage` state: the * reconciliation with whatever operation the workspace is already waiting @@ -185,11 +199,8 @@ export function useFullPageCheckout() { const journey = useCheckoutJourney('full_page') journey.enter() - /** A link that names no plan has nothing to quote, so it is as unreadable as a malformed one. */ const page = shallowRef( - unreadableLink.value === undefined && entry.value?.plan !== undefined - ? RESOLVING - : UNREADABLE_LINK + arrivalPage({ entry, error: unreadableLink }) ) /** Busy from the Pay click until the attempt resolves, whatever the lifecycle's promise does. */ @@ -205,8 +216,12 @@ export function useFullPageCheckout() { * reopens only a challenge that stays on this page (below), and anything * else waits for Complete verification. */ + let handedToHostedStep = false const checkout = useCheckout({ - openUrl: (url) => window.location.assign(url), + openUrl: (url) => { + handedToHostedStep = true + window.location.assign(url) + }, navigationMode: 'redirect', challengePort, autoContinue: () => submitting.value, @@ -579,6 +594,33 @@ export function useFullPageCheckout() { const { returnLink, openedByScript, close } = useCheckoutExit(page) + watch( + () => endingOf(page.value)?.kind, + (kind) => { + if (kind === undefined) return + const current = page.value + journey.ended( + kind, + current.kind === 'terminal' ? current.attribution : undefined + ) + }, + { immediate: true } + ) + + /** A page handed to a hosted step or a method's own site has not been abandoned. */ + function leftForPayment() { + const current = page.value + return ( + handedToHostedStep || + (current.kind === 'capture' && + submitPhaseOf(current).kind === 'redirecting') + ) + } + + useEventListener(window, 'pagehide', () => { + if (!leftForPayment()) journey.abandoned('page_exit') + }) + /** * The live catalog, on the Team tab when the link asked for a team plan: * one the quote named without its stop, or a link that carries a stop. @@ -735,6 +777,7 @@ export function useFullPageCheckout() { viewPlansLink, openedByScript, close, + abandon: journey.abandoned, retryLoad, onPaymentPhase, savedMethods: saved.methods, diff --git a/apps/billing-web/src/telemetry/billingWebTelemetry.test.ts b/apps/billing-web/src/telemetry/billingWebTelemetry.test.ts index 33879a692db..0005f611950 100644 --- a/apps/billing-web/src/telemetry/billingWebTelemetry.test.ts +++ b/apps/billing-web/src/telemetry/billingWebTelemetry.test.ts @@ -337,6 +337,27 @@ describe('trackCheckoutJourneyEvent', () => { ) }) + it('sends an abandoned checkout to PostHog by beacon, since the page is going away', async () => { + const telemetry = createBillingWebTelemetry() + await telemetry.startPostHog({ + config: Promise.resolve(CONFIGURED), + identity: ref({ kind: 'unknown' }) + }) + + telemetry.trackCheckoutJourneyEvent({ + ...ENTERED, + phase: 'abandoned', + last_phase: 'entered', + exit: 'page_exit' + }) + + expect(posthog.capture).toHaveBeenCalledExactlyOnceWith( + 'billing.checkout.abandoned', + expect.objectContaining({ last_phase: 'entered', exit: 'page_exit' }), + { transport: 'sendBeacon' } + ) + }) + it('holds back the journey phases the backend switched off, and only those', async () => { const telemetry = createBillingWebTelemetry() await telemetry.startPostHog({ diff --git a/apps/billing-web/src/telemetry/billingWebTelemetry.ts b/apps/billing-web/src/telemetry/billingWebTelemetry.ts index e62e017e3ef..8f77469db8c 100644 --- a/apps/billing-web/src/telemetry/billingWebTelemetry.ts +++ b/apps/billing-web/src/telemetry/billingWebTelemetry.ts @@ -45,6 +45,8 @@ type PostHogClient = Pick< interface BillingEvent { readonly name: BillingTelemetryEventName | CheckoutJourneyTelemetryEventName readonly properties: Readonly> + /** Sent while the page goes away, after PostHog has drained its queue on `pagehide`. */ + readonly onPageExit?: true } interface IdentitySink { @@ -155,8 +157,12 @@ export function createBillingWebTelemetry() { posthog.waiting.push(event) return case 'ready': - if (!posthog.disabledEvents.has(event.name)) - posthog.client.capture(event.name, event.properties) + if (posthog.disabledEvents.has(event.name)) return + if (event.onPageExit) + posthog.client.capture(event.name, event.properties, { + transport: 'sendBeacon' + }) + else posthog.client.capture(event.name, event.properties) } } @@ -217,7 +223,8 @@ export function createBillingWebTelemetry() { properties: { ...getCheckoutJourneyTelemetryEventPayload(event), billing_surface: 'billing_web' - } + }, + ...(event.phase === 'abandoned' && { onPageExit: true }) }) ) } diff --git a/apps/billing-web/src/views/FullPageCheckoutView.journey.test.ts b/apps/billing-web/src/views/FullPageCheckoutView.journey.test.ts index 0cb50db5db6..b70a7a35455 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.journey.test.ts +++ b/apps/billing-web/src/views/FullPageCheckoutView.journey.test.ts @@ -318,8 +318,13 @@ describe('the full-page checkout journey', () => { ])('$name', async ({ options, arrange, path, last }) => { await renderCheckout(options, arrange, path) - await waitFor(() => expect(journey()).toHaveLength(2)) - expect(journeyNames()[0]).toBe('billing.checkout.entered') + await waitFor(() => + expect(journeyNames()).toEqual([ + 'billing.checkout.entered', + 'billing.checkout.preview_failed', + 'billing.checkout.ended' + ]) + ) expect(journey()[1]).toMatchObject(last) }) @@ -416,7 +421,8 @@ describe('the full-page checkout journey', () => { 'billing.checkout.payment_submit_attempted', 'billing.checkout.method_selected', 'billing.checkout.submitted', - 'billing.checkout.operation_linked' + 'billing.checkout.operation_linked', + 'billing.checkout.ended' ]) ) const [, , , , , submitted, linked] = journey() @@ -824,3 +830,107 @@ describe('the full-page operation a Pay links', () => { expect(linked()).toMatchObject([{ billing_op_id: 'op_9' }]) }) }) + +describe('the full-page checkout exits and endings', () => { + beforeEach(() => { + vi.mocked(datadogRum.getInitConfiguration).mockReturnValue({ + clientToken: 'pub', + applicationId: 'app' + }) + vi.spyOn(window.location, 'assign').mockImplementation(() => {}) + }) + + const leavePage = () => { + window.dispatchEvent(new PageTransitionEvent('pagehide')) + } + const exitsOf = () => + journey().filter(({ name }) => name === 'billing.checkout.abandoned') + + it.for<{ name: string; leave: () => Promise | void; exit: string }>([ + { name: 'the page goes away', leave: leavePage, exit: 'page_exit' }, + { + name: 'the customer goes Back', + leave: () => + userEvent.click(screen.getByRole('button', { name: 'Back' })), + exit: 'back' + } + ])( + 'reports a checkout abandoned once, at its last phase, when $name', + async ({ leave, exit }) => { + await renderCheckout() + await waitFor(() => + expect(journeyNames()).toContain('billing.checkout.preview_ready') + ) + + await leave() + leavePage() + + expect(exitsOf()).toEqual([ + expect.objectContaining({ + phase: 'abandoned', + last_phase: 'preview_ready', + exit, + billing_surface: 'billing_web' + }) + ]) + } + ) + + it('reports no abandon for a page that left for a payment method of its own site', async () => { + const fake = await renderCheckout() + await screen.findByText('Subscribe to Creator Plan · Acme Team') + fake.subscribe.mockImplementation(() => new Promise(() => {})) + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + form.emit('confirm', 'ctoken_1', 'alipay') + await waitFor(() => expect(fake.subscribe).toHaveBeenCalled()) + + leavePage() + + expect(exitsOf()).toEqual([]) + }) + + it('reports the ending its own payment reached, and no abandon after it', async () => { + const fake = await renderCheckout({ + subscribe: { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation('op_9') } + } + }) + await screen.findByText('Subscribe to Creator Plan · Acme Team') + reportPhase({ phase: 'payment_element_ready', element: 'payment' }) + form.emit('confirm', 'ctoken_1', 'card') + await waitFor(() => expect(fake.subscribe).toHaveBeenCalled()) + await waitFor(() => + expect(journeyNames()).toContain('billing.checkout.ended') + ) + + leavePage() + + expect( + journey().filter(({ name }) => name === 'billing.checkout.ended') + ).toEqual([ + expect.objectContaining({ + phase: 'ended', + ending_kind: 'success', + attribution: 'started' + }) + ]) + expect(exitsOf()).toEqual([]) + }) + + it('reports an ending no payment reached without an attribution', async () => { + await renderCheckout({ + capabilities: {}, + denials: { can_subscribe_self_serve: 'not_workspace_owner' } + }) + + await waitFor(() => + expect(journeyNames()).toContain('billing.checkout.ended') + ) + const [ended] = journey().filter( + ({ name }) => name === 'billing.checkout.ended' + ) + expect(ended).toMatchObject({ ending_kind: 'refused' }) + expect(ended).not.toHaveProperty('attribution') + }) +}) diff --git a/apps/billing-web/src/views/FullPageCheckoutView.vue b/apps/billing-web/src/views/FullPageCheckoutView.vue index 09c1579fe66..590b51739fc 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.vue +++ b/apps/billing-web/src/views/FullPageCheckoutView.vue @@ -42,6 +42,7 @@ const { viewPlansLink, openedByScript, close, + abandon, retryLoad, onPaymentPhase, savedMethods, @@ -160,6 +161,7 @@ const endingPlan = computed(() => { function goBack() { reportReturnClicked('back') + abandon('back') window.location.assign(returnLink.value) } diff --git a/packages/account-core/src/core/billing/telemetry/checkoutJourney.test.ts b/packages/account-core/src/core/billing/telemetry/checkoutJourney.test.ts index 8813927270d..d55f53c1453 100644 --- a/packages/account-core/src/core/billing/telemetry/checkoutJourney.test.ts +++ b/packages/account-core/src/core/billing/telemetry/checkoutJourney.test.ts @@ -142,6 +142,43 @@ const CASES: readonly PayloadCase[] = [ phase: 'preview_failed', failure_category: 'network' } + }, + { + name: 'an abandoned checkout names the last phase it reached and how the customer left', + event: { + ...CONTEXT, + billing_op_id: 'op-1', + phase: 'abandoned', + last_phase: 'operation_linked', + exit: 'page_exit' + }, + payload: { + ...PAYLOAD_OF_CONTEXT, + billing_op_id: 'op-1', + phase: 'abandoned', + last_phase: 'operation_linked', + exit: 'page_exit' + } + }, + { + name: 'an ending names its screen and whose payment it was', + event: { + ...CONTEXT, + phase: 'ended', + ending_kind: 'success', + attribution: 'started' + }, + payload: { + ...PAYLOAD_OF_CONTEXT, + phase: 'ended', + ending_kind: 'success', + attribution: 'started' + } + }, + { + name: 'an ending no payment reached carries no attribution', + event: { ...CONTEXT, phase: 'ended', ending_kind: 'refused' }, + payload: { ...PAYLOAD_OF_CONTEXT, phase: 'ended', ending_kind: 'refused' } } ] diff --git a/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts b/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts index b3e648d0417..29c82551f9a 100644 --- a/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts +++ b/packages/account-core/src/core/billing/telemetry/checkoutJourney.ts @@ -125,7 +125,7 @@ type CheckoutJourneyOperationLinked = { billing_op_id: string } -export type CheckoutJourneyPhaseEvent = +type CheckoutJourneyProgressEvent = | CheckoutJourneyEntered | CheckoutJourneyPreviewReady | CheckoutJourneyPreviewFailed @@ -139,7 +139,45 @@ export type CheckoutJourneyPhaseEvent = | CheckoutJourneySubmitted | CheckoutJourneyOperationLinked -type CheckoutJourneyPhase = CheckoutJourneyPhaseEvent['phase'] +/** How the customer left: the page went away, or a control of this page led out. */ +export type CheckoutExit = 'page_exit' | 'back' | 'close' | 'host_link' +/** The ending screens of the full-page checkout. */ +export type CheckoutEndingKind = + | 'success' + | 'completed' + | 'already_completed' + | 'in_progress' + | 'received' + | 'unconfirmed' + | 'refused' + | 'plan_unavailable' + | 'link_invalid' + | 'load_failed' +/** Whose payment an ending shows: this page's Pay, a return, one it followed, or one already settled. */ +export type CheckoutEndingAttribution = + | 'started' + | 'returned' + | 'followed' + | 'settled' + +/** The customer left before the checkout reached an ending. */ +type CheckoutJourneyAbandoned = { + phase: 'abandoned' + last_phase: CheckoutJourneyProgressEvent['phase'] + exit: CheckoutExit +} +type CheckoutJourneyEnded = { + phase: 'ended' + ending_kind: CheckoutEndingKind + attribution?: CheckoutEndingAttribution +} + +export type CheckoutJourneyPhaseEvent = + | CheckoutJourneyProgressEvent + | CheckoutJourneyAbandoned + | CheckoutJourneyEnded + +export type CheckoutJourneyPhase = CheckoutJourneyPhaseEvent['phase'] export type CheckoutJourneyTelemetryEvent = CheckoutJourneyContext & CheckoutJourneyPhaseEvent @@ -167,7 +205,9 @@ export const CHECKOUT_JOURNEY_EVENT_NAME_BY_PHASE: Record< promo: 'billing.checkout.promo', pay_blocked: 'billing.checkout.pay_blocked', submitted: 'billing.checkout.submitted', - operation_linked: 'billing.checkout.operation_linked' + operation_linked: 'billing.checkout.operation_linked', + abandoned: 'billing.checkout.abandoned', + ended: 'billing.checkout.ended' } export function getCheckoutJourneyTelemetryEventName( @@ -236,6 +276,16 @@ function getChoicePayload(event: CheckoutJourneyPhaseEvent) { } } +function getExitPayload(event: CheckoutJourneyPhaseEvent) { + return { + ...('last_phase' in event && { last_phase: event.last_phase }), + ...('exit' in event && { exit: event.exit }), + ...('ending_kind' in event && { ending_kind: event.ending_kind }), + ...('attribution' in event && + event.attribution !== undefined && { attribution: event.attribution }) + } +} + export function getCheckoutJourneyTelemetryEventPayload( event: CheckoutJourneyTelemetryEvent ) { @@ -243,7 +293,8 @@ export function getCheckoutJourneyTelemetryEventPayload( ...getContextPayload(event), ...getPreviewPayload(event), ...getPaymentFormPayload(event), - ...getChoicePayload(event) + ...getChoicePayload(event), + ...getExitPayload(event) } } diff --git a/packages/account-core/src/core/billing/telemetry/index.ts b/packages/account-core/src/core/billing/telemetry/index.ts index 0858e823e93..fa1e6952f82 100644 --- a/packages/account-core/src/core/billing/telemetry/index.ts +++ b/packages/account-core/src/core/billing/telemetry/index.ts @@ -40,10 +40,14 @@ export type { } from './webSessionEvent.js' export type { CheckoutAssignmentStatus, + CheckoutEndingAttribution, + CheckoutEndingKind, CheckoutEntryFlow, + CheckoutExit, CheckoutEntrySource, CheckoutJourneyArm, CheckoutJourneyContext, + CheckoutJourneyPhase, CheckoutJourneyPhaseEvent, CheckoutJourneyTelemetryEvent, CheckoutJourneyTelemetryEventName, From 415ab5b090d3792eb41daef24b086336c647579d Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 21:46:37 -0400 Subject: [PATCH 11/19] test(billing-web): expect the embedded checkout to report abandons and ending screens --- .../src/views/CheckoutView.journey.test.ts | 175 +++++++++++++++++- .../src/views/CheckoutView.streams.test.ts | 1 + 2 files changed, 173 insertions(+), 3 deletions(-) diff --git a/apps/billing-web/src/views/CheckoutView.journey.test.ts b/apps/billing-web/src/views/CheckoutView.journey.test.ts index 267977f4342..c296a94c11f 100644 --- a/apps/billing-web/src/views/CheckoutView.journey.test.ts +++ b/apps/billing-web/src/views/CheckoutView.journey.test.ts @@ -22,6 +22,7 @@ import type { import { createFakeBillingClient, failedOperation, + hostedPendingOperation, pendingOperation, previewOf, succeededOperation @@ -260,9 +261,8 @@ describe('the embedded checkout journey', () => { ])('$name', async ({ options, last }) => { await renderCheckout(CHECKOUT_PATH, options) - await waitFor(() => expect(journey()).toHaveLength(2)) + await waitFor(() => expect(journey()[1]).toMatchObject(last)) expect(journeyNames()[0]).toBe('billing.checkout.entered') - expect(journey()[1]).toMatchObject(last) }) it.for<{ @@ -358,7 +358,8 @@ describe('the embedded checkout journey', () => { 'billing.checkout.payment_submit_attempted', 'billing.checkout.method_selected', 'billing.checkout.submitted', - 'billing.checkout.operation_linked' + 'billing.checkout.operation_linked', + 'billing.checkout.ended' ]) ) const [, , , , , submitted, linked] = journey() @@ -798,3 +799,171 @@ describe('the embedded checkout journey', () => { }) }) }) + +describe('the embedded checkout exits and endings', () => { + beforeEach(() => { + vi.mocked(datadogRum.getInitConfiguration).mockReturnValue({ + clientToken: 'pub', + applicationId: 'app' + }) + vi.spyOn(window.location, 'assign').mockImplementation(() => {}) + vi.spyOn(window, 'close').mockImplementation(() => {}) + }) + + const leavePage = () => { + window.dispatchEvent(new PageTransitionEvent('pagehide')) + } + const exitsOf = () => + journey().filter(({ name }) => name === 'billing.checkout.abandoned') + const endingsOf = () => + journey().filter(({ name }) => name === 'billing.checkout.ended') + + it.for<{ name: string; leave: () => Promise | void; exit: string }>([ + { name: 'the page goes away', leave: leavePage, exit: 'page_exit' }, + { + name: 'the customer goes Back', + leave: () => + userEvent.click(screen.getByRole('button', { name: 'Back' })), + exit: 'back' + }, + { + name: 'the customer closes the checkout', + leave: () => + userEvent.click(screen.getByRole('button', { name: 'Close' })), + exit: 'close' + } + ])( + 'reports a checkout abandoned once, at its last phase, when $name', + async ({ leave, exit }) => { + await renderCheckout() + await screen.findByRole('button', { name: 'Pay and subscribe' }) + await waitFor(() => + expect(journeyNames()).toContain('billing.checkout.preview_ready') + ) + + await leave() + leavePage() + + expect(exitsOf()).toEqual([ + expect.objectContaining({ + phase: 'abandoned', + last_phase: 'preview_ready', + exit, + ui_mode: 'embedded', + billing_surface: 'billing_web' + }) + ]) + } + ) + + it('reports no abandon for a page handed to a hosted payment step', async () => { + const fake = await renderCheckout() + await screen.findByRole('button', { name: 'Pay and subscribe' }) + + fake.publishOperation( + hostedPendingOperation('https://hooks.stripe.test/redirect/op_1') + ) + await waitFor(() => expect(window.location.assign).toHaveBeenCalled()) + leavePage() + + expect(exitsOf()).toEqual([]) + }) + + it('reports no abandon for a page that left for a payment method of its own site', async () => { + const fake = await renderCheckout() + await screen.findByRole('button', { name: 'Pay and subscribe' }) + fake.subscribe.mockImplementation(() => new Promise(() => {})) + + reportConfirm('ctoken_1', 'alipay') + await waitFor(() => expect(fake.subscribe).toHaveBeenCalled()) + leavePage() + + expect(exitsOf()).toEqual([]) + }) + + it('reports a card Pay still in flight when the page goes away as abandoned', async () => { + const fake = await renderCheckout() + await screen.findByRole('button', { name: 'Pay and subscribe' }) + fake.subscribe.mockImplementation(() => new Promise(() => {})) + + reportConfirm('ctoken_1', 'card') + await waitFor(() => expect(fake.subscribe).toHaveBeenCalled()) + leavePage() + + expect(exitsOf()).toEqual([ + expect.objectContaining({ last_phase: 'submitted', exit: 'page_exit' }) + ]) + }) + + it('reports the success its own payment reached, and no abandon after it', async () => { + await renderCheckout(CHECKOUT_PATH, { + subscribe: { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation('op_9') } + } + }) + await screen.findByRole('button', { name: 'Pay and subscribe' }) + + reportConfirm('ctoken_1', 'card') + await screen.findByRole('heading', { name: "You're all set" }) + await waitFor(() => expect(endingsOf()).toHaveLength(1)) + const [, closeButton] = screen.getAllByRole('button', { name: 'Close' }) + await userEvent.click(closeButton) + leavePage() + + expect(endingsOf()).toEqual([ + expect.objectContaining({ + phase: 'ended', + ending_kind: 'success', + attribution: 'started', + billing_op_id: 'op_9' + }) + ]) + expect(exitsOf()).toEqual([]) + }) + + it.for<{ + name: string + preview: PreviewSubscribeResult + kind: string + }>([ + { + name: 'a session the quote refused', + preview: { status: 'error', code: 'ACCESS_DENIED' }, + kind: 'refused' + }, + { + name: 'a plan the catalog does not have', + preview: { + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 400, + serverCode: readBillingErrorCode({ + code: 'INVALID_PLAN', + message: 'unknown plan' + }) + }, + kind: 'plan_unavailable' + }, + { + name: 'a quote that never got an answer', + preview: { status: 'error', code: 'REQUEST_FAILED' }, + kind: 'load_failed' + } + ])( + 'reports the ending screen of $name without an attribution, and no abandon after it', + async ({ preview, kind }) => { + await renderCheckout(CHECKOUT_PATH, { preview }) + await screen.findByRole('button', { name: 'Back' }) + + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + leavePage() + + expect(endingsOf()).toEqual([ + expect.objectContaining({ phase: 'ended', ending_kind: kind }) + ]) + expect(endingsOf()[0]).not.toHaveProperty('attribution') + expect(exitsOf()).toEqual([]) + } + ) +}) diff --git a/apps/billing-web/src/views/CheckoutView.streams.test.ts b/apps/billing-web/src/views/CheckoutView.streams.test.ts index 5fc02d99398..4571ff2abcf 100644 --- a/apps/billing-web/src/views/CheckoutView.streams.test.ts +++ b/apps/billing-web/src/views/CheckoutView.streams.test.ts @@ -240,6 +240,7 @@ describe('the embedded checkout journey beside the attempt and the SDK stream', { name: 'billing.operation.started', billingOpId: 'op_1' }, { name: 'billing.checkout.operation_linked', billingOpId: 'op_1' }, { name: 'billing.operation.succeeded', billingOpId: 'op_1' }, + { name: 'billing.checkout.ended', billingOpId: 'op_1' }, { name: 'billing.subscription_checkout.succeeded', billingOpId: 'op_1' } ]) }) From cc34e7eeb4451b54c53dd1fa37fb4d169a27ca63 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 2 Oct 2026 21:50:01 -0400 Subject: [PATCH 12/19] feat(billing-web): report abandons and ending screens on the embedded checkout --- .../src/checkout/checkoutJourney.ts | 13 +++++++++++ .../src/views/CheckoutView.journey.test.ts | 15 ++++++++++++ apps/billing-web/src/views/CheckoutView.vue | 23 +++++++++++++++++-- 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/apps/billing-web/src/checkout/checkoutJourney.ts b/apps/billing-web/src/checkout/checkoutJourney.ts index 30a6b557947..fedc3b5cf77 100644 --- a/apps/billing-web/src/checkout/checkoutJourney.ts +++ b/apps/billing-web/src/checkout/checkoutJourney.ts @@ -1,10 +1,13 @@ import type { + CheckoutEndingKind, CheckoutEntryFlow, CheckoutEntrySource, CheckoutJourneyPhaseEvent, PreviewSubscribeResult, + SubscriptionCommandFailure, SubscriptionPreview } from '@comfyorg/account-core/billing' +import { matchesServerCode } from '@comfyorg/account-core/billing' import type { BillingSource } from '@comfyorg/billing-contract' import type { CheckoutPageEvent } from '@/checkout/checkoutPage' @@ -110,6 +113,16 @@ export function previewFailureOfResult( } } +/** The full-page ending the embedded checkout's quote failure screen stands for. */ +export function quoteFailureEndingOf( + failure: SubscriptionCommandFailure +): CheckoutEndingKind { + if (failure.code === 'ACCESS_DENIED') return 'refused' + return 'serverCode' in failure && matchesServerCode(failure, 'INVALID_PLAN') + ? 'plan_unavailable' + : 'load_failed' +} + type MethodSelectedPhase = Extract< CheckoutJourneyPhaseEvent, { phase: 'method_selected' } diff --git a/apps/billing-web/src/views/CheckoutView.journey.test.ts b/apps/billing-web/src/views/CheckoutView.journey.test.ts index c296a94c11f..630e58fb1b6 100644 --- a/apps/billing-web/src/views/CheckoutView.journey.test.ts +++ b/apps/billing-web/src/views/CheckoutView.journey.test.ts @@ -922,6 +922,21 @@ describe('the embedded checkout exits and endings', () => { expect(exitsOf()).toEqual([]) }) + it('reports a success this page recovered rather than paid as followed', async () => { + await renderCheckout(CHECKOUT_PATH, { + recover: { status: 'ok', value: succeededOperation('op_old') } + }) + + await screen.findByRole('heading', { name: "You're all set" }) + await waitFor(() => expect(endingsOf()).toHaveLength(1)) + + expect(endingsOf()[0]).toMatchObject({ + ending_kind: 'success', + attribution: 'followed' + }) + expect(endingsOf()[0]).not.toHaveProperty('billing_op_id') + }) + it.for<{ name: string preview: PreviewSubscribeResult diff --git a/apps/billing-web/src/views/CheckoutView.vue b/apps/billing-web/src/views/CheckoutView.vue index f35f1756cc0..60671b7deb9 100644 --- a/apps/billing-web/src/views/CheckoutView.vue +++ b/apps/billing-web/src/views/CheckoutView.vue @@ -6,7 +6,7 @@ * every way out leads back there. A hosted continuation redirects this tab * and comes back on `/v1/result`. */ -import { useTimeoutFn } from '@vueuse/core' +import { useEventListener, useTimeoutFn } from '@vueuse/core' import { computed, onMounted, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' @@ -39,6 +39,7 @@ import { buildReturnUrl } from '@comfyorg/billing-contract' +import { quoteFailureEndingOf } from '@/checkout/checkoutJourney' import type { PaymentChoice } from '@/checkout/checkoutRequest' import { buildSubscribeRequest, @@ -97,8 +98,15 @@ const { lifecycle, status } = useBillingClient<'lifecycle' | 'status'>( undefined ) +/** A page handed to a hosted step or a method's own site has not been abandoned. */ +let handedToHostedStep = false +let payingOnOwnSite = false + const checkout = useCheckout({ - openUrl: (url) => window.location.assign(url), + openUrl: (url) => { + handedToHostedStep = true + window.location.assign(url) + }, navigationMode: 'redirect', // Deferred: reads the key at challenge time, not this setup's snapshot. challengePort: createDeferredStripeChallengePort(awaitBillingWebStripeKey) @@ -133,6 +141,8 @@ async function quotePlan( if (call === latestQuoteCall) { if (promotionCode === undefined) journey.quoted(result) else journey.promoQuoted(result, promotionCode) + if (failure.value && !preview.value) + journey.ended(quoteFailureEndingOf(failure.value), undefined) } return result } @@ -416,6 +426,7 @@ watch( if (!settled || submitting || id === announcedSuccess.value) return announcedSuccess.value = id const result = checkout.result.value + journey.ended('success', result?.status === 'ok' ? 'started' : 'followed') const tookPayment = result?.status !== 'ok' || result.value.issuedStatus !== 'subscribed' if (tookPayment) showSuccessToast() @@ -523,6 +534,8 @@ async function pay(choice: PaymentChoice) { submitFailure.value = undefined reportMethodSelected(choice) const press = journey.submitted() + payingOnOwnSite = + choice.methodType !== undefined && choice.methodType !== 'card' let result: SubscriptionCommandResult try { result = await attempts.run(checkoutAttemptOf(quoted, entry.value), () => @@ -539,6 +552,7 @@ async function pay(choice: PaymentChoice) { ) ) } finally { + payingOnOwnSite = false journey.submitSettled(press) } if (result.status === 'ok') return @@ -572,8 +586,13 @@ function leaveForHost(control: WebReturnControl) { const href = returnLink.value if (href === undefined) return reportReturnClicked(control) + if (control !== 'success_close') journey.abandoned(control) returnToHost(href) } + +useEventListener(window, 'pagehide', () => { + if (!handedToHostedStep && !payingOnOwnSite) journey.abandoned('page_exit') +})