-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.extraBalance.unit.tests.js
More file actions
560 lines (470 loc) · 21.3 KB
/
Copy pathbilling.extraBalance.unit.tests.js
File metadata and controls
560 lines (470 loc) · 21.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
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
/**
* Module dependencies.
*/
import { jest, describe, test, beforeEach, afterEach, expect } from '@jest/globals';
/**
* Unit tests for billing.extraBalance.repository.js and billing.extraBalance.schema.js
*/
describe('BillingExtraBalance unit tests:', () => {
// ─── Schema tests ──────────────────────────────────────────────────────────
describe('Schema validation', () => {
let schema;
beforeEach(async () => {
const mod = await import('../models/billing.extraBalance.schema.js');
schema = mod.default;
});
describe('BillingExtraBalance', () => {
test('should be valid with minimal required fields', () => {
const result = schema.BillingExtraBalance.safeParse({
organization: '507f1f77bcf86cd799439011',
});
expect(result.error).toBeFalsy();
expect(result.data.cachedBalance).toBe(0);
expect(result.data.ledger).toEqual([]);
});
test('should reject invalid organizationId', () => {
const result = schema.BillingExtraBalance.safeParse({
organization: 'not-valid',
});
expect(result.error).toBeDefined();
});
test('should accept a valid ledger entry', () => {
const result = schema.BillingExtraBalance.safeParse({
organization: '507f1f77bcf86cd799439011',
ledger: [
{
kind: 'topup',
amount: 500000,
stripeSessionId: 'cs_test_abc123',
},
],
cachedBalance: 500000,
});
expect(result.error).toBeFalsy();
expect(result.data.ledger[0].kind).toBe('topup');
expect(result.data.ledger[0].amount).toBe(500000);
});
test('should reject invalid ledger kind', () => {
const result = schema.BillingExtraBalance.safeParse({
organization: '507f1f77bcf86cd799439011',
ledger: [{ kind: 'invalid', amount: 100 }],
});
expect(result.error).toBeDefined();
});
test('should accept all valid ledger kinds with correct sign', () => {
// topup/adjustment require positive amount; debit/expiration/refund require negative
const cases = [
{ kind: 'topup', amount: 100 },
{ kind: 'adjustment', amount: 100 },
{ kind: 'debit', amount: -100 },
{ kind: 'expiration', amount: -100 },
{ kind: 'refund', amount: -100 },
];
for (const entry of cases) {
const result = schema.LedgerEntry.safeParse(entry);
expect(result.error).toBeFalsy();
}
});
test('should accept negative amount for debit kind', () => {
const result = schema.LedgerEntry.safeParse({ kind: 'debit', amount: -500 });
expect(result.error).toBeFalsy();
expect(result.data.amount).toBe(-500);
});
});
describe('ExtraBalanceCreditPack', () => {
test('should be valid with required fields', () => {
const result = schema.ExtraBalanceCreditPack.safeParse({
orgId: '507f1f77bcf86cd799439011',
amount: 500000,
stripeSessionId: 'cs_test_abc',
});
expect(result.error).toBeFalsy();
});
test('should reject amount of 0', () => {
const result = schema.ExtraBalanceCreditPack.safeParse({
orgId: '507f1f77bcf86cd799439011',
amount: 0,
stripeSessionId: 'cs_test_abc',
});
expect(result.error).toBeDefined();
});
test('should accept optional expiresAt', () => {
const result = schema.ExtraBalanceCreditPack.safeParse({
orgId: '507f1f77bcf86cd799439011',
amount: 500000,
stripeSessionId: 'cs_test_abc',
expiresAt: '2027-01-01T00:00:00Z',
});
expect(result.error).toBeFalsy();
expect(result.data.expiresAt).toBeInstanceOf(Date);
});
});
describe('ExtraBalanceDebit', () => {
test('should be valid with required fields', () => {
const result = schema.ExtraBalanceDebit.safeParse({
orgId: '507f1f77bcf86cd799439011',
amount: 1000,
refId: 'history_abc123',
});
expect(result.error).toBeFalsy();
});
test('should reject empty refId', () => {
const result = schema.ExtraBalanceDebit.safeParse({
orgId: '507f1f77bcf86cd799439011',
amount: 1000,
refId: '',
});
expect(result.error).toBeDefined();
});
});
});
// ─── Repository tests ──────────────────────────────────────────────────────
describe('Repository', () => {
let BillingExtraBalanceRepository;
let mockModel;
const orgId = '507f1f77bcf86cd799439011';
/**
* @param {Object} [overrides={}] - Fields to override on the stub document.
* @returns {Object} A stub ExtraBalance document.
*/
const makeDoc = (overrides = {}) => ({
_id: '507f1f77bcf86cd799439099',
organization: orgId,
ledger: [],
cachedBalance: 0,
cachedBalanceAt: new Date(),
...overrides,
});
beforeEach(async () => {
jest.resetModules();
mockModel = {
findOne: jest.fn(),
findOneAndUpdate: jest.fn(),
updateOne: jest.fn(),
updateMany: jest.fn(),
};
jest.unstable_mockModule('mongoose', () => ({
default: {
model: jest.fn(() => mockModel),
Types: {
ObjectId: {
isValid: jest.fn(() => true),
},
},
},
}));
const mod = await import('../repositories/billing.extraBalance.repository.js');
BillingExtraBalanceRepository = mod.default;
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('getOrCreate', () => {
test('should call findOneAndUpdate with upsert', async () => {
const doc = makeDoc();
mockModel.findOneAndUpdate.mockResolvedValue(doc);
const result = await BillingExtraBalanceRepository.getOrCreate(orgId);
expect(mockModel.findOneAndUpdate).toHaveBeenCalledWith(
{ organization: orgId },
expect.objectContaining({ $setOnInsert: expect.any(Object) }),
expect.objectContaining({ upsert: true, returnDocument: 'after' }),
);
expect(result).toBe(doc);
});
test('should return null for malformed orgId (ObjectId guard)', async () => {
const { default: mongoose } = await import('mongoose');
mongoose.Types.ObjectId.isValid = jest.fn(() => false);
const result = await BillingExtraBalanceRepository.getOrCreate('not-valid-id');
expect(result).toBeNull();
expect(mockModel.findOneAndUpdate).not.toHaveBeenCalled();
});
});
describe('creditPack — idempotency', () => {
test('should apply credit when stripeSessionId is new', async () => {
const updatedDoc = makeDoc({ cachedBalance: 500000, ledger: [{ kind: 'topup', amount: 500000, stripeSessionId: 'cs_abc' }] });
// Step 1: getOrCreate (no-op on existing); Step 2: actual credit
mockModel.findOneAndUpdate
.mockResolvedValueOnce(makeDoc())
.mockResolvedValueOnce(updatedDoc);
const result = await BillingExtraBalanceRepository.creditPack(orgId, 500000, 'cs_abc', null);
expect(result.applied).toBe(true);
expect(result.doc.cachedBalance).toBe(500000);
expect(mockModel.findOneAndUpdate).toHaveBeenCalledTimes(2);
});
test('should return applied=false with reason duplicate_session when stripeSessionId already exists', async () => {
// Step 1: getOrCreate succeeds; Step 2: idempotency filter excludes → null
mockModel.findOneAndUpdate
.mockResolvedValueOnce(makeDoc())
.mockResolvedValueOnce(null);
const result = await BillingExtraBalanceRepository.creditPack(orgId, 500000, 'cs_abc', null);
expect(result.applied).toBe(false);
expect(result.reason).toBe('duplicate_session');
expect(result.doc).toBeNull();
});
test('step 1 issues upsert getOrCreate with $setOnInsert (fresh org support)', async () => {
let step1Filter;
let step1Update;
let step1Options;
const updatedDoc = makeDoc({ cachedBalance: 500000 });
mockModel.findOneAndUpdate.mockImplementation((filter, update, options) => {
if (!step1Filter) {
step1Filter = filter;
step1Update = update;
step1Options = options;
return Promise.resolve(null); // fresh org — no doc yet
}
return Promise.resolve(updatedDoc);
});
await BillingExtraBalanceRepository.creditPack(orgId, 500000, 'cs_fresh', null);
expect(step1Options?.upsert).toBe(true);
expect(step1Update.$setOnInsert).toMatchObject({ organization: orgId, ledger: [], cachedBalance: 0 });
});
test('step 2 does NOT include upsert (doc guaranteed by step 1)', async () => {
let step2Options;
mockModel.findOneAndUpdate
.mockResolvedValueOnce(makeDoc())
.mockImplementation((filter, update, options) => {
step2Options = options;
return Promise.resolve(makeDoc({ cachedBalance: 1000 }));
});
await BillingExtraBalanceRepository.creditPack(orgId, 1000, 'cs_no_upsert', null);
expect(step2Options?.upsert).toBeFalsy();
});
test('should set expiresAt on topup entry when provided', async () => {
const expiresAt = new Date('2027-01-01');
let capturedUpdate;
mockModel.findOneAndUpdate
.mockResolvedValueOnce(makeDoc())
.mockImplementation((filter, update) => {
capturedUpdate = update;
return Promise.resolve(makeDoc({ cachedBalance: 1000, ledger: [{ kind: 'topup', amount: 1000, stripeSessionId: 'cs_xyz', expiresAt }] }));
});
await BillingExtraBalanceRepository.creditPack(orgId, 1000, 'cs_xyz', expiresAt);
expect(capturedUpdate.$push.ledger.expiresAt).toBe(expiresAt);
});
});
describe('debit', () => {
test('should apply debit when balance is sufficient and refId is new', async () => {
const existingDoc = makeDoc();
const updatedDoc = makeDoc({ cachedBalance: 400000, ledger: [{ kind: 'debit', amount: -100000, refId: 'ref_1' }] });
// Step 1: getOrCreate (no-op on existing); Step 2: actual debit
mockModel.findOneAndUpdate
.mockResolvedValueOnce(existingDoc)
.mockResolvedValueOnce(updatedDoc);
const result = await BillingExtraBalanceRepository.debit(orgId, 100000, 'ref_1');
expect(result.applied).toBe(true);
expect(result.doc).toBe(updatedDoc);
expect(mockModel.findOneAndUpdate).toHaveBeenCalledTimes(2);
});
test('should apply debit and allow negative balance when amount exceeds cachedBalance (overage)', async () => {
// cachedBalance=10, amount=15 → balance becomes -5; applied=true (no balance guard)
const existingDoc = makeDoc({ cachedBalance: 10 });
const updatedDoc = makeDoc({ cachedBalance: -5, ledger: [{ kind: 'debit', amount: -15, refId: 'ref_overage' }] });
mockModel.findOneAndUpdate
.mockResolvedValueOnce(existingDoc)
.mockResolvedValueOnce(updatedDoc);
const result = await BillingExtraBalanceRepository.debit(orgId, 15, 'ref_overage');
expect(result.applied).toBe(true);
expect(result.doc.cachedBalance).toBe(-5);
});
test('step 1 issues upsert getOrCreate with $setOnInsert (fresh org support)', async () => {
let step1Filter;
let step1Update;
let step1Options;
const updatedDoc = makeDoc({ cachedBalance: -50 });
mockModel.findOneAndUpdate.mockImplementation((filter, update, options) => {
if (!step1Filter) {
step1Filter = filter;
step1Update = update;
step1Options = options;
return Promise.resolve(null); // fresh org — no doc yet
}
return Promise.resolve(updatedDoc);
});
await BillingExtraBalanceRepository.debit(orgId, 50, 'ref_fresh');
expect(step1Options?.upsert).toBe(true);
expect(step1Update.$setOnInsert).toMatchObject({ organization: orgId, ledger: [], cachedBalance: 0 });
});
test('filter does NOT include cachedBalance guard (allows negative balance)', async () => {
const existingDoc = makeDoc();
let step2Filter;
mockModel.findOneAndUpdate
.mockResolvedValueOnce(existingDoc)
.mockImplementation((filter) => {
step2Filter = filter;
return Promise.resolve(makeDoc({ cachedBalance: -5 }));
});
await BillingExtraBalanceRepository.debit(orgId, 15, 'ref_no_balance_guard');
expect(step2Filter).not.toHaveProperty('cachedBalance');
});
test('should return applied=false with reason duplicate_step when refId already used (replay protection)', async () => {
// Step 1: getOrCreate succeeds; Step 2: idempotency filter excludes → null
mockModel.findOneAndUpdate
.mockResolvedValueOnce(makeDoc())
.mockResolvedValueOnce(null);
const result = await BillingExtraBalanceRepository.debit(orgId, 100, 'ref_duplicate');
expect(result.applied).toBe(false);
expect(result.reason).toBe('duplicate_step');
});
test('should push a negative amount entry to the ledger', async () => {
const existingDoc = makeDoc();
let step2Update;
mockModel.findOneAndUpdate
.mockResolvedValueOnce(existingDoc)
.mockImplementation((filter, update) => {
step2Update = update;
return Promise.resolve(makeDoc({ cachedBalance: 0 }));
});
await BillingExtraBalanceRepository.debit(orgId, 500, 'ref_check');
expect(step2Update.$push.ledger.amount).toBe(-500);
expect(step2Update.$push.ledger.kind).toBe('debit');
expect(step2Update.$inc.cachedBalance).toBe(-500);
});
});
describe('addExpirationEntries — idempotency', () => {
test('should return 0 when no document exists', async () => {
mockModel.findOne.mockReturnValue({ lean: jest.fn().mockResolvedValue(null) });
const result = await BillingExtraBalanceRepository.addExpirationEntries(orgId, new Date());
expect(result).toBe(0);
});
test('should return 0 when no topup entries have expired', async () => {
const future = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000);
const doc = makeDoc({
ledger: [{ _id: '507f1f77bcf86cd799439abc', kind: 'topup', amount: 1000, expiresAt: future }],
});
mockModel.findOne.mockReturnValue({ lean: jest.fn().mockResolvedValue(doc) });
const result = await BillingExtraBalanceRepository.addExpirationEntries(orgId, new Date());
expect(result).toBe(0);
});
test('should expire a topup entry and return 1', async () => {
const past = new Date(Date.now() - 1000);
const entryId = '507f1f77bcf86cd799439abc';
const doc = makeDoc({
ledger: [{ _id: entryId, kind: 'topup', amount: 1000, expiresAt: past }],
});
mockModel.findOne.mockReturnValue({ lean: jest.fn().mockResolvedValue(doc) });
mockModel.findOneAndUpdate.mockResolvedValue(makeDoc({ cachedBalance: 0 }));
const result = await BillingExtraBalanceRepository.addExpirationEntries(orgId, new Date());
expect(result).toBe(1);
// Verify expiration entry references the topup id
const call = mockModel.findOneAndUpdate.mock.calls[0];
expect(call[1].$push.ledger.refId).toBe(`expire-${entryId}`);
expect(call[1].$push.ledger.kind).toBe('expiration');
expect(call[1].$push.ledger.amount).toBe(-1000);
});
test('should NOT add a second expiration entry when already expired (idempotent)', async () => {
const past = new Date(Date.now() - 1000);
const entryId = '507f1f77bcf86cd799439abc';
const doc = makeDoc({
ledger: [
{ _id: entryId, kind: 'topup', amount: 1000, expiresAt: past },
{ kind: 'expiration', amount: -1000, refId: `expire-${entryId}` },
],
});
mockModel.findOne.mockReturnValue({ lean: jest.fn().mockResolvedValue(doc) });
const result = await BillingExtraBalanceRepository.addExpirationEntries(orgId, new Date());
expect(result).toBe(0);
expect(mockModel.findOneAndUpdate).not.toHaveBeenCalled();
});
});
describe('getBalance', () => {
test('should return cached balance', async () => {
mockModel.findOne.mockReturnValue({
lean: jest.fn().mockResolvedValue({ cachedBalance: 123456 }),
});
const balance = await BillingExtraBalanceRepository.getBalance(orgId);
expect(balance).toBe(123456);
});
test('should return 0 when no document exists', async () => {
mockModel.findOne.mockReturnValue({
lean: jest.fn().mockResolvedValue(null),
});
const balance = await BillingExtraBalanceRepository.getBalance(orgId);
expect(balance).toBe(0);
});
});
describe('refundPartial', () => {
test('should apply refund atomically when refId is new', async () => {
const updatedDoc = makeDoc({ cachedBalance: 0 });
mockModel.findOneAndUpdate.mockResolvedValue(updatedDoc);
const result = await BillingExtraBalanceRepository.refundPartial(
orgId,
'cs_refund_test',
500000,
'refund-cs_refund_test-4900',
);
expect(result.applied).toBe(true);
expect(result.doc).toBe(updatedDoc);
const call = mockModel.findOneAndUpdate.mock.calls[0];
expect(call[0]).toEqual({ organization: orgId, 'ledger.refId': { $ne: 'refund-cs_refund_test-4900' } });
expect(call[1].$push.ledger.kind).toBe('refund');
expect(call[1].$push.ledger.amount).toBe(-500000);
expect(call[1].$push.ledger.stripeSessionId).toBe('cs_refund_test');
expect(call[1].$push.ledger.refId).toBe('refund-cs_refund_test-4900');
expect(call[1].$inc.cachedBalance).toBe(-500000);
});
test('should return applied=false when refId already used (idempotent)', async () => {
mockModel.findOneAndUpdate.mockResolvedValue(null);
const result = await BillingExtraBalanceRepository.refundPartial(
orgId,
'cs_refund_test',
500000,
'refund-cs_refund_test-4900',
);
expect(result.applied).toBe(false);
expect(result.doc).toBeNull();
});
test('should allow negative resulting balance (economic reflection)', async () => {
const updatedDoc = makeDoc({ cachedBalance: -500000 });
mockModel.findOneAndUpdate.mockResolvedValue(updatedDoc);
const result = await BillingExtraBalanceRepository.refundPartial(orgId, 'cs_neg', 500000, 'refund-cs_neg-4900');
expect(result.applied).toBe(true);
expect(result.doc.cachedBalance).toBe(-500000);
});
test('should throw on zero refundUnits', async () => {
await expect(
BillingExtraBalanceRepository.refundPartial(orgId, 'cs_abc', 0, 'refund-key'),
).rejects.toThrow('invalid argument: refundUnits must be a positive finite number');
});
test('should throw on empty refId', async () => {
await expect(
BillingExtraBalanceRepository.refundPartial(orgId, 'cs_abc', 100, ''),
).rejects.toThrow('invalid argument: refId must be a non-empty string');
});
});
describe('creditPack — input guards', () => {
test('should throw on zero amount', async () => {
await expect(
BillingExtraBalanceRepository.creditPack(orgId, 0, 'cs_test', null),
).rejects.toThrow('invalid argument: amount must be a positive finite number');
});
test('should throw on negative amount', async () => {
await expect(
BillingExtraBalanceRepository.creditPack(orgId, -100, 'cs_test', null),
).rejects.toThrow('invalid argument: amount must be a positive finite number');
});
test('should throw on empty stripeSessionId', async () => {
await expect(
BillingExtraBalanceRepository.creditPack(orgId, 100, '', null),
).rejects.toThrow('invalid argument: stripeSessionId must be a non-empty string');
});
});
describe('debit — input guards', () => {
test('should throw on zero amount', async () => {
await expect(
BillingExtraBalanceRepository.debit(orgId, 0, 'ref_test'),
).rejects.toThrow('invalid argument: amount must be a positive finite number');
});
test('should throw on negative amount', async () => {
await expect(
BillingExtraBalanceRepository.debit(orgId, -50, 'ref_test'),
).rejects.toThrow('invalid argument: amount must be a positive finite number');
});
test('should throw on empty refId', async () => {
await expect(
BillingExtraBalanceRepository.debit(orgId, 100, ''),
).rejects.toThrow('invalid argument: refId must be a non-empty string');
});
});
});
});