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.DELIVER_ITEM, {
10 operation({ action, currentOrder, options }) {
11 const item = currentOrder.items.find(
12 (item) => item.id === action.details.reference_id
13 )!
14
15 item.detail.delivered_quantity ??= 0
16
17 item.detail.delivered_quantity = MathBN.add(
18 item.detail.delivered_quantity,
19 action.details.quantity
20 )
21
22 setActionReference(item, action, options)
23 },
24 validate({ action, currentOrder }) {
25 const refId = action.details?.reference_id
26
27 if (refId == null) {
28 throw new MedusaError(
29 MedusaError.Types.INVALID_DATA,
30 "Reference ID is required."
31 )
32 }
33
34 const item = currentOrder.items.find((item) => item.id === refId)
35
36 if (!item) {
37 throw new MedusaError(
38 MedusaError.Types.INVALID_DATA,
39 `Item ID "${refId}" not found.`
40 )
41 }
42
43 const totalDeliverable = MathBN.convert(item.quantity)
44 const totalDelivered = MathBN.convert(item.detail?.delivered_quantity)
45 const newDelivered = MathBN.convert(action.details?.quantity ?? 0)
46 const newTotalDelivered = MathBN.sum(totalDelivered, newDelivered)
47
48 const totalFulfilled = MathBN.convert(item.detail?.fulfilled_quantity)
49
50 if (MathBN.lte(newDelivered, 0)) {
51 throw new MedusaError(
52 MedusaError.Types.INVALID_DATA,
53 `Quantity of item ${refId} must be greater than 0.`
54 )
55 }
56
57 if (MathBN.gt(newTotalDelivered, totalFulfilled)) {
58 throw new MedusaError(
59 MedusaError.Types.INVALID_DATA,
60 `Cannot deliver more items than what was fulfilled for item ${refId}.`
61 )
62 }
63
64 if (MathBN.gt(newTotalDelivered, totalDeliverable)) {
65 throw new MedusaError(
66 MedusaError.Types.INVALID_DATA,
67 `Cannot deliver more items than what was ordered for item ${refId}.`
68 )
69 }
70 },
71 })