Line data Source code
1 : import type { SubscriptionCheckoutType } from '@comfyorg/account-core/billing'
2 : import type { SubscriptionDuration } from '@comfyorg/ingest-types'
3 : import {
4 : getTierPrice,
5 : toTierKey
6 : } from '@/platform/billing/subscription/constants/tierPricing'
7 : import type {
8 : IngestSubscriptionTier,
9 : TierKey
10 : } from '@/platform/billing/subscription/constants/tierPricing'
11 : import type { BillingCycle } from '@/platform/billing/subscription/utils/subscriptionTierRank'
12 : import type {
13 : PaymentIntentSource,
14 : ResubscribeClickMetadata,
15 : SubscriptionSuccessMetadata
16 : } from '@comfyorg/telemetry/types'
17 :
18 2355 : const PENDING_SUBSCRIPTION_CHECKOUT_MAX_AGE_MS = 6 * 60 * 60 * 1000
19 2355 : const PENDING_SUBSCRIPTION_CHECKOUT_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000
20 2355 : const VALID_TIER_KEYS: ReadonlySet<string> = new Set([
21 : 'free',
22 : 'standard',
23 : 'creator',
24 : 'pro',
25 : 'founder'
26 : ])
27 2355 : const VALID_PAYMENT_INTENT_SOURCES = {
28 : subscription_required: true,
29 : out_of_credits: true,
30 : top_up_blocked: true,
31 : deep_link: true,
32 : subscribe_to_run: true,
33 : subscribe_now_button: true,
34 : upgrade_to_add_credits: true,
35 : settings_billing_panel: true,
36 : avatar_menu_plans: true,
37 : team_members_panel: true,
38 : invite_member_upsell: true,
39 : upload_model_upgrade: true,
40 : team_upgrade_resume: true,
41 : free_tier_quota: true,
42 : agent_paywall: true
43 : } satisfies Record<PaymentIntentSource, true>
44 :
45 2355 : export const PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY =
46 : 'comfy.subscription.pending_checkout_attempt'
47 2355 : export const PENDING_SUBSCRIPTION_CHECKOUT_EVENT =
48 : 'comfy:subscription-checkout-attempt-changed'
49 2355 : const PENDING_SUBSCRIPTION_CHECKOUT_TERMINAL_STORAGE_KEY =
50 : 'comfy.subscription.pending_checkout_terminal'
51 :
52 : export type PendingCheckoutTerminal =
53 : | 'completion_missing'
54 : | 'recovery_unreachable'
55 :
56 : interface PendingCheckoutTerminalClaim {
57 : attempt_id: string
58 : terminal: PendingCheckoutTerminal
59 : }
60 :
61 : interface SubscriptionStatusSnapshot {
62 : is_active?: boolean
63 : subscription_tier?: IngestSubscriptionTier | null
64 : subscription_duration?: SubscriptionDuration | null
65 : cancel_at?: string | null
66 : }
67 :
68 : export interface PendingSubscriptionCheckoutAttempt {
69 : attempt_id: string
70 : started_at_ms: number
71 : tier: TierKey
72 : cycle: BillingCycle
73 : checkout_type: SubscriptionCheckoutType
74 : previous_tier?: TierKey
75 : previous_cycle?: BillingCycle
76 : /** Cancellation marker observed before a resubscribe checkout opened. */
77 : previous_cancel_at?: string | null
78 : payment_intent_source?: PaymentIntentSource
79 : /** Set when this attempt was initiated from the resubscribe flow, not a plain subscribe. */
80 : operation?: 'resubscribe'
81 : /** Click-time source for a resubscribe attempt; carried through to the terminal event. */
82 : resubscribe_source?: ResubscribeClickMetadata['source']
83 : /** User and workspace that opened checkout, used to reject another session's attempt. */
84 : owner_id?: string
85 : workspace_id?: string | null
86 : /** Set when this attempt already emitted `billing.subscription_checkout.started`. */
87 : start_reported?: true
88 : }
89 :
90 : export interface PendingSubscriptionCheckoutAttemptInput {
91 : tier: TierKey
92 : cycle: BillingCycle
93 : checkout_type: SubscriptionCheckoutType
94 : previous_tier?: TierKey
95 : previous_cycle?: BillingCycle
96 : previous_cancel_at?: string | null
97 : payment_intent_source?: PaymentIntentSource
98 : operation?: 'resubscribe'
99 : resubscribe_source?: ResubscribeClickMetadata['source']
100 : owner_id?: string
101 : workspace_id?: string | null
102 : start_reported?: true
103 : }
104 :
105 2355 : const dispatchPendingCheckoutChangeEvent = () => {
106 0 : if (typeof window === 'undefined') {
107 0 : return
108 : }
109 :
110 0 : window.dispatchEvent(new Event(PENDING_SUBSCRIPTION_CHECKOUT_EVENT))
111 : }
112 :
113 : const createAttemptId = (): string => {
114 : if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
115 : return crypto.randomUUID()
116 : }
117 :
118 : return `attempt-${Date.now()}`
119 : }
120 :
121 : type CheckoutStorage = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
122 :
123 2355 : const getStorage = (): CheckoutStorage | null => {
124 0 : let storage: unknown
125 :
126 0 : try {
127 0 : storage = globalThis.localStorage
128 : } catch {
129 0 : return null
130 : }
131 :
132 0 : return isCheckoutStorage(storage) ? storage : null
133 : }
134 :
135 0 : function isCheckoutStorage(value: unknown): value is CheckoutStorage {
136 0 : return (
137 : !!value &&
138 : typeof value === 'object' &&
139 : 'getItem' in value &&
140 : typeof value.getItem === 'function' &&
141 : 'setItem' in value &&
142 : typeof value.setItem === 'function' &&
143 : 'removeItem' in value &&
144 : typeof value.removeItem === 'function'
145 : )
146 : }
147 :
148 0 : function isUnknownRecord(value: unknown): value is Record<string, unknown> {
149 0 : return !!value && typeof value === 'object'
150 : }
151 :
152 : const getAnnualCheckoutValue = (tier: Exclude<TierKey, 'free' | 'founder'>) =>
153 : getTierPrice(tier, true) * 12
154 :
155 : const getCheckoutValue = (tier: TierKey, cycle: BillingCycle): number => {
156 : if (tier === 'free' || tier === 'founder') {
157 : return getTierPrice(tier, cycle === 'yearly')
158 : }
159 :
160 : return cycle === 'yearly'
161 : ? getAnnualCheckoutValue(tier)
162 : : getTierPrice(tier, false)
163 : }
164 :
165 : const getTierFromStatus = (
166 : status: SubscriptionStatusSnapshot
167 : ): TierKey | null => {
168 : const subscriptionTier = status.subscription_tier
169 : if (!subscriptionTier) {
170 : return null
171 : }
172 :
173 : return toTierKey(subscriptionTier)
174 : }
175 :
176 : const getCycleFromStatus = (
177 : status: SubscriptionStatusSnapshot
178 : ): BillingCycle | null => {
179 : if (status.subscription_duration === 'ANNUAL') {
180 : return 'yearly'
181 : }
182 :
183 : if (status.subscription_duration === 'MONTHLY') {
184 : return 'monthly'
185 : }
186 :
187 : return null
188 : }
189 :
190 2355 : const isExpired = (attempt: PendingSubscriptionCheckoutAttempt): boolean =>
191 : Date.now() - attempt.started_at_ms > PENDING_SUBSCRIPTION_CHECKOUT_MAX_AGE_MS
192 :
193 2355 : const isCheckoutAttemptCore = (
194 : value: Record<string, unknown>
195 : ): value is Record<string, unknown> & {
196 : attempt_id: string
197 : started_at_ms: number
198 : tier: TierKey
199 : cycle: BillingCycle
200 : checkout_type: SubscriptionCheckoutType
201 : } =>
202 : typeof value.attempt_id === 'string' &&
203 : typeof value.started_at_ms === 'number' &&
204 : Number.isFinite(value.started_at_ms) &&
205 : value.started_at_ms <=
206 : Date.now() + PENDING_SUBSCRIPTION_CHECKOUT_MAX_FUTURE_SKEW_MS &&
207 : isTierKey(value.tier) &&
208 : (value.cycle === 'monthly' || value.cycle === 'yearly') &&
209 : (value.checkout_type === 'new' || value.checkout_type === 'change')
210 :
211 2355 : const optionalCheckoutAttemptFields = (
212 : candidate: Record<string, unknown>
213 : ): Partial<PendingSubscriptionCheckoutAttempt> => ({
214 : ...(isTierKey(candidate.previous_tier)
215 : ? { previous_tier: candidate.previous_tier }
216 : : {}),
217 : ...(candidate.previous_cycle === 'monthly' ||
218 : candidate.previous_cycle === 'yearly'
219 : ? { previous_cycle: candidate.previous_cycle }
220 : : {}),
221 : ...(typeof candidate.previous_cancel_at === 'string' ||
222 : candidate.previous_cancel_at === null
223 : ? { previous_cancel_at: candidate.previous_cancel_at }
224 : : {}),
225 : ...(isPaymentIntentSource(candidate.payment_intent_source)
226 : ? { payment_intent_source: candidate.payment_intent_source }
227 : : {}),
228 : ...(candidate.operation === 'resubscribe'
229 : ? { operation: 'resubscribe' }
230 : : {}),
231 : ...(candidate.resubscribe_source === 'pricing_dialog' ||
232 : candidate.resubscribe_source === 'settings_billing_panel'
233 : ? { resubscribe_source: candidate.resubscribe_source }
234 : : {}),
235 : ...(typeof candidate.owner_id === 'string'
236 : ? { owner_id: candidate.owner_id }
237 : : {}),
238 : ...(typeof candidate.workspace_id === 'string' ||
239 : candidate.workspace_id === null
240 : ? { workspace_id: candidate.workspace_id }
241 : : {}),
242 : ...(candidate.start_reported === true ? { start_reported: true } : {})
243 : })
244 :
245 2355 : const normalizeAttempt = (
246 : value: unknown
247 : ): PendingSubscriptionCheckoutAttempt | null => {
248 0 : if (!isUnknownRecord(value) || !isCheckoutAttemptCore(value)) return null
249 :
250 0 : return {
251 : attempt_id: value.attempt_id,
252 : started_at_ms: Math.min(value.started_at_ms, Date.now()),
253 : tier: value.tier,
254 : cycle: value.cycle,
255 : checkout_type: value.checkout_type,
256 : ...optionalCheckoutAttemptFields(value)
257 : }
258 : }
259 :
260 2355 : const isTierKey = (value: unknown): value is TierKey =>
261 : typeof value === 'string' && VALID_TIER_KEYS.has(value)
262 :
263 2355 : const isPaymentIntentSource = (value: unknown): value is PaymentIntentSource =>
264 : typeof value === 'string' &&
265 : Object.hasOwn(VALID_PAYMENT_INTENT_SOURCES, value)
266 :
267 2355 : export const clearPendingSubscriptionCheckoutAttempt = (): void => {
268 0 : const storage = getStorage()
269 0 : if (!storage) {
270 0 : return
271 : }
272 :
273 0 : try {
274 0 : storage.removeItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY)
275 0 : storage.removeItem(PENDING_SUBSCRIPTION_CHECKOUT_TERMINAL_STORAGE_KEY)
276 : } catch {
277 0 : return
278 : }
279 0 : dispatchPendingCheckoutChangeEvent()
280 : }
281 :
282 2355 : const persistClampedStartTime = (
283 : storage: CheckoutStorage,
284 : attempt: PendingSubscriptionCheckoutAttempt
285 : ) => {
286 0 : try {
287 0 : storage.setItem(
288 : PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY,
289 : JSON.stringify(attempt)
290 : )
291 : } catch {
292 0 : return
293 : }
294 : }
295 :
296 2355 : export const getPendingSubscriptionCheckoutAttempt =
297 : (): PendingSubscriptionCheckoutAttempt | null => {
298 0 : const storage = getStorage()
299 0 : if (!storage) {
300 0 : return null
301 : }
302 :
303 0 : let rawAttempt: string | null
304 :
305 0 : try {
306 0 : rawAttempt = storage.getItem(PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY)
307 : } catch {
308 0 : return null
309 : }
310 :
311 0 : if (!rawAttempt) {
312 0 : return null
313 : }
314 :
315 0 : try {
316 0 : const parsed = JSON.parse(rawAttempt)
317 0 : const attempt = normalizeAttempt(parsed)
318 :
319 0 : if (!attempt || isExpired(attempt)) {
320 0 : clearPendingSubscriptionCheckoutAttempt()
321 0 : return null
322 : }
323 :
324 0 : if (
325 : isUnknownRecord(parsed) &&
326 : parsed.started_at_ms !== attempt.started_at_ms
327 : ) {
328 0 : persistClampedStartTime(storage, attempt)
329 : }
330 :
331 0 : return attempt
332 : } catch {
333 0 : clearPendingSubscriptionCheckoutAttempt()
334 0 : return null
335 : }
336 : }
337 :
338 2355 : const isPendingCheckoutTerminal = (
339 : value: unknown
340 : ): value is PendingCheckoutTerminal =>
341 : value === 'completion_missing' || value === 'recovery_unreachable'
342 :
343 2355 : const parsePendingCheckoutTerminalClaim = (
344 : rawClaim: string
345 : ): PendingCheckoutTerminalClaim | null => {
346 0 : try {
347 0 : const value: unknown = JSON.parse(rawClaim)
348 0 : if (
349 : !isUnknownRecord(value) ||
350 : typeof value.attempt_id !== 'string' ||
351 : !isPendingCheckoutTerminal(value.terminal)
352 : ) {
353 0 : return null
354 : }
355 0 : return { attempt_id: value.attempt_id, terminal: value.terminal }
356 : } catch {
357 0 : return null
358 : }
359 : }
360 :
361 2355 : export const getPendingCheckoutTerminal = (
362 : attemptId: string
363 : ): PendingCheckoutTerminal | null => {
364 0 : try {
365 0 : const rawClaim = getStorage()?.getItem(
366 : PENDING_SUBSCRIPTION_CHECKOUT_TERMINAL_STORAGE_KEY
367 : )
368 0 : if (!rawClaim) return null
369 0 : const claim = parsePendingCheckoutTerminalClaim(rawClaim)
370 0 : return claim?.attempt_id === attemptId ? claim.terminal : null
371 : } catch {
372 0 : return null
373 : }
374 : }
375 :
376 2355 : export const claimPendingCheckoutTerminal = (
377 : attemptId: string,
378 : terminal: PendingCheckoutTerminal
379 : ): PendingSubscriptionCheckoutAttempt | null => {
380 0 : const attempt = getPendingSubscriptionCheckoutAttempt()
381 0 : if (
382 : attempt?.attempt_id !== attemptId ||
383 : getPendingCheckoutTerminal(attemptId)
384 : ) {
385 0 : return null
386 : }
387 :
388 0 : try {
389 0 : getStorage()?.setItem(
390 : PENDING_SUBSCRIPTION_CHECKOUT_TERMINAL_STORAGE_KEY,
391 : JSON.stringify({ attempt_id: attemptId, terminal })
392 : )
393 : } catch {
394 0 : return null
395 : }
396 :
397 0 : return getPendingCheckoutTerminal(attemptId) === terminal ? attempt : null
398 : }
399 :
400 2355 : export const hasPendingSubscriptionCheckoutAttempt = (): boolean =>
401 : getPendingSubscriptionCheckoutAttempt() !== null
402 :
403 : const createPendingSubscriptionCheckoutAttempt = (
404 : input: PendingSubscriptionCheckoutAttemptInput
405 : ): PendingSubscriptionCheckoutAttempt => {
406 : return {
407 : attempt_id: createAttemptId(),
408 : started_at_ms: Date.now(),
409 : tier: input.tier,
410 : cycle: input.cycle,
411 : checkout_type: input.checkout_type,
412 : ...(input.previous_tier ? { previous_tier: input.previous_tier } : {}),
413 : ...(input.previous_cycle ? { previous_cycle: input.previous_cycle } : {}),
414 : ...(input.previous_cancel_at !== undefined
415 : ? { previous_cancel_at: input.previous_cancel_at }
416 : : {}),
417 : ...(input.payment_intent_source
418 : ? { payment_intent_source: input.payment_intent_source }
419 : : {}),
420 : ...(input.operation ? { operation: input.operation } : {}),
421 : ...(input.resubscribe_source
422 : ? { resubscribe_source: input.resubscribe_source }
423 : : {}),
424 : ...(input.owner_id ? { owner_id: input.owner_id } : {}),
425 : ...(input.workspace_id !== undefined
426 : ? { workspace_id: input.workspace_id }
427 : : {}),
428 : ...(input.start_reported ? { start_reported: true } : {})
429 : }
430 : }
431 :
432 : const persistPendingSubscriptionCheckoutAttempt = (
433 : attempt: PendingSubscriptionCheckoutAttempt
434 : ): PendingSubscriptionCheckoutAttempt => {
435 : const storage = getStorage()
436 : if (!storage) {
437 : return attempt
438 : }
439 :
440 : try {
441 : storage.setItem(
442 : PENDING_SUBSCRIPTION_CHECKOUT_STORAGE_KEY,
443 : JSON.stringify(attempt)
444 : )
445 : } catch {
446 : return attempt
447 : }
448 : dispatchPendingCheckoutChangeEvent()
449 :
450 : return attempt
451 : }
452 :
453 : export const recordPendingSubscriptionCheckoutAttempt = (
454 : input: PendingSubscriptionCheckoutAttemptInput
455 : ): PendingSubscriptionCheckoutAttempt =>
456 : persistPendingSubscriptionCheckoutAttempt(
457 : createPendingSubscriptionCheckoutAttempt(input)
458 : )
459 :
460 : const didAttemptSucceed = (
461 : attempt: PendingSubscriptionCheckoutAttempt,
462 : status: SubscriptionStatusSnapshot
463 : ): boolean => {
464 : if (!status.is_active) {
465 : return false
466 : }
467 :
468 : if (attempt.operation === 'resubscribe') {
469 : return (
470 : attempt.previous_cancel_at !== undefined &&
471 : (status.cancel_at ?? null) !== attempt.previous_cancel_at &&
472 : getTierFromStatus(status) === attempt.tier &&
473 : getCycleFromStatus(status) === attempt.cycle
474 : )
475 : }
476 :
477 : return (
478 : getTierFromStatus(status) === attempt.tier &&
479 : getCycleFromStatus(status) === attempt.cycle
480 : )
481 : }
482 :
483 : export const consumePendingSubscriptionCheckoutSuccess = (
484 : status: SubscriptionStatusSnapshot
485 : ):
486 : | (SubscriptionSuccessMetadata &
487 : Pick<
488 : PendingSubscriptionCheckoutAttempt,
489 : 'start_reported' | 'started_at_ms'
490 : >)
491 : | null => {
492 : const attempt = getPendingSubscriptionCheckoutAttempt()
493 : if (!attempt || !didAttemptSucceed(attempt, status)) {
494 : return null
495 : }
496 :
497 : const wasReportedTerminal = getPendingCheckoutTerminal(attempt.attempt_id)
498 : clearPendingSubscriptionCheckoutAttempt()
499 :
500 : const value = getCheckoutValue(attempt.tier, attempt.cycle)
501 :
502 : return {
503 : checkout_attempt_id: attempt.attempt_id,
504 : tier: attempt.tier,
505 : cycle: attempt.cycle,
506 : checkout_type: attempt.checkout_type,
507 : ...(attempt.previous_tier ? { previous_tier: attempt.previous_tier } : {}),
508 : ...(attempt.payment_intent_source
509 : ? { payment_intent_source: attempt.payment_intent_source }
510 : : {}),
511 : ...(attempt.operation ? { operation: attempt.operation } : {}),
512 : ...(attempt.resubscribe_source
513 : ? { resubscribe_source: attempt.resubscribe_source }
514 : : {}),
515 : ...(wasReportedTerminal
516 : ? { recovery_outcome: 'late_success' as const }
517 : : {}),
518 : ...(attempt.start_reported ? { start_reported: true as const } : {}),
519 : started_at_ms: attempt.started_at_ms,
520 : value,
521 : currency: 'USD',
522 : ecommerce: {
523 : value,
524 : currency: 'USD',
525 : items: [
526 : {
527 : item_name: attempt.tier,
528 : item_category: 'subscription',
529 : item_variant: attempt.cycle,
530 : price: value,
531 : quantity: 1
532 : }
533 : ]
534 : }
535 : }
536 : }
|