1 import { LoadStrategy, raw } from "@medusajs/framework/mikro-orm/core"
2 import { Constructor, Context, DAL } from "@medusajs/framework/types"
3 import {
4 augmentFindOptionsWithCrossModuleJoins,
5 MikroOrmBaseRepository,
6 pruneFindOptionsAgainstMetadata,
7 toMikroORMEntity,
8 } from "@medusajs/framework/utils"
9 import {
10 Order,
11 OrderClaim,
12 OrderLineItemAdjustment,
13 OrderShippingMethodAdjustment,
14 } from "@models"
15
16 import { mapRepositoryToOrderModel } from "."
17
18 /**
19 * The order module replaces MikroORM repository `find`/`findAndCount` with
20 * version-aware implementations, so it must apply cross-module join filters
21 * itself — the base repository's `prepareFindOptions` is never called.
22 */
23 function applyCrossModuleJoins(
24 repository: {
25 entity: { name?: string; meta?: { className?: string } }
26 tableName: string
27 },
28 findOptions: DAL.FindOptions<any>,
29 manager: {
30 schema?: string
31 config?: { get?: (key: string) => unknown }
32 }
33 ): DAL.FindOptions<any> {
34 const entityName =
35 repository.entity.name ?? repository.entity.meta?.className ?? "Order"
36 const primaryKey =
37 MikroOrmBaseRepository.retrievePrimaryKeys(repository.entity as any)[0] ??
38 "id"
39 const defaultSchema =
40 manager.schema ?? (manager.config?.get?.("schema") as string) ?? undefined
41
42 const augmented = augmentFindOptionsWithCrossModuleJoins(findOptions, {
43 entityName,
44 entityTable: repository.tableName,
45 primaryKey,
46 defaultSchema,
47 })
48
49 // Match MikroOrmBaseRepository.prepareFindOptions: strip residual internal
50 // metadata before handing options to MikroORM.
51 if (augmented.options?.__internal) {
52 delete augmented.options.__internal
53 }
54
55 return augmented
56 }
57
58 function ensureOrderItemFieldsSelection(config: any, isRelatedEntity: boolean) {
59 const populate = config.options?.populate ?? []
60 const fields = config.options?.fields ?? []
61
62 const hasItemsItemPopulate = populate.some(
63 (p: string) =>
64 p === "items.item" ||
65 p.startsWith("items.item.") ||
66 p === "order.items.item" ||
67 p.startsWith("order.items.item.")
68 )
69
70 if (!hasItemsItemPopulate) {
71 return
72 }
73
74 const hasOrderItemFields = fields.some((field: string) => {
75 if (field === "items.*" || field === "order.items.*") {
76 return true
77 }
78
79 if (field.startsWith("items.") && !field.startsWith("items.item.")) {
80 return true
81 }
82
83 if (
84 field.startsWith("order.items.") &&
85 !field.startsWith("order.items.item.")
86 ) {
87 return true
88 }
89
90 return false
91 })
92
93 if (!hasOrderItemFields) {
94 fields.push(isRelatedEntity ? "order.items.*" : "items.*")
95 config.options.fields = fields
96 }
97 }
98
99 function ensureOrderShippingMethodFieldsSelection(
100 config: any,
101 isRelatedEntity: boolean
102 ) {
103 const populate = config.options?.populate ?? []
104 const fields = config.options?.fields ?? []
105
106 const hasShippingMethodPopulate = populate.some(
107 (p: string) =>
108 p === "shipping_methods.shipping_method" ||
109 p.startsWith("shipping_methods.shipping_method.") ||
110 p === "order.shipping_methods.shipping_method" ||
111 p.startsWith("order.shipping_methods.shipping_method.")
112 )
113
114 if (!hasShippingMethodPopulate) {
115 return
116 }
117
118 const hasOrderShippingMethodFields = fields.some((field: string) => {
119 if (
120 field === "shipping_methods.*" ||
121 field === "order.shipping_methods.*"
122 ) {
123 return true
124 }
125
126 if (
127 field.startsWith("shipping_methods.") &&
128 !field.startsWith("shipping_methods.shipping_method.")
129 ) {
130 return true
131 }
132
133 if (
134 field.startsWith("order.shipping_methods.") &&
135 !field.startsWith("order.shipping_methods.shipping_method.")
136 ) {
137 return true
138 }
139
140 return false
141 })
142
143 if (!hasOrderShippingMethodFields) {
144 fields.push(
145 isRelatedEntity ? "order.shipping_methods.*" : "shipping_methods.*"
146 )
147 config.options.fields = fields
148 }
149 }
150
151 export function setFindMethods<T>(klass: Constructor<T>, entity: any) {
152 klass.prototype.find = async function find(
153 this: any,
154 options?: DAL.FindOptions<T>,
155 context?: Context
156 ): Promise<T[]> {
157 const manager = this.getActiveManager(context)
158 const knex = manager.getKnex()
159
160 let findOptions_ = { ...options } as any
161 findOptions_.options ??= {}
162 findOptions_.where ??= {}
163
164 findOptions_ = applyCrossModuleJoins(this, findOptions_, manager)
165
166 if (!("strategy" in findOptions_.options)) {
167 if (findOptions_.options.limit != null || findOptions_.options.offset) {
168 Object.assign(findOptions_.options, {
169 strategy: LoadStrategy.SELECT_IN,
170 })
171 }
172 }
173
174 const isRelatedEntity = entity.name !== Order.name
175
176 const config = mapRepositoryToOrderModel(findOptions_, isRelatedEntity)
177 config.options ??= {}
178 config.options.populate ??= []
179
180 pruneFindOptionsAgainstMetadata(
181 manager.getDriver().getMetadata().get(entity.name),
182 config.options
183 )
184
185 const strategy = findOptions_.options.strategy ?? LoadStrategy.JOINED
186 let orderAlias = "o0"
187 if (isRelatedEntity) {
188 if (entity === OrderClaim) {
189 config.options.populate.push("claim_items")
190 }
191
192 if (strategy === LoadStrategy.JOINED) {
193 config.options.populate.push("order.shipping_methods")
194 config.options.populate.push(
195 "order.shipping_methods.shipping_method.adjustments"
196 )
197 config.options.populate.push("order.summary")
198 config.options.populate.push("shipping_methods")
199 }
200
201 if (!config.options.populate.includes("order.items")) {
202 config.options.populate.unshift("order.items")
203 }
204
205 // first relation is always order if the entity is not Order
206 const index = config.options.populate.findIndex((p) => p === "order")
207 if (index > -1) {
208 config.options.populate.splice(index, 1)
209 }
210
211 config.options.populate.unshift("order")
212 orderAlias = "o1"
213 }
214
215 let defaultVersion = knex.raw(`"${orderAlias}"."version"`)
216
217 if (strategy === LoadStrategy.SELECT_IN) {
218 const sql = manager
219 .qb(toMikroORMEntity(Order), "_sub0")
220 .select("version")
221 .where({ id: knex.raw(`"${orderAlias}"."order_id"`) })
222 .getKnexQuery()
223 .toString()
224
225 defaultVersion = knex.raw(`(${sql})`)
226 }
227
228 const version = config.where?.version ?? defaultVersion
229 delete config.where?.version
230
231 configurePopulateWhere(
232 config,
233 isRelatedEntity,
234 version,
235 strategy === LoadStrategy.SELECT_IN,
236 manager
237 )
238
239 let shouldLoadItemAdjustments = false
240 let shouldLoadShippingAdjustments = false
241 if (config.options.populate.includes("items.item.adjustments")) {
242 // TODO: handle if populate is an object
243 shouldLoadItemAdjustments = true
244
245 config.options.populate.splice(
246 config.options.populate.indexOf("items.item.adjustments"),
247 1
248 )
249
250 config.options.populate.push("items")
251 config.options.populate.push("items.item")
252
253 // make sure version is loaded if adjustments are requested
254 if (config.options.fields?.some((f) => f.includes("items.item."))) {
255 config.options.fields.push(
256 isRelatedEntity ? "order.items.version" : "items.version"
257 )
258 }
259 }
260
261 if (
262 config.options.populate.includes(
263 "shipping_methods.shipping_method.adjustments"
264 )
265 ) {
266 // TODO: handle if populate is an object
267 shouldLoadShippingAdjustments = true
268
269 config.options.populate.splice(
270 config.options.populate.indexOf(
271 "shipping_methods.shipping_method.adjustments"
272 ),
273 1
274 )
275
276 config.options.populate.push("shipping_methods")
277 config.options.populate.push("shipping_methods.shipping_method")
278
279 if (
280 config.options.fields?.some((f) =>
281 f.includes("shipping_methods.shipping_method.")
282 )
283 ) {
284 config.options.fields.push(
285 isRelatedEntity
286 ? "order.shipping_methods.version"
287 : "shipping_methods.version"
288 )
289 }
290 }
291
292 if (!config.options.orderBy) {
293 config.options.orderBy = { id: "ASC" }
294 }
295
296 config.where ??= {}
297
298 if (strategy === LoadStrategy.SELECT_IN) {
299 ensureOrderItemFieldsSelection(config, isRelatedEntity)
300 ensureOrderShippingMethodFieldsSelection(config, isRelatedEntity)
301 MikroOrmBaseRepository.compensateRelationFieldsSelectionFromLoadStrategy({
302 findOptions: config,
303 })
304 }
305
306 const result = await manager.find(this.entity, config.where, config.options)
307
308 if (shouldLoadItemAdjustments || shouldLoadShippingAdjustments) {
309 const orders = !isRelatedEntity
310 ? [...result]
311 : [...result].map((r) => r.order).filter(Boolean)
312
313 if (shouldLoadItemAdjustments) {
314 await loadItemAdjustments(manager, orders)
315 }
316
317 if (shouldLoadShippingAdjustments) {
318 await loadShippingAdjustments(manager, orders)
319 }
320 }
321
322 return result
323 }
324
325 klass.prototype.findAndCount = async function findAndCount(
326 this: any,
327 findOptions: DAL.FindOptions<T> = { where: {} } as DAL.FindOptions<T>,
328 context: Context = {}
329 ): Promise<[T[], number]> {
330 const manager = this.getActiveManager(context)
331 const knex = manager.getKnex()
332
333 let findOptions_ = { ...findOptions } as any
334 findOptions_.options ??= {}
335 findOptions_.where ??= {}
336
337 findOptions_ = applyCrossModuleJoins(this, findOptions_, manager)
338
339 if (!("strategy" in findOptions_.options)) {
340 Object.assign(findOptions_.options, {
341 strategy: LoadStrategy.SELECT_IN,
342 })
343 }
344
345 const isRelatedEntity = entity.name !== Order.name
346
347 const config = mapRepositoryToOrderModel(findOptions_, isRelatedEntity)
348 config.options ??= {}
349 config.options.populate ??= []
350
351 pruneFindOptionsAgainstMetadata(
352 manager.getDriver().getMetadata().get(entity.name),
353 config.options
354 )
355
356 let orderAlias = "o0"
357 if (isRelatedEntity) {
358 if (entity === OrderClaim) {
359 if (
360 config.options.populate.includes("additional_items") &&
361 !config.options.populate.includes("claim_items")
362 ) {
363 config.options.populate.push("claim_items")
364 }
365 }
366
367 const index = config.options.populate.findIndex((p) => p === "order")
368 if (index > -1) {
369 config.options.populate.splice(index, 1)
370 }
371
372 config.options.populate.unshift("order")
373 orderAlias = "o1"
374 }
375
376 let defaultVersion = knex.raw(`"${orderAlias}"."version"`)
377 const strategy = config.options.strategy ?? LoadStrategy.JOINED
378 if (strategy === LoadStrategy.SELECT_IN) {
379 defaultVersion = getVersionSubQuery(manager, orderAlias)
380 }
381
382 const version = config.where.version ?? defaultVersion
383 delete config.where.version
384
385 let loadAdjustments = false
386 if (config.options.populate.includes("items.item.adjustments")) {
387 loadAdjustments = true
388 config.options.populate.splice(
389 config.options.populate.indexOf("items.item.adjustments"),
390 1
391 )
392
393 config.options.populate.push("items")
394 config.options.populate.push("items.item")
395
396 // make sure version is loaded if adjustments are requested
397 if (config.options.fields?.some((f) => f.includes("items.item."))) {
398 config.options.fields.push(
399 isRelatedEntity ? "order.items.version" : "items.version"
400 )
401 }
402 }
403
404 let shouldLoadShippingAdjustments = false
405 if (
406 config.options.populate.includes(
407 "shipping_methods.shipping_method.adjustments"
408 )
409 ) {
410 shouldLoadShippingAdjustments = true
411 config.options.populate.splice(
412 config.options.populate.indexOf(
413 "shipping_methods.shipping_method.adjustments"
414 ),
415 1
416 )
417
418 config.options.populate.push("shipping_methods")
419 config.options.populate.push("shipping_methods.shipping_method")
420
421 // make sure version is loaded if adjustments are requested
422 if (
423 config.options.fields?.some((f) =>
424 f.includes("shipping_methods.shipping_method.")
425 )
426 ) {
427 config.options.fields.push(
428 isRelatedEntity
429 ? "order.shipping_methods.version"
430 : "shipping_methods.version"
431 )
432 }
433 }
434
435 configurePopulateWhere(
436 config,
437 isRelatedEntity,
438 version,
439 strategy === LoadStrategy.SELECT_IN,
440 manager
441 )
442
443 if (!config.options.orderBy) {
444 config.options.orderBy = { id: "ASC" }
445 }
446
447 if (strategy === LoadStrategy.SELECT_IN) {
448 ensureOrderItemFieldsSelection(config, isRelatedEntity)
449 ensureOrderShippingMethodFieldsSelection(config, isRelatedEntity)
450 MikroOrmBaseRepository.compensateRelationFieldsSelectionFromLoadStrategy({
451 findOptions: config,
452 })
453 }
454
455 // The count query uses JOINED strategy internally (MikroORM 6.6+), but
456 // populateWhere version subqueries reference SELECT_IN aliases (e.g. "o0")
457 // that don't exist in the JOINED count context. Since version filters only
458 // control which items to load (not which root entities to count), we run
459 // find and count separately with different populateWhere options.
460 const countOptions = { ...config.options, populateWhere: undefined }
461 const [result, count] = await Promise.all([
462 manager.find(this.entity, config.where, config.options),
463 manager.count(this.entity, config.where, countOptions),
464 ])
465
466 if (loadAdjustments || shouldLoadShippingAdjustments) {
467 const orders = !isRelatedEntity
468 ? [...result]
469 : [...result].map((r) => r.order).filter(Boolean)
470
471 if (loadAdjustments) {
472 await loadItemAdjustments(manager, orders)
473 }
474 if (shouldLoadShippingAdjustments) {
475 await loadShippingAdjustments(manager, orders)
476 }
477 }
478
479 return [result, count]
480 }
481 }
482
483 /**
484 * Load adjustment for the latest items/order version
485 * @param manager MikroORM manager
486 * @param orders Orders to load adjustments for
487 */
488 async function loadItemAdjustments(manager, orders) {
489 const items = orders.flatMap((r) => [...(r.items ?? [])])
490 const itemsIdMap = new Map<string, any>(items.map((i) => [i.item.id, i.item]))
491
492 if (!items.length) {
493 return
494 }
495
496 const params = items.map((i) => {
497 // preinitialise all items so an empty array is returned for ones without adjustments
498 if (!i.item.adjustments.isInitialized()) {
499 i.item.adjustments.initialized = true
500 }
501
502 if (!i.version) {
503 throw new Error("Item version is required to load adjustments")
504 }
505 return {
506 item_id: i.item.id,
507 version: i.version,
508 }
509 })
510
511 const adjustments = await manager.find(OrderLineItemAdjustment, {
512 $or: params,
513 })
514
515 for (const adjustment of adjustments) {
516 const item = itemsIdMap.get(adjustment.item_id)
517 if (item) {
518 item.adjustments.add(adjustment)
519 }
520 }
521 }
522
523 /**
524 * Load adjustment for the latest shipping methods/order version
525 * @param manager MikroORM manager
526 * @param orders Orders to load adjustments for
527 */
528 async function loadShippingAdjustments(manager, orders) {
529 const shippingMethods = orders.flatMap((r) => [...(r.shipping_methods ?? [])])
530 const shippingMethodsIdMap = new Map<string, any>(
531 shippingMethods.map((s) => [s.shipping_method.id, s.shipping_method])
532 )
533
534 if (!shippingMethods.length) {
535 return
536 }
537
538 const params = shippingMethods.map((s) => {
539 // preinitialise all shipping methods so an empty array is returned for ones without adjustments
540 if (!s.shipping_method.adjustments.isInitialized()) {
541 s.shipping_method.adjustments.initialized = true
542 }
543
544 if (!s.version) {
545 throw new Error("Shipping method version is required to load adjustments")
546 }
547 return {
548 shipping_method_id: s.shipping_method.id,
549 version: s.version,
550 }
551 })
552
553 const adjustments = await manager.find(OrderShippingMethodAdjustment, {
554 $or: params,
555 })
556
557 for (const adjustment of adjustments) {
558 const shippingMethod = shippingMethodsIdMap.get(
559 adjustment.shipping_method_id
560 )
561 if (shippingMethod) {
562 shippingMethod.adjustments.add(adjustment)
563 }
564 }
565 }
566
567 function getVersionSubQuery(manager, alias, field = "order_id") {
568 const knex = manager.getKnex()
569 const sql = manager
570 .qb(toMikroORMEntity(Order), "_sub0")
571 .select("version")
572 .where({ id: knex.raw(`"${alias}"."${field}"`) })
573 .getKnexQuery()
574 .toString()
575
576 return knex.raw(`(${sql})`)
577 }
578
579 function configurePopulateWhere(
580 config: any,
581 isRelatedEntity: boolean,
582 version: any,
583 isSelectIn = false,
584 manager?
585 ) {
586 const requestedPopulate = config.options?.populate ?? []
587 const hasRelation = (relation: string) =>
588 requestedPopulate.some(
589 (p) => p === relation || p.startsWith(`${relation}.`)
590 )
591
592 config.options.populateWhere ??= {}
593 const popWhere = config.options.populateWhere
594
595 if (isRelatedEntity) {
596 popWhere.order ??= {}
597
598 const popWhereOrder = popWhere.order
599
600 if (!isSelectIn) {
601 // For JOINED strategy, version is a reference to the order alias (e.g. "o1"."version")
602 // This is trivially true since Order has one row per id, but kept for consistency
603 popWhereOrder.version = version
604 }
605 // For SELECT_IN strategy, the order.version condition is always trivially true
606 // (Order has one row per id) so we skip it entirely
607
608 // related entity shipping method
609 if (hasRelation("shipping_methods")) {
610 popWhere.shipping_methods ??= {}
611 if (isSelectIn) {
612 // For MikroORM 6.6.x+, populateWhere conditions for force-joined relations are
613 // embedded as inline JOIN conditions. Use alias callback so [::alias::] gets
614 // replaced with the actual shipping_method alias at query-build time.
615 const fragment = raw(
616 (alias) =>
617 `"${alias}"."version" = (select "_sub0"."version" from "order" as "_sub0" where "_sub0"."id" = "${alias}"."order_id")`
618 )
619 ;(popWhere.shipping_methods as any)[fragment.toString()] = []
620 } else {
621 popWhere.shipping_methods.version = version
622 }
623 }
624
625 if (hasRelation("items") || hasRelation("order.items")) {
626 popWhereOrder.items ??= {}
627 if (isSelectIn) {
628 // In MikroORM 6.6.x+, the global alias counter changed (no longer per-entity-type),
629 // so "o0" no longer exists in the query context for related entity queries.
630 // Instead, use a self-referential raw fragment: the [::alias::] placeholder is
631 // replaced with the order_item's own JOIN alias, and order_item.order_id is used
632 // to look up the order's current version.
633 const fragment = raw(
634 (alias) =>
635 `"${alias}"."version" = (select "_sub0"."version" from "order" as "_sub0" where "_sub0"."id" = "${alias}"."order_id")`
636 )
637 ;(popWhereOrder.items as any)[fragment.toString()] = []
638 } else {
639 popWhereOrder.items.version = version
640 }
641 }
642
643 if (hasRelation("shipping_methods")) {
644 popWhereOrder.shipping_methods ??= {}
645 if (isSelectIn) {
646 const fragment = raw(
647 (alias) =>
648 `"${alias}"."version" = (select "_sub0"."version" from "order" as "_sub0" where "_sub0"."id" = "${alias}"."order_id")`
649 )
650 ;(popWhereOrder.shipping_methods as any)[fragment.toString()] = []
651 } else {
652 popWhereOrder.shipping_methods.version = version
653 }
654 }
655
656 return
657 }
658
659 if (isSelectIn) {
660 version = getVersionSubQuery(manager, "o0")
661 }
662
663 if (hasRelation("summary")) {
664 popWhere.summary ??= {}
665 popWhere.summary.version = version
666 }
667
668 if (hasRelation("credit_lines")) {
669 popWhere.credit_lines ??= {}
670 popWhere.credit_lines.version = version
671 }
672
673 if (hasRelation("items") || hasRelation("order.items")) {
674 popWhere.items ??= {}
675 popWhere.items.version = version
676 }
677
678 if (hasRelation("shipping_methods")) {
679 popWhere.shipping_methods ??= {}
680 popWhere.shipping_methods.version = version
681 }
682 }