Line data Source code
1 : import type { BillingTelemetryFailureCategory } from '@comfyorg/account-core/billing'
2 :
3 : import {
4 : toBillingCycle,
5 : toCurrentTier
6 : } from '@/platform/billing/subscription/utils/billingPlanTelemetry'
7 : import type {
8 : SubscriptionCancellationMetadata,
9 : TelemetryDispatcher
10 : } from '@comfyorg/telemetry/types'
11 : import type {
12 : SubscriptionDuration,
13 : SubscriptionTier
14 : } from '@comfyorg/billing-core'
15 :
16 : interface SubscriptionCancellationMetadataOptions {
17 : cancelAt?: string
18 : duration?: SubscriptionDuration | null
19 : endDate?: string | null
20 : tier?: SubscriptionTier | null
21 : }
22 :
23 0 : export function getSubscriptionCancellationMetadata({
24 : cancelAt,
25 : duration,
26 : endDate,
27 : tier
28 : }: SubscriptionCancellationMetadataOptions): SubscriptionCancellationMetadata {
29 0 : const effectiveEndDate = cancelAt ?? endDate
30 0 : return {
31 : source: 'cancel_plan_menu',
32 : current_tier: tier?.toLowerCase(),
33 : ...(duration
34 : ? { cycle: duration === 'ANNUAL' ? 'yearly' : 'monthly' }
35 : : {}),
36 : ...(effectiveEndDate ? { end_date: effectiveEndDate } : {})
37 : }
38 : }
39 :
40 : /**
41 : * Reports a cancel flow as billing events. Once the customer confirms, the flow
42 : * is no longer abandoned. While a confirmed cancel is expected to become an
43 : * operation, its `billing.operation.*` events also own any failure, so `failed`
44 : * is reported only for a flow that has no operation expected.
45 : */
46 4 : export function createCancelFlowReporter(
47 : telemetry: TelemetryDispatcher | null,
48 : getPlan: () => Pick<
49 : SubscriptionCancellationMetadataOptions,
50 : 'duration' | 'tier'
51 : >,
52 : options: { confirmed?: boolean } = {}
53 : ) {
54 4 : let confirmed = options.confirmed ?? false
55 4 : let operationFollows = false
56 4 : const plan = () => {
57 0 : const { duration, tier } = getPlan()
58 0 : return {
59 : current_tier: toCurrentTier(tier),
60 : cycle: toBillingCycle(duration)
61 : }
62 : }
63 :
64 4 : return {
65 : intent() {
66 4 : telemetry?.trackBillingEvent({
67 : operation: 'cancel',
68 : stage: 'intent',
69 : outcome: 'pending',
70 : ...plan()
71 : })
72 : },
73 : confirmed(options: { operationFollows: boolean }) {
74 1 : confirmed = true
75 1 : operationFollows = options.operationFollows
76 : },
77 : abandoned() {
78 2 : if (confirmed) return
79 2 : telemetry?.trackBillingEvent({
80 : operation: 'cancel',
81 : stage: 'abandoned',
82 : outcome: 'pending',
83 : ...plan()
84 : })
85 : },
86 : failed(failureCategory: BillingTelemetryFailureCategory) {
87 1 : if (operationFollows) return
88 1 : telemetry?.trackBillingEvent({
89 : operation: 'cancel',
90 : stage: 'failed',
91 : outcome: 'failure',
92 : failure_category: failureCategory,
93 : ...plan()
94 : })
95 : }
96 : }
97 : }
|