1 import {
2 CreateOrderLineItemAdjustmentDTO,
3 CreateOrderShippingMethodAdjustmentDTO,
4 InferEntityType,
5 OrderChangeActionDTO,
6 OrderDTO,
7 } from "@medusajs/framework/types"
8 import {
9 ChangeActionType,
10 createRawPropertiesFromBigNumber,
11 decorateCartTotals,
12 isDefined,
13 MathBN,
14 } from "@medusajs/framework/utils"
15 import { OrderCreditLine, OrderItem, OrderShippingMethod } from "@models"
16 import { calculateOrderChange } from "./calculate-order-change"
17
18 export interface ApplyOrderChangeDTO extends OrderChangeActionDTO {
19 id: string
20 order_id: string
21 version: number
22 applied: boolean
23 }
24
25 export async function applyChangesToOrder(
26 orders: any[],
27 actionsMap: Record<string, any[]>,
28 options?: {
29 addActionReferenceToObject?: boolean
30 includeTaxLinesAndAdjustmentsToPreview?: (...args) => void
31 }
32 ) {
33 const itemsToUpsert: InferEntityType<typeof OrderItem>[] = []
34 const creditLinesToUpsert: InferEntityType<typeof OrderCreditLine>[] = []
35 const shippingMethodsToUpsert: InferEntityType<typeof OrderShippingMethod>[] =
36 []
37 const lineItemAdjustmentsToCreate: CreateOrderLineItemAdjustmentDTO[] = []
38 const shippingMethodAdjustmentsToCreate: CreateOrderShippingMethodAdjustmentDTO[] =
39 []
40 const summariesToUpsert: any[] = []
41 const orderToUpdate: any[] = []
42
43 const orderEditableAttributes = [
44 "customer_id",
45 "sales_channel_id",
46 "email",
47 "no_notification",
48 ]
49
50 const calculatedOrders = {}
51 for (const order of orders) {
52 const calculated = calculateOrderChange({
53 order: order as any,
54 actions: actionsMap[order.id],
55 transactions: order.transactions ?? [],
56 options,
57 })
58
59 createRawPropertiesFromBigNumber(calculated)
60
61 const version = actionsMap[order.id]?.[0]?.version ?? order.version
62 const orderAttributes: {
63 version?: number
64 customer_id?: string
65 email?: string
66 } = {}
67
68 // Editable attributes that have changed
69 for (const attr of orderEditableAttributes) {
70 if (order[attr] !== calculated.order[attr]) {
71 orderAttributes[attr] = calculated.order[attr]
72 }
73 }
74
75 for (const item of calculated.order.items) {
76 if (MathBN.lte(item.quantity, 0)) {
77 continue
78 }
79
80 const isExistingItem = item.id === item.detail?.item_id
81 const orderItem = isExistingItem ? (item.detail as any) : item
82 const itemId = isExistingItem ? orderItem.item_id : item.id
83
84 const itemToUpsert = {
85 id: orderItem.version === version ? orderItem.id : undefined,
86 item_id: itemId,
87 order_id: order.id,
88 version,
89 quantity: orderItem.quantity,
90 unit_price: item.unit_price ?? orderItem.unit_price,
91 compare_at_unit_price:
92 item.compare_at_unit_price ?? orderItem.compare_at_unit_price,
93 fulfilled_quantity: orderItem.fulfilled_quantity ?? 0,
94 delivered_quantity: orderItem.delivered_quantity ?? 0,
95 shipped_quantity: orderItem.shipped_quantity ?? 0,
96 return_requested_quantity: orderItem.return_requested_quantity ?? 0,
97 return_received_quantity: orderItem.return_received_quantity ?? 0,
98 return_dismissed_quantity: orderItem.return_dismissed_quantity ?? 0,
99 written_off_quantity: orderItem.written_off_quantity ?? 0,
100 metadata: orderItem.metadata,
101 } as any
102
103 if (version > order.version) {
104 item.adjustments?.forEach((adjustment) => {
105 lineItemAdjustmentsToCreate.push({
106 item_id: itemId,
107 version,
108 amount: adjustment.amount,
109 description: adjustment.description,
110 promotion_id: adjustment.promotion_id,
111 code: adjustment.code,
112 is_tax_inclusive: adjustment.is_tax_inclusive,
113 })
114 })
115 }
116
117 itemsToUpsert.push(itemToUpsert)
118 }
119
120 if (version > order.version) {
121 // Handle credit line versioning
122 for (const creditLine of calculated.order.credit_lines ?? []) {
123 const creditLine_ = creditLine as any
124 if (!creditLine_) {
125 continue
126 }
127
128 const isExisting = isDefined(creditLine_.id)
129
130 const upsertCreditLine = {
131 id: creditLine_.version === version ? creditLine_.id : undefined,
132 order_id: order.id,
133 version,
134 reference: creditLine_.reference,
135 reference_id: creditLine_.reference_id,
136 amount: creditLine_.amount,
137 raw_amount: creditLine_.raw_amount,
138 metadata: isExisting
139 ? creditLine_.metadata
140 : { ...(creditLine_.metadata ?? {}), created_in_version: version },
141 } as any
142
143 creditLinesToUpsert.push(upsertCreditLine)
144 }
145
146 // Handle shipping method versioning
147 for (const shippingMethod of calculated.order.shipping_methods ?? []) {
148 const shippingMethod_ = shippingMethod as any
149 const isNewShippingMethod = !isDefined(shippingMethod_?.detail)
150 if (!shippingMethod_) {
151 continue
152 }
153
154 let associatedMethodId
155 let hasShippingMethod = false
156 if (isNewShippingMethod) {
157 associatedMethodId = shippingMethod_.actions?.find((sm) => {
158 return (
159 sm.action === ChangeActionType.SHIPPING_ADD && sm.reference_id
160 )
161 })
162 hasShippingMethod = !!associatedMethodId
163 } else {
164 associatedMethodId = shippingMethod_?.detail?.shipping_method_id
165 }
166
167 const sm = {
168 ...(isNewShippingMethod ? shippingMethod_ : shippingMethod_.detail),
169 version,
170 shipping_method_id: associatedMethodId,
171 } as any
172
173 delete sm.id
174
175 if (!hasShippingMethod) {
176 shippingMethodsToUpsert.push(sm)
177 }
178
179 shippingMethod_.adjustments?.forEach((adjustment) => {
180 shippingMethodAdjustmentsToCreate.push({
181 shipping_method_id: associatedMethodId,
182 version,
183 amount: adjustment.amount,
184 description: adjustment.description,
185 promotion_id: adjustment.promotion_id,
186 code: adjustment.code,
187 })
188 })
189 }
190
191 orderAttributes.version = version
192 }
193
194 // Including tax lines and adjustments for added items and shipping methods
195 if (options?.includeTaxLinesAndAdjustmentsToPreview) {
196 await options?.includeTaxLinesAndAdjustmentsToPreview(
197 calculated.order,
198 itemsToUpsert,
199 shippingMethodsToUpsert,
200 lineItemAdjustmentsToCreate,
201 shippingMethodAdjustmentsToCreate
202 )
203 decorateCartTotals(calculated.order)
204 }
205
206 const orderSummary = order.summary
207 const upsertSummary = {
208 id: orderSummary?.version === version ? orderSummary.id : undefined,
209 order_id: order.id,
210 version,
211 totals: calculated.getSummaryFromOrder(
212 calculated.order as unknown as OrderDTO
213 ),
214 }
215
216 createRawPropertiesFromBigNumber(upsertSummary)
217 summariesToUpsert.push(upsertSummary)
218
219 if (Object.keys(orderAttributes).length > 0) {
220 orderToUpdate.push({
221 selector: {
222 id: order.id,
223 },
224 data: {
225 ...orderAttributes,
226 },
227 })
228 }
229
230 calculatedOrders[order.id] = calculated
231 }
232
233 return {
234 lineItemAdjustmentsToCreate,
235 shippingMethodAdjustmentsToCreate,
236 itemsToUpsert,
237 creditLinesToUpsert,
238 shippingMethodsToUpsert,
239 summariesToUpsert,
240 orderToUpdate,
241 calculatedOrders,
242 }
243 }