diff --git a/apps/billing-web/src/components/SubscriptionActions.vue b/apps/billing-web/src/components/SubscriptionActions.vue index 45428b0ab0a..347bb1e1e74 100644 --- a/apps/billing-web/src/components/SubscriptionActions.vue +++ b/apps/billing-web/src/components/SubscriptionActions.vue @@ -6,7 +6,7 @@ * the checkout composable, whose continuation redirects this tab when the * server asks for a card. */ -import { nextTick, onMounted, ref } from 'vue' +import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue' import { useI18n } from 'vue-i18n' import type { @@ -18,6 +18,13 @@ import { useBillingClient, useCheckout } from '@comfyorg/account-ui/billing' import { useHostedCopy } from '@/composables/useHostedCopy' import { awaitBillingWebStripeKey } from '@/config/stripeKey' import { createDeferredStripeChallengePort } from '@/session/stripeChallengePort' +import { createCancelFlowTelemetry } from '@/telemetry/cancelTelemetry' +import type { CancelledPlan } from '@/telemetry/cancelTelemetry' + +const { currentPlan } = defineProps<{ + /** The plan a cancel would end, for the cancel flow's telemetry. */ + currentPlan?: CancelledPlan +}>() const emit = defineEmits<{ /** The subscription changed on the server; readers over it are stale. */ @@ -37,6 +44,9 @@ const checkout = useCheckout({ challengePort: createDeferredStripeChallengePort(awaitBillingWebStripeKey) }) +const cancelFlow = createCancelFlowTelemetry({ plan: () => currentPlan }) +onBeforeUnmount(() => cancelFlow.abandoned()) + const allowed = ref() const confirmingCancel = ref(false) const cancelTrigger = ref(null) @@ -83,12 +93,14 @@ async function settle( /** The trigger is replaced by these controls, so the keyboard has to follow. */ async function askToCancel() { confirmingCancel.value = true + cancelFlow.intent() await nextTick() confirmCancelAction.value?.focus() } async function keepPlan() { confirmingCancel.value = false + cancelFlow.abandoned() await nextTick() cancelTrigger.value?.focus() } @@ -96,7 +108,7 @@ async function keepPlan() { async function cancelSubscription() { confirmingCancel.value = false await settle( - () => commands.cancelSubscription(), + () => cancelFlow.confirm(() => commands.cancelSubscription()), t('hosted.subscription.cancelled') ) } diff --git a/apps/billing-web/src/components/SubscriptionPanel.vue b/apps/billing-web/src/components/SubscriptionPanel.vue index f48cba7b37b..0cf665506e4 100644 --- a/apps/billing-web/src/components/SubscriptionPanel.vue +++ b/apps/billing-web/src/components/SubscriptionPanel.vue @@ -29,13 +29,14 @@ async function subscriptionChanged() { const endsAt = computed(() => billingStatus.value?.cancel_at) -const currentName = computed(() => { +const currentPlan = computed(() => { const catalog = plans.value - const current = catalog?.plans.find( - (plan) => plan.slug === catalog.current_plan_slug - ) - return current ? planName(current) : undefined + return catalog?.plans.find((plan) => plan.slug === catalog.current_plan_slug) }) + +const currentName = computed(() => + currentPlan.value ? planName(currentPlan.value) : undefined +) diff --git a/apps/billing-web/src/telemetry/cancelTelemetry.ts b/apps/billing-web/src/telemetry/cancelTelemetry.ts new file mode 100644 index 00000000000..37f2ce2aa73 --- /dev/null +++ b/apps/billing-web/src/telemetry/cancelTelemetry.ts @@ -0,0 +1,69 @@ +import type { + BillingPlansData, + BillingTelemetryEvent, + SubscriptionCommandResult +} from '@comfyorg/account-core/billing' +import { isAnnualDuration } from '@comfyorg/account-ui/billing/checkout' + +import { outcomeOfCommandResult } from '@/telemetry/attemptTelemetry' +import { billingWebTelemetry } from '@/telemetry/billingWebTelemetry' +import { checkoutTierOf } from '@/telemetry/subscriptionCheckoutTelemetry' + +export type CancelledPlan = Pick< + BillingPlansData['plans'][number], + 'tier' | 'duration' +> + +/** + * The cancel flow's own stages. A confirmed cancel that issues an operation + * ends in that operation's `billing.operation.*` events, which the SDK + * reports, so `failed` here is only a refusal before any operation exists. + */ +export function createCancelFlowTelemetry({ + plan, + track = billingWebTelemetry.trackBillingEvent +}: { + readonly plan: () => CancelledPlan | undefined + readonly track?: (event: BillingTelemetryEvent) => void +}) { + let open = false + + function describe() { + const current = plan() + return { + operation: 'cancel', + billing_client: 'sdk', + current_tier: current && checkoutTierOf(current.tier), + cycle: + current && (isAnnualDuration(current.duration) ? 'yearly' : 'monthly') + } as const + } + + return { + intent() { + if (open) return + open = true + track({ ...describe(), stage: 'intent', outcome: 'pending' }) + }, + abandoned() { + if (!open) return + open = false + track({ ...describe(), stage: 'abandoned', outcome: 'pending' }) + }, + async confirm( + command: () => Promise + ): Promise { + open = false + const result = await command() + const outcome = outcomeOfCommandResult(result) + if (result.status === 'error' && outcome.kind === 'failed') + track({ + ...describe(), + stage: 'failed', + outcome: 'failure', + ...outcome.failure + }) + return result + } + } +} diff --git a/apps/billing-web/src/telemetry/subscriptionCheckoutTelemetry.ts b/apps/billing-web/src/telemetry/subscriptionCheckoutTelemetry.ts index feaa0804c42..6482c7c2a9b 100644 --- a/apps/billing-web/src/telemetry/subscriptionCheckoutTelemetry.ts +++ b/apps/billing-web/src/telemetry/subscriptionCheckoutTelemetry.ts @@ -36,12 +36,19 @@ const TIER_BY_SERVER_TIER: Record< ENTERPRISE: undefined } +/** The contract's name for a plan tier the server reports; absent for one it has no name for. */ +export function checkoutTierOf( + tier: ServerTier +): SubscriptionCheckoutTier | undefined { + return TIER_BY_SERVER_TIER[tier] +} + export function checkoutAttemptOf( quote: SubscriptionPreview, entry: { readonly source?: PaymentIntentSource } | undefined ): CheckoutAttempt { return { - tier: TIER_BY_SERVER_TIER[quote.new_plan.tier], + tier: checkoutTierOf(quote.new_plan.tier), cycle: isAnnualDuration(quote.new_plan.duration) ? 'yearly' : 'monthly', checkoutType: quote.transition_type === 'new_subscription' ? 'new' : 'change', diff --git a/apps/billing-web/src/views/SubscriptionView.test.ts b/apps/billing-web/src/views/SubscriptionView.test.ts index 33137ce6768..92f40351a74 100644 --- a/apps/billing-web/src/views/SubscriptionView.test.ts +++ b/apps/billing-web/src/views/SubscriptionView.test.ts @@ -2,7 +2,11 @@ import userEvent from '@testing-library/user-event' import { render, screen, waitFor } from '@testing-library/vue' import { createMemoryHistory, createRouter } from 'vue-router' -import type { BillingPlansData } from '@comfyorg/account-core/billing' +import type { + BillingPlansData, + BillingTelemetryEvent, + SubscriptionCommandResult +} from '@comfyorg/account-core/billing' import { BILLING_CLIENT_KEY } from '@comfyorg/account-ui/billing' import { parseBillingEntry } from '@comfyorg/billing-contract' @@ -12,9 +16,12 @@ import type { FakeBillingClientOptions } from '@/test/fakeBillingClient' import { challengedPendingOperation, createFakeBillingClient, + failedOperation, hostedPendingOperation, - planOf + planOf, + succeededOperation } from '@/test/fakeBillingClient' +import { trackedBillingEvents } from '@/test/trackedBillingEvents' import SubscriptionView from '@/views/SubscriptionView.vue' /** The values this surface and the session it sits under read; a test-family key stands in for a deployment's. */ @@ -71,13 +78,13 @@ async function renderSubscription(options: FakeBillingClientOptions = {}) { }) await router.push(`${SURFACE_PATH}?${ENTRY_QUERY}`) await router.isReady() - render(SubscriptionView, { + const { unmount } = render(SubscriptionView, { global: { plugins: [createBillingI18n(), router], provide: { [BILLING_CLIENT_KEY]: fake.client } } }) - return fake + return { ...fake, unmount } } describe('SubscriptionView', () => { @@ -385,4 +392,146 @@ describe('SubscriptionView', () => { ) ).toBeInTheDocument() }) + + describe('cancel flow telemetry', () => { + const PRO_ANNUAL: BillingPlansData = { + current_plan_slug: 'pro_annual', + plans: [planOf({ slug: 'pro_annual', tier: 'PRO', duration: 'ANNUAL' })] + } + + const flow = { + operation: 'cancel', + billing_client: 'sdk', + current_tier: 'pro', + cycle: 'yearly' + } as const + + const INTENT: BillingTelemetryEvent = { + ...flow, + stage: 'intent', + outcome: 'pending' + } + + function cancelEvents(sent: () => BillingTelemetryEvent[]) { + return sent().filter((event) => event.operation === 'cancel') + } + + async function openCancelFlow(cancel?: SubscriptionCommandResult) { + const sent = trackedBillingEvents() + const view = await renderSubscription({ + capabilities: { can_cancel: true }, + plans: { status: 'ok', value: PRO_ANNUAL }, + ...(cancel ? { cancel } : {}) + }) + await screen.findByText('Current plan: Pro ยท Yearly') + await userEvent.click( + screen.getByRole('button', { name: 'Cancel subscription' }) + ) + return { sent, view } + } + + it('reports opening the confirmation and keeping the plan', async () => { + const { sent } = await openCancelFlow() + + await userEvent.click( + screen.getByRole('button', { name: 'Keep my plan' }) + ) + + expect(cancelEvents(sent)).toEqual([ + INTENT, + { ...flow, stage: 'abandoned', outcome: 'pending' } + ]) + }) + + it('reports leaving the page while the confirmation is open as abandoned', async () => { + const { sent, view } = await openCancelFlow() + + view.unmount() + + expect(cancelEvents(sent)).toEqual([ + INTENT, + { ...flow, stage: 'abandoned', outcome: 'pending' } + ]) + }) + + it.for<{ name: string; cancel: SubscriptionCommandResult }>([ + { + name: 'a cancel the server settled', + cancel: { + status: 'ok', + value: { phase: 'succeeded', operation: succeededOperation() } + } + }, + { + name: 'a cancel operation that failed', + cancel: { + status: 'ok', + value: { + phase: 'failed', + operation: failedOperation('card_declined') + } + } + }, + { + name: 'a cancel that already held', + cancel: { status: 'ok', value: { phase: 'succeeded' } } + } + ])( + 'leaves the end of $name to the operation events', + async ({ cancel }) => { + const { sent, view } = await openCancelFlow(cancel) + + await userEvent.click( + screen.getByRole('button', { name: 'Confirm cancellation' }) + ) + await waitFor(() => + expect(view.cancelSubscription).toHaveBeenCalledOnce() + ) + view.unmount() + + expect(cancelEvents(sent)).toEqual([INTENT]) + } + ) + + it.for<{ + name: string + cancel: SubscriptionCommandResult + failure: Record + }>([ + { + name: 'a request that never reached the server', + cancel: { status: 'error', code: 'REQUEST_FAILED' }, + failure: { failure_category: 'network' } + }, + { + name: 'no subscription to cancel', + cancel: { status: 'error', code: 'NO_ACTIVE_SUBSCRIPTION' }, + failure: { failure_category: 'api_rejected' } + }, + { + name: 'an earlier payment still open', + cancel: { status: 'error', code: 'OPERATION_ALREADY_PENDING' }, + failure: { + failure_category: 'api_rejected', + error_code: 'operation_already_pending' + } + } + ])( + 'reports $name as a failed cancel before any operation exists', + async ({ cancel, failure }) => { + const { sent } = await openCancelFlow(cancel) + + await userEvent.click( + screen.getByRole('button', { name: 'Confirm cancellation' }) + ) + + await waitFor(() => + expect(cancelEvents(sent)).toEqual([ + INTENT, + { ...flow, stage: 'failed', outcome: 'failure', ...failure } + ]) + ) + } + ) + }) })