-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.init.unit.tests.js
More file actions
407 lines (339 loc) · 17.6 KB
/
Copy pathbilling.init.unit.tests.js
File metadata and controls
407 lines (339 loc) · 17.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
/**
* Module dependencies.
*/
import { jest, describe, test, beforeEach, afterEach, expect } from '@jest/globals';
/**
* Unit tests for billing.init — boot validators.
*/
describe('billing.init unit tests:', () => {
let billingInit;
let mockBillingUsageRepository;
let mockConfig;
let mockDistinct;
let mockMongoose;
let mockLogger;
let mockInvitationEvents;
let mockReferralService;
let mockOrganizationEvents;
let mockUserService;
let mockInvitationRepository;
let mockSignupGrantService;
const mockApp = {};
beforeEach(async () => {
jest.resetModules();
mockConfig = {
billing: {
meterMode: false,
packs: [],
},
};
mockBillingUsageRepository = {
countLegacyConsumedHistoryIds: jest.fn().mockResolvedValue(0),
};
mockDistinct = jest.fn().mockResolvedValue([]);
mockMongoose = {
model: jest.fn().mockReturnValue({ distinct: mockDistinct }),
};
mockLogger = { info: jest.fn(), error: jest.fn(), warn: jest.fn() };
jest.unstable_mockModule('../../../config/index.js', () => ({
default: mockConfig,
}));
jest.unstable_mockModule('../repositories/billing.usage.repository.js', () => ({
default: mockBillingUsageRepository,
}));
// Stub analytics, logger and events to avoid side effects
jest.unstable_mockModule('../../../lib/services/analytics.js', () => ({
default: { groupIdentify: jest.fn() },
}));
jest.unstable_mockModule('../../../lib/services/logger.js', () => ({
default: mockLogger,
}));
jest.unstable_mockModule('../lib/events.js', () => ({
default: { on: jest.fn(), emit: jest.fn() },
}));
// P8a: billing is an optional consumer of the invitations `invitation.accepted`
// event — stub the singleton so the unit test asserts the listener wiring in isolation.
mockInvitationEvents = { on: jest.fn(), emit: jest.fn() };
jest.unstable_mockModule('../../invitations/lib/events.js', () => ({
default: mockInvitationEvents,
}));
// #3842: the listener lazy-imports the referral service — stub it so the wiring
// tests stay isolated from users/organizations resolution.
mockReferralService = { grantForInvitation: jest.fn().mockResolvedValue({}) };
jest.unstable_mockModule('../services/billing.referral.service.js', () => ({
default: mockReferralService,
}));
// #3844: the organizations `organization.provisioned` singleton — stub like invitationEvents.
mockOrganizationEvents = { on: jest.fn(), emit: jest.fn() };
jest.unstable_mockModule('../../organizations/lib/events.js', () => ({
default: mockOrganizationEvents,
}));
// #3844: the listener lazy-imports UserService + InvitationRepository — stub both.
mockUserService = { getBrut: jest.fn().mockResolvedValue(null) };
jest.unstable_mockModule('../../users/services/users.service.js', () => ({
default: mockUserService,
}));
mockInvitationRepository = { findByAcceptedUserId: jest.fn().mockResolvedValue(null) };
jest.unstable_mockModule('../../invitations/repositories/invitations.repository.js', () => ({
default: mockInvitationRepository,
}));
// #3952: the organization.created listener delegates to BillingSignupGrantService — stub it
// so the wiring tests stay isolated from the real grant/plan/repository resolution.
mockSignupGrantService = { grantOnSignup: jest.fn().mockResolvedValue({ applied: true }) };
jest.unstable_mockModule('../services/billing.signupGrant.service.js', () => ({
default: mockSignupGrantService,
}));
// Stub billing.email so boot validator tests don't wire real email listeners
jest.unstable_mockModule('../billing.email.js', () => ({
setupBillingEmails: jest.fn(),
}));
jest.unstable_mockModule('mongoose', () => ({
default: mockMongoose,
}));
const mod = await import('../billing.init.js');
billingInit = mod.default;
});
afterEach(() => {
jest.restoreAllMocks();
});
test('resolves without error when meterMode=false', async () => {
await expect(billingInit(mockApp)).resolves.toBeUndefined();
});
describe('#3842 referral grant listener (invitation.accepted):', () => {
const payload = { invitationId: 'i1', email: 'a@b.co', invitedBy: 'x', acceptedUserId: 'u1' };
/**
* Boot the module and return the registered invitation.accepted handler.
* @returns {Promise<Function>} The wired listener.
*/
const getHandler = async () => {
await billingInit(mockApp);
const acceptedCall = mockInvitationEvents.on.mock.calls.find(([evt]) => evt === 'invitation.accepted');
expect(acceptedCall).toBeDefined();
return acceptedCall[1];
};
test('wires the listener on the invitations emitter', async () => {
const handler = await getHandler();
expect(typeof handler).toBe('function');
});
test('config-gated: disabled (default) → returns immediately, the service is never imported/called', async () => {
// mockConfig.billing has NO referral block — existing deployments unaffected.
const handler = await getHandler();
await handler(payload);
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
test('config-gated: enabled:false explicitly → no-op', async () => {
mockConfig.billing.referral = { enabled: false, referrerUnits: 1000, refereeUnits: 500 };
const handler = await getHandler();
await handler(payload);
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
test('enabled → delegates the payload to BillingReferralService.grantForInvitation', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
const handler = await getHandler();
await handler(payload);
expect(mockReferralService.grantForInvitation).toHaveBeenCalledTimes(1);
expect(mockReferralService.grantForInvitation).toHaveBeenCalledWith(payload);
});
test('self-guard: a grant REJECTION is swallowed + logged, never escapes the listener', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockReferralService.grantForInvitation.mockRejectedValue(new Error('mongo down'));
const handler = await getHandler();
// The emit-site catch is sync-only — the async listener must resolve, not reject.
await expect(handler(payload)).resolves.toBeUndefined();
const errCall = mockLogger.error.mock.calls.find(([msg]) => msg.includes('referral grant failed'));
expect(errCall).toBeDefined();
expect(errCall[1]).toMatchObject({ invitationId: 'i1', err: 'mongo down' });
});
test('self-guard: even a malformed payload cannot make the listener throw/reject', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockReferralService.grantForInvitation.mockRejectedValue(new Error('boom'));
const handler = await getHandler();
await expect(handler(undefined)).resolves.toBeUndefined();
expect(mockLogger.error).toHaveBeenCalled();
});
});
describe('#3844 instant referee grant listener (organization.provisioned):', () => {
const payload = { userId: 'u1', organizationId: 'o1' };
const invitation = { _id: 'i9', invitedBy: 'x', acceptedUserId: 'u1' };
/**
* Boot the module and return the registered organization.provisioned handler.
* @returns {Promise<Function>} The wired listener.
*/
const getHandler = async () => {
await billingInit(mockApp);
const provisionedCall = mockOrganizationEvents.on.mock.calls.find(([evt]) => evt === 'organization.provisioned');
expect(provisionedCall).toBeDefined();
return provisionedCall[1];
};
test('wires the listener on the organizations emitter', async () => {
const handler = await getHandler();
expect(typeof handler).toBe('function');
});
test('config-gated: disabled (default) → returns immediately, no lookup, no grant', async () => {
// mockConfig.billing has NO referral block — existing deployments unaffected.
const handler = await getHandler();
await handler(payload);
expect(mockUserService.getBrut).not.toHaveBeenCalled();
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
test('user without referredBy → no invitation lookup, no grant', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockUserService.getBrut.mockResolvedValue({ _id: 'u1', referredBy: null });
const handler = await getHandler();
await handler(payload);
expect(mockUserService.getBrut).toHaveBeenCalledWith({ id: 'u1' });
expect(mockInvitationRepository.findByAcceptedUserId).not.toHaveBeenCalled();
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
test('referredBy set but no accepted invitation found → no grant (the cron owns the edge)', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockUserService.getBrut.mockResolvedValue({ _id: 'u1', referredBy: 'x' });
mockInvitationRepository.findByAcceptedUserId.mockResolvedValue(null);
const handler = await getHandler();
await handler(payload);
expect(mockInvitationRepository.findByAcceptedUserId).toHaveBeenCalledWith('u1');
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
test('happy path → grant called once with the exact stringified invitation payload', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockUserService.getBrut.mockResolvedValue({ _id: 'u1', referredBy: 'x' });
mockInvitationRepository.findByAcceptedUserId.mockResolvedValue(invitation);
const handler = await getHandler();
await handler(payload);
expect(mockReferralService.grantForInvitation).toHaveBeenCalledTimes(1);
expect(mockReferralService.grantForInvitation).toHaveBeenCalledWith({
invitationId: 'i9',
invitedBy: 'x',
acceptedUserId: 'u1',
});
});
test('admin-created invite (invitedBy null) → grant called with invitedBy:null', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockUserService.getBrut.mockResolvedValue({ _id: 'u1', referredBy: 'x' });
mockInvitationRepository.findByAcceptedUserId.mockResolvedValue({ _id: 'i9', invitedBy: null, acceptedUserId: 'u1' });
const handler = await getHandler();
await handler(payload);
expect(mockReferralService.grantForInvitation).toHaveBeenCalledWith({
invitationId: 'i9',
invitedBy: null,
acceptedUserId: 'u1',
});
});
test('self-guard: a grant REJECTION is swallowed + logged, never escapes the listener', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
mockUserService.getBrut.mockResolvedValue({ _id: 'u1', referredBy: 'x' });
mockInvitationRepository.findByAcceptedUserId.mockResolvedValue(invitation);
mockReferralService.grantForInvitation.mockRejectedValue(new Error('mongo down'));
const handler = await getHandler();
// The emit-site catch is sync-only — the async listener must resolve, not reject.
await expect(handler(payload)).resolves.toBeUndefined();
const errCall = mockLogger.error.mock.calls.find(([msg]) => msg.includes('instant referee grant failed'));
expect(errCall).toBeDefined();
expect(errCall[1]).toMatchObject({ userId: 'u1', err: 'mongo down' });
});
test('self-guard: even a malformed payload cannot make the listener throw/reject', async () => {
mockConfig.billing.referral = { enabled: true, referrerUnits: 1000, refereeUnits: 500 };
const handler = await getHandler();
await expect(handler(undefined)).resolves.toBeUndefined();
expect(mockUserService.getBrut).not.toHaveBeenCalled();
expect(mockReferralService.grantForInvitation).not.toHaveBeenCalled();
});
});
describe('#3952 signup grant listener (organization.created):', () => {
const payload = { orgId: 'org1', planId: 'free' };
/**
* Boot the module and return the registered organization.created handler.
* @returns {Promise<Function>} The wired listener.
*/
const getHandler = async () => {
await billingInit(mockApp);
const createdCall = mockOrganizationEvents.on.mock.calls.find(([evt]) => evt === 'organization.created');
expect(createdCall).toBeDefined();
return createdCall[1];
};
test('wires the listener on the organizations emitter', async () => {
const handler = await getHandler();
expect(typeof handler).toBe('function');
});
test('NOT config-gated — delegates to BillingSignupGrantService.grantOnSignup with no referral config set', async () => {
// mockConfig.billing has NO referral block — unlike the two referral listeners above,
// this one must still fire (grantOnSignup is core signup behavior, not a referral reward).
const handler = await getHandler();
await handler(payload);
expect(mockSignupGrantService.grantOnSignup).toHaveBeenCalledTimes(1);
expect(mockSignupGrantService.grantOnSignup).toHaveBeenCalledWith({ orgId: 'org1', planId: 'free' });
});
test('passes the payload through verbatim (orgId + planId from both org-creation call sites)', async () => {
const handler = await getHandler();
await handler({ orgId: 'org2', planId: 'growth' });
expect(mockSignupGrantService.grantOnSignup).toHaveBeenCalledWith({ orgId: 'org2', planId: 'growth' });
});
test('self-guard: a grant REJECTION is swallowed + logged, never escapes the listener', async () => {
mockSignupGrantService.grantOnSignup.mockRejectedValue(new Error('mongo down'));
const handler = await getHandler();
// The emit-site catch (organizations) is sync-only — the async listener must resolve, not reject.
await expect(handler(payload)).resolves.toBeUndefined();
const errCall = mockLogger.error.mock.calls.find(([msg]) => msg.includes('signup grant failed via organization.created listener'));
expect(errCall).toBeDefined();
expect(errCall[1]).toMatchObject({ orgId: 'org1', planId: 'free', err: 'mongo down' });
});
test('self-guard: even a malformed payload cannot make the listener throw/reject', async () => {
const handler = await getHandler();
await expect(handler(undefined)).resolves.toBeUndefined();
expect(mockSignupGrantService.grantOnSignup).toHaveBeenCalledWith({ orgId: undefined, planId: undefined });
});
});
test('resolves without error when meterMode=true and no legacy docs', async () => {
mockConfig.billing.meterMode = true;
mockConfig.billing.plans = ['free', 'growth', 'pro'];
await expect(billingInit(mockApp)).resolves.toBeUndefined();
});
test('boot validator warns on orphaned Subscription.plan values when meterMode=true', async () => {
mockConfig.billing.meterMode = true;
mockConfig.billing.plans = ['free', 'starter', 'pro'];
mockDistinct.mockResolvedValue(['free', 'legacy_plan']);
await billingInit(mockApp);
expect(mockDistinct).toHaveBeenCalledWith('plan');
// After Batch 4 item 6: uses logger.warn instead of console.warn
const warnCalls = mockLogger.warn.mock.calls.map((c) => c[0]);
expect(warnCalls.some((w) => w.includes('"legacy_plan" not in planDefinitions'))).toBe(true);
expect(warnCalls.some((w) => w.includes('"free"'))).toBe(false);
});
test('meterMode=true aborts boot when legacy consumedHistoryIds fields remain', async () => {
mockConfig.billing.meterMode = true;
mockBillingUsageRepository.countLegacyConsumedHistoryIds.mockResolvedValue(2);
await expect(billingInit(mockApp)).rejects.toThrow('legacy consumedHistoryIds field still present');
});
test('warns at boot when thresholdPercents contains unsupported value (not 80/100)', async () => {
mockConfig.billing.meterMode = true;
mockConfig.billing.alerts = { thresholdPercents: [75] };
mockConfig.billing.plans = ['free'];
await billingInit(mockApp);
// After Batch 4 item 6: uses logger.warn instead of console.warn
const warnCalls = mockLogger.warn.mock.calls.map((c) => c[0]);
expect(warnCalls.some((w) => w.includes('75%') && w.includes('silently skipped'))).toBe(true);
});
test('does not warn at boot when thresholdPercents contains only supported values', async () => {
mockConfig.billing.meterMode = true;
mockConfig.billing.alerts = { thresholdPercents: [80, 100] };
mockConfig.billing.plans = ['free'];
await billingInit(mockApp);
const warnCalls = mockLogger.warn.mock.calls.map((c) => c[0]);
expect(warnCalls.some((w) => typeof w === 'string' && w.includes('silently skipped'))).toBe(false);
});
test('does not warn at boot for threshold validation when meterMode=false', async () => {
mockConfig.billing.meterMode = false;
mockConfig.billing.alerts = { thresholdPercents: [75] };
await billingInit(mockApp);
const warnCalls = mockLogger.warn.mock.calls.map((c) => c[0]);
expect(warnCalls.some((w) => typeof w === 'string' && w.includes('silently skipped'))).toBe(false);
});
test('boot validator failure does not crash boot', async () => {
mockConfig.billing.meterMode = true;
mockConfig.billing.plans = ['free'];
mockMongoose.model.mockImplementation(() => {
throw new Error('model not registered');
});
await expect(billingInit(mockApp)).resolves.toBeUndefined();
});
});