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