-
Notifications
You must be signed in to change notification settings - Fork 672
Expand file tree
/
Copy pathTopUpCreditsDialogContentWorkspace.test.ts
More file actions
588 lines (502 loc) · 18.6 KB
/
Copy pathTopUpCreditsDialogContentWorkspace.test.ts
File metadata and controls
588 lines (502 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import { render, screen, waitFor } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'
import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi'
import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi'
import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorkspace.vue'
const mockFetchBalance = vi.fn()
const mockFetchStatus = vi.fn()
const mockTopup =
vi.fn<(amountCents: number) => Promise<CreateTopupResponse | void>>()
const mockStartOperation = vi.fn()
const mockShowSettings = vi.fn()
const mockToastAdd = vi.fn()
const mockCloseDialog = vi.fn()
const mockTrackTopUpPurchase = vi.fn()
const mockTrackBillingEvent = vi.fn()
const mockPermissions = vi.hoisted(() => ({
ref: undefined as { value: { canTopUp: boolean } } | undefined
}))
const mockShouldUseWorkspaceBilling = vi.hoisted(() => ({ value: true }))
const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true }))
const mockWorkspace = vi.hoisted(() => ({
activeWorkspaceId: 'workspace-1' as string | null,
workspaceTransitionGeneration: 0
}))
vi.mock('@/platform/distribution/types', () => mockDistributionTypes)
const mockBillingOperationState = vi.hoisted(() => ({
isAddingCredits: undefined as { value: boolean } | undefined,
topupActionOperation: undefined as
| { value: { actionUrl: string } | undefined }
| undefined
}))
vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: () => ({
fetchBalance: mockFetchBalance,
fetchStatus: mockFetchStatus,
topup: (amountCents: number) => mockTopup(amountCents)
})
}))
vi.mock('@/platform/workspace/stores/billingOperationStore', async () => {
const { ref } = await import('vue')
mockBillingOperationState.isAddingCredits = ref(false)
mockBillingOperationState.topupActionOperation = ref(undefined)
return {
useBillingOperationStore: () => ({
hasPendingOperations: true,
get isAddingCredits() {
return mockBillingOperationState.isAddingCredits?.value ?? false
},
get topupActionOperation() {
return mockBillingOperationState.topupActionOperation?.value
},
startOperation: mockStartOperation
})
}
})
vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({
useTeamWorkspaceStore: () => mockWorkspace
}))
vi.mock('@/platform/workspace/composables/useWorkspaceUI', async () => {
const { ref } = await import('vue')
mockPermissions.ref = ref({ canTopUp: true })
return {
useWorkspaceUI: () => ({ permissions: mockPermissions.ref })
}
})
vi.mock('@/composables/billing/useBillingRouting', () => ({
useBillingRouting: () => ({
shouldUseWorkspaceBilling: {
__v_isRef: true,
get value() {
return mockShouldUseWorkspaceBilling.value
}
}
})
}))
vi.mock('@/platform/settings/composables/useSettingsDialog', () => ({
useSettingsDialog: () => ({ show: mockShowSettings })
}))
vi.mock('@/stores/dialogStore', () => ({
useDialogStore: () => ({ closeDialog: mockCloseDialog })
}))
vi.mock('@/platform/telemetry', () => ({
useTelemetry: () => ({
trackApiCreditTopupButtonPurchaseClicked: mockTrackTopUpPurchase,
trackBillingEvent: mockTrackBillingEvent
})
}))
vi.mock('@/platform/telemetry/topupTracker', () => ({
clearTopupTracking: vi.fn()
}))
vi.mock('@/composables/useExternalLink', () => ({
useExternalLink: () => ({
buildDocsUrl: () => 'https://docs.comfy.org',
docsPaths: { partnerNodesPricing: '' }
})
}))
vi.mock('primevue/usetoast', () => ({
useToast: () => ({ add: mockToastAdd })
}))
vi.mock('@/base/credits/comfyCredits', () => ({
creditsToUsd: (credits: number) => credits,
usdToCredits: (usd: number) => usd
}))
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en: {
g: { back: 'Back', close: 'Close' },
subscription: {
addCredits: 'Add credits',
preview: {
completeVerification: 'Complete verification',
totalDueToday: 'Total due today'
}
},
credits: {
topUp: {
addMoreCredits: 'Add more credits',
addMoreCreditsToRun: 'Add more credits to run',
selectAmount: 'Select amount',
youPay: 'You pay',
youGet: 'You get',
purchaseSuccess: 'Credits added successfully!',
purchaseError: 'Purchase Failed',
purchaseErrorDetail: 'Failed to purchase credits: {error}',
unknownError: 'An unknown error occurred',
minRequired: 'Minimum required',
maxAllowed: 'Maximum allowed',
needMore: 'Need more?',
contactUs: 'Contact us',
viewPricing: 'View pricing',
insufficientWorkflowMessage: 'Insufficient credits',
chargedImmediatelyNote: 'Your saved card is charged immediately.',
confirmSubtitle:
'Credits are added to this workspace as soon as payment completes.',
confirmTitle: 'Confirm',
payAmount: 'Pay {amount}',
verifyBody:
'Your bank requires additional verification to complete this payment.',
verifyTitle: 'Verify your payment'
}
}
}
}
})
function topupResponse(
status: CreateTopupResponse['status']
): CreateTopupResponse {
return {
billing_op_id: 'op-1',
topup_id: 'topup-1',
status,
amount_cents: 5000
}
}
function renderDialog() {
return render(TopUpCreditsDialogContentWorkspace, {
global: {
plugins: [i18n],
stubs: {
FormattedNumberStepper: {
name: 'FormattedNumberStepper',
props: ['modelValue'],
template: '<div />'
}
}
}
})
}
function setCanTopUp(canTopUp: boolean) {
if (!mockPermissions.ref) throw new Error('Permissions mock not initialized')
mockPermissions.ref.value = { canTopUp }
}
function setIsAddingCredits(isAddingCredits: boolean) {
if (!mockBillingOperationState.isAddingCredits) {
throw new Error('Billing operation mock not initialized')
}
mockBillingOperationState.isAddingCredits.value = isAddingCredits
}
function setTopupActionOperation(operation: { actionUrl: string } | undefined) {
if (!mockBillingOperationState.topupActionOperation) {
throw new Error('Billing operation mock not initialized')
}
mockBillingOperationState.topupActionOperation.value = operation
}
async function clickAddCredits() {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Add credits' }))
}
describe('TopUpCreditsDialogContentWorkspace', () => {
beforeEach(() => {
mockDistributionTypes.isCloud = true
setCanTopUp(true)
mockShouldUseWorkspaceBilling.value = true
mockWorkspace.activeWorkspaceId = 'workspace-1'
mockWorkspace.workspaceTransitionGeneration = 0
setIsAddingCredits(false)
setTopupActionOperation(undefined)
mockFetchBalance.mockResolvedValue(undefined)
mockFetchStatus.mockResolvedValue(undefined)
mockStartOperation.mockImplementation(() => {
setIsAddingCredits(true)
return new Promise(() => {})
})
})
it('fires a started event before the purchase resolves', async () => {
mockTopup.mockResolvedValue(topupResponse('pending'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
await waitFor(() =>
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'started',
outcome: 'pending'
})
)
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'operation',
stage: 'started',
outcome: 'pending',
operation_type: 'topup'
})
})
it('reports failure telemetry when topup resolves with no response', async () => {
mockTopup.mockResolvedValue(undefined)
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
await waitFor(() =>
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'failed',
outcome: 'failure',
failure_category: 'unknown',
duration_ms: expect.any(Number)
})
)
})
it('allows a top-up while an unrelated billing operation is pending', () => {
renderDialog()
expect(screen.getByRole('button', { name: 'Add credits' })).toBeEnabled()
})
it('advances to confirmation without charging', async () => {
renderDialog()
await clickAddCredits()
expect(screen.getByText('Confirm')).toBeInTheDocument()
expect(screen.getByText('Total due today')).toBeInTheDocument()
expect(screen.getByText('$50.00')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeEnabled()
expect(mockTopup).not.toHaveBeenCalled()
})
it('allows returning to amount selection before payment', async () => {
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Back' }))
expect(screen.getByText('Select amount')).toBeInTheDocument()
})
it('reopens in verification without exposing the action URL', async () => {
const actionUrl = 'https://verify.example/sensitive-token'
const open = vi.spyOn(window, 'open').mockReturnValue({} as Window)
setTopupActionOperation({ actionUrl })
const { container } = renderDialog()
expect(screen.getByText('Verify your payment')).toBeInTheDocument()
expect(screen.queryByText('Select amount')).not.toBeInTheDocument()
expect(container.innerHTML).not.toContain(actionUrl)
await userEvent.click(
screen.getByRole('button', { name: 'Complete verification' })
)
expect(open).toHaveBeenCalledWith(
actionUrl,
'_blank',
'noopener,noreferrer'
)
open.mockRestore()
})
it('reopens in verification while the action URL is loading', () => {
setIsAddingCredits(true)
renderDialog()
expect(screen.getByText('Verify your payment')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Complete verification' })
).toBeDisabled()
expect(screen.queryByText('Select amount')).not.toBeInTheDocument()
})
it('returns to amount selection when a reopened operation ends', async () => {
setIsAddingCredits(true)
renderDialog()
expect(screen.getByText('Verify your payment')).toBeInTheDocument()
setIsAddingCredits(false)
await nextTick()
expect(screen.getByText('Select amount')).toBeInTheDocument()
expect(screen.queryByText('Verify your payment')).not.toBeInTheDocument()
})
it('hides topup verification after permission is revoked', () => {
setCanTopUp(false)
setTopupActionOperation({
actionUrl: 'https://verify.example/sensitive-token'
})
renderDialog()
expect(
screen.queryByRole('button', { name: 'Complete verification' })
).not.toBeInTheDocument()
})
it('locks pending payment actions and prevents duplicate top-ups', async () => {
mockTopup.mockResolvedValue(topupResponse('pending'))
renderDialog()
await clickAddCredits()
const payButton = screen.getByRole('button', { name: 'Pay $50.00' })
await userEvent.click(payButton)
await nextTick()
expect(screen.getByRole('button', { name: 'Back' })).toBeDisabled()
expect(payButton).toBeDisabled()
expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', {
attemptStartedAt: expect.any(Number)
})
payButton.dispatchEvent(new MouseEvent('click', { bubbles: true }))
expect(mockTopup).toHaveBeenCalledOnce()
})
it('unlocks payment and reports an operation start failure', async () => {
const error = new Error('Operation unavailable')
mockTopup.mockResolvedValue(topupResponse('pending'))
mockStartOperation.mockRejectedValue(error)
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeEnabled()
)
expect(mockToastAdd).toHaveBeenCalledWith({
severity: 'error',
summary: 'Purchase Failed',
detail: 'Failed to purchase credits: An unknown error occurred'
})
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'failed',
outcome: 'failure',
billing_op_id: 'op-1',
failure_category: 'unknown',
duration_ms: expect.any(Number)
})
expect(consoleError).toHaveBeenCalledWith('Purchase failed')
consoleError.mockRestore()
})
it('refreshes both balance and status after a completed top-up', async () => {
mockTopup.mockResolvedValue(topupResponse('completed'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockFetchBalance).toHaveBeenCalledOnce()
expect(mockFetchStatus).toHaveBeenCalledOnce()
expect(mockShowSettings).toHaveBeenCalledWith('workspace')
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'succeeded',
outcome: 'success',
billing_op_id: 'op-1',
duration_ms: expect.any(Number)
})
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'operation',
stage: 'succeeded',
outcome: 'success',
operation_type: 'topup',
billing_op_id: 'op-1',
duration_ms: expect.any(Number)
})
})
it('ignores a completed top-up after switching away and back', async () => {
let resolveTopup!: (response: CreateTopupResponse) => void
mockTopup.mockReturnValueOnce(
new Promise((resolve) => {
resolveTopup = resolve
})
)
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
await waitFor(() => expect(mockTopup).toHaveBeenCalledOnce())
mockWorkspace.activeWorkspaceId = 'workspace-2'
mockWorkspace.workspaceTransitionGeneration++
mockWorkspace.activeWorkspaceId = 'workspace-1'
mockWorkspace.workspaceTransitionGeneration++
resolveTopup(topupResponse('completed'))
await nextTick()
expect(mockFetchBalance).not.toHaveBeenCalled()
expect(mockFetchStatus).not.toHaveBeenCalled()
expect(mockToastAdd).not.toHaveBeenCalledWith(
expect.objectContaining({ severity: 'success' })
)
expect(mockCloseDialog).not.toHaveBeenCalled()
expect(mockShowSettings).not.toHaveBeenCalled()
})
it('opens Credits settings after a completed local top-up', async () => {
mockDistributionTypes.isCloud = false
mockTopup.mockResolvedValue(topupResponse('completed'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockShowSettings).toHaveBeenCalledWith('credits')
})
it('keeps completed top-up telemetry successful when refresh fails', async () => {
mockTopup.mockResolvedValue(topupResponse('completed'))
mockFetchBalance.mockRejectedValueOnce(new Error('balance unavailable'))
mockFetchStatus.mockRejectedValueOnce(new Error('status unavailable'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockTrackBillingEvent).toHaveBeenCalledTimes(4)
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'succeeded',
outcome: 'success',
billing_op_id: 'op-1',
duration_ms: expect.any(Number)
})
expect(mockShowSettings).toHaveBeenCalledWith('workspace')
})
it('does not refresh balance or status for a pending top-up', async () => {
mockTopup.mockResolvedValue(topupResponse('pending'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockStartOperation).toHaveBeenCalledWith('op-1', 'topup', {
attemptStartedAt: expect.any(Number)
})
expect(mockFetchBalance).not.toHaveBeenCalled()
expect(mockFetchStatus).not.toHaveBeenCalled()
expect(mockTrackBillingEvent).not.toHaveBeenCalledWith(
expect.objectContaining({ stage: 'succeeded' })
)
})
it('does not refresh balance or status for a failed top-up', async () => {
mockTopup.mockResolvedValue(topupResponse('failed'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockFetchBalance).not.toHaveBeenCalled()
expect(mockFetchStatus).not.toHaveBeenCalled()
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'failed',
outcome: 'failure',
billing_op_id: 'op-1',
failure_category: 'provider_decline',
duration_ms: expect.any(Number)
})
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'operation',
stage: 'failed',
outcome: 'failure',
operation_type: 'topup',
billing_op_id: 'op-1',
failure_category: 'provider_decline',
duration_ms: expect.any(Number)
})
})
it('categorizes a thrown topup error via the shared classifier', async () => {
const workspaceApiError = new WorkspaceApiError('upstream rejected', 500)
mockTopup.mockRejectedValue(workspaceApiError)
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
await waitFor(() =>
expect(mockTrackBillingEvent).toHaveBeenCalledWith({
operation: 'topup',
stage: 'failed',
outcome: 'failure',
failure_category: 'api_rejected',
duration_ms: expect.any(Number)
})
)
})
it('does not top up after the workspace role loses permission', async () => {
renderDialog()
await clickAddCredits()
setCanTopUp(false)
await nextTick()
expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeDisabled()
expect(mockTopup).not.toHaveBeenCalled()
expect(mockTrackTopUpPurchase).not.toHaveBeenCalled()
expect(mockToastAdd).not.toHaveBeenCalled()
expect(mockCloseDialog).not.toHaveBeenCalled()
})
it('keeps a mounted workspace dialog usable after routing switches to legacy billing', async () => {
setCanTopUp(false)
mockShouldUseWorkspaceBilling.value = false
mockTopup.mockResolvedValue(topupResponse('completed'))
renderDialog()
await clickAddCredits()
await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' }))
expect(mockTopup).toHaveBeenCalledWith(5000)
expect(mockFetchBalance).toHaveBeenCalledOnce()
expect(mockFetchStatus).toHaveBeenCalledOnce()
})
})