1 import {
2 createRawPropertiesFromBigNumber,
3 decorateCartTotals,
4 deduplicate,
5 isDefined,
6 isObject,
7 toMikroORMEntity,
8 } from "@medusajs/framework/utils"
9
10 const ORDER_ITEM_FIELDS = ["quantity", "unit_price", "compare_at_unit_price"]
11
12 // Reshape the order object to match the OrderDTO
13 // This function is used to format the order object before returning to the main module methods
14 export function formatOrder<T = any>(
15 order,
16 options: {
17 entity: any
18 includeTotals?: boolean
19 }
20 ): T {
21 const isArray = Array.isArray(order)
22 const orders = [...(isArray ? order : [order])]
23
24 orders.map((order) => {
25 let mainOrder = order
26 const entity = options?.entity ? toMikroORMEntity(options.entity) : null
27
28 const isRelatedEntity = entity?.name !== "Order"
29
30 // If the entity is a related entity, the original order is located in the order property
31 if (isRelatedEntity) {
32 if (!order.order) {
33 return order
34 }
35
36 mainOrder = order.order
37 }
38
39 mainOrder.items = mainOrder.items?.map((orderItem) => {
40 const isFormatted = isDefined(orderItem.detail?.fulfilled_quantity)
41 if (isFormatted) {
42 return orderItem
43 }
44
45 const detail = { ...orderItem }
46 delete detail.order
47 delete detail.item
48
49 return {
50 ...orderItem.item,
51 quantity: detail.quantity,
52 raw_quantity: detail.raw_quantity,
53 unit_price: detail.unit_price ?? orderItem.item.unit_price,
54 raw_unit_price: detail.raw_unit_price ?? orderItem.item.raw_unit_price,
55 compare_at_unit_price:
56 detail.compare_at_unit_price ?? orderItem.item.compare_at_unit_price,
57 raw_compare_at_unit_price:
58 detail.raw_compare_at_unit_price ??
59 orderItem.item.raw_compare_at_unit_price,
60 metadata: detail.metadata ?? orderItem.item.metadata,
61 line_item_metadata: orderItem.item.metadata,
62 detail,
63 }
64 })
65
66 if (isRelatedEntity) {
67 if (order.return) {
68 formatOrderReturn(order.return, mainOrder)
69 }
70
71 const entityName = options.entity.name
72 if (entityName === "OrderClaim") {
73 formatClaim(order)
74 } else if (entityName === "OrderExchange") {
75 formatExchange(order)
76 } else if (entityName === "Return") {
77 formatReturn(order)
78 }
79 }
80
81 if (order.shipping_methods) {
82 order.shipping_methods = order.shipping_methods?.map((shippingMethod) => {
83 if (shippingMethod.detail) {
84 return shippingMethod
85 }
86
87 const sm = { ...shippingMethod.shipping_method }
88
89 delete shippingMethod.shipping_method
90 cleanNestedRelations(shippingMethod)
91
92 return {
93 ...sm,
94 order_id: shippingMethod.order_id,
95 detail: {
96 ...shippingMethod,
97 },
98 }
99 })
100 }
101
102 if (mainOrder.summary) {
103 mainOrder.summary = mainOrder.summary?.[0]?.totals
104 }
105
106 return createRawPropertiesFromBigNumber(
107 options?.includeTotals ? decorateCartTotals(order) : order
108 )
109 })
110
111 return isArray ? (orders as T) : orders[0]
112 }
113
114 function cleanNestedRelations(obj) {
115 if (!isObject(obj)) {
116 return
117 }
118
119 const obj_ = obj as any
120 delete obj_.order
121 delete obj_.return
122 delete obj_.claim
123 delete obj_.exchange
124 }
125
126 function formatOrderReturn(orderReturn, mainOrder) {
127 orderReturn.items?.forEach((orderItem) => {
128 const item = mainOrder.items?.find((item) => item.id === orderItem.item_id)
129
130 orderItem.detail = item?.detail
131 })
132 }
133
134 function formatClaim(claim) {
135 if (claim.additional_items) {
136 claim.additional_items = claim.additional_items.filter(
137 (item) => item.is_additional_item
138 )
139
140 claim.additional_items.forEach((orderItem) => {
141 const item = claim.order.items?.find(
142 (item) => item.id === orderItem.item_id
143 )
144 cleanNestedRelations(item)
145 orderItem.detail = item?.detail
146 })
147 }
148
149 if (!claim.claim_items) {
150 return
151 }
152
153 claim.claim_items = claim.claim_items.filter(
154 (item) => !item.is_additional_item
155 )
156 claim.claim_items.forEach((orderItem) => {
157 const item = claim.order.items?.find(
158 (item) => item.id === orderItem.item_id
159 )
160
161 cleanNestedRelations(item)
162 orderItem.detail = item?.detail
163 })
164 }
165
166 function formatExchange(exchange) {
167 if (!exchange.additional_items) {
168 return
169 }
170
171 exchange.additional_items.forEach((orderItem) => {
172 const item = exchange.order.items?.find(
173 (item) => item.id === orderItem.item_id
174 )
175
176 cleanNestedRelations(item)
177 orderItem.detail = item?.detail
178 })
179 }
180
181 function formatReturn(returnOrder) {
182 if (!returnOrder.items) {
183 return
184 }
185
186 returnOrder.items.forEach((orderItem) => {
187 const item = returnOrder.order.items?.find(
188 (item) => item.id === orderItem.item_id
189 )
190
191 cleanNestedRelations(item)
192 orderItem.detail = item?.detail
193 })
194 }
195
196 // Map the public order model to the repository model format
197 // As the public responses have a different shape than the repository responses, this function is used to map the public properties to the internal db entities
198 // e.g "items" is the relation between "line-item" and "order" + "version", The line item itself is in "items.item"
199 // This helper maps to the correct repository to query the DB, and the function "formatOrder" remap the response to the public shape
200 export function mapRepositoryToOrderModel(config, isRelatedEntity = false) {
201 if (isRelatedEntity) {
202 return mapRepositoryToRelatedEntity(config)
203 }
204
205 const conf = { ...config }
206
207 function replace(obj, type): string[] | undefined {
208 if (!isDefined(obj[type])) {
209 return
210 }
211
212 return deduplicate(
213 obj[type].sort().flatMap((rel) => {
214 if (rel == "summary" && type === "fields") {
215 obj.populate.push("summary")
216 return "summary.totals"
217 } else if (
218 rel.includes("shipping_methods") &&
219 !rel.includes("shipping_methods.shipping_method")
220 ) {
221 obj.populate.push("shipping_methods.shipping_method")
222
223 return rel.replace(
224 "shipping_methods",
225 "shipping_methods.shipping_method"
226 )
227 } else if (rel.includes("items.detail")) {
228 return rel.replace("items.detail", "items")
229 } else if (rel == "items") {
230 return "items.item"
231 } else if (
232 type === "fields" &&
233 ORDER_ITEM_FIELDS.some((field) => rel === `items.${field}`)
234 ) {
235 // These live on the order item (with a line item fallback), not only on the line item
236 return [rel, rel.replace("items.", "items.item.")]
237 } else if (rel.includes("items.") && !rel.includes("items.item")) {
238 return rel.replace("items.", "items.item.")
239 }
240 return rel
241 })
242 )
243 }
244
245 conf.options.fields = replace(config.options, "fields")
246 conf.options.populate = replace(config.options, "populate")
247
248 if (conf.where?.items) {
249 const original = { ...conf.where.items }
250 if (original.detail) {
251 delete conf.where.items.detail
252 }
253
254 conf.where.items = {
255 item: conf.where?.items,
256 }
257
258 if (original.quantity) {
259 conf.where.items.quantity = original.quantity
260 delete conf.where.items.item.quantity
261 }
262
263 if (original.unit_price) {
264 conf.where.items.unit_price = original.unit_price
265 delete conf.where.items.item.unit_price
266 }
267
268 if (original.compare_at_unit_price) {
269 conf.where.items.compare_at_unit_price = original.compare_at_unit_price
270 delete conf.where.items.item.compare_at_unit_price
271 }
272
273 if (original.detail) {
274 conf.where.items = {
275 ...original.detail,
276 ...conf.where.items,
277 }
278 }
279 }
280
281 return conf
282 }
283
284 // This function has the same purpose as "mapRepositoryToOrderModel" but for returns, claims and exchanges
285 function mapRepositoryToRelatedEntity(config) {
286 const conf = { ...config }
287
288 function replace(obj, type): string[] | undefined {
289 if (!isDefined(obj[type])) {
290 return
291 }
292
293 return deduplicate(
294 obj[type].sort().map((rel) => {
295 if (
296 rel.includes("shipping_methods") &&
297 !rel.includes("shipping_methods.shipping_method")
298 ) {
299 obj.populate.push("shipping_methods.shipping_method")
300
301 return rel.replace(
302 "shipping_methods",
303 "shipping_methods.shipping_method"
304 )
305 }
306 return rel
307 })
308 )
309 }
310
311 conf.options.fields = replace(config.options, "fields")
312 conf.options.populate = replace(config.options, "populate")
313
314 return conf
315 }