LCOV - code coverage report
Current view: top level - src/platform/billing/stores - billingOperationStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 9.3 % 367 34
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useWorkspaceBillingStateStore } from '@/platform/billing/stores/workspaceBillingStateStore'
       2              : import type {
       3              :   BillingTelemetryEvent,
       4              :   BillingTelemetryFailure,
       5              :   SubscriptionCheckoutTier,
       6              :   SubscriptionCheckoutType
       7              : } from '@comfyorg/account-core/billing'
       8              : import { customerCanActHere } from '@comfyorg/account-core/billing'
       9              : import { useEventListener } from '@vueuse/core'
      10              : import { defineStore } from 'pinia'
      11              : import { computed, ref } from 'vue'
      12              : 
      13              : import { useToast } from '@/components/ui/toast/toastStore'
      14              : import { t } from '@/i18n'
      15              : import type { TierKey } from '@/platform/billing/subscription/constants/tierPricing'
      16              : import type { BillingCycle } from '@/platform/billing/subscription/utils/subscriptionTierRank'
      17              : import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
      18              : import { isCloud } from '@/platform/distribution/types'
      19              : import { useTelemetry } from '@comfyorg/telemetry'
      20              : import { reportError } from '@comfyorg/telemetry/reportError'
      21              : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
      22              : import { billingApi } from '@/platform/billing/api/billingApi'
      23              : import type {
      24              :   BillingAuthenticationState,
      25              :   BillingOperationPhase,
      26              :   BillingRecoveryAction
      27              : } from '@comfyorg/billing-core'
      28              : import { refreshBilling } from '@/platform/billing/billingRefresh'
      29              : import type {
      30              :   ProgressToast,
      31              :   ProgressToastKind
      32              : } from '@/platform/billing/customerAttention'
      33              : import {
      34              :   isBlockedOnCustomerPhase,
      35              :   isParkedCheckout,
      36              :   legacyOperationActionHold,
      37              :   needsCustomerAttention,
      38              :   progressToastKind
      39              : } from '@/platform/billing/customerAttention'
      40              : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
      41              : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
      42              : import {
      43              :   clearCheckoutJourney,
      44              :   getActiveCheckoutJourney,
      45              :   getCheckoutJourneyPaymentIntentSource
      46              : } from '@/platform/billing/utils/checkoutJourney'
      47              : import { useDialogStore } from '@/stores/dialogStore'
      48              : 
      49         2356 : const INITIAL_INTERVAL_MS = 1000
      50         2356 : const MAX_INTERVAL_MS = 8000
      51         2356 : const ACTION_REQUIRED_INTERVAL_MS = 30_000
      52              : // Twenty turns of the backend's 3 s PaymentIntent status cache.
      53         2356 : const ACTION_DISCOVERY_WINDOW_MS = 60_000
      54         2356 : const BACKOFF_MULTIPLIER = 1.5
      55         2356 : const TIMEOUT_MS = 120_000
      56         2356 : const SUBSCRIPTION_ACTION_DISCOVERY_TIMEOUT_MS = 5 * 60_000
      57         2356 : const AUTHENTICATION_TIMEOUT_MS = 23 * 60 * 60_000
      58              : // Failure reason for a checkout the user replaced by picking a different plan
      59              : // mid-flow. The operation is terminal-failed only because it never completed —
      60              : // its replacement is proceeding normally, so there is nothing to report.
      61         2356 : const CHECKOUT_SUPERSEDED_REASON = 'checkout_superseded'
      62              : const FAILURE_DETAIL_CODES: [string, string[]][] = [
      63              :   ['billingOperation.insufficientFundsDetail', ['insufficient_funds']],
      64              :   ['billingOperation.expiredCardDetail', ['expired_card']],
      65              :   ['billingOperation.incorrectCvcDetail', ['incorrect_cvc', 'invalid_cvc']],
      66              :   [
      67              :     'billingOperation.incorrectNumberDetail',
      68              :     ['incorrect_number', 'invalid_number']
      69              :   ],
      70              :   ['billingOperation.noPaymentMethodDetail', ['reset_now_no_payment_method']],
      71              :   [
      72              :     'billingOperation.topupMethodIncompatibleDetail',
      73              :     ['topup_currency_incompatible']
      74              :   ],
      75              :   [
      76              :     'billingOperation.authenticationFailedDetail',
      77              :     [
      78              :       'authentication_failed',
      79              :       'authentication_required',
      80              :       'payment_intent_authentication_failure',
      81              :       'payment_not_completed',
      82              :       'payment_method_customer_decline',
      83              :       'payment_intent_payment_attempt_expired'
      84              :     ]
      85              :   ],
      86              :   [
      87              :     'billingOperation.processingErrorDetail',
      88              :     ['processing_error', 'issuer_not_available', 'try_again_later']
      89              :   ],
      90              :   [
      91              :     'billingOperation.paymentDeclinedDetail',
      92              :     [
      93              :       'card_declined',
      94              :       'generic_decline',
      95              :       'fraudulent',
      96              :       'lost_card',
      97              :       'stolen_card',
      98              :       'pickup_card',
      99              :       'invalid_account',
     100              :       'card_velocity_exceeded',
     101              :       'approve_with_id',
     102              :       'call_issuer',
     103              :       'do_not_honor',
     104              :       'do_not_try_again',
     105              :       'not_permitted',
     106              :       'restricted_card',
     107              :       'security_violation',
     108              :       'service_not_allowed',
     109              :       'transaction_not_allowed',
     110              :       'initial_subscription_rejected',
     111              :       'subscribe_invoice_payment_failed',
     112              :       'topup_payment_declined',
     113              :       'topup_invoice_payment_failed',
     114              :       'upgrade_payment_declined',
     115              :       'upgrade_invoice_payment_failed',
     116              :       'team_credit_raise_payment_declined',
     117              :       'reset_now_payment_declined',
     118              :       'reset_now_invoice_payment_failed'
     119              :     ]
     120              :   ]
     121              : ]
     122              : 
     123         2356 : const FAILURE_DETAIL_KEYS = new Map(
     124              :   FAILURE_DETAIL_CODES.flatMap(([key, codes]) =>
     125              :     codes.map((code) => [code, key] as const)
     126              :   )
     127              : )
     128              : 
     129              : // The poller adopts only operations the legacy rail issued; the SDK rail settles its own.
     130            0 : function trackLegacyBillingEvent(event: BillingTelemetryEvent) {
     131            0 :   useTelemetry()?.trackBillingEvent({ ...event, billing_client: 'legacy' })
     132              : }
     133              : 
     134              : type OperationType = 'subscription' | 'topup' | 'cancel' | 'retention'
     135              : type PaymentOperationType = Extract<OperationType, 'subscription' | 'topup'>
     136              : 
     137            0 : function isPaymentOperation(type: OperationType): type is PaymentOperationType {
     138            0 :   return type === 'subscription' || type === 'topup'
     139              : }
     140              : 
     141              : type OperationStatus =
     142              :   | 'pending'
     143              :   | 'succeeded'
     144              :   | 'failed'
     145              :   | 'timeout'
     146              :   | 'reconciliation_needed'
     147              : 
     148              : export interface StartOperationMetadata {
     149              :   workspaceId?: string
     150              :   tier?: SubscriptionCheckoutTier
     151              :   cycle?: BillingCycle
     152              :   checkoutType?: SubscriptionCheckoutType
     153              :   paymentIntentSource?: PaymentIntentSource
     154              :   /**
     155              :    * Adopted from a status read rather than started by the customer here. The
     156              :    * read names the operation but not what it waits on, so without a served
     157              :    * link it is announced by its first status, never before it.
     158              :    */
     159              :   resumed?: boolean
     160              :   paymentMethodUrl?: string
     161              :   downgradeToPersonal?: {
     162              :     memberRemovalCount: number
     163              :     memberRemovalFailures: number
     164              :     targetTier?: TierKey
     165              :     startedAt: number
     166              :   }
     167              :   /**
     168              :    * The timestamp the caller used for its own canonical `started` telemetry
     169              :    * event (i.e. before the initiating subscribe/top-up/cancel API call), so
     170              :    * `duration_ms` on the poller's terminal events spans the full emitted
     171              :    * lifecycle instead of just the poll-observation window. Defaults to
     172              :    * `Date.now()` (poll-start time) when the caller has no such timestamp,
     173              :    * e.g. recovering a pending operation on page load.
     174              :    */
     175              :   attemptStartedAt?: number
     176              : }
     177              : 
     178              : interface BillingOperation {
     179              :   opId: string
     180              :   type: OperationType
     181              :   status: OperationStatus
     182              :   errorMessage: string | null
     183              :   startedAt: number
     184              :   operationStartedAt: number
     185              :   businessAttemptStartedAt?: number
     186              :   actionUrl: string | null
     187              :   paymentMethodUrl: string | null
     188              :   authenticationState: BillingAuthenticationState | null
     189              :   authenticationDeadline?: string
     190              :   isAuthenticating: boolean
     191              :   canRetryAuthentication: boolean
     192              :   authenticationRequiredSeen: boolean
     193              :   // Latches once the server has reported a phase blocked on the customer. The
     194              :   // phase itself moves on — an invoice being finalised reports in_progress —
     195              :   // and elapsed time is counted from the start, so re-reading it would measure
     196              :   // the whole parked wait against the short budget the moment it advances.
     197              :   blockedOnCustomerSeen: boolean
     198              :   workspaceId: string | null
     199              :   tier?: SubscriptionCheckoutTier
     200              :   cycle?: BillingCycle
     201              :   checkoutType?: SubscriptionCheckoutType
     202              :   paymentIntentSource?: PaymentIntentSource
     203              :   // Last phase the server reported for a pending operation. The phases
     204              :   // isBlockedOnCustomerPhase names will not advance until the customer acts, so
     205              :   // a dialog should offer them a way back rather than keep waiting. Null while
     206              :   // unknown — the field is optional in the contract, and absent is explicitly
     207              :   // no claim, never an implied in_progress.
     208              :   phase: BillingOperationPhase | null
     209              :   downgradeToPersonal?: StartOperationMetadata['downgradeToPersonal']
     210              :   // Set when the customer walked away from this operation in the UI (e.g.
     211              :   // "Start over" after a failed challenge). The operation itself is not
     212              :   // over — only the server decides that — so it keeps polling and can still
     213              :   // resolve normally; this only hides it from the selectors a dialog reads.
     214              :   dismissed: boolean
     215              : }
     216              : 
     217              : type TerminalResolver = (operation: BillingOperation) => void
     218              : 
     219              : interface FailureRecovery {
     220              :   readonly action?: BillingRecoveryAction
     221              :   // The contract's authority on whether starting another operation can succeed.
     222              :   readonly retryable?: boolean
     223              : }
     224              : 
     225         2356 : export const useBillingOperationStore = defineStore('billingOperation', () => {
     226         2355 :   const workspaceStore = useWorkspaceIdentity()
     227         2355 :   const toast = useToast()
     228         2355 :   const operations = ref<Map<string, BillingOperation>>(new Map())
     229         2355 :   const timeouts = new Map<string, ReturnType<typeof setTimeout>>()
     230         2355 :   const intervals = new Map<string, number>()
     231         2355 :   const waitingWithoutActionSince = new Map<string, number>()
     232         2355 :   const progressToasts = new Map<string, ProgressToast>()
     233         2355 :   const progressToastsAwaitingFirstRead = new Set<string>()
     234         2355 :   const dismissedProgressToasts = new Set<string>()
     235         2355 :   const terminalResolvers = new Map<string, TerminalResolver>()
     236         2355 :   const terminalPromises = new Map<string, Promise<BillingOperation>>()
     237         2355 :   const inFlightPolls = new Map<string, Promise<void>>()
     238         2355 :   const generations = new Map<string, symbol>()
     239              : 
     240         2355 :   useEventListener(document, 'visibilitychange', () => {
     241          100 :     if (document.visibilityState === 'visible') pollPendingOperations()
     242              :   })
     243              : 
     244         2355 :   const hasPendingOperations = computed(() =>
     245              :     [...operations.value.values()].some((op) => op.status === 'pending')
     246              :   )
     247              : 
     248         2355 :   const isSettingUp = computed(() =>
     249              :     [...operations.value.values()].some(
     250              :       (op) =>
     251              :         op.status === 'pending' &&
     252              :         op.authenticationState !== 'requires_action' &&
     253              :         op.authenticationState !== 'failed_retryable' &&
     254              :         !isParkedCheckout(op) &&
     255              :         op.type === 'subscription' &&
     256              :         op.workspaceId === workspaceStore.activeWorkspaceId
     257              :     )
     258              :   )
     259              : 
     260         2355 :   const isAddingCredits = computed(() =>
     261              :     [...operations.value.values()].some(
     262              :       (op) =>
     263              :         op.status === 'pending' &&
     264              :         op.authenticationState !== 'failed_retryable' &&
     265              :         !op.dismissed &&
     266              :         op.type === 'topup' &&
     267              :         op.workspaceId === workspaceStore.activeWorkspaceId
     268              :     )
     269              :   )
     270              : 
     271         2355 :   const subscriptionActionOperation = computed(() =>
     272              :     [...operations.value.values()].find(
     273              :       (op) =>
     274              :         op.type === 'subscription' &&
     275              :         op.workspaceId === workspaceStore.activeWorkspaceId &&
     276              :         needsCustomerAttention(op)
     277              :     )
     278              :   )
     279              : 
     280         2355 :   const topupActionOperation = computed(() =>
     281              :     [...operations.value.values()].find(
     282              :       (op) =>
     283              :         op.type === 'topup' &&
     284              :         op.workspaceId === workspaceStore.activeWorkspaceId &&
     285              :         !op.dismissed &&
     286              :         needsCustomerAttention(op)
     287              :     )
     288              :   )
     289              : 
     290            0 :   function getOperation(opId: string) {
     291            0 :     return operations.value.get(opId)
     292              :   }
     293              : 
     294              :   // An operation parked on a bank challenge is waiting on the customer, not on
     295              :   // us, so it must not keep announcing "processing" — that reads as "nothing to
     296              :   // do here" next to the verification prompt the same state renders.
     297            0 :   function syncProgressToast(
     298              :     opId: string,
     299              :     type: PaymentOperationType,
     300              :     kind: ProgressToastKind | undefined
     301              :   ) {
     302            0 :     const previous = progressToasts.get(opId)
     303            0 :     if (previous?.kind === kind) return
     304            0 :     if (previous) {
     305            0 :       progressToasts.delete(opId)
     306            0 :       if (toast.takeClosedByUser(previous.id)) {
     307            0 :         dismissedProgressToasts.add(opId)
     308              :       } else {
     309            0 :         toast.dismiss(previous.id)
     310              :       }
     311              :     }
     312            0 :     if (
     313              :       kind === undefined ||
     314              :       (kind === 'processing' && dismissedProgressToasts.has(opId))
     315              :     ) {
     316            0 :       return
     317              :     }
     318              : 
     319            0 :     const messageKey =
     320              :       type === 'subscription'
     321              :         ? kind === 'action'
     322              :           ? 'billingOperation.subscriptionActionRequired'
     323              :           : 'billingOperation.subscriptionProcessing'
     324              :         : kind === 'action'
     325              :           ? 'billingOperation.topupActionRequired'
     326              :           : 'billingOperation.topupProcessing'
     327              : 
     328            0 :     const id =
     329              :       kind === 'action'
     330              :         ? toast.warning(t(messageKey))
     331              :         : toast.loading(t(messageKey))
     332            0 :     progressToasts.set(opId, { kind, id })
     333              :   }
     334              : 
     335            0 :   function announceStart(
     336              :     operation: BillingOperation,
     337              :     metadata: StartOperationMetadata | undefined
     338              :   ) {
     339            0 :     if (!isPaymentOperation(operation.type)) return
     340            0 :     if (metadata?.resumed && operation.actionUrl === null) {
     341            0 :       progressToastsAwaitingFirstRead.add(operation.opId)
     342            0 :       return
     343              :     }
     344            0 :     syncProgressToast(
     345              :       operation.opId,
     346              :       operation.type,
     347              :       progressToastKind(operation)
     348              :     )
     349              :   }
     350              : 
     351              :   // The action URL is the last field a read applies, so an operation awaiting
     352              :   // its first read is announced here by what that read found.
     353            0 :   function syncProgressToastAfterRead(
     354              :     before: BillingOperation,
     355              :     after: BillingOperation
     356              :   ) {
     357            0 :     if (
     358              :       isPaymentOperation(after.type) &&
     359              :       progressToastsAwaitingFirstRead.delete(after.opId)
     360              :     ) {
     361            0 :       syncProgressToast(after.opId, after.type, progressToastKind(after))
     362            0 :       return
     363              :     }
     364            0 :     syncProgressToastOnChange(before, after)
     365              :   }
     366              : 
     367            0 :   function syncProgressToastOnChange(
     368              :     before: BillingOperation,
     369              :     after: BillingOperation
     370              :   ) {
     371            0 :     if (!isPaymentOperation(after.type)) return
     372            0 :     const kind = progressToastKind(after)
     373            0 :     if (kind !== progressToastKind(before)) {
     374            0 :       syncProgressToast(after.opId, after.type, kind)
     375              :     }
     376              :   }
     377              : 
     378            0 :   function isAwaitingPaymentMethod(operation: BillingOperation): boolean {
     379            0 :     return (
     380              :       operation.phase === null || operation.phase === 'awaiting_payment_method'
     381              :     )
     382              :   }
     383              : 
     384            0 :   function showsOnlyPaymentMethodUrl(operation: BillingOperation): boolean {
     385            0 :     return (
     386              :       operation.actionUrl === null ||
     387              :       operation.actionUrl === operation.paymentMethodUrl
     388              :     )
     389              :   }
     390              : 
     391            0 :   function adoptPaymentMethodUrl(
     392              :     operation: BillingOperation,
     393              :     paymentMethodUrl: string | null
     394              :   ) {
     395            0 :     if (
     396              :       !paymentMethodUrl ||
     397              :       operation.status !== 'pending' ||
     398              :       !isAwaitingPaymentMethod(operation) ||
     399              :       !showsOnlyPaymentMethodUrl(operation)
     400              :     ) {
     401            0 :       return
     402              :     }
     403            0 :     const updated: BillingOperation = {
     404              :       ...operation,
     405              :       actionUrl: paymentMethodUrl,
     406              :       paymentMethodUrl,
     407              :       authenticationRequiredSeen: true
     408              :     }
     409            0 :     operations.value = new Map(operations.value).set(operation.opId, updated)
     410            0 :     syncProgressToastAfterRead(operation, updated)
     411              :   }
     412              : 
     413            0 :   function createPendingOperation(
     414              :     opId: string,
     415              :     type: OperationType,
     416              :     metadata: StartOperationMetadata | undefined,
     417              :     initialActionUrl: string | undefined
     418              :   ): BillingOperation {
     419            0 :     const paymentMethodUrl = validateActionUrl(metadata?.paymentMethodUrl)
     420            0 :     const actionUrl = validateActionUrl(initialActionUrl) ?? paymentMethodUrl
     421            0 :     const now = Date.now()
     422              :     const operation: BillingOperation = {
     423              :       opId,
     424              :       type,
     425              :       status: 'pending',
     426              :       errorMessage: null,
     427              :       startedAt: now,
     428              :       operationStartedAt: metadata?.attemptStartedAt ?? now,
     429              :       businessAttemptStartedAt: metadata?.attemptStartedAt,
     430              :       actionUrl,
     431              :       paymentMethodUrl,
     432              :       authenticationState: null,
     433              :       isAuthenticating: false,
     434              :       canRetryAuthentication: false,
     435              :       authenticationRequiredSeen: actionUrl !== null,
     436              :       blockedOnCustomerSeen: false,
     437              :       workspaceId: metadata?.workspaceId ?? workspaceStore.activeWorkspaceId,
     438              :       tier: metadata?.tier,
     439              :       cycle: metadata?.cycle,
     440              :       checkoutType: metadata?.checkoutType,
     441              :       paymentIntentSource:
     442              :         metadata?.paymentIntentSource ??
     443              :         getCheckoutJourneyPaymentIntentSource(opId),
     444              :       phase: null,
     445              :       downgradeToPersonal: metadata?.downgradeToPersonal,
     446              :       dismissed: false
     447              :     }
     448            0 :     return operation
     449              :   }
     450              : 
     451            0 :   function startOperation(
     452              :     opId: string,
     453              :     type: OperationType,
     454              :     metadata?: StartOperationMetadata,
     455              :     initialActionUrl?: string
     456              :   ): Promise<BillingOperation> {
     457            0 :     const existing = operations.value.get(opId)
     458            0 :     if (existing && existing.status !== 'timeout') {
     459            0 :       adoptPaymentMethodUrl(
     460              :         existing,
     461              :         validateActionUrl(metadata?.paymentMethodUrl)
     462              :       )
     463            0 :       return terminalPromises.get(opId) ?? Promise.resolve(existing)
     464              :     }
     465            0 :     if (existing) clearOperation(opId)
     466              : 
     467            0 :     const operation = createPendingOperation(
     468              :       opId,
     469              :       type,
     470              :       metadata,
     471              :       initialActionUrl
     472              :     )
     473              : 
     474            0 :     generations.set(opId, Symbol(opId))
     475            0 :     operations.value = new Map(operations.value).set(opId, operation)
     476            0 :     intervals.set(opId, INITIAL_INTERVAL_MS)
     477              : 
     478            0 :     if (metadata?.attemptStartedAt === undefined) {
     479            0 :       trackLegacyBillingEvent({
     480              :         operation: 'operation',
     481              :         stage: 'started',
     482              :         outcome: 'pending',
     483              :         operation_type: type
     484              :       })
     485              :     }
     486              : 
     487            0 :     announceStart(operation, metadata)
     488              : 
     489            0 :     const terminal = new Promise<BillingOperation>((resolve) => {
     490            0 :       terminalResolvers.set(opId, resolve)
     491              :     })
     492            0 :     terminalPromises.set(opId, terminal)
     493              : 
     494            0 :     void poll(opId)
     495              : 
     496            0 :     return terminal
     497              :   }
     498              : 
     499            0 :   async function poll(opId: string) {
     500            0 :     const inFlight = inFlightPolls.get(opId)
     501            0 :     if (inFlight) {
     502            0 :       await inFlight
     503            0 :       return
     504              :     }
     505              : 
     506            0 :     const request = pollOnce(opId).finally(() => {
     507            0 :       inFlightPolls.delete(opId)
     508              :     })
     509            0 :     inFlightPolls.set(opId, request)
     510            0 :     await request
     511              :   }
     512              : 
     513            0 :   function isStalePoll(opId: string, generation: symbol | undefined) {
     514            0 :     return (
     515              :       generations.get(opId) !== generation ||
     516              :       operations.value.get(opId)?.status !== 'pending'
     517              :     )
     518              :   }
     519              : 
     520            0 :   async function pollOnce(opId: string) {
     521            0 :     const operation = operations.value.get(opId)
     522            0 :     if (!operation || operation.status !== 'pending') return
     523            0 :     pausePolling(opId)
     524            0 :     if (operation.isAuthenticating) return
     525              : 
     526            0 :     if (stopIfTimedOut(opId, operation)) return
     527              : 
     528            0 :     if (operation.workspaceId !== workspaceStore.activeWorkspaceId) {
     529            0 :       scheduleNextPoll(opId)
     530            0 :       return
     531              :     }
     532              : 
     533            0 :     const generation = generations.get(opId)
     534            0 :     try {
     535            0 :       const response = await billingApi.getBillingOpStatus(opId)
     536            0 :       if (isStalePoll(opId, generation)) return
     537            0 :       if (operation.workspaceId !== workspaceStore.activeWorkspaceId) {
     538            0 :         if (stopIfTimedOut(opId, operation)) return
     539            0 :         scheduleNextPoll(opId)
     540            0 :         return
     541              :       }
     542              : 
     543            0 :       if (response.status === 'succeeded') {
     544            0 :         await handleSuccess(opId)
     545            0 :         return
     546              :       }
     547              : 
     548            0 :       if (response.status === 'failed') {
     549            0 :         handleFailure(opId, response.error_message ?? null, {
     550              :           action: response.recovery_action,
     551              :           retryable: response.retryable
     552              :         })
     553            0 :         return
     554              :       }
     555              : 
     556            0 :       if (response.status === 'reconciliation_needed') {
     557            0 :         handleReconciliationNeeded(opId)
     558            0 :         return
     559              :       }
     560              : 
     561            0 :       updateOperationPhase(opId, response.phase ?? null)
     562            0 :       if (stopIfTimedOut(opId, operations.value.get(opId) ?? operation)) return
     563              : 
     564            0 :       updateOperationActionUrl(
     565              :         opId,
     566              :         validateActionUrl(response.action_url),
     567              :         response.authentication_deadline
     568              :       )
     569            0 :       scheduleNextPoll(opId)
     570              :     } catch {
     571            0 :       const currentOperation = operations.value.get(opId)
     572            0 :       if (!currentOperation || isStalePoll(opId, generation)) return
     573            0 :       if (stopIfTimedOut(opId, currentOperation)) return
     574            0 :       scheduleNextPoll(opId)
     575              :     }
     576              :   }
     577              : 
     578            1 :   function pollPendingOperations() {
     579            1 :     for (const operation of operations.value.values()) {
     580            0 :       if (
     581              :         operation.workspaceId === workspaceStore.activeWorkspaceId &&
     582              :         operation.status === 'pending' &&
     583              :         !operation.isAuthenticating
     584              :       ) {
     585            0 :         pausePolling(operation.opId)
     586            0 :         void poll(operation.opId)
     587              :       }
     588              :     }
     589              :   }
     590              : 
     591              :   // The slow cadence is for an operation parked on the customer: a challenge
     592              :   // to complete elsewhere, or a failed attempt awaiting their retry. Once this
     593              :   // tab's own challenge completes, the state reads processing and nothing
     594              :   // waits on the customer anymore — holding the slow cadence there left a
     595              :   // settled payment spinning for half a minute.
     596            0 :   function isWaitingOnCustomer(operation: BillingOperation): boolean {
     597            0 :     return (
     598              :       isBlockedOnCustomerPhase(operation.phase) ||
     599              :       operation.authenticationState === 'requires_action' ||
     600              :       operation.actionUrl !== null ||
     601              :       (operation.authenticationState === 'failed_retryable' &&
     602              :         operation.authenticationRequiredSeen)
     603              :     )
     604              :   }
     605              : 
     606              :   // Parked straight away only while the customer can act here. The server can
     607              :   // report a blocked phase and a client secret before its cached
     608              :   // authentication_state catches up, so an actionless wait keeps the backoff
     609              :   // for the discovery window. Past it the action is not coming to this tab (a
     610              :   // member without billing permission, embedded checkout off) and it parks.
     611            0 :   function isParkedAwaitingCustomer(
     612              :     operation: BillingOperation,
     613              :     waitedWithoutActionMs: number
     614              :   ): boolean {
     615            0 :     if (!isWaitingOnCustomer(operation)) return false
     616            0 :     return (
     617              :       customerCanAct(operation) ||
     618              :       waitedWithoutActionMs >= ACTION_DISCOVERY_WINDOW_MS
     619              :     )
     620              :   }
     621              : 
     622            0 :   function trackWaitWithoutAction(operation: BillingOperation): number {
     623            0 :     if (!isWaitingOnCustomer(operation) || customerCanAct(operation)) {
     624            0 :       waitingWithoutActionSince.delete(operation.opId)
     625            0 :       return 0
     626              :     }
     627            0 :     const now = Date.now()
     628            0 :     const since = waitingWithoutActionSince.get(operation.opId) ?? now
     629            0 :     waitingWithoutActionSince.set(operation.opId, since)
     630            0 :     return now - since
     631              :   }
     632              : 
     633            0 :   function customerCanAct(operation: BillingOperation): boolean {
     634            0 :     return customerCanActHere(legacyOperationActionHold(operation, false))
     635              :   }
     636              : 
     637            0 :   function scheduleNextPoll(opId: string) {
     638            0 :     const operation = operations.value.get(opId)
     639            0 :     if (!operation || operation.status !== 'pending') return
     640              :     // One chain per operation: an explicit retry polls immediately while a
     641              :     // scheduled poll may still be armed, and two chains would double the
     642              :     // request rate and race each other's state writes.
     643            0 :     pausePolling(opId)
     644            0 :     const nextInterval = isParkedAwaitingCustomer(
     645              :       operation,
     646              :       trackWaitWithoutAction(operation)
     647              :     )
     648              :       ? ACTION_REQUIRED_INTERVAL_MS
     649              :       : Math.min(
     650              :           (intervals.get(opId) ?? INITIAL_INTERVAL_MS) * BACKOFF_MULTIPLIER,
     651              :           MAX_INTERVAL_MS
     652              :         )
     653            0 :     intervals.set(opId, nextInterval)
     654              : 
     655            0 :     const timeoutId = setTimeout(() => void poll(opId), nextInterval)
     656            0 :     timeouts.set(opId, timeoutId)
     657              :   }
     658              : 
     659            0 :   function validateActionUrl(value: string | undefined): string | null {
     660            0 :     if (!value) return null
     661            0 :     try {
     662              :       const url = new URL(value)
     663            0 :       return url.protocol === 'https:' ? value : null
     664              :     } catch {
     665            0 :       return null
     666              :     }
     667              :   }
     668              : 
     669            0 :   function hasTimedOut(operation: BillingOperation): boolean {
     670            0 :     const elapsed = Date.now() - operation.startedAt
     671            0 :     if (
     672              :       isPaymentOperation(operation.type) &&
     673              :       (operation.authenticationRequiredSeen || operation.blockedOnCustomerSeen)
     674              :     ) {
     675            0 :       return elapsed > AUTHENTICATION_TIMEOUT_MS
     676              :     }
     677            0 :     return operation.type === 'subscription'
     678              :       ? elapsed > SUBSCRIPTION_ACTION_DISCOVERY_TIMEOUT_MS
     679              :       : elapsed > TIMEOUT_MS
     680              :   }
     681              : 
     682            0 :   function updateOperation(opId: string, patch: Partial<BillingOperation>) {
     683            0 :     const operation = operations.value.get(opId)
     684            0 :     if (!operation) return
     685            0 :     const settled = patch.status !== undefined && patch.status !== 'pending'
     686            0 :     operations.value = new Map(operations.value).set(opId, {
     687              :       ...operation,
     688              :       ...patch,
     689              :       ...(settled && { paymentMethodUrl: null })
     690              :     })
     691              :   }
     692              : 
     693            0 :   function pausePolling(opId: string) {
     694            0 :     const timeoutId = timeouts.get(opId)
     695            0 :     if (timeoutId) clearTimeout(timeoutId)
     696            0 :     timeouts.delete(opId)
     697              :   }
     698              : 
     699            0 :   function stopIfTimedOut(opId: string, operation: BillingOperation): boolean {
     700            0 :     if (!hasTimedOut(operation)) return false
     701            0 :     handleTimeout(opId)
     702            0 :     return true
     703              :   }
     704              : 
     705            0 :   function updateOperationPhase(
     706              :     opId: string,
     707              :     phase: BillingOperationPhase | null
     708              :   ) {
     709            0 :     const operation = operations.value.get(opId)
     710            0 :     if (
     711              :       !operation ||
     712              :       operation.status !== 'pending' ||
     713              :       operation.phase === phase
     714              :     ) {
     715            0 :       return
     716              :     }
     717            0 :     const updated: BillingOperation = {
     718              :       ...operation,
     719              :       phase,
     720              :       blockedOnCustomerSeen:
     721              :         operation.blockedOnCustomerSeen || isBlockedOnCustomerPhase(phase)
     722              :     }
     723            0 :     operations.value = new Map(operations.value).set(opId, updated)
     724            0 :     syncProgressToastOnChange(operation, updated)
     725              :   }
     726              : 
     727            0 :   function keptPaymentMethodUrl(
     728              :     operation: BillingOperation,
     729              :     polledActionUrl: string | null
     730              :   ): string | null {
     731              :     const keeps =
     732              :       polledActionUrl === null && operation.phase === 'awaiting_payment_method'
     733            0 :     return keeps ? operation.paymentMethodUrl : null
     734              :   }
     735              : 
     736            0 :   function updateOperationActionUrl(
     737              :     opId: string,
     738              :     actionUrl: string | null,
     739              :     authenticationDeadline?: string
     740              :   ) {
     741            0 :     const operation = operations.value.get(opId)
     742            0 :     if (!operation || operation.status !== 'pending') return
     743            0 :     const paymentMethodUrl = keptPaymentMethodUrl(operation, actionUrl)
     744            0 :     const shownUrl = actionUrl ?? paymentMethodUrl
     745            0 :     const updated: BillingOperation = {
     746              :       ...operation,
     747              :       actionUrl: shownUrl,
     748              :       paymentMethodUrl,
     749              :       authenticationDeadline,
     750              :       authenticationRequiredSeen:
     751              :         operation.authenticationRequiredSeen || shownUrl !== null
     752              :     }
     753            0 :     operations.value = new Map(operations.value).set(opId, updated)
     754            0 :     syncProgressToastAfterRead(operation, updated)
     755              :   }
     756              : 
     757            0 :   async function handleSuccess(opId: string) {
     758            0 :     const operation = operations.value.get(opId)
     759            0 :     if (!operation) return
     760              : 
     761            0 :     updateOperationStatus(opId, 'succeeded', null)
     762              : 
     763            0 :     if (getActiveCheckoutJourney()?.billing_op_id === opId) {
     764            0 :       clearCheckoutJourney()
     765              :     }
     766              : 
     767            0 :     try {
     768            0 :       cleanup(opId)
     769              : 
     770            0 :       const telemetry = useTelemetry()
     771            0 :       const now = Date.now()
     772            0 :       const operationDurationMs = now - operation.operationStartedAt
     773            0 :       trackLegacyBillingEvent({
     774              :         operation: 'operation',
     775              :         stage: 'succeeded',
     776              :         outcome: 'success',
     777              :         billing_op_id: opId,
     778              :         operation_type: operation.type,
     779              :         tier: operation.tier,
     780              :         cycle: operation.cycle,
     781              :         checkout_type: operation.checkoutType,
     782              :         payment_intent_source: operation.paymentIntentSource,
     783              :         duration_ms: operationDurationMs
     784              :       })
     785              : 
     786            0 :       if (
     787              :         operation.type === 'subscription' &&
     788              :         operation.businessAttemptStartedAt !== undefined
     789              :       ) {
     790            0 :         const durationMs = now - operation.businessAttemptStartedAt
     791            0 :         trackLegacyBillingEvent({
     792              :           operation: 'subscription_checkout',
     793              :           stage: 'succeeded',
     794              :           outcome: 'success',
     795              :           tier: operation.tier,
     796              :           cycle: operation.cycle,
     797              :           checkout_type: operation.checkoutType,
     798              :           payment_intent_source: operation.paymentIntentSource,
     799              :           billing_op_id: opId,
     800              :           duration_ms: durationMs
     801              :         })
     802              :         // Also fires the legacy event for providers (Mixpanel, GTM) that don't
     803              :         // implement trackBillingEvent. Gated to actual new/upgraded
     804              :         // subscriptions — a downgrade-to-personal is churn, not a conversion,
     805              :         // and this event drives a GA4 "subscription succeeded" conversion goal.
     806            0 :         if (!operation.downgradeToPersonal) {
     807            0 :           telemetry?.trackMonthlySubscriptionSucceeded({
     808              :             tier: operation.tier,
     809              :             cycle: operation.cycle,
     810              :             checkout_type: operation.checkoutType,
     811              :             payment_intent_source: operation.paymentIntentSource,
     812              :             billing_op_id: opId
     813              :           })
     814              :         }
     815            0 :       } else if (
     816              :         operation.type === 'topup' &&
     817              :         operation.businessAttemptStartedAt !== undefined
     818              :       ) {
     819            0 :         trackLegacyBillingEvent({
     820              :           operation: 'topup',
     821              :           stage: 'succeeded',
     822              :           outcome: 'success',
     823              :           billing_op_id: opId,
     824              :           payment_intent_source: operation.paymentIntentSource,
     825              :           duration_ms: now - operation.businessAttemptStartedAt
     826              :         })
     827              :       }
     828              :       // Mirrors handleFailure's structure: not gated on businessAttemptStartedAt,
     829              :       // since a downgrade always has its own startedAt for duration_ms below.
     830            0 :       if (operation.downgradeToPersonal) {
     831            0 :         trackLegacyBillingEvent({
     832              :           operation: 'downgrade_to_personal',
     833              :           stage: 'succeeded',
     834              :           outcome: 'success',
     835              :           member_removal_count:
     836              :             operation.downgradeToPersonal.memberRemovalCount,
     837              :           member_removal_failures:
     838              :             operation.downgradeToPersonal.memberRemovalFailures,
     839              :           target_tier: operation.downgradeToPersonal.targetTier,
     840              :           duration_ms: now - operation.downgradeToPersonal.startedAt
     841              :         })
     842              :       }
     843              : 
     844            0 :       if (operation.type === 'retention') return
     845              : 
     846            0 :       const capabilities = useBillingCapabilities()
     847            0 :       if (operation.type === 'subscription') {
     848            0 :         await Promise.allSettled([
     849              :           refreshBilling('subscription'),
     850              :           capabilities.refresh()
     851              :         ])
     852              :       } else {
     853            0 :         await Promise.allSettled([
     854              :           refreshBilling('account'),
     855              :           capabilities.refresh()
     856              :         ])
     857              :       }
     858              : 
     859            0 :       if (operation.type === 'cancel') {
     860            0 :         if (operation.workspaceId) {
     861            0 :           useWorkspaceBillingStateStore().updateSummary(operation.workspaceId, {
     862              :             isSubscribed: false
     863              :           })
     864              :         }
     865            0 :         return
     866              :       }
     867              : 
     868              :       // A subscription checkout shows its own success step in the pricing dialog,
     869              :       // so leave it open. Top-ups have no such step: close and surface settings.
     870            0 :       if (operation.type === 'topup') {
     871            0 :         useDialogStore().closeDialog({ key: 'top-up-credits' })
     872            0 :         useSettingsDialog().show(isCloud ? 'workspace' : 'credits')
     873              :       }
     874              : 
     875            0 :       const messageKey =
     876              :         operation.type === 'subscription'
     877              :           ? 'billingOperation.subscriptionSuccess'
     878              :           : 'billingOperation.topupSuccess'
     879              : 
     880            0 :       toast.success(t(messageKey), { duration: 5000 })
     881              :     } catch (error) {
     882            0 :       reportError(error, {
     883              :         surface: 'billing',
     884              :         errorType: 'failure_handling_billing_operation_success',
     885              :         context: { billing_op_id: opId }
     886              :       })
     887            0 :       throw error
     888              :     } finally {
     889            0 :       resolveTerminal(opId)
     890              :     }
     891              :   }
     892              : 
     893            0 :   function handleFailure(
     894              :     opId: string,
     895              :     errorMessage: string | null,
     896              :     recovery?: FailureRecovery
     897              :   ) {
     898            0 :     const operation = operations.value.get(opId)
     899            0 :     if (!operation) return
     900              : 
     901            0 :     const superseded = errorMessage === CHECKOUT_SUPERSEDED_REASON
     902            0 :     const defaultMessage = failureMessage(operation.type)
     903              :     // A recovery action describes a card the customer must re-present. An
     904              :     // operation that never charges one — a cancellation, a downgrade — cannot
     905              :     // be recovered that way whatever the server reports.
     906            0 :     const chargesACard =
     907              :       isPaymentOperation(operation.type) && !operation.downgradeToPersonal
     908            0 :     const detail = billingFailureDetail(
     909              :       operation.type,
     910              :       errorMessage,
     911              :       chargesACard ? recovery : undefined
     912              :     )
     913              : 
     914            0 :     updateOperationStatus(opId, 'failed', detail ?? defaultMessage)
     915            0 :     cleanup(opId)
     916              : 
     917            0 :     const now = Date.now()
     918            0 :     const failureCategory = superseded
     919              :       ? 'stale_operation'
     920              :       : categorizePollFailure(
     921              :           operation.type,
     922              :           errorMessage,
     923              :           Boolean(operation.downgradeToPersonal)
     924              :         )
     925            0 :     trackLegacyBillingEvent({
     926              :       operation: 'operation',
     927              :       stage: 'failed',
     928              :       outcome: 'failure',
     929              :       billing_op_id: opId,
     930              :       operation_type: operation.type,
     931              :       tier: operation.tier,
     932              :       cycle: operation.cycle,
     933              :       checkout_type: operation.checkoutType,
     934              :       payment_intent_source: operation.paymentIntentSource,
     935              :       failure_category: failureCategory,
     936              :       duration_ms: now - operation.operationStartedAt
     937              :     })
     938            0 :     if (
     939              :       operation.type === 'subscription' &&
     940              :       operation.businessAttemptStartedAt !== undefined
     941              :     ) {
     942            0 :       trackLegacyBillingEvent({
     943              :         operation: 'subscription_checkout',
     944              :         stage: 'failed',
     945              :         outcome: 'failure',
     946              :         tier: operation.tier,
     947              :         cycle: operation.cycle,
     948              :         checkout_type: operation.checkoutType,
     949              :         payment_intent_source: operation.paymentIntentSource,
     950              :         billing_op_id: opId,
     951              :         failure_category: failureCategory,
     952              :         duration_ms: now - operation.businessAttemptStartedAt
     953              :       })
     954            0 :     } else if (
     955              :       operation.type === 'topup' &&
     956              :       operation.businessAttemptStartedAt !== undefined
     957              :     ) {
     958            0 :       trackLegacyBillingEvent({
     959              :         operation: 'topup',
     960              :         stage: 'failed',
     961              :         outcome: 'failure',
     962              :         billing_op_id: opId,
     963              :         payment_intent_source: operation.paymentIntentSource,
     964              :         failure_category: failureCategory,
     965              :         duration_ms: now - operation.businessAttemptStartedAt
     966              :       })
     967              :     }
     968            0 :     if (operation.downgradeToPersonal) {
     969            0 :       trackLegacyBillingEvent({
     970              :         operation: 'downgrade_to_personal',
     971              :         stage: 'failed',
     972              :         outcome: 'failure',
     973              :         member_removal_count: operation.downgradeToPersonal.memberRemovalCount,
     974              :         member_removal_failures:
     975              :           operation.downgradeToPersonal.memberRemovalFailures,
     976              :         target_tier: operation.downgradeToPersonal.targetTier,
     977              :         failure_category: failureCategory,
     978              :         duration_ms: now - operation.downgradeToPersonal.startedAt
     979              :       })
     980              :     }
     981              : 
     982            0 :     if (isPaymentOperation(operation.type) && !superseded) {
     983            0 :       toast.error(defaultMessage, {
     984              :         description: detail ?? undefined,
     985              :         duration: 7000
     986              :       })
     987              :     }
     988              : 
     989            0 :     resolveTerminal(opId)
     990              :   }
     991              : 
     992            0 :   function handleReconciliationNeeded(opId: string) {
     993            0 :     const operation = operations.value.get(opId)
     994            0 :     if (!operation) return
     995            0 :     updateOperation(opId, {
     996              :       status: 'reconciliation_needed',
     997              :       authenticationState: 'reconciliation_needed',
     998              :       canRetryAuthentication: false,
     999              :       isAuthenticating: false,
    1000              :       errorMessage: null,
    1001              :       actionUrl: null
    1002              :     })
    1003            0 :     cleanup(opId)
    1004              : 
    1005            0 :     const now = Date.now()
    1006            0 :     trackLegacyBillingEvent({
    1007              :       operation: 'operation',
    1008              :       stage: 'failed',
    1009              :       outcome: 'failure',
    1010              :       billing_op_id: opId,
    1011              :       operation_type: operation.type,
    1012              :       tier: operation.tier,
    1013              :       cycle: operation.cycle,
    1014              :       checkout_type: operation.checkoutType,
    1015              :       payment_intent_source: operation.paymentIntentSource,
    1016              :       failure_category: 'reconciliation_needed',
    1017              :       duration_ms: now - operation.operationStartedAt
    1018              :     })
    1019            0 :     if (
    1020              :       operation.type === 'subscription' &&
    1021              :       operation.businessAttemptStartedAt !== undefined
    1022              :     ) {
    1023            0 :       trackLegacyBillingEvent({
    1024              :         operation: 'subscription_checkout',
    1025              :         stage: 'failed',
    1026              :         outcome: 'failure',
    1027              :         tier: operation.tier,
    1028              :         cycle: operation.cycle,
    1029              :         checkout_type: operation.checkoutType,
    1030              :         payment_intent_source: operation.paymentIntentSource,
    1031              :         billing_op_id: opId,
    1032              :         failure_category: 'reconciliation_needed',
    1033              :         duration_ms: now - operation.businessAttemptStartedAt
    1034              :       })
    1035            0 :     } else if (
    1036              :       operation.type === 'topup' &&
    1037              :       operation.businessAttemptStartedAt !== undefined
    1038              :     ) {
    1039            0 :       trackLegacyBillingEvent({
    1040              :         operation: 'topup',
    1041              :         stage: 'failed',
    1042              :         outcome: 'failure',
    1043              :         billing_op_id: opId,
    1044              :         payment_intent_source: operation.paymentIntentSource,
    1045              :         failure_category: 'reconciliation_needed',
    1046              :         duration_ms: now - operation.businessAttemptStartedAt
    1047              :       })
    1048              :     }
    1049            0 :     if (operation.downgradeToPersonal) {
    1050            0 :       trackLegacyBillingEvent({
    1051              :         operation: 'downgrade_to_personal',
    1052              :         stage: 'failed',
    1053              :         outcome: 'failure',
    1054              :         member_removal_count: operation.downgradeToPersonal.memberRemovalCount,
    1055              :         member_removal_failures:
    1056              :           operation.downgradeToPersonal.memberRemovalFailures,
    1057              :         target_tier: operation.downgradeToPersonal.targetTier,
    1058              :         failure_category: 'reconciliation_needed',
    1059              :         duration_ms: now - operation.downgradeToPersonal.startedAt
    1060              :       })
    1061              :     }
    1062            0 :     resolveTerminal(opId)
    1063              :   }
    1064              : 
    1065            0 :   function handleTimeout(opId: string) {
    1066            0 :     const operation = operations.value.get(opId)
    1067            0 :     if (!operation) return
    1068              : 
    1069            0 :     const message = timeoutMessage(operation.type)
    1070              : 
    1071            0 :     updateOperationStatus(opId, 'timeout', message)
    1072            0 :     cleanup(opId)
    1073              : 
    1074            0 :     const now = Date.now()
    1075            0 :     trackLegacyBillingEvent({
    1076              :       operation: 'operation',
    1077              :       stage: 'timeout',
    1078              :       outcome: 'failure',
    1079              :       billing_op_id: opId,
    1080              :       operation_type: operation.type,
    1081              :       tier: operation.tier,
    1082              :       cycle: operation.cycle,
    1083              :       checkout_type: operation.checkoutType,
    1084              :       payment_intent_source: operation.paymentIntentSource,
    1085              :       failure_category: 'poll_timeout',
    1086              :       duration_ms: now - operation.operationStartedAt
    1087              :     })
    1088            0 :     if (
    1089              :       operation.type === 'subscription' &&
    1090              :       operation.businessAttemptStartedAt !== undefined
    1091              :     ) {
    1092            0 :       trackLegacyBillingEvent({
    1093              :         operation: 'subscription_checkout',
    1094              :         stage: 'failed',
    1095              :         outcome: 'failure',
    1096              :         tier: operation.tier,
    1097              :         cycle: operation.cycle,
    1098              :         checkout_type: operation.checkoutType,
    1099              :         payment_intent_source: operation.paymentIntentSource,
    1100              :         billing_op_id: opId,
    1101              :         failure_category: 'poll_timeout',
    1102              :         duration_ms: now - operation.businessAttemptStartedAt
    1103              :       })
    1104            0 :     } else if (
    1105              :       operation.type === 'topup' &&
    1106              :       operation.businessAttemptStartedAt !== undefined
    1107              :     ) {
    1108            0 :       trackLegacyBillingEvent({
    1109              :         operation: 'topup',
    1110              :         stage: 'failed',
    1111              :         outcome: 'failure',
    1112              :         billing_op_id: opId,
    1113              :         payment_intent_source: operation.paymentIntentSource,
    1114              :         failure_category: 'poll_timeout',
    1115              :         duration_ms: now - operation.businessAttemptStartedAt
    1116              :       })
    1117              :     }
    1118            0 :     if (operation.downgradeToPersonal) {
    1119            0 :       trackLegacyBillingEvent({
    1120              :         operation: 'downgrade_to_personal',
    1121              :         stage: 'failed',
    1122              :         outcome: 'failure',
    1123              :         member_removal_count: operation.downgradeToPersonal.memberRemovalCount,
    1124              :         member_removal_failures:
    1125              :           operation.downgradeToPersonal.memberRemovalFailures,
    1126              :         target_tier: operation.downgradeToPersonal.targetTier,
    1127              :         failure_category: 'poll_timeout',
    1128              :         duration_ms: now - operation.downgradeToPersonal.startedAt
    1129              :       })
    1130              :     }
    1131              : 
    1132            0 :     if (isPaymentOperation(operation.type)) {
    1133            0 :       toast.error(message)
    1134              :     }
    1135              : 
    1136            0 :     resolveTerminal(opId)
    1137              :   }
    1138              : 
    1139              :   /**
    1140              :    * No caught JS error here — only the backend's free-form `error_message`, if
    1141              :    * any. `cancel` and zero-payment operations (e.g. downgrade-to-personal,
    1142              :    * which removes members / changes tier but never touches a card) can't be a
    1143              :    * provider decline, so they're always an api rejection. For payment-bearing
    1144              :    * `subscription`/`topup` polls, a message naming a connectivity/system
    1145              :    * failure isn't a decline either; only fall back to `provider_decline` when
    1146              :    * the backend gave no more specific signal.
    1147              :    */
    1148            0 :   function categorizePollFailure(
    1149              :     type: OperationType,
    1150              :     errorMessage: string | null,
    1151              :     isZeroPaymentOperation: boolean
    1152              :   ): BillingTelemetryFailure['failure_category'] {
    1153            0 :     if (!isPaymentOperation(type) || isZeroPaymentOperation)
    1154            0 :       return 'api_rejected'
    1155              : 
    1156            0 :     if (errorMessage && /network|connection|unreachable/i.test(errorMessage)) {
    1157            0 :       return 'network'
    1158              :     }
    1159              : 
    1160            0 :     return 'provider_decline'
    1161              :   }
    1162              : 
    1163            0 :   function failureMessage(type: OperationType) {
    1164            0 :     if (type === 'retention') return t('subscription.retentionOffer.failed')
    1165            0 :     if (type === 'subscription') return t('billingOperation.subscriptionFailed')
    1166            0 :     if (type === 'topup') return t('billingOperation.topupFailed')
    1167            0 :     return t('billingOperation.cancelFailed')
    1168              :   }
    1169              : 
    1170            0 :   function billingFailureDetail(
    1171              :     type: OperationType,
    1172              :     errorMessage: string | null,
    1173              :     recovery?: FailureRecovery
    1174              :   ) {
    1175            0 :     const detailKey = errorMessage && FAILURE_DETAIL_KEYS.get(errorMessage)
    1176            0 :     if (detailKey) return t(detailKey)
    1177            0 :     if (
    1178              :       errorMessage === 'subscribe_method_not_chargeable_off_session' &&
    1179              :       recovery
    1180              :     ) {
    1181            0 :       return t('billingOperation.methodNotChargeableOffSessionDetail')
    1182              :     }
    1183            0 :     if (recovery?.action === 'authenticate_payment') {
    1184            0 :       return t(
    1185              :         recovery.retryable === false
    1186              :           ? 'billingOperation.authenticatePaymentBlockedDetail'
    1187              :           : 'billingOperation.authenticatePaymentDetail'
    1188              :       )
    1189              :     }
    1190            0 :     if (type === 'subscription')
    1191            0 :       return t('billingOperation.subscriptionFailedDetail')
    1192            0 :     if (type === 'topup' && errorMessage) return t('credits.topUp.unknownError')
    1193            0 :     return errorMessage
    1194              :   }
    1195              : 
    1196            0 :   function timeoutMessage(type: OperationType) {
    1197            0 :     if (type === 'retention')
    1198            0 :       return t('subscription.retentionOffer.unconfirmed')
    1199            0 :     if (type === 'subscription')
    1200            0 :       return t('billingOperation.subscriptionTimeout')
    1201            0 :     if (type === 'topup') return t('billingOperation.topupTimeout')
    1202            0 :     return t('billingOperation.cancelTimeout')
    1203              :   }
    1204              : 
    1205            0 :   function resolveTerminal(opId: string) {
    1206            0 :     const resolve = terminalResolvers.get(opId)
    1207            0 :     const operation = operations.value.get(opId)
    1208            0 :     if (resolve && operation) {
    1209            0 :       resolve(operation)
    1210              :     }
    1211            0 :     terminalResolvers.delete(opId)
    1212            0 :     terminalPromises.delete(opId)
    1213              :   }
    1214              : 
    1215            0 :   function updateOperationStatus(
    1216              :     opId: string,
    1217              :     status: OperationStatus,
    1218              :     errorMessage: string | null
    1219              :   ) {
    1220            0 :     const operation = operations.value.get(opId)
    1221            0 :     if (!operation) return
    1222              : 
    1223            0 :     const updated = {
    1224              :       ...operation,
    1225              :       status,
    1226              :       errorMessage,
    1227              :       actionUrl: null,
    1228              :       paymentMethodUrl: null,
    1229              :       authenticationState: null,
    1230              :       canRetryAuthentication: false,
    1231              :       isAuthenticating: false
    1232              :     }
    1233            0 :     operations.value = new Map(operations.value).set(opId, updated)
    1234              :   }
    1235              : 
    1236            0 :   function cleanup(opId: string) {
    1237            0 :     const timeoutId = timeouts.get(opId)
    1238            0 :     if (timeoutId) {
    1239            0 :       clearTimeout(timeoutId)
    1240            0 :       timeouts.delete(opId)
    1241              :     }
    1242            0 :     intervals.delete(opId)
    1243            0 :     waitingWithoutActionSince.delete(opId)
    1244            0 :     progressToastsAwaitingFirstRead.delete(opId)
    1245            0 :     dismissedProgressToasts.delete(opId)
    1246              : 
    1247            0 :     const progressToast = progressToasts.get(opId)
    1248            0 :     if (progressToast) {
    1249            0 :       toast.dismiss(progressToast.id)
    1250            0 :       progressToasts.delete(opId)
    1251              :     }
    1252              :   }
    1253              : 
    1254            0 :   function clearOperation(opId: string) {
    1255            0 :     cleanup(opId)
    1256            0 :     generations.delete(opId)
    1257            0 :     const newMap = new Map(operations.value)
    1258            0 :     newMap.delete(opId)
    1259            0 :     operations.value = newMap
    1260            0 :     terminalResolvers.delete(opId)
    1261            0 :     terminalPromises.delete(opId)
    1262              :   }
    1263              : 
    1264              :   // Unlike clearOperation, this keeps the operation live: polling continues
    1265              :   // and a late success or failure still resolves normally. It only removes
    1266              :   // the operation from the selectors a dialog reads, since whether the
    1267              :   // customer wants to see it is a view concern — whether it is over is not.
    1268              :   // A server-side cancel (BE-10064/BE-11559) would let a dismissal actually
    1269              :   // end the operation instead of merely hiding it; call that here once it
    1270              :   // exists.
    1271            0 :   function dismissOperation(opId: string) {
    1272            0 :     updateOperation(opId, { dismissed: true })
    1273              :   }
    1274              : 
    1275         2355 :   return {
    1276              :     operations,
    1277              :     hasPendingOperations,
    1278              :     isSettingUp,
    1279              :     isAddingCredits,
    1280              :     subscriptionActionOperation,
    1281              :     topupActionOperation,
    1282              :     getOperation,
    1283              :     startOperation,
    1284              :     clearOperation,
    1285              :     dismissOperation
    1286              :   }
    1287              : })
        

Generated by: LCOV version 2.0-1