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.FULFILL_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.fulfilled_quantity ??= 0
16
17 existing.detail.fulfilled_quantity = MathBN.add(
18 existing.detail.fulfilled_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 fulfill of item ${refId} is required.`
45 )
46 }
47
48 if (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 notFulfilled = MathBN.sub(
56 existing.quantity,
57 existing.detail?.fulfilled_quantity
58 )
59 const greater = MathBN.gt(action.details?.quantity, notFulfilled)
60 if (greater) {
61 throw new MedusaError(
62 MedusaError.Types.INVALID_DATA,
63 `Cannot fulfill more items than what was ordered for item ${refId}.`
64 )
65 }
66 },
67 })