LCOV - code coverage report
Current view: top level - src/platform/billing/sdk - subscriptionOperationView.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 10.6 % 47 5
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * Projections from the SDK's subscription results onto what the workspace
       3              :  * billing adapter already does with the legacy calls: succeed, throw a
       4              :  * `WorkspaceApiError`, or hand the action back so the legacy call runs.
       5              :  *
       6              :  * A 404 is the third case. The backend gate on these routes is independent of
       7              :  * the client flag, so a rail that is on before the routes are deployed must
       8              :  * leave the customer on the path that still works.
       9              :  */
      10              : import type {
      11              :   BillingClient,
      12              :   BillingTelemetryFailure,
      13              :   CancelOperationResult,
      14              :   PaymentPortalResult,
      15              :   PreviewSubscribeInput,
      16              :   PreviewSubscribeResult,
      17              :   SubscribeInput,
      18              :   SubscriptionCommandFailure,
      19              :   SubscriptionCommandOutcome,
      20              :   SubscriptionCommandResult
      21              : } from '@comfyorg/account-core/billing'
      22              : import { failureCategoryFor } from '@comfyorg/account-core/billing'
      23              : 
      24              : import { t } from '@/i18n'
      25              : import type {
      26              :   PreviewSubscribeResponse,
      27              :   SubscribeResponse
      28              : } from '@comfyorg/billing-core'
      29              : import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError'
      30              : 
      31              : import { declineDetail } from './topupOperationView'
      32              : 
      33              : /** False only when the server said the state already held: no operation was issued, so the lifecycle reported nothing. */
      34              : export interface SettledCommand {
      35              :   readonly operationObserved: boolean
      36              : }
      37              : 
      38              : /**
      39              :  * A subscribe response as the checkout reads it. `requiredPayment` is set only
      40              :  * by the SDK rail, where `status` is always the settled `subscribed`: it says
      41              :  * whether the server had to take a payment from the customer to get there.
      42              :  * The legacy path leaves it unset — there a `subscribed` response is a plan
      43              :  * that was already active, and the poller it never started is what drew the
      44              :  * same line. `operationObserved` is set on the same rail, for the same reason
      45              :  * as on `SettledCommand`.
      46              :  */
      47              : export interface SettledSubscribeResponse
      48              :   extends SubscribeResponse, Partial<SettledCommand> {
      49              :   readonly requiredPayment?: boolean
      50              : }
      51              : 
      52              : /** The lifecycle drove the operation to a failed terminal and reported it; a refused attempt stays a plain `WorkspaceApiError` for the caller to report. */
      53         2356 : export class SettledOperationError extends WorkspaceApiError {
      54              :   constructor(
      55              :     message: string,
      56              :     phase: string,
      57            0 :     readonly billingOpId: string | undefined,
      58              :     failureCategory?: BillingTelemetryFailure['failure_category']
      59              :   ) {
      60            0 :     super(message, undefined, phase, failureCategory)
      61            0 :     this.name = 'SettledOperationError'
      62              :   }
      63              : }
      64              : 
      65              : import type { BillingOperationRecordView } from './operationRecordView'
      66              : 
      67              : /** The client a subscription action issued now runs on: the rail while its routes serve, else the legacy call. */
      68            0 : export function billingClientOf(rail: SubscriptionRail | null): BillingClient {
      69            0 :   return rail?.subscriptionRouteAvailable ? 'sdk' : 'legacy'
      70              : }
      71              : 
      72              : export type SubscriptionRailOutcome<T = void> =
      73              :   | { readonly status: 'ok'; readonly value: T }
      74              :   | { readonly status: 'error'; readonly error: Error }
      75              :   /** The route is not deployed here; the caller runs its legacy path. */
      76              :   | { readonly status: 'unavailable' }
      77              : 
      78              : /**
      79              :  * The subscription actions the host routes through the SDK. Cancel and
      80              :  * resubscribe report only whether they settled; the portal hands back the URL
      81              :  * the host opens; subscribe and its quote hand back the bodies the checkout
      82              :  * already reads.
      83              :  */
      84              : export interface SubscriptionRail {
      85              :   /**
      86              :    * The hosted step a subscribe on this rail is parked on, or null. The rail
      87              :    * opens it once itself, so this is what the checkout puts behind a button
      88              :    * when the browser blocked that open.
      89              :    */
      90              :   readonly subscriptionActionUrl: string | null
      91              :   /**
      92              :    * The subscribe waiting on the customer, as the poller's record. The checkout
      93              :    * drives its parked-recovery prompt, its authentication state and its busy
      94              :    * state off this, so on this rail it has to come from the lifecycle.
      95              :    */
      96              :   readonly subscriptionActionOperation: BillingOperationRecordView | undefined
      97              :   /** False once this tab's backend answered that the routes are not deployed. */
      98              :   readonly subscriptionRouteAvailable: boolean
      99              :   /** One operation by id, unscoped: the caller compares the workspace itself. */
     100              :   getOperation: (opId: string) => BillingOperationRecordView | undefined
     101              :   /** `callerStarted`: the caller reported `started`, so the rail reports only the terminal. */
     102              :   subscribe: (
     103              :     input: SubscribeInput,
     104              :     options?: { readonly callerStarted?: boolean }
     105              :   ) => Promise<SubscriptionRailOutcome<SettledSubscribeResponse>>
     106              :   previewSubscribe: (
     107              :     input: PreviewSubscribeInput
     108              :   ) => Promise<SubscriptionRailOutcome<PreviewSubscribeResponse>>
     109              :   cancelSubscription: () => Promise<SubscriptionRailOutcome<SettledCommand>>
     110              :   resubscribe: () => Promise<SubscriptionRailOutcome<SettledCommand>>
     111              :   openPaymentPortal: (
     112              :     returnUrl: string
     113              :   ) => Promise<SubscriptionRailOutcome<string>>
     114              :   /** Asks the server to drop a pending payment it reported `cancelable`. */
     115              :   cancelOperation: (opId: string) => Promise<SubscriptionRailOutcome>
     116              : }
     117              : 
     118         2356 : const UNAVAILABLE = { status: 'unavailable' } as const
     119              : 
     120         2356 : const OBSERVED: SubscriptionRailOutcome<SettledCommand> = {
     121              :   status: 'ok',
     122              :   value: { operationObserved: true }
     123              : }
     124              : 
     125         2356 : const ALREADY_HELD: SubscriptionRailOutcome<SettledCommand> = {
     126              :   status: 'ok',
     127              :   value: { operationObserved: false }
     128              : }
     129              : 
     130              : /**
     131              :  * The failure as the adapter's own error. `serverCode` lands where the
     132              :  * adapter already keeps `WorkspaceApiError.code`, and the server's own
     133              :  * sentence is the message, as on the legacy rail.
     134              :  */
     135            0 : function projectFailure(
     136              :   failure: SubscriptionCommandFailure
     137              : ): SubscriptionRailOutcome<never> {
     138            0 :   const httpStatus = 'httpStatus' in failure ? failure.httpStatus : undefined
     139            0 :   if (httpStatus === 404) return UNAVAILABLE
     140              : 
     141              :   // Nothing failed and nothing was charged, so the generic subscription
     142              :   // failure would misread. The earlier payment is what the customer has to
     143              :   // finish, and this sentence is the only thing that says so.
     144            0 :   if (failure.code === 'OPERATION_ALREADY_PENDING') {
     145            0 :     return {
     146              :       status: 'error',
     147              :       error: new WorkspaceApiError(
     148              :         t('billingOperation.operationAlreadyPendingDetail'),
     149              :         undefined,
     150              :         failure.code
     151              :       )
     152              :     }
     153              :   }
     154              : 
     155            0 :   const serverCode = 'serverCode' in failure ? failure.serverCode : undefined
     156            0 :   const serverMessage =
     157              :     'serverMessage' in failure ? failure.serverMessage : undefined
     158            0 :   return {
     159              :     status: 'error',
     160              :     error: new WorkspaceApiError(
     161              :       serverMessage ?? t('billingOperation.subscriptionFailedDetail'),
     162              :       httpStatus,
     163              :       serverCode ?? failure.code
     164              :     )
     165              :   }
     166              : }
     167              : 
     168            0 : function unsuccessfulSettleDetail({
     169              :   operation,
     170              :   phase
     171              : }: SubscriptionCommandOutcome): string {
     172            0 :   if (operation?.phase === 'failed')
     173            0 :     return declineDetail(operation.declineReason)
     174            0 :   if (phase === 'timed_out')
     175            0 :     return t(
     176              :       operation?.kind === 'cancel'
     177              :         ? 'billingOperation.cancelTimeout'
     178              :         : 'billingOperation.subscriptionTimeout'
     179              :     )
     180            0 :   return t('billingOperation.subscriptionFailedDetail')
     181              : }
     182              : 
     183            0 : function projectUnsuccessfulSettle(
     184              :   outcome: SubscriptionCommandOutcome
     185              : ): SubscriptionRailOutcome<never> {
     186            0 :   const { operation, phase } = outcome
     187            0 :   return {
     188              :     status: 'error',
     189              :     error: new SettledOperationError(
     190              :       unsuccessfulSettleDetail(outcome),
     191              :       phase,
     192              :       operation?.id,
     193              :       operation && failureCategoryFor(operation)
     194              :     )
     195              :   }
     196              : }
     197              : 
     198              : /**
     199              :  * A command that settled anywhere but `succeeded` failed for the customer,
     200              :  * exactly as a poller operation that ends in any other status does. A success
     201              :  * with no operation is the server saying the state already held.
     202              :  */
     203            0 : export function projectSubscriptionResult(
     204              :   result: SubscriptionCommandResult
     205              : ): SubscriptionRailOutcome<SettledCommand> {
     206            0 :   if (result.status === 'error') return projectFailure(result)
     207            0 :   const { phase, operation } = result.value
     208            0 :   if (phase !== 'succeeded') return projectUnsuccessfulSettle(result.value)
     209            0 :   return operation === undefined ? ALREADY_HELD : OBSERVED
     210              : }
     211              : 
     212              : /**
     213              :  * A settled subscribe as the body `handleSubscribeResponse` already handles.
     214              :  * The SDK waits for the operation, so by the time this projects there is
     215              :  * nothing left to poll: the status is always the settled `subscribed`, never
     216              :  * the response's `needs_payment_method` or `pending_payment`, both of which
     217              :  * the lifecycle drove to a conclusion first. `issuedStatus` is what the
     218              :  * server answered before that, so `requiredPayment` keeps the line the legacy
     219              :  * poller drew: it watched — and so counted and announced — exactly the
     220              :  * subscribes the server could not activate on the spot. An adopted operation
     221              :  * carries no issued status and is one the server was still settling, which is
     222              :  * the same side of that line.
     223              :  *
     224              :  * An outcome carries no operation only when the server answered that the
     225              :  * requested state already held, which subscribe never reaches: the route
     226              :  * documents no already-held code.
     227              :  */
     228            0 : export function projectSubscribeResult(
     229              :   result: SubscriptionCommandResult
     230              : ): SubscriptionRailOutcome<SettledSubscribeResponse> {
     231            0 :   if (result.status === 'error') return projectFailure(result)
     232            0 :   const { phase, operation, issuedStatus } = result.value
     233            0 :   if (phase !== 'succeeded' || operation === undefined) {
     234            0 :     return projectUnsuccessfulSettle(result.value)
     235              :   }
     236            0 :   return {
     237              :     status: 'ok',
     238              :     value: {
     239              :       billing_op_id: operation.id,
     240              :       status: 'subscribed',
     241              :       requiredPayment: issuedStatus !== 'subscribed',
     242              :       operationObserved: true
     243              :     }
     244              :   }
     245              : }
     246              : 
     247            0 : export function projectPreviewSubscribeResult(
     248              :   result: PreviewSubscribeResult
     249              : ): SubscriptionRailOutcome<PreviewSubscribeResponse> {
     250            0 :   return result.status === 'error'
     251              :     ? projectFailure(result)
     252              :     : { status: 'ok', value: result.value }
     253              : }
     254              : 
     255            0 : export function projectPaymentPortalResult(
     256              :   result: PaymentPortalResult
     257              : ): SubscriptionRailOutcome<string> {
     258            0 :   if (result.status === 'error') return projectFailure(result)
     259            0 :   return { status: 'ok', value: result.value.url }
     260              : }
     261              : 
     262         2356 : const CANCEL_REFUSAL_COPY = {
     263              :   NOT_CANCELABLE: 'billingOperation.cancelPaymentNotCancelable',
     264              :   PAYMENT_IN_FLIGHT: 'billingOperation.cancelPaymentInFlight'
     265              : } as const
     266              : 
     267              : /**
     268              :  * A cancel the server took is done: the lifecycle it woke re-reads the
     269              :  * operation and settles it. Anything else reads as our own copy; the
     270              :  * server's text stays diagnostic.
     271              :  */
     272            0 : export function projectCancelOperationResult(
     273              :   result: CancelOperationResult
     274              : ): SubscriptionRailOutcome {
     275            0 :   if (result.status !== 'not_canceled' && result.status !== 'error')
     276            0 :     return { status: 'ok', value: undefined }
     277            0 :   return {
     278              :     status: 'error',
     279              :     error: new WorkspaceApiError(
     280              :       t(
     281              :         result.status === 'not_canceled'
     282              :           ? CANCEL_REFUSAL_COPY[result.code]
     283              :           : 'billingOperation.cancelPaymentFailed'
     284              :       ),
     285              :       'httpStatus' in result ? result.httpStatus : undefined,
     286              :       result.code
     287              :     )
     288              :   }
     289              : }
        

Generated by: LCOV version 2.0-1