-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.webhook.checkout.unit.tests.js
More file actions
495 lines (422 loc) · 18 KB
/
billing.webhook.checkout.unit.tests.js
File metadata and controls
495 lines (422 loc) · 18 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
/**
* Module dependencies.
*/
import { jest, describe, test, beforeEach, afterEach, expect } from '@jest/globals';
/**
* Unit tests for checkout webhook handlers:
* - handleCheckoutSessionCompleted routing (subscription vs payment mode)
* - handleCheckoutPaymentCompleted (extras pack credit)
* - handleCheckoutCompleted (subscription creation/update)
*/
describe('Billing webhook checkout unit tests:', () => {
let BillingWebhookService;
let mockSubscriptionRepository;
let mockOrganizationRepository;
let mockExtraService;
let mockStripeInstance;
const orgId = '507f1f77bcf86cd799439011';
const subId = '607f1f77bcf86cd799439022';
const stripeSessionId = 'cs_test_session_abc';
beforeEach(async () => {
jest.resetModules();
mockSubscriptionRepository = {
findByOrganization: jest.fn(),
findByStripeCustomerId: jest.fn(),
findByStripeSubscriptionId: jest.fn(),
create: jest.fn(),
update: jest.fn(),
updateIfEventNewer: jest.fn().mockResolvedValue({ _id: subId }),
};
mockOrganizationRepository = {
setPlan: jest.fn().mockResolvedValue({}),
};
mockExtraService = {
creditPack: jest.fn().mockResolvedValue({ doc: {}, applied: true }),
refundPartial: jest.fn(),
};
mockStripeInstance = {
paymentIntents: {
update: jest.fn().mockResolvedValue({}),
},
subscriptions: {
// Default: return 'active' status so handleCheckoutCompleted proceeds normally in tests.
retrieve: jest.fn().mockResolvedValue({ status: 'active' }),
},
};
jest.unstable_mockModule('../repositories/billing.subscription.repository.js', () => ({
default: mockSubscriptionRepository,
}));
jest.unstable_mockModule('../repositories/billing.processedStripeEvent.repository.js', () => ({
default: {
wasProcessed: jest.fn().mockResolvedValue(false),
tryRecord: jest.fn().mockResolvedValue({ recorded: true }),
},
}));
jest.unstable_mockModule('../../organizations/repositories/organizations.repository.js', () => ({
default: mockOrganizationRepository,
}));
jest.unstable_mockModule('../services/billing.extra.service.js', () => ({
default: mockExtraService,
}));
jest.unstable_mockModule('../services/billing.reset.service.js', () => ({
default: { resetWeek: jest.fn() },
}));
jest.unstable_mockModule('../lib/events.js', () => ({
default: { emit: jest.fn() },
}));
jest.unstable_mockModule('../lib/stripe.js', () => ({
default: jest.fn(() => mockStripeInstance),
}));
jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
billing: { plans: ['free', 'starter', 'pro', 'enterprise'] },
},
}));
jest.unstable_mockModule('../../../lib/services/logger.js', () => ({
default: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },
}));
jest.unstable_mockModule('mongoose', () => ({
default: {
Types: { ObjectId: { isValid: (id) => /^[a-f\d]{24}$/i.test(id) } },
model: () => ({}),
},
}));
const mod = await import('../services/billing.webhook.service.js');
BillingWebhookService = mod.default;
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
describe('handleCheckoutSessionCompleted routing', () => {
test('mode=subscription routes to handleCheckoutCompleted (subscription update)', async () => {
const existing = { _id: subId, organization: orgId };
mockSubscriptionRepository.findByOrganization.mockResolvedValue(existing);
mockSubscriptionRepository.updateIfEventNewer.mockResolvedValue({ _id: subId });
await BillingWebhookService.handleCheckoutSessionCompleted({
id: 'evt_co_1',
created: 1700000010,
data: {
object: {
id: stripeSessionId,
mode: 'subscription',
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
},
});
expect(mockSubscriptionRepository.updateIfEventNewer).toHaveBeenCalledWith(
subId,
1700000010,
'evt_co_1',
expect.objectContaining({ plan: 'pro', status: 'active' }),
'subscription',
);
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('mode=payment + kind=extras + payment_status=paid routes to handleCheckoutPaymentCompleted (creditPack)', async () => {
await BillingWebhookService.handleCheckoutSessionCompleted({
data: {
object: {
id: stripeSessionId,
mode: 'payment',
payment_status: 'paid',
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
},
},
});
expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
expect(mockSubscriptionRepository.update).not.toHaveBeenCalled();
});
test('mode=payment without metadata skips creditPack', async () => {
await BillingWebhookService.handleCheckoutSessionCompleted({
data: {
object: {
id: stripeSessionId,
mode: 'payment',
payment_status: 'paid',
metadata: null,
},
},
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
expect(mockSubscriptionRepository.update).not.toHaveBeenCalled();
});
test('mode=payment + kind≠extras skips creditPack', async () => {
await BillingWebhookService.handleCheckoutSessionCompleted({
data: {
object: {
id: stripeSessionId,
mode: 'payment',
payment_status: 'paid',
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'donation' },
},
},
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
});
describe('handleCheckoutPaymentCompleted', () => {
test('should call creditPack with orgId, packId, sessionId when payment_status=paid', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
});
test('should skip creditPack when payment_status is not paid (e.g. unpaid)', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'unpaid',
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('should skip when kind is not extras', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'other' },
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('should skip when organizationId is invalid ObjectId', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
metadata: { organizationId: 'not-valid', packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('should skip silently when packId is missing', async () => {
// MEDIUM 3: explicit verification of the silent skip on missing packId
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
metadata: { organizationId: orgId, kind: 'extras' },
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('should skip when organizationId is missing', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
metadata: { packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});
test('should call stripe.paymentIntents.update with real sessionId after creditPack succeeds (CRITICAL: refund correlation)', async () => {
const paymentIntentId = 'pi_test_abc123';
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
payment_intent: paymentIntentId,
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
expect(mockStripeInstance.paymentIntents.update).toHaveBeenCalledWith(
paymentIntentId,
{
metadata: {
organizationId: orgId,
packId: 'pack_500k',
kind: 'extras',
stripeSessionId, // real cs_* ID (not '__pending__')
},
},
);
});
test('should skip paymentIntents.update when payment_intent is absent', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
// payment_intent omitted — e.g. in test fixtures without PI
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});
expect(mockExtraService.creditPack).toHaveBeenCalled();
expect(mockStripeInstance.paymentIntents.update).not.toHaveBeenCalled();
});
test('should not throw when paymentIntents.update fails (non-fatal fallback)', async () => {
jest.useFakeTimers();
const paymentIntentId = 'pi_test_failing';
mockStripeInstance.paymentIntents.update.mockRejectedValue(new Error('Stripe API error'));
const promise = BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
payment_intent: paymentIntentId,
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});
// handleCheckoutPaymentCompleted catches the retry exhaustion internally (non-fatal),
// so the promise resolves; advance the backoff timers while it is pending.
const assertion = expect(promise).resolves.toBeUndefined();
await jest.runAllTimersAsync();
await assertion;
// creditPack should still have run despite the PI update failure
expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
});
});
describe('handleCheckoutCompleted (mode=subscription)', () => {
const checkoutEvent = { id: 'evt_co_2', created: 1700000020, data: {} };
test('should update existing subscription via updateIfEventNewer', async () => {
const existing = { _id: subId, organization: orgId };
mockSubscriptionRepository.findByOrganization.mockResolvedValue(existing);
mockSubscriptionRepository.updateIfEventNewer.mockResolvedValue({ _id: subId });
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.updateIfEventNewer).toHaveBeenCalledWith(
subId,
1700000020,
'evt_co_2',
expect.objectContaining({ plan: 'pro', status: 'active' }),
'subscription',
);
});
test('should create subscription with seeded markers when none exists', async () => {
mockSubscriptionRepository.findByOrganization.mockResolvedValue(null);
mockSubscriptionRepository.create.mockResolvedValue({});
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'starter' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.create).toHaveBeenCalledWith(
expect.objectContaining({
organization: orgId,
plan: 'starter',
status: 'active',
lastSubscriptionEventCreatedAt: 1700000020,
lastSubscriptionEventId: 'evt_co_2',
}),
);
});
test('should persist real status from Stripe (trialing, not active)', async () => {
mockStripeInstance.subscriptions.retrieve.mockResolvedValue({ status: 'trialing' });
const existing = { _id: subId, organization: orgId };
mockSubscriptionRepository.findByOrganization.mockResolvedValue(existing);
mockSubscriptionRepository.updateIfEventNewer.mockResolvedValue({ _id: subId });
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.updateIfEventNewer).toHaveBeenCalledWith(
subId,
1700000020,
'evt_co_2',
expect.objectContaining({ status: 'trialing' }),
'subscription',
);
});
test('should abort without persisting when stripe.subscriptions.retrieve throws', async () => {
mockStripeInstance.subscriptions.retrieve.mockRejectedValue(new Error('Stripe API error'));
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
// Should not persist anything — aborting to avoid stale 'active' assumption
expect(mockSubscriptionRepository.updateIfEventNewer).not.toHaveBeenCalled();
expect(mockSubscriptionRepository.create).not.toHaveBeenCalled();
});
test('should abort without persisting when stripe returns null status', async () => {
mockStripeInstance.subscriptions.retrieve.mockResolvedValue({ status: null });
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.updateIfEventNewer).not.toHaveBeenCalled();
expect(mockSubscriptionRepository.create).not.toHaveBeenCalled();
});
test('should return early without querying when stripeSubscriptionId is missing', async () => {
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
// subscription omitted — e.g. mode=subscription but sub not created yet
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.updateIfEventNewer).not.toHaveBeenCalled();
expect(mockSubscriptionRepository.create).not.toHaveBeenCalled();
});
test('should abort without querying when Stripe is not configured (getStripe returns null)', async () => {
// The billing.webhook.checkout.unit.tests.js mocks stripe.js at module level.
// To test the getStripe()=null branch, we reload the module with a null-returning mock.
jest.resetModules();
jest.unstable_mockModule('../lib/stripe.js', () => ({ default: jest.fn(() => null) }));
jest.unstable_mockModule('../repositories/billing.subscription.repository.js', () => ({
default: mockSubscriptionRepository,
}));
jest.unstable_mockModule('../repositories/billing.processedStripeEvent.repository.js', () => ({
default: { wasProcessed: jest.fn().mockResolvedValue(false), tryRecord: jest.fn().mockResolvedValue({ recorded: true }) },
}));
jest.unstable_mockModule('../../organizations/repositories/organizations.repository.js', () => ({
default: mockOrganizationRepository,
}));
jest.unstable_mockModule('../services/billing.extra.service.js', () => ({
default: { creditPack: jest.fn(), refundPartial: jest.fn() },
}));
jest.unstable_mockModule('../services/billing.reset.service.js', () => ({
default: { resetWeek: jest.fn() },
}));
jest.unstable_mockModule('../lib/events.js', () => ({ default: { emit: jest.fn() } }));
jest.unstable_mockModule('../../../lib/services/logger.js', () => ({
default: { info: jest.fn(), error: jest.fn(), warn: jest.fn() },
}));
jest.unstable_mockModule('../../../config/index.js', () => ({
default: { billing: { plans: ['free', 'starter', 'pro', 'enterprise'] } },
}));
jest.unstable_mockModule('mongoose', () => ({
default: { Types: { ObjectId: { isValid: (id) => /^[a-f\d]{24}$/i.test(id) } }, model: () => ({}) },
}));
const mod2 = await import('../services/billing.webhook.service.js');
const svc2 = mod2.default;
await svc2.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
expect(mockSubscriptionRepository.updateIfEventNewer).not.toHaveBeenCalled();
expect(mockSubscriptionRepository.create).not.toHaveBeenCalled();
});
test('should skip org sync when checkout event is stale (updateIfEventNewer returns null)', async () => {
const existing = { _id: subId, organization: orgId };
mockSubscriptionRepository.findByOrganization.mockResolvedValue(existing);
mockSubscriptionRepository.updateIfEventNewer.mockResolvedValue(null);
await BillingWebhookService.handleCheckoutCompleted(
{
customer: 'cus_123',
subscription: 'sub_456',
metadata: { organizationId: orgId, plan: 'pro' },
},
checkoutEvent,
);
// Event was stale — org plan should not be synced
expect(mockOrganizationRepository.setPlan).not.toHaveBeenCalled();
});
});
});