1 import {
2 ChangeActionType,
3 isDefined,
4 MathBN,
5 MedusaError,
6 mergeMetadata,
7 } from "@medusajs/framework/utils"
8 import { VirtualOrder } from "@types"
9 import { OrderChangeProcessing } from "../calculate-order-change"
10 import { setActionReference } from "../set-action-reference"
11
12 OrderChangeProcessing.registerActionType(ChangeActionType.ITEM_ADD, {
13 operation({ action, currentOrder, options }) {
14 let existing = currentOrder.items.find(
15 (item) => item.id === action.details.reference_id
16 )
17
18 if (existing) {
19 existing.detail.quantity ??= 0
20
21 existing.quantity = MathBN.add(existing.quantity, action.details.quantity)
22
23 existing.detail.quantity = MathBN.add(
24 existing.detail.quantity,
25 action.details.quantity
26 )
27
28 if (isDefined(action.details.metadata)) {
29 const isUnset = action.details.metadata === null
30
31 if (isUnset) {
32 existing.metadata = null
33 } else {
34 existing.metadata = mergeMetadata(
35 existing.metadata ?? {},
36 action.details.metadata
37 )
38 }
39 }
40 } else {
41 existing = {
42 id: action.details.reference_id!,
43 order_id: currentOrder.id,
44 return_id: action.return_id,
45 claim_id: action.claim_id,
46 exchange_id: action.exchange_id,
47 unit_price: action.details.unit_price,
48 compare_at_unit_price: action.details.compare_at_unit_price,
49 quantity: action.details.quantity,
50 ...(action.details.metadata !== undefined
51 ? { metadata: action.details.metadata }
52 : {}),
53 } as VirtualOrder["items"][0]
54
55 currentOrder.items.push(existing)
56 }
57
58 setActionReference(existing, action, options)
59
60 return MathBN.mult(action.details.unit_price, action.details.quantity)
61 },
62 validate({ action }) {
63 const refId = action.details?.reference_id
64
65 if (action.amount == null && action.details?.unit_price == null) {
66 throw new MedusaError(
67 MedusaError.Types.INVALID_DATA,
68 `Unit price of item ${refId} is required if no action.amount is provided.`
69 )
70 }
71
72 if (!action.details?.quantity) {
73 throw new MedusaError(
74 MedusaError.Types.INVALID_DATA,
75 `Quantity of item ${refId} is required.`
76 )
77 }
78
79 if (MathBN.lt(action.details?.quantity, 1)) {
80 throw new MedusaError(
81 MedusaError.Types.INVALID_DATA,
82 `Quantity of item ${refId} must be greater than 0.`
83 )
84 }
85 },
86 })