LCOV - code coverage report
Current view: top level - src/platform/billing/subscription/composables - useSubscriptionDialog.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 25.0 % 36 9
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useDialogService } from '@/services/dialogService'
       2              : import { useDialogStore } from '@/stores/dialogStore'
       3              : import { useBillingContext } from '@/platform/billing/composables/useBillingContext'
       4              : import { useBillingRouting } from '@/platform/billing/composables/useBillingRouting'
       5              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
       6              : import {
       7              :   getStopDiscountedMonthlyUsd,
       8              :   mapApiTeamCreditStops
       9              : } from '@comfyorg/account-ui/billing/catalog'
      10              : import { isCloud } from '@/platform/distribution/types'
      11              : import { useTelemetry } from '@comfyorg/telemetry'
      12              : import { reportError } from '@comfyorg/telemetry/reportError'
      13              : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
      14              : import type {
      15              :   SubscriptionCheckoutSelection,
      16              :   SubscriptionDialogOptions
      17              : } from '@/platform/billing/composables/types'
      18              : import { useBillingUI } from '@/platform/billing/composables/useBillingUI'
      19              : import {
      20              :   navigateToPlatformPlans,
      21              :   openPlatformPlans
      22              : } from '@/platform/billing/openPlatformPlans'
      23              : import { t } from '@/i18n'
      24              : import { useFreeTierQuota } from '@/platform/billing/subscription/composables/useFreeTierQuota'
      25              : import { provideSubscriptionDialog } from '@/platform/billing/subscription/composables/subscriptionDialogAccess'
      26              : import { toCurrentTier } from '@/platform/billing/subscription/utils/billingPlanTelemetry'
      27              : import { useBillingSdkStore } from '@/platform/billing/sdk/billingSdkStore'
      28              : import { useBillingOperationStore } from '@/platform/billing/stores/billingOperationStore'
      29              : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
      30              : import { getWorkspaceTelemetryContext } from '@/platform/billing/telemetry/workspaceTelemetryContext'
      31              : import { useAuthStore } from '@/stores/authStore'
      32              : import {
      33              :   clearPendingSubscriptionCheckout,
      34              :   clearPendingSubscriptionCheckoutIfTerminal,
      35              :   getPendingSubscriptionCheckout
      36              : } from '@/platform/billing/utils/pendingSubscriptionCheckout'
      37              : import type { PendingSubscriptionCheckout } from '@/platform/billing/utils/pendingSubscriptionCheckout'
      38              : 
      39         2356 : const DIALOG_KEY = 'subscription-required'
      40              : 
      41              : interface PlansLinkCopy {
      42              :   title: string
      43              :   body: string
      44              :   linkLabel: string
      45              : }
      46              : 
      47              : function paymentIntentSourceOf(
      48              :   options?: SubscriptionDialogOptions
      49              : ): PaymentIntentSource | undefined {
      50              :   return options?.paymentIntentSource ?? options?.reason
      51              : }
      52              : 
      53              : function getInitialPlanMode(
      54              :   explicitMode: SubscriptionDialogOptions['planMode'],
      55              :   isTeamPlan: boolean,
      56              :   hasCurrentPlan: boolean,
      57              :   isPersonalWorkspace: boolean
      58              : ): NonNullable<SubscriptionDialogOptions['planMode']> {
      59              :   if (explicitMode) return explicitMode
      60              :   if (isTeamPlan) return 'team'
      61              :   if (hasCurrentPlan) return 'personal'
      62              :   return isPersonalWorkspace ? 'personal' : 'team'
      63              : }
      64              : 
      65         2356 : export const useSubscriptionDialog = () => {
      66         6460 :   const { shouldUseWorkspaceBilling } = useBillingRouting()
      67         6460 :   const dialogService = useDialogService()
      68         6460 :   const dialogStore = useDialogStore()
      69         6460 :   const workspaceStore = useWorkspaceIdentity()
      70         6460 :   const { flags } = useFeatureFlags()
      71              : 
      72            0 :   function hide() {
      73            0 :     dialogStore.closeDialog({ key: DIALOG_KEY })
      74              :   }
      75              : 
      76              :   function trackModalOpened(
      77              :     reason?: PaymentIntentSource,
      78              :     refusalType?: string
      79              :   ) {
      80              :     const { tier } = useBillingContext()
      81              :     useTelemetry()?.trackSubscription('modal_opened', {
      82              :       current_tier: tier.value?.toLowerCase(),
      83              :       reason,
      84              :       ...(refusalType && { refusal_type: refusalType }),
      85              :       ...getWorkspaceTelemetryContext()
      86              :     })
      87              :   }
      88              : 
      89              :   function trackPaywallShown(paymentIntentSource?: PaymentIntentSource) {
      90              :     const { tier } = useBillingContext()
      91              :     useTelemetry()?.trackBillingEvent({
      92              :       operation: 'entry',
      93              :       stage: 'paywall_shown',
      94              :       outcome: 'pending',
      95              :       payment_intent_source: paymentIntentSource,
      96              :       current_tier: toCurrentTier(tier.value)
      97              :     })
      98              :   }
      99              : 
     100              :   function trackPaywallEntry(
     101              :     reason?: PaymentIntentSource,
     102              :     paymentIntentSource?: PaymentIntentSource,
     103              :     refusalType?: string
     104              :   ) {
     105              :     trackModalOpened(reason, refusalType)
     106              :     trackPaywallShown(paymentIntentSource)
     107              :   }
     108              : 
     109              :   async function showInactiveMemberDialog(
     110              :     paymentIntentSource?: PaymentIntentSource
     111              :   ): Promise<boolean> {
     112              :     if (!shouldUseWorkspaceBilling.value) return false
     113              : 
     114              :     const { permissions } = useBillingUI()
     115              :     if (permissions.value.canManageSubscription) return false
     116              : 
     117              :     dialogService.showLayoutDialog({
     118              :       key: DIALOG_KEY,
     119              :       component: (
     120              :         await import('@/platform/billing/components/SubscriptionInactiveMemberDialog.vue')
     121              :       ).default,
     122              :       props: { onClose: hide }
     123              :     })
     124              :     trackPaywallShown(paymentIntentSource)
     125              :     return true
     126              :   }
     127              : 
     128              :   function runRefusedCopy(): PlansLinkCopy {
     129              :     const { subscriptionState } = useBillingContext()
     130              :     const { available, maxAvailable } = useFreeTierQuota()
     131              :     const body =
     132              :       subscriptionState.value === 'ended'
     133              :         ? t('subscription.plansLink.runRefusedEnded')
     134              :         : subscriptionState.value === 'never_subscribed' &&
     135              :             maxAvailable.value > 0 &&
     136              :             available.value === 0
     137              :           ? t('subscription.plansLink.runRefusedFreeRunsUsed', {
     138              :               total: maxAvailable.value
     139              :             })
     140              :           : t('subscription.plansLink.runRefusedNoPlan')
     141              :     return {
     142              :       title: t('subscription.plansLink.runRefusedTitle'),
     143              :       body,
     144              :       linkLabel: t('subscription.plansLink.choosePlan')
     145              :     }
     146              :   }
     147              : 
     148              :   async function showPlansLinkDialog(copy: PlansLinkCopy): Promise<void> {
     149              :     dialogService.showLayoutDialog({
     150              :       key: DIALOG_KEY,
     151              :       component: (
     152              :         await import('@/platform/billing/components/PlatformPlansLinkDialog.vue')
     153              :       ).default,
     154              :       props: { ...copy, onClose: hide }
     155              :     })
     156              :   }
     157              : 
     158              :   async function handOffToPlatformPlans(
     159              :     options: SubscriptionDialogOptions | undefined,
     160              :     trackEntry: () => void
     161              :   ): Promise<void> {
     162              :     if (options?.runRefused) {
     163              :       await showPlansLinkDialog(runRefusedCopy())
     164              :       trackEntry()
     165              :       return
     166              :     }
     167              :     if (options?.sameTab) {
     168              :       trackPaywallShown(paymentIntentSourceOf(options))
     169              :       navigateToPlatformPlans()
     170              :       return
     171              :     }
     172              :     if (openPlatformPlans()) {
     173              :       trackPaywallShown(paymentIntentSourceOf(options))
     174              :       return
     175              :     }
     176              :     await showPlansLinkDialog({
     177              :       title: t('subscription.plansLink.blockedTitle'),
     178              :       body: t('subscription.plansLink.blockedBody'),
     179              :       linkLabel: t('subscription.plansLink.openPlansPage')
     180              :     })
     181              :     trackEntry()
     182              :   }
     183              : 
     184              :   function usesPlansLinkDialog(): boolean {
     185              :     return flags.billingNewUxEnabled && !flags.pricingTableFallback
     186              :   }
     187              : 
     188            0 :   async function showPricingTable(
     189              :     options?: SubscriptionDialogOptions
     190              :   ): Promise<boolean> {
     191            0 :     if (!isCloud) return false
     192              :     try {
     193              :       const {
     194              :         whenRoutingKnown,
     195              :         currentPlanSlug,
     196              :         isLegacyTeamPlan,
     197              :         isTeamPlan
     198              :       } = useBillingContext()
     199              :       if (!(await whenRoutingKnown())) return false
     200              :       const paymentIntentSource = paymentIntentSourceOf(options)
     201              :       if (await showInactiveMemberDialog(paymentIntentSource)) return true
     202              : 
     203              :       const { reason, creditsLocked, refusalType } = options ?? {}
     204              :       const dialogProps = {
     205              :         onClose: hide,
     206              :         reason,
     207              :         paymentIntentSource,
     208              :         creditsLocked
     209              :       }
     210              :       const trackEntry = () =>
     211              :         trackPaywallEntry(reason, paymentIntentSource, refusalType)
     212              : 
     213              :       if (usesPlansLinkDialog()) {
     214              :         await handOffToPlatformPlans(options, trackEntry)
     215              :         return true
     216              :       }
     217              :       if (!options?.resumingCheckout && openPlatformPlans()) {
     218              :         trackPaywallShown(paymentIntentSource)
     219              :         return true
     220              :       }
     221              : 
     222              :       const nonDismissableDialogProps = {
     223              :         dismissOnPointerDownOutside: false
     224              :       } as const
     225              : 
     226              :       if (isLegacyTeamPlan.value) {
     227              :         const personalInitialCheckout =
     228              :           options?.initialCheckout?.planMode === 'personal'
     229              :             ? options.initialCheckout
     230              :             : undefined
     231              :         dialogService.showLayoutDialog({
     232              :           key: DIALOG_KEY,
     233              :           component: (
     234              :             await import('@/platform/billing/components/SubscriptionRequiredDialogContentWorkspace.vue')
     235              :           ).default,
     236              :           props: {
     237              :             ...dialogProps,
     238              :             ...(personalInitialCheckout
     239              :               ? {
     240              :                   initialCheckout: personalInitialCheckout,
     241              :                   isPersonal: true
     242              :                 }
     243              :               : {})
     244              :           },
     245              :           dialogComponentProps: nonDismissableDialogProps
     246              :         })
     247              :         trackEntry()
     248              :         return true
     249              :       }
     250              : 
     251              :       dialogService.showLayoutDialog({
     252              :         key: DIALOG_KEY,
     253              :         component: (
     254              :           await import('@/platform/billing/components/SubscriptionRequiredDialogContentUnified.vue')
     255              :         ).default,
     256              :         props: {
     257              :           ...dialogProps,
     258              :           initialCheckout: options?.initialCheckout,
     259              :           initialPlanMode: getInitialPlanMode(
     260              :             options?.planMode,
     261              :             isTeamPlan.value,
     262              :             currentPlanSlug.value !== null,
     263              :             workspaceStore.isInPersonalWorkspace
     264              :           )
     265              :         },
     266              :         dialogComponentProps: {
     267              :           dismissOnPointerDownOutside: false
     268              :         }
     269              :       })
     270              :       trackEntry()
     271              :       return true
     272              :     } catch (error) {
     273              :       reportError(error, {
     274              :         surface: 'billing',
     275              :         errorType: 'error_opening_subscription_dialog'
     276              :       })
     277              :       return false
     278              :     }
     279              :   }
     280              : 
     281            0 :   async function restoreCheckoutSelection(
     282              :     pending: PendingSubscriptionCheckout
     283              :   ): Promise<SubscriptionCheckoutSelection | null> {
     284            0 :     const selection = pending.selection
     285            0 :     if (selection.planMode === 'personal') return selection
     286              : 
     287            0 :     const {
     288              :       fetchPlans,
     289              :       fetchStatus,
     290              :       teamCreditStops,
     291              :       currentTeamCreditStop,
     292              :       subscription,
     293              :       subscriptionStatus
     294              :     } = useBillingContext()
     295            0 :     await Promise.all([fetchPlans(), fetchStatus()])
     296            0 :     const stop = mapApiTeamCreditStops(teamCreditStops.value?.stops ?? []).find(
     297              :       ({ id }) => id === selection.teamCreditStopId
     298              :     )
     299            0 :     if (!stop?.id) return null
     300              : 
     301            0 :     return {
     302              :       planMode: 'team',
     303              :       stop: {
     304              :         id: stop.id,
     305              :         usd: stop.usd,
     306              :         credits: stop.credits,
     307              :         discountedUsd: getStopDiscountedMonthlyUsd(
     308              :           stop,
     309              :           selection.billingCycle
     310              :         ),
     311              :         periodChargeUsd: stop.periodChargeUsd
     312              :       },
     313              :       billingCycle: selection.billingCycle,
     314              :       isChange:
     315              :         currentTeamCreditStop.value !== null &&
     316              :         subscriptionStatus.value !== 'ended' &&
     317              :         (currentTeamCreditStop.value.id !== stop.id ||
     318              :           (subscription.value?.duration === 'MONTHLY'
     319              :             ? 'monthly'
     320              :             : 'yearly') !== selection.billingCycle)
     321              :     }
     322              :   }
     323              : 
     324            0 :   async function resumePendingCheckout(
     325              :     pending: PendingSubscriptionCheckout
     326              :   ): Promise<void> {
     327            0 :     if (
     328              :       pending.workspaceId !== workspaceStore.activeWorkspaceId ||
     329              :       pending.ownerUid !== useAuthStore().userId
     330              :     ) {
     331            0 :       clearPendingSubscriptionCheckout(pending.operationId)
     332            0 :       return
     333              :     }
     334              : 
     335            0 :     const operation = flags.billingSdkRailEnabled
     336              :       ? await useBillingSdkStore().recoverPendingOperation(pending.operationId)
     337              :       : await useBillingOperationStore().startOperation(
     338              :           pending.operationId,
     339              :           'subscription',
     340              :           {
     341              :             tier:
     342              :               pending.selection.planMode === 'personal'
     343              :                 ? pending.selection.tierKey
     344              :                 : 'team',
     345              :             cycle: pending.selection.billingCycle,
     346              :             attemptStartedAt: pending.attemptedAt
     347              :           }
     348              :         )
     349            0 :     if (!operation) {
     350            0 :       clearPendingSubscriptionCheckout(pending.operationId)
     351            0 :       return
     352              :     }
     353            0 :     clearPendingSubscriptionCheckoutIfTerminal(
     354              :       pending.operationId,
     355              :       operation.status
     356              :     )
     357            0 :     if (operation.status !== 'failed') return
     358              : 
     359            0 :     const initialCheckout = await restoreCheckoutSelection(pending)
     360            0 :     await showPricingTable({
     361              :       planMode: pending.selection.planMode,
     362              :       resumingCheckout: true,
     363              :       ...(initialCheckout && { initialCheckout })
     364              :     })
     365              :   }
     366              : 
     367            0 :   async function resumePendingPricingFlow(): Promise<void> {
     368            0 :     const pendingCheckout = getPendingSubscriptionCheckout()
     369            0 :     if (pendingCheckout) return resumePendingCheckout(pendingCheckout)
     370              :   }
     371              : 
     372         6460 :   return {
     373              :     show: showPricingTable,
     374              :     showPricingTable,
     375              :     hide,
     376              :     resumePendingPricingFlow
     377              :   }
     378              : }
     379              : 
     380         2356 : provideSubscriptionDialog(useSubscriptionDialog)
        

Generated by: LCOV version 2.0-1