Line data Source code
1 : /**
2 : * One billing operation as the SDK sees it: a discriminated union over the
3 : * lifecycle a `billing_op_id` moves through, and the pure transition that
4 : * advances it. The identity is fixed at adoption and survives every
5 : * presentation change, so switching a checkout from the embedded challenge
6 : * to the hosted page (or back) is a transition on the same operation, never
7 : * a replacement one.
8 : *
9 : * The transition consumes the generated `BillingOpStatusResponse`. It reads
10 : * the coded `decline_reason` and `recovery_action` and never `error_message`,
11 : * so no server or payment-provider text can reach a consumer through this
12 : * state.
13 : */
14 : import {
15 : zAcceptedAutoTopUpSettings,
16 : zBillingOpChargeBreakdown,
17 : zBillingOpChargeReason,
18 : zBillingOpReceiptPlan,
19 : zBillingOpStatusResponse,
20 : zTopUpPurchaseAmount
21 : } from '@comfyorg/ingest-types/zod'
22 : import { z } from 'zod'
23 :
24 : import type { BillingScope } from './billingScope'
25 : import { SubscriptionDiscountSchema } from './subscriptionDiscount'
26 : import { wireCents } from './wireCents'
27 :
28 2356 : const ChargeBreakdownSchema = zBillingOpChargeBreakdown.extend({
29 : amount_charged_cents: wireCents,
30 : reasons: z.array(
31 : zBillingOpChargeReason.extend({
32 : amount_cents: wireCents,
33 : discount: SubscriptionDiscountSchema.optional()
34 : })
35 : )
36 : })
37 :
38 2356 : const ReceiptPlanSchema = zBillingOpReceiptPlan.extend({
39 : price_cents: wireCents.optional(),
40 : monthly_price_cents: wireCents.optional()
41 : })
42 :
43 2356 : export const BillingOpStatusSchema = zBillingOpStatusResponse.extend({
44 : amount_charged_cents: wireCents.optional(),
45 : auto_top_up: zAcceptedAutoTopUpSettings
46 : .extend({
47 : monthly_budget_cents: wireCents,
48 : target_credits: wireCents,
49 : threshold_credits: wireCents
50 : })
51 : .optional(),
52 : credits_added: wireCents.optional(),
53 : charge_breakdown: ChargeBreakdownSchema.optional(),
54 : plan: ReceiptPlanSchema.optional(),
55 : topup_purchase_amount: zTopUpPurchaseAmount
56 : .extend({ amount_cents: wireCents })
57 : .optional()
58 : })
59 :
60 : export type BillingOpStatus = z.infer<typeof BillingOpStatusSchema>
61 :
62 : export type BillingChargeBreakdown = NonNullable<
63 : BillingOpStatus['charge_breakdown']
64 : >
65 : export type BillingChargeReason = BillingChargeBreakdown['reasons'][number]
66 :
67 : export type BillingOperationKind = 'subscription' | 'topup' | 'cancel'
68 :
69 : /**
70 : * The plan the server reports an operation is for, in every status of a plan
71 : * change, initial subscription or resubscribe. Its tier and prices are absent
72 : * when the server cannot describe the plan.
73 : */
74 : export type BillingOperationPlan = NonNullable<BillingOpStatus['plan']>
75 :
76 : /**
77 : * Where the customer completes the operation: the challenge this tab drives
78 : * through the host's payment-provider adapter, or the page behind the
79 : * server's `action_url`.
80 : */
81 : export type BillingPresentation = 'embedded' | 'hosted'
82 :
83 : /**
84 : * Which origin serves a hosted presentation: the provider page behind the
85 : * server's `action_url`, or the hosted billing app.
86 : */
87 : export type HostedBillingDestination = 'stripe' | 'billing_web'
88 :
89 : export type BillingDeclineReason = NonNullable<
90 : BillingOpStatus['decline_reason']
91 : >
92 : export type BillingRecoveryAction = NonNullable<
93 : BillingOpStatus['recovery_action']
94 : >
95 : export type BillingAuthenticationState = NonNullable<
96 : BillingOpStatus['authentication_state']
97 : >
98 : export type BillingOperationServerPhase = NonNullable<BillingOpStatus['phase']>
99 :
100 : /**
101 : * The phases the contract defines as blocked on the customer. Neither advances
102 : * on its own, so an operation reporting one waits on them even before it has a
103 : * link to offer.
104 : */
105 0 : export function isBlockedOnCustomerPhase(
106 : phase: BillingOperationServerPhase | null | undefined
107 : ): boolean {
108 0 : return (
109 : phase === 'awaiting_payment_method' || phase === 'awaiting_invoice_payment'
110 : )
111 : }
112 :
113 : export type BillingPresentationState =
114 : | { readonly presentation: 'embedded'; readonly hostedDestination?: never }
115 : | {
116 : readonly presentation: 'hosted'
117 : readonly hostedDestination: HostedBillingDestination
118 : }
119 :
120 : export type BillingOperationIdentity = BillingPresentationState & {
121 : readonly id: string
122 : readonly kind: BillingOperationKind
123 : readonly scope: BillingScope
124 : /** When this tab began observing the operation; the poll budget counts from here. */
125 : readonly observedAt: number
126 : /** When the attempt began, before the command was issued; telemetry durations count from here. */
127 : readonly attemptStartedAt: number
128 : /**
129 : * This tab issued the operation and was still waiting on its outcome when
130 : * it adopted it: from its own command, or after a reload or a return from
131 : * a provider page. Absent for an operation another tab issued, and for one
132 : * this tab already saw succeed.
133 : */
134 : readonly awaitedHere?: true
135 : }
136 :
137 : /**
138 : * The in-page challenge for an embedded presentation. `completed` and
139 : * `failed` are this tab's verdicts and outrank a server echo of the same
140 : * challenge, so the presentation neither flaps back to "verify" after a
141 : * failure nor reopens the pay step mid-payment after a success.
142 : */
143 : export interface EmbeddedChallenge {
144 : readonly clientSecret: string
145 : readonly status: 'required' | 'in_progress' | 'completed' | 'failed'
146 : }
147 :
148 : export type PendingBillingOperation = BillingOperationIdentity & {
149 : readonly phase: 'pending'
150 : /** The hosted continuation the server currently offers; https only. */
151 : readonly actionUrl?: string
152 : readonly challenge?: EmbeddedChallenge
153 : readonly authenticationState?: BillingAuthenticationState
154 : /** The server's deadline for the customer's authentication, as served; absent is no claim. */
155 : readonly authenticationDeadline?: string
156 : readonly serverPhase?: BillingOperationServerPhase
157 : /** Set while the customer's last attempt was declined and they may try again. */
158 : readonly declineReason?: BillingDeclineReason
159 : readonly recoveryAction?: BillingRecoveryAction
160 : /** The server's word on whether cancelling this operation would take effect; absent is no claim. */
161 : readonly cancelable?: boolean
162 : /** True once the operation has ever waited on the customer; widens the poll budget. */
163 : readonly customerActionSeen: boolean
164 : readonly plan?: BillingOperationPlan
165 : }
166 :
167 : export type FailedBillingOperation = BillingOperationIdentity & {
168 : readonly phase: 'failed'
169 : readonly declineReason: BillingDeclineReason
170 : readonly recoveryAction?: BillingRecoveryAction
171 : readonly retryable: boolean
172 : }
173 :
174 : /**
175 : * What the server reports a succeeded operation did, for display only. Each
176 : * fact is absent while the server cannot say it: a charge billed outside a
177 : * Stripe invoice, a grant not recorded yet, or an operation that is not a
178 : * plan change.
179 : */
180 : export interface BillingOperationReceipt {
181 : readonly amountChargedCents?: number
182 : readonly chargeBreakdown?: BillingChargeBreakdown
183 : readonly creditsAdded?: number
184 : readonly plan?: BillingOperationPlan
185 : }
186 :
187 : export type SucceededBillingOperation = BillingOperationIdentity & {
188 : readonly phase: 'succeeded'
189 : readonly receipt?: BillingOperationReceipt
190 : }
191 :
192 : export type BillingOperationState =
193 : | PendingBillingOperation
194 : | SucceededBillingOperation
195 : | FailedBillingOperation
196 : /** This tab's poll budget ran out; the server may still settle the operation. */
197 : | (BillingOperationIdentity & { readonly phase: 'timed_out' })
198 : /** The server cannot settle it without a human; surface the id to support. */
199 : | (BillingOperationIdentity & { readonly phase: 'reconciliation_needed' })
200 : /**
201 : * The session or workspace changed underneath it, or the server replaced it
202 : * with a newer operation; nothing here may be attributed to this tab now.
203 : */
204 : | (BillingOperationIdentity & { readonly phase: 'superseded' })
205 :
206 : export type BillingOperationPhase = BillingOperationState['phase']
207 :
208 : export type BillingOperationEvent =
209 : | { readonly type: 'status_polled'; readonly status: BillingOpStatus }
210 : | { readonly type: 'timed_out' }
211 : | { readonly type: 'superseded' }
212 : /** The operation could not be found under this scope. */
213 : | { readonly type: 'lost' }
214 : | {
215 : readonly type: 'presentation_switched'
216 : readonly presentation: 'hosted'
217 : readonly hostedDestination: HostedBillingDestination
218 : }
219 : | {
220 : readonly type: 'presentation_switched'
221 : readonly presentation: 'embedded'
222 : }
223 : | { readonly type: 'challenge_started' }
224 : /** The server answered a resubmit with a fresh hosted step for this same operation. */
225 : | { readonly type: 'action_reissued'; readonly actionUrl: string }
226 : | {
227 : readonly type: 'challenge_settled'
228 : readonly outcome: 'completed' | 'failed'
229 : }
230 :
231 0 : export function isTerminal(
232 : state: BillingOperationState
233 : ): state is Exclude<BillingOperationState, PendingBillingOperation> {
234 0 : return state.phase !== 'pending'
235 : }
236 :
237 : /** A continuation link the SDK will hand to a host: absolute and https, nothing else. */
238 0 : export function validateActionUrl(
239 : value: string | undefined
240 : ): string | undefined {
241 0 : if (value === undefined) return undefined
242 0 : try {
243 0 : return new URL(value).protocol === 'https:' ? value : undefined
244 : } catch {
245 0 : return undefined
246 : }
247 : }
248 :
249 0 : function presentationOf(
250 : state: BillingOperationState
251 : ): BillingPresentationState {
252 0 : return state.presentation === 'hosted'
253 : ? { presentation: 'hosted', hostedDestination: state.hostedDestination }
254 : : { presentation: 'embedded' }
255 : }
256 :
257 0 : function identityOf(state: BillingOperationState): BillingOperationIdentity {
258 0 : return {
259 : id: state.id,
260 : kind: state.kind,
261 : scope: state.scope,
262 : observedAt: state.observedAt,
263 : attemptStartedAt: state.attemptStartedAt,
264 : ...(state.awaitedHere ? { awaitedHere: true } : {}),
265 : ...presentationOf(state)
266 : }
267 : }
268 :
269 0 : function withPhase<
270 : P extends Exclude<BillingOperationPhase, 'pending' | 'failed'>
271 : >(
272 : state: BillingOperationState,
273 : phase: P
274 : ): BillingOperationIdentity & { readonly phase: P } {
275 0 : return { ...identityOf(state), phase }
276 : }
277 :
278 : /**
279 : * The server's `requires_action` is an echo of a challenge this tab already
280 : * settled when it names the same client secret (or none). The tab's verdict
281 : * stands until the intent actually moves.
282 : */
283 0 : function echoesSettledChallenge(
284 : state: PendingBillingOperation,
285 : status: BillingOpStatus
286 : ): boolean {
287 0 : const challenge = state.challenge
288 0 : if (challenge === undefined) return false
289 0 : if (status.authentication_state !== 'requires_action') return false
290 0 : if (challenge.status !== 'completed' && challenge.status !== 'failed') {
291 0 : return false
292 : }
293 0 : return (
294 : status.payment_intent_client_secret === undefined ||
295 : status.payment_intent_client_secret === challenge.clientSecret
296 : )
297 : }
298 :
299 0 : function nextChallenge(
300 : state: PendingBillingOperation,
301 : status: BillingOpStatus
302 : ): EmbeddedChallenge | undefined {
303 0 : const secret = status.payment_intent_client_secret
304 0 : if (secret === undefined) return state.challenge
305 0 : if (state.challenge?.clientSecret === secret) return state.challenge
306 0 : if (state.presentation !== 'embedded') return undefined
307 0 : if (status.authentication_state !== 'requires_action') return state.challenge
308 0 : return { clientSecret: secret, status: 'required' }
309 : }
310 :
311 0 : function terminalFromStatus(
312 : state: PendingBillingOperation,
313 : status: BillingOpStatus
314 : ): BillingOperationState | undefined {
315 0 : if (status.status === 'succeeded') return succeeded(state, status)
316 0 : if (status.status === 'failed') {
317 0 : return {
318 : ...identityOf(state),
319 : phase: 'failed',
320 : declineReason: status.decline_reason ?? 'generic',
321 : ...(status.recovery_action === undefined
322 : ? {}
323 : : { recoveryAction: status.recovery_action }),
324 : retryable: status.retryable === true
325 : }
326 : }
327 0 : if (
328 : status.status === 'reconciliation_needed' ||
329 : status.authentication_state === 'reconciliation_needed'
330 : ) {
331 0 : return withPhase(state, 'reconciliation_needed')
332 : }
333 : return undefined
334 : }
335 :
336 0 : function receiptOf(
337 : status: BillingOpStatus
338 : ): BillingOperationReceipt | undefined {
339 0 : const receipt: BillingOperationReceipt = {
340 : ...(status.amount_charged_cents === undefined
341 : ? {}
342 : : { amountChargedCents: status.amount_charged_cents }),
343 : ...(status.charge_breakdown === undefined
344 : ? {}
345 : : { chargeBreakdown: status.charge_breakdown }),
346 : ...(status.credits_added === undefined
347 : ? {}
348 : : { creditsAdded: status.credits_added }),
349 : ...(status.plan === undefined ? {} : { plan: status.plan })
350 : }
351 0 : return Object.keys(receipt).length === 0 ? undefined : receipt
352 : }
353 :
354 0 : function succeeded(
355 : state: BillingOperationState,
356 : status: BillingOpStatus
357 : ): SucceededBillingOperation {
358 0 : const receipt = receiptOf(status)
359 0 : return {
360 : ...withPhase(state, 'succeeded'),
361 : ...(receipt === undefined ? {} : { receipt })
362 : }
363 : }
364 :
365 : /**
366 : * The charge went through and the server has not recorded its credits yet;
367 : * reading the operation again fills them in.
368 : */
369 0 : export function isGrantLanding(state: BillingOperationState): boolean {
370 0 : return (
371 : state.phase === 'succeeded' &&
372 : state.receipt?.amountChargedCents !== undefined &&
373 : state.receipt.creditsAdded === undefined
374 : )
375 : }
376 :
377 : /**
378 : * A link echoed while this tab's completed challenge is still processing
379 : * points at that same challenge; surfacing it would ask the customer to
380 : * redo a step they just finished. A checkout waiting on a card keeps the
381 : * link a resubmit reissued, because the server stores none for that phase.
382 : */
383 0 : function nextActionUrl(
384 : state: PendingBillingOperation,
385 : status: BillingOpStatus,
386 : authenticationState: BillingAuthenticationState | undefined
387 : ): string | undefined {
388 0 : if (
389 : state.challenge?.status === 'completed' &&
390 : authenticationState !== 'requires_action'
391 : ) {
392 0 : return state.actionUrl
393 : }
394 0 : const served = validateActionUrl(status.action_url)
395 0 : return served === undefined && status.phase === 'awaiting_payment_method'
396 : ? state.actionUrl
397 : : served
398 : }
399 :
400 : /**
401 : * A retryable failure served without a reason reads as `generic`, as a
402 : * terminal failure does, so the customer is offered the retry the state
403 : * promises. A challenge this tab saw fail supplies its own reason.
404 : */
405 0 : function nextDeclineReason(
406 : state: PendingBillingOperation,
407 : status: BillingOpStatus,
408 : authenticationState: BillingAuthenticationState | undefined
409 : ): BillingDeclineReason | undefined {
410 0 : if (authenticationState !== 'failed_retryable') return undefined
411 0 : const known = status.decline_reason ?? state.declineReason
412 0 : if (known !== undefined || state.challenge?.status === 'failed') return known
413 0 : return 'generic'
414 : }
415 :
416 0 : function nextAuthenticationDeadline(
417 : state: PendingBillingOperation,
418 : status: BillingOpStatus
419 : ): string | undefined {
420 0 : if (
421 : state.challenge?.status === 'completed' &&
422 : echoesSettledChallenge(state, status)
423 : ) {
424 0 : return state.authenticationDeadline
425 : }
426 0 : return status.authentication_deadline
427 : }
428 :
429 0 : function reducePending(
430 : state: PendingBillingOperation,
431 : status: BillingOpStatus
432 : ): BillingOperationState {
433 0 : if (status.id !== state.id) return state
434 0 : const terminal = terminalFromStatus(state, status)
435 0 : if (terminal !== undefined) return terminal
436 :
437 : const echoed = echoesSettledChallenge(state, status)
438 0 : const authenticationState = echoed
439 : ? state.authenticationState
440 : : status.authentication_state
441 0 : const authenticationDeadline = nextAuthenticationDeadline(state, status)
442 0 : const actionUrl = nextActionUrl(state, status, authenticationState)
443 0 : const declineReason = nextDeclineReason(state, status, authenticationState)
444 0 : const { plan: _previousPlan, ...rest } = state
445 :
446 0 : return {
447 : ...rest,
448 : ...(status.plan === undefined ? {} : { plan: status.plan }),
449 : challenge: nextChallenge(state, status),
450 : authenticationState,
451 : authenticationDeadline,
452 : actionUrl,
453 : serverPhase: status.phase,
454 : declineReason,
455 : recoveryAction: status.recovery_action,
456 : cancelable: status.cancelable,
457 : customerActionSeen:
458 : state.customerActionSeen ||
459 : actionUrl !== undefined ||
460 : isBlockedOnCustomerPhase(status.phase) ||
461 : status.authentication_state === 'requires_action'
462 : }
463 : }
464 :
465 0 : function settleChallenge(
466 : state: PendingBillingOperation,
467 : outcome: 'completed' | 'failed'
468 : ): PendingBillingOperation {
469 0 : if (state.challenge === undefined) return state
470 0 : const challenge = { ...state.challenge, status: outcome }
471 0 : if (outcome === 'failed') {
472 0 : return {
473 : ...state,
474 : challenge,
475 : authenticationState: 'failed_retryable',
476 : customerActionSeen: true
477 : }
478 : }
479 0 : return {
480 : ...state,
481 : challenge,
482 : authenticationState: 'processing',
483 : authenticationDeadline: undefined,
484 : actionUrl: undefined,
485 : declineReason: undefined
486 : }
487 : }
488 :
489 0 : export function reduceBillingOperation(
490 : state: BillingOperationState,
491 : event: BillingOperationEvent
492 : ): BillingOperationState {
493 0 : if (state.phase !== 'pending') return state
494 :
495 0 : switch (event.type) {
496 : case 'status_polled':
497 0 : return reducePending(state, event.status)
498 : case 'timed_out':
499 0 : return withPhase(state, 'timed_out')
500 : case 'superseded':
501 0 : return withPhase(state, 'superseded')
502 : case 'lost':
503 0 : return withPhase(state, 'reconciliation_needed')
504 : case 'presentation_switched': {
505 0 : if (event.presentation === state.presentation) return state
506 : // The challenge record survives a hosted switch so a rollback keeps the
507 : // client secret; a failed challenge becomes required again on return.
508 0 : const { presentation, hostedDestination, ...rest } = state
509 0 : return event.presentation === 'hosted'
510 : ? {
511 : ...rest,
512 : presentation: 'hosted',
513 : hostedDestination: event.hostedDestination
514 : }
515 : : {
516 : ...rest,
517 : presentation: 'embedded',
518 : ...(state.challenge?.status === 'failed'
519 : ? { challenge: { ...state.challenge, status: 'required' } }
520 : : {})
521 : }
522 : }
523 : case 'challenge_started':
524 0 : return state.challenge?.status === 'required'
525 : ? { ...state, challenge: { ...state.challenge, status: 'in_progress' } }
526 : : state
527 : case 'challenge_settled':
528 0 : return settleChallenge(state, event.outcome)
529 : case 'action_reissued': {
530 0 : const actionUrl = validateActionUrl(event.actionUrl)
531 0 : return actionUrl === undefined
532 : ? state
533 : : { ...state, actionUrl, customerActionSeen: true }
534 : }
535 : }
536 : }
|