Skip to content
34 changes: 34 additions & 0 deletions apps/billing-web/src/composables/useCheckoutJourney.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type {
CheckoutEndingAttribution,
CheckoutEndingKind,
CheckoutEntryFlow,
CheckoutExit,
CheckoutJourneyPhase,
CheckoutJourneyPhaseEvent,
PreviewSubscribeResult,
SubscriptionPreview
Expand Down Expand Up @@ -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<CheckoutJourneyPhase, 'abandoned' | 'ended'>
| 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,
Expand Down Expand Up @@ -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,
Expand Down
57 changes: 50 additions & 7 deletions apps/billing-web/src/composables/useFullPageCheckout.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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'
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<CheckoutPage>(
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. */
Expand All @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -735,6 +777,7 @@ export function useFullPageCheckout() {
viewPlansLink,
openedByScript,
close,
abandon: journey.abandoned,
retryLoad,
onPaymentPhase,
savedMethods: saved.methods,
Expand Down
21 changes: 21 additions & 0 deletions apps/billing-web/src/telemetry/billingWebTelemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SessionIdentity>({ 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({
Expand Down
13 changes: 10 additions & 3 deletions apps/billing-web/src/telemetry/billingWebTelemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ type PostHogClient = Pick<
interface BillingEvent {
readonly name: BillingTelemetryEventName | CheckoutJourneyTelemetryEventName
readonly properties: Readonly<Record<string, unknown>>
/** Sent while the page goes away, after PostHog has drained its queue on `pagehide`. */
readonly onPageExit?: true
}

interface IdentitySink {
Expand Down Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -217,7 +223,8 @@ export function createBillingWebTelemetry() {
properties: {
...getCheckoutJourneyTelemetryEventPayload(event),
billing_surface: 'billing_web'
}
},
...(event.phase === 'abandoned' && { onPageExit: true })
})
)
}
Expand Down
116 changes: 113 additions & 3 deletions apps/billing-web/src/views/FullPageCheckoutView.journey.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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> | 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')
})
})
2 changes: 2 additions & 0 deletions apps/billing-web/src/views/FullPageCheckoutView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const {
viewPlansLink,
openedByScript,
close,
abandon,
retryLoad,
onPaymentPhase,
savedMethods,
Expand Down Expand Up @@ -160,6 +161,7 @@ const endingPlan = computed<EndingPlan | undefined>(() => {

function goBack() {
reportReturnClicked('back')
abandon('back')
window.location.assign(returnLink.value)
}

Expand Down
Loading
Loading