1 import {
2 cancelOrderFulfillmentWorkflow,
3 createOrderFulfillmentWorkflow,
4 createShippingOptionsWorkflow,
5 } from "@medusajs/core-flows"
6 import {
7 medusaIntegrationTestRunner,
8 normalizeBigNumbers,
9 } from "@medusajs/test-utils"
10 import {
11 FulfillmentWorkflow,
12 IOrderModuleService,
13 IRegionModuleService,
14 IStockLocationService,
15 OrderWorkflow,
16 ProductDTO,
17 RegionDTO,
18 ShippingOptionDTO,
19 StockLocationDTO,
20 } from "@medusajs/types"
21 import { BigNumber, ContainerRegistrationKeys, Modules, remoteQueryObjectFromString, } from "@medusajs/utils"
22
23 jest.setTimeout(500000)
24
25 const env = {}
26 const providerId = "manual_test-provider"
27 const variantSkuWithInventory = "test-variant"
28 let inventoryItem
29
30 async function prepareDataFixtures({ container }) {
31 const fulfillmentService = container.resolve(Modules.FULFILLMENT)
32 const salesChannelService = container.resolve(Modules.SALES_CHANNEL)
33 const stockLocationModule: IStockLocationService = container.resolve(
34 Modules.STOCK_LOCATION
35 )
36 const productModule = container.resolve(Modules.PRODUCT)
37 const inventoryModule = container.resolve(Modules.INVENTORY)
38
39 const shippingProfile = await fulfillmentService.createShippingProfiles({
40 name: "test",
41 type: "default",
42 })
43
44 const fulfillmentSet = await fulfillmentService.createFulfillmentSets({
45 name: "Test fulfillment set",
46 type: "manual_test",
47 })
48
49 const serviceZone = await fulfillmentService.createServiceZones({
50 name: "Test service zone",
51 fulfillment_set_id: fulfillmentSet.id,
52 geo_zones: [
53 {
54 type: "country",
55 country_code: "US",
56 },
57 ],
58 })
59
60 const regionService = container.resolve(
61 Modules.REGION
62 ) as IRegionModuleService
63
64 const [region] = await regionService.createRegions([
65 {
66 name: "Test region",
67 currency_code: "eur",
68 countries: ["fr"],
69 },
70 ])
71
72 const salesChannel = await salesChannelService.createSalesChannels({
73 name: "Webshop",
74 })
75
76 const location: StockLocationDTO =
77 await stockLocationModule.createStockLocations({
78 name: "Warehouse",
79 address: {
80 address_1: "Test",
81 city: "Test",
82 country_code: "US",
83 postal_code: "12345",
84 phone: "12345",
85 },
86 })
87
88 const [product] = await productModule.createProducts([
89 {
90 title: "Test product",
91 variants: [
92 {
93 title: "Test variant",
94 sku: variantSkuWithInventory,
95 },
96 {
97 title: "Test variant no inventory management",
98 sku: "test-variant-no-inventory",
99 manage_inventory: false,
100 },
101 ],
102 },
103 ])
104
105 inventoryItem = await inventoryModule.createInventoryItems({
106 sku: "inv-1234",
107 })
108
109 await inventoryModule.createInventoryLevels([
110 {
111 inventory_item_id: inventoryItem.id,
112 location_id: location.id,
113 stocked_quantity: 2,
114 reserved_quantity: 0,
115 },
116 ])
117
118 const remoteLink = container.resolve(ContainerRegistrationKeys.REMOTE_LINK)
119
120 await remoteLink.create([
121 {
122 [Modules.STOCK_LOCATION]: {
123 stock_location_id: location.id,
124 },
125 [Modules.FULFILLMENT]: {
126 fulfillment_provider_id: "manual_test-provider",
127 },
128 },
129 ])
130
131 await remoteLink.create([
132 {
133 [Modules.PRODUCT]: {
134 product_id: product.id,
135 },
136 [Modules.FULFILLMENT]: {
137 shipping_profile_id: shippingProfile.id,
138 },
139 },
140 ])
141
142 await remoteLink.create([
143 {
144 [Modules.STOCK_LOCATION]: {
145 stock_location_id: location.id,
146 },
147 [Modules.FULFILLMENT]: {
148 fulfillment_set_id: fulfillmentSet.id,
149 },
150 },
151 {
152 [Modules.SALES_CHANNEL]: {
153 sales_channel_id: salesChannel.id,
154 },
155 [Modules.STOCK_LOCATION]: {
156 stock_location_id: location.id,
157 },
158 },
159 {
160 [Modules.PRODUCT]: {
161 variant_id: product.variants.find((v) => v.sku === variantSkuWithInventory)!.id,
162 },
163 [Modules.INVENTORY]: {
164 inventory_item_id: inventoryItem.id,
165 },
166 },
167 ])
168
169 const shippingOptionData: FulfillmentWorkflow.CreateShippingOptionsWorkflowInput =
170 {
171 name: "Shipping option",
172 price_type: "flat",
173 service_zone_id: serviceZone.id,
174 shipping_profile_id: shippingProfile.id,
175 provider_id: providerId,
176 type: {
177 code: "manual-type",
178 label: "Manual Type",
179 description: "Manual Type Description",
180 },
181 prices: [
182 {
183 currency_code: "usd",
184 amount: 10,
185 },
186 {
187 region_id: region.id,
188 amount: 100,
189 },
190 ],
191 }
192
193 const { result } = await createShippingOptionsWorkflow(container).run({
194 input: [shippingOptionData],
195 })
196
197 const remoteQueryObject = remoteQueryObjectFromString({
198 entryPoint: "shipping_option",
199 variables: {
200 id: result[0].id,
201 },
202 fields: [
203 "id",
204 "name",
205 "price_type",
206 "service_zone_id",
207 "shipping_profile_id",
208 "provider_id",
209 "data",
210 "metadata",
211 "type.*",
212 "created_at",
213 "updated_at",
214 "deleted_at",
215 "shipping_option_type_id",
216 "prices.*",
217 ],
218 })
219
220 const remoteQuery = container.resolve(ContainerRegistrationKeys.REMOTE_QUERY)
221
222 const [createdShippingOption] = await remoteQuery(remoteQueryObject)
223 return {
224 shippingOption: createdShippingOption,
225 region,
226 salesChannel,
227 location,
228 product,
229 }
230 }
231
232 async function createOrderFixture({ container, product, location }) {
233 const orderService: IOrderModuleService = container.resolve(Modules.ORDER)
234
235 const variantWithInventory = product.variants.find((v) => v.sku === variantSkuWithInventory)!
236 const variantWithoutInventory = product.variants.find((v) => v.sku === "test-variant-no-inventory")!
237
238 let order = await orderService.createOrders({
239 region_id: "test_region_id",
240 email: "foo@bar.com",
241 items: [
242 {
243 title: "Custom Item 2",
244 variant_sku: variantWithInventory.sku,
245 variant_title: variantWithInventory.title,
246 variant_id: variantWithInventory.id,
247 quantity: 1,
248 unit_price: 50,
249 adjustments: [
250 {
251 code: "VIP_25 ETH",
252 amount: "0.000000000000000005",
253 description: "VIP discount",
254 promotion_id: "prom_123",
255 provider_id: "coupon_kings",
256 },
257 ],
258 },
259 {
260 title: product.title,
261 variant_sku: variantWithoutInventory.sku,
262 variant_title: variantWithoutInventory.title,
263 variant_id: variantWithoutInventory.id,
264 quantity: 1,
265 unit_price: 200,
266 },
267 ],
268 transactions: [
269 {
270 amount: 50,
271 currency_code: "usd",
272 },
273 ],
274 sales_channel_id: "test",
275 shipping_address: {
276 first_name: "Test",
277 last_name: "Test",
278 address_1: "Test",
279 city: "Test",
280 country_code: "US",
281 postal_code: "12345",
282 phone: "12345",
283 },
284 billing_address: {
285 first_name: "Test",
286 last_name: "Test",
287 address_1: "Test",
288 city: "Test",
289 country_code: "US",
290 postal_code: "12345",
291 },
292 shipping_methods: [
293 {
294 name: "Test shipping method",
295 amount: 10,
296 data: {},
297 tax_lines: [
298 {
299 description: "shipping Tax 1",
300 tax_rate_id: "tax_usa_shipping",
301 code: "code",
302 rate: 10,
303 },
304 ],
305 adjustments: [
306 {
307 code: "VIP_10",
308 amount: 1,
309 description: "VIP discount",
310 promotion_id: "prom_123",
311 },
312 ],
313 },
314 ],
315 currency_code: "usd",
316 customer_id: "joe",
317 })
318
319 const inventoryModule = container.resolve(Modules.INVENTORY)
320
321 const itemWithInventory = order.items!.find(
322 (o) => o.variant_sku === variantSkuWithInventory
323 )!
324 const reservation = await inventoryModule.createReservationItems([
325 {
326 line_item_id: itemWithInventory.id,
327 inventory_item_id: inventoryItem.id,
328 location_id: location.id,
329 quantity: itemWithInventory.quantity,
330 },
331 ])
332
333 order = await orderService.retrieveOrder(order.id, {
334 relations: ["items"],
335 })
336
337 return order
338 }
339
340 medusaIntegrationTestRunner({
341 env,
342 testSuite: ({ getContainer }) => {
343 let container
344
345 beforeAll(() => {
346 container = getContainer()
347 })
348
349 describe("Order fulfillment workflow", () => {
350 let shippingOption: ShippingOptionDTO
351 let region: RegionDTO
352 let location: StockLocationDTO
353 let product: ProductDTO
354
355 let orderService: IOrderModuleService
356
357 beforeEach(async () => {
358 const fixtures = await prepareDataFixtures({
359 container,
360 })
361
362 shippingOption = fixtures.shippingOption
363 region = fixtures.region
364 location = fixtures.location
365 product = fixtures.product
366
367 orderService = container.resolve(Modules.ORDER)
368 })
369
370 it("should create a order fulfillment and cancel it", async () => {
371 const inventoryModule = container.resolve(Modules.INVENTORY)
372
373 const order = await createOrderFixture({ container, product, location })
374 const itemWithInventory = order.items!.find(
375 (o) => o.variant_sku === variantSkuWithInventory
376 )!
377
378 // Create a fulfillment
379 const createOrderFulfillmentData: OrderWorkflow.CreateOrderFulfillmentWorkflowInput =
380 {
381 order_id: order.id,
382 created_by: "user_1",
383 items: [
384 {
385 id: itemWithInventory.id,
386 quantity: 1,
387 },
388 ],
389 no_notification: false,
390 location_id: undefined,
391 metadata: { meta_key: "meta_value" },
392 }
393
394 await createOrderFulfillmentWorkflow(container).run({
395 input: createOrderFulfillmentData,
396 })
397
398 const remoteQuery = container.resolve(
399 ContainerRegistrationKeys.REMOTE_QUERY
400 )
401 const remoteQueryObject = remoteQueryObjectFromString({
402 entryPoint: "order",
403 variables: {
404 id: order.id,
405 },
406 fields: [
407 "*",
408 "items.*",
409 "shipping_methods.*",
410 "total",
411 "item_total",
412 "fulfillments.*",
413 ],
414 })
415
416 const [orderFulfill] = await remoteQuery(remoteQueryObject)
417
418 let orderFulfillItemWithInventory = orderFulfill.items!.find(
419 (o) => o.variant_sku === variantSkuWithInventory
420 )!
421
422 expect(orderFulfill.fulfillments).toHaveLength(1)
423 expect(
424 normalizeBigNumbers(orderFulfillItemWithInventory.detail.fulfilled_quantity)
425 ).toEqual(1)
426 expect(orderFulfill.fulfillments[0].metadata).toEqual({
427 meta_key: "meta_value",
428 })
429
430 const reservation = await inventoryModule.listReservationItems({
431 line_item_id: itemWithInventory.id,
432 })
433 expect(reservation).toHaveLength(0)
434
435 const stockAvailability = await inventoryModule.retrieveStockedQuantity(
436 inventoryItem.id,
437 [location.id]
438 )
439 expect(stockAvailability).toEqual(new BigNumber(1))
440
441 // Cancel the fulfillment
442 const cancelFulfillmentData: OrderWorkflow.CancelOrderFulfillmentWorkflowInput =
443 {
444 order_id: order.id,
445 fulfillment_id: orderFulfill.fulfillments[0].id,
446 no_notification: false,
447 }
448
449 await cancelOrderFulfillmentWorkflow(container).run({
450 input: cancelFulfillmentData,
451 })
452
453 const remoteQueryObjectFulfill = remoteQueryObjectFromString({
454 entryPoint: "order",
455 variables: {
456 id: order.id,
457 },
458 fields: [
459 "items.*",
460 "shipping_methods.*",
461 "total",
462 "item_total",
463 "fulfillments.*",
464 ],
465 })
466
467 const [orderFulfillAfterCancelled] = await remoteQuery(
468 remoteQueryObjectFulfill
469 )
470
471 orderFulfillItemWithInventory = orderFulfillAfterCancelled.items!.find(
472 (o) => o.variant_sku === variantSkuWithInventory
473 )!
474
475 expect(orderFulfillAfterCancelled.fulfillments).toHaveLength(1)
476 expect(
477 orderFulfillItemWithInventory.detail.fulfilled_quantity.valueOf()
478 ).toEqual(0)
479
480 const stockAvailabilityAfterCancelled =
481 await inventoryModule.retrieveStockedQuantity(inventoryItem.id, [
482 location.id,
483 ])
484
485 expect(stockAvailabilityAfterCancelled.valueOf()).toEqual(2)
486 })
487
488 it("should revert an order fulfillment when it fails and recreate it when tried again", async () => {
489 const order = await createOrderFixture({ container, product, location })
490
491 const itemId = order.items?.find((i) => i.title === "Custom Item 2")!
492 .id as string
493
494 // Create a fulfillment
495 const createOrderFulfillmentData: OrderWorkflow.CreateOrderFulfillmentWorkflowInput =
496 {
497 order_id: order.id,
498 created_by: "user_1",
499 items: [
500 {
501 id: itemId,
502 quantity: 1,
503 },
504 ],
505 no_notification: false,
506 location_id: undefined,
507 }
508
509 const worflow = createOrderFulfillmentWorkflow(container)
510 worflow.addAction("fail", {
511 invoke: () => {
512 throw new Error("Fulfillment failed")
513 },
514 })
515
516 await worflow
517 .run({
518 input: createOrderFulfillmentData,
519 })
520 .catch(() => void 0)
521
522 worflow.deleteAction("fail")
523
524 await worflow.run({
525 input: createOrderFulfillmentData,
526 })
527
528 const remoteQuery = container.resolve(
529 ContainerRegistrationKeys.REMOTE_QUERY
530 )
531 const remoteQueryObject = remoteQueryObjectFromString({
532 entryPoint: "order",
533 variables: {
534 id: order.id,
535 },
536 fields: [
537 "*",
538 "items.*",
539 "shipping_methods.*",
540 "total",
541 "item_total",
542 "fulfillments.*",
543 ],
544 })
545
546 const [orderFulfill] = await remoteQuery(remoteQueryObject)
547
548 const fulfilledItem = orderFulfill.items?.find((i) => i.id === itemId)
549
550 expect(orderFulfill.fulfillments).toHaveLength(1)
551 expect(normalizeBigNumbers(fulfilledItem?.detail.fulfilled_quantity)).toEqual(
552 1
553 )
554
555 const inventoryModule = container.resolve(Modules.INVENTORY)
556 const reservation = await inventoryModule.listReservationItems({
557 line_item_id: itemId,
558 })
559 expect(reservation).toHaveLength(0)
560
561 const stockAvailability = await inventoryModule.retrieveStockedQuantity(
562 inventoryItem.id,
563 [location.id]
564 )
565 expect(stockAvailability.valueOf()).toEqual(1)
566 })
567
568 it("should persist created_by field when creating a fulfillment", async () => {
569 const order = await createOrderFixture({ container, product, location })
570 const itemWithInventory = order.items!.find(
571 (o) => o.variant_sku === variantSkuWithInventory
572 )!
573
574 const createdByUserId = "user_test_123"
575
576 // Create a fulfillment with created_by
577 const createOrderFulfillmentData: OrderWorkflow.CreateOrderFulfillmentWorkflowInput =
578 {
579 order_id: order.id,
580 created_by: createdByUserId,
581 items: [
582 {
583 id: itemWithInventory.id,
584 quantity: 1,
585 },
586 ],
587 no_notification: false,
588 location_id: undefined,
589 }
590
591 await createOrderFulfillmentWorkflow(container).run({
592 input: createOrderFulfillmentData,
593 })
594
595 const remoteQuery = container.resolve(
596 ContainerRegistrationKeys.REMOTE_QUERY
597 )
598 const remoteQueryObject = remoteQueryObjectFromString({
599 entryPoint: "order",
600 variables: {
601 id: order.id,
602 },
603 fields: ["*", "fulfillments.*"],
604 })
605
606 const [orderWithFulfillment] = await remoteQuery(remoteQueryObject)
607
608 expect(orderWithFulfillment.fulfillments).toHaveLength(1)
609 expect(orderWithFulfillment.fulfillments[0].created_by).toEqual(
610 createdByUserId
611 )
612 })
613 })
614 },
615 })