1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { HttpTypes } from "@medusajs/types"
3 import { ModuleRegistrationName, ProductStatus } from "@medusajs/utils"
4 import { fetchShippingOptionForDraftOrderWorkflow } from "@medusajs/core-flows"
5 import {
6 adminHeaders,
7 createAdminUser,
8 } from "../../../../helpers/create-admin-user"
9 import { setupTaxStructure } from "../../../../modules/__tests__/fixtures"
10
11 jest.setTimeout(300000)
12
13 // The calculated fulfillment provider registered in integration-tests/http/medusa-config.js.
14 // Its identifier is "manual-calculated" and it is registered with id "test-provider-calculated",
15 // so the resolved provider id is "<identifier>_<id>". Its `calculatePrice` returns
16 // `sum(item quantities) * 1.5`.
17 const CALCULATED_PROVIDER_ID = "manual-calculated_test-provider-calculated"
18 const FLAT_PROVIDER_ID = "manual_test-provider"
19 const PRICE_PER_ITEM = 1.5
20
21 medusaIntegrationTestRunner({
22 testSuite: ({ dbConnection, getContainer, api }) => {
23 let region: HttpTypes.AdminRegion
24 let salesChannel: HttpTypes.AdminSalesChannel
25 let stockLocation: HttpTypes.AdminStockLocation
26 let testDraftOrder: HttpTypes.AdminDraftOrder
27 let calculatedShippingOption: HttpTypes.AdminShippingOption
28 let flatShippingOption: HttpTypes.AdminShippingOption
29 let product: HttpTypes.AdminProduct
30 let shippingProfile: HttpTypes.AdminShippingProfile
31 let fulfillmentSet: any
32
33 // Lets a single test observe the setPricingContext hook without leaking to
34 // others; the registered hook is a no-op while this is undefined.
35 let setPricingContextSpy: ((input: any) => any) | undefined
36
37 fetchShippingOptionForDraftOrderWorkflow.hooks.setPricingContext(
38 (input) => {
39 if (setPricingContextSpy) {
40 return setPricingContextSpy(input)
41 }
42 }
43 )
44
45 afterEach(() => {
46 setPricingContextSpy = undefined
47 })
48
49 beforeEach(async () => {
50 const container = getContainer()
51
52 await setupTaxStructure(container.resolve(ModuleRegistrationName.TAX))
53 await createAdminUser(dbConnection, adminHeaders, container)
54
55 region = (
56 await api.post(
57 `/admin/regions`,
58 { name: "USA", currency_code: "usd", countries: ["US"] },
59 adminHeaders
60 )
61 ).data.region
62
63 salesChannel = (
64 await api.post("/admin/sales-channels", { name: "test" }, adminHeaders)
65 ).data.sales_channel
66
67 stockLocation = (
68 await api.post(
69 `/admin/stock-locations`,
70 { name: "test location" },
71 adminHeaders
72 )
73 ).data.stock_location
74
75 shippingProfile = (
76 await api.post(
77 `/admin/shipping-profiles`,
78 { name: "test shipping profile", type: "default" },
79 adminHeaders
80 )
81 ).data.shipping_profile
82
83 const fulfillmentSets = (
84 await api.post(
85 `/admin/stock-locations/${stockLocation.id}/fulfillment-sets?fields=*fulfillment_sets`,
86 { name: `Test-${shippingProfile.id}`, type: "test-type" },
87 adminHeaders
88 )
89 ).data.stock_location.fulfillment_sets
90
91 fulfillmentSet = (
92 await api.post(
93 `/admin/fulfillment-sets/${fulfillmentSets[0].id}/service-zones`,
94 {
95 name: `Test-${shippingProfile.id}`,
96 geo_zones: [{ type: "country", country_code: "us" }],
97 },
98 adminHeaders
99 )
100 ).data.fulfillment_set
101
102 await api.post(
103 `/admin/stock-locations/${stockLocation.id}/fulfillment-providers`,
104 { add: [FLAT_PROVIDER_ID, CALCULATED_PROVIDER_ID] },
105 adminHeaders
106 )
107
108 await api.post(
109 `/admin/stock-locations/${stockLocation.id}/sales-channels`,
110 { add: [salesChannel.id] },
111 adminHeaders
112 )
113
114 flatShippingOption = (
115 await api.post(
116 `/admin/shipping-options`,
117 {
118 name: "Flat shipping option",
119 service_zone_id: fulfillmentSet.service_zones[0].id,
120 shipping_profile_id: shippingProfile.id,
121 provider_id: FLAT_PROVIDER_ID,
122 price_type: "flat",
123 type: {
124 label: "Test type",
125 description: "Test description",
126 code: "test-code",
127 },
128 prices: [{ currency_code: "usd", amount: 5 }],
129 rules: [],
130 },
131 adminHeaders
132 )
133 ).data.shipping_option
134
135 calculatedShippingOption = (
136 await api.post(
137 `/admin/shipping-options`,
138 {
139 name: "Calculated shipping option",
140 service_zone_id: fulfillmentSet.service_zones[0].id,
141 shipping_profile_id: shippingProfile.id,
142 provider_id: CALCULATED_PROVIDER_ID,
143 price_type: "calculated",
144 type: {
145 label: "Test type",
146 description: "Test description",
147 code: "test-code",
148 },
149 prices: [],
150 rules: [],
151 },
152 adminHeaders
153 )
154 ).data.shipping_option
155
156 const inventoryItem = (
157 await api.post(`/admin/inventory-items`, { sku: "shirt" }, adminHeaders)
158 ).data.inventory_item
159
160 await api.post(
161 `/admin/inventory-items/${inventoryItem.id}/location-levels`,
162 { location_id: stockLocation.id, stocked_quantity: 100 },
163 adminHeaders
164 )
165
166 product = (
167 await api.post(
168 "/admin/products",
169 {
170 title: "Shirt",
171 status: ProductStatus.PUBLISHED,
172 shipping_profile_id: shippingProfile.id,
173 options: [{ title: "size", values: ["large"] }],
174 variants: [
175 {
176 title: "L shirt",
177 options: { size: "large" },
178 inventory_items: [
179 { inventory_item_id: inventoryItem.id, required_quantity: 1 },
180 ],
181 prices: [{ currency_code: "usd", amount: 10 }],
182 },
183 ],
184 },
185 adminHeaders
186 )
187 ).data.product
188
189 testDraftOrder = (
190 await api.post(
191 "/admin/draft-orders",
192 {
193 email: "test@test.com",
194 region_id: region.id,
195 sales_channel_id: salesChannel.id,
196 shipping_address: {
197 address_1: "123 Main St",
198 city: "Anytown",
199 country_code: "US",
200 postal_code: "12345",
201 first_name: "John",
202 },
203 },
204 adminHeaders
205 )
206 ).data.draft_order
207 })
208
209 const beginEdit = () =>
210 api.post(
211 `/admin/draft-orders/${testDraftOrder.id}/edit`,
212 {},
213 adminHeaders
214 )
215
216 const addItem = (quantity: number) =>
217 api.post(
218 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
219 { items: [{ variant_id: product.variants![0].id, quantity }] },
220 adminHeaders
221 )
222
223 const addShippingMethod = (
224 shipping_option_id: string,
225 custom_amount?: number
226 ) =>
227 api.post(
228 `/admin/draft-orders/${testDraftOrder.id}/edit/shipping-methods`,
229 custom_amount === undefined
230 ? { shipping_option_id }
231 : { shipping_option_id, custom_amount },
232 adminHeaders
233 )
234
235 const confirmEdit = () =>
236 api.post(
237 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
238 {},
239 adminHeaders
240 )
241
242 const getDraftOrder = async () =>
243 (await api.get(`/admin/draft-orders/${testDraftOrder.id}`, adminHeaders))
244 .data.draft_order
245
246 describe("POST /draft-orders/:id/edit/shipping-methods (calculated)", () => {
247 it("adds a calculated shipping option using the provider-calculated price", async () => {
248 await beginEdit()
249 await addItem(2)
250
251 const response = await addShippingMethod(calculatedShippingOption.id)
252 expect(response.status).toBe(200)
253
254 await confirmEdit()
255
256 const order = await getDraftOrder()
257 expect(order.shipping_methods).toHaveLength(1)
258 expect(order.shipping_methods[0]).toEqual(
259 expect.objectContaining({
260 shipping_option_id: calculatedShippingOption.id,
261 amount: 2 * PRICE_PER_ITEM,
262 is_custom_amount: false,
263 })
264 )
265 })
266
267 it("uses the custom amount when one is provided for a calculated option", async () => {
268 await beginEdit()
269 await addItem(2)
270 await addShippingMethod(calculatedShippingOption.id, 99)
271 await confirmEdit()
272
273 const order = await getDraftOrder()
274 expect(order.shipping_methods[0]).toEqual(
275 expect.objectContaining({
276 shipping_option_id: calculatedShippingOption.id,
277 amount: 99,
278 is_custom_amount: true,
279 })
280 )
281 })
282
283 it("adds a flat-rate shipping option", async () => {
284 await beginEdit()
285 await addItem(2)
286 await addShippingMethod(flatShippingOption.id)
287 await confirmEdit()
288
289 const order = await getDraftOrder()
290 expect(order.shipping_methods[0]).toEqual(
291 expect.objectContaining({
292 shipping_option_id: flatShippingOption.id,
293 amount: 5,
294 })
295 )
296 })
297
298 it("refreshes the calculated shipping price when items are added", async () => {
299 await beginEdit()
300 await addItem(2)
301 await addShippingMethod(calculatedShippingOption.id)
302
303 // Adding more items should re-run the provider calculation against the
304 // updated item count (2 + 3 = 5 items).
305 await addItem(3)
306 await confirmEdit()
307
308 const order = await getDraftOrder()
309 expect(order.shipping_methods[0]).toEqual(
310 expect.objectContaining({
311 shipping_option_id: calculatedShippingOption.id,
312 amount: 5 * PRICE_PER_ITEM,
313 is_custom_amount: false,
314 })
315 )
316 })
317
318 it("recalculates the calculated price when a custom amount is reset to null", async () => {
319 await beginEdit()
320 await addItem(2)
321
322 const preview = (
323 await addShippingMethod(calculatedShippingOption.id, 99)
324 ).data.draft_order_preview
325
326 const shippingMethod = preview.shipping_methods[0]
327 const addAction = shippingMethod.actions?.find(
328 (action: any) => action.action === "SHIPPING_ADD"
329 )
330 expect(addAction).toBeDefined()
331
332 const response = await api.post(
333 `/admin/draft-orders/${testDraftOrder.id}/edit/shipping-methods/${
334 addAction!.id
335 }`,
336 {
337 shipping_option_id: calculatedShippingOption.id,
338 custom_amount: null,
339 },
340 adminHeaders
341 )
342
343 expect(response.status).toBe(200)
344 const updatedMethod =
345 response.data.draft_order_preview.shipping_methods[0]
346 expect(updatedMethod).toEqual(
347 expect.objectContaining({
348 amount: 2 * PRICE_PER_ITEM,
349 is_custom_amount: false,
350 })
351 )
352 })
353
354 it("refreshes an already-applied calculated method when a later edit changes items", async () => {
355 // Edit 1: add item qty 2 + calculated shipping, confirm (amount = 3).
356 await beginEdit()
357 await addItem(2)
358 await addShippingMethod(calculatedShippingOption.id)
359 await confirmEdit()
360
361 let order = await getDraftOrder()
362 expect(order.shipping_methods[0].amount).toBe(2 * PRICE_PER_ITEM)
363
364 // Edit 2: add more items (total qty 5), confirm WITHOUT touching shipping.
365 await beginEdit()
366 await addItem(3)
367 await confirmEdit()
368
369 order = await getDraftOrder()
370 expect(order.shipping_methods).toHaveLength(1)
371 expect(order.shipping_methods[0]).toEqual(
372 expect.objectContaining({
373 shipping_option_id: calculatedShippingOption.id,
374 amount: 5 * PRICE_PER_ITEM,
375 is_custom_amount: false,
376 })
377 )
378 })
379
380 it("refreshes the pending shipping method amount in the preview before confirm", async () => {
381 await beginEdit()
382 await addItem(2)
383
384 const afterShipping = (
385 await addShippingMethod(calculatedShippingOption.id)
386 ).data.draft_order_preview
387 expect(afterShipping.shipping_methods[0].amount).toBe(
388 2 * PRICE_PER_ITEM
389 )
390
391 // Adding more items refreshes the pending action amount in the SAME
392 // edit; the returned preview reflects it without confirming.
393 const afterMoreItems = (await addItem(3)).data.draft_order_preview
394 expect(afterMoreItems.shipping_methods[0].amount).toBe(
395 5 * PRICE_PER_ITEM
396 )
397 })
398
399 it("prices a calculated method using only items in its shipping profile", async () => {
400 const profileB = (
401 await api.post(
402 `/admin/shipping-profiles`,
403 { name: "profile B", type: "heavy" },
404 adminHeaders
405 )
406 ).data.shipping_profile
407
408 const inventoryItemB = (
409 await api.post(
410 `/admin/inventory-items`,
411 { sku: "pants" },
412 adminHeaders
413 )
414 ).data.inventory_item
415
416 await api.post(
417 `/admin/inventory-items/${inventoryItemB.id}/location-levels`,
418 { location_id: stockLocation.id, stocked_quantity: 100 },
419 adminHeaders
420 )
421
422 const productB = (
423 await api.post(
424 "/admin/products",
425 {
426 title: "Pants",
427 status: ProductStatus.PUBLISHED,
428 shipping_profile_id: profileB.id,
429 options: [{ title: "size", values: ["large"] }],
430 variants: [
431 {
432 title: "L pants",
433 options: { size: "large" },
434 inventory_items: [
435 {
436 inventory_item_id: inventoryItemB.id,
437 required_quantity: 1,
438 },
439 ],
440 prices: [{ currency_code: "usd", amount: 10 }],
441 },
442 ],
443 },
444 adminHeaders
445 )
446 ).data.product
447
448 await beginEdit()
449 // 2 items on the default profile (the calculated option's profile)...
450 await addItem(2)
451 // ...and 4 items on profile B, which the option must ignore.
452 await api.post(
453 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
454 { items: [{ variant_id: productB.variants[0].id, quantity: 4 }] },
455 adminHeaders
456 )
457
458 const preview = (await addShippingMethod(calculatedShippingOption.id))
459 .data.draft_order_preview
460
461 const method = preview.shipping_methods.find(
462 (sm: any) => sm.shipping_option_id === calculatedShippingOption.id
463 )
464 // Only the 2 default-profile items count (2 * 1.5 = 3), not all 6.
465 expect(method.amount).toBe(2 * PRICE_PER_ITEM)
466 })
467 })
468 },
469 })