Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions apps/billing-web/src/components/SubscriptionActions.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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. */
Expand All @@ -37,6 +44,9 @@ const checkout = useCheckout({
challengePort: createDeferredStripeChallengePort(awaitBillingWebStripeKey)
})

const cancelFlow = createCancelFlowTelemetry({ plan: () => currentPlan })
onBeforeUnmount(() => cancelFlow.abandoned())

const allowed = ref<BillingCapabilities | undefined>()
const confirmingCancel = ref(false)
const cancelTrigger = ref<HTMLButtonElement | null>(null)
Expand Down Expand Up @@ -83,20 +93,22 @@ 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()
}

async function cancelSubscription() {
confirmingCancel.value = false
await settle(
() => commands.cancelSubscription(),
() => cancelFlow.confirm(() => commands.cancelSubscription()),
t('hosted.subscription.cancelled')
)
}
Expand Down
16 changes: 10 additions & 6 deletions apps/billing-web/src/components/SubscriptionPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
</script>

<template>
Expand All @@ -58,6 +59,9 @@ const currentName = computed(() => {
{{ t('hosted.subscription.endsOn', { date: date(endsAt) }) }}
</p>

<SubscriptionActions @changed="subscriptionChanged" />
<SubscriptionActions
:current-plan="currentPlan"
@changed="subscriptionChanged"
/>
</section>
</template>
69 changes: 69 additions & 0 deletions apps/billing-web/src/telemetry/cancelTelemetry.ts
Original file line number Diff line number Diff line change
@@ -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<SubscriptionCommandResult>
): Promise<SubscriptionCommandResult> {
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
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
157 changes: 153 additions & 4 deletions apps/billing-web/src/views/SubscriptionView.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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. */
Expand Down Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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<string, string>
}>([
{
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 }
])
)
}
)
})
})
Loading