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

            Line data    Source code
       1              : import { computed, effectScope, ref, watch } from 'vue'
       2              : 
       3              : import type {
       4              :   BillingPlansResponse,
       5              :   Plan,
       6              :   TeamCreditStops
       7              : } from '@comfyorg/billing-core'
       8              : import type { SubscriptionPaymentRecovery } from '@comfyorg/ingest-types'
       9              : import { zSubscriptionPaymentRecovery } from '@comfyorg/ingest-types/zod'
      10              : import { reportError } from '@comfyorg/telemetry/reportError'
      11              : import { billingApi } from '@/platform/billing/api/billingApi'
      12              : import { readOnRail } from '@/platform/billing/composables/readOnRail'
      13              : import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail'
      14              : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
      15              : import { useCurrentUser } from '@/composables/auth/useCurrentUser'
      16              : import { t } from '@/i18n'
      17              : 
      18         2356 : const plans = ref<Plan[]>([])
      19         2356 : const currentPlanSlug = ref<string | null>(null)
      20         2356 : const teamCreditStops = ref<TeamCreditStops | null>(null)
      21         2356 : const subscriptionPaymentRecovery = ref<SubscriptionPaymentRecovery | null>(
      22              :   null
      23              : )
      24         2356 : const isLoading = ref(false)
      25         2356 : const error = ref<string | null>(null)
      26         2356 : let fetchPromise: Promise<void> | null = null
      27         2356 : let fetchPromiseScopeKey: string | null = null
      28         2356 : let adoptedScopeKey: string | null = null
      29         2356 : let errorScopeKey: string | null = null
      30         2356 : let isScopeWatcherInitialized = false
      31         2356 : const MAX_SCOPE_REISSUES = 4
      32              : 
      33         2415 : function billingScopeKey(): string {
      34              :   const identity = useCurrentUser().resolvedUserInfo.value?.id ?? 'anonymous'
      35              :   const workspace = useWorkspaceIdentity().activeWorkspaceId ?? 'personal'
      36              :   return `${identity}:${workspace}`
      37              : }
      38              : 
      39            3 : function clearCatalog(): void {
      40            3 :   plans.value = []
      41            3 :   currentPlanSlug.value = null
      42            3 :   teamCreditStops.value = null
      43            3 :   subscriptionPaymentRecovery.value = null
      44            3 :   adoptedScopeKey = null
      45            3 :   error.value = null
      46            3 :   errorScopeKey = null
      47              : }
      48              : 
      49            0 : function isAnonymousScope(scopeKey: string): boolean {
      50            0 :   return scopeKey.startsWith('anonymous:')
      51              : }
      52              : 
      53            0 : function hasCatalogForScope(scopeKey: string): boolean {
      54            0 :   return adoptedScopeKey === scopeKey && plans.value.length > 0
      55              : }
      56              : 
      57            0 : function reportCatalogFallback(err: unknown, hasCachedPlans: boolean): void {
      58            0 :   const hasTeamCreditStops = (teamCreditStops.value?.stops.length ?? 0) > 0
      59            0 :   reportError(err, {
      60              :     surface: 'billing',
      61              :     errorType: 'cloud_billing_plan_catalog_fallback',
      62              :     tags: {
      63              :       failure_kind: 'degraded',
      64              :       feature_area: 'billing',
      65              :       has_cached_plans: hasCachedPlans,
      66              :       has_team_credit_stops: hasTeamCreditStops,
      67              :       operation: 'load',
      68              :       outcome: hasCachedPlans ? 'recovered' : 'failed'
      69              :     },
      70              :     level: 'warning'
      71              :   })
      72              : }
      73              : 
      74         4730 : function ensureScopeWatcher(): void {
      75         4730 :   if (isScopeWatcherInitialized) return
      76         2355 :   isScopeWatcherInitialized = true
      77         2355 :   effectScope(true).run(() =>
      78              :     watch(billingScopeKey, (scopeKey) => {
      79           21 :       if (adoptedScopeKey !== null && adoptedScopeKey !== scopeKey)
      80            3 :         clearCatalog()
      81           18 :       else if (errorScopeKey !== null && errorScopeKey !== scopeKey) {
      82            0 :         error.value = null
      83            0 :         errorScopeKey = null
      84              :       }
      85              :     })
      86              :   )
      87              : }
      88              : 
      89         4730 : export function useBillingPlans() {
      90         4730 :   ensureScopeWatcher()
      91           18 :   function adopt(response: BillingPlansResponse, scopeKey: string): void {
      92           18 :     if (!Array.isArray(response.plans)) {
      93            0 :       throw new TypeError('Billing plans response did not contain a plan list')
      94              :     }
      95           18 :     if (
      96              :       response.team_credit_stops != null &&
      97              :       !Array.isArray(response.team_credit_stops.stops)
      98              :     ) {
      99            0 :       throw new TypeError(
     100              :         'Billing plans response did not contain a team credit stop list'
     101              :       )
     102              :     }
     103           18 :     plans.value = response.plans
     104           18 :     currentPlanSlug.value = response.current_plan_slug ?? null
     105           18 :     teamCreditStops.value = response.team_credit_stops ?? null
     106           18 :     const recovery = zSubscriptionPaymentRecovery.safeParse(
     107              :       response.subscription_payment_recovery
     108              :     )
     109           18 :     subscriptionPaymentRecovery.value = recovery.success ? recovery.data : null
     110           18 :     adoptedScopeKey = scopeKey
     111              :   }
     112              : 
     113           19 :   function fetchPlans(reissueCount = 0): Promise<void> {
     114           19 :     const scopeKey = billingScopeKey()
     115           19 :     if (fetchPromise && fetchPromiseScopeKey === scopeKey) return fetchPromise
     116           19 :     if (adoptedScopeKey !== null && adoptedScopeKey !== scopeKey) {
     117            0 :       clearCatalog()
     118           19 :     } else if (errorScopeKey !== null && errorScopeKey !== scopeKey) {
     119            0 :       error.value = null
     120            0 :       errorScopeKey = null
     121              :     }
     122           19 :     const rail = useBillingReadRail()
     123              :     // A superseded read publishes nothing, so whatever the last read left
     124              :     // behind has to survive this one: the catalog stays, and so does the
     125              :     // error, or a failed read followed by a superseded one would leave an
     126              :     // empty catalog with nothing on screen to explain it.
     127           19 :     const priorError = error.value
     128           19 :     isLoading.value = true
     129           19 :     error.value = null
     130              : 
     131           19 :     const reissueForCurrentScope = (): Promise<void> | undefined => {
     132            0 :       const currentScope = billingScopeKey()
     133            0 :       if (errorScopeKey === currentScope) error.value = priorError
     134            0 :       if (isAnonymousScope(currentScope)) return
     135            0 :       if (currentScope === scopeKey) return
     136            0 :       if (reissueCount >= MAX_SCOPE_REISSUES) {
     137            0 :         const exhaustion = new Error(t('subscription.plansLoadFailed'), {
     138              :           cause: { reissueCount, scopeKey: currentScope }
     139              :         })
     140            0 :         error.value ??= t('subscription.plansLoadFailed')
     141            0 :         errorScopeKey = currentScope
     142            0 :         reportCatalogFallback(exhaustion, hasCatalogForScope(currentScope))
     143            0 :         return
     144              :       }
     145            0 :       if (fetchPromise === request) {
     146            0 :         fetchPromise = null
     147            0 :         fetchPromiseScopeKey = null
     148              :       }
     149            0 :       return fetchPlans(reissueCount + 1)
     150              :     }
     151              : 
     152           19 :     const request: Promise<void> = (
     153              :       rail
     154              :         ? readOnRail(rail.readPlans, 'getBillingPlans')
     155              :         : billingApi.getBillingPlans()
     156              :     )
     157              :       .then((response) => {
     158           18 :         if (fetchPromise !== request) return fetchPromise ?? undefined
     159              :         // Undefined is a read the scope moved on under; the catalog it would
     160              :         // have published belongs to an actor this host has left.
     161           18 :         if (response === undefined) return reissueForCurrentScope()
     162           18 :         else if (billingScopeKey() === scopeKey) adopt(response, scopeKey)
     163            0 :         else return reissueForCurrentScope()
     164              :       })
     165              :       .catch((err: unknown) => {
     166            0 :         if (fetchPromise !== request) return fetchPromise ?? undefined
     167            0 :         if (billingScopeKey() !== scopeKey) {
     168            0 :           return reissueForCurrentScope()
     169              :         }
     170            0 :         error.value =
     171              :           err instanceof Error ? err.message : 'Failed to fetch plans'
     172            0 :         errorScopeKey = scopeKey
     173            0 :         reportCatalogFallback(err, hasCatalogForScope(scopeKey))
     174              :       })
     175              :       .finally(() => {
     176           18 :         if (fetchPromise !== request) return
     177           18 :         isLoading.value = false
     178           18 :         fetchPromise = null
     179           18 :         fetchPromiseScopeKey = null
     180              :       })
     181              : 
     182           19 :     fetchPromise = request
     183           19 :     fetchPromiseScopeKey = scopeKey
     184           19 :     return request
     185              :   }
     186              : 
     187         4730 :   const monthlyPlans = computed(() =>
     188              :     plans.value.filter((p) => p.duration === 'MONTHLY')
     189              :   )
     190              : 
     191         4730 :   const annualPlans = computed(() =>
     192              :     plans.value.filter((p) => p.duration === 'ANNUAL')
     193              :   )
     194              : 
     195            0 :   function getPlanBySlug(slug: string) {
     196            0 :     return plans.value.find((p) => p.slug === slug)
     197              :   }
     198              : 
     199            0 :   function getPlansForTier(tier: Plan['tier']) {
     200            0 :     return plans.value.filter((p) => p.tier === tier)
     201              :   }
     202              : 
     203         4730 :   const isCurrentPlan = (slug: string) => currentPlanSlug.value === slug
     204              : 
     205         4730 :   return {
     206              :     plans,
     207              :     currentPlanSlug,
     208              :     teamCreditStops,
     209              :     subscriptionPaymentRecovery,
     210              :     isLoading,
     211              :     error,
     212              :     monthlyPlans,
     213              :     annualPlans,
     214              :     fetchPlans,
     215              :     getPlanBySlug,
     216              :     getPlansForTier,
     217              :     isCurrentPlan
     218              :   }
     219              : }
        

Generated by: LCOV version 2.0-1