|
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.REINSTATE_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.written_off_quantity ??= 0 |
|
16
|
existing.detail.written_off_quantity = MathBN.sub( |
|
17
|
existing.detail.written_off_quantity, |
|
18
|
action.details.quantity |
|
19
|
) |
|
20
|
|
|
21
|
setActionReference(existing, action, options) |
|
22
|
}, |
|
23
|
validate({ action, currentOrder }) { |
|
24
|
const refId = action.details?.reference_id |
|
25
|
if (refId == null) { |
|
26
|
throw new MedusaError( |
|
27
|
MedusaError.Types.INVALID_DATA, |
|
28
|
"Details reference ID is required." |
|
29
|
) |
|
30
|
} |
|
31
|
|
|
32
|
const existing = currentOrder.items.find((item) => item.id === refId) |
|
33
|
|
|
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 reinstate item ${refId} is required.` |
|
45
|
) |
|
46
|
} |
|
47
|
|
|
48
|
const quantityAvailable = existing!.quantity ?? 0 |
|
49
|
const greater = MathBN.gt(action.details?.quantity, quantityAvailable) |
|
50
|
if (greater) { |
|
51
|
throw new MedusaError( |
|
52
|
MedusaError.Types.INVALID_DATA, |
|
53
|
"Cannot unclaim more items than what was ordered." |
|
54
|
) |
|
55
|
} |
|
56
|
}, |
|
57
|
}) |