Line data Source code
1 : import { openBillingUrl } from '@/platform/billing/billingTab'
2 : /**
3 : * The app's single billing SDK instance and the top-up effects the poller
4 : * performs today, moved onto the lifecycle's state: the progress toast and —
5 : * for an operation this tab reattached to rather than issued — the refresh,
6 : * dialog routing, toast, and telemetry that the dialog performs for the
7 : * operations it issues itself.
8 : */
9 : import type {
10 : BillingOperationKind,
11 : BillingOperationState,
12 : BillingEventsReadOptions,
13 : BillingOperationTelemetryEvent,
14 : BillingResult,
15 : CapabilitiesReadOptions,
16 : PendingBillingOperation,
17 : PreviewSubscribeInput,
18 : SubscribeInput
19 : } from '@comfyorg/account-core/billing'
20 : import {
21 : BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT,
22 : BILLING_OPERATION_TELEMETRY_EVENT,
23 : toBillingTelemetryEvent,
24 : validateActionUrl
25 : } from '@comfyorg/account-core/billing'
26 : import { until, useEventListener } from '@vueuse/core'
27 : import { defineStore } from 'pinia'
28 : import { computed, shallowRef } from 'vue'
29 :
30 : import { useToast } from '@/components/ui/toast/toastStore'
31 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
32 : import { t } from '@/i18n'
33 : import { webSessionRequests } from '@comfyorg/api-client/webSessionFetch'
34 : import { isCloud } from '@/platform/distribution/types'
35 : import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
36 : import { useTelemetry } from '@comfyorg/telemetry'
37 : import type {
38 : BillingBalanceResponse,
39 : BillingCapabilitiesRead,
40 : BillingEventsResponse,
41 : BillingPlansResponse,
42 : BillingStatusResponse,
43 : CreateTopupResponse,
44 : PreviewSubscribeResponse,
45 : SavedPaymentMethod
46 : } from '@comfyorg/billing-core'
47 : import { ingestApiUrl } from '@/platform/remote/ingest/ingestApiUrl'
48 : import { refreshBilling } from '@/platform/billing/billingRefresh'
49 : import type {
50 : ProgressToast,
51 : ProgressToastKind
52 : } from '@/platform/billing/customerAttention'
53 : import {
54 : isParkedCheckout,
55 : needsCustomerAttention,
56 : progressToastKind
57 : } from '@/platform/billing/customerAttention'
58 : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
59 : import { provideBillingSdkStore } from '@/platform/billing/composables/useBillingReadRail'
60 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
61 : import { useWorkspaceSession } from '@/platform/workspace/ports/workspaceSession'
62 : import { getCheckoutJourneyPaymentIntentSource } from '@/platform/billing/utils/checkoutJourney'
63 : import { useDialogStore } from '@/stores/dialogStore'
64 : import { fetchWithRetry } from '@comfyorg/api-client/fetchWithRetry'
65 :
66 : import { projectBillingBalance } from './billingBalanceView'
67 : import { projectBillingCapabilities } from './billingCapabilitiesView'
68 : import { projectBillingPlans } from './billingPlansView'
69 : import { projectBillingStatus } from './billingStatusView'
70 : import type { BillingSdkOptions } from '@comfyorg/billing-core/sdk'
71 : import { createBillingSdk } from '@comfyorg/billing-core/sdk'
72 : import type { TopupAutoTopUpSettings } from '@comfyorg/ingest-types'
73 : import type { BillingOperationRecordView } from './operationRecordView'
74 : import { projectOperationRecord } from './operationRecordView'
75 : import type {
76 : SettledCommand,
77 : SettledSubscribeResponse,
78 : SubscriptionRailOutcome
79 : } from './subscriptionOperationView'
80 : import {
81 : projectCancelOperationResult,
82 : projectPaymentPortalResult,
83 : projectPreviewSubscribeResult,
84 : projectSubscribeResult,
85 : projectSubscriptionResult
86 : } from './subscriptionOperationView'
87 : import type { HostedCheckoutSession } from './topupOperationView'
88 : import {
89 : declineDetail,
90 : projectHostedTopupCheckoutResult,
91 : projectTopupOperation,
92 : projectTopupResult
93 : } from './topupOperationView'
94 : import { createWebSessionBillingSession } from './webSessionBillingSession'
95 :
96 2356 : const PROGRESS_SUMMARY = {
97 : topup: {
98 : processing: 'billingOperation.topupProcessing',
99 : action: 'billingOperation.topupActionRequired'
100 : },
101 : subscription: {
102 : processing: 'billingOperation.subscriptionProcessing',
103 : action: 'billingOperation.subscriptionActionRequired'
104 : }
105 : } as const satisfies Record<string, Record<ProgressToastKind, string>>
106 :
107 2356 : const FRICTION_EVENT_NAMES: ReadonlySet<string> = new Set(
108 : Object.values(BILLING_CHECKOUT_FRICTION_TELEMETRY_EVENT)
109 : )
110 :
111 0 : function isFrictionEvent(event: BillingOperationTelemetryEvent): boolean {
112 0 : return FRICTION_EVENT_NAMES.has(event.name)
113 : }
114 :
115 2356 : export const useBillingSdkStore = defineStore('billingSdk', () => {
116 0 : const workspaceAuthStore = useWorkspaceSession()
117 0 : const workspaceStore = useWorkspaceIdentity()
118 0 : const toast = useToast()
119 0 : const { flags } = useFeatureFlags()
120 0 : const billingCapabilities = useBillingCapabilities()
121 :
122 0 : const operations = shallowRef<readonly BillingOperationState[]>([])
123 0 : const dismissed = shallowRef<ReadonlySet<string>>(new Set())
124 0 : const resumedOperations = new Set<string>()
125 0 : const callerStarted = new Set<BillingOperationKind>()
126 0 : const offeredActions = new Map<string, Set<string>>()
127 0 : const progressToasts = new Map<string, ProgressToast>()
128 0 : const closedProgressToasts = new Set<string>()
129 :
130 0 : function sessionPorts(): Pick<
131 : BillingSdkOptions,
132 : 'session' | 'scopeSource' | 'workspaceId'
133 : > {
134 0 : const requests = webSessionRequests()
135 0 : if (requests) {
136 0 : const session = createWebSessionBillingSession(requests)
137 0 : return {
138 : session,
139 : scopeSource: session,
140 : workspaceId: requests.workspaceId
141 : }
142 : }
143 0 : return {
144 : session: workspaceAuthStore.getUnifiedSessionClient(),
145 : workspaceId: () => workspaceAuthStore.getUnifiedMintWorkspaceId()
146 : }
147 : }
148 :
149 0 : const sdk = createBillingSdk({
150 : ...sessionPorts(),
151 : resolveUrl: ingestApiUrl,
152 : fetchImpl: fetchWithRetry,
153 : pointerStorage: sessionStorage,
154 : hostedDestination: () => flags.hostedBillingDestination,
155 : onTelemetry: reportTelemetry
156 : })
157 :
158 0 : sdk.lifecycle.subscribe((state) => {
159 0 : operations.value = sdk.lifecycle.getSnapshot()
160 0 : if (state.kind === 'topup') onTopupChanged(state)
161 0 : else onSubscriptionChanged(state)
162 : })
163 :
164 0 : const wake = () => {
165 0 : if (document.visibilityState === 'visible') sdk.lifecycle.wake()
166 : }
167 0 : useEventListener(document, 'visibilitychange', wake)
168 0 : useEventListener(window, 'focus', wake)
169 :
170 0 : const topupViews = computed(() =>
171 : operations.value
172 : .filter((state) => !dismissed.value.has(state.id))
173 : .flatMap((state) => projectTopupOperation(state) ?? [])
174 : )
175 0 : const isAddingCredits = computed(() =>
176 : topupViews.value.some(
177 : (view) =>
178 : view.status === 'pending' &&
179 : view.authenticationState !== 'failed_retryable'
180 : )
181 : )
182 0 : const topupActionOperation = computed(() =>
183 : topupViews.value.find(needsCustomerAttention)
184 : )
185 :
186 : // The lifecycle already refuses anything but https on the way in
187 : // (`operationLifecycle.ts` adoption, `operationState.ts` on every poll); the
188 : // same predicate runs again here so the rule holds for whoever publishes a
189 : // state, and so the guarantee is readable where the URL is handed out.
190 0 : const hostedActionUrl = (state: BillingOperationState): string | undefined =>
191 : state.phase === 'pending' ? validateActionUrl(state.actionUrl) : undefined
192 :
193 0 : const subscriptionActionUrl = computed(
194 : () =>
195 : operations.value.flatMap((state) =>
196 : state.kind === 'subscription' ? (hostedActionUrl(state) ?? []) : []
197 : )[0] ?? null
198 : )
199 :
200 : // The four below mirror `billingOperationStore`'s own predicates, including
201 : // where it does and does not scope to the active workspace: the lifecycle
202 : // keeps operations from a scope it has left, and a consumer switching rails
203 : // must not find a different answer on the other side.
204 0 : const operationRecords = computed(() =>
205 : operations.value.flatMap((state) => projectOperationRecord(state) ?? [])
206 : )
207 :
208 0 : const hasPendingOperations = computed(() =>
209 : operationRecords.value.some((record) => record.status === 'pending')
210 : )
211 :
212 0 : const isSettingUp = computed(() =>
213 : operationRecords.value.some(
214 : (record) =>
215 : record.kind === 'subscription' &&
216 : record.status === 'pending' &&
217 : record.authenticationState !== 'requires_action' &&
218 : record.authenticationState !== 'failed_retryable' &&
219 : !isParkedCheckout(record) &&
220 : record.workspaceId === workspaceStore.activeWorkspaceId
221 : )
222 : )
223 :
224 0 : const subscriptionActionOperation = computed(() =>
225 : operationRecords.value.find(
226 : (record) =>
227 : record.kind === 'subscription' &&
228 : record.workspaceId === workspaceStore.activeWorkspaceId &&
229 : needsCustomerAttention(record)
230 : )
231 : )
232 :
233 0 : function getOperation(opId: string): BillingOperationRecordView | undefined {
234 0 : return operationRecords.value.find((record) => record.opId === opId)
235 : }
236 :
237 : // A top-up the dialog issued is reported by the dialog, exactly as before;
238 : // the lifecycle's events stand in for the poller's only on an operation
239 : // this tab reattached to. A cancel or subscribe the caller announced with
240 : // its own `started` keeps that one event: the lifecycle's `started` is
241 : // dropped inside the caller's command window, and its terminal is always
242 : // forwarded, since only the lifecycle holds the operation's id, category
243 : // and timing. A command no caller announced — a resubscribe, a checkout
244 : // that reports nothing — is reported at both ends by the lifecycle.
245 : // Friction inside an operation has no other reporter, so it always goes.
246 0 : function reportTelemetry(event: BillingOperationTelemetryEvent) {
247 0 : if (isFrictionEvent(event)) {
248 0 : useTelemetry()?.trackBillingEvent(toBillingTelemetryEvent(event))
249 0 : return
250 : }
251 0 : if (event.operation_type === 'topup' && !event.resumed) return
252 0 : const started = event.name === BILLING_OPERATION_TELEMETRY_EVENT.started
253 0 : if (started && event.resumed) resumedOperations.add(event.billing_op_id)
254 0 : if (started && !event.resumed && callerStarted.has(event.operation_type)) {
255 0 : return
256 : }
257 0 : useTelemetry()?.trackBillingEvent(
258 : toBillingTelemetryEvent(
259 : event,
260 : getCheckoutJourneyPaymentIntentSource(event.billing_op_id)
261 : )
262 : )
263 : }
264 :
265 : // Sound because the lifecycle runs one command per kind at a time and
266 : // emits both of an issued operation's events before the command resolves.
267 0 : async function withCallerStart<T>(
268 : kind: BillingOperationKind,
269 : run: () => Promise<T>
270 : ): Promise<T> {
271 0 : callerStarted.add(kind)
272 0 : try {
273 0 : return await run()
274 : } finally {
275 0 : callerStarted.delete(kind)
276 : }
277 : }
278 :
279 0 : function onTopupChanged(state: BillingOperationState) {
280 0 : if (state.phase === 'pending') {
281 0 : syncProgressToast(state, 'topup')
282 0 : return
283 : }
284 0 : clearProgressToast(state.id)
285 0 : closedProgressToasts.delete(state.id)
286 0 : dismissed.value = new Set(
287 : [...dismissed.value].filter((id) => id !== state.id)
288 : )
289 0 : if (state.phase === 'timed_out') {
290 0 : toast.error(t('billingOperation.topupTimeout'))
291 : }
292 0 : if (resumedOperations.delete(state.id)) void settleResumed(state)
293 : }
294 :
295 0 : function syncProgressToast(
296 : state: PendingBillingOperation,
297 : kind: keyof typeof PROGRESS_SUMMARY
298 : ) {
299 0 : const progress = progressToastKind({
300 : actionUrl: state.actionUrl,
301 : phase: state.serverPhase
302 : })
303 0 : const current = progressToasts.get(state.id)
304 0 : if (current?.kind === progress) return
305 0 : if (current && toast.takeClosedByUser(current.id)) {
306 0 : closedProgressToasts.add(state.id)
307 : }
308 0 : clearProgressToast(state.id)
309 0 : if (
310 : progress === undefined ||
311 : (progress === 'processing' && closedProgressToasts.has(state.id))
312 : ) {
313 0 : return
314 : }
315 0 : const title = t(PROGRESS_SUMMARY[kind][progress])
316 0 : const id =
317 : progress === 'action' ? toast.warning(title) : toast.loading(title)
318 0 : progressToasts.set(state.id, { kind: progress, id })
319 : }
320 :
321 0 : function clearProgressToast(operationId: string) {
322 0 : const current = progressToasts.get(operationId)
323 0 : if (!current) return
324 0 : toast.dismiss(current.id)
325 0 : progressToasts.delete(operationId)
326 : }
327 :
328 0 : function onSubscriptionChanged(state: BillingOperationState) {
329 0 : if (state.phase !== 'pending') {
330 0 : clearProgressToast(state.id)
331 0 : closedProgressToasts.delete(state.id)
332 0 : offeredActions.delete(state.id)
333 0 : if (resumedOperations.delete(state.id)) {
334 0 : void settleResumedSubscription(state)
335 : }
336 0 : return
337 : }
338 0 : if (state.kind === 'subscription') syncProgressToast(state, 'subscription')
339 0 : if (resumedOperations.has(state.id)) return
340 0 : openHostedAction(state)
341 : }
342 :
343 0 : function openHostedStep(operationId: string, actionUrl: string): boolean {
344 0 : if (!openBillingUrl(actionUrl)) return false
345 0 : sdk.lifecycle.reportHostedStepOpened(operationId, 'new_tab')
346 0 : return true
347 : }
348 :
349 0 : function isHostedStepOwed(operationId: string, actionUrl: string): boolean {
350 0 : const current = sdk.lifecycle.get(operationId)
351 0 : return current !== undefined && hostedActionUrl(current) === actionUrl
352 : }
353 :
354 0 : function openHostedAction(state: PendingBillingOperation) {
355 0 : const actionUrl = hostedActionUrl(state)
356 0 : if (actionUrl === undefined) return
357 0 : const offered = offeredActions.get(state.id) ?? new Set<string>()
358 0 : if (offered.has(actionUrl)) return
359 0 : offeredActions.set(state.id, offered.add(actionUrl))
360 0 : if (openHostedStep(state.id, actionUrl)) return
361 0 : toast.warning(t('g.warning'), {
362 : description: t('subscription.preview.paymentPopupBlocked'),
363 : action: {
364 : label: t('subscription.planLoadErrorRetry'),
365 : onClick: () => {
366 0 : if (isHostedStepOwed(state.id, actionUrl)) {
367 0 : openHostedStep(state.id, actionUrl)
368 : }
369 : }
370 : }
371 : })
372 : }
373 :
374 0 : async function settleResumed(state: BillingOperationState) {
375 0 : if (state.phase === 'succeeded') {
376 0 : await Promise.allSettled([
377 : refreshBilling('account'),
378 : billingCapabilities.refresh()
379 : ])
380 0 : useDialogStore().closeDialog({ key: 'top-up-credits' })
381 0 : useSettingsDialog().show(isCloud ? 'workspace' : 'credits')
382 0 : toast.success(t('billingOperation.topupSuccess'), {
383 : duration: 5000
384 : })
385 0 : return
386 : }
387 0 : if (state.phase === 'failed') {
388 0 : toast.error(t('billingOperation.topupFailed'), {
389 : description: declineDetail(state.declineReason),
390 : duration: 7000
391 : })
392 : }
393 : }
394 :
395 : // A subscribe this tab reattached to after a reload has no checkout left to
396 : // report it, so it settles the way the poller settled it. Only a subscribe
397 : // is ever reattached: the status names a pending subscription or top-up.
398 0 : async function settleResumedSubscription(state: BillingOperationState) {
399 0 : if (state.phase === 'succeeded') {
400 0 : await refreshAfterSubscriptionChange()
401 0 : toast.success(t('billingOperation.subscriptionSuccess'), {
402 : duration: 5000
403 : })
404 0 : return
405 : }
406 0 : if (state.phase === 'timed_out') {
407 0 : toast.error(t('billingOperation.subscriptionTimeout'))
408 0 : return
409 : }
410 0 : if (state.phase === 'failed') {
411 0 : toast.error(t('billingOperation.subscriptionFailed'), {
412 : description: declineDetail(state.declineReason),
413 : duration: 7000
414 : })
415 : }
416 : }
417 :
418 0 : async function createTopup(
419 : amountCents: number
420 : ): Promise<CreateTopupResponse | undefined> {
421 0 : const result = await sdk.topup.createTopupCheckout({ amountCents })
422 0 : if (result.status === 'ok') void billingCapabilities.refresh()
423 0 : return projectTopupResult(result, amountCents)
424 : }
425 :
426 0 : async function quoteTopup(
427 : amountCents: number,
428 : signal: AbortSignal
429 : ): Promise<number | null> {
430 0 : const quoted = await sdk.topup.quoteTopup({ amountCents, signal })
431 0 : return quoted.status === 'ok' ? quoted.value.credits : null
432 : }
433 :
434 0 : async function createHostedTopupCheckout(
435 : amountCents: number,
436 : returnUrl: string,
437 : signal?: AbortSignal,
438 : autoTopUp?: TopupAutoTopUpSettings
439 : ): Promise<HostedCheckoutSession> {
440 0 : return projectHostedTopupCheckoutResult(
441 : await sdk.topup.createHostedTopupCheckout({
442 : amountCents,
443 : returnUrl,
444 : ...(signal === undefined ? {} : { signal }),
445 : ...(autoTopUp === undefined ? {} : { autoTopUp })
446 : })
447 : )
448 : }
449 :
450 : // The backend gate on these routes is independent of the client flag, so a
451 : // 404 means the rail is on too early. One answer settles it for the tab:
452 : // every later action goes straight to the legacy call.
453 0 : const subscriptionRouteAvailable = shallowRef(true)
454 :
455 0 : async function onSubscriptionRoute<T>(
456 : run: () => Promise<SubscriptionRailOutcome<T>>
457 : ): Promise<SubscriptionRailOutcome<T>> {
458 0 : if (!subscriptionRouteAvailable.value) return { status: 'unavailable' }
459 0 : const outcome = await run()
460 0 : if (outcome.status === 'unavailable') {
461 0 : subscriptionRouteAvailable.value = false
462 : }
463 0 : return outcome
464 : }
465 :
466 0 : async function runSubscriptionCommand<T>(
467 : command: () => Promise<SubscriptionRailOutcome<T>>,
468 : refresh: () => Promise<void>
469 : ): Promise<SubscriptionRailOutcome<T>> {
470 0 : const outcome = await onSubscriptionRoute(command)
471 0 : if (outcome.status === 'ok') await refresh()
472 0 : return outcome
473 : }
474 :
475 : // What the poller refreshes when one of its operations succeeds, so the
476 : // panels read the same state whichever rail settled the operation.
477 0 : async function refreshAfterCancel(): Promise<void> {
478 0 : await Promise.allSettled([
479 : refreshBilling('account'),
480 : billingCapabilities.refresh()
481 : ])
482 : }
483 :
484 0 : async function refreshAfterSubscriptionChange(): Promise<void> {
485 0 : await Promise.allSettled([
486 : refreshBilling('subscription'),
487 : billingCapabilities.refresh()
488 : ])
489 : }
490 :
491 0 : function cancelSubscription(): Promise<
492 : SubscriptionRailOutcome<SettledCommand>
493 : > {
494 0 : return withCallerStart('cancel', () =>
495 : runSubscriptionCommand(
496 : async () =>
497 : projectSubscriptionResult(await sdk.commands.cancelSubscription()),
498 : refreshAfterCancel
499 : )
500 : )
501 : }
502 :
503 0 : function resubscribe(): Promise<SubscriptionRailOutcome<SettledCommand>> {
504 0 : return runSubscriptionCommand(
505 : async () => projectSubscriptionResult(await sdk.commands.resubscribe()),
506 : refreshAfterSubscriptionChange
507 : )
508 : }
509 :
510 0 : function subscribe(
511 : input: SubscribeInput,
512 : { callerStarted: announced = false }: { callerStarted?: boolean } = {}
513 : ): Promise<SubscriptionRailOutcome<SettledSubscribeResponse>> {
514 0 : const run = () =>
515 : runSubscriptionCommand(
516 : async () => projectSubscribeResult(await sdk.commands.subscribe(input)),
517 : refreshAfterSubscriptionChange
518 : )
519 0 : return announced ? withCallerStart('subscription', run) : run()
520 : }
521 :
522 : // A quote changes nothing, so it refreshes nothing; it shares the route
523 : // latch because the backend gates it with the rest of them.
524 0 : async function previewSubscribe(
525 : input: PreviewSubscribeInput
526 : ): Promise<SubscriptionRailOutcome<PreviewSubscribeResponse>> {
527 0 : return onSubscriptionRoute(async () =>
528 : projectPreviewSubscribeResult(await sdk.commands.previewSubscribe(input))
529 : )
530 : }
531 :
532 0 : async function openPaymentPortal(
533 : returnUrl: string
534 : ): Promise<SubscriptionRailOutcome<string>> {
535 0 : const outcome = await onSubscriptionRoute(async () =>
536 : projectPaymentPortalResult(
537 : await sdk.commands.openPaymentPortal({ returnUrl })
538 : )
539 : )
540 : // The portal may add or remove a card and says nothing on the way back, so
541 : // handing the URL out is the last moment this tab's list is known good.
542 0 : if (outcome.status === 'ok') sdk.paymentMethods.invalidate()
543 0 : return outcome
544 : }
545 :
546 0 : async function cancelOperation(
547 : opId: string
548 : ): Promise<SubscriptionRailOutcome> {
549 0 : return projectCancelOperationResult(
550 : await sdk.commands.cancelOperation(opId)
551 : )
552 : }
553 :
554 : /** Adopts the operation the server reports pending; true once one is adopted. */
555 0 : async function recover(): Promise<boolean> {
556 0 : const adopted = await sdk.lifecycle.recover()
557 0 : return adopted.status === 'ok' && adopted.value !== undefined
558 : }
559 :
560 : /**
561 : * Adopt the operation the server reports pending and resolve once it settles,
562 : * for the caller that has something to decide on the outcome.
563 : * `lifecycle.recover()` resolves at adoption, not at settlement, and it
564 : * adopts whatever the server names — so an id other than the one asked for
565 : * means the pointer this caller held is stale.
566 : */
567 0 : async function recoverPendingOperation(
568 : opId: string
569 : ): Promise<BillingOperationRecordView | undefined> {
570 0 : const adopted = await sdk.lifecycle.recover()
571 0 : if (adopted.status === 'error' || adopted.value?.id !== opId) {
572 0 : return undefined
573 : }
574 0 : const record = computed(() => getOperation(opId))
575 0 : return until(record).toMatch(
576 : (view) => view === undefined || view.status !== 'pending'
577 : )
578 : }
579 :
580 : // The readers the commands above already refresh after a success, exposed
581 : // so the panels read the state the rail settled rather than a second read
582 : // through the workspace client.
583 0 : async function readStatus(): Promise<BillingResult<BillingStatusResponse>> {
584 0 : const result = await sdk.status.read()
585 0 : if (result.status === 'error') return result
586 0 : const status = projectBillingStatus(result.value.status)
587 0 : return status === undefined
588 : ? { status: 'error', code: 'MALFORMED_RESPONSE' }
589 : : { status: 'ok', value: status }
590 : }
591 :
592 0 : async function readBalance(): Promise<BillingResult<BillingBalanceResponse>> {
593 0 : const result = await sdk.credits.read()
594 0 : return result.status === 'ok'
595 : ? { status: 'ok', value: projectBillingBalance(result.value.balance) }
596 : : result
597 : }
598 :
599 0 : async function readPlans(): Promise<BillingResult<BillingPlansResponse>> {
600 0 : const result = await sdk.plans.read()
601 0 : if (result.status === 'error') return result
602 0 : const plans = projectBillingPlans(result.value.data)
603 0 : return plans === undefined
604 : ? { status: 'error', code: 'MALFORMED_RESPONSE' }
605 : : { status: 'ok', value: plans }
606 : }
607 :
608 0 : async function readCapabilities(
609 : options: CapabilitiesReadOptions
610 : ): Promise<BillingResult<BillingCapabilitiesRead>> {
611 0 : const result = await sdk.capabilities.read(options)
612 0 : return result.status === 'ok'
613 : ? { status: 'ok', value: projectBillingCapabilities(result.value) }
614 : : result
615 : }
616 :
617 0 : async function readPaymentMethods(): Promise<
618 : BillingResult<SavedPaymentMethod[]>
619 : > {
620 0 : const result = await sdk.paymentMethods.read()
621 0 : return result.status === 'ok'
622 : ? { status: 'ok', value: [...result.value.methods] }
623 : : result
624 : }
625 :
626 : // The one read with nothing to project: the events response carries no
627 : // int64, so the decoded page already holds the numbers the host's type
628 : // says it does. Only the scope and read instant the snapshot adds are
629 : // dropped here.
630 0 : async function readEvents(
631 : options?: BillingEventsReadOptions
632 : ): Promise<BillingResult<BillingEventsResponse>> {
633 0 : const result = await sdk.events.read(options)
634 0 : if (result.status === 'error') return result
635 0 : const { events, page, limit, total, totalPages } = result.value
636 0 : return {
637 : status: 'ok',
638 : value: { events: [...events], page, limit, total, totalPages }
639 : }
640 : }
641 :
642 0 : function dismissOperation(operationId: string) {
643 0 : dismissed.value = new Set([...dismissed.value, operationId])
644 : }
645 :
646 0 : return {
647 : isAddingCredits,
648 : topupActionOperation,
649 : subscriptionActionUrl,
650 : hasPendingOperations,
651 : isSettingUp,
652 : subscriptionActionOperation,
653 : subscriptionRouteAvailable,
654 : getOperation,
655 : recoverPendingOperation,
656 : createTopup,
657 : createHostedTopupCheckout,
658 : quoteTopup,
659 : subscribe,
660 : previewSubscribe,
661 : cancelSubscription,
662 : resubscribe,
663 : openPaymentPortal,
664 : cancelOperation,
665 : recover,
666 : readStatus,
667 : readBalance,
668 : readPlans,
669 : readCapabilities,
670 : readPaymentMethods,
671 : readEvents,
672 : dismissOperation
673 : }
674 : })
675 :
676 2356 : provideBillingSdkStore(useBillingSdkStore)
|