1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { ICartModuleService, IPromotionModuleService } from "@medusajs/types"
3 import {
4 Modules,
5 PromotionStatus,
6 PromotionType,
7 } from "@medusajs/utils"
8 import {
9 adminHeaders,
10 createAdminUser,
11 generatePublishableKey,
12 generateStoreHeaders,
13 } from "../../../../helpers/create-admin-user"
14
15 jest.setTimeout(50000)
16
17 const env = {}
18
19 medusaIntegrationTestRunner({
20 env,
21 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
22 describe("Store Carts API: Concurrent promotion requests", () => {
23 let appContainer
24 let cartModuleService: ICartModuleService
25 let promotionModuleService: IPromotionModuleService
26 let storeHeaders
27
28 beforeAll(async () => {
29 appContainer = getContainer()
30 cartModuleService = appContainer.resolve(Modules.CART)
31 promotionModuleService = appContainer.resolve(Modules.PROMOTION)
32 })
33
34 beforeAll(async () => {
35 await createAdminUser(dbConnection, adminHeaders, appContainer)
36 const publishableKey = await generatePublishableKey(appContainer)
37 storeHeaders = generateStoreHeaders({ publishableKey })
38
39 await dbUtils.snapshot()
40 })
41
42 describe("POST /store/carts/:id/promotions", () => {
43 it("should not create duplicate adjustments when the same promo code is sent concurrently", async () => {
44 const promotion = await promotionModuleService.createPromotions({
45 code: "CONCURRENT_TEST",
46 type: PromotionType.STANDARD,
47 status: PromotionStatus.ACTIVE,
48 application_method: {
49 type: "fixed",
50 target_type: "items",
51 allocation: "each",
52 value: 500,
53 apply_to_quantity: 1,
54 currency_code: "usd",
55 max_quantity: 1,
56 },
57 })
58
59 const cart = await cartModuleService.createCarts({
60 currency_code: "usd",
61 items: [
62 {
63 id: "item-concurrent",
64 unit_price: 2000,
65 quantity: 1,
66 title: "Test item",
67 product_id: "prod_test",
68 } as any,
69 ],
70 })
71
72 const results = await Promise.all(
73 Array.from({ length: 3 }, () =>
74 api
75 .post(
76 `/store/carts/${cart.id}/promotions`,
77 { promo_codes: [promotion.code] },
78 storeHeaders
79 )
80 .catch((e) => e)
81 )
82 )
83
84 const successes = results.filter((r) => r.status === 200)
85 expect(successes.length).toBeGreaterThanOrEqual(1)
86
87 const finalCart = (
88 await api.get(
89 `/store/carts/${cart.id}?fields=*items,*items.adjustments`,
90 storeHeaders
91 )
92 ).data.cart
93
94 const item = finalCart.items.find(
95 (i: any) => i.id === "item-concurrent"
96 )
97
98 const promoAdjustments = item.adjustments.filter(
99 (a: any) => a.code === promotion.code
100 )
101
102 expect(promoAdjustments).toHaveLength(1)
103 expect(promoAdjustments[0].amount).toBe(500)
104 })
105 })
106 })
107 },
108 })