Line data Source code
1 : import {
2 : computed,
3 : getCurrentScope,
4 : onScopeDispose,
5 : ref,
6 : shallowRef,
7 : watch
8 : } from 'vue'
9 :
10 : import type {
11 : BillingClient,
12 : BillingTelemetryFailure,
13 : PreviewSubscribeInput
14 : } from '@comfyorg/account-core/billing'
15 :
16 : import { useToast } from '@/components/ui/toast/toastStore'
17 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
18 : import { t } from '@/i18n'
19 : import { useBillingPlans } from '@/platform/billing/subscription/composables/useBillingPlans'
20 : import { useTelemetry } from '@comfyorg/telemetry'
21 : import { reportError } from '@comfyorg/telemetry/reportError'
22 : import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory'
23 : import { createBillingPortalReporter } from '@/platform/telemetry/utils/billingPortalTelemetry'
24 : import type {
25 : BillingBalanceResponse,
26 : BillingStatusResponse,
27 : CreateTopupResponse,
28 : PreviewSubscribeOptions,
29 : PreviewSubscribeResponse,
30 : SubscribeOptions
31 : } from '@comfyorg/billing-core'
32 : import { billingApi } from '@/platform/billing/api/billingApi'
33 : import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError'
34 : import { reserveBillingTab } from '@/platform/billing/billingTab'
35 : import { openHostedBillingTabOutcome } from '@/platform/billing/openHostedBillingTab'
36 : import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn'
37 : import { useBillingSdkStore } from '@/platform/billing/sdk/billingSdkStore'
38 : import type {
39 : SettledSubscribeResponse,
40 : SubscriptionRailOutcome
41 : } from '@/platform/billing/sdk/subscriptionOperationView'
42 : import { SettledOperationError } from '@/platform/billing/sdk/subscriptionOperationView'
43 : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
44 : import { readOnRail } from '@/platform/billing/composables/readOnRail'
45 : import type { BillingReadRail } from '@/platform/billing/composables/useBillingReadRail'
46 : import { useBillingReadRail } from '@/platform/billing/composables/useBillingReadRail'
47 : import { useSubscriptionRail } from '@/platform/billing/composables/useSubscriptionRail'
48 : import { useBillingOperationStore } from '@/platform/billing/stores/billingOperationStore'
49 : import { subscribeInputFrom } from '@/platform/billing/subscribeInput'
50 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
51 :
52 : import type {
53 : BalanceInfo,
54 : BillingActions,
55 : BillingPortalOutcome,
56 : BillingState,
57 : SubscriptionInfo
58 : } from '@/platform/billing/composables/types'
59 :
60 2356 : export class CancellationScopeChangedError extends Error {
61 : constructor(message: string) {
62 0 : super(message)
63 0 : this.name = 'CancellationScopeChangedError'
64 : }
65 : }
66 :
67 0 : function assertCancellationScopeCurrent(isScopeCurrent: () => boolean): void {
68 0 : if (isScopeCurrent()) return
69 0 : throw new CancellationScopeChangedError(
70 : t('subscription.cancelDialog.workspaceChanged')
71 : )
72 : }
73 :
74 : /**
75 : * Which client path resumes a recovered operation. Exhaustive on purpose: the
76 : * two-way check this replaces sent anything that was not `topup` down the
77 : * subscription path, which covers the customer's real plan with a "setting up
78 : * your subscription" spinner until the operation settles.
79 : */
80 0 : function resumeModeFor(
81 : type: BillingStatusResponse['pending_billing_op_type']
82 : ): 'subscription' | 'topup' {
83 0 : switch (type) {
84 : case 'topup':
85 0 : return 'topup'
86 : case 'subscription':
87 0 : return 'subscription'
88 : // A server predating the field only ever had subscriptions to hand back.
89 : case undefined:
90 0 : return 'subscription'
91 : default: {
92 : const unexpected: never = type
93 : // JSON.stringify, not String: the latter throws on a value with no
94 : // callable toString/valueOf, and throwing out of the branch that exists
95 : // to absorb a bad value would abort recovery entirely. The value came
96 : // from a parsed response, so it cannot be circular.
97 0 : reportError(
98 : new Error(
99 : `Unknown pending billing op type: ${JSON.stringify(unexpected)}`
100 : ),
101 : {
102 : surface: 'workspace',
103 : errorType: 'billing_unknown_resume_mode'
104 : }
105 : )
106 : // Reachable only against a newer server. Dropping recovery strands a
107 : // customer who cannot reach the payment page; a wrong panel clears on
108 : // reload, so recovery wins.
109 0 : return 'subscription'
110 : }
111 : }
112 : }
113 :
114 : /**
115 : * Whether a rejection means the subscription already holds the state the caller
116 : * asked for. The request did nothing, but the user's intent is satisfied, so
117 : * surfacing it as a failure would report a problem that does not exist — most
118 : * visibly when a request succeeds and its response is lost, and the retry is
119 : * then refused.
120 : *
121 : * The 4xx check keeps a server fault that happens to echo one of these codes
122 : * from being swallowed as success.
123 : */
124 0 : function isAlreadyInRequestedState(err: unknown, code: string): boolean {
125 0 : return (
126 : err instanceof WorkspaceApiError &&
127 : err.code === code &&
128 : err.status !== undefined &&
129 : err.status >= 400 &&
130 : err.status < 500
131 : )
132 : }
133 :
134 : /**
135 : * Refreshes local state after a no-op, without letting the refresh overturn the
136 : * outcome. The desired state already holds on the server, so a failed read must
137 : * not turn it back into a reported failure — which is exactly what would happen
138 : * on the flaky network that caused the no-op in the first place.
139 : */
140 0 : async function resyncQuietly(refresh: () => Promise<unknown>): Promise<void> {
141 0 : try {
142 0 : await refresh()
143 : } catch {
144 : // Intentionally ignored: the next read corrects the view.
145 : }
146 : }
147 :
148 : /** The SDK rail refusing an action, distinct from any value it could return. */
149 2356 : const DECLINED = Symbol('subscription rail declined')
150 :
151 0 : function previewSubscribeInputFrom(
152 : planSlug: string,
153 : options: PreviewSubscribeOptions = {}
154 : ): PreviewSubscribeInput {
155 0 : return {
156 : planSlug,
157 : ...(options.promotionCode === undefined
158 : ? {}
159 : : { promotionCode: options.promotionCode }),
160 : ...(options.teamCreditStopId === undefined
161 : ? {}
162 : : { teamCreditStopId: options.teamCreditStopId })
163 : }
164 : }
165 :
166 : interface SeatCapacity {
167 : maxSeats: number
168 : occupiedSeats: number
169 : }
170 :
171 19 : function seatCapacityFrom(status: BillingStatusResponse): SeatCapacity | null {
172 19 : if (
173 : typeof status.max_seats === 'number' &&
174 : Number.isInteger(status.max_seats) &&
175 : status.max_seats >= 0 &&
176 : typeof status.occupied_seats === 'number' &&
177 : Number.isInteger(status.occupied_seats) &&
178 : status.occupied_seats >= 0
179 : ) {
180 19 : return {
181 : maxSeats: status.max_seats,
182 : occupiedSeats: status.occupied_seats
183 : }
184 : }
185 0 : return null
186 : }
187 :
188 : /**
189 : * Adapter for workspace-scoped billing via /billing/* endpoints.
190 : * Used for team workspaces.
191 : * @internal - Use useBillingContext() instead of importing directly.
192 : */
193 : export type WorkspaceBilling = BillingState &
194 : BillingActions & {
195 : /**
196 : * Reads status and resolves true once the operation it reports pending
197 : * has been adopted, so its own polling shows progress and outcome.
198 : */
199 : readAndAdoptPendingOperation: () => Promise<boolean>
200 : }
201 :
202 4730 : export function useWorkspaceBilling(): WorkspaceBilling {
203 4730 : const billingPlans = useBillingPlans()
204 4730 : const billingOperationStore = useBillingOperationStore()
205 4730 : const workspaceStore = useWorkspaceIdentity()
206 4730 : const telemetry = useTelemetry()
207 4730 : const { flags } = useFeatureFlags()
208 :
209 4730 : const isInitialized = ref(false)
210 4730 : const isLoading = ref(false)
211 4730 : const error = ref<string | null>(null)
212 :
213 4730 : const statusData = shallowRef<BillingStatusResponse | null>(null)
214 4730 : const statusReadAuthoritative = ref(true)
215 4730 : let adoption: Promise<boolean> = Promise.resolve(false)
216 4730 : const seatCapacity = shallowRef<SeatCapacity | null>(null)
217 4730 : const balanceData = shallowRef<BillingBalanceResponse | null>(null)
218 : // Prevent older status and balance responses from overwriting newer state.
219 4730 : const latestBillingReadIds = { status: 0, balance: 0 }
220 :
221 4730 : const canAccessSubscriptionFeatures = computed(
222 : () => statusData.value?.is_active ?? false
223 : )
224 4730 : const isFreeTier = computed(
225 : () => statusData.value?.subscription_tier === 'FREE'
226 : )
227 :
228 4730 : const subscription = computed<SubscriptionInfo | null>(() => {
229 4749 : const status = statusData.value
230 4749 : if (!status) return null
231 :
232 4749 : return {
233 : isActive: status.is_active,
234 : tier: status.subscription_tier ?? null,
235 : duration: status.subscription_duration ?? null,
236 : planSlug: status.plan_slug ?? null,
237 : scheduledChange: status.scheduled_change ?? null,
238 : renewalDate: status.renewal_date ?? null,
239 : endDate: status.cancel_at ?? null,
240 : endedAt: status.ended_at,
241 : isCancelled: status.subscription_status === 'canceled',
242 : hasFunds: status.has_funds,
243 : agentHasFunds:
244 : status.scoped_effective_has_funds?.agent ?? status.has_funds,
245 : agentScopedHasFunds: status.scoped_has_funds?.agent,
246 : agentScopedHasFundsAuthoritative:
247 : statusReadAuthoritative.value && status.billing_rail !== undefined
248 : }
249 : })
250 :
251 4730 : const balance = computed<BalanceInfo | null>(() => {
252 21 : const data = balanceData.value
253 21 : if (!data) return null
254 :
255 21 : return {
256 : amountMicros: data.amount_micros,
257 : currency: data.currency,
258 : effectiveBalanceMicros:
259 : data.effective_balance_micros ?? data.amount_micros,
260 : effectiveBalanceAuthoritative: data.effective_balance_authoritative,
261 : prepaidBalanceMicros: data.prepaid_balance_micros ?? 0,
262 : cloudCreditBalanceMicros: data.cloud_credit_balance_micros ?? 0,
263 : cloudCreditDisplayBalanceCents: data.cloud_credit_display_balance_cents,
264 : suggestedTopupAmountCents: data.suggested_topup_amount_cents,
265 : minTopupCents: data.min_topup_cents,
266 : minTopupCredits: data.min_topup_credits,
267 : maxTopupCents: data.max_topup_cents,
268 : maxTopupCredits: data.max_topup_credits,
269 : lowBalance: data.low_balance
270 : }
271 : })
272 :
273 4730 : const billingStatus = computed(() => statusData.value?.billing_status ?? null)
274 4730 : const subscriptionStatus = computed(
275 : () => statusData.value?.subscription_status ?? null
276 : )
277 4730 : const subscriptionState = computed(
278 : () => statusData.value?.subscription_state ?? null
279 : )
280 4730 : const tier = computed(() => statusData.value?.subscription_tier ?? null)
281 4730 : const renewalDate = computed(() => statusData.value?.renewal_date ?? null)
282 4730 : const renewalInvoice = computed(
283 : () => statusData.value?.renewal_invoice ?? null
284 : )
285 4730 : const periodCreditGrant = computed(
286 : () => statusData.value?.period_credit_grant ?? null
287 : )
288 4730 : const nextCreditRefillAt = computed(
289 : () => statusData.value?.next_credit_refill_at ?? null
290 : )
291 :
292 4730 : const plans = computed(() => billingPlans.plans.value)
293 4730 : const currentPlanSlug = computed(
294 : () => statusData.value?.plan_slug ?? billingPlans.currentPlanSlug.value
295 : )
296 4730 : const teamCreditStops = computed(() => billingPlans.teamCreditStops.value)
297 4730 : const subscriptionPaymentRecovery = computed(
298 : () => billingPlans.subscriptionPaymentRecovery.value
299 : )
300 4730 : const currentTeamCreditStop = computed(
301 : () => statusData.value?.team_credit_stop ?? null
302 : )
303 4730 : const maxSeats = computed(() => seatCapacity.value?.maxSeats ?? null)
304 4730 : const occupiedSeats = computed(
305 : () => seatCapacity.value?.occupiedSeats ?? null
306 : )
307 :
308 4730 : watch(
309 : () => workspaceStore.activeWorkspace?.id,
310 : () => {
311 43 : seatCapacity.value = null
312 : }
313 : )
314 :
315 19 : async function initialize(): Promise<void> {
316 19 : if (isInitialized.value) return
317 :
318 19 : isLoading.value = true
319 19 : error.value = null
320 19 : try {
321 19 : await Promise.all([fetchStatus(), fetchBalance(), fetchPlans()])
322 : // Re-fetch balance if free tier credits were just lazily granted
323 19 : if (isFreeTier.value && balance.value?.amountMicros === 0) {
324 0 : await fetchBalance()
325 : }
326 18 : isInitialized.value = true
327 : } catch (err) {
328 0 : error.value =
329 : err instanceof Error ? err.message : 'Failed to initialize billing'
330 0 : throw err
331 : } finally {
332 18 : isLoading.value = false
333 : }
334 : }
335 :
336 19 : async function resumePendingOperation(
337 : status: BillingStatusResponse
338 : ): Promise<boolean> {
339 19 : if (!status.pending_billing_op_id) return false
340 0 : if (billingOperationStore.getOperation(status.pending_billing_op_id)) {
341 0 : return true
342 : }
343 0 : if (flags.billingSdkRailEnabled) {
344 0 : return useBillingSdkStore()
345 : .recover()
346 : .catch(() => false)
347 : }
348 0 : void billingOperationStore.startOperation(
349 : status.pending_billing_op_id,
350 : resumeModeFor(status.pending_billing_op_type),
351 : { resumed: true },
352 : status.action_url
353 : )
354 0 : return true
355 : }
356 :
357 45 : function isStaleBillingRead(
358 : billingResource: keyof typeof latestBillingReadIds,
359 : requestId: number,
360 : workspaceId: string | undefined
361 : ): boolean {
362 45 : return (
363 : requestId !== latestBillingReadIds[billingResource] ||
364 : workspaceId !== workspaceStore.activeWorkspace?.id
365 : )
366 : }
367 :
368 0 : async function readAndAdoptPendingOperation(): Promise<boolean> {
369 0 : await fetchStatus()
370 0 : return adoption
371 : }
372 :
373 19 : async function fetchStatus(): Promise<void> {
374 19 : adoption = Promise.resolve(false)
375 19 : const requestId = ++latestBillingReadIds.status
376 19 : const workspaceId = workspaceStore.activeWorkspace?.id
377 19 : const rail: BillingReadRail | null = useBillingReadRail()
378 19 : isLoading.value = true
379 19 : error.value = null
380 19 : try {
381 19 : const status = rail
382 : ? await readOnRail(rail.readStatus, 'getBillingStatus')
383 : : await billingApi.getBillingStatus()
384 19 : if (
385 : status === undefined ||
386 : isStaleBillingRead('status', requestId, workspaceId)
387 : )
388 0 : return
389 :
390 19 : seatCapacity.value = seatCapacityFrom(status)
391 19 : statusData.value = status
392 19 : statusReadAuthoritative.value = true
393 19 : adoption = resumePendingOperation(status)
394 : } catch (err) {
395 0 : if (requestId === latestBillingReadIds.status) {
396 0 : statusReadAuthoritative.value = false
397 0 : error.value =
398 : err instanceof Error ? err.message : 'Failed to fetch billing status'
399 : }
400 0 : throw err
401 : } finally {
402 19 : if (requestId === latestBillingReadIds.status) isLoading.value = false
403 : }
404 : }
405 :
406 26 : async function fetchBalance(): Promise<void> {
407 26 : const requestId = ++latestBillingReadIds.balance
408 26 : const workspaceId = workspaceStore.activeWorkspace?.id
409 26 : const rail: BillingReadRail | null = useBillingReadRail()
410 26 : isLoading.value = true
411 26 : error.value = null
412 26 : try {
413 26 : const balance = rail
414 : ? await readOnRail(rail.readBalance, 'getBillingBalance')
415 : : await billingApi.getBillingBalance()
416 26 : if (
417 : balance !== undefined &&
418 : !isStaleBillingRead('balance', requestId, workspaceId)
419 : ) {
420 26 : balanceData.value = balance
421 : }
422 : } catch (err) {
423 0 : if (isStaleBillingRead('balance', requestId, workspaceId)) return
424 0 : error.value =
425 : err instanceof Error ? err.message : 'Failed to fetch balance'
426 0 : throw err
427 : } finally {
428 26 : if (requestId === latestBillingReadIds.balance) isLoading.value = false
429 : }
430 : }
431 :
432 0 : async function retryBillingRead(
433 : fetchBillingResource: () => Promise<void>,
434 : billingResource: keyof typeof latestBillingReadIds
435 : ): Promise<{ failed: boolean; requestId: number }> {
436 0 : const firstAttempt = fetchBillingResource()
437 0 : const firstRequestId = latestBillingReadIds[billingResource]
438 0 : try {
439 0 : await firstAttempt
440 0 : return { failed: false, requestId: firstRequestId }
441 : } catch {
442 0 : if (firstRequestId !== latestBillingReadIds[billingResource]) {
443 0 : return { failed: false, requestId: firstRequestId }
444 : }
445 : }
446 :
447 0 : const retry = fetchBillingResource()
448 0 : const retryRequestId = latestBillingReadIds[billingResource]
449 0 : try {
450 0 : await retry
451 0 : return { failed: false, requestId: retryRequestId }
452 : } catch {
453 0 : return {
454 : failed: retryRequestId === latestBillingReadIds[billingResource],
455 : requestId: retryRequestId
456 : }
457 : }
458 : }
459 :
460 0 : async function reconcileBillingStateAfterSubscribe(): Promise<void> {
461 0 : const [statusResult, balanceResult] = await Promise.all([
462 : retryBillingRead(fetchStatus, 'status'),
463 : retryBillingRead(fetchBalance, 'balance')
464 : ])
465 0 : const statusFailed =
466 : statusResult.failed &&
467 : statusResult.requestId === latestBillingReadIds.status
468 0 : const balanceFailed =
469 : balanceResult.failed &&
470 : balanceResult.requestId === latestBillingReadIds.balance
471 :
472 0 : if (statusFailed || balanceFailed) {
473 0 : error.value = 'Subscription succeeded, but billing state refresh failed'
474 : }
475 : }
476 :
477 0 : async function subscribe(
478 : planSlug: string,
479 : options?: SubscribeOptions
480 : ): Promise<SettledSubscribeResponse> {
481 0 : const rail = useSubscriptionRail()
482 0 : const attemptStartedAt = options?.attemptStartedAt
483 0 : if (rail?.subscriptionRouteAvailable) {
484 0 : const response = await onSubscriptionRail(() =>
485 : rail.subscribe(subscribeInputFrom(planSlug, options), {
486 : callerStarted: attemptStartedAt !== undefined
487 : })
488 : )
489 : // The SDK waited for the operation, so the refresh the legacy path fires
490 : // and forgets has already run on the rail.
491 0 : if (response !== DECLINED) return response
492 0 : if (attemptStartedAt !== undefined) {
493 : // The caller started this attempt on the rail; the legacy call is its own attempt.
494 0 : telemetry?.trackBillingEvent({
495 : operation: 'operation',
496 : stage: 'failed',
497 : outcome: 'failure',
498 : operation_type: 'subscription',
499 : billing_client: 'sdk',
500 : failure_category: 'api_rejected',
501 : duration_ms: Date.now() - attemptStartedAt
502 : })
503 0 : telemetry?.trackBillingEvent({
504 : operation: 'operation',
505 : stage: 'started',
506 : outcome: 'pending',
507 : operation_type: 'subscription',
508 : billing_client: 'legacy'
509 : })
510 : }
511 : }
512 :
513 0 : isLoading.value = true
514 0 : error.value = null
515 0 : try {
516 0 : const response = await billingApi.subscribe(planSlug, options)
517 0 : isLoading.value = false
518 0 : void reconcileBillingStateAfterSubscribe()
519 0 : return response
520 : } catch (err) {
521 0 : error.value = err instanceof Error ? err.message : 'Failed to subscribe'
522 0 : isLoading.value = false
523 0 : throw err
524 : }
525 : }
526 :
527 0 : async function previewSubscribe(
528 : planSlug: string,
529 : options?: PreviewSubscribeOptions
530 : ): Promise<PreviewSubscribeResponse | null> {
531 0 : const rail = useSubscriptionRail()
532 0 : if (rail) {
533 0 : const quote = await onSubscriptionRail(() =>
534 : rail.previewSubscribe(previewSubscribeInputFrom(planSlug, options))
535 : )
536 0 : if (quote !== DECLINED) return quote
537 : }
538 :
539 0 : isLoading.value = true
540 0 : error.value = null
541 0 : try {
542 0 : return await billingApi.previewSubscribe(planSlug, options)
543 : } catch (err) {
544 0 : error.value =
545 : err instanceof Error ? err.message : 'Failed to preview subscription'
546 0 : throw err
547 : } finally {
548 0 : isLoading.value = false
549 : }
550 : }
551 :
552 : // A cancellation or card change made in the portal window never pushes
553 : // back to this one — status has no return refetch and capability reads
554 : // are paced — so the next return to the app re-reads everything the
555 : // portal could have changed.
556 4730 : let stopPortalReturnRefresh: (() => void) | null = null
557 0 : function refreshOnPortalReturn() {
558 0 : stopPortalReturnRefresh?.()
559 0 : stopPortalReturnRefresh = registerRefreshOnReturn(() =>
560 : Promise.allSettled([
561 : fetchStatus(),
562 : fetchBalance(),
563 : useBillingCapabilities().refresh()
564 : ])
565 : )
566 : }
567 :
568 4730 : if (getCurrentScope()) {
569 4710 : onScopeDispose(() => {
570 0 : stopPortalReturnRefresh?.()
571 : })
572 : }
573 :
574 : /**
575 : * Runs one action on the SDK rail and reports into this adapter's own
576 : * state. `DECLINED` means the routes are not deployed on this backend, so
577 : * the caller runs its legacy path.
578 : */
579 0 : async function onSubscriptionRail<T>(
580 : run: () => Promise<SubscriptionRailOutcome<T>>
581 : ): Promise<T | typeof DECLINED> {
582 0 : isLoading.value = true
583 0 : error.value = null
584 0 : try {
585 0 : const outcome = await run()
586 0 : if (outcome.status === 'unavailable') return DECLINED
587 0 : if (outcome.status === 'error') {
588 0 : error.value = outcome.error.message
589 0 : throw outcome.error
590 : }
591 0 : return outcome.value
592 : } finally {
593 0 : isLoading.value = false
594 : }
595 : }
596 :
597 0 : function reportBillingTabBlocked(): void {
598 0 : useToast().warning(t('g.warning'), {
599 : description: t('subscription.billingTabBlocked')
600 : })
601 : }
602 :
603 0 : function reportBillingPortalUnavailable(): void {
604 0 : useToast().error(t('g.error'), {
605 : description: t('subscription.billingPortalUnavailable')
606 : })
607 : }
608 :
609 : /** The rail's portal URL, or the legacy client's when the rail declines. */
610 0 : async function requestPortalUrl(): Promise<{
611 : url: string | undefined
612 : billingClient: BillingClient
613 : }> {
614 0 : const rail = useSubscriptionRail()
615 0 : if (rail) {
616 0 : const url = await onSubscriptionRail(() =>
617 : rail.openPaymentPortal(window.location.href)
618 : )
619 0 : if (url !== DECLINED) return { url, billingClient: 'sdk' }
620 : }
621 :
622 0 : isLoading.value = true
623 0 : error.value = null
624 0 : try {
625 0 : const returnUrl = window.location.href
626 : const response = await billingApi.getPaymentPortalUrl(returnUrl)
627 0 : return { url: response.url || undefined, billingClient: 'legacy' }
628 : } catch (err) {
629 0 : error.value =
630 : err instanceof Error ? err.message : 'Failed to open billing portal'
631 0 : throw err
632 : } finally {
633 0 : isLoading.value = false
634 : }
635 : }
636 :
637 0 : async function manageSubscription(): Promise<BillingPortalOutcome> {
638 0 : error.value = null
639 0 : const hosted = openHostedBillingTabOutcome('payment-methods')
640 0 : if (hosted === 'opened') return { ok: true }
641 0 : if (hosted === 'blocked') {
642 0 : reportBillingTabBlocked()
643 0 : return { ok: false, reason: 'blocked' }
644 : }
645 :
646 0 : const portal = createBillingPortalReporter(telemetry, 'manage_subscription')
647 0 : const portalTab = reserveBillingTab()
648 0 : if (!portalTab) {
649 0 : portal.blocked()
650 0 : reportBillingTabBlocked()
651 0 : return { ok: false, reason: 'blocked' }
652 : }
653 0 : try {
654 0 : const { url, billingClient } = await requestPortalUrl()
655 0 : if (!url) {
656 0 : portal.failed(undefined, billingClient)
657 0 : portalTab.close()
658 0 : reportBillingPortalUnavailable()
659 0 : return { ok: false, reason: 'missing_url' }
660 : }
661 0 : portalTab.navigate(url)
662 0 : portal.opened(billingClient)
663 0 : refreshOnPortalReturn()
664 0 : return { ok: true }
665 : } catch (err) {
666 0 : portalTab.close()
667 0 : portal.failed(err)
668 0 : throw err
669 : }
670 : }
671 :
672 0 : async function cancelSubscription(
673 : isScopeCurrent: () => boolean = () => true
674 : ): Promise<void> {
675 0 : assertCancellationScopeCurrent(isScopeCurrent)
676 0 : const attemptStartedAt = Date.now()
677 0 : const rail = useSubscriptionRail()
678 0 : const trackCancelStarted = (billingClient: BillingClient) =>
679 : telemetry?.trackBillingEvent({
680 : operation: 'operation',
681 : stage: 'started',
682 : outcome: 'pending',
683 : operation_type: 'cancel',
684 : billing_client: billingClient
685 : })
686 0 : const trackCancelSucceeded = (billingClient: BillingClient) =>
687 : telemetry?.trackBillingEvent({
688 : operation: 'operation',
689 : stage: 'succeeded',
690 : outcome: 'success',
691 : operation_type: 'cancel',
692 : billing_client: billingClient,
693 : duration_ms: Date.now() - attemptStartedAt
694 : })
695 0 : const trackCancelFailed = (
696 : failureCategory: BillingTelemetryFailure['failure_category'],
697 : billingClient: BillingClient
698 : ) =>
699 : telemetry?.trackBillingEvent({
700 : operation: 'operation',
701 : stage: 'failed',
702 : outcome: 'failure',
703 : operation_type: 'cancel',
704 : billing_client: billingClient,
705 : failure_category: failureCategory,
706 : duration_ms: Date.now() - attemptStartedAt
707 : })
708 :
709 : // A rail that already learned its routes are missing goes straight to the
710 : // legacy call, so it never starts an SDK attempt.
711 0 : if (rail?.subscriptionRouteAvailable) {
712 0 : trackCancelStarted('sdk')
713 0 : const settled = await onSubscriptionRail(() =>
714 : rail.cancelSubscription()
715 : ).catch((err: unknown) => {
716 0 : if (!(err instanceof SettledOperationError)) {
717 0 : trackCancelFailed(categorizeBillingApiError(err), 'sdk')
718 : }
719 0 : throw err
720 : })
721 0 : if (settled !== DECLINED) {
722 0 : if (!settled.operationObserved) trackCancelSucceeded('sdk')
723 0 : return
724 : }
725 : // The backend refused the SDK request; the legacy call is its own attempt.
726 0 : trackCancelFailed('api_rejected', 'sdk')
727 : }
728 :
729 0 : assertCancellationScopeCurrent(isScopeCurrent)
730 0 : trackCancelStarted('legacy')
731 :
732 0 : isLoading.value = true
733 0 : error.value = null
734 : // Once set, the poller (billingOperationStore) owns failure telemetry; until then, this must report it.
735 0 : let billingOpId: string | undefined
736 0 : try {
737 : const response = await billingApi.cancelSubscription()
738 0 : billingOpId = response.billing_op_id
739 0 : const operation = await billingOperationStore.startOperation(
740 : billingOpId,
741 : 'cancel',
742 : { attemptStartedAt }
743 : )
744 :
745 0 : if (operation.status !== 'succeeded') {
746 0 : throw new Error(
747 : operation.errorMessage ?? 'Failed to cancel subscription'
748 : )
749 : }
750 : } catch (err) {
751 0 : if (isAlreadyInRequestedState(err, 'ALREADY_CANCELED')) {
752 0 : await resyncQuietly(fetchStatus)
753 : // fetchStatus records its own read failure; the cancellation still
754 : // holds, so the operation is not in error.
755 0 : error.value = null
756 0 : trackCancelSucceeded('legacy')
757 0 : return
758 : }
759 0 : if (billingOpId === undefined) {
760 0 : trackCancelFailed(categorizeBillingApiError(err), 'legacy')
761 : }
762 0 : error.value =
763 : err instanceof Error ? err.message : 'Failed to cancel subscription'
764 0 : throw err
765 : } finally {
766 0 : isLoading.value = false
767 : }
768 : }
769 :
770 0 : async function resubscribe(_options?: {
771 : source?: 'pricing_dialog' | 'settings_billing_panel'
772 : }): Promise<void> {
773 : // Workspace's resubscribe() call is itself the terminal reactivation, so
774 : // the click-time source isn't needed here the way the legacy adapter
775 : // needs it for its pending-checkout-recovery terminal event.
776 0 : const rail = useSubscriptionRail()
777 0 : if (
778 : rail &&
779 : (await onSubscriptionRail(() => rail.resubscribe())) !== DECLINED
780 : ) {
781 0 : return
782 : }
783 :
784 0 : isLoading.value = true
785 0 : error.value = null
786 0 : try {
787 0 : const response = await billingApi.resubscribe()
788 0 : await Promise.allSettled([fetchStatus(), fetchBalance()])
789 : // A pending resubscribe (e.g. SCA/3DS re-authentication) isn't done
790 : // yet: wait for the tracked billing op to actually resolve instead of
791 : // reporting success the instant the request was accepted. fetchStatus
792 : // above may have already started tracking this op via
793 : // pending_billing_op_id; startOperation dedupes by opId either way.
794 0 : if (response.status === 'pending') {
795 0 : const operation = await billingOperationStore.startOperation(
796 : response.billing_op_id,
797 : 'subscription'
798 : )
799 0 : if (operation.status !== 'succeeded') {
800 0 : throw new Error(operation.errorMessage ?? 'Failed to resubscribe')
801 : }
802 0 : await Promise.allSettled([fetchStatus(), fetchBalance()])
803 : }
804 : } catch (err) {
805 0 : if (isAlreadyInRequestedState(err, 'NOT_SCHEDULED_FOR_CANCELLATION')) {
806 : // Mirrors the success path, which refreshes balance too. allSettled,
807 : // not all: a rejection from one read must not release this branch while
808 : // the other is still in flight, or that one writes its failure into
809 : // error after the clear below.
810 0 : await resyncQuietly(() =>
811 : Promise.allSettled([fetchStatus(), fetchBalance()])
812 : )
813 0 : error.value = null
814 0 : return
815 : }
816 0 : error.value = err instanceof Error ? err.message : 'Failed to resubscribe'
817 0 : throw err
818 : } finally {
819 0 : isLoading.value = false
820 : }
821 : }
822 :
823 0 : async function topup(
824 : amountCents: number
825 : ): Promise<CreateTopupResponse | undefined> {
826 0 : isLoading.value = true
827 0 : error.value = null
828 0 : try {
829 0 : return await billingApi.createTopup(amountCents, crypto.randomUUID())
830 : } catch (err) {
831 0 : error.value =
832 : err instanceof Error ? err.message : 'Failed to top up credits'
833 0 : throw err
834 : } finally {
835 0 : isLoading.value = false
836 : }
837 : }
838 :
839 19 : async function fetchPlans(): Promise<void> {
840 19 : isLoading.value = true
841 19 : error.value = null
842 19 : try {
843 19 : await billingPlans.fetchPlans()
844 19 : if (billingPlans.error.value) {
845 0 : error.value = billingPlans.error.value
846 : }
847 : } finally {
848 18 : isLoading.value = false
849 : }
850 : }
851 :
852 4730 : return {
853 : // State
854 : isInitialized,
855 : subscription,
856 : balance,
857 : plans,
858 : currentPlanSlug,
859 : teamCreditStops,
860 : subscriptionPaymentRecovery,
861 : currentTeamCreditStop,
862 : maxSeats,
863 : occupiedSeats,
864 : isLoading,
865 : error,
866 : canAccessSubscriptionFeatures,
867 : isFreeTier,
868 : billingStatus,
869 : subscriptionStatus,
870 : subscriptionState,
871 : tier,
872 : renewalDate,
873 : renewalInvoice,
874 : periodCreditGrant,
875 : nextCreditRefillAt,
876 : readAndAdoptPendingOperation,
877 :
878 : // Actions
879 : initialize,
880 : fetchStatus,
881 : fetchBalance,
882 : subscribe,
883 : previewSubscribe,
884 : manageSubscription,
885 : cancelSubscription,
886 : resubscribe,
887 : topup,
888 : fetchPlans
889 : }
890 : }
|