Line data Source code
1 : /**
2 : * The subscription commands on the shared operation lifecycle: subscribe,
3 : * resubscribe, cancel, and the payment portal. Each one encodes its request
4 : * against the generated contract, issues it through `lifecycle.begin`, and
5 : * waits for the settled operation; polling, routing, recovery, and telemetry
6 : * stay in the lifecycle. `previewSubscribe` sits beside them without a
7 : * lifecycle: it only quotes a change.
8 : *
9 : * No command decides for the server whether a transition is allowed
10 : * (`../../../docs/billing-command-eligibility.md`). Server codes are matched
11 : * against the closed set named here; a code outside it reaches the caller only
12 : * as the transport's coded failure.
13 : */
14 : import {
15 : zCancelBillingOpResponse,
16 : zCancelSubscriptionResponse2,
17 : zPaymentPortalResponse,
18 : zPreviewPlanInfo,
19 : zPreviewSubscribeRequest,
20 : zPreviewSubscribeResponse,
21 : zResubscribeResponse,
22 : zSubscribeRequest,
23 : zSubscribeResponse
24 : } from '@comfyorg/ingest-types/zod'
25 : import { z } from 'zod'
26 :
27 : import type { BillingFailure, BillingTransport } from './billingContracts'
28 : import { matchesServerCode } from './billingContracts'
29 : import type { CapabilitiesReader } from './capabilities'
30 : import type { CreditsReader } from './credits'
31 : import type {
32 : BillingOperationLifecycle,
33 : IssuedBillingOperation
34 : } from './operationLifecycle'
35 : import { operationRoute } from './operationLifecycle'
36 : import type {
37 : BillingOperationKind,
38 : BillingOperationState,
39 : PendingBillingOperation
40 : } from './operationState'
41 : import { validateActionUrl } from './operationState'
42 : import type { ParsedBillingBody } from './sharedRead'
43 : import { readValidatedBillingResponse } from './sharedRead'
44 : import type { BillingStatusReader } from './status'
45 : import { SubscriptionDiscountSchema } from './subscriptionDiscount'
46 : import { wireCents } from './wireCents'
47 :
48 2356 : export const SUBSCRIBE_ROUTE = '/billing/subscribe'
49 2356 : export const RESUBSCRIBE_ROUTE = '/billing/subscription/resubscribe'
50 2356 : export const CANCEL_SUBSCRIPTION_ROUTE = '/billing/subscription/cancel'
51 2356 : export const PAYMENT_PORTAL_ROUTE = '/billing/payment-portal'
52 2356 : export const PREVIEW_SUBSCRIBE_ROUTE = '/billing/preview-subscribe'
53 :
54 0 : export function cancelOperationRoute(operationId: string): string {
55 0 : return `${operationRoute(operationId)}/cancel`
56 : }
57 :
58 : /** The closed set of `serverCode` values these commands act on. */
59 2356 : const NO_ACTIVE_SUBSCRIPTION_SERVER_CODE = 'NO_ACTIVE_SUBSCRIPTION'
60 2356 : const REACTIVATION_CONFIRMATION_REQUIRED_SERVER_CODE =
61 : 'REACTIVATION_CONFIRMATION_REQUIRED'
62 2356 : const NOT_SCHEDULED_FOR_CANCELLATION_SERVER_CODE =
63 : 'NOT_SCHEDULED_FOR_CANCELLATION'
64 2356 : const ALREADY_CANCELED_SERVER_CODE = 'ALREADY_CANCELED'
65 2356 : const SUBSCRIPTION_QUOTE_STALE_SERVER_CODE = 'SUBSCRIPTION_QUOTE_STALE'
66 2356 : const SUBSCRIPTION_CHANGE_IN_PROGRESS_SERVER_CODE =
67 : 'SUBSCRIPTION_CHANGE_IN_PROGRESS'
68 2356 : const CANCEL_REFUSAL_SERVER_CODES = [
69 : 'NOT_CANCELABLE',
70 : 'PAYMENT_IN_FLIGHT'
71 : ] as const
72 :
73 : export type SubscribeInput = z.infer<typeof zSubscribeRequest>
74 :
75 : export type TerminalBillingOperation = Exclude<
76 : BillingOperationState,
77 : PendingBillingOperation
78 : >
79 :
80 : /** Outcomes a subscription command adds to the shared `BillingErrorCode` set. */
81 : export type SubscriptionCommandCode =
82 : /** The input fails the generated request contract; nothing was sent. */
83 : | 'INVALID_REQUEST'
84 : /** `confirmation_token` and `saved_payment_method_id` were both given. */
85 : | 'CONFLICTING_PAYMENT_METHOD'
86 : /** The server wants the host to re-preview and resend with `confirm_reactivation`. */
87 : | 'REACTIVATION_CONFIRMATION_REQUIRED'
88 : | 'NO_ACTIVE_SUBSCRIPTION'
89 : /** The server asked for a hosted payment step but offered no page for it. */
90 : | 'MISSING_PAYMENT_METHOD_URL'
91 : /** The quote no longer matches what the server would charge; re-preview. */
92 : | 'QUOTE_STALE'
93 :
94 : export type SubscriptionCommandFailure =
95 : | BillingFailure
96 : | { readonly status: 'error'; readonly code: SubscriptionCommandCode }
97 :
98 : /** What the subscribe route answered before the lifecycle drove the operation on. */
99 : type SubscribeIssuedStatus = z.infer<typeof zSubscribeResponse>['status']
100 :
101 : export interface SubscriptionCommandOutcome {
102 : readonly phase: TerminalBillingOperation['phase']
103 : /** Absent when the requested state already held and nothing was issued. */
104 : readonly operation?: TerminalBillingOperation
105 : /**
106 : * The `status` the subscribe response carried, before the lifecycle settled
107 : * the operation: `subscribed` is a plan the server activated on the spot,
108 : * the other two are payment steps it could not complete without the
109 : * customer. Absent for every other command, and whenever this call read no
110 : * subscribe response at all: `begin` adopted an operation the server was
111 : * already settling, or joined one another `subscription` command had in
112 : * flight. Both land on `requiredPayment: true`, the side an operation the
113 : * server is mid-payment on belongs to.
114 : */
115 : readonly issuedStatus?: SubscribeIssuedStatus
116 : }
117 :
118 : export type SubscriptionCommandResult =
119 : | { readonly status: 'ok'; readonly value: SubscriptionCommandOutcome }
120 : | SubscriptionCommandFailure
121 :
122 : /**
123 : * Why the server kept a payment it was asked to cancel. `PAYMENT_IN_FLIGHT`:
124 : * the payment won the race and the operation will settle on its own.
125 : * `NOT_CANCELABLE`: the operation is not one waiting on authentication.
126 : */
127 : export type CancelRefusalCode = (typeof CANCEL_REFUSAL_SERVER_CODES)[number]
128 :
129 : /**
130 : * The server's answer to cancelling a pending operation. `canceled`: dropped,
131 : * nothing charged, also for one already discarded. `cancel_requested`: the
132 : * cancel was delivered but has not settled; asking again is safe.
133 : */
134 : export type CancelOperationResult =
135 : | { readonly status: 'canceled' | 'cancel_requested' }
136 : | { readonly status: 'not_canceled'; readonly code: CancelRefusalCode }
137 : | BillingFailure
138 :
139 : export type PaymentPortalResult =
140 : | { readonly status: 'ok'; readonly value: { readonly url: string } }
141 : | BillingFailure
142 :
143 2356 : const PlanInfoSchema = zPreviewPlanInfo.extend({
144 : credits_cents: wireCents,
145 : price_cents: wireCents,
146 : list_price_cents: wireCents.optional(),
147 : monthly_list_price_cents: wireCents.optional(),
148 : monthly_price_cents: wireCents.optional(),
149 : seat_summary: zPreviewPlanInfo.shape.seat_summary.extend({
150 : total_cost_cents: wireCents,
151 : total_credits_cents: wireCents
152 : })
153 : })
154 :
155 2356 : const PreviewSchema = zPreviewSubscribeResponse.extend({
156 : amount_due_cents: wireCents.optional(),
157 : cost_next_period_cents: wireCents,
158 : cost_today_cents: wireCents,
159 : credits_next_period_cents: wireCents,
160 : credits_today_cents: wireCents,
161 : credits_today: wireCents.nonnegative().optional(),
162 : credits_next_period: wireCents.nonnegative().optional(),
163 : renewal_amount_cents: wireCents.optional(),
164 : subtotal_cents: wireCents.optional(),
165 : balance_applied_cents: wireCents.optional(),
166 : proration_remaining_cents: wireCents.optional(),
167 : proration_unused_cents: wireCents.optional(),
168 : current_plan: PlanInfoSchema.optional(),
169 : new_plan: PlanInfoSchema,
170 : discounts: z.array(SubscriptionDiscountSchema).optional()
171 : })
172 :
173 : /**
174 : * The quote the server returns for a plan change, in the generated field names.
175 : *
176 : * Its strings are product copy, not `serverCode`'s kind of machine identifier:
177 : * a `discounts[]` entry describes a discount the server applied, and a
178 : * `promotion` one carries back the very `promotionCode` the caller sent, so a
179 : * host renders `code` and `name` rather than matching them.
180 : */
181 : export type SubscriptionPreview = z.infer<typeof PreviewSchema>
182 :
183 : export interface PreviewSubscribeInput {
184 : readonly planSlug: string
185 : readonly promotionCode?: string
186 : readonly teamCreditStopId?: string
187 : readonly checkoutAttemptId?: string
188 : }
189 :
190 : export interface PreviewSubscribeOptions {
191 : readonly signal?: AbortSignal
192 : readonly timeoutMs?: number
193 : }
194 :
195 : export type PreviewSubscribeResult =
196 : | { readonly status: 'ok'; readonly value: SubscriptionPreview }
197 : | SubscriptionCommandFailure
198 :
199 : export interface BillingCommandsOptions {
200 : readonly transport: BillingTransport
201 : readonly lifecycle: BillingOperationLifecycle
202 : readonly statusReader: BillingStatusReader
203 : readonly capabilities: CapabilitiesReader
204 : readonly credits: CreditsReader
205 : /** One key per attempt; the backend's dedupe key and the transport's replay gate. */
206 : readonly idempotencyKey?: () => string
207 : }
208 :
209 : export interface BillingCommands {
210 : subscribe: (input: SubscribeInput) => Promise<SubscriptionCommandResult>
211 : /**
212 : * Quotes a plan change without issuing an operation or touching the
213 : * capability cache: a read the backend happens to shape as a POST. It sends
214 : * no idempotency key, so a stale token surfaces as the transient
215 : * `REQUEST_FAILED` that callers already retry rather than as a denial.
216 : */
217 : previewSubscribe: (
218 : input: PreviewSubscribeInput,
219 : options?: PreviewSubscribeOptions
220 : ) => Promise<PreviewSubscribeResult>
221 : resubscribe: () => Promise<SubscriptionCommandResult>
222 : cancelSubscription: () => Promise<SubscriptionCommandResult>
223 : /**
224 : * Asks the server to drop an operation still waiting on the customer's
225 : * authentication. Any answer that names the operation's fate wakes the
226 : * lifecycle, so the operation it follows catches up with the server.
227 : */
228 : cancelOperation: (operationId: string) => Promise<CancelOperationResult>
229 : /** Returns the portal URL; the host decides how to open it. */
230 : openPaymentPortal: (input: {
231 : readonly returnUrl?: string
232 : }) => Promise<PaymentPortalResult>
233 : }
234 :
235 : interface IssuedOutcome {
236 : readonly status: 'ok'
237 : readonly value: IssuedBillingOperation
238 : readonly issuedStatus?: SubscribeIssuedStatus
239 : }
240 :
241 : type IssueOutcome =
242 : | IssuedOutcome
243 : /** The server refused because the requested state already holds. */
244 : | { readonly status: 'already_held' }
245 : | SubscriptionCommandFailure
246 :
247 2356 : const ALREADY_HELD: SubscriptionCommandResult = {
248 : status: 'ok',
249 : value: { phase: 'succeeded' }
250 : }
251 :
252 0 : function coded(code: SubscriptionCommandCode): SubscriptionCommandFailure {
253 0 : return { status: 'error', code }
254 : }
255 :
256 : /**
257 : * A server code is trusted as state only from a 4xx: a 5xx echoing the code
258 : * is an upstream failure that happens to carry it, and the state it names
259 : * cannot be assumed to hold.
260 : */
261 0 : function refusedWith(failure: BillingFailure, serverCode: string): boolean {
262 0 : return (
263 : matchesServerCode(failure, serverCode) &&
264 : failure.httpStatus !== undefined &&
265 : failure.httpStatus >= 400 &&
266 : failure.httpStatus < 500
267 : )
268 : }
269 :
270 : /**
271 : * The server's refusal because another subscription operation is still open
272 : * is the same answer the lifecycle gives when it sees that operation first.
273 : */
274 0 : function refusedWhilePending(failure: BillingFailure): BillingFailure {
275 0 : return refusedWith(failure, SUBSCRIPTION_CHANGE_IN_PROGRESS_SERVER_CODE)
276 : ? { ...failure, code: 'OPERATION_ALREADY_PENDING' }
277 : : failure
278 : }
279 :
280 0 : function mapServerCode(
281 : failure: BillingFailure,
282 : alreadyHeldCode: string
283 : ): IssueOutcome {
284 : // A server code the caller's request already satisfies is a success.
285 0 : if (refusedWith(failure, alreadyHeldCode)) {
286 0 : return { status: 'already_held' }
287 : }
288 0 : return matchesServerCode(failure, NO_ACTIVE_SUBSCRIPTION_SERVER_CODE)
289 : ? coded('NO_ACTIVE_SUBSCRIPTION')
290 : : refusedWhilePending(failure)
291 : }
292 :
293 0 : function dropEmpty(value: string | undefined): string | undefined {
294 0 : return value === '' ? undefined : value
295 : }
296 :
297 0 : function previewRequestBody(input: PreviewSubscribeInput): unknown {
298 0 : const { planSlug, promotionCode, teamCreditStopId, checkoutAttemptId } = input
299 0 : return {
300 : plan_slug: planSlug,
301 : ...(promotionCode === undefined ? {} : { promotion_code: promotionCode }),
302 : ...(teamCreditStopId === undefined
303 : ? {}
304 : : { team_credit_stop_id: teamCreditStopId }),
305 : ...(checkoutAttemptId === undefined
306 : ? {}
307 : : { checkout_attempt_id: checkoutAttemptId })
308 : }
309 : }
310 :
311 0 : export function createBillingCommands(
312 : options: BillingCommandsOptions
313 : ): BillingCommands {
314 0 : const {
315 : transport,
316 : lifecycle,
317 : statusReader,
318 : capabilities,
319 : credits,
320 : idempotencyKey = () => crypto.randomUUID()
321 : } = options
322 :
323 0 : async function refreshAfterSuccess(): Promise<void> {
324 0 : capabilities.invalidate()
325 0 : await Promise.all([credits.read(), statusReader.read()])
326 : }
327 :
328 0 : function post<T>(
329 : route: string,
330 : body: unknown,
331 : parse: (body: unknown) => ParsedBillingBody<T>,
332 : key?: string
333 : ) {
334 0 : return readValidatedBillingResponse(
335 : transport,
336 : {
337 : method: 'POST',
338 : route,
339 : body,
340 : ...(key === undefined ? {} : { idempotencyKey: key })
341 : },
342 : parse
343 : )
344 : }
345 :
346 0 : async function settle(
347 : kind: BillingOperationKind,
348 : issue: () => Promise<IssueOutcome>
349 : ): Promise<SubscriptionCommandResult> {
350 : // The lifecycle carries only the shared codes; the command's own verdict
351 : // and what it read off the issuing response wait here for `begin` to
352 : // return. Both stay unset whenever `begin` never ran this caller's issue:
353 : // it adopted an operation the server was already settling, or joined one
354 : // another command of the same kind had in flight.
355 0 : const verdict: { value?: Exclude<IssueOutcome, { status: 'ok' }> } = {}
356 0 : const issued: { value?: IssuedOutcome } = {}
357 0 : const began = await lifecycle.begin(kind, async () => {
358 0 : const outcome = await issue()
359 0 : if (outcome.status === 'ok') {
360 0 : issued.value = outcome
361 0 : return outcome
362 : }
363 0 : verdict.value = outcome
364 0 : return { status: 'error', code: 'REQUEST_FAILED' }
365 : })
366 0 : if (verdict.value !== undefined) {
367 0 : if (verdict.value.status !== 'already_held') return verdict.value
368 0 : await refreshAfterSuccess()
369 0 : return ALREADY_HELD
370 : }
371 0 : if (began.status === 'error') return began
372 :
373 0 : const settled = lifecycle.settled(began.value.id)
374 0 : const operation = settled === undefined ? began.value : await settled
375 0 : if (operation.phase === 'pending') {
376 0 : return { status: 'error', code: 'SUPERSEDED' }
377 : }
378 0 : if (operation.phase === 'succeeded') await refreshAfterSuccess()
379 0 : const issuedStatus = issued.value?.issuedStatus
380 0 : return {
381 : status: 'ok',
382 : value: {
383 : phase: operation.phase,
384 : operation,
385 : ...(issuedStatus === undefined ? {} : { issuedStatus })
386 : }
387 : }
388 : }
389 :
390 0 : async function issueSubscribe(input: SubscribeInput): Promise<IssueOutcome> {
391 0 : const key = idempotencyKey()
392 0 : const response = await post(
393 : SUBSCRIBE_ROUTE,
394 : { ...input, idempotency_key: key },
395 : (body) => zSubscribeResponse.safeParse(body),
396 : key
397 : )
398 0 : if (response.status === 'error') {
399 0 : if (
400 : matchesServerCode(
401 : response,
402 : REACTIVATION_CONFIRMATION_REQUIRED_SERVER_CODE
403 : )
404 : ) {
405 0 : return coded('REACTIVATION_CONFIRMATION_REQUIRED')
406 : }
407 0 : return refusedWith(response, SUBSCRIPTION_QUOTE_STALE_SERVER_CODE)
408 : ? coded('QUOTE_STALE')
409 : : refusedWhilePending(response)
410 : }
411 0 : const { billing_op_id, status, payment_method_url } = response.value.data
412 0 : if (status !== 'needs_payment_method') {
413 0 : return {
414 : status: 'ok',
415 : value: { operationId: billing_op_id },
416 : issuedStatus: status
417 : }
418 : }
419 0 : if (payment_method_url === undefined) {
420 0 : return coded('MISSING_PAYMENT_METHOD_URL')
421 : }
422 0 : return {
423 : status: 'ok',
424 : value: { operationId: billing_op_id, actionUrl: payment_method_url },
425 : issuedStatus: status
426 : }
427 : }
428 :
429 0 : async function issueResubscribe(): Promise<IssueOutcome> {
430 0 : const key = idempotencyKey()
431 0 : const response = await post(
432 : RESUBSCRIBE_ROUTE,
433 : { idempotency_key: key },
434 : (body) => zResubscribeResponse.safeParse(body),
435 : key
436 : )
437 0 : if (response.status === 'error') {
438 0 : return mapServerCode(response, NOT_SCHEDULED_FOR_CANCELLATION_SERVER_CODE)
439 : }
440 0 : return {
441 : status: 'ok',
442 : value: { operationId: response.value.data.billing_op_id }
443 : }
444 : }
445 :
446 0 : async function issueCancel(): Promise<IssueOutcome> {
447 0 : const key = idempotencyKey()
448 0 : const response = await post(
449 : CANCEL_SUBSCRIPTION_ROUTE,
450 : { idempotency_key: key },
451 : (body) => zCancelSubscriptionResponse2.safeParse(body),
452 : key
453 : )
454 0 : if (response.status === 'error') {
455 0 : return mapServerCode(response, ALREADY_CANCELED_SERVER_CODE)
456 : }
457 0 : return {
458 : status: 'ok',
459 : value: { operationId: response.value.data.billing_op_id }
460 : }
461 : }
462 :
463 0 : const resubscribe = () => settle('subscription', issueResubscribe)
464 :
465 0 : async function subscribe(
466 : input: SubscribeInput
467 : ): Promise<SubscriptionCommandResult> {
468 0 : const confirmationToken = dropEmpty(input.confirmation_token)
469 0 : const savedPaymentMethodId = dropEmpty(input.saved_payment_method_id)
470 0 : if (confirmationToken !== undefined && savedPaymentMethodId !== undefined) {
471 0 : return coded('CONFLICTING_PAYMENT_METHOD')
472 : }
473 : // JSON drops `undefined` but keeps `''`, so an empty credential would
474 : // reach the server as a present-but-meaningless value.
475 0 : const request: SubscribeInput = {
476 : ...input,
477 : confirmation_token: confirmationToken,
478 : saved_payment_method_id: savedPaymentMethodId
479 : }
480 0 : if (!zSubscribeRequest.safeParse(request).success) {
481 0 : return coded('INVALID_REQUEST')
482 : }
483 :
484 0 : return settle('subscription', () => issueSubscribe(request))
485 : }
486 :
487 0 : async function previewSubscribe(
488 : input: PreviewSubscribeInput,
489 : options: PreviewSubscribeOptions = {}
490 : ): Promise<PreviewSubscribeResult> {
491 0 : const body = previewRequestBody(input)
492 0 : if (!zPreviewSubscribeRequest.safeParse(body).success) {
493 0 : return coded('INVALID_REQUEST')
494 : }
495 0 : const response = await readValidatedBillingResponse(
496 : transport,
497 : {
498 : method: 'POST',
499 : route: PREVIEW_SUBSCRIBE_ROUTE,
500 : body,
501 : ...(options.signal === undefined ? {} : { signal: options.signal }),
502 : ...(options.timeoutMs === undefined
503 : ? {}
504 : : { timeoutMs: options.timeoutMs })
505 : },
506 : (raw) => PreviewSchema.safeParse(raw)
507 : )
508 0 : return response.status === 'error'
509 : ? response
510 : : { status: 'ok', value: response.value.data }
511 : }
512 :
513 0 : async function openPaymentPortal(input: {
514 : readonly returnUrl?: string
515 : }): Promise<PaymentPortalResult> {
516 0 : const response = await post(
517 : PAYMENT_PORTAL_ROUTE,
518 : input.returnUrl === undefined ? {} : { return_url: input.returnUrl },
519 : (body) => zPaymentPortalResponse.safeParse(body)
520 : )
521 0 : if (response.status === 'error') return response
522 0 : const url = validateActionUrl(response.value.data.url)
523 0 : if (url === undefined) {
524 0 : return {
525 : status: 'error',
526 : code: 'MALFORMED_RESPONSE',
527 : httpStatus: response.value.httpStatus
528 : }
529 : }
530 0 : return { status: 'ok', value: { url } }
531 : }
532 :
533 0 : async function cancelOperation(
534 : operationId: string
535 : ): Promise<CancelOperationResult> {
536 0 : const response = await post(
537 : cancelOperationRoute(operationId),
538 : undefined,
539 : (body) => zCancelBillingOpResponse.safeParse(body)
540 : )
541 0 : if (response.status === 'error') {
542 0 : const refusal = CANCEL_REFUSAL_SERVER_CODES.find((code) =>
543 : refusedWith(response, code)
544 : )
545 0 : if (refusal === undefined) return response
546 0 : lifecycle.wake()
547 0 : return { status: 'not_canceled', code: refusal }
548 : }
549 0 : lifecycle.wake()
550 0 : return { status: response.value.data.status }
551 : }
552 :
553 0 : return {
554 : subscribe,
555 : previewSubscribe,
556 : resubscribe,
557 : cancelSubscription: () => settle('cancel', issueCancel),
558 : cancelOperation,
559 : openPaymentPortal
560 : }
561 : }
|