Line data Source code
1 : import { computed, onScopeDispose, shallowRef, toValue, watch } from 'vue'
2 : import type { MaybeRefOrGetter } from 'vue'
3 :
4 : import type {
5 : AddCreditsAmount,
6 : AddCreditsEvent,
7 : AddCreditsFacts,
8 : AddCreditsRefusal,
9 : AddCreditsState,
10 : AutoTopUpActivation,
11 : AutoTopUpActivationOutcome,
12 : TopupCommand
13 : } from '@comfyorg/account-core/billing'
14 : import {
15 : addCreditsRefusalFor,
16 : reduceAddCredits,
17 : startAddCredits,
18 : viewAddCreditsAmount
19 : } from '@comfyorg/account-core/billing'
20 :
21 : import type { AddCreditsAutoTopUpRequest } from './useAddCreditsAutoTopUp'
22 :
23 : export type AddCreditsQuoteResult =
24 : | { readonly status: 'ok'; readonly credits: number }
25 : | { readonly status: 'error' }
26 :
27 : export type AddCreditsCheckoutResult =
28 : | { readonly status: 'ok'; readonly url: string }
29 : | { readonly status: 'error'; readonly refusal: AddCreditsRefusal }
30 :
31 : /** A tab opened inside the click, so a pop-up blocker lets it through. */
32 : export interface AddCreditsCheckoutTab {
33 : readonly navigate: (url: string) => void
34 : readonly close: () => void
35 : }
36 :
37 : /** Everything the dialog reaches outside itself for; the host owns each one. */
38 : export interface AddCreditsPorts {
39 : readonly quote: (
40 : amountCents: number,
41 : signal: AbortSignal
42 : ) => Promise<AddCreditsQuoteResult>
43 : /** `autoTopUp` turns auto top-up on once this purchase is paid. */
44 : readonly createCheckout: (
45 : amountCents: number,
46 : signal: AbortSignal,
47 : autoTopUp?: AutoTopUpActivation
48 : ) => Promise<AddCreditsCheckoutResult>
49 : readonly reserveTab: () => AddCreditsCheckoutTab | null
50 : /** Calls `landed` once the server reports the top-up went through, with the activation outcome when one was requested; returns its stop. */
51 : readonly watchPayment: (
52 : landed: (activation?: AutoTopUpActivationOutcome) => void
53 : ) => () => void
54 : /** True when a checkout URL works once: none is created without a reserved tab, and the blocked step requests one again in its own click. */
55 : readonly singleUseCheckout?: boolean
56 : /** True when `createCheckout` sends `autoTopUp` and `watchPayment` reports its outcome; the checkbox shows only then. */
57 : readonly activatesAutoTopUp?: boolean
58 : /** After a top-up lands, Platform's Turn on auto top-up link when the served facts offer it, else null. */
59 : readonly autoTopUpSetupUrl?: () => Promise<string | null>
60 : /** False once the host no longer owns the watched checkout; a landing still reading its setup link is then dropped. */
61 : readonly ownsCheckout?: () => boolean
62 : }
63 :
64 : export type AddCreditsQuote =
65 : | { readonly status: 'loading' }
66 : | { readonly status: 'ok'; readonly credits: number }
67 : | { readonly status: 'unavailable' }
68 :
69 : export interface AddCreditsDialogOptions {
70 : readonly ports: AddCreditsPorts
71 : readonly facts: MaybeRefOrGetter<AddCreditsFacts>
72 : readonly initialAmount: AddCreditsAmount
73 : readonly autoTopUp?: MaybeRefOrGetter<AddCreditsAutoTopUpRequest>
74 : readonly onLanded?: () => void
75 : }
76 :
77 : /** Quote and checkout session from a billing client; the host still supplies the tab and the payment watch. */
78 : export function addCreditsClientPorts(
79 : client: {
80 : readonly topup: Pick<
81 : TopupCommand,
82 : 'quoteTopup' | 'createHostedTopupCheckout'
83 : >
84 : },
85 : returnUrl: () => string
86 : ): Pick<AddCreditsPorts, 'quote' | 'createCheckout'> {
87 : return {
88 : async quote(amountCents, signal) {
89 : const quoted = await client.topup.quoteTopup({ amountCents, signal })
90 : return quoted.status === 'ok'
91 : ? { status: 'ok', credits: quoted.value.credits }
92 : : { status: 'error' }
93 : },
94 : async createCheckout(amountCents, signal) {
95 : const session = await client.topup.createHostedTopupCheckout({
96 : amountCents,
97 : returnUrl: returnUrl(),
98 : signal
99 : })
100 : return session.status === 'ok'
101 : ? { status: 'ok', url: session.url }
102 : : { status: 'error', refusal: addCreditsRefusalFor(session) }
103 : }
104 : }
105 : }
106 :
107 : /** `window.open` inside the click; null when the browser blocks it. */
108 : export function reserveBrowserTab(): AddCreditsCheckoutTab | null {
109 : const opened = window.open('', '_blank')
110 : if (!opened) return null
111 : opened.opener = null
112 : return {
113 : navigate: (url) => opened.location.replace(url),
114 : close: () => opened.close()
115 : }
116 : }
117 :
118 0 : function landedEvent(
119 : setupUrl: string | null,
120 : activation: AutoTopUpActivationOutcome | undefined
121 : ): AddCreditsEvent {
122 0 : return {
123 : type: 'payment_landed',
124 : ...(setupUrl === null ? {} : { autoTopUpSetupUrl: setupUrl }),
125 : ...(activation === undefined ? {} : { activation })
126 : }
127 : }
128 :
129 4 : export function useAddCreditsDialog(options: AddCreditsDialogOptions) {
130 4 : const { ports } = options
131 4 : const state = shallowRef<AddCreditsState>(
132 : startAddCredits(options.initialAmount)
133 : )
134 4 : const dispatch = (event: AddCreditsEvent) => {
135 5 : state.value = reduceAddCredits(state.value, event)
136 : }
137 :
138 4 : const autoTopUpRequest = (): AddCreditsAutoTopUpRequest =>
139 : toValue(options.autoTopUp) ?? { kind: 'not_offered' }
140 :
141 4 : const pickedView = computed(() =>
142 : state.value.step === 'amount' || state.value.step === 'opening'
143 : ? viewAddCreditsAmount(state.value, toValue(options.facts))
144 : : undefined
145 : )
146 :
147 4 : const amountView = computed(() => {
148 9 : const view = pickedView.value
149 9 : return view && autoTopUpRequest().kind === 'invalid'
150 : ? { ...view, canContinue: false }
151 : : view
152 : })
153 :
154 4 : const quotedCents = computed(() =>
155 : amountView.value
156 : ? amountView.value.amountCents
157 : : 'amountCents' in state.value
158 : ? state.value.amountCents
159 : : undefined
160 : )
161 :
162 4 : const quoteRead = shallowRef<{
163 : readonly cents: number
164 : readonly quote: AddCreditsQuote
165 : }>()
166 4 : const quote = computed<AddCreditsQuote | undefined>(() => {
167 10 : const cents = quotedCents.value
168 10 : if (cents === undefined) return undefined
169 10 : return quoteRead.value?.cents === cents
170 : ? quoteRead.value.quote
171 : : { status: 'loading' }
172 : })
173 :
174 4 : let quoteScope: AbortController | undefined
175 4 : watch(
176 : quotedCents,
177 : async (cents) => {
178 5 : quoteScope?.abort()
179 5 : if (cents === undefined) return
180 5 : const scope = new AbortController()
181 5 : quoteScope = scope
182 5 : const result = await ports
183 : .quote(cents, scope.signal)
184 : .catch((): AddCreditsQuoteResult => ({ status: 'error' }))
185 5 : if (scope.signal.aborted) return
186 5 : quoteRead.value = {
187 : cents,
188 : quote:
189 : result.status === 'ok'
190 : ? { status: 'ok', credits: result.credits }
191 : : { status: 'unavailable' }
192 : }
193 : },
194 : { immediate: true }
195 : )
196 :
197 4 : let checkoutScope: AbortController | undefined
198 4 : let stopWatch: (() => void) | undefined
199 4 : let disposed = false
200 4 : let acceptedRequest: AddCreditsAutoTopUpRequest = { kind: 'not_offered' }
201 :
202 1 : function armPaymentWatch() {
203 1 : if (stopWatch) return
204 1 : stopWatch = ports.watchPayment((activation) => {
205 0 : stopWatch?.()
206 0 : stopWatch = undefined
207 0 : void land(activation)
208 : })
209 : }
210 :
211 0 : async function setupUrl(): Promise<string | null> {
212 0 : return ports.autoTopUpSetupUrl
213 : ? ports.autoTopUpSetupUrl().catch(() => null)
214 : : null
215 : }
216 :
217 0 : function setupUrlAfterPaying(
218 : activation: AutoTopUpActivationOutcome | undefined
219 : ): Promise<string | null> {
220 : const asks =
221 : activation?.status === 'failed' || acceptedRequest.kind === 'not_offered'
222 0 : return asks ? setupUrl() : Promise.resolve(null)
223 : }
224 :
225 0 : async function land(activation?: AutoTopUpActivationOutcome) {
226 0 : const url =
227 : activation?.status === 'on' ? null : await setupUrlAfterPaying(activation)
228 0 : if (disposed || ports.ownsCheckout?.() === false) return
229 0 : dispatch(landedEvent(url, activation))
230 0 : if (state.value.step === 'landed') options.onLanded?.()
231 : }
232 :
233 2 : async function openCheckout(
234 : amountCents: number,
235 : request: AddCreditsAutoTopUpRequest
236 : ) {
237 2 : const tab = ports.reserveTab()
238 2 : if (tab === null && ports.singleUseCheckout) {
239 0 : dispatch({ type: 'tab_blocked', amountCents })
240 0 : return
241 : }
242 2 : dispatch({
243 : type: 'checkout_requested',
244 : amountCents,
245 : tabReserved: tab !== null
246 : })
247 2 : const scope = new AbortController()
248 2 : checkoutScope = scope
249 2 : const session = await ports
250 : .createCheckout(
251 : amountCents,
252 : scope.signal,
253 : request.kind === 'checked' ? request.activation : undefined
254 : )
255 : .catch((): AddCreditsCheckoutResult => ({
256 : status: 'error',
257 : refusal: { kind: 'checkout_failed' }
258 : }))
259 2 : if (scope.signal.aborted) {
260 0 : tab?.close()
261 0 : dispatch({ type: 'checkout_abandoned' })
262 0 : return
263 : }
264 2 : if (session.status === 'error') {
265 1 : tab?.close()
266 1 : dispatch({ type: 'checkout_refused', refusal: session.refusal })
267 1 : return
268 : }
269 2 : tab?.navigate(session.url)
270 2 : dispatch({ type: 'checkout_created', checkoutUrl: session.url })
271 2 : armPaymentWatch()
272 : }
273 :
274 2 : function continueToCheckout() {
275 2 : const view = amountView.value
276 2 : if (!view?.canContinue || view.amountCents === undefined) return
277 2 : acceptedRequest = autoTopUpRequest()
278 2 : return openCheckout(view.amountCents, acceptedRequest)
279 : }
280 :
281 0 : function reopenCheckout() {
282 0 : const current = state.value
283 0 : if (
284 : (current.step !== 'checkout_opened' &&
285 : current.step !== 'checkout_blocked') ||
286 : !toValue(options.facts).canTopUp
287 : )
288 0 : return
289 0 : return openCheckout(current.amountCents, acceptedRequest)
290 : }
291 :
292 4 : onScopeDispose(() => {
293 0 : disposed = true
294 0 : quoteScope?.abort()
295 0 : checkoutScope?.abort()
296 0 : stopWatch?.()
297 : })
298 :
299 4 : return {
300 : state,
301 : amountView,
302 : pickedCents: computed(() => pickedView.value?.amountCents),
303 : quote,
304 : pickPreset: (cents: number) => dispatch({ type: 'preset_picked', cents }),
305 : typeAmount: (input: string) => dispatch({ type: 'amount_typed', input }),
306 : continueToCheckout,
307 : reopenCheckout,
308 : followBlockedLink: () => dispatch({ type: 'blocked_link_followed' })
309 : }
310 : }
|