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