-
Notifications
You must be signed in to change notification settings - Fork 673
Expand file tree
/
Copy pathCreditsTile.test.ts
More file actions
427 lines (391 loc) · 14.3 KB
/
Copy pathCreditsTile.test.ts
File metadata and controls
427 lines (391 loc) · 14.3 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
import { render, screen, waitFor } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { computed } from 'vue'
import { createI18n } from 'vue-i18n'
import type { BalanceInfo, SubscriptionInfo } from '@/composables/billing/types'
import CreditsTile from '@/platform/cloud/subscription/components/CreditsTile.vue'
import type { CurrentTeamCreditStop } from '@/platform/workspace/api/workspaceApi'
type Balance = Pick<
BalanceInfo,
'amountMicros' | 'cloudCreditBalanceMicros' | 'prepaidBalanceMicros'
>
type Subscription = Pick<SubscriptionInfo, 'duration' | 'renewalDate'> & {
tier: SubscriptionInfo['tier'] | 'TEAM'
}
type TeamStop = CurrentTeamCreditStop
const state = vi.hoisted(() => ({
isCloud: true,
balance: null as Balance | null,
subscription: null as Subscription | null,
isActiveSubscription: false,
isFreeTier: false,
currentTeamCreditStop: null as TeamStop | null,
isLoading: false,
canTopUp: true,
fetchBalance: vi.fn(),
fetchStatus: vi.fn(),
showPricingTable: vi.fn(),
showTopUpCreditsDialog: vi.fn(),
trackAddApiCreditButtonClicked: vi.fn(),
toastErrorHandler: vi.fn()
}))
vi.mock('@/composables/useErrorHandling', () => ({
useErrorHandling: () => ({
wrapWithErrorHandlingAsync:
<TArgs extends unknown[], TReturn>(
action: (...args: TArgs) => Promise<TReturn> | TReturn
) =>
async (...args: TArgs): Promise<TReturn | undefined> => {
try {
return await action(...args)
} catch (e) {
state.toastErrorHandler(e)
}
}
})
}))
vi.mock('@/platform/distribution/types', () => ({
get isCloud() {
return state.isCloud
}
}))
vi.mock('@/composables/billing/useBillingContext', () => ({
useBillingContext: () => ({
balance: computed(() => state.balance),
subscription: computed(() => state.subscription),
isActiveSubscription: computed(() => state.isActiveSubscription),
isFreeTier: computed(() => state.isFreeTier),
currentTeamCreditStop: computed(() => state.currentTeamCreditStop),
isLoading: computed(() => state.isLoading),
fetchBalance: state.fetchBalance,
fetchStatus: state.fetchStatus
})
}))
vi.mock('@/platform/workspace/composables/useWorkspaceUI', () => ({
useWorkspaceUI: () => ({
permissions: computed(() => ({ canTopUp: state.canTopUp }))
})
}))
vi.mock(
'@/platform/cloud/subscription/composables/useSubscriptionDialog',
() => ({
useSubscriptionDialog: () => ({ showPricingTable: state.showPricingTable })
})
)
vi.mock('@/services/dialogService', () => ({
useDialogService: () => ({
showTopUpCreditsDialog: state.showTopUpCreditsDialog
})
}))
vi.mock('@/platform/telemetry', () => ({
useTelemetry: () => ({
trackAddApiCreditButtonClicked: state.trackAddApiCreditButtonClicked
})
}))
const i18n = createI18n({
legacy: false,
locale: 'en',
messages: {
en: {
subscription: {
totalCredits: 'Total credits',
remaining: 'remaining',
refreshCredits: 'Refresh credits',
monthly: 'Monthly',
refillsDate: 'Refills {date}',
refillsNextCycle: 'Refills next cycle',
creditsUsed: '{used} used',
creditsLeftOfTotal: '{remaining} left of {total}',
monthlyUsageProgress: '{used} of {total} monthly credits used',
additionalCreditsInfo: 'About additional credits',
additionalCreditsTooltip: 'Credits you add on top of your plan.',
additionalCredits: 'Additional credits',
additionalCreditsInUse: 'In use',
usedAfterMonthly: 'Used after monthly runs out',
reactivateToUseCredits: 'Reactivate your plan to use these credits',
monthlyCreditsUsedUpTitle:
'Monthly credits are used up. Refills {date}',
monthlyCreditsUsedUpTitleNoDate: 'Monthly credits are used up',
monthlyCreditsUsedUpDescription:
"You're now spending additional credits.",
outOfCreditsTitle: "You're out of credits. Credits refill {date}",
outOfCreditsTitleNoDate: "You're out of credits",
outOfCreditsDescription: 'Add more credits to continue generating.',
addCredits: 'Add credits',
upgradeToAddCredits: 'Upgrade to add credits'
}
}
}
})
function renderTile(props: Record<string, unknown> = {}) {
return render(CreditsTile, {
props,
global: {
plugins: [i18n],
directives: { tooltip: () => {} },
stubs: {
Button: {
template:
'<button v-bind="$attrs" :data-variant="variant" :disabled="loading" @click="$emit(\'click\')"><slot/></button>',
props: ['variant', 'size', 'loading'],
emits: ['click']
},
Skeleton: { template: '<div role="status" aria-label="Loading"></div>' }
}
}
})
}
function activeProSubscription() {
state.isActiveSubscription = true
state.subscription = {
tier: 'PRO',
duration: 'MONTHLY',
renewalDate: '2026-02-20T12:00:00Z'
}
// amountMicros are cents; centsToCredits multiplies by 2.11.
state.balance = {
amountMicros: 500, // -> 1,055 total
cloudCreditBalanceMicros: 200, // -> 422 monthly remaining
prepaidBalanceMicros: 300 // -> 633 additional
}
}
describe('CreditsTile', () => {
beforeEach(() => {
state.isCloud = true
state.balance = null
state.subscription = null
state.isActiveSubscription = false
state.isFreeTier = false
state.currentTeamCreditStop = null
state.isLoading = false
state.canTopUp = true
vi.clearAllMocks()
})
it('renders the total balance (cents converted to credits) with the remaining suffix', () => {
activeProSubscription()
const { container } = renderTile()
expect(container.textContent).toContain('1,055')
expect(container.textContent).toContain('remaining')
})
it('renders the monthly usage bar and additional breakdown', () => {
activeProSubscription()
const { container } = renderTile()
// PRO monthly allowance = 21,100; remaining 422 -> used 20,678.
expect(container.textContent).toContain('Monthly')
expect(container.textContent).toMatch(/Refills Feb/)
expect(container.textContent).toContain('20,678 used')
expect(container.textContent).toContain('422 left of 21,100')
expect(container.textContent).toContain('Additional credits')
expect(container.textContent).toContain('633')
expect(container.textContent).toContain('Used after monthly runs out')
})
it('renders a compact monthly summary for narrow containers', () => {
activeProSubscription()
const { container } = renderTile()
expect(container.textContent).toContain('422 left of 21K')
})
it('uses the full annual Team grant for the credit pool total', () => {
state.isActiveSubscription = true
state.subscription = {
tier: 'TEAM',
duration: 'ANNUAL',
renewalDate: '2026-02-20T12:00:00Z'
}
state.currentTeamCreditStop = {
id: 'team_700',
credits_monthly: 147700,
stop_usd: 700
}
state.balance = {
amountMicros: 840000,
cloudCreditBalanceMicros: 840000
}
const { container } = renderTile()
expect(container.textContent).toContain('1,772,400 left of 1,772,400')
})
it('keeps the monthly Team grant as the monthly credit pool total', () => {
state.isActiveSubscription = true
state.subscription = {
tier: 'TEAM',
duration: 'MONTHLY',
renewalDate: '2026-02-20T12:00:00Z'
}
state.currentTeamCreditStop = {
id: 'team_700',
credits_monthly: 147700,
stop_usd: 700
}
state.balance = {
amountMicros: 70000,
cloudCreditBalanceMicros: 70000
}
const { container } = renderTile()
expect(container.textContent).toContain('147,700 left of 147,700')
})
it('uses the full annual grant for a personal tier credit pool', () => {
state.isActiveSubscription = true
state.subscription = {
tier: 'PRO',
duration: 'ANNUAL',
renewalDate: '2026-02-20T12:00:00Z'
}
state.balance = {
amountMicros: 120000,
cloudCreditBalanceMicros: 120000
}
const { container } = renderTile()
expect(container.textContent).toContain('253,200 left of 253,200')
})
it('falls back to a dateless refills label when renewal date is missing', () => {
activeProSubscription()
state.subscription = { tier: 'PRO', duration: 'MONTHLY', renewalDate: null }
const { container } = renderTile()
expect(container.textContent).toContain('Refills next cycle')
expect(container.textContent).not.toContain('Refills Feb')
})
it('uses a dateless out-of-credits notice when renewal date is invalid', () => {
activeProSubscription()
state.subscription = {
tier: 'PRO',
duration: 'MONTHLY',
renewalDate: 'not-a-date'
}
state.balance = {
amountMicros: 0,
cloudCreditBalanceMicros: 0,
prepaidBalanceMicros: 0
}
const { container } = renderTile()
expect(container.textContent).toContain("You're out of credits")
expect(container.textContent).not.toContain('Credits refill')
})
it('hides the breakdown and forces zeros in the zero state', () => {
activeProSubscription()
const { container } = renderTile({ zeroState: true })
expect(container.textContent).toContain('0')
expect(container.textContent).not.toContain('left of')
expect(container.textContent).not.toContain('Additional credits')
expect(screen.queryByText('Add credits')).toBeNull()
})
it('shows disabled credit details for an inactive plan', () => {
activeProSubscription()
const { container } = renderTile({ inactivePlan: true })
expect(container.textContent).toContain('0remaining')
expect(container.textContent).toContain('Additional credits')
expect(container.textContent).toContain(
'Reactivate your plan to use these credits'
)
expect(screen.queryByText('Add credits')).toBeNull()
})
it('shows only the balance with no breakdown when there is no active subscription', () => {
state.isActiveSubscription = false
state.balance = { amountMicros: 500 }
const { container } = renderTile()
expect(container.textContent).toContain('1,055')
expect(container.textContent).not.toContain('left of')
expect(container.textContent).not.toContain('Additional credits')
expect(screen.queryByText('Add credits')).toBeNull()
})
it('shows no depletion notice or in-use badge while monthly credits remain', () => {
activeProSubscription()
const { container } = renderTile()
expect(container.textContent).not.toContain('Monthly credits are used up')
expect(container.textContent).not.toContain("You're out of credits")
expect(screen.queryByText('In use')).toBeNull()
})
it('flags spending of additional credits once the monthly allowance is depleted', () => {
activeProSubscription()
state.balance = {
amountMicros: 300,
cloudCreditBalanceMicros: 0,
prepaidBalanceMicros: 300
}
const { container } = renderTile()
expect(container.textContent).toContain(
'Monthly credits are used up. Refills Feb 20'
)
expect(container.textContent).toContain(
"You're now spending additional credits."
)
expect(screen.getByText('In use')).toBeTruthy()
expect(screen.getByText('Add credits').dataset.variant).toBe('secondary')
})
it('emphasizes add-credits when fully out of credits', () => {
activeProSubscription()
state.balance = {
amountMicros: 0,
cloudCreditBalanceMicros: 0,
prepaidBalanceMicros: 0
}
const { container } = renderTile()
expect(container.textContent).toContain(
"You're out of credits. Credits refill Feb 20"
)
expect(container.textContent).toContain(
'Add more credits to continue generating.'
)
expect(screen.queryByText('In use')).toBeNull()
expect(screen.getByText('Add credits').dataset.variant).toBe('inverted')
})
it('suppresses the depletion notice until the balance has loaded', () => {
activeProSubscription()
state.balance = null
state.isLoading = true
const { container } = renderTile()
expect(container.textContent).not.toContain('Monthly credits are used up')
expect(container.textContent).not.toContain("You're out of credits")
})
it('routes add-credits through telemetry + the top-up dialog', async () => {
activeProSubscription()
renderTile()
await userEvent.click(screen.getByText('Add credits'))
expect(state.trackAddApiCreditButtonClicked).toHaveBeenCalledOnce()
expect(state.showTopUpCreditsDialog).toHaveBeenCalledOnce()
})
it('offers the upgrade path instead of add-credits on the free tier', async () => {
activeProSubscription()
state.isFreeTier = true
renderTile()
expect(screen.queryByText('Add credits')).toBeNull()
await userEvent.click(screen.getByText('Upgrade to add credits'))
expect(state.showPricingTable).toHaveBeenCalledOnce()
})
it('keeps add-credits on the free tier off cloud, where there is no upgrade flow', async () => {
activeProSubscription()
state.isCloud = false
state.isFreeTier = true
renderTile()
expect(screen.queryByText('Upgrade to add credits')).toBeNull()
await userEvent.click(screen.getByText('Add credits'))
expect(state.showPricingTable).not.toHaveBeenCalled()
expect(state.showTopUpCreditsDialog).toHaveBeenCalledOnce()
})
it('hides the action button when the user lacks the top-up permission', () => {
activeProSubscription()
state.canTopUp = false
renderTile()
expect(screen.queryByText('Add credits')).toBeNull()
expect(screen.queryByText('Upgrade to add credits')).toBeNull()
})
it('refreshes balance and status from the facade on mount and on demand', async () => {
activeProSubscription()
renderTile()
expect(state.fetchBalance).toHaveBeenCalledOnce()
expect(state.fetchStatus).toHaveBeenCalledOnce()
await userEvent.click(
screen.getByRole('button', { name: 'Refresh credits' })
)
expect(state.fetchBalance).toHaveBeenCalledTimes(2)
expect(state.fetchStatus).toHaveBeenCalledTimes(2)
})
it('surfaces a failure toast when a refresh rejects', async () => {
activeProSubscription()
const failure = new Error('network down')
state.fetchBalance.mockRejectedValueOnce(failure)
renderTile()
await waitFor(() =>
expect(state.toastErrorHandler).toHaveBeenCalledWith(failure)
)
})
})