1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { HttpTypes } from "@medusajs/types"
3 import {
4 ApiKeyType,
5 ModuleRegistrationName,
6 PriceListStatus,
7 PriceListType,
8 ProductStatus,
9 PromotionStatus,
10 PromotionType,
11 } from "@medusajs/utils"
12 import {
13 adminHeaders,
14 createAdminUser,
15 } from "../../../../helpers/create-admin-user"
16 import { setupTaxStructure } from "../../../../modules/__tests__/fixtures"
17
18 jest.setTimeout(300000)
19
20 medusaIntegrationTestRunner({
21 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
22 let region: HttpTypes.AdminRegion
23 let salesChannel: HttpTypes.AdminSalesChannel
24 let stockLocation: HttpTypes.AdminStockLocation
25 let testDraftOrder: HttpTypes.AdminDraftOrder
26 let shippingOption: HttpTypes.AdminShippingOption
27 let shippingOptionHeavy: HttpTypes.AdminShippingOption
28 let apiKey: HttpTypes.AdminApiKeyResponse["api_key"]
29 let userId: string
30
31 beforeAll(async () => {
32 const container = getContainer()
33
34 await setupTaxStructure(container.resolve(ModuleRegistrationName.TAX))
35 userId = await createAdminUser(
36 dbConnection,
37 adminHeaders,
38 container
39 ).then((res) => res.user.id)
40
41 region = (
42 await api.post(
43 `/admin/regions`,
44 {
45 name: "USA",
46 currency_code: "usd",
47 countries: ["US"],
48 },
49 adminHeaders
50 )
51 ).data.region
52
53 salesChannel = (
54 await api.post("/admin/sales-channels", { name: "test" }, adminHeaders)
55 ).data.sales_channel
56
57 stockLocation = (
58 await api.post(
59 `/admin/stock-locations`,
60 { name: "test location" },
61 adminHeaders
62 )
63 ).data.stock_location
64
65 const shippingProfile = (
66 await api.post(
67 `/admin/shipping-profiles`,
68 { name: "test shipping profile", type: "default" },
69 adminHeaders
70 )
71 ).data.shipping_profile
72
73 const shippingProfileHeavy = (
74 await api.post(
75 `/admin/shipping-profiles`,
76 { name: "test shipping profile heavy", type: "heavy" },
77 adminHeaders
78 )
79 ).data.shipping_profile
80
81 const fulfillmentSets = (
82 await api.post(
83 `/admin/stock-locations/${stockLocation.id}/fulfillment-sets?fields=*fulfillment_sets`,
84 {
85 name: `Test-${shippingProfile.id}`,
86 type: "test-type",
87 },
88 adminHeaders
89 )
90 ).data.stock_location.fulfillment_sets
91
92 const fulfillmentSet = (
93 await api.post(
94 `/admin/fulfillment-sets/${fulfillmentSets[0].id}/service-zones`,
95 {
96 name: `Test-${shippingProfile.id}`,
97 geo_zones: [{ type: "country", country_code: "us" }],
98 },
99 adminHeaders
100 )
101 ).data.fulfillment_set
102
103 await api.post(
104 `/admin/stock-locations/${stockLocation.id}/fulfillment-providers`,
105 { add: ["manual_test-provider"] },
106 adminHeaders
107 )
108
109 await api.post(
110 `/admin/stock-locations/${stockLocation.id}/sales-channels`,
111 { add: [salesChannel.id] },
112 adminHeaders
113 )
114
115 shippingOption = (
116 await api.post(
117 `/admin/shipping-options`,
118 {
119 name: `Test shipping option ${fulfillmentSet.id}`,
120 service_zone_id: fulfillmentSet.service_zones[0].id,
121 shipping_profile_id: shippingProfile.id,
122 provider_id: "manual_test-provider",
123 price_type: "flat",
124 type: {
125 label: "Test type",
126 description: "Test description",
127 code: "test-code",
128 },
129 prices: [{ currency_code: "usd", amount: 5 }],
130 rules: [],
131 },
132 adminHeaders
133 )
134 ).data.shipping_option
135
136 shippingOptionHeavy = (
137 await api.post(
138 `/admin/shipping-options`,
139 {
140 name: `Test shipping option ${fulfillmentSet.id}`,
141 service_zone_id: fulfillmentSet.service_zones[0].id,
142 shipping_profile_id: shippingProfileHeavy.id,
143 provider_id: "manual_test-provider",
144 price_type: "flat",
145 type: {
146 label: "Test type",
147 description: "Test description",
148 code: "test-code",
149 },
150 prices: [{ currency_code: "usd", amount: 10 }],
151 rules: [],
152 },
153 adminHeaders
154 )
155 ).data.shipping_option
156
157 testDraftOrder = (
158 await api.post(
159 "/admin/draft-orders",
160 {
161 email: "test@test.com",
162 region_id: region.id,
163 sales_channel_id: salesChannel.id,
164 shipping_address: {
165 address_1: "123 Main St",
166 city: "Anytown",
167 country_code: "US",
168 postal_code: "12345",
169 first_name: "John",
170 },
171 },
172 adminHeaders
173 )
174 ).data.draft_order
175
176 await dbUtils.snapshot()
177 })
178
179 describe("GET /draft-orders", () => {
180 it("should get a list of draft orders", async () => {
181 const response = await api.get("/admin/draft-orders", adminHeaders)
182
183 expect(response.status).toBe(200)
184 expect(response.data.draft_orders).toBeDefined()
185 expect(response.data.draft_orders.length).toBe(1)
186 expect(response.data.draft_orders).toEqual(
187 expect.arrayContaining([
188 expect.objectContaining({
189 email: "test@test.com",
190 }),
191 ])
192 )
193 })
194 })
195
196 describe("POST /draft-orders", () => {
197 it("should create a draft order", async () => {
198 const response = await api.post(
199 "/admin/draft-orders",
200 {
201 email: "test2@test.com",
202 region_id: region.id,
203 },
204 adminHeaders
205 )
206
207 expect(response.status).toBe(200)
208 expect(response.data.draft_order.email).toBe("test2@test.com")
209 expect(response.data.draft_order.region_id).toBe(region.id)
210 })
211
212 it("should create a draft order without an email or customer_id", async () => {
213 const response = await api.post(
214 "/admin/draft-orders",
215 {
216 region_id: region.id,
217 },
218 adminHeaders
219 )
220
221 expect(response.status).toBe(200)
222 expect(response.data.draft_order.email).toBeFalsy()
223 expect(response.data.draft_order.customer_id).toBeFalsy()
224 expect(response.data.draft_order.region_id).toBe(region.id)
225 })
226 })
227
228 describe("GET /draft-orders/:id", () => {
229 it("should get a draft order", async () => {
230 const response = await api.get(
231 `/admin/draft-orders/${testDraftOrder.id}`,
232 adminHeaders
233 )
234
235 expect(response.status).toBe(200)
236 expect(response.data.draft_order.email).toBe("test@test.com")
237 expect(response.data.draft_order.region_id).toBe(region.id)
238 })
239 })
240
241 describe("POST /draft-orders/:id", () => {
242 it("should update a draft order", async () => {
243 const response = await api.post(
244 `/admin/draft-orders/${testDraftOrder.id}`,
245 {
246 email: "test_new@test.com",
247 },
248 adminHeaders
249 )
250
251 expect(response.status).toBe(200)
252 expect(response.data.draft_order.email).toBe("test_new@test.com")
253 })
254
255 it("should use the secret key linked user to set created_by", async () => {
256 apiKey = (
257 await api.post(
258 "/admin/api-keys",
259 {
260 title: "secret-key",
261 type: ApiKeyType.SECRET,
262 },
263 adminHeaders
264 )
265 ).data.api_key
266
267 const draftOrderResponse = await api.post(
268 `/admin/draft-orders/${testDraftOrder.id}`,
269 {
270 email: "test_new@test.com",
271 },
272 {
273 headers: {
274 Authorization: `Basic ${apiKey.token}`,
275 },
276 }
277 )
278
279 expect(draftOrderResponse.status).toBe(200)
280 expect(draftOrderResponse.data.draft_order.email).toBe(
281 "test_new@test.com"
282 )
283
284 const orderChange = (
285 await api.get(
286 `/admin/orders/${testDraftOrder.id}/changes`,
287 adminHeaders
288 )
289 ).data.order_changes[0]
290
291 expect(orderChange).toEqual(
292 expect.objectContaining({
293 created_by: userId,
294 })
295 )
296 })
297 })
298
299 describe("DELETE /draft-orders/:id", () => {
300 it("should delete a draft order", async () => {
301 const response = await api.delete(
302 `/admin/draft-orders/${testDraftOrder.id}`,
303 adminHeaders
304 )
305
306 expect(response.status).toBe(200)
307 expect(response.data).toEqual(
308 expect.objectContaining({
309 id: testDraftOrder.id,
310 object: "draft-order",
311 deleted: true,
312 })
313 )
314 })
315 })
316
317 describe("POST /draft-orders/:id/convert-to-order", () => {
318 let product
319 let inventoryItemLarge
320 let inventoryItemMedium
321
322 beforeEach(async () => {
323 inventoryItemLarge = (
324 await api.post(
325 `/admin/inventory-items`,
326 { sku: "shirt-large" },
327 adminHeaders
328 )
329 ).data.inventory_item
330
331 inventoryItemMedium = (
332 await api.post(
333 `/admin/inventory-items`,
334 { sku: "shirt-medium" },
335 adminHeaders
336 )
337 ).data.inventory_item
338
339 await api.post(
340 `/admin/inventory-items/${inventoryItemLarge.id}/location-levels`,
341 {
342 location_id: stockLocation.id,
343 stocked_quantity: 10,
344 },
345 adminHeaders
346 )
347
348 await api.post(
349 `/admin/inventory-items/${inventoryItemMedium.id}/location-levels`,
350 {
351 location_id: stockLocation.id,
352 stocked_quantity: 10,
353 },
354 adminHeaders
355 )
356
357 product = (
358 await api.post(
359 "/admin/products",
360 {
361 title: "Shirt",
362 status: ProductStatus.PUBLISHED,
363 options: [{ title: "size", values: ["large", "medium"] }],
364 variants: [
365 {
366 title: "L shirt",
367 options: { size: "large" },
368 manage_inventory: true,
369 inventory_items: [
370 {
371 inventory_item_id: inventoryItemLarge.id,
372 required_quantity: 1,
373 },
374 ],
375 prices: [
376 {
377 currency_code: "usd",
378 amount: 10,
379 },
380 ],
381 },
382 {
383 title: "M shirt",
384 options: { size: "medium" },
385 manage_inventory: true,
386 inventory_items: [
387 {
388 inventory_item_id: inventoryItemMedium.id,
389 required_quantity: 1,
390 },
391 ],
392 prices: [
393 {
394 currency_code: "usd",
395 amount: 10,
396 },
397 ],
398 },
399 ],
400 },
401 adminHeaders
402 )
403 ).data.product
404 })
405
406 it("should convert a draft order to an order", async () => {
407 const response = await api.post(
408 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
409 {},
410 adminHeaders
411 )
412
413 expect(response.status).toBe(200)
414 expect(response.data.order.status).toBe("pending")
415 })
416
417 it("should recompute tax lines when the shipping address changes and carry the current jurisdiction's tax into the converted order", async () => {
418 // Add an item under the US default jurisdiction (2%)
419 await api.post(
420 `/admin/draft-orders/${testDraftOrder.id}/edit`,
421 {},
422 adminHeaders
423 )
424
425 await api.post(
426 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
427 {
428 items: [
429 {
430 variant_id: product.variants.find((v) => v.title === "L shirt")
431 .id,
432 quantity: 1,
433 },
434 ],
435 },
436 adminHeaders
437 )
438
439 await api.post(
440 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
441 {},
442 adminHeaders
443 )
444
445 const taxFields =
446 "?fields=+tax_total,+items.tax_total,+items.tax_lines.rate"
447
448 let draftOrder = (
449 await api.get(
450 `/admin/draft-orders/${testDraftOrder.id}${taxFields}`,
451 adminHeaders
452 )
453 ).data.draft_order
454
455 expect(draftOrder.items[0].tax_lines).toEqual([
456 expect.objectContaining({ rate: 2 }),
457 ])
458 expect(draftOrder.items[0].tax_total).toBe(0.2)
459
460 // Change the shipping address to the CA province jurisdiction (5%)
461 await api.post(
462 `/admin/draft-orders/${testDraftOrder.id}`,
463 {
464 shipping_address: {
465 province: "CA",
466 },
467 },
468 adminHeaders
469 )
470
471 // Tax lines should be recomputed to reflect the new jurisdiction
472 draftOrder = (
473 await api.get(
474 `/admin/draft-orders/${testDraftOrder.id}${taxFields}`,
475 adminHeaders
476 )
477 ).data.draft_order
478
479 expect(draftOrder.items[0].tax_lines).toEqual([
480 expect.objectContaining({ rate: 5 }),
481 ])
482 expect(draftOrder.items[0].tax_total).toBe(0.5)
483
484 // Convert to order and confirm the placed order reflects the current jurisdiction
485 const response = await api.post(
486 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
487 {},
488 adminHeaders
489 )
490
491 expect(response.status).toBe(200)
492 expect(response.data.order.status).toBe("pending")
493
494 const order = (
495 await api.get(
496 `/admin/orders/${response.data.order.id}${taxFields}`,
497 adminHeaders
498 )
499 ).data.order
500
501 expect(order.items[0].tax_lines).toEqual([
502 expect.objectContaining({ rate: 5 }),
503 ])
504 expect(order.items[0].tax_total).toBe(0.5)
505 })
506
507 it("should create reservations on draft order to order conversion", async () => {
508 await api.post(
509 `/admin/draft-orders/${testDraftOrder.id}/edit`,
510 {},
511 adminHeaders
512 )
513
514 await api.post(
515 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
516 {
517 items: [
518 {
519 variant_id: product.variants.find((v) => v.title === "L shirt")
520 .id,
521 quantity: 1,
522 },
523 ],
524 },
525 adminHeaders
526 )
527
528 await api.post(
529 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
530 {
531 items: [
532 {
533 variant_id: product.variants.find((v) => v.title === "M shirt")
534 .id,
535 quantity: 1,
536 },
537 ],
538 },
539 adminHeaders
540 )
541
542 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
543 .data.reservations
544
545 expect(reservations.length).toBe(0)
546
547 await api.post(
548 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
549 {},
550 adminHeaders
551 )
552
553 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
554 .reservations
555
556 expect(reservations.length).toBe(0)
557
558 const response = await api.post(
559 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
560 {},
561 adminHeaders
562 )
563
564 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
565 .reservations
566
567 expect(reservations).toEqual(
568 expect.arrayContaining([
569 expect.objectContaining({
570 inventory_item_id: inventoryItemLarge.id,
571 quantity: 1,
572 }),
573 expect.objectContaining({
574 inventory_item_id: inventoryItemMedium.id,
575 quantity: 1,
576 }),
577 ])
578 )
579
580 expect(response.status).toBe(200)
581 expect(response.data.order.status).toBe("pending")
582 })
583
584 it("should convert a draft order with a custom item (without variant_id) to an order", async () => {
585 await api.post(
586 `/admin/draft-orders/${testDraftOrder.id}/edit`,
587 {},
588 adminHeaders
589 )
590
591 await api.post(
592 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
593 {
594 items: [
595 {
596 title: "Custom Item",
597 quantity: 2,
598 unit_price: 1500,
599 },
600 ],
601 },
602 adminHeaders
603 )
604
605 await api.post(
606 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
607 {},
608 adminHeaders
609 )
610
611 const response = await api.post(
612 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
613 {},
614 adminHeaders
615 )
616
617 expect(response.status).toBe(200)
618 expect(response.data.order.status).toBe("pending")
619 })
620
621 it("should convert a draft order with both variant items and custom items to an order", async () => {
622 await api.post(
623 `/admin/draft-orders/${testDraftOrder.id}/edit`,
624 {},
625 adminHeaders
626 )
627
628 await api.post(
629 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
630 {
631 items: [
632 {
633 variant_id: product.variants.find((v) => v.title === "L shirt")
634 .id,
635 quantity: 1,
636 },
637 {
638 title: "Custom Item",
639 quantity: 1,
640 unit_price: 2000,
641 },
642 ],
643 },
644 adminHeaders
645 )
646
647 await api.post(
648 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
649 {},
650 adminHeaders
651 )
652
653 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
654 .data.reservations
655
656 expect(reservations.length).toBe(0)
657
658 const response = await api.post(
659 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
660 {},
661 adminHeaders
662 )
663
664 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
665 .reservations
666
667 expect(reservations).toEqual(
668 expect.arrayContaining([
669 expect.objectContaining({
670 inventory_item_id: inventoryItemLarge.id,
671 quantity: 1,
672 }),
673 ])
674 )
675
676 expect(response.status).toBe(200)
677 expect(response.data.order.status).toBe("pending")
678 })
679 })
680
681 describe("POST /draft-orders/:id/edit/items/:item_id", () => {
682 let product
683 let inventoryItemLarge
684 let inventoryItemMedium
685 let inventoryItemSmall
686
687 beforeEach(async () => {
688 inventoryItemLarge = (
689 await api.post(
690 `/admin/inventory-items`,
691 { sku: "shirt-large" },
692 adminHeaders
693 )
694 ).data.inventory_item
695
696 inventoryItemMedium = (
697 await api.post(
698 `/admin/inventory-items`,
699 { sku: "shirt-medium" },
700 adminHeaders
701 )
702 ).data.inventory_item
703
704 inventoryItemSmall = (
705 await api.post(
706 `/admin/inventory-items`,
707 { sku: "shirt-small" },
708 adminHeaders
709 )
710 ).data.inventory_item
711
712 await api.post(
713 `/admin/inventory-items/${inventoryItemLarge.id}/location-levels`,
714 {
715 location_id: stockLocation.id,
716 stocked_quantity: 10,
717 },
718 adminHeaders
719 )
720
721 await api.post(
722 `/admin/inventory-items/${inventoryItemMedium.id}/location-levels`,
723 {
724 location_id: stockLocation.id,
725 stocked_quantity: 10,
726 },
727 adminHeaders
728 )
729 await api.post(
730 `/admin/inventory-items/${inventoryItemSmall.id}/location-levels`,
731 {
732 location_id: stockLocation.id,
733 stocked_quantity: 10,
734 },
735 adminHeaders
736 )
737
738 product = (
739 await api.post(
740 "/admin/products",
741 {
742 title: "Shirt",
743 status: ProductStatus.PUBLISHED,
744 options: [
745 { title: "size", values: ["large", "medium", "small"] },
746 ],
747 variants: [
748 {
749 title: "L shirt",
750 options: { size: "large" },
751 manage_inventory: true,
752 inventory_items: [
753 {
754 inventory_item_id: inventoryItemLarge.id,
755 required_quantity: 1,
756 },
757 ],
758 prices: [
759 {
760 currency_code: "usd",
761 amount: 10,
762 },
763 ],
764 },
765 {
766 title: "M shirt",
767 options: { size: "medium" },
768 manage_inventory: true,
769 inventory_items: [
770 {
771 inventory_item_id: inventoryItemMedium.id,
772 required_quantity: 1,
773 },
774 ],
775 prices: [
776 {
777 currency_code: "usd",
778 amount: 10,
779 },
780 ],
781 },
782 {
783 title: "S shirt",
784 options: { size: "small" },
785 manage_inventory: true,
786 inventory_items: [
787 {
788 inventory_item_id: inventoryItemSmall.id,
789 required_quantity: 1,
790 },
791 ],
792 prices: [
793 {
794 currency_code: "usd",
795 amount: 10,
796 },
797 ],
798 },
799 ],
800 },
801 adminHeaders
802 )
803 ).data.product
804 })
805
806 it("should not create reservations on draft order edit confirmation", async () => {
807 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
808 .data.reservations
809
810 expect(reservations.length).toBe(0)
811
812 // 1. Create first edit and add items to it
813 let edit = (
814 await api.post(
815 `/admin/draft-orders/${testDraftOrder.id}/edit`,
816 {},
817 adminHeaders
818 )
819 ).data.draft_order_preview
820
821 await api.post(
822 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
823 {
824 items: [
825 {
826 variant_id: product.variants.find((v) => v.title === "L shirt")
827 .id,
828 quantity: 1,
829 },
830 ],
831 },
832 adminHeaders
833 )
834
835 await api.post(
836 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
837 {
838 items: [
839 {
840 variant_id: product.variants.find((v) => v.title === "M shirt")
841 .id,
842 quantity: 1,
843 },
844 ],
845 },
846 adminHeaders
847 )
848
849 edit = (
850 await api.post(
851 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
852 {},
853 adminHeaders
854 )
855 ).data.draft_order_preview
856
857 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
858 .reservations
859
860 expect(reservations.length).toBe(0)
861
862 // Create second edit
863 edit = (
864 await api.post(
865 `/admin/draft-orders/${testDraftOrder.id}/edit`,
866 {},
867 adminHeaders
868 )
869 ).data.draft_order_preview
870
871 // Add item
872 await api.post(
873 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
874 {
875 items: [
876 {
877 variant_id: product.variants.find((v) => v.title === "S shirt")
878 .id,
879 quantity: 1,
880 },
881 ],
882 },
883 adminHeaders
884 )
885
886 // Remove item
887 await api.post(
888 `/admin/draft-orders/${testDraftOrder.id}/edit/items/item/${
889 edit.items.find((i) => i.subtitle === "M shirt").id
890 }`,
891 { quantity: 0 },
892 adminHeaders
893 )
894
895 // Update item
896 await api.post(
897 `/admin/draft-orders/${testDraftOrder.id}/edit/items/item/${
898 edit.items.find((i) => i.subtitle === "L shirt").id
899 }`,
900 { quantity: 2 },
901 adminHeaders
902 )
903
904 edit = (
905 await api.post(
906 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
907 {},
908 adminHeaders
909 )
910 ).data.draft_order_preview
911
912 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
913 .reservations
914
915 expect(reservations.length).toBe(0)
916 })
917
918 it("should update item metadata", async () => {
919 // Create edit
920 await api.post(
921 `/admin/draft-orders/${testDraftOrder.id}/edit`,
922 {},
923 adminHeaders
924 )
925
926 // Add item with initial metadata
927 let orderPreview = (
928 await api.post(
929 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
930 {
931 items: [
932 {
933 variant_id: product.variants.find(
934 (v) => v.title === "L shirt"
935 ).id,
936 quantity: 1,
937 metadata: { initial: "value", custom_field: "original" },
938 },
939 ],
940 },
941 adminHeaders
942 )
943 ).data.draft_order_preview
944
945 const itemToUpdate = orderPreview.items.find(
946 (i) => i.subtitle === "L shirt"
947 )
948 expect(itemToUpdate.metadata).toEqual({
949 initial: "value",
950 custom_field: "original",
951 })
952
953 await api.post(
954 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
955 {},
956 adminHeaders
957 )
958
959 await api.post(
960 `/admin/draft-orders/${testDraftOrder.id}/edit`,
961 {},
962 adminHeaders
963 )
964
965 // Update item with new metadata
966 orderPreview = (
967 await api.post(
968 `/admin/draft-orders/${testDraftOrder.id}/edit/items/item/${itemToUpdate.id}`,
969 {
970 quantity: 2,
971 metadata: { updated: "metadata", custom_field: "modified" },
972 },
973 adminHeaders
974 )
975 ).data.draft_order_preview
976
977 const updatedItem = orderPreview.items.find(
978 (i) => i.subtitle === "L shirt"
979 )
980 expect(updatedItem.quantity).toBe(2)
981 expect(updatedItem.metadata).toEqual({
982 updated: "metadata",
983 initial: "value",
984 custom_field: "modified",
985 })
986
987 await api.post(
988 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
989 {},
990 adminHeaders
991 )
992
993 const order = (
994 await api.get(
995 `/admin/draft-orders/${testDraftOrder.id}`,
996 adminHeaders
997 )
998 ).data.draft_order
999
1000 expect(
1001 order.items.find((i) => i.subtitle === "L shirt").metadata
1002 ).toEqual({
1003 updated: "metadata",
1004 initial: "value",
1005 custom_field: "modified",
1006 })
1007 })
1008 })
1009
1010 describe("POST /draft-orders/:id/edit/promotions", () => {
1011 describe("with recompute adjustments", () => {
1012 let product
1013 let promotion
1014
1015 beforeEach(async () => {
1016 product = (
1017 await api.post(
1018 "/admin/products",
1019 {
1020 title: "Promo product",
1021 status: ProductStatus.PUBLISHED,
1022 sales_channels: [{ id: salesChannel.id }],
1023 options: [{ title: "size", values: ["large", "small"] }],
1024 variants: [
1025 {
1026 title: "L shirt",
1027 options: { size: "large" },
1028 manage_inventory: false,
1029 prices: [
1030 {
1031 currency_code: "usd",
1032 amount: 1000,
1033 },
1034 ],
1035 },
1036 {
1037 title: "S shirt",
1038 options: { size: "small" },
1039 manage_inventory: false,
1040 prices: [
1041 {
1042 currency_code: "usd",
1043 amount: 1000,
1044 },
1045 ],
1046 },
1047 ],
1048 },
1049 adminHeaders
1050 )
1051 ).data.product
1052
1053 const promoCode = "recompute-test"
1054
1055 promotion = (
1056 await api.post(
1057 "/admin/promotions",
1058 {
1059 code: promoCode,
1060 type: "standard",
1061 status: "active",
1062 application_method: {
1063 type: "fixed",
1064 target_type: "items",
1065 allocation: "each",
1066 currency_code: "usd",
1067 value: 100,
1068 max_quantity: 5,
1069 },
1070 is_automatic: false,
1071 is_tax_inclusive: true,
1072 },
1073 adminHeaders
1074 )
1075 ).data.promotion
1076 })
1077
1078 it("should recompute adjustments when adding items after promotions", async () => {
1079 await api.post(
1080 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1081 {},
1082 adminHeaders
1083 )
1084
1085 let response = await api.post(
1086 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1087 {
1088 items: [{ variant_id: product.variants[0].id, quantity: 1 }],
1089 },
1090 adminHeaders
1091 )
1092
1093 let preview = response.data.draft_order_preview
1094 let firstItem = preview.items.find(
1095 (item) => item.variant_id === product.variants[0].id
1096 )
1097
1098 expect(preview.discount_total).toBe(0)
1099 expect(firstItem?.discount_total ?? 0).toBe(0)
1100 expect(firstItem?.adjustments ?? []).toHaveLength(0)
1101
1102 response = await api.post(
1103 `/admin/draft-orders/${testDraftOrder.id}/edit/promotions`,
1104 {
1105 promo_codes: [promotion.code],
1106 },
1107 adminHeaders
1108 )
1109
1110 preview = response.data.draft_order_preview
1111 firstItem = preview.items.find(
1112 (item) => item.variant_id === product.variants[0].id
1113 )
1114
1115 expect(preview.discount_total).toBe(100)
1116 expect(firstItem?.discount_total).toBe(100)
1117 expect(firstItem?.adjustments).toEqual(
1118 expect.arrayContaining([
1119 expect.objectContaining({
1120 code: promotion.code,
1121 amount: 100,
1122 promotion_id: promotion.id,
1123 }),
1124 ])
1125 )
1126
1127 response = await api.post(
1128 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1129 {
1130 items: [{ variant_id: product.variants[1].id, quantity: 1 }],
1131 },
1132 adminHeaders
1133 )
1134
1135 preview = response.data.draft_order_preview
1136 const itemsByVariant = new Map(
1137 preview.items.map((item) => [item.variant_id, item])
1138 )
1139
1140 const firstItemAfter = itemsByVariant.get(product.variants[0].id)
1141 const secondItemAfter = itemsByVariant.get(product.variants[1].id)
1142
1143 expect(preview.discount_total).toBe(200)
1144 expect(firstItemAfter?.discount_total).toBe(100)
1145 expect(secondItemAfter?.discount_total).toBe(100)
1146 expect(firstItemAfter?.adjustments).toEqual(
1147 expect.arrayContaining([
1148 expect.objectContaining({
1149 code: promotion.code,
1150 amount: 100,
1151 promotion_id: promotion.id,
1152 }),
1153 ])
1154 )
1155 expect(secondItemAfter?.adjustments).toEqual(
1156 expect.arrayContaining([
1157 expect.objectContaining({
1158 code: promotion.code,
1159 amount: 100,
1160 promotion_id: promotion.id,
1161 }),
1162 ])
1163 )
1164 })
1165 })
1166
1167 describe("with promotion rules", () => {
1168 let taggedProduct
1169 let untaggedProduct
1170 let taggedVariant
1171 let untaggedVariant
1172 let tag
1173 let promotion
1174
1175 beforeEach(async () => {
1176 tag = (
1177 await api.post(
1178 "/admin/product-tags",
1179 { value: "promo-tag" },
1180 adminHeaders
1181 )
1182 ).data.product_tag
1183
1184 taggedProduct = (
1185 await api.post(
1186 "/admin/products",
1187 {
1188 title: "Tagged Shirt",
1189 status: ProductStatus.PUBLISHED,
1190 tags: [{ id: tag.id }],
1191 options: [{ title: "size", values: ["default"] }],
1192 variants: [
1193 {
1194 title: "Tagged Variant",
1195 options: { size: "default" },
1196 manage_inventory: false,
1197 prices: [
1198 {
1199 currency_code: "usd",
1200 amount: 10,
1201 },
1202 ],
1203 },
1204 ],
1205 },
1206 adminHeaders
1207 )
1208 ).data.product
1209
1210 untaggedProduct = (
1211 await api.post(
1212 "/admin/products",
1213 {
1214 title: "Untagged Shirt",
1215 status: ProductStatus.PUBLISHED,
1216 options: [{ title: "size", values: ["default"] }],
1217 variants: [
1218 {
1219 title: "Untagged Variant",
1220 options: { size: "default" },
1221 manage_inventory: false,
1222 prices: [
1223 {
1224 currency_code: "usd",
1225 amount: 10,
1226 },
1227 ],
1228 },
1229 ],
1230 },
1231 adminHeaders
1232 )
1233 ).data.product
1234
1235 taggedVariant = taggedProduct.variants[0]
1236 untaggedVariant = untaggedProduct.variants[0]
1237
1238 promotion = (
1239 await api.post(
1240 `/admin/promotions`,
1241 {
1242 code: "TAG_ONLY_PROMO",
1243 type: PromotionType.STANDARD,
1244 status: PromotionStatus.ACTIVE,
1245 application_method: {
1246 type: "fixed",
1247 target_type: "items",
1248 allocation: "each",
1249 value: 5,
1250 max_quantity: 1,
1251 currency_code: "usd",
1252 target_rules: [
1253 {
1254 attribute: "items.product.tags.id",
1255 operator: "in",
1256 values: [tag.id],
1257 },
1258 ],
1259 },
1260 },
1261 adminHeaders
1262 )
1263 ).data.promotion
1264 })
1265
1266 it("should apply the promotion only to items matching the product tag rule", async () => {
1267 await api.post(
1268 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1269 {},
1270 adminHeaders
1271 )
1272
1273 await api.post(
1274 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1275 {
1276 items: [
1277 {
1278 variant_id: taggedVariant.id,
1279 quantity: 1,
1280 },
1281 {
1282 variant_id: untaggedVariant.id,
1283 quantity: 1,
1284 },
1285 ],
1286 },
1287 adminHeaders
1288 )
1289
1290 await api.post(
1291 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1292 {},
1293 adminHeaders
1294 )
1295
1296 await api.post(
1297 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1298 {},
1299 adminHeaders
1300 )
1301
1302 const response = await api.post(
1303 `/admin/draft-orders/${testDraftOrder.id}/edit/promotions`,
1304 { promo_codes: [promotion.code] },
1305 adminHeaders
1306 )
1307
1308 expect(response.status).toBe(200)
1309
1310 await api.post(
1311 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1312 {},
1313 adminHeaders
1314 )
1315
1316 const order = (
1317 await api.get(
1318 `/admin/draft-orders/${testDraftOrder.id}?fields=+discount_total,+item_discount_total,+items.discount_total,+items.discount_tax_total,+items.adjustments.*`,
1319 adminHeaders
1320 )
1321 ).data.draft_order
1322
1323 const preview = response.data.draft_order_preview
1324 const taggedItem = preview.items.find(
1325 (item) => item.product_id === taggedProduct.id
1326 )
1327 const untaggedItem = preview.items.find(
1328 (item) => item.product_id === untaggedProduct.id
1329 )
1330
1331 expect(taggedItem?.adjustments?.length).toBe(1)
1332 expect(taggedItem?.adjustments?.[0]).toEqual(
1333 expect.objectContaining({
1334 code: promotion.code,
1335 })
1336 )
1337 expect(untaggedItem?.adjustments?.length ?? 0).toBe(0)
1338 const taggedDiscountTotal = taggedItem?.discount_total ?? 0
1339 // 5 * (1 + taxRate / 100)
1340 expect(taggedDiscountTotal).toBe(5.1)
1341 expect(preview.item_discount_total).toBe(5.1)
1342 expect(preview.discount_total).toBe(5.1)
1343 expect(untaggedItem?.discount_total ?? 0).toBe(0)
1344
1345 const taggedOrderItem = order.items.find(
1346 (item) => item.product_id === taggedProduct.id
1347 )
1348 const untaggedOrderItem = order.items.find(
1349 (item) => item.product_id === untaggedProduct.id
1350 )
1351
1352 expect(taggedOrderItem?.adjustments?.length).toBe(1)
1353 expect(taggedOrderItem?.adjustments?.[0]).toEqual(
1354 expect.objectContaining({
1355 code: promotion.code,
1356 })
1357 )
1358 expect(untaggedOrderItem?.adjustments?.length ?? 0).toBe(0)
1359 expect(order.item_discount_total).toBe(5.1)
1360 expect(order.discount_total).toBe(5.1)
1361 })
1362 })
1363 })
1364
1365 describe("DELETE /draft-orders/:id/shipping-options/methods/:method_id", () => {
1366 let product
1367 let edit
1368
1369 beforeEach(async () => {
1370 const inventoryItem = (
1371 await api.post(
1372 `/admin/inventory-items`,
1373 { sku: "shirt" },
1374 adminHeaders
1375 )
1376 ).data.inventory_item
1377
1378 await api.post(
1379 `/admin/inventory-items/${inventoryItem.id}/location-levels`,
1380 {
1381 location_id: stockLocation.id,
1382 stocked_quantity: 10,
1383 },
1384 adminHeaders
1385 )
1386
1387 product = (
1388 await api.post(
1389 "/admin/products",
1390 {
1391 title: "Shirt",
1392 status: ProductStatus.PUBLISHED,
1393 options: [{ title: "size", values: ["large", "small"] }],
1394 variants: [
1395 {
1396 title: "L shirt",
1397 options: { size: "large" },
1398 inventory_items: [
1399 {
1400 inventory_item_id: inventoryItem.id,
1401 required_quantity: 1,
1402 },
1403 ],
1404 prices: [
1405 {
1406 currency_code: "usd",
1407 amount: 10,
1408 },
1409 ],
1410 },
1411 {
1412 title: "S shirt",
1413 options: { size: "small" },
1414 inventory_items: [
1415 {
1416 inventory_item_id: inventoryItem.id,
1417 required_quantity: 1,
1418 },
1419 ],
1420 prices: [
1421 {
1422 currency_code: "usd",
1423 amount: 10,
1424 },
1425 ],
1426 },
1427 ],
1428 },
1429 adminHeaders
1430 )
1431 ).data.product
1432
1433 edit = (
1434 await api.post(
1435 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1436 {},
1437 adminHeaders
1438 )
1439 ).data.draft_order_preview
1440
1441 await api.post(
1442 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1443 {
1444 items: [{ variant_id: product.variants[0].id, quantity: 1 }],
1445 },
1446 adminHeaders
1447 )
1448
1449 await api.post(
1450 `/admin/draft-orders/${testDraftOrder.id}/edit/shipping-methods`,
1451 {
1452 shipping_option_id: shippingOption.id,
1453 },
1454 adminHeaders
1455 )
1456
1457 edit = (
1458 await api.post(
1459 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1460 {},
1461 adminHeaders
1462 )
1463 ).data.draft_order_preview
1464 })
1465
1466 it("should delete a shipping method from the draft order", async () => {
1467 edit = (
1468 await api.post(
1469 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1470 {},
1471 adminHeaders
1472 )
1473 ).data.draft_order_preview
1474
1475 const response = await api.delete(
1476 `/admin/draft-orders/${testDraftOrder.id}/edit/shipping-methods/method/${edit.shipping_methods[0].id}`,
1477 adminHeaders
1478 )
1479
1480 expect(response.status).toBe(200)
1481 expect(response.data.draft_order_preview.shipping_methods.length).toBe(
1482 0
1483 )
1484
1485 await api.post(
1486 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1487 {},
1488 adminHeaders
1489 )
1490
1491 const order = (
1492 await api.get(
1493 `/admin/draft-orders/${testDraftOrder.id}`,
1494 adminHeaders
1495 )
1496 ).data.draft_order
1497
1498 expect(order.shipping_methods.length).toBe(0)
1499 })
1500
1501 it("should ensure that the shipping method is removed from the order and tax lines are updated with multiple shipping methods", async () => {
1502 /**
1503 * Add Heavy SO
1504 */
1505
1506 edit = (
1507 await api.post(
1508 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1509 {},
1510 adminHeaders
1511 )
1512 ).data.draft_order_preview
1513
1514 await api.post(
1515 `/admin/draft-orders/${testDraftOrder.id}/edit/shipping-methods`,
1516 {
1517 shipping_option_id: shippingOptionHeavy.id,
1518 },
1519 adminHeaders
1520 )
1521
1522 edit = (
1523 await api.post(
1524 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1525 {},
1526 adminHeaders
1527 )
1528 ).data.draft_order_preview
1529
1530 /**
1531 * Tax rate -> 2%
1532 *
1533 * One product -> 10$
1534 * Shipping method 1 -> 5$
1535 * Shipping method 2 -> 10$
1536 */
1537
1538 expect(edit).toEqual(
1539 expect.objectContaining({
1540 total: 25.5,
1541 subtotal: 25,
1542 tax_total: 0.5,
1543
1544 items: [
1545 expect.objectContaining({
1546 subtotal: 10,
1547 total: 10.2,
1548 tax_total: 0.2,
1549 tax_lines: [
1550 expect.objectContaining({
1551 rate: 2,
1552 }),
1553 ],
1554 }),
1555 ],
1556 shipping_methods: expect.arrayContaining([
1557 expect.objectContaining({
1558 shipping_option_id: shippingOption.id,
1559 amount: 5,
1560 subtotal: 5,
1561 total: 5.1,
1562 tax_total: 0.1,
1563 }),
1564 expect.objectContaining({
1565 shipping_option_id: shippingOptionHeavy.id,
1566 amount: 10,
1567 subtotal: 10,
1568 total: 10.2,
1569 tax_total: 0.2,
1570 }),
1571 ]),
1572 })
1573 )
1574
1575 /**
1576 * Remove Heavy shipping method
1577 */
1578
1579 edit = (
1580 await api.post(
1581 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1582 {},
1583 adminHeaders
1584 )
1585 ).data.draft_order_preview
1586
1587 const response = await api.delete(
1588 `/admin/draft-orders/${
1589 testDraftOrder.id
1590 }/edit/shipping-methods/method/${
1591 edit.shipping_methods.find(
1592 (sm) => sm.shipping_option_id === shippingOptionHeavy.id
1593 ).id
1594 }`,
1595 adminHeaders
1596 )
1597
1598 expect(response.status).toBe(200)
1599 expect(response.data.draft_order_preview.shipping_methods.length).toBe(
1600 1
1601 )
1602
1603 await api.post(
1604 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1605 {},
1606 adminHeaders
1607 )
1608
1609 const order = (
1610 await api.get(
1611 `/admin/draft-orders/${testDraftOrder.id}?fields=+total,+subtotal,+tax_total,+items.subtotal,+items.total,+items.tax_total,+shipping_methods.amount,+shipping_methods.subtotal,+shipping_methods.total,+shipping_methods.tax_total`,
1612 adminHeaders
1613 )
1614 ).data.draft_order
1615
1616 expect(order).toEqual(
1617 expect.objectContaining({
1618 total: 15.3,
1619 subtotal: 15,
1620 tax_total: 0.3,
1621
1622 items: [
1623 expect.objectContaining({
1624 subtotal: 10,
1625 total: 10.2,
1626 tax_total: 0.2,
1627 tax_lines: [
1628 expect.objectContaining({
1629 rate: 2,
1630 }),
1631 ],
1632 }),
1633 ],
1634 shipping_methods: expect.arrayContaining([
1635 expect.objectContaining({
1636 shipping_option_id: shippingOption.id,
1637 amount: 5,
1638 subtotal: 5,
1639 total: 5.1,
1640 tax_total: 0.1,
1641 }),
1642 ]),
1643 })
1644 )
1645 })
1646 })
1647
1648 describe("POST /draft-orders/:id/edit/items", () => {
1649 let customer
1650 let customerGroup
1651 let draftOrder
1652 let product
1653
1654 beforeEach(async () => {
1655 const inventoryItem = (
1656 await api.post(
1657 `/admin/inventory-items`,
1658 { sku: "shirt" },
1659 adminHeaders
1660 )
1661 ).data.inventory_item
1662
1663 await api.post(
1664 `/admin/inventory-items/${inventoryItem.id}/location-levels`,
1665 {
1666 location_id: stockLocation.id,
1667 stocked_quantity: 10,
1668 },
1669 adminHeaders
1670 )
1671
1672 product = (
1673 await api.post(
1674 "/admin/products",
1675 {
1676 title: "Shirt",
1677 status: ProductStatus.PUBLISHED,
1678 options: [{ title: "size", values: ["large"] }],
1679 variants: [
1680 {
1681 title: "L shirt",
1682 options: { size: "large" },
1683 manage_inventory: true,
1684 inventory_items: [
1685 {
1686 inventory_item_id: inventoryItem.id,
1687 required_quantity: 1,
1688 },
1689 ],
1690 prices: [
1691 {
1692 currency_code: "usd",
1693 amount: 10,
1694 },
1695 ],
1696 },
1697 ],
1698 },
1699 adminHeaders
1700 )
1701 ).data.product
1702
1703 customer = (
1704 await api.post(
1705 "/admin/customers",
1706 {
1707 first_name: "Tony",
1708 last_name: "Stark",
1709 email: "tony@stark-industries.com",
1710 },
1711 adminHeaders
1712 )
1713 ).data.customer
1714
1715 customerGroup = (
1716 await api.post(
1717 "/admin/customer-groups",
1718 { name: "VIP" },
1719 adminHeaders
1720 )
1721 ).data.customer_group
1722
1723 await api.post(
1724 `/admin/customer-groups/${customerGroup.id}/customers`,
1725 { add: [customer.id] },
1726 adminHeaders
1727 )
1728
1729 await api.post(
1730 `/admin/price-lists`,
1731 {
1732 title: "VIP price list",
1733 description: "test",
1734 status: PriceListStatus.ACTIVE,
1735 type: PriceListType.SALE,
1736 prices: [
1737 {
1738 amount: 2,
1739 currency_code: "usd",
1740 variant_id: product.variants[0].id,
1741 },
1742 ],
1743 rules: {
1744 "customer.groups.id": [customerGroup.id],
1745 },
1746 },
1747 adminHeaders
1748 )
1749
1750 draftOrder = (
1751 await api.post(
1752 "/admin/draft-orders",
1753 {
1754 customer_id: customer.id,
1755 region_id: region.id,
1756 sales_channel_id: salesChannel.id,
1757 shipping_address: {
1758 address_1: "123 Main St",
1759 city: "Anytown",
1760 country_code: "US",
1761 postal_code: "12345",
1762 first_name: "Tony",
1763 },
1764 },
1765 adminHeaders
1766 )
1767 ).data.draft_order
1768 })
1769
1770 it("should apply price from price list associated to a customer group when customer rules match", async () => {
1771 await api.post(
1772 `/admin/draft-orders/${draftOrder.id}/edit`,
1773 {},
1774 adminHeaders
1775 )
1776
1777 const response = await api.post(
1778 `/admin/draft-orders/${draftOrder.id}/edit/items`,
1779 {
1780 items: [
1781 {
1782 variant_id: product.variants[0].id,
1783 quantity: 1,
1784 },
1785 ],
1786 },
1787 adminHeaders
1788 )
1789
1790 const preview = response.data.draft_order_preview
1791
1792 expect(response.status).toBe(200)
1793 expect(preview.items).toEqual(
1794 expect.arrayContaining([
1795 expect.objectContaining({
1796 variant_id: product.variants[0].id,
1797 unit_price: 2,
1798 compare_at_unit_price: 10,
1799 quantity: 1,
1800 }),
1801 ])
1802 )
1803 })
1804
1805 it("should apply price from price list associated to a customer group when items are provided at draft order creation", async () => {
1806 const created = (
1807 await api.post(
1808 "/admin/draft-orders",
1809 {
1810 customer_id: customer.id,
1811 region_id: region.id,
1812 sales_channel_id: salesChannel.id,
1813 shipping_address: {
1814 address_1: "123 Main St",
1815 city: "Anytown",
1816 country_code: "US",
1817 postal_code: "12345",
1818 first_name: "Tony",
1819 },
1820 items: [
1821 {
1822 variant_id: product.variants[0].id,
1823 quantity: 1,
1824 },
1825 ],
1826 },
1827 adminHeaders
1828 )
1829 ).data.draft_order
1830
1831 const draftOrderWithItems = (
1832 await api.get(
1833 `/admin/draft-orders/${created.id}?fields=*items`,
1834 adminHeaders
1835 )
1836 ).data.draft_order
1837
1838 expect(draftOrderWithItems.items).toEqual(
1839 expect.arrayContaining([
1840 expect.objectContaining({
1841 variant_id: product.variants[0].id,
1842 unit_price: 2,
1843 quantity: 1,
1844 }),
1845 ])
1846 )
1847 })
1848 })
1849
1850 describe("POST /draft-orders/:id/edit/items - allow_backorder", () => {
1851 let outOfStockProduct
1852 let outOfStockInventoryItem
1853
1854 beforeEach(async () => {
1855 outOfStockInventoryItem = (
1856 await api.post(
1857 `/admin/inventory-items`,
1858 { sku: "out-of-stock-sku" },
1859 adminHeaders
1860 )
1861 ).data.inventory_item
1862
1863 // A location level exists for the sales channel, but with no
1864 // available stock, so the variant is out of stock.
1865 await api.post(
1866 `/admin/inventory-items/${outOfStockInventoryItem.id}/location-levels`,
1867 {
1868 location_id: stockLocation.id,
1869 stocked_quantity: 0,
1870 },
1871 adminHeaders
1872 )
1873
1874 outOfStockProduct = (
1875 await api.post(
1876 "/admin/products",
1877 {
1878 title: "Out of stock product",
1879 status: ProductStatus.PUBLISHED,
1880 options: [{ title: "size", values: ["large"] }],
1881 variants: [
1882 {
1883 title: "L shirt",
1884 options: { size: "large" },
1885 manage_inventory: true,
1886 allow_backorder: false,
1887 inventory_items: [
1888 {
1889 inventory_item_id: outOfStockInventoryItem.id,
1890 required_quantity: 1,
1891 },
1892 ],
1893 prices: [{ currency_code: "usd", amount: 10 }],
1894 },
1895 ],
1896 },
1897 adminHeaders
1898 )
1899 ).data.product
1900
1901 await api.post(
1902 `/admin/draft-orders/${testDraftOrder.id}/edit`,
1903 {},
1904 adminHeaders
1905 )
1906 })
1907
1908 it("should not allow adding an out-of-stock variant without allow_backorder", async () => {
1909 const variantId = outOfStockProduct.variants[0].id
1910
1911 const error = await api
1912 .post(
1913 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1914 { items: [{ variant_id: variantId, quantity: 1 }] },
1915 adminHeaders
1916 )
1917 .catch((e) => e)
1918
1919 expect(error.response.status).toBe(400)
1920 expect(error.response.data.message).toContain(
1921 "does not have the required inventory"
1922 )
1923 })
1924
1925 it("should allow adding an out-of-stock variant when allow_backorder is true on the item", async () => {
1926 const variantId = outOfStockProduct.variants[0].id
1927
1928 const response = await api.post(
1929 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1930 {
1931 items: [
1932 { variant_id: variantId, quantity: 1, allow_backorder: true },
1933 ],
1934 },
1935 adminHeaders
1936 )
1937
1938 expect(response.status).toBe(200)
1939 expect(response.data.draft_order_preview.items).toEqual(
1940 expect.arrayContaining([
1941 expect.objectContaining({
1942 variant_id: variantId,
1943 quantity: 1,
1944 }),
1945 ])
1946 )
1947 })
1948
1949 it("should convert a draft order with an out-of-stock item added with allow_backorder", async () => {
1950 const variantId = outOfStockProduct.variants[0].id
1951
1952 await api.post(
1953 `/admin/draft-orders/${testDraftOrder.id}/edit/items`,
1954 {
1955 items: [
1956 { variant_id: variantId, quantity: 2, allow_backorder: true },
1957 ],
1958 },
1959 adminHeaders
1960 )
1961
1962 await api.post(
1963 `/admin/draft-orders/${testDraftOrder.id}/edit/confirm`,
1964 {},
1965 adminHeaders
1966 )
1967
1968 const response = await api.post(
1969 `/admin/draft-orders/${testDraftOrder.id}/convert-to-order`,
1970 {},
1971 adminHeaders
1972 )
1973
1974 expect(response.status).toBe(200)
1975 expect(response.data.order.status).toBe("pending")
1976
1977 const reservations = (
1978 await api.get(
1979 `/admin/reservations?inventory_item_id[]=${outOfStockInventoryItem.id}`,
1980 adminHeaders
1981 )
1982 ).data.reservations
1983
1984 expect(reservations).toEqual([
1985 expect.objectContaining({
1986 inventory_item_id: outOfStockInventoryItem.id,
1987 quantity: 2,
1988 }),
1989 ])
1990 })
1991 })
1992 },
1993 })