-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.lifecycle.integration.tests.js
More file actions
240 lines (211 loc) · 8.38 KB
/
Copy pathbilling.lifecycle.integration.tests.js
File metadata and controls
240 lines (211 loc) · 8.38 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
/**
* Module dependencies.
*/
import mongoose from 'mongoose';
import { describe, beforeAll, beforeEach, afterAll, afterEach, test, expect, jest } from '@jest/globals';
import config from '../../../config/index.js';
import mongooseService from '../../../lib/services/mongoose.js';
import { isoWeekKey } from '../lib/billing.isoWeek.js';
/**
* Integration tests for meter lifecycle hardening.
*
* BillingPlan collection has been removed — plan definitions come from
* config.billing.planDefinitions. Tests that previously relied on
* BillingPlan.create() now seed planDefinitions directly on config.
*
* BillingMeterOutbox has been removed — extras debit is now inline in
* incrementMeter with non-fatal error handling.
*/
describe('Billing meter lifecycle integration tests:', () => {
let BillingUsage;
let Subscription;
let Organization;
let BillingExtraBalance;
let BillingWebhookService;
let BillingMeterService;
let BillingUsageService;
let billingEvents;
let originalMeterMode;
let originalPlanDefinitions;
beforeAll(async () => {
originalMeterMode = config.billing.meterMode;
originalPlanDefinitions = config.billing.planDefinitions;
config.billing.meterMode = true;
await mongooseService.loadModels();
await mongooseService.connect();
BillingUsage = mongoose.model('BillingUsage');
Subscription = mongoose.model('Subscription');
Organization = mongoose.model('Organization');
BillingExtraBalance = mongoose.model('BillingExtraBalance');
BillingWebhookService = (await import('../services/billing.webhook.service.js')).default;
BillingMeterService = (await import('../services/billing.meter.service.js')).default;
BillingUsageService = (await import('../services/billing.usage.service.js')).default;
billingEvents = (await import('../lib/events.js')).default;
});
beforeEach(async () => {
await Promise.all([
BillingUsage.deleteMany({}),
Subscription.deleteMany({}),
Organization.deleteMany({}),
BillingExtraBalance.deleteMany({}),
]);
config.billing.planDefinitions = originalPlanDefinitions;
});
afterEach(() => {
jest.restoreAllMocks();
billingEvents.removeAllListeners('billing.extras_debit.exhausted');
});
afterAll(async () => {
config.billing.meterMode = originalMeterMode;
config.billing.planDefinitions = originalPlanDefinitions;
await mongooseService.disconnect();
});
test('plan.changed webhook updates active week quota snapshot mid-week', async () => {
// Pick two distinct plan ids from the project's enum so the test runs on any downstream
// (upstream defaults expose no plans → fall back to legacy 'starter'/'pro').
const plans = Array.isArray(config.billing.plans) && config.billing.plans.length >= 2
? config.billing.plans
: ['starter', 'pro'];
const initialPlan = plans[0];
const upgradePlan = plans[plans.length - 1];
const initialVersion = `${initialPlan}-v1`;
const upgradeVersion = `${upgradePlan}-v2`;
config.billing.planDefinitions = [
{ planId: initialPlan, version: initialVersion, meterQuota: 100, ratios: { scrap: 1 } },
{ planId: upgradePlan, version: upgradeVersion, meterQuota: 1000, ratios: { scrap: 1 } },
];
const organizationId = new mongoose.Types.ObjectId();
const weekKey = isoWeekKey(new Date());
await Organization.create({ _id: organizationId, name: 'Lifecycle Org', slug: 'lifecycle-org', plan: initialPlan });
await Subscription.create({
organization: organizationId,
stripeCustomerId: 'cus_lifecycle',
stripeSubscriptionId: 'sub_lifecycle',
plan: initialPlan,
status: 'active',
});
await BillingUsage.create({
organizationId,
month: '2026-05',
weekKey,
counters: {},
meterUsed: 25,
meterQuota: 100,
planVersion: initialVersion,
meterBreakdown: { scrap: 25 },
consumedAttributionKeys: [],
});
await BillingWebhookService.handleSubscriptionUpdated(
{
id: 'sub_lifecycle',
status: 'active',
current_period_end: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,
current_period_start: Math.floor(Date.now() / 1000) - 24 * 60 * 60,
cancel_at_period_end: false,
items: { data: [{ price: { metadata: { planId: upgradePlan } } }] },
},
{
data: {
previous_attributes: {
items: { data: [{ price: { metadata: { planId: initialPlan } } }] },
},
},
},
);
const usage = await BillingUsage.findOne({ organizationId, weekKey }).lean();
expect(usage.meterQuota).toBe(1000);
expect(usage.planVersion).toBe(upgradeVersion);
expect(usage.meterUsed).toBe(25);
expect(usage.meterBreakdown).toEqual({ scrap: 25 });
});
test('attribute applies usage inline — no outbox collection created', async () => {
config.billing.planDefinitions = [
{ planId: 'pro', version: 'pro-v1', meterQuota: 100000, ratios: { scrap: 1 } },
];
config.billing.meter = { ...(config.billing.meter ?? {}), ratioVersion: 'pro-v1' };
const organizationId = new mongoose.Types.ObjectId();
await Subscription.create({
organization: organizationId,
plan: 'pro',
status: 'active',
});
const result = await BillingMeterService.attribute(
{
_id: new mongoose.Types.ObjectId(),
costs: { scrap: 0.01 },
planId: 'pro',
planVersion: 'pro-v1',
},
organizationId.toString(),
);
// Attribution succeeded inline — applied=true, meterUsed > 0
expect(result.applied).toBe(true);
expect(result.meterUsed).toBeGreaterThan(0);
// No extras consumed since within quota
expect(result.extrasConsumed).toBe(0);
// BillingUsage doc exists with the attributed units
const usage = await BillingUsage.findOne({ organizationId }).lean();
expect(usage).not.toBeNull();
expect(usage.meterUsed).toBe(result.meterUsed);
});
test('attribute with overflow debits extras inline — no outbox doc persisted', async () => {
config.billing.planDefinitions = [
{ planId: 'pro', version: 'pro-v1', meterQuota: 5, ratios: { scrap: 1 } },
];
config.billing.meter = { ...(config.billing.meter ?? {}), ratioVersion: 'pro-v1' };
const organizationId = new mongoose.Types.ObjectId();
await Subscription.create({
organization: organizationId,
plan: 'pro',
status: 'active',
});
await BillingExtraBalance.create({
organization: organizationId,
ledger: [{ kind: 'topup', amount: 100, stripeSessionId: 'cs_lifecycle_overflow' }],
cachedBalance: 100,
});
const result = await BillingMeterService.attribute(
{
_id: new mongoose.Types.ObjectId(),
costs: { scrap: 0.01 },
planId: 'pro',
planVersion: 'pro-v1',
},
organizationId.toString(),
);
// Applied = true, and extras consumed inline (meterUsed > quota)
expect(result.applied).toBe(true);
expect(result.extrasConsumed).toBeGreaterThan(0);
// Balance was debited inline — lower than initial 100
const balance = await BillingExtraBalance.findOne({ organization: organizationId }).lean();
expect(balance.cachedBalance).toBeLessThan(100);
// No outbox collection exists (model not registered)
const collections = await mongoose.connection.db.listCollections({ name: 'billingmeteroutboxes' }).toArray();
expect(collections).toHaveLength(0);
});
test('incrementMeter creates BillingUsage doc with correct meter snapshot', async () => {
config.billing.planDefinitions = [
{ planId: 'free', version: 'free-v1', meterQuota: 500, ratios: { scrap: 1 } },
];
const organizationId = new mongoose.Types.ObjectId();
await Subscription.create({
organization: organizationId,
plan: 'free',
status: 'active',
});
const result = await BillingUsageService.incrementMeter(
organizationId.toString(),
10,
{ scrap: 10 },
`${organizationId.toString()}:initial`,
);
expect(result.applied).toBe(true);
expect(result.meterUsed).toBe(10);
expect(result.extrasConsumed).toBe(0);
const usage = await BillingUsage.findOne({ organizationId }).lean();
expect(usage.meterUsed).toBe(10);
expect(usage.meterQuota).toBe(500);
expect(usage.planVersion).toBe('free-v1');
expect(usage.consumedAttributionKeys).toContain(`${organizationId.toString()}:initial`);
});
});