1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { IOrderModuleService, IPromotionModuleService } from "@medusajs/types"
3 import {
4 ContainerRegistrationKeys,
5 Modules,
6 OrderChangeStatus,
7 OrderEditWorkflowEvents,
8 ProductStatus,
9 PromotionStatus,
10 PromotionType,
11 RuleOperator,
12 } from "@medusajs/utils"
13 import {
14 adminHeaders,
15 createAdminUser,
16 generatePublishableKey,
17 generateStoreHeaders,
18 } from "../../../helpers/create-admin-user"
19 import { medusaTshirtProduct } from "../../__fixtures__/product"
20
21 jest.setTimeout(300000)
22
23 medusaIntegrationTestRunner({
24 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
25 let order
26 let taxLine
27 let shippingOption
28 let shippingProfile
29 let fulfillmentSet
30 let inventoryItem
31 let inventoryItemExtra
32 let location
33 let locationTwo
34 let productExtra
35 let container
36 let region
37 let salesChannel
38 let buyRuleProduct
39
40 const shippingProviderId = "manual_test-provider"
41
42 beforeAll(async () => {
43 container = getContainer()
44 await createAdminUser(dbConnection, adminHeaders, container)
45
46 region = (
47 await api.post(
48 "/admin/regions",
49 {
50 payment_providers: ["pp_system_default"],
51 name: "test-region",
52 currency_code: "usd",
53 },
54 adminHeaders
55 )
56 ).data.region
57
58 const customer = (
59 await api.post(
60 "/admin/customers",
61 {
62 first_name: "joe",
63 email: "joe@admin.com",
64 },
65 adminHeaders
66 )
67 ).data.customer
68
69 const taxRegion = (
70 await api.post(
71 "/admin/tax-regions",
72 {
73 provider_id: "tp_system",
74 country_code: "US",
75 },
76 adminHeaders
77 )
78 ).data.tax_region
79
80 taxLine = (
81 await api.post(
82 "/admin/tax-rates",
83 {
84 rate: 10,
85 code: "standard",
86 name: "Taxation is theft",
87 is_default: true,
88 tax_region_id: taxRegion.id,
89 },
90 adminHeaders
91 )
92 ).data.tax_rate
93
94 salesChannel = (
95 await api.post(
96 "/admin/sales-channels",
97 {
98 name: "Test channel",
99 },
100 adminHeaders
101 )
102 ).data.sales_channel
103
104 shippingProfile = (
105 await api.post(
106 `/admin/shipping-profiles`,
107 {
108 name: "Test",
109 type: "default",
110 },
111 adminHeaders
112 )
113 ).data.shipping_profile
114
115 const product = (
116 await api.post(
117 "/admin/products",
118 {
119 title: "Test product",
120 status: ProductStatus.PUBLISHED,
121 options: [{ title: "size", values: ["large", "small"] }],
122 shipping_profile_id: shippingProfile.id,
123 variants: [
124 {
125 title: "Test variant",
126 sku: "test-variant",
127 options: { size: "large" },
128 prices: [
129 {
130 currency_code: "usd",
131 amount: 10,
132 },
133 ],
134 },
135 ],
136 },
137 adminHeaders
138 )
139 ).data.product
140
141 productExtra = (
142 await api.post(
143 "/admin/products",
144 {
145 title: "Extra product",
146 status: ProductStatus.PUBLISHED,
147 options: [{ title: "size", values: ["large", "small"] }],
148 shipping_profile_id: shippingProfile.id,
149 variants: [
150 {
151 title: "my variant",
152 sku: "variant-sku",
153 options: { size: "large" },
154 prices: [
155 {
156 currency_code: "usd",
157 amount: 12,
158 },
159 ],
160 },
161 ],
162 },
163 adminHeaders
164 )
165 ).data.product
166
167 buyRuleProduct = (
168 await api.post(
169 "/admin/products",
170 {
171 title: "Buy rule product",
172 options: [{ title: "size", values: ["large", "small"] }],
173 shipping_profile_id: shippingProfile.id,
174 variants: [
175 {
176 title: "buy rule variant",
177 manage_inventory: false,
178 sku: "buy-rule-variant-sku",
179 options: { size: "large" },
180 prices: [
181 {
182 currency_code: "usd",
183 amount: 10,
184 },
185 ],
186 },
187 ],
188 },
189 adminHeaders
190 )
191 ).data.product
192
193 const orderModule = container.resolve(Modules.ORDER)
194
195 order = await orderModule.createOrders({
196 region_id: region.id,
197 email: "foo@bar.com",
198 items: [
199 {
200 title: "Custom Item",
201 variant_id: product.variants[0].id,
202 quantity: 2,
203 unit_price: 25,
204 },
205 ],
206 sales_channel_id: salesChannel.id,
207 shipping_address: {
208 first_name: "Test",
209 last_name: "Test",
210 address_1: "Test",
211 city: "Test",
212 country_code: "US",
213 postal_code: "12345",
214 phone: "12345",
215 },
216 billing_address: {
217 first_name: "Test",
218 last_name: "Test",
219 address_1: "Test",
220 city: "Test",
221 country_code: "US",
222 postal_code: "12345",
223 },
224 shipping_methods: [
225 {
226 name: "Test shipping method",
227 amount: 10,
228 },
229 ],
230 currency_code: "usd",
231 customer_id: customer.id,
232 })
233
234 location = (
235 await api.post(
236 `/admin/stock-locations`,
237 {
238 name: "Test location",
239 },
240 adminHeaders
241 )
242 ).data.stock_location
243
244 location = (
245 await api.post(
246 `/admin/stock-locations/${location.id}/fulfillment-sets?fields=*fulfillment_sets`,
247 {
248 name: "Test",
249 type: "test-type",
250 },
251 adminHeaders
252 )
253 ).data.stock_location
254
255 fulfillmentSet = (
256 await api.post(
257 `/admin/fulfillment-sets/${location.fulfillment_sets[0].id}/service-zones`,
258 {
259 name: "Test",
260 geo_zones: [{ type: "country", country_code: "us" }],
261 },
262 adminHeaders
263 )
264 ).data.fulfillment_set
265
266 inventoryItem = (
267 await api.post(
268 `/admin/inventory-items`,
269 { sku: "inv-1234" },
270 adminHeaders
271 )
272 ).data.inventory_item
273
274 await api.post(
275 `/admin/inventory-items/${inventoryItem.id}/location-levels`,
276 {
277 location_id: location.id,
278 stocked_quantity: 2,
279 },
280 adminHeaders
281 )
282
283 inventoryItemExtra = (
284 await api.get(`/admin/inventory-items?sku=variant-sku`, adminHeaders)
285 ).data.inventory_items[0]
286
287 await api.post(
288 `/admin/inventory-items/${inventoryItemExtra.id}/location-levels`,
289 {
290 location_id: location.id,
291 stocked_quantity: 4,
292 },
293 adminHeaders
294 )
295
296 const remoteLink = container.resolve(
297 ContainerRegistrationKeys.REMOTE_LINK
298 )
299
300 await remoteLink.create([
301 {
302 [Modules.STOCK_LOCATION]: {
303 stock_location_id: location.id,
304 },
305 [Modules.FULFILLMENT]: {
306 fulfillment_provider_id: shippingProviderId,
307 },
308 },
309 {
310 [Modules.STOCK_LOCATION]: {
311 stock_location_id: location.id,
312 },
313 [Modules.FULFILLMENT]: {
314 fulfillment_set_id: fulfillmentSet.id,
315 },
316 },
317 {
318 [Modules.SALES_CHANNEL]: {
319 sales_channel_id: salesChannel.id,
320 },
321 [Modules.STOCK_LOCATION]: {
322 stock_location_id: location.id,
323 },
324 },
325 {
326 [Modules.PRODUCT]: {
327 variant_id: product.variants[0].id,
328 },
329 [Modules.INVENTORY]: {
330 inventory_item_id: inventoryItem.id,
331 },
332 },
333 {
334 [Modules.PRODUCT]: {
335 variant_id: productExtra.variants[0].id,
336 },
337 [Modules.INVENTORY]: {
338 inventory_item_id: inventoryItemExtra.id,
339 },
340 },
341 ])
342
343 const shippingOptionPayload = {
344 name: "Shipping",
345 service_zone_id: fulfillmentSet.service_zones[0].id,
346 shipping_profile_id: shippingProfile.id,
347 provider_id: shippingProviderId,
348 price_type: "flat",
349 type: {
350 label: "Test type",
351 description: "Test description",
352 code: "test-code",
353 },
354 prices: [
355 {
356 currency_code: "usd",
357 amount: 10,
358 },
359 ],
360 rules: [
361 {
362 operator: RuleOperator.EQ,
363 attribute: "is_return",
364 value: "true",
365 },
366 ],
367 }
368
369 shippingOption = (
370 await api.post(
371 "/admin/shipping-options",
372 shippingOptionPayload,
373 adminHeaders
374 )
375 ).data.shipping_option
376
377 await dbUtils.snapshot()
378 })
379
380 describe("Order Edits lifecycle", () => {
381 it("Full flow test", async () => {
382 let result = await api.post(
383 "/admin/order-edits",
384 {
385 order_id: order.id,
386 description: "Test",
387 },
388 adminHeaders
389 )
390
391 const orderId = result.data.order_change.order_id
392
393 const item = order.items[0]
394
395 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
396 .order
397
398 expect(result.summary.current_order_total).toEqual(60)
399 expect(result.summary.original_order_total).toEqual(60)
400
401 // New Items ($12 each)
402 result = (
403 await api.post(
404 `/admin/order-edits/${orderId}/items`,
405 {
406 items: [
407 {
408 variant_id: productExtra.variants[0].id,
409 quantity: 2,
410 },
411 ],
412 },
413 adminHeaders
414 )
415 ).data.order_preview
416
417 expect(result.summary.current_order_total).toEqual(86.4)
418 expect(result.summary.original_order_total).toEqual(60)
419
420 // Update item quantity and unit_price with the same amount as we have originally should not change totals
421 result = (
422 await api.post(
423 `/admin/order-edits/${orderId}/items/item/${item.id}`,
424 {
425 quantity: 2,
426 unit_price: 25,
427 },
428 adminHeaders
429 )
430 ).data.order_preview
431
432 expect(result.summary.current_order_total).toEqual(86.4)
433 expect(result.summary.original_order_total).toEqual(60)
434
435 // Update item quantity, but keep the price as it was originally, should add + 25 to previous amount
436 result = (
437 await api.post(
438 `/admin/order-edits/${orderId}/items/item/${item.id}`,
439 {
440 quantity: 3,
441 unit_price: 25,
442 },
443 adminHeaders
444 )
445 ).data.order_preview
446
447 expect(result.summary.current_order_total).toEqual(111.4)
448 expect(result.summary.original_order_total).toEqual(60)
449
450 // Update item quantity, with a new price
451 // 30 * 3 = 90 (new item)
452 // 12 * 2 = 24 (custom item)
453 // 10 * 1 = 10 (shipping item)
454 // total = 124
455 result = (
456 await api.post(
457 `/admin/order-edits/${orderId}/items/item/${item.id}`,
458 {
459 quantity: 3,
460 unit_price: 30,
461 },
462 adminHeaders
463 )
464 ).data.order_preview
465
466 expect(result.summary.current_order_total).toEqual(126.4)
467 expect(result.summary.original_order_total).toEqual(60)
468
469 const updatedItem = result.items.find((i) => i.id === item.id)
470 expect(updatedItem.actions).toEqual([
471 expect.objectContaining({
472 details: expect.objectContaining({
473 quantity: 2,
474 unit_price: 25,
475 quantity_diff: 0,
476 }),
477 }),
478 expect.objectContaining({
479 details: expect.objectContaining({
480 quantity: 3,
481 unit_price: 25,
482 quantity_diff: 1,
483 }),
484 }),
485 expect.objectContaining({
486 details: expect.objectContaining({
487 quantity: 3,
488 unit_price: 30,
489 quantity_diff: 1,
490 }),
491 }),
492 ])
493
494 // Update item with decimal quantity
495 result = (
496 await api.post(
497 `/admin/order-edits/${orderId}/items/item/${item.id}`,
498 {
499 quantity: 2.5,
500 unit_price: 30,
501 },
502 adminHeaders
503 )
504 ).data.order_preview
505
506 expect(result.summary.current_order_total).toEqual(111.4)
507 expect(result.summary.original_order_total).toEqual(60)
508
509 const decimalUpdatedItem = result.items.find((i) => i.id === item.id)
510 expect(decimalUpdatedItem.actions[3]).toEqual(
511 expect.objectContaining({
512 details: expect.objectContaining({
513 quantity: 2.5,
514 unit_price: 30,
515 quantity_diff: 0.5,
516 }),
517 })
518 )
519 // Remove the item by setting the quantity to 0
520 result = (
521 await api.post(
522 `/admin/order-edits/${orderId}/items/item/${item.id}`,
523 {
524 quantity: 0,
525 },
526 adminHeaders
527 )
528 ).data.order_preview
529
530 expect(result.summary.current_order_total).toEqual(36.4)
531 expect(result.summary.original_order_total).toEqual(60)
532 expect(result.items.length).toEqual(2)
533
534 result = (
535 await api.post(
536 `/admin/order-edits/${orderId}/request`,
537 {},
538 adminHeaders
539 )
540 ).data.order_preview
541
542 expect(result.order_change.status).toEqual(OrderChangeStatus.REQUESTED)
543 expect(result.summary.current_order_total).toEqual(36.4)
544 expect(result.summary.original_order_total).toEqual(60)
545 expect(result.items.length).toEqual(2)
546
547 const newItem = result.items.find(
548 (i) => i.variant_id === productExtra.variants[0].id
549 )
550 expect(newItem.tax_lines[0].tax_rate_id).toEqual(taxLine.id)
551 expect(newItem.tax_lines[0].rate).toEqual(10)
552
553 result = (
554 await api.post(
555 `/admin/order-edits/${orderId}/confirm`,
556 {},
557 adminHeaders
558 )
559 ).data.order_preview
560
561 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
562 .order
563
564 expect(result.total).toEqual(36.4)
565 expect(result.items.length).toEqual(1)
566
567 result = (
568 await api.get(
569 `/admin/orders/${orderId}/changes?change_type=edit`,
570 adminHeaders
571 )
572 ).data.order_changes
573
574 expect(result[0].actions).toHaveLength(6)
575 expect(result[0].status).toEqual("confirmed")
576 expect(result[0].confirmed_by).toEqual(expect.stringContaining("user_"))
577 })
578 })
579
580 describe("Order Edit Inventory", () => {
581 let product
582 let inventoryItemLarge
583 let inventoryItemMedium
584 let inventoryItemSmall
585 let inventoryOrder
586
587 beforeEach(async () => {
588 const container = getContainer()
589
590 inventoryItemLarge = (
591 await api.post(
592 `/admin/inventory-items`,
593 { sku: "shirt-large" },
594 adminHeaders
595 )
596 ).data.inventory_item
597
598 inventoryItemMedium = (
599 await api.post(
600 `/admin/inventory-items`,
601 { sku: "shirt-medium" },
602 adminHeaders
603 )
604 ).data.inventory_item
605
606 inventoryItemSmall = (
607 await api.post(
608 `/admin/inventory-items`,
609 { sku: "shirt-small" },
610 adminHeaders
611 )
612 ).data.inventory_item
613
614 location = (
615 await api.post(
616 `/admin/stock-locations`,
617 {
618 name: "Test location",
619 },
620 adminHeaders
621 )
622 ).data.stock_location
623
624 locationTwo = (
625 await api.post(
626 `/admin/stock-locations`,
627 {
628 name: "Test location two",
629 },
630 adminHeaders
631 )
632 ).data.stock_location
633
634 await api.post(
635 `/admin/inventory-items/${inventoryItemLarge.id}/location-levels`,
636 {
637 location_id: location.id,
638 stocked_quantity: 0,
639 },
640 adminHeaders
641 )
642
643 await api.post(
644 `/admin/inventory-items/${inventoryItemLarge.id}/location-levels`,
645 {
646 location_id: locationTwo.id,
647 stocked_quantity: 10,
648 },
649 adminHeaders
650 )
651
652 await api.post(
653 `/admin/inventory-items/${inventoryItemMedium.id}/location-levels`,
654 {
655 location_id: location.id,
656 stocked_quantity: 10,
657 },
658 adminHeaders
659 )
660 await api.post(
661 `/admin/inventory-items/${inventoryItemSmall.id}/location-levels`,
662 {
663 location_id: location.id,
664 stocked_quantity: 10,
665 },
666 adminHeaders
667 )
668
669 product = (
670 await api.post(
671 "/admin/products",
672 {
673 title: "Shirt",
674 status: ProductStatus.PUBLISHED,
675 options: [
676 { title: "size", values: ["large", "medium", "small"] },
677 ],
678 variants: [
679 {
680 title: "L shirt",
681 options: { size: "large" },
682 manage_inventory: true,
683 inventory_items: [
684 {
685 inventory_item_id: inventoryItemLarge.id,
686 required_quantity: 1,
687 },
688 ],
689 prices: [
690 {
691 currency_code: "usd",
692 amount: 10,
693 },
694 ],
695 },
696 {
697 title: "M shirt",
698 options: { size: "medium" },
699 manage_inventory: true,
700 inventory_items: [
701 {
702 inventory_item_id: inventoryItemMedium.id,
703 required_quantity: 1,
704 },
705 ],
706 prices: [
707 {
708 currency_code: "usd",
709 amount: 10,
710 },
711 ],
712 },
713 {
714 title: "S shirt",
715 options: { size: "small" },
716 manage_inventory: true,
717 inventory_items: [
718 {
719 inventory_item_id: inventoryItemSmall.id,
720 required_quantity: 1,
721 },
722 ],
723 prices: [
724 {
725 currency_code: "usd",
726 amount: 10,
727 },
728 ],
729 },
730 ],
731 },
732 adminHeaders
733 )
734 ).data.product
735
736 const region = (
737 await api.post(
738 "/admin/regions",
739 {
740 payment_providers: ["pp_system_default"],
741 name: "test-region",
742 currency_code: "usd",
743 },
744 adminHeaders
745 )
746 ).data.region
747
748 const customer = (
749 await api.post(
750 "/admin/customers",
751 {
752 first_name: "joe2",
753 email: "joe2@admin.com",
754 },
755 adminHeaders
756 )
757 ).data.customer
758
759 const taxRegion = (
760 await api.post(
761 "/admin/tax-regions",
762 {
763 provider_id: "tp_system",
764 country_code: "UK",
765 },
766 adminHeaders
767 )
768 ).data.tax_region
769
770 taxLine = (
771 await api.post(
772 "/admin/tax-rates",
773 {
774 rate: 10,
775 code: "standard",
776 name: "Taxation is theft",
777 is_default: true,
778 tax_region_id: taxRegion.id,
779 },
780 adminHeaders
781 )
782 ).data.tax_rate
783
784 const salesChannel = (
785 await api.post(
786 "/admin/sales-channels",
787 {
788 name: "Test channel",
789 },
790 adminHeaders
791 )
792 ).data.sales_channel
793
794 const orderModule = container.resolve(Modules.ORDER)
795
796 inventoryOrder = await orderModule.createOrders({
797 region_id: region.id,
798 email: "foo@bar.com",
799 items: [
800 {
801 title: "Medusa T-shirt",
802 subtitle: "L shirt",
803 variant_id: product.variants.find((v) => v.title === "L shirt")
804 .id,
805 quantity: 2,
806 unit_price: 25,
807 },
808 {
809 title: "Medusa T-shirt",
810 subtitle: "M shirt",
811 variant_id: product.variants.find((v) => v.title === "M shirt")
812 .id,
813 quantity: 2,
814 unit_price: 25,
815 },
816 ],
817 sales_channel_id: salesChannel.id,
818 shipping_address: {
819 first_name: "Test",
820 last_name: "Test",
821 address_1: "Test",
822 city: "Test",
823 country_code: "US",
824 postal_code: "12345",
825 phone: "12345",
826 },
827 billing_address: {
828 first_name: "Test",
829 last_name: "Test",
830 address_1: "Test",
831 city: "Test",
832 country_code: "US",
833 postal_code: "12345",
834 },
835 shipping_methods: [
836 {
837 name: "Test shipping method",
838 amount: 10,
839 },
840 ],
841 currency_code: "usd",
842 customer_id: customer.id,
843 })
844
845 const remoteLink = container.resolve(
846 ContainerRegistrationKeys.REMOTE_LINK
847 )
848
849 await remoteLink.create([
850 {
851 [Modules.SALES_CHANNEL]: {
852 sales_channel_id: salesChannel.id,
853 },
854 [Modules.STOCK_LOCATION]: {
855 stock_location_id: location.id,
856 },
857 },
858 {
859 [Modules.SALES_CHANNEL]: {
860 sales_channel_id: salesChannel.id,
861 },
862 [Modules.STOCK_LOCATION]: {
863 stock_location_id: locationTwo.id,
864 },
865 },
866 ])
867 })
868
869 it("should manage reservations on order edit", async () => {
870 let edit = (
871 await api.post(
872 `/admin/order-edits`,
873 { order_id: inventoryOrder.id },
874 adminHeaders
875 )
876 ).data.order_change
877
878 // Add item
879 await api.post(
880 `/admin/order-edits/${inventoryOrder.id}/items`,
881 {
882 items: [
883 {
884 variant_id: product.variants.find((v) => v.title === "S shirt")
885 .id,
886 quantity: 1,
887 },
888 ],
889 },
890 adminHeaders
891 )
892
893 // Remove item
894 await api.post(
895 `/admin/order-edits/${inventoryOrder.id}/items/item/${
896 inventoryOrder.items.find((i) => i.subtitle === "M shirt").id
897 }`,
898 { quantity: 0 },
899 adminHeaders
900 )
901
902 // Update item
903 await api.post(
904 `/admin/order-edits/${inventoryOrder.id}/items/item/${
905 inventoryOrder.items.find((i) => i.subtitle === "L shirt").id
906 }`,
907 { quantity: 2 },
908 adminHeaders
909 )
910
911 edit = (
912 await api.post(
913 `/admin/order-edits/${inventoryOrder.id}/request`,
914 {},
915 adminHeaders
916 )
917 ).data.order_change
918
919 edit = (
920 await api.post(
921 `/admin/order-edits/${inventoryOrder.id}/confirm`,
922 {},
923 adminHeaders
924 )
925 ).data.order_change
926
927 inventoryOrder = (
928 await api.get(`/admin/orders/${inventoryOrder.id}`, adminHeaders)
929 ).data.order
930
931 expect(inventoryOrder.items.length).toBe(2)
932 expect(inventoryOrder.items).toEqual(
933 expect.arrayContaining([
934 expect.objectContaining({
935 subtitle: "L shirt",
936 quantity: 2,
937 }),
938 expect.objectContaining({
939 subtitle: "S shirt",
940 quantity: 1,
941 }),
942 ])
943 )
944 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
945 .data.reservations
946
947 expect(reservations.length).toBe(2)
948 expect(reservations).toEqual(
949 expect.arrayContaining([
950 expect.objectContaining({
951 inventory_item_id: inventoryItemLarge.id,
952 quantity: 2,
953 }),
954 expect.objectContaining({
955 inventory_item_id: inventoryItemSmall.id,
956 quantity: 1,
957 }),
958 ])
959 )
960 })
961
962 it("should manage inventory across locations in order edit", async () => {
963 let edit = (
964 await api.post(
965 `/admin/order-edits`,
966 { order_id: inventoryOrder.id },
967 adminHeaders
968 )
969 ).data.order_change
970
971 // Add item
972 await api.post(
973 `/admin/order-edits/${inventoryOrder.id}/items`,
974 {
975 items: [
976 {
977 variant_id: product.variants.find((v) => v.title === "L shirt")
978 .id,
979 quantity: 1,
980 },
981 ],
982 },
983 adminHeaders
984 )
985
986 edit = (
987 await api.post(
988 `/admin/order-edits/${inventoryOrder.id}/request`,
989 {},
990 adminHeaders
991 )
992 ).data.order_change
993
994 edit = (
995 await api.post(
996 `/admin/order-edits/${inventoryOrder.id}/confirm`,
997 {},
998 adminHeaders
999 )
1000 ).data.order_change
1001
1002 inventoryOrder = (
1003 await api.get(`/admin/orders/${inventoryOrder.id}`, adminHeaders)
1004 ).data.order
1005
1006 expect(inventoryOrder.items.length).toBe(3)
1007 expect(inventoryOrder.items).toEqual(
1008 expect.arrayContaining([
1009 expect.objectContaining({
1010 subtitle: "L shirt",
1011 quantity: 2,
1012 }),
1013 ])
1014 )
1015 })
1016
1017 it("should confirm an order edit with an out-of-stock item added with allow_backorder", async () => {
1018 await api.post(
1019 `/admin/order-edits`,
1020 { order_id: inventoryOrder.id },
1021 adminHeaders
1022 )
1023
1024 await api.post(
1025 `/admin/order-edits/${inventoryOrder.id}/items`,
1026 {
1027 items: [
1028 {
1029 variant_id: product.variants.find((v) => v.title === "S shirt")
1030 .id,
1031 quantity: 15,
1032 allow_backorder: true,
1033 },
1034 ],
1035 },
1036 adminHeaders
1037 )
1038
1039 await api.post(
1040 `/admin/order-edits/${inventoryOrder.id}/request`,
1041 {},
1042 adminHeaders
1043 )
1044
1045 const response = await api.post(
1046 `/admin/order-edits/${inventoryOrder.id}/confirm`,
1047 {},
1048 adminHeaders
1049 )
1050
1051 expect(response.status).toBe(200)
1052
1053 const reservations = (
1054 await api.get(
1055 `/admin/reservations?inventory_item_id[]=${inventoryItemSmall.id}`,
1056 adminHeaders
1057 )
1058 ).data.reservations
1059
1060 expect(reservations).toEqual([
1061 expect.objectContaining({
1062 inventory_item_id: inventoryItemSmall.id,
1063 quantity: 15,
1064 }),
1065 ])
1066 })
1067 })
1068
1069 describe("Order Edit Shipping Methods", () => {
1070 it("should add a shipping method through an order edit", async () => {
1071 await api.post(
1072 "/admin/order-edits",
1073 { order_id: order.id, description: "Test" },
1074 adminHeaders
1075 )
1076
1077 const orderId = order.id
1078
1079 const shippingMethodResponse = await api.post(
1080 `/admin/order-edits/${orderId}/shipping-method`,
1081 { shipping_option_id: shippingOption.id, custom_amount: 5 },
1082 adminHeaders
1083 )
1084
1085 expect(
1086 shippingMethodResponse.data.order_preview.shipping_methods.length
1087 ).toEqual(2)
1088 expect(
1089 shippingMethodResponse.data.order_preview.shipping_methods
1090 ).toEqual(
1091 expect.arrayContaining([
1092 expect.objectContaining({
1093 amount: 10,
1094 }),
1095 expect.objectContaining({
1096 amount: 5,
1097 }),
1098 ])
1099 )
1100
1101 const requestResult = await api.post(
1102 `/admin/order-edits/${orderId}/request`,
1103 {},
1104 adminHeaders
1105 )
1106
1107 expect(requestResult.data.order_preview.order_change.status).toEqual(
1108 OrderChangeStatus.REQUESTED
1109 )
1110
1111 await api.post(
1112 `/admin/order-edits/${orderId}/confirm`,
1113 {},
1114 adminHeaders
1115 )
1116
1117 const orderResult = await api.get(
1118 `/admin/orders/${orderId}`,
1119 adminHeaders
1120 )
1121
1122 expect(orderResult.data.order.shipping_methods.length).toEqual(2)
1123 expect(orderResult.data.order.shipping_methods).toEqual(
1124 expect.arrayContaining([
1125 expect.objectContaining({ amount: 10 }),
1126 expect.objectContaining({ amount: 5 }),
1127 ])
1128 )
1129
1130 const orderChangesResult = await api.get(
1131 `/admin/orders/${orderId}/changes?change_type=edit`,
1132 adminHeaders
1133 )
1134
1135 expect(orderChangesResult.data.order_changes.length).toEqual(1)
1136 expect(orderChangesResult.data.order_changes[0].status).toEqual(
1137 OrderChangeStatus.CONFIRMED
1138 )
1139 })
1140
1141 it("should store no_notification on the order change and pass it to the order edit events", async () => {
1142 const eventBus = container.resolve(Modules.EVENT_BUS)
1143 const requestedSubscriber = jest.fn()
1144 const confirmedSubscriber = jest.fn()
1145
1146 eventBus.subscribe(
1147 OrderEditWorkflowEvents.REQUESTED,
1148 requestedSubscriber
1149 )
1150 eventBus.subscribe(
1151 OrderEditWorkflowEvents.CONFIRMED,
1152 confirmedSubscriber
1153 )
1154
1155 const orderId = order.id
1156
1157 await api.post(
1158 "/admin/order-edits",
1159 { order_id: orderId, description: "Test" },
1160 adminHeaders
1161 )
1162
1163 await api.post(
1164 `/admin/order-edits/${orderId}/shipping-method`,
1165 { shipping_option_id: shippingOption.id, custom_amount: 5 },
1166 adminHeaders
1167 )
1168
1169 const requestResult = await api.post(
1170 `/admin/order-edits/${orderId}/request`,
1171 { no_notification: true },
1172 adminHeaders
1173 )
1174
1175 expect(requestResult.data.order_preview.order_change).toEqual(
1176 expect.objectContaining({ no_notification: true })
1177 )
1178
1179 await api.post(
1180 `/admin/order-edits/${orderId}/confirm`,
1181 {},
1182 adminHeaders
1183 )
1184
1185 const orderChangesResult = await api.get(
1186 `/admin/orders/${orderId}/changes?change_type=edit`,
1187 adminHeaders
1188 )
1189
1190 expect(orderChangesResult.data.order_changes[0]).toEqual(
1191 expect.objectContaining({ no_notification: true })
1192 )
1193
1194 await new Promise((resolve) => setTimeout(resolve, 100))
1195
1196 expect(requestedSubscriber.mock.calls[0][0].data).toMatchObject({
1197 order_id: orderId,
1198 no_notification: true,
1199 })
1200
1201 expect(confirmedSubscriber.mock.calls[0][0].data).toMatchObject({
1202 order_id: orderId,
1203 no_notification: true,
1204 })
1205
1206 eventBus.unsubscribe(
1207 OrderEditWorkflowEvents.REQUESTED,
1208 requestedSubscriber
1209 )
1210 eventBus.unsubscribe(
1211 OrderEditWorkflowEvents.CONFIRMED,
1212 confirmedSubscriber
1213 )
1214 })
1215 })
1216
1217 describe("Order Edit Payment Collection", () => {
1218 let appContainer
1219 let storeHeaders
1220 let region, product, salesChannel
1221
1222 const shippingAddressData = {
1223 address_1: "test address 1",
1224 address_2: "test address 2",
1225 city: "SF",
1226 country_code: "US",
1227 province: "CA",
1228 postal_code: "94016",
1229 }
1230
1231 beforeAll(async () => {
1232 appContainer = getContainer()
1233 })
1234
1235 beforeEach(async () => {
1236 const publishableKey = await generatePublishableKey(appContainer)
1237 storeHeaders = generateStoreHeaders({ publishableKey })
1238
1239 region = (
1240 await api.post(
1241 "/admin/regions",
1242 {
1243 payment_providers: ["pp_system_default"],
1244 name: "US",
1245 currency_code: "usd",
1246 countries: ["us"],
1247 },
1248 adminHeaders
1249 )
1250 ).data.region
1251
1252 product = (
1253 await api.post(
1254 "/admin/products",
1255 { ...medusaTshirtProduct },
1256 adminHeaders
1257 )
1258 ).data.product
1259
1260 salesChannel = (
1261 await api.post(
1262 "/admin/sales-channels",
1263 { name: "Webshop", description: "channel" },
1264 adminHeaders
1265 )
1266 ).data.sales_channel
1267 })
1268
1269 it("should add a create a new payment collection if the order has authorized payment collection", async () => {
1270 const cart = (
1271 await api.post(
1272 `/store/carts`,
1273 {
1274 currency_code: "usd",
1275 sales_channel_id: salesChannel.id,
1276 region_id: region.id,
1277 shipping_address: shippingAddressData,
1278 items: [{ variant_id: product.variants[0].id, quantity: 1 }],
1279 },
1280 storeHeaders
1281 )
1282 ).data.cart
1283
1284 const paymentCollection = (
1285 await api.post(
1286 `/store/payment-collections`,
1287 { cart_id: cart.id },
1288 storeHeaders
1289 )
1290 ).data.payment_collection
1291
1292 await api.post(
1293 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
1294 { provider_id: "pp_system_default" },
1295 storeHeaders
1296 )
1297
1298 const order = (
1299 await api.post(
1300 `/store/carts/${cart.id}/complete`,
1301 { cart_id: cart.id },
1302 storeHeaders
1303 )
1304 ).data.order
1305
1306 await api.post(
1307 `/admin/order-edits`,
1308 { order_id: order.id, description: "Test" },
1309 adminHeaders
1310 )
1311
1312 await api.post(
1313 `/admin/order-edits/${order.id}/items`,
1314 {
1315 items: [
1316 {
1317 variant_id: product.variants[0].id,
1318 quantity: 1,
1319 },
1320 ],
1321 },
1322 adminHeaders
1323 )
1324
1325 await api.post(
1326 `/admin/order-edits/${order.id}/confirm`,
1327 {},
1328 adminHeaders
1329 )
1330
1331 const orderResult = (
1332 await api.get(`/admin/orders/${order.id}`, adminHeaders)
1333 ).data.order
1334
1335 expect(orderResult.payment_collections).toEqual(
1336 expect.arrayContaining([
1337 expect.objectContaining({
1338 id: paymentCollection.id,
1339 status: "canceled",
1340 }),
1341 expect.objectContaining({
1342 id: expect.any(String),
1343 status: "not_paid",
1344 amount: orderResult.total,
1345 }),
1346 ])
1347 )
1348 })
1349 })
1350
1351 describe("Order Edits promotions", () => {
1352 let appliedPromotion
1353 let promotionModule: IPromotionModuleService
1354 let orderModule: IOrderModuleService
1355 let remoteLink
1356
1357 beforeEach(async () => {
1358 promotionModule = container.resolve(Modules.PROMOTION)
1359 remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
1360
1361 appliedPromotion = await promotionModule.createPromotions({
1362 code: "PROMOTION_APPLIED",
1363 type: PromotionType.STANDARD,
1364 status: PromotionStatus.ACTIVE,
1365 application_method: {
1366 type: "percentage",
1367 target_type: "order",
1368 allocation: "across",
1369 value: 10,
1370 currency_code: "usd",
1371 target_rules: [],
1372 },
1373 })
1374
1375 await remoteLink.create([
1376 {
1377 [Modules.SALES_CHANNEL]: {
1378 sales_channel_id: salesChannel.id,
1379 },
1380 [Modules.STOCK_LOCATION]: {
1381 stock_location_id: location.id,
1382 },
1383 },
1384 ])
1385
1386 orderModule = container.resolve(Modules.ORDER)
1387
1388 // @ts-ignore
1389 order = await orderModule.createOrders({
1390 email: "foo@bar.com",
1391 region_id: region.id,
1392 sales_channel_id: salesChannel.id,
1393 items: [
1394 {
1395 // @ts-ignore
1396 id: "item-1",
1397 title: "Custom Item",
1398 quantity: 1,
1399 unit_price: 10,
1400 },
1401 ],
1402 shipping_address: {
1403 first_name: "Test",
1404 last_name: "Test",
1405 address_1: "Test",
1406 city: "Test",
1407 country_code: "US",
1408 postal_code: "12345",
1409 phone: "12345",
1410 },
1411 billing_address: {
1412 first_name: "Test",
1413 last_name: "Test",
1414 address_1: "Test",
1415 city: "Test",
1416 country_code: "US",
1417 postal_code: "12345",
1418 },
1419 currency_code: "usd",
1420 })
1421
1422 await orderModule.createOrderLineItemTaxLines(order.id, [
1423 {
1424 // TODO check why item_id is not in param
1425 // @ts-ignore
1426 item_id: "item-1",
1427 code: "tax-1",
1428 rate: 10,
1429 description: "tax-1",
1430 // @ts-ignore
1431 code: "standard",
1432 provider_id: "system",
1433 total: 1.2,
1434 subtotal: 1.2,
1435 },
1436 ])
1437
1438 await orderModule.createOrderLineItemAdjustments([
1439 {
1440 version: 1,
1441 code: appliedPromotion.code!,
1442 amount: 1,
1443 item_id: "item-1",
1444 promotion_id: appliedPromotion.id,
1445 },
1446 ])
1447
1448 await remoteLink.create({
1449 [Modules.ORDER]: { order_id: order.id },
1450 [Modules.PROMOTION]: { promotion_id: appliedPromotion.id },
1451 })
1452 })
1453
1454 it("should update adjustments when adding a new item", async () => {
1455 let result = await api.post(
1456 "/admin/order-edits",
1457 {
1458 order_id: order.id,
1459 description: "Test",
1460 },
1461 adminHeaders
1462 )
1463
1464 // allow carry over promotions flag on the edit
1465 const orderChangeId = result.data.order_change.id
1466 await api.post(
1467 `/admin/order-changes/${orderChangeId}`,
1468 {
1469 carry_over_promotions: true,
1470 },
1471 adminHeaders
1472 )
1473
1474 const orderId = result.data.order_change.order_id
1475
1476 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
1477 .order
1478
1479 expect(result.original_total).toEqual(11) // $10 + 10% tax
1480 expect(result.total).toEqual(10 * 0.9 * 1.1) // ($10 - 10% discount) + 10% tax
1481
1482 // Add item with price $12, 10% discount and 10% tax
1483 result = (
1484 await api.post(
1485 `/admin/order-edits/${orderId}/items`,
1486 {
1487 items: [
1488 {
1489 variant_id: productExtra.variants[0].id,
1490 quantity: 1,
1491 },
1492 ],
1493 },
1494 adminHeaders
1495 )
1496 ).data.order_preview
1497
1498 // two items of $12 and $10 and 10% discount -> subtotal is $22 - 10% discount = $19.8
1499 // Aside from this there is a tax rate of 10%, which adds (19.8 / 10 = $1.98)
1500 // Total is $19.8 + $1.98 = $21.78
1501 expect(result.total).toEqual(21.78)
1502 expect(result.original_total).toEqual(24.2) // $22 + 10% tax
1503
1504 // Confirm that the adjustment values are correct
1505 const adjustments = result.items[0].adjustments
1506 const adjustments2 = result.items[1].adjustments
1507 expect(adjustments).toEqual([
1508 expect.objectContaining({
1509 amount: 1,
1510 }),
1511 ])
1512 expect(adjustments2).toEqual([
1513 expect.objectContaining({
1514 amount: 1.2,
1515 }),
1516 ])
1517
1518 const orderResult = (
1519 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1520 ).data.order
1521
1522 // confirm original order is not updated
1523 expect(orderResult.total).toEqual(9.9) // initial item 10$ and 10% discount and 10% tax
1524 expect(orderResult.original_total).toEqual(11) // initial item 10$ + 10% tax
1525
1526 await api.post(
1527 `/admin/order-edits/${orderId}/confirm`,
1528 {},
1529 adminHeaders
1530 )
1531
1532 const orderResult2 = (
1533 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1534 ).data.order
1535
1536 expect(orderResult2.total).toEqual(21.78)
1537 expect(orderResult2.original_total).toEqual(24.2)
1538 })
1539
1540 it("should apply customer group and collection rules on new items", async () => {
1541 const customerGroup = (
1542 await api.post(
1543 "/admin/customer-groups",
1544 {
1545 name: "VIP Customers",
1546 },
1547 adminHeaders
1548 )
1549 ).data.customer_group
1550
1551 const customer = (
1552 await api.post(
1553 "/admin/customers",
1554 {
1555 first_name: "Group",
1556 last_name: "Customer",
1557 email: "group.customer@admin.com",
1558 },
1559 adminHeaders
1560 )
1561 ).data.customer
1562
1563 await api.post(
1564 `/admin/customer-groups/${customerGroup.id}/customers`,
1565 { add: [customer.id] },
1566 adminHeaders
1567 )
1568
1569 const collection = (
1570 await api.post(
1571 "/admin/collections",
1572 {
1573 title: "Promo Collection",
1574 },
1575 adminHeaders
1576 )
1577 ).data.collection
1578
1579 await api.post(
1580 `/admin/products/${productExtra.id}`,
1581 {
1582 collection_id: collection.id,
1583 },
1584 adminHeaders
1585 )
1586
1587 const promotion = (
1588 await api.post(
1589 "/admin/promotions",
1590 {
1591 code: "GROUP_COLLECTION_RULE",
1592 type: PromotionType.STANDARD,
1593 status: PromotionStatus.ACTIVE,
1594 application_method: {
1595 type: "fixed",
1596 target_type: "items",
1597 allocation: "each",
1598 value: 5,
1599 max_quantity: 10,
1600 currency_code: "usd",
1601 target_rules: [
1602 {
1603 attribute: "items.product.collection_id",
1604 operator: RuleOperator.IN,
1605 values: [collection.id],
1606 },
1607 ],
1608 },
1609 rules: [
1610 {
1611 attribute: "customer.groups.id",
1612 operator: RuleOperator.IN,
1613 values: [customerGroup.id],
1614 },
1615 ],
1616 },
1617 adminHeaders
1618 )
1619 ).data.promotion
1620
1621 const orderForPromotion = await orderModule.createOrders({
1622 email: "group.customer@admin.com",
1623 region_id: region.id,
1624 sales_channel_id: salesChannel.id,
1625 items: [
1626 {
1627 variant_id: buyRuleProduct.variants[0].id,
1628 title: "original item",
1629 quantity: 1,
1630 unit_price: 10,
1631 },
1632 ],
1633 shipping_address: {
1634 first_name: "Group",
1635 last_name: "Customer",
1636 address_1: "Test",
1637 city: "Test",
1638 country_code: "US",
1639 postal_code: "12345",
1640 },
1641 billing_address: {
1642 first_name: "Group",
1643 last_name: "Customer",
1644 address_1: "Test",
1645 city: "Test",
1646 country_code: "US",
1647 postal_code: "12345",
1648 },
1649 currency_code: "usd",
1650 customer_id: customer.id,
1651 })
1652
1653 await remoteLink.create({
1654 [Modules.ORDER]: { order_id: orderForPromotion.id },
1655 [Modules.PROMOTION]: { promotion_id: promotion.id },
1656 })
1657
1658 let result = await api.post(
1659 "/admin/order-edits",
1660 {
1661 order_id: orderForPromotion.id,
1662 description: "Test",
1663 },
1664 adminHeaders
1665 )
1666
1667 const orderChangeId = result.data.order_change.id
1668 await api.post(
1669 `/admin/order-changes/${orderChangeId}`,
1670 {
1671 carry_over_promotions: true,
1672 },
1673 adminHeaders
1674 )
1675
1676 result = (
1677 await api.post(
1678 `/admin/order-edits/${orderForPromotion.id}/items`,
1679 {
1680 items: [
1681 {
1682 variant_id: productExtra.variants[0].id,
1683 quantity: 1,
1684 },
1685 ],
1686 },
1687 adminHeaders
1688 )
1689 ).data.order_preview
1690
1691 const collectionItem = result.items.find(
1692 (item) => item.variant_id === productExtra.variants[0].id
1693 )
1694 const nonCollectionItem = result.items.find(
1695 (item) => item.variant_id === buyRuleProduct.variants[0].id
1696 )
1697
1698 expect(collectionItem.adjustments).toEqual([
1699 expect.objectContaining({
1700 amount: 5,
1701 }),
1702 ])
1703 expect(nonCollectionItem.adjustments).toEqual([])
1704 })
1705
1706 it("should update adjustments when updating an item", async () => {
1707 let result = await api.post(
1708 "/admin/order-edits",
1709 {
1710 order_id: order.id,
1711 description: "Test",
1712 },
1713 adminHeaders
1714 )
1715
1716 const orderId = result.data.order_change.order_id
1717
1718 // allow carry over promotions flag on the edit
1719 const orderChangeId = result.data.order_change.id
1720 await api.post(
1721 `/admin/order-changes/${orderChangeId}`,
1722 {
1723 carry_over_promotions: true,
1724 },
1725 adminHeaders
1726 )
1727
1728 const item = order.items[0]
1729
1730 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
1731 .order
1732
1733 expect(result.original_total).toEqual(11) // $10 + 10% tax
1734 expect(result.total).toEqual(9.9) // ($10 - 10% discount) + 10% tax = 9 + 0.9 = 9.9
1735
1736 let adjustments = result.items[0].adjustments
1737
1738 expect(adjustments).toEqual([
1739 expect.objectContaining({
1740 amount: 1,
1741 item_id: item.id,
1742 version: 1,
1743 }),
1744 ])
1745
1746 // Update item quantity
1747 result = (
1748 await api.post(
1749 `/admin/order-edits/${orderId}/items/item/${item.id}`,
1750 {
1751 quantity: 2,
1752 },
1753 adminHeaders
1754 )
1755 ).data.order_preview
1756
1757 expect(result.original_total).toEqual(22) // $20 + 10% tax
1758 expect(result.total).toEqual(19.8) // ($20 - 10% discount) + 10% tax = 18 + 1.8 = 19.8
1759
1760 adjustments = result.items[0].adjustments
1761
1762 expect(adjustments).toEqual([
1763 expect.objectContaining({
1764 amount: 2,
1765 item_id: item.id,
1766 // version: 2,
1767 }),
1768 ])
1769
1770 const orderResult = (
1771 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1772 ).data.order
1773
1774 // confirm original order is not updated
1775 expect(orderResult.original_total).toEqual(11)
1776 expect(orderResult.total).toEqual(9.9)
1777
1778 await api.post(
1779 `/admin/order-edits/${orderId}/confirm`,
1780 {},
1781 adminHeaders
1782 )
1783
1784 const orderResult2 = (
1785 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1786 ).data.order
1787
1788 expect(orderResult2.original_total).toEqual(22)
1789 expect(orderResult2.total).toEqual(19.8)
1790 })
1791
1792 it("should update adjustments when removing an item", async () => {
1793 let result = await api.post(
1794 "/admin/order-edits",
1795 {
1796 order_id: order.id,
1797 description: "Test",
1798 },
1799 adminHeaders
1800 )
1801
1802 const orderId = result.data.order_change.order_id
1803
1804 // allow carry over promotions flag on the edit
1805 const orderChangeId = result.data.order_change.id
1806 await api.post(
1807 `/admin/order-changes/${orderChangeId}`,
1808 {
1809 carry_over_promotions: true,
1810 },
1811 adminHeaders
1812 )
1813
1814 const item = order.items[0]
1815
1816 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
1817 .order
1818
1819 expect(result.original_total).toEqual(11) // $10 + 10% tax
1820 expect(result.total).toEqual(9.9) // ($10 - 10% discount) + 10% tax = 9 + 0.9 = 9.9
1821
1822 let adjustments = result.items[0].adjustments
1823
1824 expect(adjustments).toEqual([
1825 expect.objectContaining({
1826 amount: 1,
1827 item_id: item.id,
1828 }),
1829 ])
1830
1831 result = (
1832 await api.post(
1833 `/admin/order-edits/${orderId}/items`,
1834 {
1835 items: [
1836 {
1837 variant_id: productExtra.variants[0].id,
1838 quantity: 1,
1839 },
1840 ],
1841 },
1842 adminHeaders
1843 )
1844 ).data.order_preview
1845
1846 const orderItems = result.items
1847
1848 expect(orderItems).toEqual([
1849 expect.objectContaining({
1850 adjustments: [
1851 expect.objectContaining({
1852 amount: 1,
1853 item_id: item.id,
1854 }),
1855 ],
1856 }),
1857 expect.objectContaining({
1858 adjustments: [
1859 expect.objectContaining({
1860 amount: 1.2,
1861 }),
1862 ],
1863 }),
1864 ])
1865
1866 const newItem = result.items.find(
1867 (item) => item.variant_id === productExtra.variants[0].id
1868 )
1869
1870 const actionId = newItem.actions[0].id
1871
1872 result = (
1873 await api.delete(
1874 `/admin/order-edits/${orderId}/items/${actionId}`,
1875 adminHeaders
1876 )
1877 ).data.order_preview
1878
1879 adjustments = result.items[0].adjustments
1880
1881 expect(adjustments).toEqual([
1882 expect.objectContaining({
1883 amount: 1,
1884 item_id: item.id,
1885 }),
1886 ])
1887
1888 const orderResult = (
1889 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1890 ).data.order
1891
1892 // confirm original order is not updated
1893 expect(orderResult.total).toEqual(9.9)
1894 expect(orderResult.original_total).toEqual(11)
1895
1896 await api.post(
1897 `/admin/order-edits/${orderId}/confirm`,
1898 {},
1899 adminHeaders
1900 )
1901
1902 const orderResult2 = (
1903 await api.get(`/admin/orders/${orderId}`, adminHeaders)
1904 ).data.order
1905
1906 expect(orderResult2.total).toEqual(9.9)
1907 expect(orderResult2.original_total).toEqual(11)
1908 })
1909
1910 it("should update adjustments correctly when adding items in 2 consecutive order edits", async () => {
1911 // 1. Create the first order edit
1912 let response = await api.post(
1913 "/admin/order-edits",
1914 {
1915 order_id: order.id,
1916 description: "First order edit",
1917 },
1918 adminHeaders
1919 )
1920 const orderChange1 = response.data.order_change
1921
1922 // allow carry over promotions flag on the edit
1923 const orderChangeId = response.data.order_change.id
1924 await api.post(
1925 `/admin/order-changes/${orderChangeId}`,
1926 {
1927 carry_over_promotions: true,
1928 },
1929 adminHeaders
1930 )
1931
1932 // 2. Add a new item in the first edit
1933 response = await api.post(
1934 `/admin/order-edits/${orderChange1.order_id}/items`,
1935 {
1936 items: [
1937 {
1938 variant_id: productExtra.variants[0].id,
1939 quantity: 1,
1940 },
1941 ],
1942 },
1943 adminHeaders
1944 )
1945 let orderEditPreview1 = response.data.order_preview
1946
1947 const originalItem = orderEditPreview1.items.find(
1948 (i) => i.variant_id === order.items[0].variant_id
1949 )
1950 const addedItem1 = orderEditPreview1.items.find(
1951 (i) => i.variant_id === productExtra.variants[0].id
1952 )
1953 expect(addedItem1).toBeDefined()
1954 expect(addedItem1.quantity).toBe(1)
1955 expect(orderEditPreview1.items.length).toBe(2)
1956
1957 // Validate adjustments for added item in edit 1
1958 expect(addedItem1.adjustments).toEqual([
1959 expect.objectContaining({
1960 item_id: addedItem1.id,
1961 amount: 1.2,
1962 }),
1963 ])
1964
1965 // Validate total and original total after first edit
1966 // original: $10 (orig item) + $12 (added) = $22 → 10% tax = $2.2 → 24.2
1967 // promo: -$1 (orig item), -$1.2 (added) → subtotal $19.8, 10% = 1.98 → 21.78
1968 expect(orderEditPreview1.original_total).toBeCloseTo(24.2)
1969 expect(orderEditPreview1.total).toBeCloseTo(21.78)
1970
1971 // 3. Confirm the first order edit
1972 response = await api.post(
1973 `/admin/order-edits/${orderChange1.order_id}/confirm`,
1974 {},
1975 adminHeaders
1976 )
1977 expect(response.status).toBe(200)
1978
1979 // validate order
1980 let orderResult = (
1981 await api.get(`/admin/orders/${order.id}`, adminHeaders)
1982 ).data.order
1983 expect(orderResult.original_total).toEqual(24.2)
1984 expect(orderResult.total).toEqual(21.78)
1985
1986 expect(orderResult.items).toEqual(
1987 expect.arrayContaining([
1988 expect.objectContaining({
1989 id: originalItem.id,
1990 adjustments: expect.arrayContaining([
1991 expect.objectContaining({
1992 item_id: originalItem.id,
1993 amount: 1,
1994 version: 2,
1995 }),
1996 ]),
1997 }),
1998 expect.objectContaining({
1999 id: addedItem1.id,
2000 adjustments: expect.arrayContaining([
2001 expect.objectContaining({
2002 item_id: addedItem1.id,
2003 amount: 1.2,
2004 version: 2,
2005 }),
2006 ]),
2007 }),
2008 ])
2009 )
2010
2011 // 4. Create the second order edit
2012 response = await api.post(
2013 "/admin/order-edits",
2014 {
2015 order_id: order.id,
2016 description: "Second order edit",
2017 },
2018 adminHeaders
2019 )
2020 const orderChange2 = response.data.order_change
2021 await api.post(
2022 `/admin/order-changes/${orderChange2.id}`,
2023 {
2024 carry_over_promotions: true,
2025 },
2026 adminHeaders
2027 )
2028
2029 // 5. Add another productExtra item
2030 response = await api.post(
2031 `/admin/order-edits/${orderChange2.order_id}/items`,
2032 {
2033 items: [
2034 {
2035 variant_id: productExtra.variants[0].id,
2036 quantity: 2,
2037 },
2038 ],
2039 },
2040 adminHeaders
2041 )
2042
2043 let orderEditPreview2 = response.data.order_preview
2044
2045 // Adjustments should account for all quantity
2046 // The individual adjustment for this add: -$1.2 per quantity added (for second edit), but for a 3-quantity line, adjustment stack
2047 // We must find the two promo adjustments (from first and second edit): -$1.2 (from before, quantity 1), -$2.4 (from just now, quantity 2)
2048 // Check that at least two adjustments exist with matching amount
2049 expect(orderEditPreview2.items).toEqual(
2050 expect.arrayContaining([
2051 expect.objectContaining({
2052 id: originalItem.id,
2053 adjustments: expect.arrayContaining([
2054 expect.objectContaining({
2055 item_id: originalItem.id,
2056 amount: 1,
2057 // version: 3,
2058 }),
2059 ]),
2060 }),
2061 // added in 1st edit
2062 expect.objectContaining({
2063 id: expect.any(String),
2064 adjustments: expect.arrayContaining([
2065 expect.objectContaining({
2066 item_id: expect.any(String),
2067 amount: 1.2,
2068 // version: 3,
2069 }),
2070 ]),
2071 }),
2072 // added in 2nd edit
2073 expect.objectContaining({
2074 id: expect.any(String),
2075 adjustments: expect.arrayContaining([
2076 expect.objectContaining({
2077 item_id: expect.any(String),
2078 amount: 2.4,
2079 // version: 3,
2080 }),
2081 ]),
2082 }),
2083 ])
2084 )
2085 // Validate totals after the second edit with explicit numbers
2086 // Original: $10 (orig) + $12*3 (added, 3 qty) = 10+36=46; 46*0.1=4.6 tax -> 50.6
2087 // Promos: -$1 (orig), -$1.2 (first add), -$2.4 (second add, 2 qty * 1.2)
2088 // subtotal after promos: 46 - 1 - 1.2 - 2.4 = 41.4; 41.4*0.1=4.14 tax -> total: 45.54
2089 expect(orderEditPreview2.original_total).toBeCloseTo(50.6)
2090 expect(orderEditPreview2.total).toBeCloseTo(45.54)
2091
2092 // validate that order is in the same state as after the first edit before we confirm the second edit
2093 orderResult = (await api.get(`/admin/orders/${order.id}`, adminHeaders))
2094 .data.order
2095 expect(orderResult.original_total).toEqual(24.2)
2096 expect(orderResult.total).toEqual(21.78)
2097
2098 expect(orderResult.items).toEqual(
2099 expect.arrayContaining([
2100 expect.objectContaining({
2101 id: originalItem.id,
2102 adjustments: expect.arrayContaining([
2103 expect.objectContaining({
2104 item_id: originalItem.id,
2105 amount: 1,
2106 version: 2,
2107 }),
2108 ]),
2109 }),
2110 expect.objectContaining({
2111 id: addedItem1.id,
2112 adjustments: expect.arrayContaining([
2113 expect.objectContaining({
2114 item_id: addedItem1.id,
2115 amount: 1.2,
2116 version: 2,
2117 }),
2118 ]),
2119 }),
2120 ])
2121 )
2122
2123 // 6. Confirm the second order edit
2124 response = await api.post(
2125 `/admin/order-edits/${orderChange2.order_id}/confirm`,
2126 {},
2127 adminHeaders
2128 )
2129 expect(response.status).toBe(200)
2130
2131 // 7. Retrieve the final order and validate
2132 response = await api.get(`/admin/orders/${order.id}`, adminHeaders)
2133 const finalOrder = response.data.order
2134
2135 // Adjustments in DB: two on added item
2136 expect(finalOrder.items).toEqual(
2137 expect.arrayContaining([
2138 expect.objectContaining({
2139 id: originalItem.id,
2140 adjustments: expect.arrayContaining([
2141 expect.objectContaining({
2142 item_id: originalItem.id,
2143 amount: 1,
2144 version: 3,
2145 }),
2146 ]),
2147 }),
2148 expect.objectContaining({
2149 id: addedItem1.id,
2150 adjustments: expect.arrayContaining([
2151 expect.objectContaining({
2152 item_id: addedItem1.id,
2153 amount: 1.2,
2154 version: 3,
2155 }),
2156 ]),
2157 }),
2158 expect.objectContaining({
2159 id: expect.any(String),
2160 adjustments: expect.arrayContaining([
2161 expect.objectContaining({
2162 item_id: expect.any(String),
2163 amount: 2.4,
2164 version: 3,
2165 }),
2166 ]),
2167 }),
2168 ])
2169 )
2170
2171 // Totals should match previous calculation
2172 expect(finalOrder.original_total).toBeCloseTo(50.6)
2173 expect(finalOrder.total).toBeCloseTo(45.54)
2174 })
2175
2176 it("should update adjustments correctly when 2 promotions are applied (one is fixed, one is percentage)", async () => {
2177 const publishableKey = await generatePublishableKey(container)
2178 const storeHeaders = generateStoreHeaders({ publishableKey })
2179
2180 const product = (
2181 await api.post(
2182 "/admin/products",
2183 {
2184 title: "Prod 1",
2185 status: ProductStatus.PUBLISHED,
2186 sales_channels: [{ id: salesChannel.id }],
2187
2188 options: [{ title: "size", values: ["large", "small"] }],
2189 shipping_profile_id: undefined,
2190 variants: [
2191 {
2192 title: "Prod 1 variant",
2193 manage_inventory: false,
2194 sku: "prod-1-variant-123",
2195 options: { size: "large" },
2196 prices: [
2197 {
2198 currency_code: "usd",
2199 amount: 10,
2200 },
2201 ],
2202 },
2203 ],
2204 },
2205 adminHeaders
2206 )
2207 ).data.product
2208
2209 // 1. Create two promotions: one fixed ($2 off), one 10% off
2210 const fixedPromotion = await api.post(
2211 "/admin/promotions",
2212 {
2213 code: "FIXED2",
2214 type: "standard",
2215 status: "active",
2216 application_method: {
2217 type: "fixed",
2218 currency_code: "usd",
2219 target_type: "items",
2220 allocation: "each",
2221 max_quantity: 5,
2222 value: 2,
2223 },
2224 is_automatic: false,
2225 },
2226 adminHeaders
2227 )
2228
2229 const percentPromotion = await api.post(
2230 "/admin/promotions",
2231 {
2232 code: "PERCENT10",
2233 type: "standard",
2234 status: "active",
2235 application_method: {
2236 type: "percentage",
2237 currency_code: "usd",
2238 target_type: "items",
2239 allocation: "across",
2240 value: 10,
2241 },
2242 is_automatic: false,
2243 },
2244 adminHeaders
2245 )
2246
2247 // 2. Create a fresh cart with a single item
2248 const freshCartRes = await api.post(
2249 "/store/carts",
2250 {
2251 sales_channel_id: salesChannel.id,
2252 currency_code: "usd",
2253 region_id: order.region_id,
2254 email: "multi-promo@example.com",
2255 items: [
2256 {
2257 variant_id: product.variants[0].id,
2258 quantity: 1,
2259 },
2260 ],
2261 // Apply both promotions to the cart
2262 promo_codes: ["FIXED2", "PERCENT10"],
2263 },
2264 storeHeaders
2265 )
2266
2267 const freshCartId = freshCartRes.data.cart.id
2268
2269 const paymentCollection = (
2270 await api.post(
2271 `/store/payment-collections`,
2272 { cart_id: freshCartId },
2273 storeHeaders
2274 )
2275 ).data.payment_collection
2276
2277 await api.post(
2278 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
2279 {
2280 provider_id: "pp_system_default",
2281 },
2282 storeHeaders
2283 )
2284
2285 const completeOrderRes = await api.post(
2286 `/store/carts/${freshCartId}/complete`,
2287 {},
2288 storeHeaders
2289 )
2290
2291 const newOrderId = completeOrderRes.data.order.id
2292 let response = await api.get(
2293 `/admin/orders/${newOrderId}`,
2294 adminHeaders
2295 )
2296 let freshOrder = response.data.order
2297 const originalItem = freshOrder.items[0]
2298
2299 // Check adjustments on item: should have both promos
2300 expect(originalItem.adjustments).toEqual(
2301 expect.arrayContaining([
2302 expect.objectContaining({
2303 amount: 2, // fixed accross
2304 code: "FIXED2",
2305 }),
2306 expect.objectContaining({
2307 amount: 1, // 10% off
2308 code: "PERCENT10",
2309 }),
2310 ])
2311 )
2312
2313 expect(freshOrder.original_total).toBe(10) // just 10$ item without tax
2314 expect(freshOrder.total).toBe(7) // 10$ - 2$ fixed - 10% = 7$
2315
2316 const editRes = await api.post(
2317 "/admin/order-edits",
2318 {
2319 order_id: newOrderId,
2320 },
2321 adminHeaders
2322 )
2323
2324 // allow carry over promotions flag on the edit
2325 const orderChangeId = editRes.data.order_change.id
2326 await api.post(
2327 `/admin/order-changes/${orderChangeId}`,
2328 {
2329 carry_over_promotions: true,
2330 },
2331 adminHeaders
2332 )
2333
2334 const editOrderId = editRes.data.order_change.order_id
2335 const extraVariantId = productExtra.variants[0].id
2336
2337 const addedItemsResult = (
2338 await api.post(
2339 `/admin/order-edits/${editOrderId}/items`,
2340 {
2341 items: [
2342 {
2343 variant_id: extraVariantId,
2344 quantity: 1,
2345 },
2346 ],
2347 },
2348 adminHeaders
2349 )
2350 ).data.order_preview
2351
2352 const addedItem = addedItemsResult.items.find(
2353 (i) => i.variant_id === extraVariantId
2354 )
2355
2356 const initialItem = addedItemsResult.items.find(
2357 (i) => i.variant_id === product.variants[0].id
2358 )
2359 expect(addedItem).toBeDefined()
2360
2361 // Should have both promo adjustments on new item as well
2362 expect(addedItem.adjustments).toEqual(
2363 expect.arrayContaining([
2364 expect.objectContaining({
2365 code: "FIXED2",
2366 amount: 2,
2367 version: 2,
2368 }),
2369 expect.objectContaining({
2370 code: "PERCENT10",
2371 amount: 1.2,
2372 version: 2,
2373 }),
2374 ])
2375 )
2376
2377 expect(addedItemsResult.original_total).toBe(10 + 12)
2378 expect(addedItemsResult.total).toBe(15.8) // 22$ - 2$ - 2$ - 1.2$ - 1$
2379
2380 expect(initialItem.adjustments).toEqual(
2381 expect.arrayContaining([
2382 expect.objectContaining({
2383 code: "FIXED2",
2384 amount: 2,
2385 }),
2386 expect.objectContaining({
2387 code: "PERCENT10",
2388 amount: 1,
2389 }),
2390 ])
2391 )
2392
2393 const initialOrder = (
2394 await api.get(`/admin/orders/${newOrderId}`, adminHeaders)
2395 ).data.order
2396
2397 // original order is still unchanged
2398 expect(initialOrder.original_total).toBe(10)
2399 expect(initialOrder.total).toBe(7)
2400
2401 await api.post(
2402 `/admin/order-edits/${editOrderId}/confirm`,
2403 {},
2404 adminHeaders
2405 )
2406
2407 const confirmedOrder = (
2408 await api.get(`/admin/orders/${newOrderId}`, adminHeaders)
2409 ).data.order
2410
2411 expect(confirmedOrder.original_total).toBe(10 + 12)
2412 expect(confirmedOrder.total).toBe(15.8) // 22$ - 2$ - 2$ - 1.2$ - 1$
2413 })
2414
2415 it("should update adjustments when adding then updating then removing the original item", async () => {
2416 // Create a new order edit
2417 let result = await api.post(
2418 "/admin/order-edits",
2419 {
2420 order_id: order.id,
2421 description: "Test",
2422 },
2423 adminHeaders
2424 )
2425
2426 const orderId = result.data.order_change.order_id
2427 const originalItem = order.items[0]
2428
2429 // allow carry over promotions flag on the edit
2430 const orderChangeId = result.data.order_change.id
2431 await api.post(
2432 `/admin/order-changes/${orderChangeId}`,
2433 {
2434 carry_over_promotions: true,
2435 },
2436 adminHeaders
2437 )
2438
2439 // Add a new item
2440 result = (
2441 await api.post(
2442 `/admin/order-edits/${orderId}/items`,
2443 {
2444 items: [
2445 {
2446 variant_id: productExtra.variants[0].id,
2447 quantity: 1,
2448 },
2449 ],
2450 },
2451 adminHeaders
2452 )
2453 ).data.order_preview
2454
2455 const addedItem = result.items.find(
2456 (i) => i.variant_id === productExtra.variants[0].id
2457 )
2458 expect(addedItem).toBeDefined() // item is added
2459 expect(result.original_total).toEqual(24.2) // ($10 + $12) + 10% tax = 22 + 2.2 = 24.2
2460 expect(result.total).toEqual(21.78) // ($10 + $12 - $1 - $1.2) + 10% tax = 10 + 12 - 2.2 = 19.8 + 1.98 = 21.78
2461
2462 let adjustments = addedItem.adjustments
2463 expect(adjustments).toEqual([
2464 expect.objectContaining({
2465 item_id: addedItem.id,
2466 amount: 1.2,
2467 }),
2468 ])
2469
2470 // Update the quantity of the newly added item by updating the action
2471 const actionId = addedItem.actions.find(
2472 (a) => a.action === "ITEM_ADD"
2473 )?.id
2474
2475 result = (
2476 await api.post(
2477 `/admin/order-edits/${orderId}/items/${actionId}`,
2478 {
2479 quantity: 2,
2480 },
2481 adminHeaders
2482 )
2483 ).data.order_preview
2484
2485 let updatedAddedItem = result.items.find((i) => i.id === addedItem.id)
2486
2487 expect(result.original_total).toEqual(37.4) // $10 + $12*2 = 10+24=34 + 10% tax = 3.4 = 37.4
2488 expect(result.total).toEqual(33.66) // ($10 + $24 - $1 - $2.4) + 10% tax = 31.6 + 3.16 = 34.76
2489
2490 adjustments = updatedAddedItem.adjustments
2491 expect(adjustments).toEqual([
2492 expect.objectContaining({
2493 item_id: updatedAddedItem.id,
2494 amount: 2.4,
2495 }),
2496 ])
2497
2498 // Remove the original item by setting its quantity to 0
2499 result = (
2500 await api.post(
2501 `/admin/order-edits/${orderId}/items/item/${originalItem.id}`,
2502 {
2503 quantity: 0,
2504 },
2505 adminHeaders
2506 )
2507 ).data.order_preview
2508
2509 // $12*2 + 10% tax = $24 + $2.4 = $26.4
2510 expect(result.original_total).toEqual(26.4)
2511 expect(result.total).toEqual(23.76) // ($24 - $2.4) + $2.16 = $21.6 + $2.16 = $23.76
2512
2513 updatedAddedItem = result.items.find((i) => i.id === addedItem.id)
2514 adjustments = updatedAddedItem.adjustments
2515 expect(adjustments).toEqual([
2516 expect.objectContaining({
2517 item_id: updatedAddedItem.id,
2518 amount: 2.4,
2519 }),
2520 ])
2521
2522 // Confirm that the original order is not updated
2523 const orderResult = (
2524 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2525 ).data.order
2526 expect(orderResult.original_total).toEqual(11)
2527 expect(orderResult.total).toEqual(9.9)
2528
2529 // Confirm the order edit
2530 await api.post(
2531 `/admin/order-edits/${orderId}/confirm`,
2532 {},
2533 adminHeaders
2534 )
2535
2536 // Final check after confirmation
2537 const orderResult2 = (
2538 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2539 ).data.order
2540
2541 expect(orderResult2.original_total).toEqual(26.4)
2542 expect(orderResult2.total).toEqual(23.76)
2543 })
2544
2545 it("should not create adjustments when adding a new item if promotion is disabled", async () => {
2546 let result = await api.post(
2547 "/admin/order-edits",
2548 {
2549 order_id: order.id,
2550 description: "Test",
2551 },
2552 adminHeaders
2553 )
2554
2555 // allow carry over promotions flag on the edit
2556 const orderChangeId = result.data.order_change.id
2557 await api.post(
2558 `/admin/order-changes/${orderChangeId}`,
2559 {
2560 carry_over_promotions: true,
2561 },
2562 adminHeaders
2563 )
2564
2565 const orderId = result.data.order_change.order_id
2566
2567 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
2568 .order
2569
2570 expect(result.original_total).toEqual(11) // $10 + 10% tax
2571 expect(result.total).toEqual(9.9) // initial item 10$ and 10% discount and 10% tax
2572
2573 // promotion was active before so the item has an adjustment
2574 // only now we disable it
2575
2576 await api.post(
2577 `/admin/promotions/${appliedPromotion.id}`,
2578 {
2579 status: "draft",
2580 },
2581 adminHeaders
2582 )
2583
2584 // Add item with price $12 + $1.2 in taxes
2585 result = (
2586 await api.post(
2587 `/admin/order-edits/${orderId}/items`,
2588 {
2589 items: [
2590 {
2591 variant_id: productExtra.variants[0].id,
2592 quantity: 1,
2593 },
2594 ],
2595 },
2596 adminHeaders
2597 )
2598 ).data.order_preview
2599
2600 expect(result.total).toEqual(13.2 + 11) // since action is replace -> old adjustments are not recreated in this version
2601 expect(result.original_total).toEqual(13.2 + 11)
2602
2603 // Confirm that the adjustment values are correct
2604 const adjustments = result.items[0].adjustments
2605 const adjustments2 = result.items[1].adjustments
2606 expect(adjustments).toEqual([])
2607 expect(adjustments2).toEqual([])
2608
2609 const orderResult = (
2610 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2611 ).data.order
2612
2613 // confirm original order is not updated
2614 expect(orderResult.total).toEqual(9.9) // but adjustments of the intial version are still there despite the promotion being disabled in the meantime
2615 expect(orderResult.original_total).toEqual(11)
2616
2617 await api.post(
2618 `/admin/order-edits/${orderId}/confirm`,
2619 {},
2620 adminHeaders
2621 )
2622
2623 const orderResult2 = (
2624 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2625 ).data.order
2626
2627 // The promotion is disabled, so what happens is that promotions that were initially applied are removed
2628 expect(orderResult2.total).toEqual(24.2)
2629 expect(orderResult2.original_total).toEqual(24.2)
2630 })
2631
2632 it("should add, remove, and add buy-get adjustment depending on the quantity of the buy rule product", async () => {
2633 promotionModule = container.resolve(Modules.PROMOTION)
2634
2635 appliedPromotion = await promotionModule.createPromotions({
2636 code: "BUY_GET_PROMO",
2637 type: "buyget",
2638 status: "active",
2639 application_method: {
2640 allocation: "each",
2641 value: 100,
2642 max_quantity: 1,
2643 type: "percentage",
2644 target_type: "items",
2645 apply_to_quantity: 1,
2646 buy_rules_min_quantity: 2,
2647 target_rules: [
2648 {
2649 operator: "eq",
2650 attribute: "items.product.id",
2651 values: [productExtra.id],
2652 },
2653 ],
2654 buy_rules: [
2655 {
2656 operator: "eq",
2657 attribute: "items.product.id",
2658 values: [buyRuleProduct.id],
2659 },
2660 ],
2661 },
2662 is_tax_inclusive: false,
2663 is_automatic: true,
2664 })
2665
2666 const orderModule: IOrderModuleService = container.resolve(
2667 Modules.ORDER
2668 )
2669
2670 order = await orderModule.createOrders({
2671 email: "foo@bar.com",
2672 region_id: region.id,
2673 sales_channel_id: salesChannel.id,
2674 items: [
2675 {
2676 variant_id: buyRuleProduct.variants[0].id,
2677 quantity: 2,
2678 title: "Buy rule product",
2679 unit_price: 10,
2680 product_id: buyRuleProduct.id,
2681 },
2682 {
2683 variant_id: productExtra.variants[0].id,
2684 quantity: 1,
2685 title: "Extra product",
2686 unit_price: 10,
2687 product_id: productExtra.id,
2688 adjustments: [
2689 {
2690 code: appliedPromotion.code!,
2691 amount: 10,
2692 promotion_id: appliedPromotion.id,
2693 },
2694 ],
2695 },
2696 ],
2697 shipping_address: {
2698 first_name: "Test",
2699 last_name: "Test",
2700 address_1: "Test",
2701 city: "Test",
2702 country_code: "US",
2703 postal_code: "12345",
2704 phone: "12345",
2705 },
2706 billing_address: {
2707 first_name: "Test",
2708 last_name: "Test",
2709 address_1: "Test",
2710 city: "Test",
2711 country_code: "US",
2712 postal_code: "12345",
2713 },
2714 currency_code: "usd",
2715 })
2716
2717 await orderModule.createOrderLineItemAdjustments([
2718 {
2719 code: appliedPromotion.code!,
2720 amount: 1,
2721 item_id: "item-1",
2722 promotion_id: appliedPromotion.id,
2723 },
2724 ])
2725
2726 const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
2727
2728 await remoteLink.create({
2729 [Modules.ORDER]: { order_id: order.id },
2730 [Modules.PROMOTION]: { promotion_id: appliedPromotion.id },
2731 })
2732
2733 // Initially, the buy-get adjustment should be added to the order
2734 let result = await api.post(
2735 "/admin/order-edits",
2736 {
2737 order_id: order.id,
2738 description: "Test",
2739 },
2740 adminHeaders
2741 )
2742
2743 // allow carry over promotions flag on the edit
2744 const orderChangeId = result.data.order_change.id
2745 await api.post(
2746 `/admin/order-changes/${orderChangeId}`,
2747 {
2748 carry_over_promotions: true,
2749 },
2750 adminHeaders
2751 )
2752
2753 const orderId = result.data.order_change.order_id
2754
2755 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
2756 .order
2757
2758 expect(result.original_total).toEqual(30)
2759 expect(result.total).toEqual(20)
2760
2761 const buyRuleItem = result.items.find(
2762 (item) => item.product_id === buyRuleProduct.id
2763 )
2764
2765 // Update buy rule product quantity to 1
2766 // This should remove the buy-get adjustment, as it is no longer valid
2767 result = (
2768 await api.post(
2769 `/admin/order-edits/${orderId}/items/item/${buyRuleItem.id}`,
2770 {
2771 quantity: 1,
2772 },
2773 adminHeaders
2774 )
2775 ).data.order_preview
2776
2777 expect(result.total).toEqual(20)
2778 expect(result.original_total).toEqual(20)
2779
2780 // Confirm that the original order is not updated
2781 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
2782 .order
2783
2784 expect(result.original_total).toEqual(30)
2785 expect(result.total).toEqual(20)
2786
2787 await api.post(
2788 `/admin/order-edits/${orderId}/confirm`,
2789 {},
2790 adminHeaders
2791 )
2792
2793 const orderResult2 = (
2794 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2795 ).data.order
2796
2797 expect(orderResult2.total).toEqual(20)
2798 expect(orderResult2.original_total).toEqual(20)
2799 })
2800
2801 it("should maintain shipping method adjustments when adding a new item with promotion targeting shipping methods", async () => {
2802 // Create a promotion that targets shipping methods
2803 const shippingPromotion = await promotionModule.createPromotions({
2804 code: "SHIPPING_PROMO",
2805 type: PromotionType.STANDARD,
2806 status: PromotionStatus.ACTIVE,
2807 application_method: {
2808 type: "fixed",
2809 target_type: "shipping_methods",
2810 allocation: "each",
2811 value: 2,
2812 max_quantity: 1,
2813 currency_code: "usd",
2814 target_rules: [
2815 {
2816 attribute: "name",
2817 operator: "in",
2818 values: ["Test shipping method"],
2819 },
2820 ],
2821 },
2822 })
2823
2824 // Create an order with shipping method
2825 // @ts-ignore
2826 const orderWithShipping = await orderModule.createOrders({
2827 email: "foo@bar.com",
2828 region_id: region.id,
2829 sales_channel_id: salesChannel.id,
2830 items: [
2831 {
2832 // @ts-ignore
2833 id: "item-shipping-1",
2834 title: "Custom Item",
2835 quantity: 1,
2836 unit_price: 10,
2837 },
2838 ],
2839 shipping_address: {
2840 first_name: "Test",
2841 last_name: "Test",
2842 address_1: "Test",
2843 city: "Test",
2844 country_code: "US",
2845 postal_code: "12345",
2846 phone: "12345",
2847 },
2848 billing_address: {
2849 first_name: "Test",
2850 last_name: "Test",
2851 address_1: "Test",
2852 city: "Test",
2853 country_code: "US",
2854 postal_code: "12345",
2855 },
2856 shipping_methods: [
2857 {
2858 name: "Test shipping method",
2859 amount: 5,
2860 },
2861 ],
2862 currency_code: "usd",
2863 })
2864
2865 // Create shipping method adjustment for the promotion
2866 if (orderWithShipping.shipping_methods?.[0]) {
2867 await orderModule.createOrderShippingMethodAdjustments(
2868 orderWithShipping.id,
2869 [
2870 {
2871 shipping_method_id: orderWithShipping.shipping_methods[0].id,
2872 code: shippingPromotion.code!,
2873 amount: 2,
2874 },
2875 ]
2876 )
2877 }
2878
2879 // Link promotion to order
2880 await remoteLink.create({
2881 [Modules.ORDER]: { order_id: orderWithShipping.id },
2882 [Modules.PROMOTION]: { promotion_id: shippingPromotion.id },
2883 })
2884
2885 // Create order edit
2886 let result = await api.post(
2887 "/admin/order-edits",
2888 {
2889 order_id: orderWithShipping.id,
2890 description: "Test shipping promotion",
2891 },
2892 adminHeaders
2893 )
2894
2895 const orderChangeId = result.data.order_change.id
2896 const orderId = result.data.order_change.order_id
2897
2898 // Enable carry over promotions
2899 await api.post(
2900 `/admin/order-changes/${orderChangeId}`,
2901 {
2902 carry_over_promotions: true,
2903 },
2904 adminHeaders
2905 )
2906
2907 result = (await api.get(`/admin/orders/${orderId}`, adminHeaders)).data
2908 .order
2909
2910 // Original order: $10 item + $5 shipping - $2 shipping discount = $13
2911 expect(result.total).toEqual(13)
2912 expect(result.shipping_methods[0].adjustments).toEqual([
2913 expect.objectContaining({
2914 code: shippingPromotion.code!,
2915 amount: 2,
2916 }),
2917 ])
2918
2919 // Add item with price $12
2920 result = (
2921 await api.post(
2922 `/admin/order-edits/${orderId}/items`,
2923 {
2924 items: [
2925 {
2926 variant_id: productExtra.variants[0].id,
2927 quantity: 1,
2928 },
2929 ],
2930 },
2931 adminHeaders
2932 )
2933 ).data.order_preview
2934
2935 // After adding item: $22 items + $5 shipping - $2 shipping discount + $1.2 tax = $26.2
2936 expect(result.total).toEqual(26.2)
2937 expect(result.original_total).toEqual(28.2) // +$2 shipping discount
2938
2939 // Shipping method adjustment should still be present
2940 expect(result.shipping_methods[0].adjustments).toEqual([
2941 expect.objectContaining({
2942 code: shippingPromotion.code!,
2943 amount: 2,
2944 }),
2945 ])
2946
2947 // Confirm original order is not updated
2948 const orderResult = (
2949 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2950 ).data.order
2951
2952 expect(orderResult.total).toEqual(13)
2953 expect(orderResult.shipping_methods[0].adjustments).toEqual([
2954 expect.objectContaining({
2955 code: shippingPromotion.code!,
2956 amount: 2,
2957 }),
2958 ])
2959
2960 // Confirm the order edit
2961 await api.post(
2962 `/admin/order-edits/${orderId}/confirm`,
2963 {},
2964 adminHeaders
2965 )
2966
2967 const orderResult2 = (
2968 await api.get(`/admin/orders/${orderId}`, adminHeaders)
2969 ).data.order
2970
2971 expect(orderResult2.total).toEqual(26.2)
2972 expect(orderResult2.original_total).toEqual(28.2)
2973 expect(orderResult2.shipping_methods[0].adjustments).toEqual([
2974 expect.objectContaining({
2975 code: shippingPromotion.code!,
2976 amount: 2,
2977 }),
2978 ])
2979 })
2980 })
2981 },
2982 })