-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcredits.spec.ts
More file actions
364 lines (304 loc) · 13.6 KB
/
Copy pathcredits.spec.ts
File metadata and controls
364 lines (304 loc) · 13.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
import { jest } from '@jest/globals'
import { CreditsUseCases } from '../../../src/core/users/credits.js'
import { purchasedCreditsRepository } from '../../../src/infrastructure/repositories/users/purchasedCredits.js'
import { AccountsUseCases } from '../../../src/core/users/accounts.js'
import { ForbiddenError } from '../../../src/errors/index.js'
import {
type Account,
type PurchasedCredit,
type User,
type UserWithOrganization,
UserRole,
} from '@auto-drive/models'
import { config } from '../../../src/config.js'
// ─────────────────────────────────────────────────────────────────────────────
// Test fixtures
// ─────────────────────────────────────────────────────────────────────────────
const now = new Date()
const baseUser: UserWithOrganization = {
id: 'user-id',
publicId: 'pub-1',
walletAddress: '0xabc',
createdAt: now,
updatedAt: now,
authProvider: 'google',
oauthProvider: 'google',
oauthUsername: 'test@gmail.com',
organizationId: 'org-1',
role: UserRole.User,
} as unknown as UserWithOrganization
const adminUser: User = {
...baseUser,
role: UserRole.Admin,
} as unknown as User
const nonAdminUser: User = {
...baseUser,
role: UserRole.User,
} as unknown as User
const mockAccount: Account = {
id: 'account-id',
organizationId: 'org-1',
model: 'monthly',
uploadLimit: 100,
downloadLimit: 100,
} as unknown as Account
const FUTURE_EXPIRY = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
const SOON_EXPIRY = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 7 days
const makeCreditRow = (
overrides: Partial<PurchasedCredit> = {},
): PurchasedCredit => ({
id: 'credit-1',
accountId: 'account-id',
intentId: 'intent-1',
uploadBytesOriginal: BigInt(1024 * 1024 * 1024), // 1 GiB
uploadBytesRemaining: BigInt(1024 * 1024 * 1024),
downloadBytesOriginal: BigInt(1024 * 1024 * 1024),
downloadBytesRemaining: BigInt(1024 * 1024 * 1024),
purchasedAt: now,
expiresAt: FUTURE_EXPIRY,
expired: false,
refundedAt: null,
createdAt: now,
updatedAt: now,
...overrides,
})
// ─────────────────────────────────────────────────────────────────────────────
// Test suite
// ─────────────────────────────────────────────────────────────────────────────
describe('CreditsUseCases', () => {
beforeEach(() => {
jest.clearAllMocks()
jest
.spyOn(AccountsUseCases, 'getOrCreateAccount')
.mockResolvedValue(mockAccount)
})
afterEach(() => {
jest.restoreAllMocks()
})
// ──────────────────────────────────────────────────────────────────────────
// getSummary
// ──────────────────────────────────────────────────────────────────────────
describe('getSummary', () => {
it('returns zeros and canPurchase=true when no credits exist', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: 0n,
downloadBytesRemaining: 0n,
nextExpiryDate: null,
activeRowCount: 0,
})
const summary = await CreditsUseCases.getSummary(baseUser)
expect(summary.uploadBytesRemaining).toBe(0n)
expect(summary.downloadBytesRemaining).toBe(0n)
expect(summary.nextExpiryDate).toBeNull()
expect(summary.batchCount).toBe(0)
expect(summary.canPurchase).toBe(true)
expect(summary.maxPurchasableBytes).toBe(config.credits.maxBytesPerUser)
})
it('returns googleVerified=true for Google-authed user', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: 0n,
downloadBytesRemaining: 0n,
nextExpiryDate: null,
activeRowCount: 0,
})
const summary = await CreditsUseCases.getSummary(baseUser)
expect(summary.googleVerified).toBe(true)
})
it('returns googleVerified=false for non-Google user', async () => {
const githubUser: UserWithOrganization = {
...baseUser,
oauthProvider: 'github',
} as unknown as UserWithOrganization
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: 0n,
downloadBytesRemaining: 0n,
nextExpiryDate: null,
activeRowCount: 0,
})
const summary = await CreditsUseCases.getSummary(githubUser)
expect(summary.googleVerified).toBe(false)
})
it('computes maxPurchasableBytes using the larger of upload/download remaining', async () => {
// Upload has 80 GiB remaining, download has 50 GiB
// Binding constraint is upload (80 GiB), so room = cap - 80 GiB
const uploadRemaining = BigInt(80 * 1024 ** 3)
const downloadRemaining = BigInt(50 * 1024 ** 3)
const cap = config.credits.maxBytesPerUser // 100 GiB
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: uploadRemaining,
downloadBytesRemaining: downloadRemaining,
nextExpiryDate: FUTURE_EXPIRY,
activeRowCount: 2,
})
const summary = await CreditsUseCases.getSummary(baseUser)
expect(summary.maxPurchasableBytes).toBe(cap - uploadRemaining)
expect(summary.canPurchase).toBe(true)
})
it('returns canPurchase=false and maxPurchasableBytes=0n when at or over cap', async () => {
const cap = config.credits.maxBytesPerUser
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: cap,
downloadBytesRemaining: cap,
nextExpiryDate: FUTURE_EXPIRY,
activeRowCount: 1,
})
const summary = await CreditsUseCases.getSummary(baseUser)
expect(summary.canPurchase).toBe(false)
expect(summary.maxPurchasableBytes).toBe(0n)
})
it('uses upload bytes only for cap even when download remaining is higher', async () => {
const uploadRemaining = BigInt(30 * 1024 ** 3)
const downloadRemaining = BigInt(70 * 1024 ** 3)
const cap = config.credits.maxBytesPerUser
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: uploadRemaining,
downloadBytesRemaining: downloadRemaining,
nextExpiryDate: FUTURE_EXPIRY,
activeRowCount: 3,
})
const summary = await CreditsUseCases.getSummary(baseUser)
// Cap is upload-only — download bytes are not allocated on purchase
// and do not factor into maxPurchasableBytes.
expect(summary.maxPurchasableBytes).toBe(cap - uploadRemaining)
expect(summary.canPurchase).toBe(true)
})
it('populates batchCount and nextExpiryDate from repository', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getRemainingCredits')
.mockResolvedValue({
uploadBytesRemaining: BigInt(1024),
downloadBytesRemaining: BigInt(1024),
nextExpiryDate: SOON_EXPIRY,
activeRowCount: 5,
})
const summary = await CreditsUseCases.getSummary(baseUser)
expect(summary.batchCount).toBe(5)
expect(summary.nextExpiryDate).toEqual(SOON_EXPIRY)
})
})
// ──────────────────────────────────────────────────────────────────────────
// getBatches
// ──────────────────────────────────────────────────────────────────────────
describe('getBatches', () => {
it('returns the full purchase history from repository', async () => {
const credits = [makeCreditRow(), makeCreditRow({ id: 'credit-2' })]
jest
.spyOn(purchasedCreditsRepository, 'getByAccountId')
.mockResolvedValue(credits)
const result = await CreditsUseCases.getBatches(baseUser)
expect(result).toEqual(credits)
expect(
purchasedCreditsRepository.getByAccountId,
).toHaveBeenCalledWith(mockAccount.id)
})
it('returns an empty array when no purchases exist', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getByAccountId')
.mockResolvedValue([])
const result = await CreditsUseCases.getBatches(baseUser)
expect(result).toEqual([])
})
})
// ──────────────────────────────────────────────────────────────────────────
// getExpiringBatches
// ──────────────────────────────────────────────────────────────────────────
describe('getExpiringBatches', () => {
it('returns rows expiring soon via per-account repository method', async () => {
const expiring = [makeCreditRow({ expiresAt: SOON_EXPIRY })]
jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsByAccountId')
.mockResolvedValue(expiring)
const result = await CreditsUseCases.getExpiringBatches(baseUser)
expect(result).toEqual(expiring)
expect(
purchasedCreditsRepository.getExpiringCreditsByAccountId,
).toHaveBeenCalledWith(mockAccount.id, 30)
})
it('returns empty array when nothing is expiring', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsByAccountId')
.mockResolvedValue([])
const result = await CreditsUseCases.getExpiringBatches(baseUser)
expect(result).toEqual([])
})
})
// ──────────────────────────────────────────────────────────────────────────
// getEconomics
// ──────────────────────────────────────────────────────────────────────────
describe('getEconomics', () => {
it('returns 403 ForbiddenError for non-admin user', async () => {
const getAggregateSpy = jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsAggregate')
.mockResolvedValue({
count: 0,
totalUploadBytesRemaining: 0n,
totalDownloadBytesRemaining: 0n,
})
const result = await CreditsUseCases.getEconomics(nonAdminUser)
expect(result.isErr()).toBe(true)
expect(result._unsafeUnwrapErr()).toBeInstanceOf(ForbiddenError)
expect(getAggregateSpy).not.toHaveBeenCalled()
})
it('returns aggregated economics for admin user', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsAggregate')
.mockResolvedValue({
count: 2,
totalUploadBytesRemaining:
BigInt(2 * 1024 ** 3) + BigInt(1024 ** 3),
totalDownloadBytesRemaining:
BigInt(3 * 1024 ** 3) + BigInt(2 * 1024 ** 3),
})
const result = await CreditsUseCases.getEconomics(adminUser)
expect(result.isOk()).toBe(true)
const economics = result._unsafeUnwrap()
expect(economics.totalExpiringWithin30Days).toBe(2)
expect(economics.totalExpiringUploadBytes).toBe(
BigInt(2 * 1024 ** 3) + BigInt(1024 ** 3),
)
expect(economics.totalExpiringDownloadBytes).toBe(
BigInt(3 * 1024 ** 3) + BigInt(2 * 1024 ** 3),
)
})
it('returns zeros when no credits are expiring soon', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsAggregate')
.mockResolvedValue({
count: 0,
totalUploadBytesRemaining: 0n,
totalDownloadBytesRemaining: 0n,
})
const result = await CreditsUseCases.getEconomics(adminUser)
expect(result.isOk()).toBe(true)
const economics = result._unsafeUnwrap()
expect(economics.totalExpiringWithin30Days).toBe(0)
expect(economics.totalExpiringUploadBytes).toBe(0n)
expect(economics.totalExpiringDownloadBytes).toBe(0n)
})
it('queries within 30 days window', async () => {
jest
.spyOn(purchasedCreditsRepository, 'getExpiringCreditsAggregate')
.mockResolvedValue({
count: 0,
totalUploadBytesRemaining: 0n,
totalDownloadBytesRemaining: 0n,
})
await CreditsUseCases.getEconomics(adminUser)
expect(
purchasedCreditsRepository.getExpiringCreditsAggregate,
).toHaveBeenCalledWith(30)
})
})
})