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/checkout/checkoutRequest.test.ts b/apps/billing-web/src/checkout/checkoutRequest.test.ts index 3b8bf1cedf8..febaae8f740 100644 --- a/apps/billing-web/src/checkout/checkoutRequest.test.ts +++ b/apps/billing-web/src/checkout/checkoutRequest.test.ts @@ -2,6 +2,7 @@ import { previewOf } from '@/test/fakeBillingClient' import { buildSubscribeRequest, + paysOnOwnSite, teamCheckoutPlan, tierCheckoutPlan } from './checkoutRequest' @@ -123,3 +124,14 @@ describe('buildSubscribeRequest', () => { ).toEqual({ plan_slug: 'pro_monthly', confirmation_token: 'ctok' }) }) }) + +describe('paysOnOwnSite', () => { + it.for<{ name: string; methodType: string | undefined; away: boolean }>([ + { name: 'an Alipay account', methodType: 'alipay', away: true }, + { name: 'any other non-card method', methodType: 'sepa_debit', away: true }, + { name: 'a card', methodType: 'card', away: false }, + { name: 'a method nobody named', methodType: undefined, away: false } + ])('says $name pays on its own site: $away', ({ methodType, away }) => { + expect(paysOnOwnSite(methodType)).toBe(away) + }) +}) diff --git a/apps/billing-web/src/checkout/checkoutRequest.ts b/apps/billing-web/src/checkout/checkoutRequest.ts index b5cbc3c2503..f044cac9d0a 100644 --- a/apps/billing-web/src/checkout/checkoutRequest.ts +++ b/apps/billing-web/src/checkout/checkoutRequest.ts @@ -68,6 +68,11 @@ export interface PaymentChoice { readonly confirmReactivation?: boolean } +/** A method other than a card authenticates on its own site, so the page leaves while it pays. */ +export function paysOnOwnSite(methodType: string | undefined): boolean { + return methodType !== undefined && methodType !== 'card' +} + export interface SubscribeContext { readonly planSlug: string readonly teamCreditStopId?: string diff --git a/apps/billing-web/src/views/CheckoutView.journey.test.ts b/apps/billing-web/src/views/CheckoutView.journey.test.ts index 267977f4342..c532e53c380 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,224 @@ 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.for<{ name: string; type: string; label: string; exits: number }>([ + { + name: 'a saved Alipay account, which pays on its own site', + type: 'alipay', + label: 'Alipay', + exits: 0 + }, + { name: 'a saved card', type: 'card', label: 'visa •••• 4242', exits: 1 } + ])( + 'reports $exits abandon when the page goes away during a Pay with $name', + async ({ type, label, exits }) => { + const fake = await renderCheckout(CHECKOUT_PATH, { + paymentMethods: { + status: 'ok', + value: [ + { + id: 'pm_saved', + type, + brand: 'visa', + last4: '4242', + is_default: true + } + ] + } + }) + await screen.findByText(label) + fake.subscribe.mockImplementation(() => new Promise(() => {})) + + await userEvent.click( + screen.getByRole('button', { name: 'Pay and subscribe' }) + ) + await waitFor(() => expect(fake.subscribe).toHaveBeenCalled()) + leavePage() + + expect(exitsOf()).toHaveLength(exits) + } + ) + + 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('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 + 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' } ]) }) diff --git a/apps/billing-web/src/views/CheckoutView.vue b/apps/billing-web/src/views/CheckoutView.vue index f35f1756cc0..3aa2e8ba0ea 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,9 +39,11 @@ import { buildReturnUrl } from '@comfyorg/billing-contract' +import { quoteFailureEndingOf } from '@/checkout/checkoutJourney' import type { PaymentChoice } from '@/checkout/checkoutRequest' import { buildSubscribeRequest, + paysOnOwnSite, teamCheckoutPlan, tierCheckoutPlan } from '@/checkout/checkoutRequest' @@ -97,8 +99,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 +142,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 +427,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() @@ -509,11 +521,12 @@ function selectedRailOf(choice: PaymentChoice) { return choice.savedPaymentMethodId !== undefined ? 'saved' : 'on_file' } -function reportMethodSelected(choice: PaymentChoice) { - const savedType = methods.value?.find( - ({ id }) => id === choice.savedPaymentMethodId - )?.type - journey.methodSelected(selectedRailOf(choice), choice.methodType ?? savedType) +/** The chosen method's type: the form names a new one, and a saved one is read from the loaded methods. */ +function methodTypeOf(choice: PaymentChoice): string | undefined { + return ( + choice.methodType ?? + methods.value?.find(({ id }) => id === choice.savedPaymentMethodId)?.type + ) } async function pay(choice: PaymentChoice) { @@ -521,8 +534,10 @@ async function pay(choice: PaymentChoice) { const slug = planSlug.value if (slug === undefined || !quoted || loading.value) return submitFailure.value = undefined - reportMethodSelected(choice) + const methodType = methodTypeOf(choice) + journey.methodSelected(selectedRailOf(choice), methodType) const press = journey.submitted() + payingOnOwnSite = paysOnOwnSite(methodType) let result: SubscriptionCommandResult try { result = await attempts.run(checkoutAttemptOf(quoted, entry.value), () => @@ -539,6 +554,7 @@ async function pay(choice: PaymentChoice) { ) ) } finally { + payingOnOwnSite = false journey.submitSettled(press) } if (result.status === 'ok') return @@ -572,8 +588,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') +})