Raw
1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { IOrderModuleService, IPromotionModuleService } from "@medusajs/types"
3 import {
4 ContainerRegistrationKeys,
5 Modules,
6 ProductStatus,
7 PromotionStatus,
8 PromotionType,
9 RuleOperator,
10 } from "@medusajs/utils"
11 import {
12 adminHeaders,
13 createAdminUser,
14 } from "../../../helpers/create-admin-user"
15 import { setupTaxStructure } from "../../../modules/__tests__/fixtures/tax"
16
17 jest.setTimeout(300000)
18
19 medusaIntegrationTestRunner({
20 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
21 let order, order2
22 let returnShippingOption
23 let outboundShippingOption
24 let shippingProfile
25 let fulfillmentSet
26 let returnReason
27 let inventoryItem
28 let inventoryItemExtra
29 let inventoryItemExtra2
30 let location
31 let productExtra
32 let productExtra2
33 const shippingProviderId = "manual_test-provider"
34
35 beforeAll(async () => {
36 const container = getContainer()
37 await createAdminUser(dbConnection, adminHeaders, container)
38
39 const region = (
40 await api.post(
41 "/admin/regions",
42 {
43 name: "test-region",
44 currency_code: "usd",
45 },
46 adminHeaders
47 )
48 ).data.region
49
50 shippingProfile = (
51 await api.post(
52 `/admin/shipping-profiles`,
53 {
54 name: "Test",
55 type: "default",
56 },
57 adminHeaders
58 )
59 ).data.shipping_profile
60
61 const customer = (
62 await api.post(
63 "/admin/customers",
64 {
65 first_name: "joe",
66 email: "joe@admin.com",
67 },
68 adminHeaders
69 )
70 ).data.customer
71
72 const salesChannel = (
73 await api.post(
74 "/admin/sales-channels",
75 {
76 name: "Test channel",
77 },
78 adminHeaders
79 )
80 ).data.sales_channel
81
82 const product = (
83 await api.post(
84 "/admin/products",
85 {
86 title: "Test product",
87 status: ProductStatus.PUBLISHED,
88 shipping_profile_id: shippingProfile.id,
89 options: [{ title: "size", values: ["large", "small"] }],
90 variants: [
91 {
92 title: "Test variant",
93 sku: "test-variant",
94 options: { size: "large" },
95 prices: [
96 {
97 currency_code: "usd",
98 amount: 10,
99 },
100 ],
101 },
102 ],
103 },
104 adminHeaders
105 )
106 ).data.product
107
108 productExtra = (
109 await api.post(
110 "/admin/products",
111 {
112 title: "Extra product",
113 status: ProductStatus.PUBLISHED,
114 shipping_profile_id: shippingProfile.id,
115 options: [{ title: "size", values: ["large", "small"] }],
116 variants: [
117 {
118 title: "my variant",
119 sku: "variant-sku",
120 options: { size: "large" },
121 prices: [
122 {
123 currency_code: "usd",
124 amount: 123456.1234657890123456789,
125 },
126 ],
127 },
128 ],
129 },
130 adminHeaders
131 )
132 ).data.product
133
134 productExtra2 = (
135 await api.post(
136 "/admin/products",
137 {
138 title: "Extra product 2, same price",
139 status: ProductStatus.PUBLISHED,
140 shipping_profile_id: shippingProfile.id,
141 options: [{ title: "size", values: ["large", "small"] }],
142 variants: [
143 {
144 title: "my variant 2",
145 sku: "variant-sku-2",
146 options: { size: "large" },
147 prices: [
148 {
149 currency_code: "usd",
150 amount: 25,
151 },
152 ],
153 },
154 ],
155 },
156 adminHeaders
157 )
158 ).data.product
159
160 returnReason = (
161 await api.post(
162 "/admin/return-reasons",
163 {
164 value: "return-reason-test",
165 label: "Test return reason",
166 },
167 adminHeaders
168 )
169 ).data.return_reason
170
171 const orderModule = container.resolve(Modules.ORDER)
172
173 order = await orderModule.createOrders({
174 region_id: region.id,
175 email: "foo@bar.com",
176 items: [
177 {
178 title: "Custom Item 2",
179 variant_id: product.variants[0].id,
180 quantity: 2,
181 unit_price: 25,
182 },
183 ],
184 sales_channel_id: salesChannel.id,
185 shipping_address: {
186 first_name: "Test",
187 last_name: "Test",
188 address_1: "Test",
189 city: "Test",
190 country_code: "US",
191 postal_code: "12345",
192 phone: "12345",
193 },
194 billing_address: {
195 first_name: "Test",
196 last_name: "Test",
197 address_1: "Test",
198 city: "Test",
199 country_code: "US",
200 postal_code: "12345",
201 },
202 shipping_methods: [
203 {
204 name: "Test shipping method",
205 amount: 10,
206 data: {},
207 tax_lines: [
208 {
209 description: "shipping Tax 1",
210 tax_rate_id: "tax_usa_shipping",
211 code: "code",
212 rate: 10,
213 },
214 ],
215 },
216 ],
217 currency_code: "usd",
218 customer_id: customer.id,
219 })
220
221 order2 = await orderModule.createOrders({
222 region_id: region.id,
223 email: "foo@bar2.com",
224 items: [
225 {
226 title: "Custom Iasdasd2",
227 quantity: 1,
228 unit_price: 20,
229 },
230 ],
231 sales_channel_id: salesChannel.id,
232 shipping_address: {
233 first_name: "Test",
234 last_name: "Test",
235 address_1: "Test",
236 city: "Test",
237 country_code: "US",
238 postal_code: "12345",
239 phone: "12345",
240 },
241 billing_address: {
242 first_name: "Test",
243 last_name: "Test",
244 address_1: "Test",
245 city: "Test",
246 country_code: "US",
247 postal_code: "12345",
248 },
249 currency_code: "usd",
250 customer_id: customer.id,
251 })
252
253 location = (
254 await api.post(
255 `/admin/stock-locations`,
256 {
257 name: "Test location",
258 },
259 adminHeaders
260 )
261 ).data.stock_location
262
263 location = (
264 await api.post(
265 `/admin/stock-locations/${location.id}/fulfillment-sets?fields=*fulfillment_sets`,
266 {
267 name: "Test",
268 type: "test-type",
269 },
270 adminHeaders
271 )
272 ).data.stock_location
273
274 fulfillmentSet = (
275 await api.post(
276 `/admin/fulfillment-sets/${location.fulfillment_sets[0].id}/service-zones`,
277 {
278 name: "Test",
279 geo_zones: [{ type: "country", country_code: "us" }],
280 },
281 adminHeaders
282 )
283 ).data.fulfillment_set
284
285 inventoryItem = (
286 await api.post(
287 `/admin/inventory-items`,
288 { sku: "inv-1234" },
289 adminHeaders
290 )
291 ).data.inventory_item
292
293 await api.post(
294 `/admin/inventory-items/${inventoryItem.id}/location-levels`,
295 {
296 location_id: location.id,
297 stocked_quantity: 2,
298 },
299 adminHeaders
300 )
301
302 inventoryItemExtra = (
303 await api.get(`/admin/inventory-items?sku=variant-sku`, adminHeaders)
304 ).data.inventory_items[0]
305
306 inventoryItemExtra2 = (
307 await api.get(`/admin/inventory-items?sku=variant-sku-2`, adminHeaders)
308 ).data.inventory_items[0]
309
310 await api.post(
311 `/admin/inventory-items/${inventoryItemExtra.id}/location-levels`,
312 {
313 location_id: location.id,
314 stocked_quantity: 4,
315 },
316 adminHeaders
317 )
318
319 await api.post(
320 `/admin/inventory-items/${inventoryItemExtra2.id}/location-levels`,
321 {
322 location_id: location.id,
323 stocked_quantity: 2,
324 },
325 adminHeaders
326 )
327
328 const remoteLink = container.resolve(
329 ContainerRegistrationKeys.REMOTE_LINK
330 )
331
332 await remoteLink.create([
333 {
334 [Modules.STOCK_LOCATION]: {
335 stock_location_id: location.id,
336 },
337 [Modules.FULFILLMENT]: {
338 fulfillment_provider_id: shippingProviderId,
339 },
340 },
341 {
342 [Modules.STOCK_LOCATION]: {
343 stock_location_id: location.id,
344 },
345 [Modules.FULFILLMENT]: {
346 fulfillment_set_id: fulfillmentSet.id,
347 },
348 },
349 {
350 [Modules.SALES_CHANNEL]: {
351 sales_channel_id: salesChannel.id,
352 },
353 [Modules.STOCK_LOCATION]: {
354 stock_location_id: location.id,
355 },
356 },
357 {
358 [Modules.PRODUCT]: {
359 variant_id: product.variants[0].id,
360 },
361 [Modules.INVENTORY]: {
362 inventory_item_id: inventoryItem.id,
363 },
364 },
365 {
366 [Modules.PRODUCT]: {
367 variant_id: productExtra.variants[0].id,
368 },
369 [Modules.INVENTORY]: {
370 inventory_item_id: inventoryItemExtra.id,
371 },
372 },
373 {
374 [Modules.PRODUCT]: {
375 variant_id: productExtra2.variants[0].id,
376 },
377 [Modules.INVENTORY]: {
378 inventory_item_id: inventoryItemExtra2.id,
379 },
380 },
381 ])
382
383 // create reservation for inventory item that is initially on the order
384 const inventoryModule = container.resolve(Modules.INVENTORY)
385 await inventoryModule.createReservationItems([
386 {
387 inventory_item_id: inventoryItem.id,
388 location_id: location.id,
389 quantity: 2,
390 line_item_id: order.items[0].id,
391 },
392 ])
393
394 const shippingOptionPayload = {
395 name: "Return shipping",
396 service_zone_id: fulfillmentSet.service_zones[0].id,
397 shipping_profile_id: shippingProfile.id,
398 provider_id: shippingProviderId,
399 price_type: "flat",
400 type: {
401 label: "Test type",
402 description: "Test description",
403 code: "test-code",
404 },
405 prices: [
406 {
407 currency_code: "usd",
408 amount: 1000,
409 },
410 ],
411 rules: [
412 {
413 operator: RuleOperator.EQ,
414 attribute: "is_return",
415 value: "true",
416 },
417 ],
418 }
419
420 const outboundShippingOptionPayload = {
421 name: "Oubound shipping",
422 service_zone_id: fulfillmentSet.service_zones[0].id,
423 shipping_profile_id: shippingProfile.id,
424 provider_id: shippingProviderId,
425 price_type: "flat",
426 type: {
427 label: "Test type",
428 description: "Test description",
429 code: "test-code",
430 },
431 prices: [
432 {
433 currency_code: "usd",
434 amount: 20,
435 },
436 ],
437 rules: [
438 {
439 operator: RuleOperator.EQ,
440 attribute: "is_return",
441 value: "false",
442 },
443 {
444 operator: RuleOperator.EQ,
445 attribute: "enabled_in_store",
446 value: "true",
447 },
448 ],
449 }
450 outboundShippingOption = (
451 await api.post(
452 "/admin/shipping-options",
453 outboundShippingOptionPayload,
454 adminHeaders
455 )
456 ).data.shipping_option
457
458 returnShippingOption = (
459 await api.post(
460 "/admin/shipping-options",
461 shippingOptionPayload,
462 adminHeaders
463 )
464 ).data.shipping_option
465
466 const item = order.items[0]
467
468 await api.post(
469 `/admin/orders/${order.id}/fulfillments`,
470 {
471 items: [
472 {
473 id: item.id,
474 quantity: 2,
475 },
476 ],
477 },
478 adminHeaders
479 )
480
481 await api.post(
482 `/admin/orders/${order2.id}/fulfillments`,
483 {
484 items: [
485 {
486 id: order2.items[0].id,
487 quantity: 1,
488 },
489 ],
490 },
491 adminHeaders
492 )
493
494 await setupTaxStructure(container.resolve(Modules.TAX))
495
496 await dbUtils.snapshot()
497 })
498
499 describe("Exchanges lifecycle", () => {
500 it("test full exchange flow", async () => {
501 const orderBefore = (
502 await api.get(`/admin/orders/${order.id}`, adminHeaders)
503 ).data.order
504
505 let result = await api.post(
506 "/admin/exchanges",
507 {
508 order_id: order.id,
509 description: "Test",
510 },
511 adminHeaders
512 )
513
514 expect(result.data.exchange.created_by).toEqual(expect.any(String))
515
516 const exchangeId = result.data.exchange.id
517
518 const item = order.items[0]
519
520 result = await api.post(
521 `/admin/exchanges/${exchangeId}/inbound/items`,
522 {
523 items: [
524 {
525 id: item.id,
526 reason_id: returnReason.id,
527 quantity: 2,
528 },
529 ],
530 },
531 adminHeaders
532 )
533
534 // New Item
535 result = await api.post(
536 `/admin/exchanges/${exchangeId}/outbound/items`,
537 {
538 items: [
539 {
540 variant_id: productExtra2.variants[0].id,
541 quantity: 2,
542 },
543 ],
544 },
545 adminHeaders
546 )
547
548 result = await api.post(
549 `/admin/exchanges/${exchangeId}/request`,
550 {},
551 adminHeaders
552 )
553 const returnId = result.data.exchange.return_id
554
555 result = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
556 .order
557
558 expect(orderBefore.total).toBe(61)
559 expect(result.total).toBe(112)
560
561 // receive return
562 await api.post(`/admin/returns/${returnId}/receive`, {}, adminHeaders)
563 await api.post(
564 `/admin/returns/${returnId}/receive-items`,
565 {
566 items: [
567 {
568 id: item.id,
569 quantity: 2,
570 },
571 ],
572 },
573 adminHeaders
574 )
575
576 await api.post(
577 `/admin/returns/${returnId}/receive/confirm`,
578 {},
579 adminHeaders
580 )
581
582 result = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
583 .order
584
585 expect(orderBefore.total).toBe(61)
586 expect(result.total).toBe(62) // +1 is from taxes of the new item
587 })
588
589 it("Full flow with 2 orders", async () => {
590 let result = await api.post(
591 "/admin/exchanges",
592 {
593 order_id: order.id,
594 description: "Test",
595 },
596 adminHeaders
597 )
598
599 expect(result.data.exchange.created_by).toEqual(expect.any(String))
600
601 const exchangeId = result.data.exchange.id
602
603 let r2 = await api.post(
604 "/admin/exchanges",
605 {
606 order_id: order2.id,
607 },
608 adminHeaders
609 )
610
611 const exchangeId2 = r2.data.exchange.id
612 const item2 = order2.items[0]
613
614 result = await api.post(
615 `/admin/exchanges/${exchangeId2}/inbound/items`,
616 {
617 items: [
618 {
619 id: item2.id,
620 quantity: 1,
621 },
622 ],
623 },
624 adminHeaders
625 )
626
627 await api.post(
628 `/admin/exchanges/${exchangeId2}/inbound/shipping-method`,
629 {
630 shipping_option_id: returnShippingOption.id,
631 },
632 adminHeaders
633 )
634
635 const { response } = await api
636 .post(`/admin/exchanges/${exchangeId2}/request`, {}, adminHeaders)
637 .catch((e) => e)
638
639 expect(response.data).toEqual({
640 type: "invalid_data",
641 message:
642 "Order exchange request should have at least 1 item inbound and 1 item outbound",
643 })
644
645 await api.post(
646 `/admin/exchanges/${exchangeId2}/outbound/items`,
647 {
648 items: [
649 {
650 variant_id: productExtra.variants[0].id,
651 quantity: 2,
652 },
653 ],
654 },
655 adminHeaders
656 )
657
658 await api.post(
659 `/admin/exchanges/${exchangeId2}/request`,
660 {},
661 adminHeaders
662 )
663
664 const item = order.items[0]
665
666 result = await api.post(
667 `/admin/exchanges/${exchangeId}/inbound/items`,
668 {
669 items: [
670 {
671 id: item.id,
672 reason_id: returnReason.id,
673 quantity: 2,
674 },
675 ],
676 },
677 adminHeaders
678 )
679
680 await api.post(
681 `/admin/exchanges/${exchangeId}/inbound/shipping-method`,
682 {
683 shipping_option_id: returnShippingOption.id,
684 },
685 adminHeaders
686 )
687
688 // updated the requested quantity
689 const updateReturnItemActionId =
690 result.data.order_preview.items[0].actions[0].id
691
692 result = await api.post(
693 `/admin/exchanges/${exchangeId}/inbound/items/${updateReturnItemActionId}`,
694 {
695 quantity: 1,
696 },
697 adminHeaders
698 )
699
700 // New Items
701 result = await api.post(
702 `/admin/exchanges/${exchangeId}/outbound/items`,
703 {
704 items: [
705 {
706 variant_id: productExtra.variants[0].id,
707 quantity: 2,
708 },
709 ],
710 },
711 adminHeaders
712 )
713
714 result = await api.post(
715 `/admin/exchanges/${exchangeId}/request`,
716 {},
717 adminHeaders
718 )
719
720 result = (
721 await api.get(
722 `/admin/exchanges?fields=+metadata,*additional_items`,
723 adminHeaders
724 )
725 ).data.exchanges
726
727 expect(result).toHaveLength(2)
728 expect(result[0].additional_items).toHaveLength(1)
729 expect(result[0].canceled_at).toBeNull()
730
731 const return_ = (
732 await api.get(
733 `/admin/returns/${result[0].return_id}?fields=*fulfillments`,
734 adminHeaders
735 )
736 ).data.return
737
738 expect(return_.fulfillments).toHaveLength(1)
739 expect(return_.fulfillments[0].canceled_at).toBeNull()
740
741 // all exchange return fulfillments should be canceled before canceling the exchange
742 await api.post(
743 `/admin/fulfillments/${return_.fulfillments[0].id}/cancel`,
744 {},
745 adminHeaders
746 )
747
748 await api.post(
749 `/admin/exchanges/${exchangeId}/cancel`,
750 {},
751 adminHeaders
752 )
753
754 result = (
755 await api.get(
756 `/admin/exchanges?fields=*additional_items`,
757 adminHeaders
758 )
759 ).data.exchanges
760 expect(result[0].canceled_at).toBeDefined()
761 })
762
763 describe("with inbound and outbound items", () => {
764 let exchange
765 let orderPreview
766
767 beforeEach(async () => {
768 exchange = (
769 await api.post(
770 "/admin/exchanges",
771 {
772 order_id: order.id,
773 description: "Test",
774 },
775 adminHeaders
776 )
777 ).data.exchange
778
779 const item = order.items[0]
780
781 await api.post(
782 `/admin/exchanges/${exchange.id}/inbound/items`,
783 {
784 items: [
785 {
786 id: item.id,
787 reason_id: returnReason.id,
788 quantity: 2,
789 },
790 ],
791 },
792 adminHeaders
793 )
794
795 await api.post(
796 `/admin/exchanges/${exchange.id}/inbound/shipping-method`,
797 { shipping_option_id: returnShippingOption.id },
798 adminHeaders
799 )
800
801 await api.post(
802 `/admin/exchanges/${exchange.id}/outbound/items`,
803 {
804 items: [
805 {
806 variant_id: productExtra.variants[0].id,
807 quantity: 2,
808 },
809 ],
810 },
811 adminHeaders
812 )
813
814 await api.post(
815 `/admin/exchanges/${exchange.id}/outbound/shipping-method`,
816 { shipping_option_id: outboundShippingOption.id },
817 adminHeaders
818 )
819
820 orderPreview = (
821 await api.get(`/admin/orders/${order.id}/preview`, adminHeaders)
822 ).data.order
823 })
824
825 it("should remove outbound shipping method when outbound items are completely removed", async () => {
826 orderPreview = (
827 await api.get(`/admin/orders/${order.id}/preview`, adminHeaders)
828 ).data.order
829
830 const exchangeItems = orderPreview.items.filter(
831 (item) =>
832 !!item.actions?.find((action) => action.action === "ITEM_ADD")
833 )
834
835 const exchangeShippingMethods = orderPreview.shipping_methods.filter(
836 (item) =>
837 !!item.actions?.find(
838 (action) =>
839 action.action === "SHIPPING_ADD" && !action.return_id
840 )
841 )
842
843 expect(exchangeItems).toHaveLength(1)
844 expect(exchangeShippingMethods).toHaveLength(1)
845
846 await api.delete(
847 `/admin/exchanges/${exchange.id}/outbound/items/${exchangeItems[0].actions[0].id}`,
848 adminHeaders
849 )
850
851 orderPreview = (
852 await api.get(`/admin/orders/${order.id}/preview`, adminHeaders)
853 ).data.order
854
855 const updatedExchangeItems = orderPreview.items.filter(
856 (item) =>
857 !!item.actions?.find((action) => action.action === "ITEM_ADD")
858 )
859
860 const updatedClaimShippingMethods =
861 orderPreview.shipping_methods.filter(
862 (item) =>
863 !!item.actions?.find(
864 (action) =>
865 action.action === "SHIPPING_ADD" && !action.return_id
866 )
867 )
868
869 expect(updatedExchangeItems).toHaveLength(0)
870 expect(updatedClaimShippingMethods).toHaveLength(0)
871 })
872
873 it("should remove inbound shipping method when inbound items are completely removed", async () => {
874 orderPreview = (
875 await api.get(`/admin/orders/${order.id}/preview`, adminHeaders)
876 ).data.order
877
878 const exchangeItems = orderPreview.items.filter(
879 (item) =>
880 !!item.actions?.find((action) => action.action === "RETURN_ITEM")
881 )
882
883 const exchangeShippingMethods = orderPreview.shipping_methods.filter(
884 (item) =>
885 !!item.actions?.find(
886 (action) =>
887 action.action === "SHIPPING_ADD" && !!action.return_id
888 )
889 )
890
891 expect(exchangeItems).toHaveLength(1)
892 expect(exchangeShippingMethods).toHaveLength(1)
893
894 await api.delete(
895 `/admin/exchanges/${exchange.id}/inbound/items/${exchangeItems[0].actions[0].id}`,
896 adminHeaders
897 )
898
899 orderPreview = (
900 await api.get(`/admin/orders/${order.id}/preview`, adminHeaders)
901 ).data.order
902
903 const updatedExchangeItems = orderPreview.items.filter(
904 (item) =>
905 !!item.actions?.find((action) => action.action === "RETURN_ITEM")
906 )
907
908 const updatedClaimShippingMethods =
909 orderPreview.shipping_methods.filter(
910 (item) =>
911 !!item.actions?.find(
912 (action) =>
913 action.action === "SHIPPING_ADD" && !!action.return_id
914 )
915 )
916
917 expect(updatedExchangeItems).toHaveLength(0)
918 expect(updatedClaimShippingMethods).toHaveLength(0)
919 })
920 })
921
922 describe("Exchange adjustments", () => {
923 let appliedPromotion
924 let promotionModule: IPromotionModuleService
925 let orderModule: IOrderModuleService
926 let remoteLink
927 let orderWithPromotion
928 let productForAdjustmentTest
929
930 beforeEach(async () => {
931 const container = getContainer()
932 promotionModule = container.resolve(Modules.PROMOTION)
933 orderModule = container.resolve(Modules.ORDER)
934 remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
935
936 productForAdjustmentTest = (
937 await api.post(
938 "/admin/products",
939 {
940 title: "Product for adjustment test",
941 status: ProductStatus.PUBLISHED,
942 shipping_profile_id: shippingProfile.id,
943 options: [{ title: "size", values: ["large", "small"] }],
944 variants: [
945 {
946 title: "Test variant",
947 sku: "test-variant-adjustment",
948 manage_inventory: false,
949 options: { size: "large" },
950 prices: [
951 {
952 currency_code: "usd",
953 amount: 12,
954 },
955 ],
956 },
957 ],
958 },
959 adminHeaders
960 )
961 ).data.product
962
963 appliedPromotion = await promotionModule.createPromotions({
964 code: "PROMOTION_APPLIED",
965 type: PromotionType.STANDARD,
966 status: PromotionStatus.ACTIVE,
967 application_method: {
968 type: "percentage",
969 target_type: "order",
970 allocation: "each",
971 value: 10,
972 max_quantity: 5,
973 currency_code: "usd",
974 target_rules: [],
975 },
976 })
977
978 await remoteLink.create([
979 {
980 [Modules.SALES_CHANNEL]: {
981 sales_channel_id: (
982 await api.get("/admin/sales-channels", adminHeaders)
983 ).data.sales_channels[0].id,
984 },
985 [Modules.STOCK_LOCATION]: {
986 stock_location_id: location.id,
987 },
988 },
989 ])
990
991 // @ts-ignore
992 orderWithPromotion = await orderModule.createOrders({
993 email: "foo@bar.com",
994 region_id: (
995 await api.get("/admin/regions", adminHeaders)
996 ).data.regions[0].id,
997 sales_channel_id: (
998 await api.get("/admin/sales-channels", adminHeaders)
999 ).data.sales_channels[0].id,
1000 items: [
1001 {
1002 // @ts-ignore
1003 id: "item-1",
1004 title: "Custom Item",
1005 quantity: 1,
1006 unit_price: 10,
1007 },
1008 ],
1009 shipping_address: {
1010 first_name: "Test",
1011 last_name: "Test",
1012 address_1: "Test",
1013 city: "Test",
1014 country_code: "US",
1015 postal_code: "12345",
1016 phone: "12345",
1017 },
1018 billing_address: {
1019 first_name: "Test",
1020 last_name: "Test",
1021 address_1: "Test",
1022 city: "Test",
1023 country_code: "US",
1024 postal_code: "12345",
1025 },
1026 currency_code: "usd",
1027 })
1028
1029 await orderModule.createOrderLineItemTaxLines(orderWithPromotion.id, [
1030 {
1031 // @ts-ignore
1032 item_id: "item-1",
1033 code: "standard",
1034 rate: 10,
1035 description: "tax-1",
1036 provider_id: "system",
1037 total: 1.2,
1038 subtotal: 1.2,
1039 },
1040 ])
1041
1042 await orderModule.createOrderLineItemAdjustments([
1043 {
1044 version: 1,
1045 code: appliedPromotion.code!,
1046 amount: 1,
1047 item_id: "item-1",
1048 promotion_id: appliedPromotion.id,
1049 },
1050 ])
1051
1052 await remoteLink.create({
1053 [Modules.ORDER]: { order_id: orderWithPromotion.id },
1054 [Modules.PROMOTION]: { promotion_id: appliedPromotion.id },
1055 })
1056 })
1057
1058 it("should update adjustments when adding an inbound and outbound item", async () => {
1059 // First item -> 10$ | 10% discount tax excl. | 10% tax
1060 // Second item -> 12$ | 10% discount tax excl. | 2% tax
1061
1062 // fulfill item so it can be returned
1063 await api.post(
1064 `/admin/orders/${orderWithPromotion.id}/fulfillments`,
1065 {
1066 items: [
1067 {
1068 id: orderWithPromotion.items[0].id,
1069 quantity: 1,
1070 },
1071 ],
1072 },
1073 adminHeaders
1074 )
1075
1076 let result = await api.post(
1077 "/admin/exchanges",
1078 {
1079 order_id: orderWithPromotion.id,
1080 description: "Test",
1081 },
1082 adminHeaders
1083 )
1084
1085 const exchangeId = result.data.exchange.id
1086 const orderId = result.data.exchange.order_id
1087
1088 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders))
1089 .data.order
1090
1091 expect(result.original_total).toEqual(11) // $10 + 10% tax
1092 expect(result.total).toEqual(10 * 0.9 * 1.1) // ($10 - 10% discount) + 10% tax
1093
1094 const orderChange = (
1095 await api.get(`/admin/orders/${orderId}/preview`, adminHeaders)
1096 ).data.order.order_change
1097
1098 // opt in for carry over promotions
1099 await api.post(
1100 `/admin/order-changes/${orderChange.id}`,
1101 {
1102 carry_over_promotions: true,
1103 },
1104 adminHeaders
1105 )
1106
1107 // Add outbound item with price $12, 10% discount and 10% tax
1108 result = (
1109 await api
1110 .post(
1111 `/admin/exchanges/${exchangeId}/outbound/items`,
1112 {
1113 items: [
1114 {
1115 variant_id: productForAdjustmentTest.variants[0].id,
1116 quantity: 1,
1117 },
1118 ],
1119 },
1120 adminHeaders
1121 )
1122 .catch((e) => console.log(e))
1123 ).data.order_preview
1124
1125 expect(result.total).toEqual(20.916) // 10 * 0.9 * 1.1 + 12 * 0.9 * 1.02
1126 expect(result.original_total).toEqual(23.24) // 10 * 1.1 + 12 * 1.02
1127
1128 // Confirm that the adjustment values are correct
1129 const adjustments = result.items[0].adjustments
1130 const adjustments2 = result.items[1].adjustments
1131 expect(adjustments).toEqual([
1132 expect.objectContaining({
1133 amount: 1,
1134 }),
1135 ])
1136 expect(adjustments2).toEqual([
1137 expect.objectContaining({
1138 amount: 1.2,
1139 }),
1140 ])
1141
1142 let orderResult = (
1143 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1144 ).data.order
1145
1146 // confirm original order is not updated
1147 expect(orderResult.total).toEqual(9.9) // initial item 10$ and 10% discount and 10% tax
1148 expect(orderResult.original_total).toEqual(11) // initial item 10$ + 10% tax
1149
1150 const originalItemId = result.items[0].id
1151
1152 // Request inbound item return
1153 result = (
1154 await api
1155 .post(
1156 `/admin/exchanges/${exchangeId}/inbound/items`,
1157 {
1158 items: [
1159 {
1160 id: originalItemId,
1161 reason_id: returnReason.id,
1162 quantity: 1,
1163 },
1164 ],
1165 },
1166 adminHeaders
1167 )
1168 .catch((e) => console.log(e))
1169 ).data.order_preview
1170
1171 const returnId = result.order_change.return_id
1172
1173 await api.post(
1174 `/admin/exchanges/${exchangeId}/request`,
1175 {},
1176 adminHeaders
1177 )
1178
1179 orderResult = (
1180 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1181 ).data.order
1182
1183 // after exchange request order contains both items and adjustments untill return is received
1184 expect(orderResult.total).toEqual(20.916) // 10 * 0.9 * 1.1 + 12 * 0.9 * 1.02
1185 expect(orderResult.original_total).toEqual(23.24) // 10 * 1.1 + 12 * 1.02
1186
1187 await api.post(`/admin/returns/${returnId}/receive`, {}, adminHeaders)
1188
1189 orderResult = (
1190 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1191 ).data.order
1192
1193 // still the same state while return receive process is pending
1194 expect(orderResult.total).toEqual(20.916) // 10 * 0.9 * 1.1 + 12 * 0.9 * 1.02
1195 expect(orderResult.original_total).toEqual(23.24) // 10 * 1.1 + 12 * 1.02
1196
1197 await api.post(
1198 `/admin/returns/${returnId}/receive-items`,
1199 {
1200 items: [
1201 {
1202 id: originalItemId,
1203 quantity: 1,
1204 },
1205 ],
1206 },
1207 adminHeaders
1208 )
1209
1210 orderResult = (
1211 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1212 ).data.order
1213
1214 // still the same state while return receive process is pending
1215 expect(orderResult.total).toEqual(20.916) // 10 * 0.9 * 1.1 + 12 * 0.9 * 1.02
1216 expect(orderResult.original_total).toEqual(23.24) // 10 * 1.1 + 12 * 1.02
1217
1218 await api.post(
1219 `/admin/returns/${returnId}/receive/confirm`,
1220 {},
1221 adminHeaders
1222 )
1223
1224 const orderResult2 = (
1225 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1226 ).data.order
1227
1228 // after confirmation only first added item is active
1229 expect(orderResult2.total).toEqual(11.016)
1230 expect(orderResult2.original_total).toEqual(12.24)
1231 })
1232
1233 it("should enable carry_over_promotions flag and apply promotions to outbound items (flag disabled before request)", async () => {
1234 // fulfill item so it can be returned
1235 await api.post(
1236 `/admin/orders/${orderWithPromotion.id}/fulfillments`,
1237 {
1238 items: [
1239 {
1240 id: orderWithPromotion.items[0].id,
1241 quantity: 1,
1242 },
1243 ],
1244 },
1245 adminHeaders
1246 )
1247
1248 let result = await api.post(
1249 "/admin/exchanges",
1250 {
1251 order_id: orderWithPromotion.id,
1252 description: "Test",
1253 },
1254 adminHeaders
1255 )
1256
1257 const exchangeId = result.data.exchange.id
1258
1259 // Query order change for the exchange
1260 const orderChange = (
1261 await api.get(
1262 `/admin/orders/${orderWithPromotion.id}/preview`,
1263 adminHeaders
1264 )
1265 ).data.order.order_change
1266
1267 const orderChangeId = orderChange.id
1268
1269 // return original item
1270 await api.post(
1271 `/admin/exchanges/${exchangeId}/inbound/items`,
1272 {
1273 items: [
1274 {
1275 id: orderWithPromotion.items[0].id,
1276 quantity: 1,
1277 },
1278 ],
1279 },
1280 adminHeaders
1281 )
1282
1283 // add outbound item
1284 await api.post(
1285 `/admin/exchanges/${exchangeId}/outbound/items`,
1286 {
1287 items: [
1288 {
1289 variant_id: productForAdjustmentTest.variants[0].id,
1290 quantity: 1,
1291 },
1292 ],
1293 },
1294 adminHeaders
1295 )
1296
1297 // Initially, promotions should be disabled by default when adding outbound items
1298 let orderPreview = (
1299 await api.get(
1300 `/admin/orders/${orderWithPromotion.id}/preview`,
1301 adminHeaders
1302 )
1303 ).data.order
1304
1305 expect(orderPreview.items).toEqual(
1306 expect.arrayContaining([
1307 expect.objectContaining({
1308 id: "item-1", // original item
1309 adjustments: [
1310 expect.objectContaining({
1311 amount: 1,
1312 }),
1313 ],
1314 }),
1315 expect.objectContaining({
1316 variant_id: productForAdjustmentTest.variants[0].id,
1317 adjustments: [], // outbound item has no adjustments initially
1318 }),
1319 ])
1320 )
1321
1322 // Enable carry_over_promotions
1323 await api.post(
1324 `/admin/order-changes/${orderChangeId}`,
1325 {
1326 carry_over_promotions: true,
1327 },
1328 adminHeaders
1329 )
1330
1331 // Verify adjustments are added
1332 orderPreview = (
1333 await api.get(
1334 `/admin/orders/${orderWithPromotion.id}/preview`,
1335 adminHeaders
1336 )
1337 ).data.order
1338
1339 expect(orderPreview.items).toEqual(
1340 expect.arrayContaining([
1341 expect.objectContaining({
1342 id: "item-1", // original item
1343 adjustments: [
1344 expect.objectContaining({
1345 amount: 1,
1346 }),
1347 ],
1348 }),
1349 expect.objectContaining({
1350 variant_id: productForAdjustmentTest.variants[0].id,
1351 adjustments: [
1352 // outbound item has adjustments after carry_over_promotions is enabled
1353 expect.objectContaining({
1354 amount: 1.2,
1355 }),
1356 ],
1357 }),
1358 ])
1359 )
1360
1361 // Disable carry_over_promotions
1362 await api.post(
1363 `/admin/order-changes/${orderChangeId}`,
1364 {
1365 carry_over_promotions: false,
1366 },
1367 adminHeaders
1368 )
1369
1370 // Verify adjustments are removed again
1371 orderPreview = (
1372 await api.get(
1373 `/admin/orders/${orderWithPromotion.id}/preview`,
1374 adminHeaders
1375 )
1376 ).data.order
1377
1378 expect(orderPreview.items).toEqual(
1379 expect.arrayContaining([
1380 expect.objectContaining({
1381 id: "item-1", // original item
1382 adjustments: [
1383 expect.objectContaining({
1384 amount: 1,
1385 }),
1386 ],
1387 }),
1388 expect.objectContaining({
1389 variant_id: productForAdjustmentTest.variants[0].id,
1390 adjustments: [], // outbound item has no adjustments
1391 }),
1392 ])
1393 )
1394
1395 await api.post(
1396 `/admin/exchanges/${exchangeId}/request`,
1397 {},
1398 adminHeaders
1399 )
1400
1401 const finalOrder = (
1402 await api.get(
1403 `/admin/orders/${orderWithPromotion.id}`,
1404 adminHeaders
1405 )
1406 ).data.order
1407
1408 // items adjustment state is equal to the last state of the order preview (flag disabled)
1409 expect(finalOrder.items).toEqual(
1410 expect.arrayContaining([
1411 expect.objectContaining({
1412 id: "item-1", // original item
1413 adjustments: [
1414 expect.objectContaining({
1415 amount: 1,
1416 }),
1417 ],
1418 }),
1419 expect.objectContaining({
1420 variant_id: productForAdjustmentTest.variants[0].id,
1421 adjustments: [],
1422 }),
1423 ])
1424 )
1425 })
1426
1427 it("should enable carry_over_promotions flag and apply promotions to outbound items (flag enabled before request)", async () => {
1428 // fulfill item so it can be returned
1429 await api.post(
1430 `/admin/orders/${orderWithPromotion.id}/fulfillments`,
1431 {
1432 items: [
1433 {
1434 id: orderWithPromotion.items[0].id,
1435 quantity: 1,
1436 },
1437 ],
1438 },
1439 adminHeaders
1440 )
1441
1442 const promotionModule = getContainer().resolve(Modules.PROMOTION)
1443
1444 // check that adjustments are computed for promotions that exceeded usage limit (we ignore usage limits on edit flows)
1445 // @ts-ignore
1446 await promotionModule.updatePromotions({
1447 id: appliedPromotion.id,
1448 limit: 1,
1449 used: 1,
1450 })
1451
1452 let result = await api.post(
1453 "/admin/exchanges",
1454 {
1455 order_id: orderWithPromotion.id,
1456 description: "Test",
1457 },
1458 adminHeaders
1459 )
1460
1461 const exchangeId = result.data.exchange.id
1462
1463 // Query order change for the exchange
1464 const orderChange = (
1465 await api.get(
1466 `/admin/orders/${orderWithPromotion.id}/preview`,
1467 adminHeaders
1468 )
1469 ).data.order.order_change
1470
1471 const orderChangeId = orderChange.id
1472
1473 // return original item
1474 await api.post(
1475 `/admin/exchanges/${exchangeId}/inbound/items`,
1476 {
1477 items: [
1478 {
1479 id: orderWithPromotion.items[0].id,
1480 quantity: 1,
1481 },
1482 ],
1483 },
1484 adminHeaders
1485 )
1486
1487 // add outbound item
1488 await api.post(
1489 `/admin/exchanges/${exchangeId}/outbound/items`,
1490 {
1491 items: [
1492 {
1493 variant_id: productForAdjustmentTest.variants[0].id,
1494 quantity: 1,
1495 },
1496 ],
1497 },
1498 adminHeaders
1499 )
1500
1501 let orderPreview = (
1502 await api.get(
1503 `/admin/orders/${orderWithPromotion.id}/preview`,
1504 adminHeaders
1505 )
1506 ).data.order
1507
1508 expect(orderPreview.items).toEqual(
1509 expect.arrayContaining([
1510 expect.objectContaining({
1511 id: "item-1", // original item
1512 adjustments: [
1513 expect.objectContaining({
1514 amount: 1,
1515 }),
1516 ],
1517 }),
1518 expect.objectContaining({
1519 variant_id: productForAdjustmentTest.variants[0].id,
1520 adjustments: [], // outbound item has no adjustments initially
1521 }),
1522 ])
1523 )
1524
1525 // Enable carry_over_promotions
1526 await api.post(
1527 `/admin/order-changes/${orderChangeId}`,
1528 {
1529 carry_over_promotions: true,
1530 },
1531 adminHeaders
1532 )
1533
1534 // Verify adjustments are added
1535 orderPreview = (
1536 await api.get(
1537 `/admin/orders/${orderWithPromotion.id}/preview`,
1538 adminHeaders
1539 )
1540 ).data.order
1541
1542 expect(orderPreview.items).toEqual(
1543 expect.arrayContaining([
1544 expect.objectContaining({
1545 id: "item-1", // original item
1546 adjustments: [
1547 expect.objectContaining({
1548 amount: 1,
1549 }),
1550 ],
1551 }),
1552 expect.objectContaining({
1553 variant_id: productForAdjustmentTest.variants[0].id,
1554 adjustments: [
1555 // outbound item has adjustments after carry_over_promotions is enabled
1556 expect.objectContaining({
1557 amount: 1.2,
1558 }),
1559 ],
1560 }),
1561 ])
1562 )
1563
1564 await api.post(
1565 `/admin/exchanges/${exchangeId}/request`,
1566 {},
1567 adminHeaders
1568 )
1569
1570 const finalOrder = (
1571 await api.get(
1572 `/admin/orders/${orderWithPromotion.id}`,
1573 adminHeaders
1574 )
1575 ).data.order
1576
1577 // items adjustment state is equal to the last state of the order preview (flag enabled)
1578 expect(finalOrder.items).toEqual(
1579 expect.arrayContaining([
1580 expect.objectContaining({
1581 id: "item-1", // original item
1582 adjustments: [
1583 expect.objectContaining({
1584 amount: 1,
1585 }),
1586 ],
1587 }),
1588 expect.objectContaining({
1589 variant_id: productForAdjustmentTest.variants[0].id,
1590 adjustments: [
1591 expect.objectContaining({
1592 amount: 1.2,
1593 }),
1594 ],
1595 }),
1596 ])
1597 )
1598 })
1599 })
1600 })
1601 },
1602 })