Line data Source code
1 : import { watch } from 'vue'
2 :
3 : import ConfirmationDialogContent from '@/components/dialog/content/ConfirmationDialogContent.vue'
4 : import { useToast } from '@/components/ui/toast/toastStore'
5 : import type { BillingTopUpDenial } from '@comfyorg/billing-core'
6 : import type {
7 : DowngradeToPersonalResult,
8 : SubscriptionDialogOptions,
9 : TopUpCreditsDialogOptions
10 : } from '@/platform/billing/composables/types'
11 : import { t } from '@/i18n'
12 : import { provideBillingDialogs } from '@/platform/billing/subscription/composables/billingDialogsAccess'
13 : import { useSubscriptionDialog } from '@/platform/billing/subscription/composables/useSubscriptionDialog'
14 : import type { CancellationFlowDialogOptions } from '@/platform/billing/subscription/launchCancellationFlow'
15 : import { isCloud } from '@/platform/distribution/types'
16 : import { useTelemetry } from '@comfyorg/telemetry'
17 : import { reportError } from '@comfyorg/telemetry/reportError'
18 : import type { PaymentIntentSource } from '@comfyorg/telemetry/types'
19 : import InsufficientCreditsMemberDialog from '@/platform/billing/components/InsufficientCreditsMemberDialog.vue'
20 : import AddCreditsDialogContent from '@/platform/billing/components/AddCreditsDialogContent.vue'
21 : import TopUpCreditsDialogContentWorkspace from '@/platform/billing/components/TopUpCreditsDialogContentWorkspace.vue'
22 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
23 : import { useBillingCapabilities } from '@/platform/billing/composables/useBillingCapabilities'
24 : import {
25 : isTopUpDeniedPastDue,
26 : usePaymentRecoveryDialog
27 : } from '@/platform/billing/composables/usePaymentRecoveryDialog'
28 : import { opensLocalBillingHandoff } from '@/platform/billing/localBillingWebEnabled'
29 : import { useWorkspaceIdentity } from '@/platform/workspace/ports/workspaceIdentity'
30 : import { useDialogStore } from '@/stores/dialogStore'
31 : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
32 :
33 2356 : const DENIED_TOP_UP_OUTCOME: Record<
34 : BillingTopUpDenial | 'unresolved',
35 : 'member' | 'plans' | 'handled' | { toast: string }
36 : > = {
37 : not_workspace_owner: 'member',
38 : free_plan: 'plans',
39 : no_subscription: 'plans',
40 : subscription_ended: 'plans',
41 : payment_past_due: 'handled',
42 : topup_purchases_paused: { toast: 'credits.topUp.deniedTopupsPaused' },
43 : creator_only_provisioning: { toast: 'credits.topUp.deniedCreatorOnly' },
44 : tier_not_self_serve: { toast: 'subscription.planUnavailable.salesManaged' },
45 : not_a_member: { toast: 'subscription.planUnavailable.notAMember' },
46 : subscription_status_unrecognized: {
47 : toast: 'subscription.planUnavailable.billingStateUnknown'
48 : },
49 : unresolved: { toast: 'subscription.planUnavailable.billingStateUnknown' }
50 : }
51 :
52 6818 : export function useBillingDialogs() {
53 6818 : const dialogStore = useDialogStore()
54 :
55 4 : async function showTopUpCreditsDialog(options?: TopUpCreditsDialogOptions) {
56 4 : useTelemetry()?.trackBillingEvent({
57 : operation: 'entry',
58 : stage: 'add_credits_clicked',
59 : outcome: 'pending',
60 : payment_intent_source:
61 : options?.source ??
62 : (options?.isInsufficientCredits ? 'out_of_credits' : undefined)
63 : })
64 4 : const { canTopUp, topUpDenial, isReady, initialize } =
65 : useBillingCapabilities()
66 4 : if (!isReady.value) await initialize()
67 4 : if (!isReady.value) return
68 :
69 4 : if (isTopUpDeniedPastDue(topUpDenial.value)) {
70 0 : return usePaymentRecoveryDialog().showPaymentRecoveryDialog()
71 : }
72 :
73 4 : if (!canTopUp.value) {
74 0 : const outcome = DENIED_TOP_UP_OUTCOME[topUpDenial.value ?? 'unresolved']
75 0 : if (outcome === 'member') {
76 0 : return dialogStore.showDialog({
77 : key: 'insufficient-credits-member',
78 : component: InsufficientCreditsMemberDialog,
79 : props: {
80 : onClose: () =>
81 : dialogStore.closeDialog({ key: 'insufficient-credits-member' })
82 : },
83 : dialogComponentProps: {
84 : headless: true
85 : }
86 : })
87 : }
88 0 : if (outcome === 'plans') {
89 0 : await useSubscriptionDialog().show({
90 : reason: options?.source ?? 'out_of_credits'
91 : })
92 0 : } else if (outcome !== 'handled') {
93 0 : useToast().error(t(outcome.toast))
94 : }
95 0 : return
96 : }
97 :
98 4 : return dialogStore.showDialog({
99 : key: 'top-up-credits',
100 : component:
101 : useFeatureFlags().flags.billingNewUxEnabled ||
102 : opensLocalBillingHandoff()
103 : ? AddCreditsDialogContent
104 : : TopUpCreditsDialogContentWorkspace,
105 : props: options,
106 : dialogComponentProps: {
107 : headless: true
108 : }
109 : })
110 : }
111 :
112 1 : async function showSubscriptionRequiredDialog(
113 : options?: SubscriptionDialogOptions
114 : ): Promise<boolean> {
115 1 : if (!isCloud) return false
116 :
117 : try {
118 : if (!window.__CONFIG__?.subscription_required) {
119 : const { remoteConfigState } =
120 : await import('@/platform/remoteConfig/remoteConfig')
121 : if (remoteConfigState.value === 'unloaded') {
122 : const { refreshRemoteConfig } =
123 : await import('@/platform/remoteConfig/refreshRemoteConfig')
124 : await refreshRemoteConfig()
125 : }
126 : }
127 :
128 : if (!window.__CONFIG__?.subscription_required) {
129 : reportError(
130 : new Error(
131 : 'showSubscriptionRequiredDialog: subscription_required gate closed'
132 : ),
133 : {
134 : surface: 'billing',
135 : errorType: 'error_opening_subscription_dialog_gate_closed'
136 : }
137 : )
138 : return false
139 : }
140 :
141 : const { show } = useSubscriptionDialog()
142 : return await show(options)
143 : } catch (error) {
144 : reportError(error, {
145 : surface: 'billing',
146 : errorType: 'error_opening_subscription_dialog'
147 : })
148 : return false
149 : }
150 : }
151 :
152 0 : function showBillingComingSoonDialog() {
153 0 : return dialogStore.showDialog({
154 : key: 'billing-coming-soon',
155 : title: t('subscription.billingComingSoon.title'),
156 : component: ConfirmationDialogContent,
157 : props: {
158 : message: t('subscription.billingComingSoon.message'),
159 : type: 'info',
160 : onConfirm: () => {}
161 : },
162 : dialogComponentProps: {
163 : size: 'sm'
164 : }
165 : })
166 : }
167 :
168 4 : async function showCancelSubscriptionDialog(
169 : cancelAt?: string,
170 : flowAlreadyOpened?: boolean,
171 : isScopeCurrent?: () => boolean,
172 : flowAlreadyConfirmed?: boolean
173 : ) {
174 4 : const { default: component } =
175 : await import('@/platform/billing/subscription/components/CancelSubscriptionDialogContent.vue')
176 4 : if (isScopeCurrent && !isScopeCurrent()) return false
177 4 : const guardedProps = {
178 : ...(flowAlreadyOpened !== undefined ? { flowAlreadyOpened } : {}),
179 : ...(flowAlreadyConfirmed !== undefined ? { flowAlreadyConfirmed } : {}),
180 : ...(cancelAt !== undefined ? { cancelAt } : {}),
181 : ...(isScopeCurrent ? { isScopeCurrent } : {})
182 : }
183 4 : dialogStore.updateDialog({
184 : key: 'cancel-subscription',
185 : contentProps: guardedProps
186 : })
187 4 : return dialogStore.showDialog({
188 : key: 'cancel-subscription',
189 : component,
190 : props: guardedProps,
191 : dialogComponentProps: {
192 : headless: true
193 : }
194 : })
195 : }
196 :
197 0 : async function showCancellationFlowDialog(
198 : options: CancellationFlowDialogOptions
199 : ) {
200 0 : const { default: component } =
201 : await import('@/platform/billing/subscription/components/CancellationFlowDialogContent.vue')
202 0 : if (!options.isScopeCurrent()) return false
203 0 : return dialogStore.showDialog({
204 : key: 'cancel-subscription',
205 : component,
206 : props: { ...options },
207 : dialogComponentProps: {
208 : headless: true,
209 : closable: false,
210 : dismissOnPointerDownOutside: false
211 : }
212 : })
213 : }
214 :
215 0 : async function showCancelSubscriptionFlow(cancelAt?: string) {
216 0 : const launchWorkspaceId = useWorkspaceIdentity().activeWorkspaceId
217 : const cancellationFlow =
218 : await import('@/platform/billing/subscription/launchCancellationFlow')
219 0 : return cancellationFlow.launchCancellationFlow({
220 : cancelAt,
221 : launchWorkspaceId,
222 : showFlow: showCancellationFlowDialog
223 : })
224 : }
225 :
226 : /**
227 : * Downgrade a team plan to a personal plan. Skips the type-"I understand"
228 : * confirm dialog only when there's nothing to confirm: no other members to
229 : * remove and no reactivation charge to disclose. Failures on that fast
230 : * path surface as an error toast.
231 : */
232 0 : async function showDowngradeToPersonalDialog(options: {
233 : planName: string
234 : planSlug: string
235 : paymentIntentSource?: PaymentIntentSource
236 : }): Promise<DowngradeToPersonalResult | null> {
237 0 : const {
238 : useDowngradeToPersonal,
239 : ReactivationConfirmationRequiredError,
240 : ReactivationAmountChangedError
241 : } = await import('@/platform/billing/composables/useDowngradeToPersonal')
242 0 : const {
243 : hasOtherMembers,
244 : refreshMembers,
245 : previewDowngrade,
246 : downgradeToPersonal
247 : } = useDowngradeToPersonal({
248 : paymentIntentSource: options.paymentIntentSource
249 : })
250 :
251 0 : let requiresReactivation = false
252 0 : let chargeCents = 0
253 0 : try {
254 0 : await refreshMembers()
255 0 : const preview = await previewDowngrade(options.planSlug)
256 0 : requiresReactivation = preview.requiresReactivationConfirmation
257 0 : chargeCents = preview.preview.cost_today_cents
258 0 : if (!hasOtherMembers.value && !requiresReactivation) {
259 0 : return await downgradeToPersonal(options.planSlug)
260 : }
261 : } catch (error) {
262 0 : useToast().error(t('subscription.downgrade.failed'), {
263 : description: getErrorMessage(error) ?? t('g.unknownError')
264 : })
265 0 : return null
266 : }
267 :
268 0 : const { default: component } =
269 : await import('@/platform/billing/components/dialogs/DowngradeRemoveMembersDialogContent.vue')
270 0 : const dialogKey = 'downgrade-remove-members'
271 0 : dialogStore.closeDialog({ key: dialogKey })
272 0 : return new Promise((resolve) => {
273 0 : const stopWatching = watch(
274 : () => dialogStore.isDialogOpen(dialogKey),
275 : (isOpen) => {
276 0 : if (!isOpen) resolveResult(null)
277 : },
278 : { flush: 'sync' }
279 : )
280 0 : function resolveResult(result: DowngradeToPersonalResult | null) {
281 0 : stopWatching()
282 0 : resolve(result)
283 : }
284 :
285 0 : dialogStore.showDialog({
286 : key: dialogKey,
287 : component,
288 : props: {
289 : planName: options.planName,
290 : planSlug: options.planSlug,
291 : requiresRemoval: hasOtherMembers.value,
292 : requiresReactivation,
293 : chargeCents,
294 : onConfirm: async (planSlug: string, confirmReactivation: boolean) => {
295 0 : try {
296 : const result = await downgradeToPersonal(
297 : planSlug,
298 : confirmReactivation,
299 : chargeCents
300 : )
301 0 : resolveResult(result)
302 : } catch (error) {
303 : // A fresh preview inside downgradeToPersonal() found the
304 : // dialog's captured state (open-time cancellation/charge) is
305 : // stale and refused to bill it. Push the corrected values into
306 : // the still-open dialog so a retry sends what these errors'
307 : // own preview says is actually true, instead of repeating the
308 : // same rejected request forever.
309 0 : if (
310 : error instanceof ReactivationConfirmationRequiredError ||
311 : error instanceof ReactivationAmountChangedError
312 : ) {
313 0 : requiresReactivation = true
314 0 : chargeCents = error.preview.cost_today_cents
315 0 : dialogStore.updateDialog({
316 : key: dialogKey,
317 : contentProps: { requiresReactivation, chargeCents }
318 : })
319 : }
320 0 : throw error
321 : }
322 : }
323 : },
324 : dialogComponentProps: {
325 : headless: true,
326 : closable: false,
327 : dismissOnPointerDownOutside: false,
328 : onClose: () => resolveResult(null)
329 : }
330 : })
331 : })
332 : }
333 :
334 6818 : return {
335 : showTopUpCreditsDialog,
336 : showSubscriptionRequiredDialog,
337 : showBillingComingSoonDialog,
338 : showCancelSubscriptionDialog,
339 : showCancelSubscriptionFlow,
340 : showDowngradeToPersonalDialog
341 : }
342 : }
343 :
344 2356 : provideBillingDialogs(useBillingDialogs)
|