-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathusage-alert-org.test.ts
More file actions
457 lines (405 loc) · 15.9 KB
/
Copy pathusage-alert-org.test.ts
File metadata and controls
457 lines (405 loc) · 15.9 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
/**
* TDD test for org-level usage alerts.
*
* Contract under test:
* New types/fields:
* - OrgConfig.usage_alerts: DbUsageAlert[] (org-scope alerts in organizations.config)
* New behaviors:
* - checkUsageAlerts evaluates ctx.org.config.usage_alerts in addition to
* customer-level and entity-level alerts.
* - Org alerts fire INDEPENDENTLY of customer alerts (idempotency key
* takes a scope segment so Svix does not dedup them).
* - Org alerts evaluate against the tracked subject balance, including
* the entity balance when the track call is entity-scoped.
* - Disabled org alerts (enabled: false) do not fire.
* - Org alert with no feature_id fires on usage of any feature (global).
* Side effects:
* - Svix `balances.usage_alert_triggered` event per customer per
* (scope, feature, threshold, threshold_type) per minute-bucket.
*
* Pre-impl red:
* - OrgConfig.usage_alerts type doesn't exist → TS error on the org config
* update payload.
* - checkUsageAlerts does not read ctx.org.config.usage_alerts → no webhook
* fires → waitForWebhook returns null → assertions fail.
*
* Post-impl green: all assertions pass once OrgConfigSchema includes
* usage_alerts and checkUsageAlerts iterates ctx.org.config.usage_alerts as a
* third scope.
*/
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
import type { DbUsageAlert } from "@autumn/shared";
import {
getPlayHistory,
getTestSvixAppId,
parseEventBody,
setupWebhookTest,
type WebhookTestSetup,
waitForWebhook,
} from "@tests/integration/utils/svixWebhookTestUtils.js";
import { TestFeature } from "@tests/setup/v2Features.js";
import { items } from "@tests/utils/fixtures/items.js";
import { products } from "@tests/utils/fixtures/products.js";
import { timeout } from "@tests/utils/genUtils.js";
import defaultCtx from "@tests/utils/testInitUtils/createTestContext.js";
import { initScenario, s } from "@tests/utils/testInitUtils/initScenario.js";
import chalk from "chalk";
import { db } from "@/db/initDrizzle.js";
import { OrgService } from "@/internal/orgs/OrgService.js";
import { setCustomerUsageAlerts } from "../../utils/usage-alert-utils/customerUsageAlertUtils.js";
type BalancesUsageAlertTriggeredPayload = {
type: string;
data: {
customer_id: string;
feature_id: string;
entity_id?: string;
usage_alert: {
name?: string;
threshold: number;
threshold_type: string;
};
};
};
// ═══════════════════════════════════════════════════════════════════════════════
// SVIX PLAY SETUP
// ═══════════════════════════════════════════════════════════════════════════════
let webhook: WebhookTestSetup;
let playToken: string;
beforeAll(async () => {
const appId = getTestSvixAppId({ svixConfig: defaultCtx.org.svix_config });
webhook = await setupWebhookTest({
appId,
filterTypes: ["balances.usage_alert_triggered"],
});
playToken = webhook.playToken;
});
afterAll(async () => {
await webhook?.cleanup();
// Final reset to ensure config doesn't leak to other suites.
await setOrgUsageAlerts([]);
});
// Each test sets the org-level alerts then clears them in afterEach so tests
// can run sequentially without bleeding across each other.
afterEach(async () => {
await setOrgUsageAlerts([]);
});
async function setOrgUsageAlerts(usageAlerts: DbUsageAlert[]) {
// Tests run in AppEnv.Sandbox — checkUsageAlerts reads
// sandbox_usage_alerts, not the live `usage_alerts` field.
await OrgService.update({
db,
orgId: defaultCtx.org.id,
updates: {
config: {
...defaultCtx.org.config,
sandbox_usage_alerts: usageAlerts,
},
},
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// TEST 1: Org-level alert fires when customer crosses threshold
// ═══════════════════════════════════════════════════════════════════════════════
test(`${chalk.yellowBright("org-alert1: org-level alert fires when customer crosses threshold")}`, async () => {
const messagesItem = items.monthlyMessages({ includedUsage: 1000 });
const prod = products.base({
id: "org-ua-threshold-1",
items: [messagesItem],
});
await setOrgUsageAlerts([
{
feature_id: TestFeature.Messages,
threshold: 750,
threshold_type: "usage",
basis: "balance",
enabled: true,
name: "org-threshold-750",
},
]);
const { customerId, autumnV2_1 } = await initScenario({
customerId: "org-usage-alert-threshold-1",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
await autumnV2_1.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
value: 850,
});
const result = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerId &&
payload.data?.usage_alert?.threshold === 750 &&
payload.data?.usage_alert?.name === "org-threshold-750",
timeoutMs: 15000,
});
expect(result).not.toBeNull();
const { data } = result!.payload;
expect(data.customer_id).toBe(customerId);
expect(data.feature_id).toBe(TestFeature.Messages);
expect(data.usage_alert.threshold).toBe(750);
expect(data.usage_alert.threshold_type).toBe("usage");
expect(data.usage_alert.name).toBe("org-threshold-750");
});
// Red: org/global alerts used the customer balance and missed entity usage.
// Green: a 100% org alert fires when an entity-scoped balance lands exactly at 100%.
test(`${chalk.yellowBright("org-alert1b: org usage_percentage alert fires for entity balance at 100%")}`, async () => {
const perEntityMessages = items.monthlyMessages({
includedUsage: 100,
entityFeatureId: TestFeature.Users,
});
const prod = products.base({
id: "org-ua-entity-100pct",
items: [perEntityMessages],
});
await setOrgUsageAlerts([
{
feature_id: TestFeature.Messages,
threshold: 100,
threshold_type: "usage_percentage",
basis: "balance",
enabled: true,
name: "org-entity-100pct",
},
]);
const { customerId, autumnV2_1, entities } = await initScenario({
customerId: "org-usage-alert-entity-100pct",
setup: [
s.customer({ testClock: false }),
s.products({ list: [prod] }),
s.entities({ count: 1, featureId: TestFeature.Users }),
],
actions: [s.attach({ productId: prod.id })],
});
await autumnV2_1.track({
customer_id: customerId,
entity_id: entities[0].id,
feature_id: TestFeature.Messages,
value: 100,
});
const result = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerId &&
payload.data?.entity_id === entities[0].id &&
payload.data?.usage_alert?.name === "org-entity-100pct",
timeoutMs: 15000,
});
expect(result).not.toBeNull();
expect(result!.payload.data.usage_alert.threshold).toBe(100);
expect(result!.payload.data.usage_alert.threshold_type).toBe(
"usage_percentage",
);
});
// ═══════════════════════════════════════════════════════════════════════════════
// TEST 2: Org alert applies to ALL customers (not customer-specific)
// ═══════════════════════════════════════════════════════════════════════════════
test(`${chalk.yellowBright("org-alert2: org-level alert fires for multiple customers independently")}`, async () => {
const messagesItem = items.monthlyMessages({ includedUsage: 1000 });
const prod = products.base({
id: "org-ua-multi-customer-1",
items: [messagesItem],
});
await setOrgUsageAlerts([
{
feature_id: TestFeature.Messages,
threshold: 600,
threshold_type: "usage",
basis: "balance",
enabled: true,
name: "org-multi-cust",
},
]);
const { customerId: customerIdA, autumnV2_1: autumnA } = await initScenario({
customerId: "org-usage-alert-multi-a",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
const { customerId: customerIdB, autumnV2_1: autumnB } = await initScenario({
customerId: "org-usage-alert-multi-b",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
await autumnA.track({
customer_id: customerIdA,
feature_id: TestFeature.Messages,
value: 700,
});
await autumnB.track({
customer_id: customerIdB,
feature_id: TestFeature.Messages,
value: 700,
});
const resultA = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerIdA &&
payload.data?.usage_alert?.threshold === 600 &&
payload.data?.usage_alert?.name === "org-multi-cust",
timeoutMs: 15000,
});
const resultB = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerIdB &&
payload.data?.usage_alert?.threshold === 600 &&
payload.data?.usage_alert?.name === "org-multi-cust",
timeoutMs: 15000,
});
expect(resultA).not.toBeNull();
expect(resultB).not.toBeNull();
expect(resultA!.payload.data.customer_id).toBe(customerIdA);
expect(resultB!.payload.data.customer_id).toBe(customerIdB);
});
// ═══════════════════════════════════════════════════════════════════════════════
// TEST 3: Org alert + customer alert at same threshold both fire independently
// ═══════════════════════════════════════════════════════════════════════════════
test(`${chalk.yellowBright("org-alert3: org and customer alerts at same threshold both fire")}`, async () => {
const messagesItem = items.monthlyMessages({ includedUsage: 1000 });
const prod = products.base({
id: "org-ua-coexist-1",
items: [messagesItem],
});
await setOrgUsageAlerts([
{
feature_id: TestFeature.Messages,
threshold: 400,
threshold_type: "usage",
basis: "balance",
enabled: true,
name: "org-coexist",
},
]);
const { customerId, autumnV2_1 } = await initScenario({
customerId: "org-usage-alert-coexist-1",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
await setCustomerUsageAlerts({
autumn: autumnV2_1,
customerId,
usageAlerts: [
{
feature_id: TestFeature.Messages,
threshold: 400,
threshold_type: "usage",
basis: "balance",
enabled: true,
name: "customer-coexist",
},
],
});
await autumnV2_1.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
value: 500,
});
await timeout(5000);
const history = await getPlayHistory({ token: playToken });
let orgMatch = 0;
let customerMatch = 0;
for (const event of history.data) {
try {
const payload = parseEventBody<BalancesUsageAlertTriggeredPayload>(event);
if (
payload.type !== "balances.usage_alert_triggered" ||
payload.data?.customer_id !== customerId ||
payload.data?.usage_alert?.threshold !== 400
)
continue;
if (payload.data.usage_alert.name === "org-coexist") orgMatch++;
if (payload.data.usage_alert.name === "customer-coexist") customerMatch++;
} catch {
// skip unparseable
}
}
expect(orgMatch).toBe(1);
expect(customerMatch).toBe(1);
});
// ═══════════════════════════════════════════════════════════════════════════════
// TEST 4: Org alert with no feature_id (global) fires on any feature
// ═══════════════════════════════════════════════════════════════════════════════
test(`${chalk.yellowBright("org-alert4: org-level global alert (no feature_id) fires on any feature")}`, async () => {
const messagesItem = items.monthlyMessages({ includedUsage: 1000 });
const prod = products.base({
id: "org-ua-global-1",
items: [messagesItem],
});
await setOrgUsageAlerts([
{
threshold: 80,
threshold_type: "usage_percentage",
basis: "balance",
enabled: true,
name: "org-global",
},
]);
const { customerId, autumnV2_1 } = await initScenario({
customerId: "org-usage-alert-global-1",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
await autumnV2_1.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
value: 900,
});
const result = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerId &&
payload.data?.usage_alert?.name === "org-global",
timeoutMs: 15000,
});
expect(result).not.toBeNull();
expect(result!.payload.data.feature_id).toBe(TestFeature.Messages);
expect(result!.payload.data.usage_alert.threshold).toBe(80);
expect(result!.payload.data.usage_alert.threshold_type).toBe(
"usage_percentage",
);
});
// ═══════════════════════════════════════════════════════════════════════════════
// TEST 5: Disabled org-level alert does not fire
// ═══════════════════════════════════════════════════════════════════════════════
test(`${chalk.yellowBright("org-alert5: disabled org-level alert does not fire")}`, async () => {
const messagesItem = items.monthlyMessages({ includedUsage: 1000 });
const prod = products.base({
id: "org-ua-disabled-1",
items: [messagesItem],
});
await setOrgUsageAlerts([
{
feature_id: TestFeature.Messages,
threshold: 300,
threshold_type: "usage",
basis: "balance",
enabled: false,
name: "org-disabled",
},
]);
const { customerId, autumnV2_1 } = await initScenario({
customerId: "org-usage-alert-disabled-1",
setup: [s.customer({ testClock: false }), s.products({ list: [prod] })],
actions: [s.attach({ productId: prod.id })],
});
await autumnV2_1.track({
customer_id: customerId,
feature_id: TestFeature.Messages,
value: 500,
});
const result = await waitForWebhook<BalancesUsageAlertTriggeredPayload>({
token: playToken,
predicate: (payload) =>
payload.type === "balances.usage_alert_triggered" &&
payload.data?.customer_id === customerId &&
payload.data?.usage_alert?.name === "org-disabled",
timeoutMs: 8000,
});
expect(result).toBeNull();
});