1 import {
2 ChangeActionType,
3 MathBN,
4 MedusaError,
5 } from "@medusajs/framework/utils"
6 import { OrderChangeProcessing } from "../calculate-order-change"
7 import { setActionReference } from "../set-action-reference"
8
9 OrderChangeProcessing.registerActionType(ChangeActionType.SHIP_ITEM, {
10 operation({ action, currentOrder, options }) {
11 const existing = currentOrder.items.find(
12 (item) => item.id === action.details.reference_id
13 )!
14
15 existing.detail.shipped_quantity ??= 0
16
17 existing.detail.shipped_quantity = MathBN.add(
18 existing.detail.shipped_quantity,
19 action.details.quantity
20 )
21
22 setActionReference(existing, action, options)
23 },
24 validate({ action, currentOrder }) {
25 const refId = action.details?.reference_id
26 if (refId == null) {
27 throw new MedusaError(
28 MedusaError.Types.INVALID_DATA,
29 "Reference ID is required."
30 )
31 }
32
33 const existing = currentOrder.items.find((item) => item.id === refId)
34 if (!existing) {
35 throw new MedusaError(
36 MedusaError.Types.INVALID_DATA,
37 `Item ID "${refId}" not found.`
38 )
39 }
40
41 if (!action.details?.quantity) {
42 throw new MedusaError(
43 MedusaError.Types.INVALID_DATA,
44 `Quantity to ship of item ${refId} is required.`
45 )
46 }
47
48 if (MathBN.lt(action.details?.quantity, 1)) {
49 throw new MedusaError(
50 MedusaError.Types.INVALID_DATA,
51 `Quantity of item ${refId} must be greater than 0.`
52 )
53 }
54
55 const notShipped = MathBN.sub(
56 existing.detail?.fulfilled_quantity,
57 existing.detail?.shipped_quantity
58 )
59
60 const greater = MathBN.gt(action.details?.quantity, notShipped)
61 if (greater) {
62 throw new MedusaError(
63 MedusaError.Types.INVALID_DATA,
64 `Cannot ship more items than what was fulfilled for item ${refId}.`
65 )
66 }
67 },
68 })