Line data Source code
1 : import { reportError } from '@comfyorg/telemetry/reportError'
2 :
3 : import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore'
4 : import { useErrorHandling } from '@/composables/useErrorHandling'
5 : import { t } from '@/i18n'
6 : import { isAuthenticatedConfigLoaded } from '@/platform/remoteConfig/remoteConfig'
7 : import { computed, onScopeDispose, ref, shallowRef, toValue, watch } from 'vue'
8 : import { createSharedComposable, until } from '@vueuse/core'
9 :
10 : import {
11 : KEY_TO_TIER,
12 : getTierFeatures
13 : } from '@/platform/billing/subscription/constants/tierPricing'
14 : import type { TierKey } from '@/platform/billing/subscription/constants/tierPricing'
15 : import { useFreeTierQuota } from '@/platform/billing/subscription/composables/useFreeTierQuota'
16 : import { isCloud } from '@/platform/distribution/types'
17 : import type {
18 : PreviewSubscribeOptions,
19 : SubscribeOptions
20 : } from '@comfyorg/billing-core'
21 : import {
22 : onBillingRefresh,
23 : provideCheckoutOperationReader
24 : } from '@/platform/billing/billingRefresh'
25 : import type { BillingRefreshScope } from '@/platform/billing/billingRefresh'
26 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
27 :
28 : import type {
29 : BalanceInfo,
30 : BillingActions,
31 : BillingContext,
32 : BillingPortalOutcome,
33 : BillingStatusReadOptions,
34 : SubscriptionInfo
35 : } from './types'
36 : import { useBillingRouting } from './useBillingRouting'
37 : import type { WorkspaceBilling } from '@/platform/billing/composables/useWorkspaceBilling'
38 : import { useWorkspaceBilling } from '@/platform/billing/composables/useWorkspaceBilling'
39 :
40 : // Legacy per-member team plans use a hyphenated `team-{tier}-{cycle}` slug; the
41 : // new credit-slider plan uses an underscore `team_per_credit_{cycle}` slug and
42 : // carries a team_credit_stop. The hyphen prefix alone separates the two, so a
43 : // new sub is never misrouted even before its credit stop is populated.
44 2356 : const LEGACY_TEAM_PLAN_SLUG_PREFIX = 'team-'
45 2356 : const PER_CREDIT_TEAM_PLAN_SLUG_PREFIX = 'team_per_credit_'
46 :
47 2356 : const ROUTING_WAIT_TIMEOUT_MS = 10_000
48 :
49 2356 : class BillingRoutingUnavailableError extends Error {}
50 :
51 2356 : class BillingWorkspaceChangedError extends Error {}
52 :
53 9 : function isTeamPlanSlug(planSlug: string | null | undefined): boolean {
54 9 : const normalizedSlug = planSlug?.toLowerCase()
55 9 : return (
56 : normalizedSlug?.startsWith(LEGACY_TEAM_PLAN_SLUG_PREFIX) === true ||
57 : normalizedSlug?.startsWith(PER_CREDIT_TEAM_PLAN_SLUG_PREFIX) === true
58 : )
59 : }
60 :
61 : /**
62 : * Unified billing context over workspace billing.
63 : *
64 : * - Workspace not loaded yet (`unknown`): reads are empty and no billing call
65 : * is made until routing is known
66 : *
67 : * The context automatically initializes when the workspace changes and provides
68 : * a unified interface for subscription status, balance, and billing actions.
69 : *
70 : * @example
71 : * ```typescript
72 : * import { formatCreditsFromCents } from '@/base/credits/comfyCredits'
73 : *
74 : * const {
75 : * type,
76 : * subscription,
77 : * balance,
78 : * isInitialized,
79 : * initialize,
80 : * subscribe
81 : * } = useBillingContext()
82 : *
83 : * // Wait for initialization
84 : * await initialize()
85 : *
86 : * // Check subscription status
87 : * if (subscription.value?.isActive) {
88 : * console.log(`Tier: ${subscription.value.tier}`)
89 : * }
90 : *
91 : * // Check balance (the *Micros fields are cents - see BalanceInfo)
92 : * if (balance.value) {
93 : * const credits = formatCreditsFromCents({ cents: balance.value.amountMicros })
94 : * console.log(`Balance: ${credits} credits`)
95 : * }
96 : * ```
97 : */
98 2355 : function useBillingContextInternal(): BillingContext {
99 2355 : const store = useWorkspaceIdentity()
100 2355 : const { type } = useBillingRouting()
101 :
102 2355 : const workspaceBillingRef = shallowRef<WorkspaceBilling | null>(null)
103 :
104 2355 : const getWorkspaceBilling = () => {
105 7105 : if (!workspaceBillingRef.value) {
106 4730 : workspaceBillingRef.value = useWorkspaceBilling()
107 : }
108 7105 : return workspaceBillingRef.value
109 : }
110 :
111 2355 : let freshStatusReadOwed = false
112 2355 : const isInitialized = ref(false)
113 2355 : const isLoading = ref(false)
114 2355 : const error = ref<string | null>(null)
115 :
116 2355 : const activeContext = computed(() => getWorkspaceBilling())
117 :
118 : // Proxy state from active context
119 2355 : const subscription = computed<SubscriptionInfo | null>(() =>
120 : toValue(activeContext.value.subscription)
121 : )
122 :
123 2355 : const balance = computed<BalanceInfo | null>(() =>
124 : toValue(activeContext.value.balance)
125 : )
126 :
127 2355 : const plans = computed(() => toValue(activeContext.value.plans))
128 :
129 2355 : const currentPlanSlug = computed(() =>
130 : toValue(activeContext.value.currentPlanSlug)
131 : )
132 :
133 2355 : const teamCreditStops = computed(() =>
134 : toValue(activeContext.value.teamCreditStops)
135 : )
136 :
137 2355 : const subscriptionPaymentRecovery = computed(() =>
138 : toValue(activeContext.value.subscriptionPaymentRecovery)
139 : )
140 :
141 2355 : const currentTeamCreditStop = computed(() =>
142 : toValue(activeContext.value.currentTeamCreditStop)
143 : )
144 :
145 2355 : const maxSeats = computed(() => toValue(activeContext.value.maxSeats))
146 2355 : const occupiedSeats = computed(() =>
147 : toValue(activeContext.value.occupiedSeats)
148 : )
149 :
150 2355 : const canAccessSubscriptionFeatures = computed(() =>
151 : type.value === 'unknown'
152 : ? !isCloud
153 : : toValue(activeContext.value.canAccessSubscriptionFeatures)
154 : )
155 :
156 2355 : const isFreeTier = computed(() => subscription.value?.tier === 'FREE')
157 :
158 2355 : const freeTierQuota = useFreeTierQuota()
159 :
160 2355 : const canRunWorkflows = computed(
161 : () =>
162 : canAccessSubscriptionFeatures.value &&
163 : (!isFreeTier.value ||
164 : !isCloud ||
165 : !isAuthenticatedConfigLoaded.value ||
166 : freeTierQuota.freeTierExecutionPermitted.value)
167 : )
168 :
169 2355 : const showsSubscribeToRunPrompt = computed(
170 : () => isInitialized.value && !canRunWorkflows.value
171 : )
172 :
173 2355 : const isLegacyTeamPlan = computed(
174 : () =>
175 : type.value === 'workspace' &&
176 : canAccessSubscriptionFeatures.value &&
177 : !isFreeTier.value &&
178 : currentTeamCreditStop.value === null &&
179 : (currentPlanSlug.value
180 : ?.toLowerCase()
181 : .startsWith(LEGACY_TEAM_PLAN_SLUG_PREFIX) ??
182 : false)
183 : )
184 :
185 : // Plan identity, independent of subscription health: the per-credit Team plan
186 : // carries a credit stop, the retired seat-based ones a `team-` slug. Kept off
187 : // canAccessSubscriptionFeatures on purpose — paused and payment_failed
188 : // both force is_active=false, which is exactly when callers still need
189 : // to know this is a team plan.
190 2355 : const isTeamPlan = computed(
191 : () =>
192 : type.value === 'workspace' &&
193 : (currentTeamCreditStop.value !== null ||
194 : isTeamPlanSlug(currentPlanSlug.value))
195 : )
196 :
197 2355 : const billingStatus = computed(() =>
198 : toValue(activeContext.value.billingStatus)
199 : )
200 2355 : const subscriptionStatus = computed(() =>
201 : toValue(activeContext.value.subscriptionStatus)
202 : )
203 2355 : const subscriptionState = computed(() =>
204 : toValue(activeContext.value.subscriptionState)
205 : )
206 2355 : const tier = computed(() => toValue(activeContext.value.tier))
207 2355 : const renewalDate = computed(() => toValue(activeContext.value.renewalDate))
208 2355 : const renewalInvoice = computed(() =>
209 : toValue(activeContext.value.renewalInvoice)
210 : )
211 2355 : const periodCreditGrant = computed(() =>
212 : toValue(activeContext.value.periodCreditGrant)
213 : )
214 2355 : const nextCreditRefillAt = computed(() =>
215 : toValue(activeContext.value.nextCreditRefillAt)
216 : )
217 :
218 0 : function getMaxSeats(tierKey: TierKey): number {
219 0 : if (type.value !== 'workspace') return 1
220 :
221 0 : const apiTier = KEY_TO_TIER[tierKey]
222 : const plan = plans.value.find(
223 : (p) => p.tier === apiTier && p.duration === 'MONTHLY'
224 : )
225 0 : return plan?.max_seats ?? getTierFeatures(tierKey).maxMembers
226 : }
227 :
228 : // Sync subscription info to workspace store for display in workspace switcher.
229 : // Subscribed means active AND not cancelled, so the delete button enables
230 : // after cancellation, even before the period ends. A null subscription means
231 : // "not loaded yet" (adapters are discarded on every workspace/type switch);
232 : // skip it so the transient reinit gap can't clobber the list-derived baseline
233 : // (personal workspaces and subscribed teams already read subscribed there).
234 2355 : watch(
235 : subscription,
236 : (sub) => {
237 2377 : if (!sub) return
238 :
239 1790 : if (!store.activeWorkspaceId) return
240 2377 : useWorkspaceBillingStateStore().updateSummary(store.activeWorkspaceId, {
241 : isSubscribed: sub.isActive && !sub.isCancelled,
242 : subscriptionPlan: sub.planSlug
243 : })
244 : },
245 : { immediate: true }
246 : )
247 :
248 : // Discarding the adapter instances forces a fresh fetch and lets an in-flight
249 : // init detect that it was superseded (its captured adapter is no longer the
250 : // active one), so a stale response can't resolve into a ready state for the
251 : // wrong workspace.
252 2375 : function resetBillingState() {
253 2375 : workspaceBillingRef.value = null
254 2375 : isInitialized.value = false
255 2375 : isLoading.value = false
256 2375 : error.value = null
257 : }
258 :
259 : // Reset and reinitialize when the active workspace or billing backend changes.
260 2355 : watch(
261 : [() => store.activeWorkspace?.id, () => type.value],
262 : async ([newWorkspaceId]) => {
263 2375 : resetBillingState()
264 2375 : if (!newWorkspaceId) return
265 :
266 1788 : try {
267 19 : await initialize()
268 : } catch (err) {
269 0 : console.error('Failed to initialize billing context:', err)
270 : }
271 18 : await runOwedFreshStatusRead()
272 : },
273 : { immediate: true }
274 : )
275 :
276 18 : async function runOwedFreshStatusRead(): Promise<void> {
277 18 : if (!freshStatusReadOwed || type.value === 'unknown') return
278 0 : freshStatusReadOwed = false
279 0 : try {
280 0 : await activeContext.value.fetchStatus({ fresh: true })
281 : } catch (err) {
282 0 : reportError(err, {
283 : surface: 'agent',
284 : errorType: 'error_refreshing_agent_billing_status'
285 : })
286 : }
287 : }
288 :
289 : // Rejects on timeout. Resolves false when the user switched workspace during
290 : // the wait, so the caller stops silently.
291 20 : async function waitForRouting(): Promise<boolean> {
292 20 : if (type.value !== 'unknown') return true
293 20 : const workspaceId = store.activeWorkspace?.id
294 20 : try {
295 20 : await until(type).not.toBe('unknown', {
296 : timeout: ROUTING_WAIT_TIMEOUT_MS,
297 : throwOnTimeout: true
298 : })
299 : } catch {
300 1 : throw new BillingRoutingUnavailableError(
301 : t('auth.webSession.token.unavailable')
302 : )
303 : }
304 20 : const currentId = store.activeWorkspace?.id
305 20 : return !workspaceId || currentId === workspaceId
306 : }
307 :
308 : // For actions whose caller shows the outcome: a workspace switch during the
309 : // wait is a failure the caller reports, not a silent drop.
310 1 : async function waitForRoutingInSameWorkspace(): Promise<void> {
311 1 : if (await waitForRouting()) return
312 0 : throw new BillingWorkspaceChangedError(
313 : t('subscription.cancelDialog.workspaceChanged')
314 : )
315 : }
316 :
317 19 : async function whenRoutingKnown(): Promise<boolean> {
318 19 : try {
319 19 : return await waitForRouting()
320 : } catch (err) {
321 0 : useErrorHandling().toastErrorHandler(err)
322 0 : return false
323 : }
324 : }
325 :
326 2355 : let inFlightInit: {
327 : adapter: WorkspaceBilling
328 : promise: Promise<void>
329 : } | null = null
330 :
331 19 : async function initialize(): Promise<void> {
332 19 : if (isInitialized.value) return
333 19 : if (!(await whenRoutingKnown())) return
334 :
335 19 : const adapter = activeContext.value
336 19 : if (inFlightInit?.adapter === adapter) return inFlightInit.promise
337 :
338 19 : const promise = initializeAdapter(adapter)
339 19 : const entry = { adapter, promise }
340 19 : inFlightInit = entry
341 19 : try {
342 19 : await promise
343 : } finally {
344 18 : if (inFlightInit === entry) inFlightInit = null
345 : }
346 : }
347 :
348 19 : async function initializeAdapter(adapter: WorkspaceBilling): Promise<void> {
349 19 : isLoading.value = true
350 19 : error.value = null
351 19 : try {
352 19 : await adapter.initialize()
353 19 : if (activeContext.value !== adapter) return
354 18 : isInitialized.value = true
355 : } catch (err) {
356 0 : if (activeContext.value !== adapter) return
357 0 : error.value =
358 : err instanceof Error ? err.message : 'Failed to initialize billing'
359 0 : throw err
360 : } finally {
361 18 : if (activeContext.value === adapter) isLoading.value = false
362 : }
363 : }
364 :
365 0 : function deferFreshReadUntilRoutingKnown(
366 : options?: BillingStatusReadOptions
367 : ): void {
368 0 : freshStatusReadOwed ||= options?.fresh === true
369 : }
370 :
371 0 : async function fetchStatus(
372 : options?: BillingStatusReadOptions
373 : ): Promise<void> {
374 0 : if (type.value === 'unknown') {
375 0 : deferFreshReadUntilRoutingKnown(options)
376 0 : return
377 : }
378 0 : return activeContext.value.fetchStatus(options)
379 : }
380 :
381 7 : async function fetchBalance(): Promise<void> {
382 7 : if (type.value === 'unknown') return
383 7 : return activeContext.value.fetchBalance()
384 : }
385 :
386 : // Reconcile and the checkout-operation read run once after a Stripe redirect
387 : // and are never retried, so they wait instead of skipping.
388 0 : async function reconcileSubscriptionSuccess(): Promise<void> {
389 0 : if (!(await whenRoutingKnown())) return
390 0 : const account = activeContext.value
391 0 : await account.fetchStatus()
392 0 : await account.fetchBalance()
393 : }
394 :
395 : /**
396 : * Reads the billing status, which resumes any operation the server
397 : * reports pending. True once that operation was adopted, so a caller
398 : * watching for a payment taken elsewhere can hand off to its own polling.
399 : */
400 0 : async function readCheckoutOperation(): Promise<boolean> {
401 0 : if (!(await whenRoutingKnown())) return false
402 0 : return activeContext.value.readAndAdoptPendingOperation()
403 : }
404 :
405 0 : function refreshFor(scope: BillingRefreshScope): Promise<unknown> {
406 0 : if (scope === 'subscription') return reconcileSubscriptionSuccess()
407 0 : return Promise.allSettled([fetchStatus(), fetchBalance()])
408 : }
409 :
410 2355 : onScopeDispose(onBillingRefresh(refreshFor))
411 2355 : onScopeDispose(provideCheckoutOperationReader(readCheckoutOperation))
412 :
413 0 : async function subscribe(planSlug: string, options?: SubscribeOptions) {
414 0 : if (!(await whenRoutingKnown())) return
415 0 : return activeContext.value.subscribe(planSlug, options)
416 : }
417 :
418 0 : async function previewSubscribe(
419 : planSlug: string,
420 : options?: PreviewSubscribeOptions
421 : ) {
422 0 : if (!(await whenRoutingKnown())) return null
423 0 : return activeContext.value.previewSubscribe(planSlug, options)
424 : }
425 :
426 0 : async function manageSubscription(): Promise<BillingPortalOutcome> {
427 0 : if (!(await whenRoutingKnown())) {
428 0 : return { ok: false, reason: 'routing_unavailable' }
429 : }
430 0 : return activeContext.value.manageSubscription()
431 : }
432 :
433 1 : async function cancelSubscription(isScopeCurrent?: () => boolean) {
434 1 : await waitForRoutingInSameWorkspace()
435 0 : await activeContext.value.cancelSubscription(isScopeCurrent)
436 : }
437 :
438 0 : async function resubscribe(
439 : options?: Parameters<BillingActions['resubscribe']>[0]
440 : ) {
441 0 : await waitForRoutingInSameWorkspace()
442 0 : return activeContext.value.resubscribe(options)
443 : }
444 :
445 0 : async function topup(amountCents: number) {
446 0 : if (
447 : !Number.isInteger(amountCents) ||
448 : amountCents <= 0 ||
449 : amountCents % 100 !== 0
450 : ) {
451 0 : throw new Error(
452 : 'Top-up amount must be a positive whole-dollar cent value'
453 : )
454 : }
455 0 : if (!(await whenRoutingKnown())) return
456 0 : return activeContext.value.topup(amountCents)
457 : }
458 :
459 0 : async function fetchPlans() {
460 0 : if (type.value === 'unknown') return
461 0 : return activeContext.value.fetchPlans()
462 : }
463 :
464 2355 : return {
465 : type,
466 : isInitialized,
467 : subscription,
468 : balance,
469 : plans,
470 : currentPlanSlug,
471 : teamCreditStops,
472 : subscriptionPaymentRecovery,
473 : currentTeamCreditStop,
474 : maxSeats,
475 : occupiedSeats,
476 : isLoading,
477 : error,
478 : showsSubscribeToRunPrompt,
479 : canAccessSubscriptionFeatures,
480 : canRunWorkflows,
481 : isFreeTier,
482 : isLegacyTeamPlan,
483 : isTeamPlan,
484 : billingStatus,
485 : subscriptionStatus,
486 : subscriptionState,
487 : tier,
488 : renewalDate,
489 : renewalInvoice,
490 : periodCreditGrant,
491 : nextCreditRefillAt,
492 : getMaxSeats,
493 :
494 : initialize,
495 : fetchStatus,
496 : fetchBalance,
497 : reconcileSubscriptionSuccess,
498 : subscribe,
499 : previewSubscribe,
500 : manageSubscription,
501 : cancelSubscription,
502 : resubscribe,
503 : topup,
504 : fetchPlans,
505 : whenRoutingKnown
506 : }
507 : }
508 :
509 2356 : export const useBillingContext = createSharedComposable(
510 : useBillingContextInternal
511 : )
|