-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.usage.endpoint.unit.tests.js
More file actions
360 lines (293 loc) · 12.3 KB
/
billing.usage.endpoint.unit.tests.js
File metadata and controls
360 lines (293 loc) · 12.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
/**
* Module dependencies.
*/
import { jest, beforeEach, afterEach } from '@jest/globals';
/**
* Unit tests for billing usage endpoint (getUsage controller)
*/
describe('Billing usage endpoint unit tests:', () => {
let billingController;
let mockBillingService;
let mockBillingUsageService;
let mockConfig;
let res;
const orgId = '507f1f77bcf86cd799439011';
beforeEach(async () => {
jest.resetModules();
mockBillingService = {
getLocalSubscription: jest.fn(),
getSubscription: jest.fn(),
};
mockBillingUsageService = {
get: jest.fn(),
};
mockConfig = {
billing: {
quotas: {
free: { documents: { create: 5 }, requests: { execute: 100 } },
starter: { documents: { create: 20 }, requests: { execute: 2000 } },
pro: { documents: { create: Infinity }, requests: { execute: Infinity } },
},
},
};
jest.unstable_mockModule('../services/billing.service.js', () => ({
default: mockBillingService,
}));
jest.unstable_mockModule('../services/billing.usage.service.js', () => ({
default: mockBillingUsageService,
}));
jest.unstable_mockModule('../services/billing.extra.service.js', () => ({
default: { getOrgBalanceContext: jest.fn().mockResolvedValue(0) },
}));
jest.unstable_mockModule('../services/billing.plan.service.js', () => ({
default: { getActivePlan: jest.fn().mockReturnValue(null) },
}));
jest.unstable_mockModule('../../../config/index.js', () => ({
default: mockConfig,
}));
// billing.extra.service.js has top-level logger/events imports — mock to prevent config read
jest.unstable_mockModule('../../../lib/services/logger.js', () => ({
default: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },
}));
jest.unstable_mockModule('../lib/events.js', () => ({
default: { emit: jest.fn() },
}));
const mod = await import('../controllers/billing.controller.js');
billingController = mod.default;
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
});
afterEach(() => {
jest.restoreAllMocks();
});
test('should return usage and limits for active subscription', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'starter', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: { 'documents_create': 5, 'requests_execute': 42 } });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
type: 'success',
message: 'billing usage',
data: expect.objectContaining({
plan: 'starter',
usage: { 'documents_create': 5, 'requests_execute': 42 },
limits: { 'documents_create': 20, 'requests_execute': 2000 },
}),
}));
});
test('should return free plan when no subscription', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue(null);
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
type: 'success',
data: expect.objectContaining({
plan: 'free',
limits: { 'documents_create': 5, 'requests_execute': 100 },
}),
}));
});
test.each([
'past_due',
'canceled',
'unpaid',
'incomplete',
'incomplete_expired',
'paused',
])('should return free plan when subscription status is %s', async (status) => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'starter', status });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: { 'documents_create': 2 } });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
plan: 'free',
limits: { 'documents_create': 5, 'requests_execute': 100 },
}),
}));
});
test('should return paid plan when subscription status is trialing', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'starter', status: 'trialing' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
plan: 'starter',
limits: { 'documents_create': 20, 'requests_execute': 2000 },
}),
}));
});
test('should return empty limits when plan has no quota config', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'enterprise', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
plan: 'enterprise',
limits: {},
}),
}));
});
test('should return correct flattened limits format', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'pro', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
plan: 'pro',
limits: { 'documents_create': null, 'requests_execute': null },
}),
}));
});
test('should return empty counters for new org (no usage yet)', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'starter', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
usage: {},
}),
}));
});
test('should return period from usage month field', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'free', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
const { data } = res.json.mock.calls[0][0];
expect(data.period).toBe('2026-03');
});
test('should NOT call getSubscription (no Stripe fetch) on usage endpoint', async () => {
// V6 P2: /usage uses getLocalSubscription, not getSubscription, to avoid +50ms Stripe call.
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'starter', status: 'active' });
mockBillingUsageService.get.mockResolvedValue({ month: '2026-03', counters: {} });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(mockBillingService.getLocalSubscription).toHaveBeenCalledWith(orgId);
expect(mockBillingService.getSubscription).not.toHaveBeenCalled();
});
test('should return 500 when an error occurs', async () => {
mockBillingService.getLocalSubscription.mockRejectedValue(new Error('DB error'));
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
type: 'error',
message: 'Internal Server Error',
}));
});
describe('meterMode — meterQuota live override', () => {
let mockBillingPlanService;
let mockMeterUsageService;
beforeEach(async () => {
jest.resetModules();
mockBillingService = {
getLocalSubscription: jest.fn(),
getSubscription: jest.fn(),
};
mockMeterUsageService = {
getMeter: jest.fn(),
currentWeekKey: jest.fn().mockReturnValue('2026-W20'),
};
mockBillingPlanService = {
getActivePlan: jest.fn(),
};
jest.unstable_mockModule('../services/billing.service.js', () => ({
default: mockBillingService,
}));
jest.unstable_mockModule('../services/billing.usage.service.js', () => ({
default: mockMeterUsageService,
}));
jest.unstable_mockModule('../services/billing.extra.service.js', () => ({
default: { getOrgBalanceContext: jest.fn().mockResolvedValue(0) },
}));
jest.unstable_mockModule('../services/billing.plan.service.js', () => ({
default: mockBillingPlanService,
}));
jest.unstable_mockModule('../../../lib/services/logger.js', () => ({
default: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },
}));
jest.unstable_mockModule('../lib/events.js', () => ({
default: { emit: jest.fn() },
}));
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
billing: {
meterMode: true,
packs: [],
},
},
}));
const mod = await import('../controllers/billing.controller.js');
billingController = mod.default;
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
};
});
test('returns growth plan quota (1600) from live config when DB snapshot shows old free quota (10)', async () => {
// DB snapshot baked when user was on free (meterQuota = 10)
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'growth', status: 'active' });
mockMeterUsageService.getMeter.mockResolvedValue({
meterUsed: 46,
meterQuota: 10,
meterBreakdown: {},
planVersion: 'v1',
weekKey: '2026-W20',
resetAt: null,
});
// Live config knows growth = 1600
mockBillingPlanService.getActivePlan.mockReturnValue({ meterQuota: 1600 });
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
const payload = res.json.mock.calls[0][0].data;
expect(payload.meterQuota).toBe(1600); // live plan config, not stale DB snapshot
expect(payload.meterUsed).toBe(46);
expect(payload.plan).toBe('growth');
});
test('falls back to DB snapshot quota when live plan config returns null (unknown plan)', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue({ plan: 'legacy', status: 'active' });
mockMeterUsageService.getMeter.mockResolvedValue({
meterUsed: 5,
meterQuota: 50,
meterBreakdown: {},
planVersion: 'v1',
weekKey: '2026-W20',
resetAt: null,
});
mockBillingPlanService.getActivePlan.mockReturnValue(null);
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
const payload = res.json.mock.calls[0][0].data;
expect(payload.meterQuota).toBe(50); // falls back to DB snapshot
});
test('returns 0 meterQuota when no DB snapshot and no live config plan', async () => {
mockBillingService.getLocalSubscription.mockResolvedValue(null);
mockMeterUsageService.getMeter.mockResolvedValue(null);
mockBillingPlanService.getActivePlan.mockReturnValue(null);
const req = { organization: { _id: orgId } };
await billingController.getUsage(req, res);
expect(res.status).toHaveBeenCalledWith(200);
const payload = res.json.mock.calls[0][0].data;
expect(payload.meterQuota).toBe(0);
expect(payload.meterUsed).toBe(0);
});
});
});