Line data Source code
1 : <template>
2 0 : <Card class="flex min-h-[500px] w-[min(512px,95vw)] flex-col shadow-md">
3 : <!-- Header -->
4 : <div class="flex items-center justify-between p-8">
5 : <div class="flex items-center gap-2">
6 : <button
7 : v-if="step === 'confirm'"
8 : class="cursor-pointer rounded-sm border-none bg-transparent p-0 text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-40"
9 : :disabled="paymentLocked"
10 : :aria-label="$t('g.back')"
11 : @click="showAmountStep"
12 : >
13 : <i class="icon-[lucide--arrow-left] size-5" />
14 : </button>
15 : <DialogTitle
16 : v-if="step === 'amount' || step === 'confirm'"
17 : class="m-0 font-bold"
18 : >
19 : {{
20 : step === 'confirm'
21 : ? $t('credits.topUp.confirmTitle')
22 : : isInsufficientCredits
23 : ? $t('credits.topUp.addMoreCreditsToRun')
24 : : $t('credits.topUp.addMoreCredits')
25 : }}
26 : </DialogTitle>
27 : </div>
28 : <button
29 : class="cursor-pointer rounded-sm border-none bg-transparent p-0 text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
30 : :aria-label="$t('g.close')"
31 : @click="
32 : () =>
33 : handleClose(
34 : !topupIsParkedWithoutLink &&
35 : step !== 'checkoutOpened' &&
36 : step !== 'checkoutBlocked'
37 : )
38 : "
39 : >
40 : <i class="icon-[lucide--x] size-6" />
41 : </button>
42 : </div>
43 : <p
44 : v-if="isInsufficientCredits && step === 'amount'"
45 : class="m-0 px-8 pb-4 text-sm text-muted-foreground"
46 : >
47 : {{ $t('credits.topUp.insufficientWorkflowMessage') }}
48 : </p>
49 :
50 : <template v-if="step === 'confirm'">
51 : <p class="m-0 px-8 text-sm text-muted-foreground">
52 : {{ $t('credits.topUp.confirmSubtitle') }}
53 : </p>
54 : <div class="flex flex-col gap-3 px-8 pt-6 font-semibold">
55 : <span class="flex items-center gap-2 py-2 text-2xl tabular-nums">
56 : <i class="icon-[lucide--coins] size-5 text-credit" />
57 : {{ formatNumber(creditsModel) }}
58 : </span>
59 : <div class="flex items-center justify-between border-t pt-4 text-base">
60 : <span>
61 : {{ $t('subscription.preview.totalDueToday') }}
62 : </span>
63 : <span class="tabular-nums">
64 : {{ displayTotal }}
65 : </span>
66 : </div>
67 : </div>
68 : <p
69 : v-if="checkoutRecovery === 'refused'"
70 : class="m-0 px-8 pt-4 text-sm text-muted-foreground"
71 : >
72 : {{ $t('credits.topUp.noPaymentMethodCheckoutHint') }}
73 : </p>
74 : <p
75 : v-else-if="checkoutRecovery === 'failed'"
76 : role="alert"
77 : class="m-0 px-8 pt-4 text-sm text-destructive"
78 : >
79 : {{ checkoutRefusal ?? $t('credits.topUp.checkoutOpenFailed') }}
80 : </p>
81 : </template>
82 :
83 : <div
84 : v-if="step === 'checkoutOpened'"
85 : class="flex flex-col items-center gap-3 px-8 text-center"
86 : >
87 : <DialogTitle class="m-0 text-center text-xl lg:text-2xl">
88 : {{ $t('credits.topUp.checkoutOpenedTitle') }}
89 : </DialogTitle>
90 : <p class="m-0 text-sm text-balance text-muted-foreground">
91 : {{ $t('credits.topUp.checkoutOpenedBody') }}
92 : </p>
93 : <p
94 : v-if="checkoutReopenFailed"
95 : role="alert"
96 : class="m-0 text-sm text-destructive"
97 : >
98 : {{ checkoutRefusal ?? $t('credits.topUp.checkoutOpenFailed') }}
99 : </p>
100 : </div>
101 :
102 : <div
103 : v-if="step === 'checkoutBlocked'"
104 : class="flex flex-col items-center gap-3 px-8 text-center"
105 : >
106 : <DialogTitle class="m-0 text-center text-xl lg:text-2xl">
107 : {{ $t('credits.topUp.checkoutBlockedTitle') }}
108 : </DialogTitle>
109 : <p class="m-0 text-sm text-balance text-muted-foreground">
110 : {{ $t('credits.topUp.checkoutBlockedBody') }}
111 : </p>
112 : </div>
113 :
114 : <div
115 : v-if="step === 'defaultCardBlocked'"
116 : class="flex flex-col items-center gap-3 px-8 text-center"
117 : >
118 : <DialogTitle class="m-0 text-center text-xl lg:text-2xl">
119 : {{ $t('credits.topUp.defaultCardBlockedTitle') }}
120 : </DialogTitle>
121 : <p class="m-0 text-sm text-balance text-muted-foreground">
122 : {{ $t('credits.topUp.defaultCardBlockedBody') }}
123 : </p>
124 : </div>
125 :
126 : <template v-if="step === 'verifying'">
127 : <div class="flex flex-col items-center gap-3 px-8 text-center">
128 : <i class="icon-[lucide--shield-alert] size-10 text-warning" />
129 : <DialogTitle class="m-0 text-xl lg:text-2xl">
130 : {{ $t('credits.topUp.verifyTitle') }}
131 : </DialogTitle>
132 : <p class="m-0 text-sm text-balance text-muted-foreground">
133 : {{ verifyingBody }}
134 : </p>
135 : <span v-if="topupReconciliationOperationId" class="font-mono text-sm">
136 : {{ topupReconciliationOperationId }}
137 : </span>
138 : </div>
139 : </template>
140 :
141 : <TopUpAmountFields
142 : v-if="step === 'amount'"
143 : :pay-amount
144 : :credits="creditsModel"
145 : :selected-preset
146 : :max-amount="maxTopup.usd"
147 : :max-credits="maxTopup.credits"
148 : :plan-credit-copy
149 : @preset="handlePresetClick"
150 : @pay-amount="handlePayAmountChange"
151 : @credits="creditsModel = $event"
152 : />
153 :
154 : <!-- Warnings -->
155 :
156 : <p
157 : v-if="negativeBalanceCredits !== null && step === 'amount'"
158 : class="m-0 px-8 pt-4 text-sm text-muted-foreground"
159 : >
160 : {{
161 : $t(
162 : 'credits.topUp.negativeBalanceNotice',
163 : { credits: formatNumber(negativeBalanceCredits) },
164 : negativeBalanceCredits
165 : )
166 : }}
167 : </p>
168 : <p
169 : v-if="isBelowMin && step === 'amount'"
170 : class="m-0 flex items-center justify-center gap-1 px-8 pt-4 text-center text-sm text-destructive"
171 : >
172 : <i class="icon-[lucide--coins]" />
173 : {{
174 : $t('credits.topUp.minRequired', {
175 : credits: formatNumber(minTopup.credits)
176 : })
177 : }}
178 : </p>
179 : <p
180 : v-if="showCeilingWarning && step === 'amount'"
181 : class="m-0 flex items-center justify-center gap-1 px-8 pt-4 text-center text-sm text-warning"
182 : >
183 : <i class="icon-[lucide--coins]" />
184 : {{
185 : $t('credits.topUp.maxAllowed', {
186 : credits: formatNumber(maxTopup.credits)
187 : })
188 : }}
189 : <span>{{ $t('credits.topUp.needMore') }}</span>
190 : <a
191 : href="https://comfy.org/cloud/enterprise/"
192 : target="_blank"
193 : class="ml-1 text-inherit"
194 : >{{ $t('credits.topUp.contactUs') }}</a
195 : >
196 : </p>
197 :
198 : <div class="mt-auto flex flex-col gap-8 p-8">
199 : <div v-if="step === 'verifying'">
200 : <Button
201 : v-if="topupIsFailedRetryable"
202 : variant="primary"
203 : size="lg"
204 : class="w-full"
205 : @click="startOverTopup"
206 : >
207 : {{ $t('credits.topUp.startOver') }}
208 : </Button>
209 : <Button
210 : v-else-if="topupIsParkedWithoutLink"
211 : variant="secondary"
212 : size="lg"
213 : class="w-full"
214 : @click="() => handleClose(false)"
215 : >
216 : {{ $t('g.ok') }}
217 : </Button>
218 : <Button
219 : v-else-if="!topupReconciliationOperationId"
220 : variant="primary"
221 : size="lg"
222 : class="w-full"
223 : :disabled="!topupActionUrl || !canTopUp"
224 : :loading="!topupActionUrl"
225 : :aria-label="$t('subscription.preview.completeVerification')"
226 : @click="openTopupVerification"
227 : >
228 : {{ $t('subscription.preview.completeVerification') }}
229 : </Button>
230 : </div>
231 : <div
232 : v-else-if="step === 'checkoutOpened'"
233 : class="flex flex-col items-center gap-4"
234 : >
235 : <Button
236 : variant="secondary"
237 : size="lg"
238 : class="w-full"
239 : @click="() => handleClose(false)"
240 : >
241 : {{ $t('g.close') }}
242 : </Button>
243 : <Button
244 : variant="link"
245 : size="md"
246 : :disabled="!canTopUp"
247 : :loading
248 : @click="reopenCheckout"
249 : >
250 : {{ $t('credits.topUp.reopenCheckout') }}
251 : <i class="icon-[lucide--external-link]" />
252 : </Button>
253 : </div>
254 : <Button
255 : v-else-if="step === 'checkoutBlocked'"
256 : variant="primary"
257 : size="lg"
258 : class="w-full"
259 : :loading="loading"
260 : @click="retryBlockedCheckout"
261 : >
262 : {{ $t('credits.topUp.openCheckout') }}
263 : <i class="icon-[lucide--external-link]" />
264 : </Button>
265 : <Button
266 : v-else-if="step === 'defaultCardBlocked' && blockedDefaultCardUrl"
267 : as="a"
268 : :href="blockedDefaultCardUrl"
269 : target="_blank"
270 : rel="noopener"
271 : variant="primary"
272 : size="lg"
273 : class="w-full no-underline"
274 : @click="followBlockedDefaultCardLink"
275 : >
276 : {{ $t('credits.topUp.openPaymentPage') }}
277 : <i class="icon-[lucide--external-link]" />
278 : </Button>
279 : <div v-else class="flex flex-col gap-2">
280 : <div
281 : v-if="processingPayment && step === 'amount'"
282 : role="status"
283 : class="flex flex-col gap-1 rounded-2xl border border-border/60 p-4"
284 : data-testid="topup-payment-processing-notice"
285 : >
286 : <div class="flex items-center gap-2">
287 : <i
288 : class="icon-[lucide--circle-alert] text-muted-foreground"
289 : aria-hidden="true"
290 : />
291 : <span class="text-sm text-foreground">{{
292 : processingNoticeTitle
293 : }}</span>
294 : </div>
295 : <p class="m-0 pl-6 text-sm text-muted-foreground">
296 : {{ $t('credits.topUp.paymentProcessingBody') }}
297 : </p>
298 : </div>
299 : <TopUpAutoTopUpCard
300 : v-if="step === 'amount' && !processingPayment"
301 : class="mb-2"
302 : />
303 : <Button
304 : v-if="step === 'confirm' && topupActionUrl && canTopUp"
305 : variant="primary"
306 : size="lg"
307 : @click="openTopupVerification"
308 : >
309 : {{ $t('subscription.preview.completeVerification') }}
310 : </Button>
311 : <Button
312 : v-if="step === 'confirm' && checkoutRecovery"
313 : variant="primary"
314 : size="lg"
315 : :disabled="!isValidAmount || paymentLocked || !canTopUp"
316 : :loading="paymentInFlight"
317 : @click="continueToCheckout"
318 : >
319 : {{ $t('credits.topUp.continueToCheckout') }}
320 : <i class="icon-[lucide--external-link]" />
321 : </Button>
322 : <Button
323 : v-else
324 : :disabled="!isValidAmount || paymentLocked || !canTopUp"
325 : :loading="paymentInFlight"
326 : :variant="
327 : step === 'confirm' && topupActionUrl ? 'tertiary' : 'primary'
328 : "
329 : size="lg"
330 : class="tabular-nums"
331 : :data-dd-action-name="BILLING_ACTION_NAME.topUpPrimary"
332 : @click="handlePrimaryAction"
333 : >
334 : {{
335 : step === 'confirm'
336 : ? $t('credits.topUp.payAmount', { amount: displayTotal })
337 : : $t('subscription.addCredits')
338 : }}
339 : </Button>
340 : <Button
341 : v-if="step === 'confirm' && checkoutRecovery"
342 : variant="secondary"
343 : size="lg"
344 : :disabled="paymentLocked"
345 : :loading="openingDefaultCardPortal"
346 : @click="setDefaultCard"
347 : >
348 : {{ $t('credits.topUp.setDefaultCard') }}
349 : </Button>
350 : </div>
351 : <div
352 : v-if="step === 'amount'"
353 : class="flex items-center justify-center gap-1"
354 : >
355 : <a
356 : :href="pricingUrl"
357 : target="_blank"
358 : class="flex items-center gap-1 text-sm text-muted-foreground no-underline transition-colors hover:text-foreground"
359 : >
360 : {{ $t('credits.topUp.viewPricing') }}
361 : <i class="icon-[lucide--external-link]" />
362 : </a>
363 : </div>
364 : </div>
365 : </Card>
366 : </template>
367 :
368 : <script setup lang="ts">
369 : import Card from '@comfyorg/design-system/card/Card'
370 : import { BILLING_ACTION_NAME } from '@/platform/telemetry/billingActionNames'
371 : import type { BillingOperationTerminal } from '@comfyorg/account-core/billing'
372 : import {
373 : getTopupAmountPreset,
374 : PURCHASE_REFUSAL_SERVER_CODES
375 : } from '@comfyorg/account-core/billing'
376 : import { useToast } from '@/components/ui/toast/toastStore'
377 : import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
378 : import { useI18n } from 'vue-i18n'
379 :
380 : import {
381 : centsToCredits,
382 : creditsToUsd,
383 : formatUsdFromCents,
384 : usdToCredits
385 : } from '@/base/credits/comfyCredits'
386 : import Button from '@comfyorg/design-system/button/Button'
387 : import DialogTitle from '@comfyorg/design-system/dialog/DialogTitle'
388 : import TopUpAmountFields from '@/platform/billing/components/TopUpAmountFields.vue'
389 : import TopUpAutoTopUpCard from '@/platform/billing/components/TopUpAutoTopUpCard.vue'
390 : import { watchForTopupBalanceUpdate } from '@/platform/billing/composables/topupBalanceRefresh'
391 : import { useTopUpPlanCreditCopy } from '@/platform/billing/legacy160/platform/billing/composables/useTopUpPlanCreditCopy'
392 : import { useBillingContext } from '@/platform/billing/composables/useBillingContext'
393 : import { useExternalLink } from '@/composables/useExternalLink'
394 : import { useTelemetry } from '@comfyorg/telemetry'
395 : import { usePendingTopup } from '@/platform/billing/composables/usePendingTopup'
396 : import { isCloud } from '@/platform/distribution/types'
397 : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
398 : import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory'
399 : import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog'
400 : import type { CreateTopupResponse } from '@comfyorg/billing-core'
401 : import { billingApi } from '@/platform/billing/api/billingApi'
402 : import { WorkspaceApiError } from '@/platform/remote/ingest/ingestApiError'
403 : import type { BillingTab } from '@/platform/billing/billingTab'
404 : import { reserveBillingTab } from '@/platform/billing/billingTab'
405 : import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn'
406 : import { topupCheckoutReturnUrl } from '@/platform/billing/topupCheckoutReturnUrl'
407 : import { isBlockedOnCustomerPhase } from '@/platform/billing/customerAttention'
408 : import { UncreditedTopupResponse } from '@/platform/billing/sdk/topupOperationView'
409 : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
410 : import { useProcessingTopupPayment } from '@/platform/billing/composables/useProcessingTopupPayment'
411 : import { useTopupOperation } from '@/platform/billing/composables/useTopupOperation'
412 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
413 : import {
414 : bindOperationToCheckoutJourney,
415 : clearCheckoutJourney,
416 : getActiveCheckoutJourney,
417 : resolveCheckoutAssignment,
418 : resolveCheckoutJourney,
419 : resolveEntrySource
420 : } from '@/platform/billing/utils/checkoutJourney'
421 : import {
422 : trackCheckoutJourneyPhase,
423 : useCheckoutJourneyExit
424 : } from '@/platform/billing/utils/checkoutJourneyTelemetry'
425 : import { api } from '@/scripts/api'
426 : import { useAuthStore } from '@/stores/authStore'
427 : import { useDialogStore } from '@/stores/dialogStore'
428 : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
429 :
430 : const { isInsufficientCredits = false, source } = defineProps<{
431 : isInsufficientCredits?: boolean
432 : source?: PaymentIntentSource
433 : }>()
434 :
435 0 : const { d, locale, n, t } = useI18n()
436 0 : const { payment: processingPayment } = useProcessingTopupPayment()
437 0 : const processingNoticeTitle = computed(() => {
438 0 : const cents = processingPayment.value?.paymentAmountCents
439 0 : if (typeof cents !== 'number')
440 0 : return t('credits.topUp.paymentProcessingTitleNoAmount')
441 0 : return t('credits.topUp.paymentProcessingTitle', {
442 : amount: formatUsdFromCents({
443 : cents,
444 : locale: locale.value,
445 : numberOptions: {
446 : style: 'currency',
447 : currency: 'USD',
448 : minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
449 : maximumFractionDigits: cents % 100 === 0 ? 0 : 2
450 : }
451 : })
452 : })
453 : })
454 0 : const dialogStore = useDialogStore()
455 0 : const settingsDialog = useSettingsDialog()
456 0 : const telemetry = useTelemetry()
457 0 : const toast = useToast()
458 0 : const { buildDocsUrl, docsPaths } = useExternalLink()
459 0 : const { balance, fetchBalance, fetchStatus } = useBillingContext()
460 0 : const planCreditCopy = useTopUpPlanCreditCopy()
461 : const billingCapabilities = useBillingCapabilities()
462 0 : const { canTopUp } = billingCapabilities
463 :
464 0 : const workspaceStore = useWorkspaceIdentity()
465 :
466 0 : function enterTopupJourney(): void {
467 0 : const workspaceId = workspaceStore.activeWorkspaceId
468 0 : const ownerUid = useAuthStore().userId
469 0 : if (!workspaceId || !ownerUid) return
470 :
471 0 : const entrySource = resolveEntrySource(source, 'settings_billing')
472 0 : const resolved = resolveCheckoutJourney({
473 : actorUid: ownerUid,
474 : workspaceId,
475 : entryFlow: 'topup',
476 : entrySource,
477 : paymentIntentSource: source,
478 : intent: entrySource,
479 : assignment: resolveCheckoutAssignment(api.getServerFeatures())
480 : })
481 0 : if (resolved.status === 'blocked' || resolved.resumed) return
482 :
483 0 : trackCheckoutJourneyPhase(resolved.record, { phase: 'entered' })
484 : }
485 :
486 0 : onMounted(enterTopupJourney)
487 0 : useCheckoutJourneyExit()
488 0 : const {
489 : billingClient,
490 : isAddingCredits,
491 : topupOperation,
492 : topup,
493 : createHostedCheckout,
494 : dismissOperation,
495 : adoptPendingOperation
496 : } = useTopupOperation()
497 : // Start over invalidates the attempt in flight: on the SDK rail the purchase
498 : // call resolves only at settlement, so a superseded attempt must not unlock
499 : // or close the dialog for the attempt that replaced it.
500 0 : let purchaseAttempt = 0
501 0 : const topupActionUrl = computed(() => topupOperation.value?.actionUrl ?? null)
502 0 : const topupAuthenticationError = computed(
503 : () => topupOperation.value?.errorMessage ?? null
504 : )
505 0 : const topupIsFailedRetryable = computed(
506 : () => topupOperation.value?.authenticationState === 'failed_retryable'
507 : )
508 : // Parked on the customer with no link to send them to. The operation stays open
509 : // server-side, and that also refuses a replacement purchase, so this state
510 : // explains the wait rather than offering a restart that would be rejected.
511 : // Leaving this screen keeps the pending-top-up marker: the copy sends the
512 : // customer off to pay elsewhere, and the marker outlives the wait, so it is
513 : // what refreshes the balance when they come back to a settled purchase.
514 : // Latent on this rail today — only the legacy hosted-checkout path sets the
515 : // marker, so usually there is none here to keep. Preserving it is still right,
516 : // and it starts paying off if this rail ever sets one when it parks.
517 0 : const topupIsParkedWithoutLink = computed(
518 : () =>
519 : !topupActionUrl.value &&
520 : isBlockedOnCustomerPhase(topupOperation.value?.phase)
521 : )
522 0 : const topupReconciliationOperationId = computed(() =>
523 : topupOperation.value?.status === 'reconciliation_needed'
524 : ? topupOperation.value.opId
525 : : null
526 : )
527 0 : const verifyingBody = computed(() => {
528 0 : if (topupReconciliationOperationId.value) {
529 0 : return t('billingOperation.reconciliationDetail')
530 : }
531 0 : if (topupAuthenticationError.value) return topupAuthenticationError.value
532 0 : if (topupIsParkedWithoutLink.value) {
533 0 : return t('credits.topUp.awaitingBankApprovalBody')
534 : }
535 0 : const deadline = new Date(topupOperation.value?.authenticationDeadline ?? '')
536 0 : if (Number.isNaN(deadline.getTime())) return t('credits.topUp.verifyBody')
537 0 : return t('credits.topUp.verifyByBody', {
538 : date: d(deadline, { month: 'long', day: 'numeric' }),
539 : time: d(deadline, { hour: 'numeric', minute: '2-digit' })
540 : })
541 : })
542 :
543 : // Constants
544 2356 : const MIN_AMOUNT = 5
545 2356 : const MAX_AMOUNT = 10000
546 2356 : const DEFAULT_AMOUNT = 50
547 :
548 0 : function wholeDollarsOrNull(cents: number | null | undefined): number | null {
549 0 : if (cents == null) return null
550 0 : const dollars = cents / 100
551 0 : return Number.isInteger(dollars) ? dollars : null
552 : }
553 :
554 : // State
555 0 : const suggestedAmount = computed(() =>
556 : wholeDollarsOrNull(balance.value?.suggestedTopupAmountCents)
557 : )
558 0 : const selectedPreset = ref<number | null>(
559 : suggestedAmount.value === null ? DEFAULT_AMOUNT : null
560 : )
561 0 : const payAmount = ref(suggestedAmount.value ?? DEFAULT_AMOUNT)
562 0 : const amountEditedByUser = ref(false)
563 :
564 0 : watch(suggestedAmount, (amount) => {
565 0 : if (amount === null || amountEditedByUser.value || step.value !== 'amount')
566 0 : return
567 0 : payAmount.value = amount
568 0 : selectedPreset.value = null
569 : })
570 0 : const loading = ref(false)
571 0 : const paymentSubmitted = ref(false)
572 0 : const checkoutRecovery = ref<'refused' | 'failed' | null>(null)
573 0 : const checkoutRefusal = ref<string | null>(null)
574 0 : const blockedDefaultCardUrl = ref<string | null>(null)
575 0 : const checkoutReopenFailed = ref(false)
576 0 : const stepBeforeCheckoutBlocked = ref<'confirm' | 'checkoutOpened'>('confirm')
577 0 : const step = ref<
578 : | 'amount'
579 : | 'confirm'
580 : | 'verifying'
581 : | 'checkoutOpened'
582 : | 'checkoutBlocked'
583 : | 'defaultCardBlocked'
584 : >(topupOperation.value && canTopUp.value ? 'verifying' : 'amount')
585 :
586 : // Computed
587 0 : const pricingUrl = computed(() =>
588 : buildDocsUrl(docsPaths.partnerNodesPricing, { includeLocale: true })
589 : )
590 :
591 0 : const creditsModel = computed({
592 : get: () => usdToCredits(payAmount.value),
593 : set: (newCredits: number) => {
594 0 : payAmount.value = Math.round(creditsToUsd(newCredits))
595 0 : selectedPreset.value = null
596 0 : amountEditedByUser.value = true
597 : }
598 : })
599 :
600 0 : function servedBoundOr(
601 : fallbackUsd: number,
602 : cents: number | undefined,
603 : credits: number | undefined
604 : ) {
605 0 : return cents === undefined || credits === undefined
606 : ? { usd: fallbackUsd, credits: usdToCredits(fallbackUsd) }
607 : : { usd: cents / 100, credits }
608 : }
609 :
610 0 : const minTopup = computed(() =>
611 : servedBoundOr(
612 : MIN_AMOUNT,
613 : balance.value?.minTopupCents,
614 : balance.value?.minTopupCredits
615 : )
616 : )
617 0 : const maxTopup = computed(() =>
618 : servedBoundOr(
619 : MAX_AMOUNT,
620 : balance.value?.maxTopupCents,
621 : balance.value?.maxTopupCredits
622 : )
623 : )
624 :
625 0 : const isValidAmount = computed(
626 : () =>
627 : payAmount.value >= minTopup.value.usd &&
628 : payAmount.value <= maxTopup.value.usd
629 : )
630 :
631 0 : const negativeBalanceCredits = computed(() => {
632 0 : const info = balance.value
633 0 : const cents = info?.effectiveBalanceMicros
634 0 : if (cents === undefined || cents >= 0) return null
635 0 : if (info?.effectiveBalanceAuthoritative === false) return null
636 0 : return centsToCredits(-cents)
637 : })
638 :
639 0 : const isBelowMin = computed(() => payAmount.value < minTopup.value.usd)
640 0 : const showCeilingWarning = computed(() => payAmount.value >= maxTopup.value.usd)
641 :
642 0 : const displayTotal = computed(() =>
643 : n(payAmount.value, {
644 : style: 'currency',
645 : currency: 'USD',
646 : minimumFractionDigits: 2,
647 : maximumFractionDigits: 2
648 : })
649 : )
650 :
651 0 : const paymentInFlight = computed(
652 : () =>
653 : loading.value ||
654 : paymentSubmitted.value ||
655 : isAddingCredits.value ||
656 : !!topupOperation.value
657 : )
658 :
659 0 : const openingDefaultCardPortal = ref(false)
660 :
661 0 : const paymentLocked = computed(
662 : () => paymentInFlight.value || openingDefaultCardPortal.value
663 : )
664 :
665 0 : watch(
666 : [isAddingCredits, topupOperation, canTopUp],
667 : ([addingCredits, operation, allowed]) => {
668 0 : if (addingCredits || operation) loading.value = false
669 0 : if (step.value === 'verifying' && !addingCredits && !operation) {
670 0 : step.value = 'amount'
671 0 : return
672 : }
673 0 : if (operation && allowed) {
674 0 : step.value = 'verifying'
675 : }
676 : }
677 : )
678 :
679 : // Utility functions
680 0 : function formatNumber(num: number): string {
681 0 : return num.toLocaleString('en-US')
682 : }
683 :
684 : // Event handlers
685 0 : function handlePayAmountChange(value: number) {
686 0 : payAmount.value = value
687 0 : selectedPreset.value = null
688 0 : amountEditedByUser.value = true
689 : }
690 :
691 0 : function handlePresetClick(amount: number) {
692 0 : payAmount.value = amount
693 0 : selectedPreset.value = amount
694 0 : amountEditedByUser.value = true
695 : }
696 :
697 0 : function handlePrimaryAction() {
698 0 : if (step.value === 'amount') {
699 0 : telemetry?.trackBillingEvent({
700 : operation: 'topup',
701 : stage: 'intent',
702 : outcome: 'pending',
703 : payment_intent_source: source
704 : })
705 0 : step.value = 'confirm'
706 0 : return
707 : }
708 0 : void handleBuy()
709 : }
710 :
711 0 : function openTopupVerification() {
712 0 : if (!topupActionUrl.value) return
713 0 : window.open(topupActionUrl.value, '_blank', 'noopener,noreferrer')
714 : }
715 :
716 0 : function showAmountStep() {
717 0 : stopPayOfferOnCardReturn()
718 0 : checkoutRecovery.value = null
719 0 : step.value = 'amount'
720 : }
721 :
722 0 : function startOverTopup() {
723 0 : purchaseAttempt += 1
724 0 : const operation = topupOperation.value
725 0 : if (operation) dismissOperation(operation.opId)
726 0 : paymentSubmitted.value = false
727 0 : showAmountStep()
728 : }
729 :
730 0 : function handleClose(clearTracking = true) {
731 0 : if (clearTracking) {
732 0 : usePendingTopup().clearPendingTopup()
733 : }
734 0 : dialogStore.closeDialog({ key: 'top-up-credits' })
735 : }
736 :
737 0 : async function handleBuy() {
738 0 : if (paymentLocked.value || !isValidAmount.value || !canTopUp.value) {
739 0 : return
740 : }
741 :
742 0 : purchaseAttempt += 1
743 0 : const attempt = purchaseAttempt
744 0 : const isCurrentAttempt = () => attempt === purchaseAttempt
745 0 : checkoutRecovery.value = null
746 0 : loading.value = true
747 0 : paymentSubmitted.value = true
748 0 : const attemptStartedAt = Date.now()
749 0 : const amountCents = payAmount.value * 100
750 0 : try {
751 0 : telemetry?.trackApiCreditTopupButtonPurchaseClicked(payAmount.value)
752 0 : telemetry?.trackBillingEvent({
753 : operation: 'topup',
754 : stage: 'started',
755 : outcome: 'pending',
756 : payment_intent_source: source,
757 : amount_cents: amountCents,
758 : amount_preset: getTopupAmountPreset(selectedPreset.value)
759 : })
760 0 : telemetry?.trackBillingEvent({
761 : operation: 'operation',
762 : stage: 'started',
763 : outcome: 'pending',
764 : operation_type: 'topup',
765 : billing_client: billingClient
766 : })
767 :
768 0 : const submittingJourney = getActiveCheckoutJourney()
769 0 : if (submittingJourney) {
770 0 : trackCheckoutJourneyPhase(submittingJourney, { phase: 'submitted' })
771 : }
772 :
773 0 : const response = await topup(amountCents)
774 0 : if (!response) {
775 0 : if (isCurrentAttempt()) paymentSubmitted.value = false
776 0 : reportTerminal(attemptStartedAt, {
777 : stage: 'failed',
778 : outcome: 'failure',
779 : failure_category: 'unknown'
780 : })
781 0 : return
782 : }
783 :
784 : // Only correlate the response to the journey that submitted it: the user
785 : // may have closed this dialog and started another journey while the
786 : // request was in flight, and that later journey must not be bound here.
787 : const submittingJourneyStillActive =
788 : submittingJourney !== null &&
789 : getActiveCheckoutJourney()?.journey_id === submittingJourney.journey_id
790 0 : if (submittingJourneyStillActive) {
791 0 : const linkedJourney = bindOperationToCheckoutJourney(
792 : response.billing_op_id
793 : )
794 0 : if (linkedJourney) {
795 0 : trackCheckoutJourneyPhase(linkedJourney, {
796 : phase: 'operation_linked',
797 : billing_op_id: response.billing_op_id
798 : })
799 : }
800 : }
801 :
802 0 : reportResponseTerminal(response, attemptStartedAt)
803 :
804 0 : if (response.status === 'completed') {
805 0 : if (
806 : getActiveCheckoutJourney()?.billing_op_id === response.billing_op_id
807 : ) {
808 0 : clearCheckoutJourney()
809 : }
810 0 : toast.success(t('credits.topUp.purchaseSuccess'), { duration: 5000 })
811 0 : await Promise.allSettled([fetchBalance(), fetchStatus()])
812 0 : if (!isCurrentAttempt()) return
813 0 : handleClose(false)
814 0 : settingsDialog.show(isCloud ? 'workspace' : 'credits')
815 0 : } else if (response.status === 'pending') {
816 0 : void adoptPendingOperation(response.billing_op_id, {
817 : attemptStartedAt,
818 : paymentIntentSource: source
819 : })
820 : .then(() => {
821 0 : if (isCurrentAttempt()) paymentSubmitted.value = false
822 : })
823 : .catch(() => {
824 0 : reportPurchaseError(
825 : attemptStartedAt,
826 : response.billing_op_id,
827 : undefined,
828 : isCurrentAttempt()
829 : )
830 : })
831 : } else {
832 0 : if (isCurrentAttempt()) paymentSubmitted.value = false
833 0 : toast.error(t('credits.topUp.purchaseError'), {
834 : description: t('credits.topUp.unknownError')
835 : })
836 : }
837 : } catch (error) {
838 0 : reportPurchaseError(attemptStartedAt, undefined, error, isCurrentAttempt())
839 : } finally {
840 0 : if (isCurrentAttempt()) loading.value = false
841 : }
842 : }
843 :
844 0 : function reportPurchaseError(
845 : attemptStartedAt: number,
846 : billingOpId?: string,
847 : error?: unknown,
848 : currentAttempt = true
849 : ) {
850 0 : if (currentAttempt) paymentSubmitted.value = false
851 0 : console.error('Purchase failed', ...(error === undefined ? [] : [error]))
852 :
853 0 : reportTerminal(
854 : attemptStartedAt,
855 : {
856 : stage: 'failed',
857 : outcome: 'failure',
858 : failure_category:
859 : error === undefined ? 'unknown' : categorizeBillingApiError(error)
860 : },
861 : billingOpId
862 : )
863 0 : if (isNoPaymentMethodRefusal(error)) {
864 0 : if (currentAttempt) checkoutRecovery.value = 'refused'
865 0 : return
866 : }
867 0 : toast.error(t('credits.topUp.purchaseError'), {
868 : description: purchaseErrorDetail(error)
869 : })
870 : }
871 :
872 0 : function isNoPaymentMethodRefusal(error: unknown): boolean {
873 0 : return (
874 : error instanceof WorkspaceApiError && error.code === 'NO_PAYMENT_METHOD'
875 : )
876 : }
877 :
878 0 : let unmounted = false
879 0 : let stopDefaultCardReturnRefresh: (() => void) | null = null
880 0 : let checkoutScope: AbortController | null = null
881 0 : watch(
882 : () => workspaceStore.workspaceTransitionGeneration,
883 : () => {
884 0 : checkoutScope?.abort()
885 0 : stopPayOfferOnCardReturn()
886 : },
887 : { flush: 'sync' }
888 : )
889 0 : onUnmounted(() => {
890 0 : unmounted = true
891 0 : checkoutScope?.abort()
892 0 : stopPayOfferOnCardReturn()
893 : })
894 :
895 0 : function watchCheckoutCompletion() {
896 0 : usePendingTopup().startPendingTopup()
897 0 : step.value = 'checkoutOpened'
898 0 : watchForTopupBalanceUpdate({
899 : onBalanceIncreased: async () => {
900 0 : if (!unmounted) handleClose(false)
901 : },
902 : source: {
903 : current: () => balance.value?.amountMicros ?? null,
904 : fetch: async () => {
905 0 : const [balanceRead, statusRead] = await Promise.allSettled([
906 : fetchBalance(),
907 : fetchStatus()
908 : ])
909 0 : if (balanceRead.status === 'rejected') throw balanceRead.reason
910 0 : if (statusRead.status === 'rejected') throw statusRead.reason
911 0 : return balance.value?.amountMicros ?? null
912 : }
913 : }
914 : })
915 : }
916 :
917 0 : function stopPayOfferOnCardReturn() {
918 0 : stopDefaultCardReturnRefresh?.()
919 0 : stopDefaultCardReturnRefresh = null
920 : }
921 :
922 0 : function offerPayOnCardReturn() {
923 0 : stopPayOfferOnCardReturn()
924 0 : const launchedGeneration = workspaceStore.workspaceTransitionGeneration
925 0 : stopDefaultCardReturnRefresh = registerRefreshOnReturn(async () => {
926 0 : stopPayOfferOnCardReturn()
927 0 : if (step.value !== 'confirm') return
928 0 : if (workspaceStore.workspaceTransitionGeneration !== launchedGeneration) {
929 0 : return
930 : }
931 0 : checkoutRecovery.value = null
932 : })
933 : }
934 :
935 0 : async function setDefaultCard() {
936 0 : if (paymentLocked.value) return
937 0 : const portalTab = reserveBillingTab()
938 0 : openingDefaultCardPortal.value = true
939 0 : try {
940 0 : const { url } = await billingApi.getPaymentPortalUrl(
941 : window.location.href,
942 : 'payment_method_update'
943 : )
944 0 : if (unmounted) {
945 0 : portalTab?.close()
946 0 : return
947 : }
948 0 : if (!url) return reportDefaultCardPortalFailure(portalTab)
949 0 : if (!portalTab) {
950 0 : blockedDefaultCardUrl.value = url
951 0 : step.value = 'defaultCardBlocked'
952 0 : return
953 : }
954 0 : portalTab.navigate(url)
955 0 : offerPayOnCardReturn()
956 : } catch {
957 0 : reportDefaultCardPortalFailure(portalTab)
958 : } finally {
959 0 : openingDefaultCardPortal.value = false
960 : }
961 : }
962 :
963 0 : function followBlockedDefaultCardLink() {
964 0 : step.value = 'confirm'
965 0 : offerPayOnCardReturn()
966 : }
967 :
968 0 : function reportDefaultCardPortalFailure(portalTab: BillingTab | null) {
969 0 : portalTab?.close()
970 0 : if (unmounted) return
971 0 : toast.error(t('credits.topUp.setDefaultCardError'), {
972 : description: t('credits.topUp.unknownError')
973 : })
974 : }
975 :
976 0 : async function continueToCheckout() {
977 0 : if (!(canTopUp.value && isValidAmount.value && !paymentLocked.value)) {
978 0 : return
979 : }
980 0 : if ((await openCheckoutInReservedTab()) === 'failed') {
981 0 : checkoutRecovery.value = 'failed'
982 : }
983 : }
984 :
985 0 : async function retryBlockedCheckout() {
986 0 : if (!canTopUp.value || loading.value) return
987 0 : const returnStep = stepBeforeCheckoutBlocked.value
988 0 : if ((await openCheckoutInReservedTab()) !== 'failed') return
989 0 : step.value = returnStep
990 0 : if (returnStep === 'checkoutOpened') checkoutReopenFailed.value = true
991 0 : else checkoutRecovery.value = 'failed'
992 : }
993 :
994 0 : async function reopenCheckout() {
995 0 : if (!canTopUp.value || loading.value) return
996 0 : checkoutReopenFailed.value = false
997 0 : checkoutReopenFailed.value = (await openCheckoutInReservedTab()) === 'failed'
998 : }
999 :
1000 0 : async function openCheckoutInReservedTab(): Promise<
1001 : 'opened' | 'blocked' | 'failed' | 'abandoned'
1002 : > {
1003 0 : checkoutRefusal.value = null
1004 0 : const returnUrl = topupCheckoutReturnUrl()
1005 0 : if (!returnUrl) return 'failed'
1006 0 : const checkoutTab = reserveBillingTab()
1007 0 : if (!checkoutTab) {
1008 0 : if (step.value === 'confirm' || step.value === 'checkoutOpened') {
1009 0 : stepBeforeCheckoutBlocked.value = step.value
1010 : }
1011 0 : step.value = 'checkoutBlocked'
1012 0 : return 'blocked'
1013 : }
1014 0 : const scope = new AbortController()
1015 0 : checkoutScope = scope
1016 0 : loading.value = true
1017 0 : try {
1018 0 : if (!balance.value) await Promise.allSettled([fetchBalance()])
1019 0 : const { url: checkoutUrl } = await createHostedCheckout(
1020 : payAmount.value * 100,
1021 : returnUrl,
1022 : scope.signal
1023 : )
1024 0 : if (unmounted || scope.signal.aborted) {
1025 0 : checkoutTab.close()
1026 0 : return 'abandoned'
1027 : }
1028 0 : checkoutTab.navigate(checkoutUrl)
1029 0 : watchCheckoutCompletion()
1030 0 : return 'opened'
1031 : } catch (error) {
1032 0 : checkoutTab.close()
1033 0 : console.error('Hosted top-up checkout failed to open', error)
1034 0 : checkoutRefusal.value = purchaseRefusalMessage(error)
1035 0 : return unmounted || scope.signal.aborted ? 'abandoned' : 'failed'
1036 : } finally {
1037 0 : if (checkoutScope === scope) checkoutScope = null
1038 0 : loading.value = false
1039 : }
1040 : }
1041 :
1042 : /**
1043 : * The terminal a response's status implies. A synchronous `failed` is a
1044 : * declined charge, not a pre-attempt rejection; a `pending` one is the
1045 : * poller's to report once it settles.
1046 : */
1047 0 : const RESPONSE_TERMINALS: Record<
1048 : CreateTopupResponse['status'],
1049 : BillingOperationTerminal | undefined
1050 : > = {
1051 : completed: { stage: 'succeeded', outcome: 'success' },
1052 : failed: {
1053 : stage: 'failed',
1054 : outcome: 'failure',
1055 : failure_category: 'provider_decline'
1056 : },
1057 : pending: undefined
1058 : }
1059 :
1060 0 : function reportResponseTerminal(
1061 : response: CreateTopupResponse,
1062 : attemptStartedAt: number
1063 : ) {
1064 0 : const terminal =
1065 : response instanceof UncreditedTopupResponse
1066 : ? response.terminal
1067 : : RESPONSE_TERMINALS[response.status]
1068 0 : if (terminal) {
1069 0 : reportTerminal(attemptStartedAt, terminal, response.billing_op_id)
1070 : }
1071 : }
1072 :
1073 0 : function reportTerminal(
1074 : attemptStartedAt: number,
1075 : terminal: BillingOperationTerminal,
1076 : billingOpId?: string
1077 : ) {
1078 0 : const attempt = {
1079 : ...(billingOpId ? { billing_op_id: billingOpId } : {}),
1080 : duration_ms: Date.now() - attemptStartedAt
1081 : }
1082 : // No timeout stage on the top-up funnel; the poller reports it as failed too.
1083 0 : telemetry?.trackBillingEvent(
1084 : terminal.stage === 'succeeded'
1085 : ? {
1086 : operation: 'topup',
1087 : stage: 'succeeded',
1088 : outcome: 'success',
1089 : payment_intent_source: source,
1090 : ...attempt
1091 : }
1092 : : {
1093 : operation: 'topup',
1094 : stage: 'failed',
1095 : outcome: 'failure',
1096 : payment_intent_source: source,
1097 : failure_category: terminal.failure_category,
1098 : ...attempt
1099 : }
1100 : )
1101 0 : telemetry?.trackBillingEvent({
1102 : operation: 'operation',
1103 : operation_type: 'topup',
1104 : billing_client: billingClient,
1105 : ...terminal,
1106 : ...attempt
1107 : })
1108 : }
1109 :
1110 0 : function purchaseRefusalMessage(error: unknown): string | null {
1111 0 : return error instanceof WorkspaceApiError &&
1112 : error.code !== undefined &&
1113 : PURCHASE_REFUSAL_SERVER_CODES.includes(error.code)
1114 : ? error.message
1115 : : null
1116 : }
1117 :
1118 0 : function purchaseErrorDetail(error?: unknown): string {
1119 0 : const refusal = purchaseRefusalMessage(error)
1120 0 : if (refusal !== null) return refusal
1121 : const code = error instanceof WorkspaceApiError ? error.code : undefined
1122 : // Only one billing operation is open at a time, so this refusal means the
1123 : // previous purchase has not settled or expired yet — not that anything failed.
1124 0 : if (code === 'SUBSCRIPTION_CHANGE_IN_PROGRESS') {
1125 0 : return t('credits.topUp.changeInProgressError')
1126 : }
1127 0 : return t('credits.topUp.purchaseErrorDetail', {
1128 : error: getErrorMessage(error) ?? t('credits.topUp.unknownError')
1129 : })
1130 : }
1131 : </script>
|