1 import { IPromotionModuleService } from "@medusajs/framework/types"
2 import { CampaignBudgetType, Modules } from "@medusajs/framework/utils"
3 import { moduleIntegrationTestRunner, SuiteOptions } from "@medusajs/test-utils"
4 import { createCampaigns } from "../../../__fixtures__/campaigns"
5 import { createDefaultPromotion } from "../../../__fixtures__/promotion"
6
7 jest.setTimeout(30000)
8
9 moduleIntegrationTestRunner({
10 moduleName: Modules.PROMOTION,
11 testSuite: ({
12 MikroOrmWrapper,
13 service,
14 }: SuiteOptions<IPromotionModuleService>) => {
15 describe("Promotion Service: campaign usage", () => {
16 beforeEach(async () => {
17 await createCampaigns(MikroOrmWrapper.forkManager())
18 })
19
20 describe("registerUsage", () => {
21 it("should register usage for type spend", async () => {
22 const createdPromotion = await createDefaultPromotion(service, {})
23
24 await service.registerUsage(
25 [
26 {
27 amount: 200,
28 code: createdPromotion.code!,
29 },
30 {
31 amount: 500,
32 code: createdPromotion.code!,
33 },
34 ],
35 { customer_email: null, customer_id: null }
36 )
37
38 const campaign = await service.retrieveCampaign("campaign-id-1", {
39 relations: ["budget"],
40 })
41
42 expect(campaign.budget).toEqual(
43 expect.objectContaining({
44 type: "spend",
45 limit: 1000,
46 used: 700,
47 })
48 )
49 })
50
51 it("should not allow concurrent registrations to exceed a spend budget", async () => {
52 const createdPromotion = await createDefaultPromotion(service, {})
53
54 await service.updateCampaigns({
55 id: "campaign-id-1",
56 budget: { used: 900, limit: 1000 },
57 })
58
59 // Two concurrent +100 registrations: each sees used=900 and passes the
60 // 1000 limit in isolation, but together they would spend 1100.
61 const outcomes = await Promise.all([
62 service
63 .registerUsage(
64 [{ amount: 100, code: createdPromotion.code! }],
65 { customer_email: null, customer_id: null }
66 )
67 .then(() => "ok", () => "threw"),
68 service
69 .registerUsage(
70 [{ amount: 100, code: createdPromotion.code! }],
71 { customer_email: null, customer_id: null }
72 )
73 .then(() => "ok", () => "threw"),
74 ])
75
76 // Budget had room for a single +100; the other registration must be rejected.
77 expect(outcomes.filter((o) => o === "threw")).toHaveLength(1)
78
79 const campaign = await service.retrieveCampaign("campaign-id-1", {
80 relations: ["budget"],
81 })
82 expect(campaign.budget!.used).toBeLessThanOrEqual(1000)
83 })
84
85 it("should not allow concurrent per-attribute registrations to exceed the limit", async () => {
86 const [createdCampaign] = await service.createCampaigns([
87 {
88 name: "attr-concurrency",
89 campaign_identifier: "attr-concurrency",
90 budget: {
91 type: CampaignBudgetType.USE_BY_ATTRIBUTE,
92 attribute: "customer_id",
93 limit: 2,
94 },
95 },
96 ])
97
98 const createdPromotion = await createDefaultPromotion(service, {
99 campaign_id: createdCampaign.id,
100 })
101
102 // Prime the per-customer usage row (used=1) so the concurrent calls take
103 // the UPDATE branch; the INSERT branch is already serialized by a unique
104 // index on (attribute_value, budget_id).
105 await service.registerUsage(
106 [{ amount: 1, code: createdPromotion.code! }],
107 { customer_id: "customer-id-1", customer_email: "c1@email.com" }
108 )
109
110 // Two concurrent uses for the same customer: each reads used=1 and passes
111 // the limit of 2 in isolation, but together they would reach 3.
112 const outcomes = await Promise.all([
113 service
114 .registerUsage(
115 [{ amount: 1, code: createdPromotion.code! }],
116 { customer_id: "customer-id-1", customer_email: "c1@email.com" }
117 )
118 .then(() => "ok", () => "threw"),
119 service
120 .registerUsage(
121 [{ amount: 1, code: createdPromotion.code! }],
122 { customer_id: "customer-id-1", customer_email: "c1@email.com" }
123 )
124 .then(() => "ok", () => "threw"),
125 ])
126
127 expect(outcomes.filter((o) => o === "threw")).toHaveLength(1)
128
129 const campaign = await service.retrieveCampaign(createdCampaign.id, {
130 relations: ["budget", "budget.usages"],
131 })
132 const usage = campaign.budget!.usages!.find(
133 (u) => u.attribute_value === "customer-id-1"
134 )
135 expect(usage!.used).toBeLessThanOrEqual(2)
136 })
137
138 it("should not deadlock when concurrent registrations lock overlapping promotions in different orders", async () => {
139 // Two promotions with a numeric usage limit (so both `promotion` rows
140 // are locked) applied by two concurrent registrations in opposite
141 // order. Locking the rows in a stable id order (orderBy("id")) is what
142 // keeps this deadlock-free: without it each transaction could hold one
143 // row and wait on the other. Limits are ample so neither guard rejects,
144 // so the only way a call fails here is a deadlock.
145 const promotionA = await createDefaultPromotion(service, {
146 code: "PROMO_A",
147 limit: 100,
148 campaign_id: "campaign-id-1",
149 })
150 const promotionB = await createDefaultPromotion(service, {
151 code: "PROMO_B",
152 limit: 100,
153 campaign_id: "campaign-id-1",
154 })
155
156 const outcomes = await Promise.all([
157 service
158 .registerUsage(
159 [
160 { amount: 1, code: promotionA.code! },
161 { amount: 1, code: promotionB.code! },
162 ],
163 { customer_email: null, customer_id: null }
164 )
165 .then(() => "ok", (e) => e.message),
166 service
167 .registerUsage(
168 [
169 { amount: 1, code: promotionB.code! },
170 { amount: 1, code: promotionA.code! },
171 ],
172 { customer_email: null, customer_id: null }
173 )
174 .then(() => "ok", (e) => e.message),
175 ])
176
177 expect(outcomes).toEqual(["ok", "ok"])
178 })
179
180 it("should register usage for type usage", async () => {
181 const createdPromotion = await createDefaultPromotion(service, {
182 campaign_id: "campaign-id-2",
183 })
184
185 await service.registerUsage(
186 [
187 {
188 amount: 200,
189 code: createdPromotion.code!,
190 },
191 {
192 amount: 500,
193 code: createdPromotion.code!,
194 },
195 ],
196 { customer_email: null, customer_id: null }
197 )
198
199 const campaign = await service.retrieveCampaign("campaign-id-2", {
200 relations: ["budget"],
201 })
202
203 expect(campaign.budget).toEqual(
204 expect.objectContaining({
205 type: "usage",
206 limit: 1000,
207 used: 1,
208 })
209 )
210 })
211
212 it("should not throw an error when compute action with code does not exist", async () => {
213 const response = await service
214 .registerUsage(
215 [
216 {
217 amount: 200,
218 code: "DOESNOTEXIST",
219 },
220 ],
221 { customer_email: null, customer_id: null }
222 )
223 .catch((e) => e)
224
225 expect(response).toEqual(undefined)
226 })
227
228 it("should throw if limit is exceeded for type usage", async () => {
229 const createdPromotion = await createDefaultPromotion(service, {
230 campaign_id: "campaign-id-2",
231 })
232
233 await service.updateCampaigns({
234 id: "campaign-id-2",
235 budget: { used: 1000, limit: 1000 },
236 })
237
238 const error = await service
239 .registerUsage(
240 [
241 {
242 amount: 200,
243 code: createdPromotion.code!,
244 },
245 {
246 amount: 500,
247 code: createdPromotion.code!,
248 },
249 ],
250 { customer_email: null, customer_id: null }
251 )
252 .catch((e) => e)
253
254 expect(error).toEqual(
255 expect.objectContaining({
256 type: "not_allowed",
257 message: "Promotion usage exceeds the budget limit.",
258 })
259 )
260
261 const [campaign] = await service.listCampaigns(
262 {
263 id: ["campaign-id-2"],
264 },
265 {
266 relations: ["budget"],
267 }
268 )
269
270 expect(campaign).toEqual(
271 expect.objectContaining({
272 budget: expect.objectContaining({
273 limit: 1000,
274 used: 1000,
275 }),
276 })
277 )
278 })
279
280 it("should throw if limit is exceeded for type spend", async () => {
281 const createdPromotion = await createDefaultPromotion(service, {})
282
283 await service.updateCampaigns({
284 id: "campaign-id-1",
285 budget: { used: 900, limit: 1000 },
286 })
287
288 const error = await service
289 .registerUsage(
290 [
291 {
292 amount: 50,
293 code: createdPromotion.code!,
294 },
295 {
296 amount: 100,
297 code: createdPromotion.code!,
298 },
299 ],
300 { customer_email: null, customer_id: null }
301 )
302 .catch((e) => e)
303
304 expect(error).toEqual(
305 expect.objectContaining({
306 type: "not_allowed",
307 message: "Promotion usage exceeds the budget limit.",
308 })
309 )
310
311 const campaign = await service.retrieveCampaign("campaign-id-1", {
312 relations: ["budget"],
313 })
314
315 expect(campaign).toEqual(
316 expect.objectContaining({
317 budget: expect.objectContaining({
318 used: 900,
319 limit: 1000,
320 }),
321 })
322 )
323 })
324
325 it("should throw if limit is exceeded for type spend (one amount exceeds the limit)", async () => {
326 const createdPromotion = await createDefaultPromotion(service, {})
327
328 await service.updateCampaigns({
329 id: "campaign-id-1",
330 budget: { used: 900, limit: 1000 },
331 })
332
333 const error = await service
334 .registerUsage(
335 [
336 {
337 amount: 75,
338 code: createdPromotion.code!,
339 },
340 {
341 amount: 75,
342 code: createdPromotion.code!,
343 },
344 ],
345 { customer_email: null, customer_id: null }
346 )
347 .catch((e) => e)
348
349 expect(error).toEqual(
350 expect.objectContaining({
351 type: "not_allowed",
352 message: "Promotion usage exceeds the budget limit.",
353 })
354 )
355
356 const [campaign] = await service.listCampaigns(
357 {
358 id: ["campaign-id-1"],
359 },
360 {
361 relations: ["budget"],
362 }
363 )
364
365 expect(campaign).toEqual(
366 expect.objectContaining({
367 budget: expect.objectContaining({
368 limit: 1000,
369 used: 900,
370 }),
371 })
372 )
373 })
374
375 it("should not throw if the spent amount exactly matches the limit", async () => {
376 const createdPromotion = await createDefaultPromotion(service, {})
377
378 await service.updateCampaigns({
379 id: "campaign-id-1",
380 budget: { used: 900, limit: 1000 },
381 })
382
383 await service.registerUsage(
384 [
385 {
386 amount: 50,
387 code: createdPromotion.code!,
388 },
389 {
390 amount: 50,
391 code: createdPromotion.code!,
392 },
393 ],
394 { customer_email: null, customer_id: null }
395 )
396
397 const campaign = await service.retrieveCampaign("campaign-id-1", {
398 relations: ["budget"],
399 })
400
401 expect(campaign).toEqual(
402 expect.objectContaining({
403 budget: expect.objectContaining({
404 limit: 1000,
405 used: 1000,
406 }),
407 })
408 )
409 })
410
411 it("should requister usage for attribute budget successfully and revert it successfully", async () => {
412 const [createdCampaign] = await service.createCampaigns([
413 {
414 name: "test",
415 campaign_identifier: "test",
416 budget: {
417 type: CampaignBudgetType.USE_BY_ATTRIBUTE,
418 attribute: "customer_id",
419 limit: 5,
420 },
421 },
422 ])
423
424 const createdPromotion = await createDefaultPromotion(service, {
425 campaign_id: createdCampaign.id,
426 })
427
428 await service.registerUsage(
429 [{ amount: 1, code: createdPromotion.code! }],
430 {
431 customer_id: "customer-id-1",
432 customer_email: "customer1@email.com",
433 }
434 )
435
436 await service.registerUsage(
437 [{ amount: 1, code: createdPromotion.code! }],
438 {
439 customer_id: "customer-id-2",
440 customer_email: "customer2@email.com",
441 }
442 )
443
444 await service.registerUsage(
445 [{ amount: 1, code: createdPromotion.code! }],
446 {
447 customer_id: "customer-id-1",
448 customer_email: "customer1@email.com",
449 }
450 )
451
452 let campaign = await service.retrieveCampaign(createdCampaign.id, {
453 relations: ["budget", "budget.usages"],
454 })
455
456 expect(campaign).toEqual(
457 expect.objectContaining({
458 budget: expect.objectContaining({
459 used: 3, // used 3 times overall
460 usages: expect.arrayContaining([
461 expect.objectContaining({
462 attribute_value: "customer-id-1",
463 used: 2,
464 }),
465 expect.objectContaining({
466 attribute_value: "customer-id-2",
467 used: 1,
468 }),
469 ]),
470 }),
471 })
472 )
473
474 await service.revertUsage(
475 [{ amount: 1, code: createdPromotion.code! }],
476 {
477 customer_id: "customer-id-1",
478 customer_email: "customer1@email.com",
479 }
480 )
481
482 campaign = await service.retrieveCampaign(createdCampaign.id, {
483 relations: ["budget", "budget.usages"],
484 })
485
486 expect(campaign).toEqual(
487 expect.objectContaining({
488 budget: expect.objectContaining({
489 used: 2,
490 usages: expect.arrayContaining([
491 expect.objectContaining({
492 attribute_value: "customer-id-1",
493 used: 1,
494 }),
495 expect.objectContaining({
496 attribute_value: "customer-id-2",
497 used: 1,
498 }),
499 ]),
500 }),
501 })
502 )
503
504 await service.revertUsage(
505 [{ amount: 1, code: createdPromotion.code! }],
506 {
507 customer_id: "customer-id-2",
508 customer_email: "customer2@email.com",
509 }
510 )
511
512 campaign = await service.retrieveCampaign(createdCampaign.id, {
513 relations: ["budget", "budget.usages"],
514 })
515
516 expect(campaign.budget!.usages!).toHaveLength(1)
517
518 expect(campaign).toEqual(
519 expect.objectContaining({
520 budget: expect.objectContaining({
521 used: 1,
522 usages: expect.arrayContaining([
523 expect.objectContaining({
524 attribute_value: "customer-id-1",
525 used: 1,
526 }),
527 ]),
528 }),
529 })
530 )
531 })
532 })
533 })
534 },
535 })