Line data Source code
1 : <template>
2 8 : <AddCreditsDialog
3 : :ports
4 : :can-top-up="canTopUp && !readingActivation"
5 : :top-up-denial="topUpDenial ?? undefined"
6 : :min-topup-cents="balance?.minTopupCents"
7 : :max-topup-cents="balance?.maxTopupCents"
8 : :suggested-topup-cents="balance?.suggestedTopupAmountCents"
9 : :negative-balance-credits="negativeBalanceCredits"
10 : :pending-topup="pendingTopup"
11 : :plan-line="planLine"
12 : :auto-top-up="autoTopUpChoice.offer.value"
13 : :billing-url="autoTopUpChoice.billingUrl.value"
14 : :host-opens-billing="opensLocalBillingHandoff()"
15 : :opens-in="handsPopupsToSystemBrowser() ? 'browser' : 'tab'"
16 : :support-url="billingSupportUrl"
17 : :locale
18 : :translate
19 : :title-as="DialogTitle"
20 : @close="close"
21 : @open-billing="autoTopUpChoice.open"
22 : @set-up-auto-top-up="autoTopUpOffer.open"
23 : @decline-auto-top-up="autoTopUpOffer.trackDeclined"
24 : >
25 : <template v-if="isInsufficientCredits" #description>
26 : <p class="m-0 text-muted-foreground">
27 : {{ $t('credits.topUp.insufficientWorkflowMessage') }}
28 : </p>
29 : </template>
30 : </AddCreditsDialog>
31 : </template>
32 :
33 : <script setup lang="ts">
34 : import { computed, nextTick, onMounted, shallowRef, watch } from 'vue'
35 : import { useI18n } from 'vue-i18n'
36 :
37 : import type { AddCreditsTranslate } from '@comfyorg/account-core/billing'
38 : import { addCreditsRefusalFor } from '@comfyorg/account-core/billing'
39 : import type { AddCreditsPorts } from '@comfyorg/account-ui/billing'
40 : import { AddCreditsDialog } from '@comfyorg/account-ui/billing'
41 : import DialogTitle from '@comfyorg/design-system/dialog/DialogTitle'
42 : import { useTelemetry } from '@comfyorg/telemetry'
43 : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
44 :
45 : import { centsToCredits } from '@/base/credits/comfyCredits'
46 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
47 : import {
48 : addCreditsPendingTopup,
49 : topupCheckoutFailure
50 : } from '@/platform/billing/addCredits/addCreditsFacts'
51 : import { readAutoTopUpActivation } from '@/platform/billing/addCredits/autoTopUpActivation'
52 : import { billingApi } from '@/platform/billing/api/billingApi'
53 : import { reserveBillingTab } from '@/platform/billing/billingTab'
54 : import {
55 : issueLocalBillingHandoff,
56 : reserveBillingHandoffTab
57 : } from '@/platform/billing/localBillingHandoff'
58 : import { opensLocalBillingHandoff } from '@/platform/billing/localBillingWebEnabled'
59 : import { handsPopupsToSystemBrowser } from '@/platform/distribution/desktopBrowser'
60 : import { watchForTopupBalanceUpdate } from '@/platform/billing/composables/topupBalanceRefresh'
61 : import { useAddCreditsAutoTopUpOffer } from '@/platform/billing/composables/useAddCreditsAutoTopUpOffer'
62 : import { useAutoTopUpSetupOffer } from '@/platform/billing/composables/useAutoTopUpSetupOffer'
63 : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
64 : import { useBillingContext } from '@/platform/billing/composables/useBillingContext'
65 : import { usePendingTopup } from '@/platform/billing/composables/usePendingTopup'
66 : import { useProcessingTopupPayment } from '@/platform/billing/composables/useProcessingTopupPayment'
67 : import { useBillingDialogsAccess } from '@/platform/billing/subscription/composables/billingDialogsAccess'
68 : import { useAddCreditsPlanLine } from '@/platform/billing/composables/useTopUpPlanCreditCopy'
69 : import { useTopupOperation } from '@/platform/billing/composables/useTopupOperation'
70 : import { topupCheckoutReturnUrl } from '@/platform/billing/topupCheckoutReturnUrl'
71 : import {
72 : resolveCheckoutAssignment,
73 : resolveCheckoutJourney,
74 : resolveEntrySource
75 : } from '@/platform/billing/utils/checkoutJourney'
76 : import {
77 : trackCheckoutJourneyPhase,
78 : useCheckoutJourneyExit
79 : } from '@/platform/billing/utils/checkoutJourneyTelemetry'
80 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
81 : import { api } from '@/scripts/api'
82 : import { useAuthStore } from '@/stores/authStore'
83 : import { useDialogStore } from '@/stores/dialogStore'
84 : import { buildSupportFormUrl } from '@/utils/supportFormUrl'
85 :
86 : const { isInsufficientCredits = false, source } = defineProps<{
87 : isInsufficientCredits?: boolean
88 : source?: PaymentIntentSource
89 : }>()
90 :
91 2356 : const BILLING_SUPPORT_URL =
92 : 'https://comfysupport.portal.usepylon.com/forms/billing-refund-issue'
93 :
94 4 : const authStore = useAuthStore()
95 4 : const billingSupportUrl = computed(() =>
96 : buildSupportFormUrl(BILLING_SUPPORT_URL, {
97 : email: authStore.userEmail,
98 : userId: authStore.userId
99 : })
100 : )
101 :
102 4 : const { t, locale } = useI18n()
103 4 : const translate: AddCreditsTranslate = (key, params = {}) =>
104 : t(`addCreditsDialog.${key}`, params)
105 :
106 4 : const dialogStore = useDialogStore()
107 4 : const { flags } = useFeatureFlags()
108 4 : const telemetry = useTelemetry()
109 4 : const workspaceIdentity = useWorkspaceIdentity()
110 4 : const { balance, fetchBalance, fetchStatus } = useBillingContext()
111 4 : const { canTopUp, topUpDenial } = useBillingCapabilities()
112 4 : const autoTopUpOffer = useAutoTopUpSetupOffer()
113 4 : const autoTopUpChoice = useAddCreditsAutoTopUpOffer()
114 4 : const { payment: processingPayment } = useProcessingTopupPayment()
115 4 : const { topupOperation, createHostedCheckout, quoteTopup } = useTopupOperation()
116 4 : const planLine = useAddCreditsPlanLine()
117 :
118 4 : const negativeBalanceCredits = computed(() => {
119 4 : const info = balance.value
120 4 : const cents = info?.effectiveBalanceMicros
121 4 : if (cents === undefined || cents >= 0) return undefined
122 4 : if (info?.effectiveBalanceAuthoritative === false) return undefined
123 0 : return centsToCredits(-cents)
124 : })
125 :
126 4 : const pendingTopup = computed(() =>
127 : addCreditsPendingTopup(topupOperation.value, processingPayment.value)
128 : )
129 :
130 4 : let paymentWatched = false
131 4 : const readingActivation = shallowRef(false)
132 :
133 : interface OwnedCheckout {
134 : readonly generation: number
135 : readonly activationSessionId?: string
136 : }
137 4 : let ownedCheckout: OwnedCheckout | undefined
138 1 : function ownsCheckout(
139 : checkout: OwnedCheckout | undefined
140 : ): checkout is OwnedCheckout {
141 1 : return (
142 : checkout?.generation === workspaceIdentity.workspaceTransitionGeneration
143 : )
144 : }
145 :
146 4 : const opensHandoff = opensLocalBillingHandoff()
147 :
148 0 : async function reopenForCurrentFlag(): Promise<void> {
149 0 : close()
150 0 : await nextTick()
151 0 : await useBillingDialogsAccess().showTopUpCreditsDialog({
152 : isInsufficientCredits,
153 : source
154 : })
155 : }
156 :
157 2 : async function createHandoffCheckout(
158 : amountCents: number,
159 : signal: AbortSignal
160 : ): ReturnType<AddCreditsPorts['createCheckout']> {
161 2 : const generation = workspaceIdentity.workspaceTransitionGeneration
162 2 : const issued = await issueLocalBillingHandoff(
163 : { intent: 'top-up', amountCents },
164 : signal
165 : )
166 2 : if (issued.status === 'error') {
167 1 : return {
168 : status: 'error',
169 : refusal: {
170 : kind: 'checkout_failed',
171 : ...(issued.message === undefined
172 : ? {}
173 : : { serverMessage: issued.message })
174 : }
175 : }
176 : }
177 1 : ownedCheckout = { generation }
178 1 : return { status: 'ok', url: issued.url }
179 : }
180 :
181 4 : const ports: AddCreditsPorts = {
182 : async quote(amountCents, signal) {
183 5 : const credits = await quoteTopup(amountCents, signal)
184 5 : return credits === null ? { status: 'error' } : { status: 'ok', credits }
185 : },
186 : get activatesAutoTopUp() {
187 0 : return !opensHandoff && flags.billingAutoTopUpAtCheckoutEnabled
188 : },
189 : singleUseCheckout: opensHandoff,
190 : async createCheckout(amountCents, signal, autoTopUp) {
191 2 : telemetry?.trackBillingEvent({
192 : operation: 'topup',
193 : stage: 'intent',
194 : outcome: 'pending',
195 : payment_intent_source: source
196 : })
197 2 : if (opensLocalBillingHandoff() !== opensHandoff) {
198 0 : void reopenForCurrentFlag()
199 0 : return { status: 'error', refusal: { kind: 'checkout_failed' } }
200 : }
201 2 : if (opensHandoff) return createHandoffCheckout(amountCents, signal)
202 0 : const returnUrl = topupCheckoutReturnUrl()
203 0 : if (!returnUrl) {
204 0 : return { status: 'error', refusal: { kind: 'checkout_failed' } }
205 : }
206 0 : const generation = workspaceIdentity.workspaceTransitionGeneration
207 2 : try {
208 0 : if (!balance.value) await Promise.allSettled([fetchBalance()])
209 0 : const { url, sessionId } = await createHostedCheckout(
210 : amountCents,
211 : returnUrl,
212 : signal,
213 : autoTopUp
214 : )
215 2 : const checkout = {
216 : generation,
217 : activationSessionId: autoTopUp && sessionId
218 : }
219 2 : if (!ownsCheckout(checkout)) {
220 0 : return { status: 'error', refusal: { kind: 'checkout_failed' } }
221 : }
222 0 : ownedCheckout = checkout
223 0 : return { status: 'ok', url }
224 : } catch (error) {
225 0 : return {
226 : status: 'error',
227 : refusal: addCreditsRefusalFor(topupCheckoutFailure(error))
228 : }
229 : }
230 : },
231 : reserveTab: opensHandoff ? reserveBillingHandoffTab : reserveBillingTab,
232 : watchPayment(landed) {
233 1 : if (!ownsCheckout(ownedCheckout)) return () => {}
234 1 : paymentWatched = true
235 1 : usePendingTopup().startPendingTopup()
236 1 : const scope = new AbortController()
237 1 : const stopOnWorkspaceChange = watch(
238 : () => workspaceIdentity.workspaceTransitionGeneration,
239 : () => scope.abort()
240 : )
241 1 : const stop = watchForTopupBalanceUpdate({
242 : onBalanceIncreased: async () => {
243 0 : const checkout = ownedCheckout
244 0 : if (!ownsCheckout(checkout)) return
245 0 : const { activationSessionId } = checkout
246 0 : if (activationSessionId === undefined) return landed()
247 0 : readingActivation.value = true
248 0 : const activation = await readAutoTopUpActivation(
249 : (signal) => billingApi.getTopupCheckout(activationSessionId, signal),
250 : scope.signal
251 : ).catch(() => null)
252 0 : if (activation !== null && ownsCheckout(checkout)) landed(activation)
253 : },
254 : source: {
255 : current: () => balance.value?.amountMicros ?? null,
256 : fetch: async () => {
257 0 : const [balanceRead, statusRead] = await Promise.allSettled([
258 : fetchBalance(),
259 : fetchStatus()
260 : ])
261 0 : if (balanceRead.status === 'rejected') throw balanceRead.reason
262 0 : if (statusRead.status === 'rejected') throw statusRead.reason
263 0 : return balance.value?.amountMicros ?? null
264 : }
265 : }
266 : })
267 1 : return () => {
268 0 : scope.abort()
269 0 : stopOnWorkspaceChange()
270 0 : stop()
271 : }
272 : },
273 : autoTopUpSetupUrl: autoTopUpOffer.setupUrl,
274 : ownsCheckout: () => ownsCheckout(ownedCheckout)
275 : }
276 :
277 0 : function close() {
278 0 : if (!paymentWatched && !topupOperation.value) {
279 0 : usePendingTopup().clearPendingTopup()
280 : }
281 0 : dialogStore.closeDialog({ key: 'top-up-credits' })
282 : }
283 :
284 4 : function enterTopupJourney(): void {
285 4 : const workspaceId = workspaceIdentity.activeWorkspaceId
286 4 : const ownerUid = useAuthStore().userId
287 4 : if (!workspaceId || !ownerUid) return
288 :
289 4 : const entrySource = resolveEntrySource(source, 'settings_billing')
290 4 : const resolved = resolveCheckoutJourney({
291 : actorUid: ownerUid,
292 : workspaceId,
293 : entryFlow: 'topup',
294 : entrySource,
295 : paymentIntentSource: source,
296 : intent: entrySource,
297 : assignment: resolveCheckoutAssignment(api.getServerFeatures())
298 : })
299 4 : if (resolved.status === 'blocked' || resolved.resumed) return
300 :
301 4 : trackCheckoutJourneyPhase(resolved.record, { phase: 'entered' })
302 : }
303 :
304 4 : onMounted(enterTopupJourney)
305 4 : useCheckoutJourneyExit()
306 : </script>
|