1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import { AdminShippingOption } from "@medusajs/types"
3 import {
4 ApiKeyType,
5 ModuleRegistrationName,
6 Modules,
7 ProductStatus,
8 } from "@medusajs/utils"
9 import {
10 adminHeaders,
11 createAdminUser,
12 generatePublishableKey,
13 generateStoreHeaders,
14 } from "../../../../helpers/create-admin-user"
15 import { setupTaxStructure } from "../../../../modules/__tests__/fixtures"
16 import { createOrderSeeder } from "../../fixtures/order"
17 import { createShippingOptionSeeder } from "../../fixtures/shipping"
18 import {
19 updateOrderChangeActionsWorkflow,
20 updateOrderChangesWorkflow,
21 updateOrderShippingMethodsStep,
22 } from "@medusajs/core-flows"
23 import {
24 createWorkflow,
25 WorkflowResponse,
26 } from "@medusajs/framework/workflows-sdk"
27
28 jest.setTimeout(300000)
29
30 medusaIntegrationTestRunner({
31 testSuite: ({ dbConnection, getContainer, api, dbUtils }) => {
32 let order,
33 seeder,
34 inventoryItemOverride3,
35 productOverride3,
36 shippingProfile,
37 productOverride4,
38 container,
39 userId
40
41 beforeAll(async () => {
42 container = getContainer()
43
44 await setupTaxStructure(container.resolve(ModuleRegistrationName.TAX))
45 userId = (await createAdminUser(dbConnection, adminHeaders, container))
46 .user.id
47
48 shippingProfile = (
49 await api.post(
50 `/admin/shipping-profiles`,
51 { name: "Test", type: "default" },
52 adminHeaders
53 )
54 ).data.shipping_profile
55
56 await dbUtils.snapshot()
57 })
58
59 describe("GET /admin/orders", () => {
60 beforeEach(async () => {
61 seeder = await createOrderSeeder({
62 api,
63 container: getContainer(),
64 })
65 order = seeder.order
66 })
67
68 it("should search orders by display_id", async () => {
69 let response = await api.get(`/admin/orders`, adminHeaders)
70
71 expect(response.data.orders).toHaveLength(1)
72 expect(response.data.orders).toEqual([
73 expect.objectContaining({
74 id: order.id,
75 }),
76 ])
77
78 response = await api.get(
79 `/admin/orders?q=${order.display_id}`,
80 adminHeaders
81 )
82
83 expect(response.data.orders).toHaveLength(1)
84 expect(response.data.orders).toEqual([
85 expect.objectContaining({
86 id: order.id,
87 }),
88 ])
89
90 response = await api.get(`/admin/orders?q=2345`, adminHeaders)
91
92 expect(response.data.orders).toHaveLength(0)
93 expect(response.data.orders).toEqual([])
94 })
95
96 it("should search orders by custom_display_id", async () => {
97 const customDisplayId = "custom-display-id-1234"
98 await dbConnection.raw(
99 `UPDATE "order" SET custom_display_id = ? WHERE id = ?`,
100 [customDisplayId, order.id]
101 )
102
103 const response = await api.get(
104 `/admin/orders?q=${customDisplayId}`,
105 adminHeaders
106 )
107
108 expect(response.data.orders).toHaveLength(1)
109 expect(response.data.orders).toEqual([
110 expect.objectContaining({
111 id: order.id,
112 }),
113 ])
114 })
115
116 it("should search orders by shipping address", async () => {
117 let response = await api.get(
118 `/admin/orders?fields=+shipping_address.address_1,+shipping_address.address_2`,
119 adminHeaders
120 )
121
122 expect(response.data.orders).toHaveLength(1)
123 expect(response.data.orders).toEqual([
124 expect.objectContaining({
125 id: order.id,
126 }),
127 ])
128
129 response = await api.get(
130 `/admin/orders?fields=+shipping_address.address_1,+shipping_address.address_2&q=${order.shipping_address.address_1}`,
131 adminHeaders
132 )
133
134 expect(response.data.orders).toHaveLength(1)
135 expect(response.data.orders).toEqual([
136 expect.objectContaining({
137 id: order.id,
138 }),
139 ])
140
141 response = await api.get(
142 `/admin/orders?q=${order.shipping_address.address_2}`,
143 adminHeaders
144 )
145
146 expect(response.data.orders).toHaveLength(1)
147 expect(response.data.orders).toEqual([
148 expect.objectContaining({
149 id: order.id,
150 }),
151 ])
152
153 response = await api.get(`/admin/orders?q=does-not-exist`, adminHeaders)
154
155 expect(response.data.orders).toHaveLength(0)
156 expect(response.data.orders).toEqual([])
157 })
158
159 describe("with matching list vs detail order totals with varying request fields", () => {
160 const getDetailTotal = async (query?: string) => {
161 const detailResponse = await api.get(
162 `/admin/orders/${order.id}${query ? `?${query}` : ""}`,
163 adminHeaders
164 )
165
166 return detailResponse.data.order.total
167 }
168
169 const getListTotal = async (query: string) => {
170 const listResponse = await api.get(
171 `/admin/orders?${query}`,
172 adminHeaders
173 )
174
175 const listedOrder = listResponse.data.orders.find(
176 (listed) => listed.id === order.id
177 )
178
179 expect(listedOrder).toBeTruthy()
180 return listedOrder!.total
181 }
182
183 it("should match totals across key fields with default list and detail responses", async () => {
184 const detailResponse = await api.get(
185 `/admin/orders/${order.id}`,
186 adminHeaders
187 )
188 const listResponse = await api.get(`/admin/orders`, adminHeaders)
189
190 const listedOrder = listResponse.data.orders.find(
191 (listed) => listed.id === order.id
192 ) as any
193
194 expect(listedOrder).toBeTruthy()
195
196 const detailOrder = detailResponse.data.order as any
197 const fieldsToCompare = [
198 // default admin order list endpoint only has total
199 "total",
200 // admin order detail endpoint has more fields
201 // "original_total",
202 // "discount_total",
203 // "discount_subtotal",
204 // "shipping_total",
205 // "tax_total",
206 ]
207
208 for (const field of fieldsToCompare) {
209 expect(listedOrder).toHaveProperty(field)
210 expect(listedOrder[field]).toBeDefined()
211 expect(listedOrder[field]).toBe(detailOrder[field])
212 }
213 })
214
215 it("should return the same total using default list fields", async () => {
216 const expectedTotal = await getDetailTotal()
217 const listTotal = await getListTotal(
218 // fields we use on the admin list page
219 `fields=${encodeURIComponent(
220 "id,status,created_at,email,display_id,custom_display_id,payment_status,fulfillment_status,total,currency_code,*customer,*sales_channel,*payment_collections"
221 )}`
222 )
223
224 expect(listTotal).toBe(expectedTotal)
225 })
226
227 it("should return the same total using minimal list fields", async () => {
228 const expectedTotal = await getDetailTotal()
229 const listTotal = await getListTotal("fields=id,total")
230
231 expect(listTotal).toBe(expectedTotal)
232 })
233
234 it("should return the same total when requesting item fields", async () => {
235 const expectedTotal = await getDetailTotal()
236 const listTotal = await getListTotal(
237 `fields=${encodeURIComponent("id,total,*items,+items.detail")}`
238 )
239
240 expect(listTotal).toBe(expectedTotal)
241 })
242
243 it("should return the same total when requesting shipping fields", async () => {
244 const expectedTotal = await getDetailTotal()
245 const listTotal = await getListTotal(
246 `fields=${encodeURIComponent(
247 "id,total,*shipping_methods,+shipping_methods.tax_lines"
248 )}`
249 )
250
251 expect(listTotal).toBe(expectedTotal)
252 })
253
254 it("should return the same total when using mixed list fields", async () => {
255 const expectedTotal = await getDetailTotal()
256 const listTotal = await getListTotal(
257 `fields=${encodeURIComponent(
258 "id,status,total,currency_code,*items,+items.detail,*shipping_methods,+shipping_methods.tax_lines"
259 )}`
260 )
261
262 expect(listTotal).toBe(expectedTotal)
263 })
264
265 it("should return the same total when using + / - field modifiers", async () => {
266 const expectedTotal = await getDetailTotal()
267 const listTotal = await getListTotal(
268 `fields=${encodeURIComponent("+total,-email")}`
269 )
270
271 expect(listTotal).toBe(expectedTotal)
272 })
273
274 it("should return the same total when ordering results", async () => {
275 const expectedTotal = await getDetailTotal()
276 const listTotal = await getListTotal(
277 "fields=id,total&order=-created_at"
278 )
279
280 expect(listTotal).toBe(expectedTotal)
281 })
282
283 it("should return the same total when requesting minimal detail fields", async () => {
284 const listTotal = await getListTotal(
285 `fields=${encodeURIComponent(
286 "id,status,created_at,email,display_id,custom_display_id,payment_status,fulfillment_status,total,currency_code,*customer,*sales_channel,*payment_collections"
287 )}`
288 )
289 const detailTotal = await getDetailTotal("fields=id,total")
290
291 expect(detailTotal).toBe(listTotal)
292 })
293
294 it("should return the same total when requesting item detail fields", async () => {
295 const listTotal = await getListTotal(
296 `fields=${encodeURIComponent(
297 "id,status,created_at,email,display_id,custom_display_id,payment_status,fulfillment_status,total,currency_code,*customer,*sales_channel,*payment_collections"
298 )}`
299 )
300 const detailTotal = await getDetailTotal(
301 `fields=${encodeURIComponent("id,total,*items,+items.detail")}`
302 )
303
304 expect(detailTotal).toBe(listTotal)
305 })
306
307 it("should return the same total when requesting shipping detail fields", async () => {
308 const listTotal = await getListTotal(
309 `fields=${encodeURIComponent(
310 "id,status,created_at,email,display_id,custom_display_id,payment_status,fulfillment_status,total,currency_code,*customer,*sales_channel,*payment_collections"
311 )}`
312 )
313 const detailTotal = await getDetailTotal(
314 `fields=${encodeURIComponent(
315 "id,total,*shipping_methods,+shipping_methods.tax_lines"
316 )}`
317 )
318
319 expect(detailTotal).toBe(listTotal)
320 })
321
322 it("should return the same total when using + / - field modifiers on detail", async () => {
323 const listTotal = await getListTotal(
324 `fields=${encodeURIComponent(
325 "id,status,created_at,email,display_id,custom_display_id,payment_status,fulfillment_status,total,currency_code,*customer,*sales_channel,*payment_collections"
326 )}`
327 )
328 const detailTotal = await getDetailTotal(
329 `fields=${encodeURIComponent("+total,-email")}`
330 )
331
332 expect(detailTotal).toBe(listTotal)
333 })
334 })
335
336 it("should search orders by billing address", async () => {
337 let response = await api.get(
338 `/admin/orders?fields=+billing_address.address_1,+billing_address.address_2`,
339 adminHeaders
340 )
341
342 expect(response.data.orders).toHaveLength(1)
343 expect(response.data.orders).toEqual([
344 expect.objectContaining({
345 id: order.id,
346 }),
347 ])
348
349 response = await api.get(
350 `/admin/orders?fields=+billing_address.address_1,+billing_address.address_2&q=${order.billing_address.address_1}`,
351 adminHeaders
352 )
353
354 expect(response.data.orders).toHaveLength(1)
355 expect(response.data.orders).toEqual([
356 expect.objectContaining({
357 id: order.id,
358 }),
359 ])
360
361 response = await api.get(
362 `/admin/orders?q=${order.billing_address.address_2}`,
363 adminHeaders
364 )
365
366 expect(response.data.orders).toHaveLength(1)
367 expect(response.data.orders).toEqual([
368 expect.objectContaining({
369 id: order.id,
370 }),
371 ])
372 })
373
374 describe("filter by total using operators", () => {
375 it.each([
376 {
377 operator: "$eq",
378 matchType: "matching",
379 getValue: (orderTotal: number) => orderTotal,
380 expectedLength: 1,
381 shouldMatchOrder: true,
382 },
383 {
384 operator: "$eq",
385 matchType: "non-matching",
386 getValue: (orderTotal: number) => orderTotal + 1000,
387 expectedLength: 0,
388 shouldMatchOrder: false,
389 },
390 {
391 operator: "$gte",
392 matchType: "matching",
393 getValue: (orderTotal: number) => orderTotal - 100,
394 expectedLength: 1,
395 shouldMatchOrder: true,
396 },
397 {
398 operator: "$gte",
399 matchType: "non-matching",
400 getValue: (orderTotal: number) => orderTotal + 1000,
401 expectedLength: 0,
402 shouldMatchOrder: false,
403 },
404 {
405 operator: "$lte",
406 matchType: "matching",
407 getValue: (orderTotal: number) => orderTotal + 100,
408 expectedLength: 1,
409 shouldMatchOrder: true,
410 },
411 {
412 operator: "$lte",
413 matchType: "non-matching",
414 getValue: (_orderTotal: number) => 0,
415 expectedLength: 0,
416 shouldMatchOrder: false,
417 },
418 ])(
419 "should filter orders by total using $operator operator - $matchType value",
420 async ({ operator, getValue, expectedLength, shouldMatchOrder }) => {
421 let filterValue: number
422
423 const orderResponse = await api.get(
424 `/admin/orders/${order.id}?fields=+summary`,
425 adminHeaders
426 )
427 const orderTotal =
428 orderResponse.data.order.summary.current_order_total
429 filterValue = getValue(orderTotal)
430
431 const queryParams = `total[${operator}]=${filterValue}`
432
433 const response = await api.get(
434 `/admin/orders?${queryParams}`,
435 adminHeaders
436 )
437
438 expect(response.data.orders).toHaveLength(expectedLength)
439 if (shouldMatchOrder) {
440 expect(response.data.orders).toEqual([
441 expect.objectContaining({
442 id: order.id,
443 }),
444 ])
445 } else {
446 expect(response.data.orders).toEqual([])
447 }
448 }
449 )
450 })
451
452 it("should return shipping_address when pagination included", async () => {
453 const response = await api.get(
454 `/admin/orders?fields=*shipping_address&offset=0`,
455 adminHeaders
456 )
457
458 expect(response.data.orders).toHaveLength(1)
459 expect(response.data.orders[0].id).toEqual(order.id)
460 expect(response.data.orders[0].shipping_address).toBeDefined()
461 expect(response.data.orders[0].shipping_address.address_1).toEqual(
462 order.shipping_address.address_1
463 )
464 expect(response.data.orders[0].shipping_address.city).toEqual(
465 order.shipping_address.city
466 )
467 })
468
469 it("should return billing_address when pagination included", async () => {
470 const response = await api.get(
471 `/admin/orders?fields=*billing_address&offset=0`,
472 adminHeaders
473 )
474
475 expect(response.data.orders).toHaveLength(1)
476 expect(response.data.orders[0].id).toEqual(order.id)
477 expect(response.data.orders[0].billing_address).toBeDefined()
478 expect(response.data.orders[0].billing_address.address_1).toEqual(
479 order.billing_address.address_1
480 )
481 expect(response.data.orders[0].billing_address.city).toEqual(
482 order.billing_address.city
483 )
484 })
485
486 it("should return specific address fields when pagination included", async () => {
487 const response = await api.get(
488 `/admin/orders?fields=+shipping_address.address_1,+shipping_address.city,+billing_address.address_1,+billing_address.city&offset=0`,
489 adminHeaders
490 )
491
492 expect(response.data.orders).toHaveLength(1)
493 const responseOrder = response.data.orders[0]
494 expect(responseOrder.id).toEqual(order.id)
495 expect(responseOrder.shipping_address).toBeDefined()
496 expect(responseOrder.shipping_address.address_1).toEqual(
497 order.shipping_address.address_1
498 )
499 expect(responseOrder.shipping_address.city).toEqual(
500 order.shipping_address.city
501 )
502 expect(responseOrder.billing_address).toBeDefined()
503 expect(responseOrder.billing_address.address_1).toEqual(
504 order.billing_address.address_1
505 )
506 expect(responseOrder.billing_address.city).toEqual(
507 order.billing_address.city
508 )
509 })
510
511 it("should expand the shipping option of a shipping method through the read-only link", async () => {
512 const fields = encodeURIComponent(
513 "id,*shipping_methods,*shipping_methods.shipping_option"
514 )
515
516 const detailShippingMethods = (
517 await api.get(
518 `/admin/orders/${order.id}?fields=${fields}`,
519 adminHeaders
520 )
521 ).data.order.shipping_methods
522
523 const listShippingMethods = (
524 await api.get(`/admin/orders?fields=${fields}`, adminHeaders)
525 ).data.orders.find((o) => o.id === order.id).shipping_methods
526
527 for (const shippingMethods of [
528 detailShippingMethods,
529 listShippingMethods,
530 ]) {
531 expect(shippingMethods).toHaveLength(1)
532 expect(shippingMethods[0]).toEqual(
533 expect.objectContaining({
534 shipping_option_id: seeder.shippingOption.id,
535 shipping_option: expect.objectContaining({
536 id: seeder.shippingOption.id,
537 name: seeder.shippingOption.name,
538 shipping_profile_id: seeder.shippingOption.shipping_profile_id,
539 }),
540 })
541 )
542 }
543 })
544 })
545
546 // shipping-method adjustments must be version-scoped
547 // in the list (findAndCount) path, as they already are in the retrieve
548 // (find) path. Before the fix, GET /admin/orders summed the free-shipping
549 // waiver once per order version, yielding a negative shipping_total and an
550 // understated total for fulfilled/shipped orders.
551 describe("list totals for a shipped order with a shipping promotion", () => {
552 let order
553 let seeder
554
555 beforeEach(async () => {
556 // automatic 100%-off-shipping promotion must exist before the order is
557 // created so the cart's shipping method picks up the adjustment
558 await api.post(
559 `/admin/promotions`,
560 {
561 code: "FREESHIP_VERSIONED",
562 type: "standard",
563 status: "active",
564 is_automatic: true,
565 application_method: {
566 type: "percentage",
567 target_type: "shipping_methods",
568 allocation: "each",
569 value: 100,
570 max_quantity: 1,
571 currency_code: "usd",
572 },
573 },
574 adminHeaders
575 )
576
577 seeder = await createOrderSeeder({ api, container: getContainer() })
578 order = seeder.order
579 })
580
581 it("should match list and detail shipping_total/total after fulfillment and shipment", async () => {
582 // sanity: the automatic promo fully waived shipping on the created order
583 const created = (
584 await api.get(
585 `/admin/orders/${order.id}?fields=id,version,shipping_total`,
586 adminHeaders
587 )
588 ).data.order
589 expect(created.shipping_total).toBe(0)
590
591 // fulfill then ship to advance the order version
592 const fulfilled = (
593 await api.post(
594 `/admin/orders/${order.id}/fulfillments?fields=id,*fulfillments`,
595 {
596 shipping_option_id: seeder.shippingOption.id,
597 location_id: seeder.stockLocation.id,
598 items: order.items.map((i) => ({
599 id: i.id,
600 quantity: i.quantity,
601 })),
602 },
603 adminHeaders
604 )
605 ).data.order
606
607 await api.post(
608 `/admin/orders/${order.id}/fulfillments/${fulfilled.fulfillments[0].id}/shipments`,
609 {
610 items: order.items.map((i) => ({
611 id: i.id,
612 quantity: i.quantity,
613 })),
614 },
615 adminHeaders
616 )
617
618 // detail (find path) is correct and version-scoped
619 const detail = (
620 await api.get(
621 `/admin/orders/${order.id}?fields=id,version,total,shipping_total`,
622 adminHeaders
623 )
624 ).data.order
625 expect(detail.version).toBeGreaterThanOrEqual(2)
626 expect(detail.shipping_total).toBe(0)
627
628 // list (findAndCount path) must agree — before the fix this returned a
629 // negative shipping_total and an understated total
630 const listed = (
631 await api.get(
632 `/admin/orders?fields=${encodeURIComponent(
633 "id,total,shipping_total"
634 )}`,
635 adminHeaders
636 )
637 ).data.orders.find((o) => o.id === order.id)
638
639 expect(listed).toBeTruthy()
640 expect(listed.shipping_total).toBe(0)
641 expect(listed.total).toBe(detail.total)
642 })
643 })
644
645 describe("created_by attribution on fulfillment and shipment creation", () => {
646 beforeEach(async () => {
647 seeder = await createOrderSeeder({ api, container: getContainer() })
648 order = seeder.order
649 })
650
651 it("should set created_by to the authenticated user on the fulfillment and its shipment", async () => {
652 const fulfillment = (
653 await api.post(
654 `/admin/orders/${order.id}/fulfillments?fields=fulfillments.id,fulfillments.created_by`,
655 {
656 shipping_option_id: seeder.shippingOption.id,
657 location_id: seeder.stockLocation.id,
658 items: order.items.map((i) => ({
659 id: i.id,
660 quantity: i.quantity,
661 })),
662 },
663 adminHeaders
664 )
665 ).data.order.fulfillments[0]
666
667 expect(fulfillment.created_by).toBe(userId)
668
669 const shipped = (
670 await api.post(
671 `/admin/orders/${order.id}/fulfillments/${fulfillment.id}/shipments?fields=fulfillments.id,fulfillments.created_by`,
672 {
673 items: order.items.map((i) => ({
674 id: i.id,
675 quantity: i.quantity,
676 })),
677 },
678 adminHeaders
679 )
680 ).data.order.fulfillments[0]
681
682 expect(shipped.created_by).toBe(userId)
683 })
684
685 it("should use the secret key's linked user to set created_by when authenticating with an api key", async () => {
686 const apiKey = (
687 await api.post(
688 "/admin/api-keys",
689 {
690 title: "secret-key",
691 type: ApiKeyType.SECRET,
692 },
693 adminHeaders
694 )
695 ).data.api_key
696
697 const apiKeyHeaders = {
698 headers: { Authorization: `Basic ${apiKey.token}` },
699 }
700
701 const fulfillment = (
702 await api.post(
703 `/admin/orders/${order.id}/fulfillments?fields=fulfillments.id,fulfillments.created_by`,
704 {
705 shipping_option_id: seeder.shippingOption.id,
706 location_id: seeder.stockLocation.id,
707 items: order.items.map((i) => ({
708 id: i.id,
709 quantity: i.quantity,
710 })),
711 },
712 apiKeyHeaders
713 )
714 ).data.order.fulfillments[0]
715
716 expect(fulfillment.created_by).toBe(userId)
717
718 const shipment = (
719 await api.post(
720 `/admin/orders/${order.id}/fulfillments/${fulfillment.id}/shipments?fields=fulfillments.id,fulfillments.created_by`,
721 {
722 items: order.items.map((i) => ({
723 id: i.id,
724 quantity: i.quantity,
725 })),
726 },
727 apiKeyHeaders
728 )
729 ).data.order.fulfillments[0]
730
731 expect(shipment.created_by).toBe(userId)
732 })
733 })
734
735 describe("POST /orders/:id", () => {
736 beforeEach(async () => {
737 seeder = await createOrderSeeder({
738 api,
739 container: getContainer(),
740 })
741 order = seeder.order
742
743 order = (
744 await api.get(
745 `/admin/orders/${order.id}?fields=+email,+customer_id`,
746 adminHeaders
747 )
748 ).data.order
749 })
750
751 it("should update shipping address on an order (by creating a new Address record)", async () => {
752 const addressBefore = order.shipping_address
753
754 const response = await api.post(
755 `/admin/orders/${order.id}`,
756 {
757 shipping_address: {
758 city: "New New York",
759 address_1: "New Main street 123",
760 },
761 },
762 adminHeaders
763 )
764
765 expect(response.data.order.shipping_address.id).not.toEqual(
766 addressBefore.id
767 ) // new addres created
768 expect(response.data.order.shipping_address).toEqual(
769 expect.objectContaining({
770 customer_id: addressBefore.customer_id,
771 company: addressBefore.company,
772 first_name: addressBefore.first_name,
773 last_name: addressBefore.last_name,
774 address_1: "New Main street 123",
775 address_2: addressBefore.address_2,
776 city: "New New York",
777 country_code: addressBefore.country_code,
778 province: addressBefore.province,
779 postal_code: addressBefore.postal_code,
780 phone: addressBefore.phone,
781 })
782 )
783
784 const orderChangesResult = (
785 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
786 ).data.order_changes
787
788 expect(orderChangesResult.length).toEqual(1)
789 expect(orderChangesResult[0]).toEqual(
790 expect.objectContaining({
791 version: 1,
792 change_type: "update_order",
793 status: "confirmed",
794 created_by: expect.any(String),
795 confirmed_by: expect.any(String),
796 confirmed_at: expect.any(String),
797 actions: expect.arrayContaining([
798 expect.objectContaining({
799 version: 1,
800 applied: true,
801 action: "UPDATE_ORDER_PROPERTIES",
802 details: expect.objectContaining({
803 type: "shipping_address",
804 old: expect.objectContaining({
805 address_1: addressBefore.address_1,
806 city: addressBefore.city,
807 country_code: addressBefore.country_code,
808 province: addressBefore.province,
809 postal_code: addressBefore.postal_code,
810 phone: addressBefore.phone,
811 company: addressBefore.company,
812 first_name: addressBefore.first_name,
813 last_name: addressBefore.last_name,
814 address_2: addressBefore.address_2,
815 }),
816 new: expect.objectContaining({
817 address_1: "New Main street 123",
818 city: "New New York",
819 country_code: addressBefore.country_code,
820 province: addressBefore.province,
821 postal_code: addressBefore.postal_code,
822 phone: addressBefore.phone,
823 company: addressBefore.company,
824 first_name: addressBefore.first_name,
825 last_name: addressBefore.last_name,
826 address_2: addressBefore.address_2,
827 }),
828 }),
829 }),
830 ]),
831 })
832 )
833 })
834
835 it("should fail to update shipping address if country code has been changed", async () => {
836 const response = await api
837 .post(
838 `/admin/orders/${order.id}`,
839 {
840 shipping_address: {
841 country_code: "HR",
842 },
843 },
844 adminHeaders
845 )
846 .catch((e) => e)
847
848 expect(response.response.status).toBe(400)
849 expect(response.response.data.message).toBe(
850 "Country code cannot be changed"
851 )
852
853 const orderChangesResult = (
854 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
855 ).data.order_changes
856
857 expect(orderChangesResult.length).toEqual(0)
858 })
859
860 it("should update billing address on an order (by creating a new Address record)", async () => {
861 const addressBefore = order.billing_address
862
863 const response = await api.post(
864 `/admin/orders/${order.id}`,
865 {
866 billing_address: {
867 city: "New New York",
868 address_1: "New Main street 123",
869 },
870 },
871 adminHeaders
872 )
873
874 expect(response.data.order.billing_address.id).not.toEqual(
875 addressBefore.id
876 ) // new addres created
877 expect(response.data.order.billing_address).toEqual(
878 expect.objectContaining({
879 customer_id: addressBefore.customer_id,
880 company: addressBefore.company,
881 first_name: addressBefore.first_name,
882 last_name: addressBefore.last_name,
883 address_1: "New Main street 123",
884 address_2: addressBefore.address_2,
885 city: "New New York",
886 country_code: addressBefore.country_code,
887 province: addressBefore.province,
888 postal_code: addressBefore.postal_code,
889 phone: addressBefore.phone,
890 })
891 )
892
893 const orderChangesResult = (
894 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
895 ).data.order_changes
896
897 expect(orderChangesResult.length).toEqual(1)
898 expect(orderChangesResult[0]).toEqual(
899 expect.objectContaining({
900 version: 1,
901 change_type: "update_order",
902 status: "confirmed",
903 created_by: expect.any(String),
904 confirmed_by: expect.any(String),
905 confirmed_at: expect.any(String),
906 actions: expect.arrayContaining([
907 expect.objectContaining({
908 version: 1,
909 applied: true,
910 action: "UPDATE_ORDER_PROPERTIES",
911 details: expect.objectContaining({
912 type: "billing_address",
913 old: expect.objectContaining({
914 address_1: addressBefore.address_1,
915 city: addressBefore.city,
916 country_code: addressBefore.country_code,
917 province: addressBefore.province,
918 postal_code: addressBefore.postal_code,
919 phone: addressBefore.phone,
920 }),
921 new: expect.objectContaining({
922 address_1: "New Main street 123",
923 city: "New New York",
924 country_code: addressBefore.country_code,
925 province: addressBefore.province,
926 postal_code: addressBefore.postal_code,
927 phone: addressBefore.phone,
928 }),
929 }),
930 }),
931 ]),
932 })
933 )
934 })
935
936 it("should fail to update billing address if country code has been changed", async () => {
937 const response = await api
938 .post(
939 `/admin/orders/${order.id}`,
940 {
941 billing_address: {
942 country_code: "HR",
943 },
944 },
945 adminHeaders
946 )
947 .catch((e) => e)
948
949 expect(response.response.status).toBe(400)
950 expect(response.response.data.message).toBe(
951 "Country code cannot be changed"
952 )
953
954 const orderChangesResult = (
955 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
956 ).data.order_changes
957
958 expect(orderChangesResult.length).toEqual(0)
959 })
960
961 it("should update orders email and shipping address and create 2 change records", async () => {
962 const response = await api.post(
963 `/admin/orders/${order.id}?fields=+email,*shipping_address`,
964 {
965 email: "new-email@example.com",
966 shipping_address: {
967 address_1: "New Main street 123",
968 },
969 },
970 adminHeaders
971 )
972
973 expect(response.data.order.email).toBe("new-email@example.com")
974 expect(response.data.order.shipping_address.id).not.toEqual(
975 order.shipping_address.id
976 )
977 expect(response.data.order.shipping_address).toEqual(
978 expect.objectContaining({
979 address_1: "New Main street 123",
980 })
981 )
982
983 const orderChangesResult = (
984 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
985 ).data.order_changes
986
987 expect(orderChangesResult.length).toEqual(2)
988 expect(orderChangesResult).toEqual(
989 expect.arrayContaining([
990 expect.objectContaining({
991 version: 1,
992 change_type: "update_order",
993 status: "confirmed",
994 confirmed_at: expect.any(String),
995 created_by: expect.any(String),
996 confirmed_by: expect.any(String),
997 actions: expect.arrayContaining([
998 expect.objectContaining({
999 version: 1,
1000 applied: true,
1001 action: "UPDATE_ORDER_PROPERTIES",
1002 details: expect.objectContaining({
1003 type: "shipping_address",
1004 old: expect.objectContaining({
1005 address_1: order.shipping_address.address_1,
1006 city: order.shipping_address.city,
1007 }),
1008 new: expect.objectContaining({
1009 address_1: "New Main street 123",
1010 }),
1011 }),
1012 }),
1013 ]),
1014 }),
1015 expect.objectContaining({
1016 version: 1,
1017 change_type: "update_order",
1018 status: "confirmed",
1019 confirmed_at: expect.any(String),
1020 created_by: expect.any(String),
1021 confirmed_by: expect.any(String),
1022 actions: expect.arrayContaining([
1023 expect.objectContaining({
1024 version: 1,
1025 applied: true,
1026 action: "UPDATE_ORDER_PROPERTIES",
1027 details: expect.objectContaining({
1028 type: "email",
1029 old: order.email,
1030 new: "new-email@example.com",
1031 }),
1032 }),
1033 ]),
1034 }),
1035 ])
1036 )
1037 })
1038
1039 it("should fail to update email if it is invalid", async () => {
1040 const response = await api
1041 .post(
1042 `/admin/orders/${order.id}`,
1043 {
1044 email: "invalid-email",
1045 },
1046 adminHeaders
1047 )
1048 .catch((e) => e)
1049
1050 expect(response.response.status).toBe(400)
1051 expect(response.response.data.message).toBe("The email is not valid")
1052
1053 const orderChangesResult = (
1054 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
1055 ).data.order_changes
1056
1057 expect(orderChangesResult.length).toEqual(0)
1058 })
1059
1060 describe("conditional customer creation", () => {
1061 it("should create or find a customer when order email is unset and input email is provided", async () => {
1062 const container = getContainer()
1063 const orderService = container.resolve(ModuleRegistrationName.ORDER)
1064 const customerService = container.resolve(
1065 ModuleRegistrationName.CUSTOMER
1066 )
1067
1068 const orderWithoutEmail = await orderService.createOrders({
1069 region_id: seeder.region.id,
1070 currency_code: "usd",
1071 items: [
1072 {
1073 title: "Test Item",
1074 quantity: 1,
1075 unit_price: 100,
1076 },
1077 ],
1078 shipping_address: {
1079 first_name: "Test",
1080 last_name: "Test",
1081 address_1: "Test",
1082 city: "Test",
1083 country_code: "US",
1084 postal_code: "12345",
1085 },
1086 billing_address: {
1087 first_name: "Test",
1088 last_name: "Test",
1089 address_1: "Test",
1090 city: "Test",
1091 country_code: "US",
1092 postal_code: "12345",
1093 },
1094 })
1095
1096 expect(orderWithoutEmail.email).toBeNull()
1097
1098 const newEmail = "newcustomer@example.com"
1099
1100 const customersBefore = await customerService.listCustomers()
1101 const customerCountBefore = customersBefore.length
1102
1103 const response = await api.post(
1104 `/admin/orders/${orderWithoutEmail.id}?fields=+email,+customer_id`,
1105 {
1106 email: newEmail,
1107 },
1108 adminHeaders
1109 )
1110
1111 expect(response.data.order.email).toBe(newEmail)
1112 expect(response.data.order.customer_id).toBeDefined()
1113
1114 const customersAfter = await customerService.listCustomers()
1115 expect(customersAfter.length).toBe(customerCountBefore + 1)
1116
1117 const customer = await customerService.retrieveCustomer(
1118 response.data.order.customer_id
1119 )
1120 expect(customer.email).toBe(newEmail)
1121 })
1122
1123 it("should NOT create or find a customer when order email is already set and input email is provided", async () => {
1124 const container = getContainer()
1125 const customerService = container.resolve(
1126 ModuleRegistrationName.CUSTOMER
1127 )
1128
1129 const existingEmail = order.email
1130
1131 expect(existingEmail).toBeDefined()
1132
1133 const originalCustomerId = order.customer_id
1134 const newEmail = "updated@example.com"
1135
1136 const customersBefore = await customerService.listCustomers()
1137 const customerCountBefore = customersBefore.length
1138
1139 const response = await api.post(
1140 `/admin/orders/${order.id}?fields=+email,+customer_id`,
1141 {
1142 email: newEmail,
1143 },
1144 adminHeaders
1145 )
1146
1147 expect(response.data.order.email).toBe(newEmail)
1148 expect(response.data.order.customer_id).toBe(originalCustomerId)
1149
1150 const customersAfter = await customerService.listCustomers()
1151 expect(customersAfter.length).toBe(customerCountBefore)
1152 })
1153
1154 it("should NOT create or find a customer when order email is unset and input email is not provided", async () => {
1155 const container = getContainer()
1156 const orderService = container.resolve(ModuleRegistrationName.ORDER)
1157 const customerService = container.resolve(
1158 ModuleRegistrationName.CUSTOMER
1159 )
1160
1161 const orderWithoutEmail = await orderService.createOrders({
1162 region_id: seeder.region.id,
1163 currency_code: "usd",
1164 email: undefined,
1165 items: [
1166 {
1167 title: "Test Item",
1168 quantity: 1,
1169 unit_price: 100,
1170 },
1171 ],
1172 shipping_address: {
1173 first_name: "Test",
1174 last_name: "Test",
1175 address_1: "Test",
1176 city: "Test",
1177 country_code: "US",
1178 postal_code: "12345",
1179 },
1180 billing_address: {
1181 first_name: "Test",
1182 last_name: "Test",
1183 address_1: "Test",
1184 city: "Test",
1185 country_code: "US",
1186 postal_code: "12345",
1187 },
1188 })
1189
1190 const customersBefore = await customerService.listCustomers()
1191 const customerCountBefore = customersBefore.length
1192
1193 const response = await api.post(
1194 `/admin/orders/${orderWithoutEmail.id}?fields=+customer_id`,
1195 {
1196 metadata: {
1197 test: "value",
1198 },
1199 },
1200 adminHeaders
1201 )
1202
1203 expect(response.data.order.customer_id).toBeNull()
1204
1205 const customersAfter = await customerService.listCustomers()
1206 expect(customersAfter.length).toBe(customerCountBefore)
1207 })
1208
1209 it("should find existing customer when order email is unset and input email matches existing customer", async () => {
1210 const container = getContainer()
1211 const orderService = container.resolve(ModuleRegistrationName.ORDER)
1212 const customerService = container.resolve(
1213 ModuleRegistrationName.CUSTOMER
1214 )
1215
1216 const existingEmail = "existingcustomer@example.com"
1217
1218 const existingCustomer = await customerService.createCustomers({
1219 email: existingEmail,
1220 })
1221
1222 const orderWithoutEmail = await orderService.createOrders({
1223 region_id: seeder.region.id,
1224 currency_code: "usd",
1225 items: [
1226 {
1227 title: "Test Item",
1228 quantity: 1,
1229 unit_price: 100,
1230 },
1231 ],
1232 shipping_address: {
1233 first_name: "Test",
1234 last_name: "Test",
1235 address_1: "Test",
1236 city: "Test",
1237 country_code: "US",
1238 postal_code: "12345",
1239 },
1240 billing_address: {
1241 first_name: "Test",
1242 last_name: "Test",
1243 address_1: "Test",
1244 city: "Test",
1245 country_code: "US",
1246 postal_code: "12345",
1247 },
1248 })
1249
1250 const customersBefore = await customerService.listCustomers()
1251 const customerCountBefore = customersBefore.length
1252
1253 const response = await api.post(
1254 `/admin/orders/${orderWithoutEmail.id}?fields=+email,+customer_id`,
1255 {
1256 email: existingEmail,
1257 },
1258 adminHeaders
1259 )
1260
1261 expect(response.data.order.email).toBe(existingEmail)
1262 expect(response.data.order.customer_id).toBe(existingCustomer.id)
1263
1264 const customersAfter = await customerService.listCustomers()
1265 expect(customersAfter.length).toBe(customerCountBefore)
1266 })
1267 })
1268 })
1269
1270 describe("POST /orders/:id/cancel", () => {
1271 beforeEach(async () => {
1272 const inventoryItemOverride = (
1273 await api.post(
1274 `/admin/inventory-items`,
1275 { sku: "test-variant", requires_shipping: false },
1276 adminHeaders
1277 )
1278 ).data.inventory_item
1279
1280 seeder = await createOrderSeeder({
1281 api,
1282 container: getContainer(),
1283 inventoryItemOverride,
1284 withoutShipping: true,
1285 })
1286 order = seeder.order
1287
1288 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
1289 .order
1290 })
1291
1292 it("should successfully cancel an order and its authorized but not captured payments", async () => {
1293 const response = await api.post(
1294 `/admin/orders/${order.id}/cancel`,
1295 {},
1296 adminHeaders
1297 )
1298
1299 expect(response.status).toBe(200)
1300 expect(response.data.order).toEqual(
1301 expect.objectContaining({
1302 id: order.id,
1303 status: "canceled",
1304
1305 summary: expect.objectContaining({
1306 current_order_total: 106,
1307 accounting_total: 106,
1308 }),
1309
1310 payment_collections: [
1311 expect.objectContaining({
1312 status: "canceled",
1313 captured_amount: 0,
1314 refunded_amount: 0,
1315 amount: 106,
1316 payments: [
1317 expect.objectContaining({
1318 canceled_at: expect.any(String),
1319 refunds: [],
1320 captures: [],
1321 }),
1322 ],
1323 }),
1324 ],
1325 })
1326 )
1327 })
1328
1329 it("should successfully cancel an order with a captured payment", async () => {
1330 const payment = order.payment_collections[0].payments[0]
1331
1332 const paymentResponse = await api.post(
1333 `/admin/payments/${payment.id}/capture`,
1334 undefined,
1335 adminHeaders
1336 )
1337
1338 expect(paymentResponse.data.payment).toEqual(
1339 expect.objectContaining({
1340 id: payment.id,
1341 captured_at: expect.any(String),
1342 captures: [
1343 expect.objectContaining({
1344 id: expect.any(String),
1345 amount: 106,
1346 }),
1347 ],
1348 refunds: [],
1349 amount: 106,
1350 })
1351 )
1352
1353 const response = await api.post(
1354 `/admin/orders/${order.id}/cancel`,
1355 {},
1356 adminHeaders
1357 )
1358
1359 expect(response.status).toBe(200)
1360 expect(response.data.order).toEqual(
1361 expect.objectContaining({
1362 id: order.id,
1363 status: "canceled",
1364
1365 summary: expect.objectContaining({
1366 current_order_total: 0,
1367 accounting_total: 0,
1368 }),
1369
1370 payment_collections: [
1371 expect.objectContaining({
1372 status: "canceled",
1373 captured_amount: 106,
1374 refunded_amount: 106,
1375 amount: 106,
1376 payments: [
1377 expect.objectContaining({
1378 canceled_at: null,
1379 refunds: [
1380 expect.objectContaining({
1381 id: expect.any(String),
1382 amount: 106,
1383 created_by: expect.any(String),
1384 }),
1385 ],
1386 captures: [
1387 expect.objectContaining({
1388 id: expect.any(String),
1389 amount: 106,
1390 }),
1391 ],
1392 }),
1393 ],
1394 }),
1395 ],
1396 })
1397 )
1398 })
1399
1400 it("should successfully cancel an order with a partially captured payment", async () => {
1401 const payment = order.payment_collections[0].payments[0]
1402
1403 const paymentResponse = await api.post(
1404 `/admin/payments/${payment.id}/capture`,
1405 { amount: 50 },
1406 adminHeaders
1407 )
1408
1409 expect(paymentResponse.data.payment).toEqual(
1410 expect.objectContaining({
1411 id: payment.id,
1412 captured_at: null,
1413 captures: [
1414 expect.objectContaining({
1415 id: expect.any(String),
1416 amount: 50,
1417 }),
1418 ],
1419 refunds: [],
1420 amount: 106,
1421 })
1422 )
1423
1424 const response = await api
1425 .post(`/admin/orders/${order.id}/cancel`, {}, adminHeaders)
1426 .catch((e) => e)
1427
1428 expect(response.status).toBe(200)
1429 expect(response.data.order).toEqual(
1430 expect.objectContaining({
1431 id: order.id,
1432 status: "canceled",
1433
1434 summary: expect.objectContaining({
1435 current_order_total: 56,
1436 accounting_total: 56,
1437 }),
1438
1439 payment_collections: [
1440 expect.objectContaining({
1441 status: "canceled",
1442 captured_amount: 50,
1443 refunded_amount: 50,
1444 amount: 106,
1445 payments: [
1446 expect.objectContaining({
1447 refunds: [
1448 expect.objectContaining({
1449 id: expect.any(String),
1450 amount: 50,
1451 created_by: expect.any(String),
1452 }),
1453 ],
1454 captures: [
1455 expect.objectContaining({
1456 id: expect.any(String),
1457 amount: 50,
1458 }),
1459 ],
1460 }),
1461 ],
1462 }),
1463 ],
1464 })
1465 )
1466 })
1467
1468 it("should only create credit lines for successfully refunded payments when some refunds fail", async () => {
1469 const paymentModule = container.resolve(Modules.PAYMENT)
1470 const payment = order.payment_collections[0].payments[0]
1471 const paymentCollectionId = order.payment_collections[0].id
1472
1473 // Capture the original payment for 50
1474 await api.post(
1475 `/admin/payments/${payment.id}/capture`,
1476 { amount: 50 },
1477 adminHeaders
1478 )
1479
1480 // Create a second payment session, authorize it, and capture it for 30
1481 const session2 = await paymentModule.createPaymentSession(
1482 paymentCollectionId,
1483 {
1484 provider_id: "pp_system_default",
1485 amount: 100,
1486 currency_code: "usd",
1487 data: {},
1488 }
1489 )
1490 const payment2 = await paymentModule.authorizePaymentSession(
1491 session2.id,
1492 {}
1493 )
1494 await paymentModule.capturePayment({
1495 payment_id: payment2.id,
1496 amount: 30,
1497 })
1498
1499 // Verify both payments are captured before canceling
1500 const orderBeforeCancel = (
1501 await api.get(
1502 `/admin/orders/${order.id}?fields=*payment_collections.payments.amount,*payment_collections.payments.captures.amount`,
1503 adminHeaders
1504 )
1505 ).data.order
1506
1507 const capturedPayments =
1508 orderBeforeCancel.payment_collections[0].payments.filter(
1509 (p) => p.captures.length > 0
1510 )
1511 expect(capturedPayments).toHaveLength(2)
1512
1513 // Mock refundPayment to fail for the second payment
1514 const originalRefundPayment =
1515 paymentModule.refundPayment.bind(paymentModule)
1516 jest
1517 .spyOn(paymentModule, "refundPayment")
1518 .mockImplementation(async (data: any, sharedContext?: any) => {
1519 if (data.payment_id === payment2.id) {
1520 throw new Error("Refund failed at payment provider")
1521 }
1522 return originalRefundPayment(data, sharedContext)
1523 })
1524
1525 // Cancel the order
1526 const cancelResponse = await api.post(
1527 `/admin/orders/${order.id}/cancel`,
1528 {},
1529 adminHeaders
1530 )
1531
1532 expect(cancelResponse.status).toBe(200)
1533
1534 // Restore the mock
1535 jest.restoreAllMocks()
1536
1537 // Get the canceled order with credit lines and summary
1538 const canceledOrder = (
1539 await api.get(
1540 `/admin/orders/${order.id}?fields=*credit_lines.amount,*payment_collections.payments.amount,*payment_collections.payments.captures.amount,*payment_collections.payments.refunds.amount`,
1541 adminHeaders
1542 )
1543 ).data.order
1544
1545 expect(canceledOrder.status).toBe("canceled")
1546
1547 // Only the first payment (50) was successfully refunded
1548 // The second payment (30) refund failed, so it should NOT be in credit lines
1549 const totalCreditLineAmount = canceledOrder.credit_lines.reduce(
1550 (sum, cl) => sum + cl.amount,
1551 0
1552 )
1553
1554 // Credit line should only reflect the successful refund (50), not both (50 + 30)
1555 expect(totalCreditLineAmount).toBe(50)
1556 expect(canceledOrder.summary.credit_line_total).toBe(50)
1557
1558 // Verify only the first payment has a refund record
1559 const originalPaymentAfter =
1560 canceledOrder.payment_collections[0].payments.find(
1561 (p) => p.id === payment.id
1562 )
1563 const payment2After =
1564 canceledOrder.payment_collections[0].payments.find(
1565 (p) => p.id === payment2.id
1566 )
1567
1568 expect(originalPaymentAfter.refunds).toHaveLength(1)
1569 expect(originalPaymentAfter.refunds[0].amount).toBe(50)
1570
1571 // The failed payment should have no refund records
1572 expect(payment2After.refunds).toHaveLength(0)
1573 })
1574
1575 it("should soft-delete a failed refund and exclude it from credit lines when the provider rejects it", async () => {
1576 const paymentModule = container.resolve(Modules.PAYMENT)
1577 const payment = order.payment_collections[0].payments[0]
1578 const paymentCollectionId = order.payment_collections[0].id
1579
1580 await api.post(
1581 `/admin/payments/${payment.id}/capture`,
1582 { amount: 50 },
1583 adminHeaders
1584 )
1585
1586 const session2 = await paymentModule.createPaymentSession(
1587 paymentCollectionId,
1588 {
1589 provider_id: "pp_system_default",
1590 amount: 100,
1591 currency_code: "usd",
1592 data: {},
1593 }
1594 )
1595 const payment2 = await paymentModule.authorizePaymentSession(
1596 session2.id,
1597 {}
1598 )
1599 await paymentModule.capturePayment({
1600 payment_id: payment2.id,
1601 amount: 30,
1602 })
1603
1604 // Unlike the test above, the failure is injected at the provider rather
1605 // than at the module, so the refund record is created before it fails.
1606 const providerService = (paymentModule as any).paymentProviderService_
1607 const originalProviderRefund =
1608 providerService.refundPayment.bind(providerService)
1609
1610 jest
1611 .spyOn(providerService, "refundPayment")
1612 .mockImplementation(async (...args: any[]) => {
1613 const [providerId, input] = args
1614 const rawAmount = input?.amount
1615 const amount =
1616 rawAmount && typeof rawAmount === "object"
1617 ? rawAmount.value
1618 : rawAmount
1619
1620 if (Number(amount) === 30) {
1621 throw new Error("Refund failed at payment provider")
1622 }
1623
1624 return originalProviderRefund(providerId, input)
1625 })
1626
1627 const cancelResponse = await api.post(
1628 `/admin/orders/${order.id}/cancel`,
1629 {},
1630 adminHeaders
1631 )
1632
1633 expect(cancelResponse.status).toBe(200)
1634
1635 jest.restoreAllMocks()
1636
1637 const canceledOrder = (
1638 await api.get(
1639 `/admin/orders/${order.id}?fields=*credit_lines.amount,*payment_collections.payments.amount,*payment_collections.payments.captures.amount`,
1640 adminHeaders
1641 )
1642 ).data.order
1643
1644 expect(canceledOrder.status).toBe("canceled")
1645
1646 // The failed refund moved no funds, so it must not reach credit lines.
1647 const totalCreditLineAmount = canceledOrder.credit_lines.reduce(
1648 (sum, cl) => sum + cl.amount,
1649 0
1650 )
1651 expect(totalCreditLineAmount).toBe(50)
1652 expect(canceledOrder.summary.credit_line_total).toBe(50)
1653
1654 const succeededRefunds = await paymentModule.listRefunds({
1655 payment_id: payment.id,
1656 })
1657 expect(succeededRefunds).toHaveLength(1)
1658 expect(succeededRefunds[0]).toEqual(
1659 expect.objectContaining({ amount: 50 })
1660 )
1661
1662 // Invisible to ordinary reads, exactly as before this change.
1663 expect(
1664 await paymentModule.listRefunds({ payment_id: payment2.id })
1665 ).toHaveLength(0)
1666
1667 // The record survives so the refund can be retried with the same key.
1668 const failedRefunds = await paymentModule.listRefunds(
1669 { payment_id: payment2.id },
1670 { withDeleted: true }
1671 )
1672 expect(failedRefunds).toHaveLength(1)
1673 expect(failedRefunds[0]).toEqual(
1674 expect.objectContaining({ amount: 30, deleted_at: expect.any(Date) })
1675 )
1676
1677 const paymentCollection = await paymentModule.retrievePaymentCollection(
1678 paymentCollectionId
1679 )
1680 expect(paymentCollection.refunded_amount).toBe(50)
1681 })
1682
1683 it("should retry a failed refund with the same idempotency key", async () => {
1684 const paymentModule = container.resolve(Modules.PAYMENT)
1685 const payment = order.payment_collections[0].payments[0]
1686
1687 await api.post(
1688 `/admin/payments/${payment.id}/capture`,
1689 { amount: 50 },
1690 adminHeaders
1691 )
1692
1693 const providerService = (paymentModule as any).paymentProviderService_
1694 const providerRefundSpy = jest
1695 .spyOn(providerService, "refundPayment")
1696 .mockRejectedValueOnce(new Error("Refund failed at payment provider"))
1697
1698 const body = { amount: 50, idempotency_key: "return_42_refund" }
1699
1700 await api
1701 .post(`/admin/payments/${payment.id}/refund`, body, adminHeaders)
1702 .catch((e) => e)
1703
1704 const afterFailure = await paymentModule.listRefunds(
1705 { payment_id: payment.id },
1706 { withDeleted: true }
1707 )
1708 expect(afterFailure).toHaveLength(1)
1709 expect(afterFailure[0].deleted_at).toEqual(expect.any(Date))
1710
1711 const response = await api.post(
1712 `/admin/payments/${payment.id}/refund`,
1713 body,
1714 adminHeaders
1715 )
1716
1717 expect(response.status).toBe(200)
1718
1719 const afterRetry = await paymentModule.listRefunds({
1720 payment_id: payment.id,
1721 })
1722 expect(afterRetry).toHaveLength(1)
1723 expect(afterRetry[0]).toEqual(
1724 expect.objectContaining({ id: afterFailure[0].id, deleted_at: null })
1725 )
1726
1727 expect(providerRefundSpy).toHaveBeenCalledTimes(2)
1728 expect(
1729 providerRefundSpy.mock.calls[1][1].context.idempotency_key
1730 ).toEqual(providerRefundSpy.mock.calls[0][1].context.idempotency_key)
1731
1732 jest.restoreAllMocks()
1733 })
1734 })
1735
1736 describe("POST /orders/:id/fulfillments", () => {
1737 let productOverride4WithOverrideShippingProfile,
1738 shippingProfileOverride,
1739 stockChannelOverride
1740
1741 beforeEach(async () => {
1742 stockChannelOverride = (
1743 await api.post(
1744 `/admin/stock-locations`,
1745 { name: "test location" },
1746 adminHeaders
1747 )
1748 ).data.stock_location
1749
1750 const inventoryItemOverride = (
1751 await api.post(
1752 `/admin/inventory-items`,
1753 { sku: "test-variant", requires_shipping: true },
1754 adminHeaders
1755 )
1756 ).data.inventory_item
1757
1758 const productOverride = (
1759 await api.post(
1760 "/admin/products",
1761 {
1762 title: `Test fixture`,
1763 status: ProductStatus.PUBLISHED,
1764 shipping_profile_id: shippingProfile.id,
1765 options: [
1766 { title: "size", values: ["large", "small"] },
1767 { title: "color", values: ["green"] },
1768 ],
1769 variants: [
1770 {
1771 title: "Test variant",
1772 sku: "w-inv-override-1",
1773 inventory_items: [
1774 {
1775 inventory_item_id: inventoryItemOverride.id,
1776 required_quantity: 1,
1777 },
1778 ],
1779 prices: [
1780 {
1781 currency_code: "usd",
1782 amount: 100,
1783 },
1784 ],
1785 options: {
1786 size: "large",
1787 color: "green",
1788 },
1789 },
1790 ],
1791 },
1792 adminHeaders
1793 )
1794 ).data.product
1795
1796 const inventoryItemOverride2 = (
1797 await api.post(
1798 `/admin/inventory-items`,
1799 { sku: "test-variant-2", requires_shipping: false },
1800 adminHeaders
1801 )
1802 ).data.inventory_item
1803
1804 inventoryItemOverride3 = (
1805 await api.post(
1806 `/admin/inventory-items`,
1807 { sku: "test-variant-3", requires_shipping: false },
1808 adminHeaders
1809 )
1810 ).data.inventory_item
1811
1812 const inventoryItemOverride4RequiresShipping = (
1813 await api.post(
1814 `/admin/inventory-items`,
1815 { sku: "test-variant-4", requires_shipping: true },
1816 adminHeaders
1817 )
1818 ).data.inventory_item
1819
1820 await api.post(
1821 `/admin/inventory-items/${inventoryItemOverride2.id}/location-levels`,
1822 {
1823 location_id: stockChannelOverride.id,
1824 stocked_quantity: 10,
1825 },
1826 adminHeaders
1827 )
1828
1829 await api.post(
1830 `/admin/inventory-items/${inventoryItemOverride3.id}/location-levels`,
1831 {
1832 location_id: stockChannelOverride.id,
1833 stocked_quantity: 10,
1834 },
1835 adminHeaders
1836 )
1837
1838 await api.post(
1839 `/admin/inventory-items/${inventoryItemOverride4RequiresShipping.id}/location-levels`,
1840 {
1841 location_id: stockChannelOverride.id,
1842 stocked_quantity: 10,
1843 },
1844 adminHeaders
1845 )
1846
1847 const productOverride2 = (
1848 await api.post(
1849 "/admin/products",
1850 {
1851 title: `Test fixture 2`,
1852 status: ProductStatus.PUBLISHED,
1853 options: [
1854 { title: "size", values: ["large", "small"] },
1855 { title: "color", values: ["green"] },
1856 ],
1857 variants: [
1858 {
1859 title: "Test variant 2",
1860 sku: "w-inv-override-2",
1861 inventory_items: [
1862 {
1863 inventory_item_id: inventoryItemOverride2.id,
1864 required_quantity: 1,
1865 },
1866 ],
1867 prices: [
1868 {
1869 currency_code: "usd",
1870 amount: 100,
1871 },
1872 ],
1873 options: {
1874 size: "large",
1875 color: "green",
1876 },
1877 },
1878 ],
1879 },
1880 adminHeaders
1881 )
1882 ).data.product
1883
1884 productOverride3 = (
1885 await api.post(
1886 "/admin/products",
1887 {
1888 title: `Test fixture 3`,
1889 status: ProductStatus.PUBLISHED,
1890 shipping_profile_id: shippingProfile.id,
1891 options: [
1892 { title: "size", values: ["large", "small"] },
1893 { title: "color", values: ["green"] },
1894 ],
1895 variants: [
1896 {
1897 title: "Test variant 3",
1898 sku: "test-variant-3",
1899 inventory_items: [
1900 {
1901 inventory_item_id: inventoryItemOverride3.id,
1902 required_quantity: 1,
1903 },
1904 ],
1905 prices: [
1906 {
1907 currency_code: "usd",
1908 amount: 100,
1909 },
1910 ],
1911 options: {
1912 size: "small",
1913 color: "green",
1914 },
1915 },
1916 ],
1917 },
1918 adminHeaders
1919 )
1920 ).data.product
1921
1922 const inventoryItemOverride4 = (
1923 await api.post(
1924 `/admin/inventory-items`,
1925 { sku: "test-variant-4-no-shipping", requires_shipping: false },
1926 adminHeaders
1927 )
1928 ).data.inventory_item
1929
1930 await api.post(
1931 `/admin/inventory-items/${inventoryItemOverride4.id}/location-levels`,
1932 {
1933 location_id: stockChannelOverride.id,
1934 stocked_quantity: 10,
1935 },
1936 adminHeaders
1937 )
1938
1939 productOverride4 = (
1940 await api.post(
1941 "/admin/products",
1942 {
1943 title: `Test override 4`,
1944 status: ProductStatus.PUBLISHED,
1945 shipping_profile_id: shippingProfile.id,
1946 options: [{ title: "size", values: ["large"] }],
1947 variants: [
1948 {
1949 title: "Test variant 4",
1950 sku: "test-variant-4-override",
1951 inventory_items: [
1952 {
1953 inventory_item_id: inventoryItemOverride4.id,
1954 required_quantity: 3,
1955 },
1956 ],
1957 prices: [
1958 {
1959 currency_code: "usd",
1960 amount: 100,
1961 },
1962 ],
1963 options: {
1964 size: "large",
1965 },
1966 },
1967 ],
1968 },
1969 adminHeaders
1970 )
1971 ).data.product
1972
1973 shippingProfileOverride = (
1974 await api.post(
1975 `/admin/shipping-profiles`,
1976 { name: `test-${stockChannelOverride.id}`, type: "default" },
1977 adminHeaders
1978 )
1979 ).data.shipping_profile
1980
1981 productOverride4WithOverrideShippingProfile = (
1982 await api.post(
1983 "/admin/products",
1984 {
1985 title: `Test fixture 4`,
1986 status: ProductStatus.PUBLISHED,
1987 shipping_profile_id: shippingProfileOverride.id,
1988 options: [
1989 { title: "size", values: ["large", "small"] },
1990 { title: "color", values: ["green"] },
1991 ],
1992 variants: [
1993 {
1994 title: "Test variant 4",
1995 sku: "test-variant-4",
1996 inventory_items: [
1997 {
1998 inventory_item_id:
1999 inventoryItemOverride4RequiresShipping.id,
2000 required_quantity: 1,
2001 },
2002 ],
2003 prices: [
2004 {
2005 currency_code: "usd",
2006 amount: 100,
2007 },
2008 ],
2009 options: {
2010 size: "small",
2011 color: "green",
2012 },
2013 },
2014 ],
2015 },
2016 adminHeaders
2017 )
2018 ).data.product
2019
2020 seeder = await createOrderSeeder({
2021 api,
2022 container: getContainer(),
2023 productOverride,
2024 additionalProducts: [
2025 { variant_id: productOverride2.variants[0].id, quantity: 1 },
2026 { variant_id: productOverride3.variants[0].id, quantity: 3 },
2027 { variant_id: productOverride4.variants[0].id, quantity: 1 },
2028 {
2029 variant_id:
2030 productOverride4WithOverrideShippingProfile.variants[0].id,
2031 quantity: 1,
2032 },
2033 ],
2034 stockChannelOverride,
2035 inventoryItemOverride,
2036 shippingProfileOverride: [shippingProfile, shippingProfileOverride],
2037 })
2038 order = seeder.order
2039 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
2040 .order
2041 })
2042
2043 it("should update stock levels correctly when creating partial fulfillment on an order", async () => {
2044 const orderItemId = order.items.find(
2045 (i) => i.variant_id === productOverride3.variants[0].id
2046 ).id
2047
2048 let iitem = (
2049 await api.get(
2050 `/admin/inventory-items/${inventoryItemOverride3.id}?fields=stocked_quantity,reserved_quantity`,
2051 adminHeaders
2052 )
2053 ).data.inventory_item
2054
2055 expect(iitem.stocked_quantity).toBe(10)
2056 expect(iitem.reserved_quantity).toBe(3)
2057
2058 await api.post(
2059 `/admin/orders/${order.id}/fulfillments`,
2060 {
2061 shipping_option_id: seeder.shippingOption.id,
2062 location_id: seeder.stockLocation.id,
2063 items: [{ id: orderItemId, quantity: 1 }],
2064 },
2065 adminHeaders
2066 )
2067
2068 iitem = (
2069 await api.get(
2070 `/admin/inventory-items/${inventoryItemOverride3.id}?fields=stocked_quantity,reserved_quantity`,
2071 adminHeaders
2072 )
2073 ).data.inventory_item
2074
2075 expect(iitem.stocked_quantity).toBe(9)
2076 expect(iitem.reserved_quantity).toBe(2)
2077
2078 await api.post(
2079 `/admin/orders/${order.id}/fulfillments`,
2080 {
2081 shipping_option_id: seeder.shippingOption.id,
2082 location_id: seeder.stockLocation.id,
2083 items: [{ id: orderItemId, quantity: 1 }],
2084 },
2085 adminHeaders
2086 )
2087
2088 iitem = (
2089 await api.get(
2090 `/admin/inventory-items/${inventoryItemOverride3.id}?fields=stocked_quantity,reserved_quantity`,
2091 adminHeaders
2092 )
2093 ).data.inventory_item
2094
2095 expect(iitem.stocked_quantity).toBe(8)
2096 expect(iitem.reserved_quantity).toBe(1)
2097
2098 const {
2099 data: { order: fulfillableOrder },
2100 } = await api.post(
2101 `/admin/orders/${order.id}/fulfillments?fields=fulfillments.id`,
2102 {
2103 shipping_option_id: seeder.shippingOption.id,
2104 location_id: seeder.stockLocation.id,
2105 items: [{ id: orderItemId, quantity: 1 }],
2106 },
2107 adminHeaders
2108 )
2109
2110 expect(fulfillableOrder.fulfillments).toHaveLength(3)
2111
2112 iitem = (
2113 await api.get(
2114 `/admin/inventory-items/${inventoryItemOverride3.id}?fields=stocked_quantity,reserved_quantity`,
2115 adminHeaders
2116 )
2117 ).data.inventory_item
2118
2119 expect(iitem.stocked_quantity).toBe(7)
2120 expect(iitem.reserved_quantity).toBe(0)
2121 })
2122
2123 it("should override the fulfillment's delivery address with the request's delivery_address", async () => {
2124 const orderItemId = order.items.find(
2125 (i) => i.variant_id === productOverride3.variants[0].id
2126 ).id
2127
2128 const {
2129 data: { order: fulfillableOrder },
2130 } = await api.post(
2131 `/admin/orders/${order.id}/fulfillments?fields=fulfillments.id,fulfillments.delivery_address.*`,
2132 {
2133 shipping_option_id: seeder.shippingOption.id,
2134 location_id: seeder.stockLocation.id,
2135 items: [{ id: orderItemId, quantity: 1 }],
2136 delivery_address: {
2137 first_name: "Nova",
2138 last_name: "Poshta",
2139 },
2140 },
2141 adminHeaders
2142 )
2143
2144 expect(fulfillableOrder.fulfillments).toHaveLength(1)
2145 expect(fulfillableOrder.fulfillments[0].delivery_address).toEqual(
2146 expect.objectContaining({
2147 // overridden by the request
2148 first_name: "Nova",
2149 last_name: "Poshta",
2150 // untouched fields are still taken from the order's shipping address
2151 address_1: order.shipping_address.address_1,
2152 city: order.shipping_address.city,
2153 country_code: order.shipping_address.country_code,
2154 })
2155 )
2156 })
2157
2158 it("should throw if trying to fulfillment more items than it is reserved", async () => {
2159 const orderItemId = order.items.find(
2160 (i) => i.variant_id === productOverride3.variants[0].id
2161 ).id
2162
2163 const res = await api
2164 .post(
2165 `/admin/orders/${order.id}/fulfillments`,
2166 {
2167 shipping_option_id: seeder.shippingOption.id,
2168 location_id: seeder.stockLocation.id,
2169 items: [{ id: orderItemId, quantity: 5 }],
2170 },
2171 adminHeaders
2172 )
2173 .catch((e) => e)
2174
2175 expect(res.response.status).toBe(400)
2176 expect(res.response.data.message).toBe(
2177 `Quantity to fulfill exceeds the reserved quantity for the item: ${orderItemId}`
2178 )
2179 })
2180
2181 it("should throw if trying to fulfillment more items than it is reserved when item has required quantity", async () => {
2182 const orderItemId = order.items.find(
2183 (i) => i.variant_id === productOverride4.variants[0].id
2184 ).id
2185
2186 let reservation = (
2187 await api.get(
2188 `/admin/reservations?line_item_id=${orderItemId}`,
2189 adminHeaders
2190 )
2191 ).data.reservations[0]
2192
2193 expect(reservation.quantity).toBe(3) // one item with required quantity 3
2194
2195 reservation = (
2196 await api.post(
2197 `/admin/reservations/${reservation.id}`,
2198 {
2199 quantity: 2,
2200 },
2201 adminHeaders
2202 )
2203 ).data.reservation
2204
2205 expect(reservation.quantity).toBe(2)
2206
2207 const res = await api
2208 .post(
2209 `/admin/orders/${order.id}/fulfillments`,
2210 {
2211 shipping_option_id: seeder.shippingOption.id,
2212 location_id: seeder.stockLocation.id,
2213 items: [{ id: orderItemId, quantity: 1 }], // fulfill 1 orer item which requires 3 inventor items
2214 },
2215 adminHeaders
2216 )
2217 .catch((e) => e)
2218
2219 expect(res.response.status).toBe(400)
2220 expect(res.response.data.message).toBe(
2221 `Quantity to fulfill exceeds the reserved quantity for the item: ${orderItemId}`
2222 )
2223 })
2224
2225 it("should throw if shipping profile of the product doesn't match the shipping profile of the shipping option", async () => {
2226 const orderItemId = order.items.find(
2227 (i) =>
2228 i.variant_id ===
2229 productOverride4WithOverrideShippingProfile.variants[0].id
2230 ).id
2231
2232 const res = await api
2233 .post(
2234 `/admin/orders/${order.id}/fulfillments`,
2235 {
2236 shipping_option_id: seeder.shippingOption.id, // shipping option with the "regular" shipping profile
2237 location_id: stockChannelOverride.id,
2238 items: [{ id: orderItemId, quantity: 1 }],
2239 },
2240 adminHeaders
2241 )
2242 .catch((e) => e)
2243
2244 expect(res.response.status).toBe(400)
2245 expect(res.response.data.message).toBe(
2246 `Shipping profile ${seeder.shippingProfile.id} does not match the shipping profile of the order item ${orderItemId}`
2247 )
2248 })
2249
2250 it("should only create fulfillments grouped by shipping requirement", async () => {
2251 const i1 = order.items.find((i) => i.variant_sku === `w-inv-override-1`)
2252 const i2 = order.items.find((i) => i.variant_sku === `w-inv-override-2`)
2253
2254 const {
2255 response: { data },
2256 } = await api
2257 .post(
2258 `/admin/orders/${order.id}/fulfillments`,
2259 {
2260 shipping_option_id: seeder.shippingOption.id,
2261 location_id: seeder.stockLocation.id,
2262 items: [
2263 {
2264 id: i1.id,
2265 quantity: 1,
2266 },
2267 {
2268 id: i2.id,
2269 quantity: 1,
2270 },
2271 ],
2272 },
2273 adminHeaders
2274 )
2275 .catch((e) => e)
2276
2277 expect(data).toEqual({
2278 type: "invalid_data",
2279 message: `Fulfillment can only be created entirely with items with shipping or items without shipping. Split this request into 2 fulfillments.`,
2280 })
2281
2282 const {
2283 data: { order: fulfillableOrder },
2284 } = await api.post(
2285 `/admin/orders/${order.id}/fulfillments?fields=+fulfillments.id,fulfillments.requires_shipping`,
2286 {
2287 shipping_option_id: seeder.shippingOption.id,
2288 location_id: seeder.stockLocation.id,
2289 items: [{ id: i1.id, quantity: 1 }],
2290 },
2291 adminHeaders
2292 )
2293
2294 expect(fulfillableOrder.fulfillments).toHaveLength(1)
2295
2296 const {
2297 data: { order: fulfillableOrder2 },
2298 } = await api.post(
2299 `/admin/orders/${order.id}/fulfillments?fields=+fulfillments.id,fulfillments.requires_shipping`,
2300 {
2301 shipping_option_id: seeder.shippingOption.id,
2302 location_id: seeder.stockLocation.id,
2303 items: [{ id: i2.id, quantity: 1 }],
2304 },
2305 adminHeaders
2306 )
2307
2308 expect(fulfillableOrder2.fulfillments).toHaveLength(2)
2309 })
2310 })
2311
2312 describe("POST /orders/:id/fulfillments/:id/cancel", () => {
2313 let inventoryItemDesk
2314 let inventoryItemLeg
2315
2316 let region
2317 let salesChannel
2318 let stockLocation
2319 let shippingOption
2320 let storeHeaders
2321
2322 beforeEach(async () => {
2323 const container = getContainer()
2324
2325 const publishableKey = await generatePublishableKey(container)
2326
2327 storeHeaders = generateStoreHeaders({
2328 publishableKey,
2329 })
2330
2331 region = (
2332 await api.post(
2333 "/admin/regions",
2334 {
2335 payment_providers: ["pp_system_default"],
2336 name: "Test region",
2337 currency_code: "usd",
2338 },
2339 adminHeaders
2340 )
2341 ).data.region
2342
2343 salesChannel = (
2344 await api.post(
2345 "/admin/sales-channels",
2346 { name: "first channel", description: "channel" },
2347 adminHeaders
2348 )
2349 ).data.sales_channel
2350
2351 stockLocation = (
2352 await api.post(
2353 `/admin/stock-locations`,
2354 { name: "test location" },
2355 adminHeaders
2356 )
2357 ).data.stock_location
2358
2359 inventoryItemDesk = (
2360 await api.post(
2361 `/admin/inventory-items`,
2362 { sku: "table-desk" },
2363 adminHeaders
2364 )
2365 ).data.inventory_item
2366
2367 inventoryItemLeg = (
2368 await api.post(
2369 `/admin/inventory-items`,
2370 { sku: "table-leg" },
2371 adminHeaders
2372 )
2373 ).data.inventory_item
2374
2375 await api.post(
2376 `/admin/inventory-items/${inventoryItemDesk.id}/location-levels`,
2377 {
2378 location_id: stockLocation.id,
2379 stocked_quantity: 10,
2380 },
2381 adminHeaders
2382 )
2383
2384 await api.post(
2385 `/admin/inventory-items/${inventoryItemLeg.id}/location-levels`,
2386 {
2387 location_id: stockLocation.id,
2388 stocked_quantity: 40,
2389 },
2390 adminHeaders
2391 )
2392
2393 await api.post(
2394 `/admin/stock-locations/${stockLocation.id}/sales-channels`,
2395 { add: [salesChannel.id] },
2396 adminHeaders
2397 )
2398
2399 shippingProfile = (
2400 await api.post(
2401 `/admin/shipping-profiles`,
2402 { name: `test-${stockLocation.id}`, type: "default" },
2403 adminHeaders
2404 )
2405 ).data.shipping_profile
2406
2407 const product = (
2408 await api.post(
2409 "/admin/products",
2410 {
2411 title: `Wooden table`,
2412 status: ProductStatus.PUBLISHED,
2413 shipping_profile_id: shippingProfile.id,
2414 options: [{ title: "color", values: ["green"] }],
2415 variants: [
2416 {
2417 title: "Green table",
2418 sku: "green-table",
2419 inventory_items: [
2420 {
2421 inventory_item_id: inventoryItemDesk.id,
2422 required_quantity: 1,
2423 },
2424 {
2425 inventory_item_id: inventoryItemLeg.id,
2426 required_quantity: 4,
2427 },
2428 ],
2429 prices: [
2430 {
2431 currency_code: "usd",
2432 amount: 100,
2433 },
2434 ],
2435 options: {
2436 color: "green",
2437 },
2438 },
2439 ],
2440 },
2441 adminHeaders
2442 )
2443 ).data.product
2444
2445 const fulfillmentSets = (
2446 await api.post(
2447 `/admin/stock-locations/${stockLocation.id}/fulfillment-sets?fields=*fulfillment_sets`,
2448 {
2449 name: `Test-${shippingProfile.id}`,
2450 type: "test-type",
2451 },
2452 adminHeaders
2453 )
2454 ).data.stock_location.fulfillment_sets
2455
2456 const fulfillmentSet = (
2457 await api.post(
2458 `/admin/fulfillment-sets/${fulfillmentSets[0].id}/service-zones`,
2459 {
2460 name: `Test-${shippingProfile.id}`,
2461 geo_zones: [{ type: "country", country_code: "us" }],
2462 },
2463 adminHeaders
2464 )
2465 ).data.fulfillment_set
2466
2467 await api.post(
2468 `/admin/stock-locations/${stockLocation.id}/fulfillment-providers`,
2469 { add: ["manual_test-provider"] },
2470 adminHeaders
2471 )
2472
2473 shippingOption = (
2474 await api.post(
2475 `/admin/shipping-options`,
2476 {
2477 name: `Test shipping option ${fulfillmentSet.id}`,
2478 service_zone_id: fulfillmentSet.service_zones[0].id,
2479 shipping_profile_id: shippingProfile.id,
2480 provider_id: "manual_test-provider",
2481 price_type: "flat",
2482 type: {
2483 label: "Test type",
2484 description: "Test description",
2485 code: "test-code",
2486 },
2487 prices: [
2488 { currency_code: "usd", amount: 1000 },
2489 { region_id: region.id, amount: 1100 },
2490 ],
2491 rules: [],
2492 },
2493 adminHeaders
2494 )
2495 ).data.shipping_option
2496
2497 const cart = (
2498 await api.post(
2499 `/store/carts`,
2500 {
2501 currency_code: "usd",
2502 email: "tony@stark-industries.com",
2503 region_id: region.id,
2504 shipping_address: {
2505 address_1: "test address 1",
2506 address_2: "test address 2",
2507 city: "ny",
2508 country_code: "us",
2509 province: "ny",
2510 postal_code: "94016",
2511 },
2512 billing_address: {
2513 address_1: "test billing address 1",
2514 address_2: "test billing address 2",
2515 city: "ny",
2516 country_code: "us",
2517 province: "ny",
2518 postal_code: "94016",
2519 },
2520 sales_channel_id: salesChannel.id,
2521 items: [{ quantity: 2, variant_id: product.variants[0].id }],
2522 },
2523 storeHeaders
2524 )
2525 ).data.cart
2526
2527 await api.post(
2528 `/store/carts/${cart.id}/shipping-methods`,
2529 { option_id: shippingOption.id },
2530 storeHeaders
2531 )
2532
2533 const paymentCollection = (
2534 await api.post(
2535 `/store/payment-collections`,
2536 {
2537 cart_id: cart.id,
2538 },
2539 storeHeaders
2540 )
2541 ).data.payment_collection
2542
2543 await api.post(
2544 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
2545 { provider_id: "pp_system_default" },
2546 storeHeaders
2547 )
2548
2549 order = (
2550 await api.post(`/store/carts/${cart.id}/complete`, {}, storeHeaders)
2551 ).data.order
2552 })
2553
2554 it("should create and cancel a fulfillment with reservations recreation multiple times", async () => {
2555 const inventoryItemTablet = (
2556 await api.post(
2557 `/admin/inventory-items`,
2558 { sku: "tablet" },
2559 adminHeaders
2560 )
2561 ).data.inventory_item
2562
2563 await api.post(
2564 `/admin/inventory-items/${inventoryItemTablet.id}/location-levels`,
2565 {
2566 location_id: stockLocation.id,
2567 stocked_quantity: 10,
2568 },
2569 adminHeaders
2570 )
2571
2572 const productTablet = (
2573 await api.post(
2574 "/admin/products",
2575 {
2576 title: `Tablet`,
2577 status: ProductStatus.PUBLISHED,
2578 shipping_profile_id: shippingProfile.id,
2579 options: [{ title: "color", values: ["green"] }],
2580 variants: [
2581 {
2582 title: "Green tablet",
2583 sku: "green-tablet",
2584 inventory_items: [
2585 {
2586 inventory_item_id: inventoryItemTablet.id,
2587 required_quantity: 1,
2588 },
2589 ],
2590 prices: [
2591 {
2592 currency_code: "usd",
2593 amount: 1000,
2594 },
2595 ],
2596 options: {
2597 color: "green",
2598 },
2599 },
2600 ],
2601 },
2602 adminHeaders
2603 )
2604 ).data.product
2605
2606 const cartTablet = (
2607 await api.post(
2608 `/store/carts`,
2609 {
2610 currency_code: "usd",
2611 email: "tony@stark-industries.com",
2612 region_id: region.id,
2613 shipping_address: {
2614 address_1: "test address 1",
2615 address_2: "test address 2",
2616 city: "ny",
2617 country_code: "us",
2618 province: "ny",
2619 postal_code: "94016",
2620 },
2621 billing_address: {
2622 address_1: "test billing address 1",
2623 address_2: "test billing address 2",
2624 city: "ny",
2625 country_code: "us",
2626 province: "ny",
2627 postal_code: "94016",
2628 },
2629 sales_channel_id: salesChannel.id,
2630 items: [
2631 { quantity: 1, variant_id: productTablet.variants[0].id },
2632 ],
2633 },
2634 storeHeaders
2635 )
2636 ).data.cart
2637
2638 await api.post(
2639 `/store/carts/${cartTablet.id}/shipping-methods`,
2640 { option_id: shippingOption.id },
2641 storeHeaders
2642 )
2643
2644 const paymentCollectionTablet = (
2645 await api.post(
2646 `/store/payment-collections`,
2647 {
2648 cart_id: cartTablet.id,
2649 },
2650 storeHeaders
2651 )
2652 ).data.payment_collection
2653
2654 await api.post(
2655 `/store/payment-collections/${paymentCollectionTablet.id}/payment-sessions`,
2656 { provider_id: "pp_system_default" },
2657 storeHeaders
2658 )
2659
2660 const tabletOrder = (
2661 await api.post(
2662 `/store/carts/${cartTablet.id}/complete`,
2663 {},
2664 storeHeaders
2665 )
2666 ).data.order
2667
2668 const lineItemId = tabletOrder.items[0].id
2669
2670 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
2671 .data.reservations
2672
2673 expect(reservations).toEqual(
2674 expect.arrayContaining([
2675 expect.objectContaining({
2676 line_item_id: lineItemId,
2677 inventory_item_id: inventoryItemTablet.id,
2678 quantity: 1,
2679 }),
2680 ])
2681 )
2682
2683 // create a fulfillment for the entire tablet order
2684 const fulOrder = (
2685 await api.post(
2686 `/admin/orders/${tabletOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
2687 {
2688 items: [{ id: tabletOrder.items[0].id, quantity: 1 }],
2689 },
2690 adminHeaders
2691 )
2692 ).data.order
2693
2694 reservations = (
2695 await api.get(
2696 `/admin/reservations?line_item_id[]=${lineItemId}`,
2697 adminHeaders
2698 )
2699 ).data.reservations
2700
2701 // no more reservations since everything is fuliflled
2702 expect(reservations.length).toEqual(0)
2703
2704 // cancel the fulfillment
2705 await api.post(
2706 `/admin/orders/${tabletOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/cancel`,
2707 {},
2708 adminHeaders
2709 )
2710
2711 reservations = (
2712 await api.get(
2713 `/admin/reservations?line_item_id=${lineItemId}`,
2714 adminHeaders
2715 )
2716 ).data.reservations
2717
2718 // reservations are recreated after the fulfillment is canceled
2719 expect(reservations).toEqual(
2720 expect.arrayContaining([
2721 expect.objectContaining({
2722 line_item_id: lineItemId,
2723 inventory_item_id: inventoryItemTablet.id,
2724 quantity: 1,
2725 }),
2726 ])
2727 )
2728
2729 // create a fulfillment for the entire tablet order again
2730 const fulOrder2 = (
2731 await api.post(
2732 `/admin/orders/${tabletOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
2733 {
2734 items: [{ id: tabletOrder.items[0].id, quantity: 1 }],
2735 },
2736 adminHeaders
2737 )
2738 ).data.order
2739
2740 reservations = (
2741 await api.get(
2742 `/admin/reservations?line_item_id[]=${lineItemId}`,
2743 adminHeaders
2744 )
2745 ).data.reservations
2746
2747 // no more reservations since everything is fuliflled again
2748 expect(reservations.length).toEqual(0)
2749
2750 // cancel the fulfillment
2751 await api.post(
2752 `/admin/orders/${tabletOrder.id}/fulfillments/${
2753 fulOrder2.fulfillments.find((f) => !f.canceled_at).id
2754 }/cancel`,
2755 {},
2756 adminHeaders
2757 )
2758
2759 reservations = (
2760 await api.get(
2761 `/admin/reservations?line_item_id=${lineItemId}`,
2762 adminHeaders
2763 )
2764 ).data.reservations
2765
2766 // reservations are recreated again
2767 expect(reservations).toEqual(
2768 expect.arrayContaining([
2769 expect.objectContaining({
2770 line_item_id: lineItemId,
2771 inventory_item_id: inventoryItemTablet.id,
2772 quantity: 1,
2773 }),
2774 ])
2775 )
2776 })
2777
2778 it("should manage reservations when canceling a fulfillment (with allow_backorder item)", async () => {
2779 const inventoryItemTablet = (
2780 await api.post(
2781 `/admin/inventory-items`,
2782 { sku: "tablet" },
2783 adminHeaders
2784 )
2785 ).data.inventory_item
2786
2787 await api.post(
2788 `/admin/inventory-items/${inventoryItemTablet.id}/location-levels`,
2789 {
2790 location_id: stockLocation.id,
2791 stocked_quantity: 1,
2792 },
2793 adminHeaders
2794 )
2795
2796 const productTablet = (
2797 await api.post(
2798 "/admin/products",
2799 {
2800 title: `Tablet`,
2801 status: ProductStatus.PUBLISHED,
2802 shipping_profile_id: shippingProfile.id,
2803 options: [{ title: "color", values: ["green"] }],
2804 variants: [
2805 {
2806 title: "Green tablet",
2807 sku: "green-tablet",
2808 allow_backorder: true,
2809 manage_inventory: true,
2810 inventory_items: [
2811 {
2812 inventory_item_id: inventoryItemTablet.id,
2813 required_quantity: 1,
2814 },
2815 ],
2816 prices: [
2817 {
2818 currency_code: "usd",
2819 amount: 1000,
2820 },
2821 ],
2822 options: {
2823 color: "green",
2824 },
2825 },
2826 ],
2827 },
2828 adminHeaders
2829 )
2830 ).data.product
2831
2832 const cartTablet = (
2833 await api.post(
2834 `/store/carts`,
2835 {
2836 currency_code: "usd",
2837 email: "tony@stark-industries.com",
2838 region_id: region.id,
2839 shipping_address: {
2840 address_1: "test address 1",
2841 address_2: "test address 2",
2842 city: "ny",
2843 country_code: "us",
2844 province: "ny",
2845 postal_code: "94016",
2846 },
2847 billing_address: {
2848 address_1: "test billing address 1",
2849 address_2: "test billing address 2",
2850 city: "ny",
2851 country_code: "us",
2852 province: "ny",
2853 postal_code: "94016",
2854 },
2855 sales_channel_id: salesChannel.id,
2856 items: [
2857 { quantity: 2, variant_id: productTablet.variants[0].id },
2858 ],
2859 },
2860 storeHeaders
2861 )
2862 ).data.cart
2863
2864 await api.post(
2865 `/store/carts/${cartTablet.id}/shipping-methods`,
2866 { option_id: shippingOption.id },
2867 storeHeaders
2868 )
2869
2870 const paymentCollectionTablet = (
2871 await api.post(
2872 `/store/payment-collections`,
2873 {
2874 cart_id: cartTablet.id,
2875 },
2876 storeHeaders
2877 )
2878 ).data.payment_collection
2879
2880 await api.post(
2881 `/store/payment-collections/${paymentCollectionTablet.id}/payment-sessions`,
2882 { provider_id: "pp_system_default" },
2883 storeHeaders
2884 )
2885
2886 const tabletOrder = (
2887 await api.post(
2888 `/store/carts/${cartTablet.id}/complete`,
2889 {},
2890 storeHeaders
2891 )
2892 ).data.order
2893
2894 const lineItemId = tabletOrder.items[0].id
2895
2896 let reservations = (
2897 await api.get(
2898 `/admin/reservations?line_item_id[]=${lineItemId}`,
2899 adminHeaders
2900 )
2901 ).data.reservations
2902
2903 expect(reservations).toEqual(
2904 expect.arrayContaining([
2905 expect.objectContaining({
2906 line_item_id: lineItemId,
2907 inventory_item_id: inventoryItemTablet.id,
2908 quantity: 2,
2909 inventory_item: expect.objectContaining({
2910 reserved_quantity: 2,
2911 stocked_quantity: 1,
2912 }),
2913 }),
2914 ])
2915 )
2916
2917 const fulOrder = (
2918 await api.post(
2919 `/admin/orders/${tabletOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
2920 {
2921 items: [{ id: tabletOrder.items[0].id, quantity: 2 }],
2922 },
2923 adminHeaders
2924 )
2925 ).data.order
2926
2927 reservations = (
2928 await api.get(
2929 `/admin/reservations?line_item_id[]=${lineItemId}`,
2930 adminHeaders
2931 )
2932 ).data.reservations
2933
2934 expect(reservations.length).toEqual(0)
2935
2936 const inventoryItem = (
2937 await api.get(
2938 `/admin/inventory-items/${inventoryItemTablet.id}`,
2939 adminHeaders
2940 )
2941 ).data.inventory_item
2942
2943 expect(inventoryItem).toEqual(
2944 expect.objectContaining({
2945 reserved_quantity: 0,
2946 stocked_quantity: -1,
2947 location_levels: [
2948 expect.objectContaining({
2949 available_quantity: -1,
2950 reserved_quantity: 0,
2951 stocked_quantity: -1,
2952 }),
2953 ],
2954 })
2955 )
2956
2957 await api.post(
2958 `/admin/orders/${tabletOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/cancel`,
2959 {},
2960 adminHeaders
2961 )
2962
2963 reservations = (
2964 await api.get(
2965 `/admin/reservations?line_item_id[]=${lineItemId}`,
2966 adminHeaders
2967 )
2968 ).data.reservations
2969
2970 expect(reservations).toEqual(
2971 expect.arrayContaining([
2972 expect.objectContaining({
2973 line_item_id: lineItemId,
2974 inventory_item_id: inventoryItemTablet.id,
2975 quantity: 2,
2976 inventory_item: expect.objectContaining({
2977 reserved_quantity: 2,
2978 stocked_quantity: 1,
2979 }),
2980 }),
2981 ])
2982 )
2983 })
2984
2985 it("should correctly manage reservations when canceling a fulfillment (with inventory kit)", async () => {
2986 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
2987 .data.reservations
2988
2989 expect(reservations).toEqual(
2990 expect.arrayContaining([
2991 expect.objectContaining({
2992 inventory_item_id: inventoryItemDesk.id,
2993 quantity: 2,
2994 inventory_item: expect.objectContaining({
2995 reserved_quantity: 2,
2996 stocked_quantity: 10,
2997 }),
2998 }),
2999 expect.objectContaining({
3000 inventory_item_id: inventoryItemLeg.id,
3001 quantity: 8,
3002 inventory_item: expect.objectContaining({
3003 reserved_quantity: 8,
3004 stocked_quantity: 40,
3005 }),
3006 }),
3007 ])
3008 )
3009
3010 const lineItemId = order.items[0].id
3011
3012 // 1. create a partial fulfillment
3013 const fulOrder = (
3014 await api.post(
3015 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3016 {
3017 items: [{ id: order.items[0].id, quantity: 1 }],
3018 },
3019 adminHeaders
3020 )
3021 ).data.order
3022
3023 // 2. two fulfillment items are created for a single (inventory kit) line item
3024 expect(fulOrder.fulfillments[0].items).toEqual(
3025 expect.arrayContaining([
3026 expect.objectContaining({
3027 inventory_item_id: inventoryItemDesk.id,
3028 quantity: 1,
3029 }),
3030 expect.objectContaining({
3031 inventory_item_id: inventoryItemLeg.id,
3032 quantity: 4,
3033 }),
3034 ])
3035 )
3036
3037 expect(fulOrder.items[0].detail.fulfilled_quantity).toEqual(1)
3038
3039 reservations = (
3040 await api.get(
3041 `/admin/reservations?line_item_id[]=${lineItemId}`,
3042 adminHeaders
3043 )
3044 ).data.reservations
3045
3046 // 3. reservations need to be reduced by half since we fulfilled 1 item out of 2 in the order
3047 expect(reservations).toEqual(
3048 expect.arrayContaining([
3049 expect.objectContaining({
3050 inventory_item_id: inventoryItemDesk.id,
3051 quantity: 1,
3052 inventory_item: expect.objectContaining({
3053 reserved_quantity: 1,
3054 stocked_quantity: 9,
3055 }),
3056 }),
3057 expect.objectContaining({
3058 inventory_item_id: inventoryItemLeg.id,
3059 quantity: 4,
3060 inventory_item: expect.objectContaining({
3061 reserved_quantity: 4,
3062 stocked_quantity: 36,
3063 }),
3064 }),
3065 ])
3066 )
3067
3068 const { data } = await api.post(
3069 `/admin/orders/${fulOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/cancel?fields=*fulfillments,*fulfillments.items`,
3070 {},
3071 adminHeaders
3072 )
3073
3074 expect(data.order.fulfillments[0].canceled_at).toBeDefined()
3075 expect(data.order.items[0].detail.fulfilled_quantity).toEqual(0)
3076
3077 reservations = (
3078 await api.get(
3079 `/admin/reservations?line_item_id[]=${lineItemId}`,
3080 adminHeaders
3081 )
3082 ).data.reservations
3083
3084 // 4. reservation qunatities are restored after partial fulfillment is canceled
3085 expect(reservations).toEqual(
3086 expect.arrayContaining([
3087 expect.objectContaining({
3088 inventory_item_id: inventoryItemDesk.id,
3089 quantity: 2,
3090 inventory_item: expect.objectContaining({
3091 reserved_quantity: 2,
3092 stocked_quantity: 10,
3093 }),
3094 }),
3095 expect.objectContaining({
3096 inventory_item_id: inventoryItemLeg.id,
3097 quantity: 8,
3098 inventory_item: expect.objectContaining({
3099 reserved_quantity: 8,
3100 stocked_quantity: 40,
3101 }),
3102 }),
3103 ])
3104 )
3105
3106 // 5. create a fullfillment for the entier quantity
3107 const fulOrderFull = (
3108 await api.post(
3109 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3110 {
3111 items: [{ id: order.items[0].id, quantity: 2 }],
3112 },
3113 adminHeaders
3114 )
3115 ).data.order
3116
3117 reservations = (
3118 await api.get(
3119 `/admin/reservations?line_item_id[]=${lineItemId}`,
3120 adminHeaders
3121 )
3122 ).data.reservations
3123
3124 // 6. no more reservations since the entier quantity is fulfilled
3125 expect(reservations).toEqual([])
3126
3127 expect(
3128 fulOrderFull.fulfillments.find((f) => !f.canceled_at)!.items
3129 ).toEqual(
3130 expect.arrayContaining([
3131 expect.objectContaining({
3132 inventory_item_id: inventoryItemDesk.id,
3133 quantity: 2,
3134 }),
3135 expect.objectContaining({
3136 inventory_item_id: inventoryItemLeg.id,
3137 quantity: 8,
3138 }),
3139 ])
3140 )
3141
3142 expect(fulOrderFull.items[0].detail.fulfilled_quantity).toEqual(2)
3143
3144 // 7. cancel the entire fulfillment once again
3145 await api.post(
3146 `/admin/orders/${fulOrderFull.id}/fulfillments/${
3147 fulOrderFull.fulfillments.find((f) => !f.canceled_at)!.id
3148 }/cancel?fields=*fulfillments,*fulfillments.items`,
3149 {},
3150 adminHeaders
3151 )
3152
3153 reservations = (
3154 await api.get(
3155 `/admin/reservations?line_item_id[]=${lineItemId}`,
3156 adminHeaders
3157 )
3158 ).data.reservations
3159
3160 // 8. reservation need to be restored to the initiall quantities
3161 expect(reservations).toEqual(
3162 expect.arrayContaining([
3163 expect.objectContaining({
3164 inventory_item_id: inventoryItemDesk.id,
3165 quantity: 2,
3166 inventory_item: expect.objectContaining({
3167 reserved_quantity: 2,
3168 stocked_quantity: 10,
3169 }),
3170 }),
3171 expect.objectContaining({
3172 inventory_item_id: inventoryItemLeg.id,
3173 quantity: 8,
3174 inventory_item: expect.objectContaining({
3175 reserved_quantity: 8,
3176 stocked_quantity: 40,
3177 }),
3178 }),
3179 ])
3180 )
3181 })
3182
3183 it("should correctly manage reservations (with shared inventory item case)", async () => {
3184 const inventoryItemBottle = (
3185 await api.post(
3186 `/admin/inventory-items`,
3187 { sku: "bottle" },
3188 adminHeaders
3189 )
3190 ).data.inventory_item
3191
3192 await api.post(
3193 `/admin/inventory-items/${inventoryItemBottle.id}/location-levels`,
3194 {
3195 location_id: stockLocation.id,
3196 stocked_quantity: 100,
3197 },
3198 adminHeaders
3199 )
3200
3201 const productBottle = (
3202 await api.post(
3203 "/admin/products",
3204 {
3205 title: `Bottle Packs`,
3206 status: ProductStatus.PUBLISHED,
3207 shipping_profile_id: shippingProfile.id,
3208 options: [{ title: "packs", values: ["one", "two", "three"] }],
3209 variants: [
3210 {
3211 title: "One Pack",
3212 sku: "one-pack",
3213 inventory_items: [
3214 {
3215 inventory_item_id: inventoryItemBottle.id,
3216 required_quantity: 1,
3217 },
3218 ],
3219 prices: [
3220 {
3221 currency_code: "usd",
3222 amount: 10,
3223 },
3224 ],
3225 options: {
3226 packs: "one",
3227 },
3228 },
3229 {
3230 title: "Two Pack",
3231 sku: "two-pack",
3232 inventory_items: [
3233 {
3234 inventory_item_id: inventoryItemBottle.id,
3235 required_quantity: 2,
3236 },
3237 ],
3238 prices: [
3239 {
3240 currency_code: "usd",
3241 amount: 20,
3242 },
3243 ],
3244 options: {
3245 packs: "two",
3246 },
3247 },
3248 {
3249 title: "Three Pack",
3250 sku: "three-pack",
3251 inventory_items: [
3252 {
3253 inventory_item_id: inventoryItemBottle.id,
3254 required_quantity: 3,
3255 },
3256 ],
3257 prices: [
3258 {
3259 currency_code: "usd",
3260 amount: 30,
3261 },
3262 ],
3263 options: {
3264 packs: "three",
3265 },
3266 },
3267 ],
3268 },
3269 adminHeaders
3270 )
3271 ).data.product
3272
3273 const cartBottle = (
3274 await api.post(
3275 `/store/carts`,
3276 {
3277 currency_code: "usd",
3278 email: "tony@stark-industries.com",
3279 region_id: region.id,
3280 shipping_address: {
3281 address_1: "test address 1",
3282 address_2: "test address 2",
3283 city: "ny",
3284 country_code: "us",
3285 province: "ny",
3286 postal_code: "94016",
3287 },
3288 billing_address: {
3289 address_1: "test billing address 1",
3290 address_2: "test billing address 2",
3291 city: "ny",
3292 country_code: "us",
3293 province: "ny",
3294 postal_code: "94016",
3295 },
3296 sales_channel_id: salesChannel.id,
3297 items: [
3298 { quantity: 2, variant_id: productBottle.variants[0].id },
3299 { quantity: 2, variant_id: productBottle.variants[1].id },
3300 { quantity: 2, variant_id: productBottle.variants[2].id },
3301 ],
3302 },
3303 storeHeaders
3304 )
3305 ).data.cart
3306
3307 await api.post(
3308 `/store/carts/${cartBottle.id}/shipping-methods`,
3309 { option_id: shippingOption.id },
3310 storeHeaders
3311 )
3312
3313 const paymentCollectionBottle = (
3314 await api.post(
3315 `/store/payment-collections`,
3316 {
3317 cart_id: cartBottle.id,
3318 },
3319 storeHeaders
3320 )
3321 ).data.payment_collection
3322
3323 await api.post(
3324 `/store/payment-collections/${paymentCollectionBottle.id}/payment-sessions`,
3325 { provider_id: "pp_system_default" },
3326 storeHeaders
3327 )
3328
3329 const bottleOrder = (
3330 await api.post(
3331 `/store/carts/${cartBottle.id}/complete`,
3332 {},
3333 storeHeaders
3334 )
3335 ).data.order
3336
3337 const lineItemIds = bottleOrder.items.map((i) => i.id).join(",")
3338
3339 const onePackItemId = bottleOrder.items.find(
3340 (i) => i.subtitle === "One Pack"
3341 )!.id
3342
3343 const twoPackItemId = bottleOrder.items.find(
3344 (i) => i.subtitle === "Two Pack"
3345 )!.id
3346
3347 const threePackItemId = bottleOrder.items.find(
3348 (i) => i.subtitle === "Three Pack"
3349 )!.id
3350
3351 let reservations = (
3352 await api.get(
3353 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3354 adminHeaders
3355 )
3356 ).data.reservations
3357
3358 expect(reservations).toEqual(
3359 expect.arrayContaining([
3360 expect.objectContaining({
3361 line_item_id: onePackItemId,
3362 inventory_item_id: inventoryItemBottle.id,
3363 quantity: 2,
3364 }),
3365 expect.objectContaining({
3366 line_item_id: twoPackItemId,
3367 inventory_item_id: inventoryItemBottle.id,
3368 quantity: 4,
3369 }),
3370 expect.objectContaining({
3371 line_item_id: threePackItemId,
3372 inventory_item_id: inventoryItemBottle.id,
3373 quantity: 6,
3374 }),
3375 ])
3376 )
3377
3378 expect(reservations[0].inventory_item).toEqual(
3379 expect.objectContaining({
3380 id: inventoryItemBottle.id,
3381 reserved_quantity: 12, // 2 * (onepack + twopack + threepack)
3382 stocked_quantity: 100,
3383 })
3384 )
3385
3386 // create a partial fulfillment only for one "Three Pack"
3387 const fulOrder = (
3388 await api.post(
3389 `/admin/orders/${bottleOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3390 {
3391 items: [
3392 {
3393 id: threePackItemId,
3394 quantity: 1,
3395 },
3396 ],
3397 },
3398 adminHeaders
3399 )
3400 ).data.order
3401
3402 expect(
3403 fulOrder.items.find((i) => i.id === threePackItemId)!.detail
3404 .fulfilled_quantity
3405 ).toEqual(1)
3406
3407 reservations = (
3408 await api.get(
3409 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3410 adminHeaders
3411 )
3412 ).data.reservations
3413
3414 expect(reservations).toEqual(
3415 expect.arrayContaining([
3416 expect.objectContaining({
3417 line_item_id: onePackItemId,
3418 inventory_item_id: inventoryItemBottle.id,
3419 quantity: 2,
3420 }),
3421 expect.objectContaining({
3422 line_item_id: twoPackItemId,
3423 inventory_item_id: inventoryItemBottle.id,
3424 quantity: 4,
3425 }),
3426 expect.objectContaining({
3427 line_item_id: threePackItemId,
3428 inventory_item_id: inventoryItemBottle.id,
3429 quantity: 3, // This was partially fulfilled
3430 }),
3431 ])
3432 )
3433
3434 expect(reservations[0].inventory_item).toEqual(
3435 expect.objectContaining({
3436 id: inventoryItemBottle.id,
3437 reserved_quantity: 9,
3438 stocked_quantity: 97,
3439 })
3440 )
3441
3442 // cancel the first partial fulfillment
3443 await api.post(
3444 `/admin/orders/${bottleOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/cancel`,
3445 {},
3446 adminHeaders
3447 )
3448
3449 reservations = (
3450 await api.get(
3451 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3452 adminHeaders
3453 )
3454 ).data.reservations
3455
3456 // reservations are restored to the initial quantities
3457 expect(reservations).toEqual(
3458 expect.arrayContaining([
3459 expect.objectContaining({
3460 line_item_id: onePackItemId,
3461 inventory_item_id: inventoryItemBottle.id,
3462 quantity: 2,
3463 }),
3464 expect.objectContaining({
3465 line_item_id: twoPackItemId,
3466 inventory_item_id: inventoryItemBottle.id,
3467 quantity: 4,
3468 }),
3469 expect.objectContaining({
3470 line_item_id: threePackItemId,
3471 inventory_item_id: inventoryItemBottle.id,
3472 quantity: 6,
3473 }),
3474 ])
3475 )
3476
3477 expect(reservations[0].inventory_item).toEqual(
3478 expect.objectContaining({
3479 id: inventoryItemBottle.id,
3480 reserved_quantity: 12, // 2 * (onepack + twopack + threepack)
3481 stocked_quantity: 100,
3482 })
3483 )
3484
3485 // create a partial fulfillment only for the entier "Two Pack" item
3486 const fulOrder2 = (
3487 await api.post(
3488 `/admin/orders/${bottleOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3489 {
3490 items: [
3491 {
3492 id: bottleOrder.items.find((i) => i.subtitle === "Two Pack")!
3493 .id,
3494 quantity: 2,
3495 },
3496 ],
3497 },
3498 adminHeaders
3499 )
3500 ).data.order
3501
3502 expect(
3503 fulOrder2.items.find((i) => i.id === twoPackItemId)!.detail
3504 .fulfilled_quantity
3505 ).toEqual(2)
3506
3507 expect(
3508 fulOrder2.items.find((i) => i.id === threePackItemId)!.detail
3509 .fulfilled_quantity
3510 ).toEqual(0)
3511
3512 reservations = (
3513 await api.get(
3514 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3515 adminHeaders
3516 )
3517 ).data.reservations
3518
3519 expect(reservations.length).toEqual(2)
3520 expect(reservations).toEqual(
3521 expect.arrayContaining([
3522 expect.objectContaining({
3523 line_item_id: onePackItemId,
3524 inventory_item_id: inventoryItemBottle.id,
3525 quantity: 2,
3526 }),
3527
3528 // Two pack was fully fulfilled
3529
3530 expect.objectContaining({
3531 line_item_id: threePackItemId,
3532 inventory_item_id: inventoryItemBottle.id,
3533 quantity: 6,
3534 }),
3535 ])
3536 )
3537
3538 expect(reservations[0].inventory_item).toEqual(
3539 expect.objectContaining({
3540 id: inventoryItemBottle.id,
3541 reserved_quantity: 8,
3542 stocked_quantity: 96,
3543 })
3544 )
3545
3546 const latestFulfillment = fulOrder2.fulfillments.find(
3547 (f) => !f.canceled_at
3548 )!
3549
3550 // cancel the second partial fulfillment of the "Two Pack" item
3551 await api.post(
3552 `/admin/orders/${bottleOrder.id}/fulfillments/${latestFulfillment.id}/cancel`,
3553 {},
3554 adminHeaders
3555 )
3556
3557 reservations = (
3558 await api.get(
3559 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3560 adminHeaders
3561 )
3562 ).data.reservations
3563
3564 // reservations are restored to the initial quantities
3565 expect(reservations).toEqual(
3566 expect.arrayContaining([
3567 expect.objectContaining({
3568 line_item_id: onePackItemId,
3569 inventory_item_id: inventoryItemBottle.id,
3570 quantity: 2,
3571 }),
3572 expect.objectContaining({
3573 line_item_id: twoPackItemId,
3574 inventory_item_id: inventoryItemBottle.id,
3575 quantity: 4,
3576 }),
3577 expect.objectContaining({
3578 line_item_id: threePackItemId,
3579 inventory_item_id: inventoryItemBottle.id,
3580 quantity: 6,
3581 }),
3582 ])
3583 )
3584
3585 expect(reservations[0].inventory_item).toEqual(
3586 expect.objectContaining({
3587 id: inventoryItemBottle.id,
3588 reserved_quantity: 12, // 2 * (onepack + twopack + threepack)
3589 stocked_quantity: 100,
3590 })
3591 )
3592
3593 // finally create a full fulfillment for the entire order
3594 const fulOrder3 = (
3595 await api.post(
3596 `/admin/orders/${bottleOrder.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3597 {
3598 items: [
3599 {
3600 id: onePackItemId,
3601 quantity: 2,
3602 },
3603 {
3604 id: twoPackItemId,
3605 quantity: 2,
3606 },
3607 {
3608 id: threePackItemId,
3609 quantity: 2,
3610 },
3611 ],
3612 },
3613 adminHeaders
3614 )
3615 ).data.order
3616
3617 reservations = (
3618 await api.get(
3619 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3620 adminHeaders
3621 )
3622 ).data.reservations
3623
3624 expect(reservations.length).toEqual(0)
3625
3626 expect(fulOrder3.items).toEqual(
3627 expect.arrayContaining([
3628 expect.objectContaining({
3629 id: onePackItemId,
3630 detail: expect.objectContaining({
3631 fulfilled_quantity: 2,
3632 }),
3633 }),
3634 expect.objectContaining({
3635 id: twoPackItemId,
3636 detail: expect.objectContaining({
3637 fulfilled_quantity: 2,
3638 }),
3639 }),
3640 expect.objectContaining({
3641 id: threePackItemId,
3642 detail: expect.objectContaining({
3643 fulfilled_quantity: 2,
3644 }),
3645 }),
3646 ])
3647 )
3648
3649 // cancel the fulfillment for the entire order
3650 await api.post(
3651 `/admin/orders/${bottleOrder.id}/fulfillments/${
3652 fulOrder3.fulfillments.find((f) => !f.canceled_at)!.id
3653 }/cancel`,
3654 {},
3655 adminHeaders
3656 )
3657
3658 reservations = (
3659 await api.get(
3660 `/admin/reservations?line_item_id[]=${lineItemIds}`,
3661 adminHeaders
3662 )
3663 ).data.reservations
3664
3665 // reservations are restored to the initial quantities
3666 expect(reservations).toEqual(
3667 expect.arrayContaining([
3668 expect.objectContaining({
3669 line_item_id: onePackItemId,
3670 inventory_item_id: inventoryItemBottle.id,
3671 quantity: 2,
3672 }),
3673 expect.objectContaining({
3674 line_item_id: twoPackItemId,
3675 inventory_item_id: inventoryItemBottle.id,
3676 quantity: 4,
3677 }),
3678 expect.objectContaining({
3679 line_item_id: threePackItemId,
3680 inventory_item_id: inventoryItemBottle.id,
3681 quantity: 6,
3682 }),
3683 ])
3684 )
3685
3686 // inventory is back to the initial quantities
3687 expect(reservations[0].inventory_item).toEqual(
3688 expect.objectContaining({
3689 id: inventoryItemBottle.id,
3690 reserved_quantity: 12,
3691 stocked_quantity: 100,
3692 })
3693 )
3694
3695 const finalOrder = (
3696 await api.get(`/admin/orders/${bottleOrder.id}`, adminHeaders)
3697 ).data.order
3698
3699 expect(finalOrder.fulfillments.every((f) => f.canceled_at)).toEqual(
3700 true
3701 )
3702 expect(
3703 finalOrder.items.every((i) => i.detail.fulfilled_quantity === 0)
3704 ).toEqual(true)
3705 })
3706
3707 it("should throw an error if the quantity to fulfill exceeds the reserved quantity (inventory kit case)", async () => {
3708 let reservations = (await api.get(`/admin/reservations`, adminHeaders))
3709 .data.reservations
3710
3711 expect(reservations).toEqual(
3712 expect.arrayContaining([
3713 expect.objectContaining({
3714 inventory_item_id: inventoryItemDesk.id,
3715 quantity: 2,
3716 }),
3717 expect.objectContaining({
3718 inventory_item_id: inventoryItemLeg.id,
3719 quantity: 8,
3720 }),
3721 ])
3722 )
3723
3724 // 1. create a partial fulfillment
3725 const fulOrder = (
3726 await api.post(
3727 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3728 {
3729 items: [{ id: order.items[0].id, quantity: 1 }],
3730 },
3731 adminHeaders
3732 )
3733 ).data.order
3734
3735 // 2. two fulfillment items are created for a single (inventory kit) line item
3736 expect(fulOrder.fulfillments[0].items).toEqual(
3737 expect.arrayContaining([
3738 expect.objectContaining({
3739 inventory_item_id: inventoryItemDesk.id,
3740 quantity: 1,
3741 }),
3742 expect.objectContaining({
3743 inventory_item_id: inventoryItemLeg.id,
3744 quantity: 4,
3745 }),
3746 ])
3747 )
3748
3749 expect(fulOrder.items[0].detail.fulfilled_quantity).toEqual(1)
3750
3751 reservations = (await api.get(`/admin/reservations`, adminHeaders)).data
3752 .reservations
3753
3754 // 3. reservations need to be reduced by half since we fulfilled 1 item out of 2 in the order
3755 expect(reservations).toEqual(
3756 expect.arrayContaining([
3757 expect.objectContaining({
3758 inventory_item_id: inventoryItemDesk.id,
3759 quantity: 1,
3760 }),
3761 expect.objectContaining({
3762 inventory_item_id: inventoryItemLeg.id,
3763 quantity: 4,
3764 }),
3765 ])
3766 )
3767
3768 const res = await api
3769 .post(
3770 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
3771 {
3772 items: [{ id: order.items[0].id, quantity: 2 }],
3773 },
3774 adminHeaders
3775 )
3776 .catch((e) => e)
3777
3778 expect(res.response.status).toBe(400)
3779 expect(res.response.data).toEqual({
3780 type: "invalid_data",
3781 message: `Quantity to fulfill exceeds the reserved quantity for the item: ${order.items[0].id}`,
3782 })
3783 })
3784 })
3785
3786 describe("GET /orders/:id/shipping-options", () => {
3787 let so1: AdminShippingOption
3788 let so2: AdminShippingOption
3789 let so3: AdminShippingOption
3790
3791 beforeEach(async () => {
3792 seeder = await createOrderSeeder({ api, container: getContainer() })
3793 order = seeder.order
3794 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
3795 .order
3796
3797 so1 = (
3798 await createShippingOptionSeeder({
3799 api,
3800 container: getContainer(),
3801 salesChannelOverride: seeder.salesChannel,
3802 countries: ["us"],
3803 })
3804 ).shippingOption
3805
3806 so2 = (
3807 await createShippingOptionSeeder({
3808 api,
3809 container: getContainer(),
3810 salesChannelOverride: seeder.salesChannel,
3811 countries: ["us", "ca"],
3812 })
3813 ).shippingOption
3814
3815 so3 = (
3816 await createShippingOptionSeeder({
3817 api,
3818 container: getContainer(),
3819 salesChannelOverride: seeder.salesChannel,
3820 countries: ["de"],
3821 })
3822 ).shippingOption
3823 })
3824
3825 it("should return the shipping options applicable for the order", async () => {
3826 const { data } = await api.get(
3827 `/admin/orders/${order.id}/shipping-options`,
3828 adminHeaders
3829 )
3830
3831 const originalShippingOptionId =
3832 order.shipping_methods[0].shipping_option_id
3833
3834 expect(order.shipping_address.country_code).toEqual("us")
3835
3836 expect(data.shipping_options.length).toEqual(3)
3837 expect(data.shipping_options).toEqual(
3838 expect.arrayContaining([
3839 expect.objectContaining({
3840 id: so1.id,
3841 insufficient_inventory: true,
3842 }),
3843 expect.objectContaining({
3844 id: so2.id,
3845 insufficient_inventory: true, // new SO without location levels for the order item, should have insufficient inventory
3846 }),
3847 expect.objectContaining({
3848 id: originalShippingOptionId,
3849 insufficient_inventory: false, // order is created with this SO, location has to have enough inventory
3850 }),
3851 ])
3852 )
3853 })
3854 })
3855
3856 describe("POST /orders/:id/fulfillments/:id/mark-as-delivered", () => {
3857 beforeEach(async () => {
3858 seeder = await createOrderSeeder({ api, container: getContainer() })
3859 order = seeder.order
3860 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
3861 .order
3862 })
3863
3864 it("should mark fulfillable item as delivered", async () => {
3865 let fulfillableItem = order.items.find(
3866 (item) => item.detail.fulfilled_quantity < item.detail.quantity
3867 )
3868
3869 await api.post(
3870 `/admin/orders/${order.id}/fulfillments`,
3871 {
3872 location_id: seeder.stockLocation.id,
3873 items: [
3874 {
3875 id: fulfillableItem.id,
3876 quantity: 1,
3877 },
3878 ],
3879 },
3880 adminHeaders
3881 )
3882
3883 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
3884 .order
3885
3886 expect(order.items[0].detail).toEqual(
3887 expect.objectContaining({
3888 fulfilled_quantity: 1,
3889 delivered_quantity: 0,
3890 })
3891 )
3892
3893 await api.post(
3894 `/admin/orders/${order.id}/fulfillments/${order.fulfillments[0].id}/mark-as-delivered`,
3895 {},
3896 adminHeaders
3897 )
3898
3899 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
3900 .order
3901
3902 expect(order.items[0].detail).toEqual(
3903 expect.objectContaining({
3904 fulfilled_quantity: 1,
3905 delivered_quantity: 1,
3906 })
3907 )
3908
3909 const { response } = await api
3910 .post(
3911 `/admin/orders/${order.id}/fulfillments/${order.fulfillments[0].id}/mark-as-delivered`,
3912 {},
3913 adminHeaders
3914 )
3915 .catch((e) => e)
3916
3917 expect(response.data).toEqual({
3918 type: "not_allowed",
3919 message: "Fulfillment has already been marked delivered",
3920 })
3921 })
3922
3923 describe("with inventory kit items", () => {
3924 let inventoryItemDesk
3925 let inventoryItemLeg
3926
3927 beforeEach(async () => {
3928 const container = getContainer()
3929
3930 const publishableKey = await generatePublishableKey(container)
3931
3932 const storeHeaders = generateStoreHeaders({
3933 publishableKey,
3934 })
3935
3936 const region = (
3937 await api.post(
3938 "/admin/regions",
3939 {
3940 payment_providers: ["pp_system_default"],
3941 name: "Test region",
3942 currency_code: "usd",
3943 },
3944 adminHeaders
3945 )
3946 ).data.region
3947
3948 const salesChannel = (
3949 await api.post(
3950 "/admin/sales-channels",
3951 { name: "first channel", description: "channel" },
3952 adminHeaders
3953 )
3954 ).data.sales_channel
3955
3956 const stockLocation = (
3957 await api.post(
3958 `/admin/stock-locations`,
3959 { name: "test location" },
3960 adminHeaders
3961 )
3962 ).data.stock_location
3963
3964 inventoryItemDesk = (
3965 await api.post(
3966 `/admin/inventory-items`,
3967 { sku: "table-desk" },
3968 adminHeaders
3969 )
3970 ).data.inventory_item
3971
3972 inventoryItemLeg = (
3973 await api.post(
3974 `/admin/inventory-items`,
3975 { sku: "table-leg" },
3976 adminHeaders
3977 )
3978 ).data.inventory_item
3979
3980 await api.post(
3981 `/admin/inventory-items/${inventoryItemDesk.id}/location-levels`,
3982 {
3983 location_id: stockLocation.id,
3984 stocked_quantity: 10,
3985 },
3986 adminHeaders
3987 )
3988
3989 await api.post(
3990 `/admin/inventory-items/${inventoryItemLeg.id}/location-levels`,
3991 {
3992 location_id: stockLocation.id,
3993 stocked_quantity: 40,
3994 },
3995 adminHeaders
3996 )
3997
3998 await api.post(
3999 `/admin/stock-locations/${stockLocation.id}/sales-channels`,
4000 { add: [salesChannel.id] },
4001 adminHeaders
4002 )
4003
4004 const shippingProfile = (
4005 await api.post(
4006 `/admin/shipping-profiles`,
4007 { name: `test-${stockLocation.id}`, type: "default" },
4008 adminHeaders
4009 )
4010 ).data.shipping_profile
4011
4012 const product = (
4013 await api.post(
4014 "/admin/products",
4015 {
4016 title: `Wooden table`,
4017 status: ProductStatus.PUBLISHED,
4018 shipping_profile_id: shippingProfile.id,
4019 options: [{ title: "color", values: ["green"] }],
4020 variants: [
4021 {
4022 title: "Green table",
4023 sku: "green-table",
4024 inventory_items: [
4025 {
4026 inventory_item_id: inventoryItemDesk.id,
4027 required_quantity: 1,
4028 },
4029 {
4030 inventory_item_id: inventoryItemLeg.id,
4031 required_quantity: 4,
4032 },
4033 ],
4034 prices: [
4035 {
4036 currency_code: "usd",
4037 amount: 100,
4038 },
4039 ],
4040 options: {
4041 color: "green",
4042 },
4043 },
4044 ],
4045 },
4046 adminHeaders
4047 )
4048 ).data.product
4049
4050 const fulfillmentSets = (
4051 await api.post(
4052 `/admin/stock-locations/${stockLocation.id}/fulfillment-sets?fields=*fulfillment_sets`,
4053 {
4054 name: `Test-${shippingProfile.id}`,
4055 type: "test-type",
4056 },
4057 adminHeaders
4058 )
4059 ).data.stock_location.fulfillment_sets
4060
4061 const fulfillmentSet = (
4062 await api.post(
4063 `/admin/fulfillment-sets/${fulfillmentSets[0].id}/service-zones`,
4064 {
4065 name: `Test-${shippingProfile.id}`,
4066 geo_zones: [{ type: "country", country_code: "us" }],
4067 },
4068 adminHeaders
4069 )
4070 ).data.fulfillment_set
4071
4072 await api.post(
4073 `/admin/stock-locations/${stockLocation.id}/fulfillment-providers`,
4074 { add: ["manual_test-provider"] },
4075 adminHeaders
4076 )
4077
4078 const shippingOption = (
4079 await api.post(
4080 `/admin/shipping-options`,
4081 {
4082 name: `Test shipping option ${fulfillmentSet.id}`,
4083 service_zone_id: fulfillmentSet.service_zones[0].id,
4084 shipping_profile_id: shippingProfile.id,
4085 provider_id: "manual_test-provider",
4086 price_type: "flat",
4087 type: {
4088 label: "Test type",
4089 description: "Test description",
4090 code: "test-code",
4091 },
4092 prices: [{ currency_code: "usd", amount: 1000 }],
4093 rules: [],
4094 },
4095 adminHeaders
4096 )
4097 ).data.shipping_option
4098
4099 const cart = (
4100 await api.post(
4101 `/store/carts`,
4102 {
4103 currency_code: "usd",
4104 email: "tony@stark-industries.com",
4105 region_id: region.id,
4106 shipping_address: {
4107 address_1: "test address 1",
4108 address_2: "test address 2",
4109 city: "ny",
4110 country_code: "us",
4111 province: "ny",
4112 postal_code: "94016",
4113 },
4114 billing_address: {
4115 address_1: "test billing address 1",
4116 address_2: "test billing address 2",
4117 city: "ny",
4118 country_code: "us",
4119 province: "ny",
4120 postal_code: "94016",
4121 },
4122 sales_channel_id: salesChannel.id,
4123 items: [{ quantity: 2, variant_id: product.variants[0].id }],
4124 },
4125 storeHeaders
4126 )
4127 ).data.cart
4128
4129 await api.post(
4130 `/store/carts/${cart.id}/shipping-methods`,
4131 { option_id: shippingOption.id },
4132 storeHeaders
4133 )
4134
4135 const paymentCollection = (
4136 await api.post(
4137 `/store/payment-collections`,
4138 {
4139 cart_id: cart.id,
4140 },
4141 storeHeaders
4142 )
4143 ).data.payment_collection
4144
4145 await api.post(
4146 `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
4147 { provider_id: "pp_system_default" },
4148 storeHeaders
4149 )
4150
4151 order = (
4152 await api.post(`/store/carts/${cart.id}/complete`, {}, storeHeaders)
4153 ).data.order
4154 })
4155
4156 it("set correct quantity as delivered on the line item when marking fulfillment as delivered", async () => {
4157 let reservations = (
4158 await api.get(`/admin/reservations`, adminHeaders)
4159 ).data.reservations
4160
4161 expect(reservations).toEqual(
4162 expect.arrayContaining([
4163 expect.objectContaining({
4164 inventory_item_id: inventoryItemDesk.id,
4165 quantity: 2,
4166 }),
4167 expect.objectContaining({
4168 inventory_item_id: inventoryItemLeg.id,
4169 quantity: 8,
4170 }),
4171 ])
4172 )
4173
4174 // 1. create a partial fulfillment
4175 const fulOrder = (
4176 await api.post(
4177 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
4178 {
4179 items: [{ id: order.items[0].id, quantity: 1 }],
4180 },
4181 adminHeaders
4182 )
4183 ).data.order
4184
4185 // 2. two fulfillment items are created for a single (inventory kit) line item
4186 expect(fulOrder.fulfillments[0].items).toEqual(
4187 expect.arrayContaining([
4188 expect.objectContaining({
4189 inventory_item_id: inventoryItemDesk.id,
4190 quantity: 1,
4191 }),
4192 expect.objectContaining({
4193 inventory_item_id: inventoryItemLeg.id,
4194 quantity: 4,
4195 }),
4196 ])
4197 )
4198
4199 expect(fulOrder.items[0].detail.fulfilled_quantity).toEqual(1)
4200
4201 // 3. mark the fulfillment as shipped
4202 const shippedOrder = (
4203 await api.post(
4204 `/admin/orders/${fulOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/shipments`,
4205 {
4206 items: [
4207 {
4208 id: fulOrder.items[0].id,
4209 quantity: 1,
4210 },
4211 ],
4212 },
4213 adminHeaders
4214 )
4215 ).data.order
4216
4217 expect(shippedOrder.items[0].detail.fulfilled_quantity).toEqual(1)
4218 expect(shippedOrder.items[0].detail.shipped_quantity).toEqual(1)
4219
4220 // 4. mark the fulfillment as delivered
4221 const deliveredOrder = (
4222 await api.post(
4223 `/admin/orders/${fulOrder.id}/fulfillments/${fulOrder.fulfillments[0].id}/mark-as-delivered`,
4224 {},
4225 adminHeaders
4226 )
4227 ).data.order
4228
4229 // 5. 1 line item was fulfilled so 1 line item is delivered
4230 expect(deliveredOrder.items[0].detail.fulfilled_quantity).toEqual(1)
4231 expect(deliveredOrder.items[0].detail.shipped_quantity).toEqual(1)
4232 expect(deliveredOrder.items[0].detail.delivered_quantity).toEqual(1)
4233
4234 // 6. repeat the same steps for the rest of the line items
4235
4236 // 7. create a partial fulfillment
4237 const fulOrder2 = (
4238 await api.post(
4239 `/admin/orders/${order.id}/fulfillments?fields=*fulfillments,*fulfillments.items`,
4240 {
4241 items: [{ id: order.items[0].id, quantity: 1 }],
4242 },
4243 adminHeaders
4244 )
4245 ).data.order
4246
4247 expect(fulOrder2.items[0].detail.fulfilled_quantity).toEqual(2)
4248
4249 const secondFulfillment = fulOrder2.fulfillments.find(
4250 (f) => !f.shipped_at
4251 )!
4252
4253 // 8. mark the fulfillment as shipped
4254 const shippedOrder2 = (
4255 await api.post(
4256 `/admin/orders/${fulOrder2.id}/fulfillments/${secondFulfillment.id}/shipments`,
4257 {
4258 items: [
4259 {
4260 id: fulOrder2.items[0].id,
4261 quantity: 1,
4262 },
4263 ],
4264 },
4265 adminHeaders
4266 )
4267 ).data.order
4268
4269 expect(shippedOrder2.items[0].detail.fulfilled_quantity).toEqual(2)
4270 expect(shippedOrder2.items[0].detail.shipped_quantity).toEqual(2)
4271 expect(shippedOrder2.items[0].detail.delivered_quantity).toEqual(1)
4272
4273 // 9. mark the fulfillment as delivered
4274 const deliveredOrder2 = (
4275 await api.post(
4276 `/admin/orders/${fulOrder2.id}/fulfillments/${secondFulfillment.id}/mark-as-delivered`,
4277 {},
4278 adminHeaders
4279 )
4280 ).data.order
4281
4282 // 10. both items are fulfilled, shipped and delivered
4283 expect(deliveredOrder2.items[0].detail.fulfilled_quantity).toEqual(2)
4284 expect(deliveredOrder2.items[0].detail.shipped_quantity).toEqual(2)
4285 expect(deliveredOrder2.items[0].detail.delivered_quantity).toEqual(2)
4286 })
4287 })
4288 })
4289
4290 describe("POST /orders/:id/credit-lines", () => {
4291 let storeHeaders
4292
4293 beforeEach(async () => {
4294 const publishableKey = await generatePublishableKey(container)
4295
4296 storeHeaders = generateStoreHeaders({
4297 publishableKey,
4298 })
4299
4300 const inventoryItemOverride = (
4301 await api.post(
4302 `/admin/inventory-items`,
4303 { sku: "test-variant", requires_shipping: false },
4304 adminHeaders
4305 )
4306 ).data.inventory_item
4307
4308 seeder = await createOrderSeeder({
4309 api,
4310 container: getContainer(),
4311 inventoryItemOverride,
4312 withoutShipping: true,
4313 })
4314 order = seeder.order
4315
4316 order = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
4317 .order
4318 })
4319
4320 it("should successfully create credit lines", async () => {
4321 const error = await api
4322 .post(
4323 `/admin/orders/${order.id}/credit-lines`,
4324 {
4325 amount: -106,
4326 reference: "order",
4327 reference_id: order.id,
4328 },
4329 adminHeaders
4330 )
4331 .catch((e) => e)
4332
4333 expect(error.response.status).toBe(400)
4334 expect(error.response.data.message).toBe(
4335 "Can only create positive credit lines if the order has a positive pending difference"
4336 )
4337
4338 const error2 = await api
4339 .post(
4340 `/admin/orders/${order.id}/credit-lines`,
4341 {
4342 amount: 10000,
4343 reference: "order",
4344 reference_id: order.id,
4345 },
4346 adminHeaders
4347 )
4348 .catch((e) => e)
4349
4350 expect(error2.response.status).toBe(400)
4351 expect(error2.response.data.message).toBe(
4352 "Cannot create more positive credit lines with amount more than the pending difference"
4353 )
4354
4355 const response = await api.post(
4356 `/admin/orders/${order.id}/credit-lines`,
4357 {
4358 amount: 106,
4359 reference: "order",
4360 reference_id: order.id,
4361 },
4362 adminHeaders
4363 )
4364
4365 expect(response.status).toBe(200)
4366 expect(response.data.order).toEqual(
4367 expect.objectContaining({
4368 id: order.id,
4369 total: 0,
4370 subtotal: 100,
4371 summary: expect.objectContaining({
4372 current_order_total: 0,
4373 accounting_total: 0,
4374 pending_difference: 0,
4375 }),
4376 })
4377 )
4378
4379 await api.post(
4380 "/admin/order-edits",
4381 {
4382 order_id: order.id,
4383 description: "Test",
4384 },
4385 adminHeaders
4386 )
4387
4388 const item = order.items[0]
4389
4390 let result = (
4391 await api.post(
4392 `/admin/order-edits/${order.id}/items/item/${item.id}`,
4393 { quantity: 0 },
4394 adminHeaders
4395 )
4396 ).data.order_preview
4397
4398 result = (
4399 await api.post(
4400 `/admin/order-edits/${order.id}/request`,
4401 {},
4402 adminHeaders
4403 )
4404 ).data.order_preview
4405
4406 result = (
4407 await api.post(
4408 `/admin/order-edits/${order.id}/confirm`,
4409 {},
4410 adminHeaders
4411 )
4412 ).data.order_preview
4413
4414 result = (await api.get(`/admin/orders/${order.id}`, adminHeaders)).data
4415 .order
4416
4417 const errorResponse = await api
4418 .post(
4419 `/admin/orders/${order.id}/credit-lines`,
4420 {
4421 amount: 106,
4422 reference: "order",
4423 reference_id: order.id,
4424 },
4425 adminHeaders
4426 )
4427 .catch((e) => e)
4428
4429 expect(errorResponse.response.status).toBe(400)
4430 expect(errorResponse.response.data.message).toBe(
4431 "Can only create negative credit lines if the order has a negative pending difference"
4432 )
4433
4434 const error3 = await api
4435 .post(
4436 `/admin/orders/${order.id}/credit-lines`,
4437 {
4438 amount: -10000,
4439 reference: "order",
4440 reference_id: order.id,
4441 },
4442 adminHeaders
4443 )
4444 .catch((e) => e)
4445
4446 expect(error3.response.status).toBe(400)
4447 expect(error3.response.data.message).toBe(
4448 "Cannot create more negative credit lines with amount more than the pending difference"
4449 )
4450
4451 const error4 = await api
4452 .post(
4453 `/admin/orders/${order.id}/credit-lines`,
4454 {
4455 amount: -106,
4456 reference: "order",
4457 reference_id: order.id,
4458 },
4459 adminHeaders
4460 )
4461 .catch((e) => e)
4462
4463 expect(error4.response.status).toBe(400)
4464 expect(error4.response.data.message).toBe(
4465 "Store credit refunds can only be issued to registered customers"
4466 )
4467
4468 const registeredCustomerToken = (
4469 await api.post("/auth/customer/emailpass/register", {
4470 email: "registered@medusajs.com",
4471 password: "password",
4472 })
4473 ).data.token
4474
4475 const customer = (
4476 await api.post(
4477 "/store/customers",
4478 { email: "registered@medusajs.com" },
4479 {
4480 headers: {
4481 ...storeHeaders.headers,
4482 Authorization: `Bearer ${registeredCustomerToken}`,
4483 },
4484 }
4485 )
4486 ).data.customer
4487
4488 await api.post(
4489 `/admin/orders/${order.id}/transfer`,
4490 { customer_id: customer.id },
4491 adminHeaders
4492 )
4493
4494 const orderChanges = (
4495 await api.get(`/admin/orders/${order.id}/changes`, adminHeaders)
4496 ).data.order_changes
4497
4498 await api.post(
4499 `/store/orders/${order.id}/transfer/accept`,
4500 {
4501 token:
4502 orderChanges[orderChanges.length - 1].actions[0].details.token,
4503 },
4504 storeHeaders
4505 )
4506
4507 const response2 = await api.post(
4508 `/admin/orders/${order.id}/credit-lines`,
4509 {
4510 amount: -106,
4511 reference: "order",
4512 reference_id: order.id,
4513 },
4514 adminHeaders
4515 )
4516
4517 expect(response2.data.order.summary.pending_difference).toEqual(0)
4518
4519 const response3 = await api
4520 .post(
4521 `/admin/orders/${order.id}/credit-lines`,
4522 {
4523 amount: -106,
4524 reference: "order",
4525 reference_id: order.id,
4526 },
4527 adminHeaders
4528 )
4529 .catch((e) => e)
4530
4531 expect(response3.response.status).toBe(400)
4532 expect(response3.response.data.message).toBe(
4533 "Can only create credit lines if the order has a positive or negative pending difference"
4534 )
4535 })
4536 })
4537
4538 describe("workflows", () => {
4539 it("updateOrderChangeActionsWorkflow - should not call listOrderChangeActions when orderChangeActions is empty", async () => {
4540 const orderService = container.resolve(Modules.ORDER)
4541 const listOrderChangeActionsSpy = jest.spyOn(
4542 orderService,
4543 "listOrderChangeActions"
4544 )
4545
4546 const { result } = await updateOrderChangeActionsWorkflow(
4547 container
4548 ).run({
4549 input: [],
4550 })
4551
4552 expect(result).toEqual([])
4553
4554 expect(listOrderChangeActionsSpy).not.toHaveBeenCalled()
4555 listOrderChangeActionsSpy.mockRestore()
4556 })
4557
4558 it("updateOrderChangesWorkflow - should not call listOrderChanges when orderChanges is empty", async () => {
4559 const orderService = container.resolve(Modules.ORDER)
4560 const listOrderChangesSpy = jest.spyOn(orderService, "listOrderChanges")
4561
4562 const { result } = await updateOrderChangesWorkflow(container).run({
4563 input: [],
4564 })
4565
4566 expect(result).toEqual([])
4567
4568 expect(listOrderChangesSpy).not.toHaveBeenCalled()
4569 listOrderChangesSpy.mockRestore()
4570 })
4571
4572 it("updateOrderShippingMethodsStep - should not call listOrderShippingMethods when shipping methods is empty", async () => {
4573 const orderService = container.resolve(Modules.ORDER)
4574 const listOrderShippingMethodsSpy = jest.spyOn(
4575 orderService,
4576 "listOrderShippingMethods"
4577 )
4578
4579 const workflow = createWorkflow("test-workflow", () => {
4580 return new WorkflowResponse(updateOrderShippingMethodsStep([]))
4581 })
4582
4583 const { result } = await workflow(container).run()
4584
4585 expect(result).toEqual([])
4586
4587 expect(listOrderShippingMethodsSpy).not.toHaveBeenCalled()
4588 listOrderShippingMethodsSpy.mockRestore()
4589 })
4590 })
4591 },
4592 })