1 import { Product, ProductOption } from "@models"
2
3 import { Context, DAL, InferEntityType } from "@medusajs/framework/types"
4 import {
5 arrayDifference,
6 DALUtils,
7 deepCopy,
8 isPresent,
9 MedusaError,
10 mergeMetadata,
11 } from "@medusajs/framework/utils"
12 import {
13 SqlEntityManager,
14 wrap,
15 } from "@medusajs/framework/mikro-orm/postgresql"
16 import { resolveAllowedOptionValues } from "../utils/resolve-allowed-option-values"
17
18 export class ProductRepository extends DALUtils.mikroOrmBaseRepositoryFactory(
19 Product
20 ) {
21 constructor(...args: any[]) {
22 // @ts-ignore
23 super(...arguments)
24 }
25
26 /**
27 * Identify the relations to load for the given update.
28 * @param update
29 * @returns
30 */
31 static #getProductDeepUpdateRelationsToLoad(
32 productsToUpdate: any[]
33 ): string[] {
34 const relationsToLoad = new Set<string>()
35 productsToUpdate.forEach((productToUpdate) => {
36 if (productToUpdate.options) {
37 relationsToLoad.add("options")
38 relationsToLoad.add("options.values")
39 }
40 if (productToUpdate.variants) {
41 relationsToLoad.add("options")
42 relationsToLoad.add("options.values")
43 relationsToLoad.add("variants")
44 relationsToLoad.add("variants.options")
45 relationsToLoad.add("variants.options.option")
46 }
47 if (productToUpdate.tags) relationsToLoad.add("tags")
48 if (productToUpdate.categories) relationsToLoad.add("categories")
49 if (productToUpdate.images) relationsToLoad.add("images")
50 if (productToUpdate.collection) relationsToLoad.add("collection")
51 if (productToUpdate.type) relationsToLoad.add("type")
52 })
53 return Array.from(relationsToLoad)
54 }
55
56 async deepUpdate(
57 productsToUpdate: ({ id: string } & any)[],
58 validateVariantOptions: (
59 variants: any[],
60 options: InferEntityType<typeof ProductOption>[],
61 productId: string,
62 allowedValueIds?: Set<string>
63 ) => void,
64 expectedOptionIdsMap: Map<string, Set<string>> = new Map(),
65 valueIdsByProductId: Map<string, Set<string>> = new Map(),
66 context: Context = {}
67 ): Promise<InferEntityType<typeof Product>[]> {
68 const productsToUpdate_ = deepCopy(productsToUpdate)
69 const productIdsToUpdate: string[] = []
70
71 productsToUpdate_.forEach((productToUpdate) => {
72 productIdsToUpdate.push(productToUpdate.id)
73 })
74
75 const relationsToLoad =
76 ProductRepository.#getProductDeepUpdateRelationsToLoad(productsToUpdate_)
77
78 // Splitting the populate into per-relation calls avoids a pathological
79 // slow path in MikroORM where a combined `find({populate})` over deep
80 // relations becomes orders of magnitude slower at moderate batch sizes
81 const products = await this.findByIdsWithSplitPopulate(
82 productIdsToUpdate,
83 relationsToLoad,
84 context
85 )
86 const productsMap = new Map(products.map((p) => [p.id, p]))
87
88 const productIds = Array.from(productsMap.keys())
89 const productsNotFound = arrayDifference(productIdsToUpdate, productIds)
90
91 if (productsNotFound.length > 0) {
92 throw new MedusaError(
93 MedusaError.Types.NOT_FOUND,
94 `Unable to update the products with ids: ${productsNotFound.join(", ")}`
95 )
96 }
97
98 for (const productToUpdate of productsToUpdate_) {
99 const product = productsMap.get(productToUpdate.id)!
100 const wrappedProduct = wrap(product)
101
102 if (productToUpdate.options) {
103 wrappedProduct.assign({ options: productToUpdate.options })
104 delete productToUpdate.options
105 }
106
107 if (productToUpdate.variants) {
108 productToUpdate.variants = productToUpdate.variants.map(
109 ({ options, ...variant }: any) =>
110 isPresent(options) ? { ...variant, options } : variant
111 )
112
113 const expectedOptionIds = expectedOptionIdsMap.get(product.id)
114 const optionsForValidation = expectedOptionIds
115 ? product.options.filter((o) => expectedOptionIds.has(o.id))
116 : product.options
117 const allowedValueIds = valueIdsByProductId.get(product.id)
118
119 validateVariantOptions(
120 productToUpdate.variants,
121 optionsForValidation,
122 product.id,
123 allowedValueIds
124 )
125
126 productToUpdate.variants.forEach((variant: any) => {
127 if (variant.options) {
128 variant.options = Object.entries(variant.options).map(
129 ([key, value]) => {
130 const productOption = product.options.find(
131 (option) => option.title === key
132 )!
133 const productOptionValue = resolveAllowedOptionValues({
134 optionTitle: key,
135 value,
136 optionValues: productOption.values,
137 allowedValueIds,
138 })
139 return productOptionValue.id
140 }
141 )
142 }
143 })
144 }
145
146 if (productToUpdate.tags) {
147 productToUpdate.tags = productToUpdate.tags.map(
148 (t: { id: string }) => t.id
149 )
150 }
151 if (productToUpdate.categories) {
152 productToUpdate.categories = productToUpdate.categories.map(
153 (c: { id: string }) => c.id
154 )
155 }
156 if (productToUpdate.images) {
157 productToUpdate.images = productToUpdate.images.map(
158 (image: any, index: number) => ({
159 ...image,
160 rank: index,
161 })
162 )
163 }
164
165 if (isPresent(productToUpdate.metadata)) {
166 productToUpdate.metadata = mergeMetadata(
167 product.metadata ?? {},
168 productToUpdate.metadata
169 )
170 }
171
172 wrappedProduct.assign(productToUpdate)
173 }
174
175 // Doing this to ensure updates are returned in the same order they were provided,
176 // since some core flows rely on this.
177 // This is a high level of coupling though.
178 return productsToUpdate_.map(
179 (productToUpdate) => productsMap.get(productToUpdate.id)!
180 )
181 }
182
183 /**
184 * Loads products by id with the given relations using sequential per-relation
185 * populate() calls instead of one combined find({populate}) — see deepUpdate
186 * for the rationale (combined populate is dramatically slower for moderate
187 * batch sizes with multiple deep relations).
188 *
189 * Callers of this method should call flush() on the manager for pending writes
190 * to relations passed for population to be visible in the loaded entities.
191 */
192 async findByIdsWithSplitPopulate(
193 productIds: string[],
194 relations: string[],
195 context: Context = {}
196 ): Promise<InferEntityType<typeof Product>[]> {
197 if (!productIds.length) {
198 return []
199 }
200 const manager = super.getActiveManager<SqlEntityManager>(context)
201 const products = await manager.find<InferEntityType<typeof Product>>(
202 Product.name,
203 { id: productIds },
204 { limit: productIds.length, refresh: true } as any
205 )
206 // `refresh: true` ensures that if the entities are already in the identity
207 // map (e.g. created earlier in the same transaction), their collections
208 // are re-hydrated from the DB instead of returning stale empty ones.
209 for (const relation of relations) {
210 await (manager as any).populate(products, [relation], { refresh: true })
211 }
212 return products
213 }
214
215 /**
216 * In order to be able to have a strict not in categories, and prevent a product
217 * to be return in the case it also belongs to other categories, we need to
218 * first find all products that are in the categories, and then exclude them
219 */
220 protected async mutateNotInCategoriesConstraints(
221 findOptions: DAL.FindOptions<typeof Product> = {
222 where: {},
223 },
224 context: Context = {}
225 ): Promise<void> {
226 const manager = this.getActiveManager<SqlEntityManager>(context)
227
228 if (
229 "categories" in findOptions.where &&
230 findOptions.where.categories?.id?.["$nin"]
231 ) {
232 const productsInCategories = await manager.find(
233 this.entity,
234 {
235 categories: {
236 id: { $in: findOptions.where.categories.id["$nin"] },
237 },
238 },
239 {
240 fields: ["id"],
241 }
242 )
243
244 const productIds = productsInCategories.map((product) => product.id)
245
246 if (productIds.length) {
247 findOptions.where.id = { $nin: productIds }
248 delete findOptions.where.categories?.id
249
250 if (Object.keys(findOptions.where.categories).length === 0) {
251 delete findOptions.where.categories
252 }
253 }
254 }
255 }
256
257 /**
258 * Checks if any variants of products use the specified option values.
259 * Queries the product_variant_option pivot table directly in bulk.
260 *
261 * @param pairs - Array of { productId, optionValueIds } pairs to check
262 * @param context - The context
263 * @returns Map keyed by `${productId}_${valueId}` with arrays of variant info (id and title) that use those values
264 */
265 async checkVariantsUsingOptionValues(
266 pairs: Array<{ productId: string; optionValueIds: string[] }> = [],
267 context: Context = {}
268 ): Promise<
269 Map<
270 string,
271 Array<{ variant_id: string; title: string | null; product_id: string }>
272 >
273 > {
274 if (pairs.length === 0) {
275 return new Map()
276 }
277
278 const validPairs = pairs.filter((p) => p.optionValueIds.length > 0)
279 if (validPairs.length === 0) {
280 return new Map()
281 }
282
283 const manager = this.getActiveManager<SqlEntityManager>(context)
284 // Use the transaction-bound knex so we see writes made earlier in the
285 // same transaction (e.g. pivot rows just inserted by another service call).
286 const knex = manager.getTransactionContext() ?? manager.getKnex()
287
288 const allProductIds = [...new Set(validPairs.map((p) => p.productId))]
289 const allValueIds = [
290 ...new Set(validPairs.flatMap((p) => p.optionValueIds)),
291 ]
292
293 const result = await knex
294 .select(
295 "pvo.variant_id",
296 "pv.title",
297 "pv.product_id",
298 "pvo.option_value_id"
299 )
300 .distinct()
301 .from("product_variant_option as pvo")
302 .innerJoin("product_variant as pv", "pv.id", "pvo.variant_id")
303 .whereIn("pv.product_id", allProductIds)
304 .whereNull("pv.deleted_at")
305 .whereIn("pvo.option_value_id", allValueIds)
306
307 const resultMap = new Map<
308 string,
309 Array<{ variant_id: string; title: string | null; product_id: string }>
310 >()
311
312 for (const row of result) {
313 const key = `${row.product_id}_${row.option_value_id}`
314 if (!resultMap.has(key)) {
315 resultMap.set(key, [])
316 }
317 resultMap.get(key)!.push({
318 variant_id: row.variant_id,
319 title: row.title,
320 product_id: row.product_id,
321 })
322 }
323
324 return resultMap
325 }
326
327 /**
328 * Checks if product options can be deleted.
329 * An option cannot be deleted if there are non-deleted products using it.
330 *
331 * @param optionIds - Array of option IDs to check
332 * @param context - The context
333 * @returns true if all options can be deleted, false if any cannot be deleted
334 */
335 async canDeleteProductOption(
336 optionIds: string[],
337 context: Context = {}
338 ): Promise<boolean> {
339 if (!optionIds.length) {
340 return true
341 }
342
343 const manager = this.getActiveManager<SqlEntityManager>(context)
344 // Use the transaction-bound knex so we see writes made earlier in the
345 // same transaction (e.g. pivot rows just inserted by another service call).
346 const knex = manager.getTransactionContext() ?? manager.getKnex()
347
348 const blockingOptions = await knex
349 .select("ppo.product_option_id")
350 .from("product_product_option as ppo")
351 .innerJoin("product as p", "p.id", "ppo.product_id")
352 .innerJoin("product_option as po", "po.id", "ppo.product_option_id")
353 .whereIn("ppo.product_option_id", optionIds)
354 .whereNull("ppo.deleted_at")
355 .whereNull("p.deleted_at") // <- allow soft deleting an option that is associated with a soft deleted product
356 .whereNull("po.deleted_at")
357 .limit(1)
358
359 return !blockingOptions.length
360 }
361
362 /**
363 * Checks whether product options can be assigned to products.
364 *
365 * Returns conflicting option ids if:
366 * - the option is already assigned to that product
367 * - the option is exclusive and is assigned to another product
368 *
369 * @param pairs - Array of { productId, optionId } pairs to check
370 * @param context - The context
371 */
372 async canAssignProductOptionToProduct(
373 pairs: Array<{ productId: string; optionId: string }> = [],
374 context: Context = {}
375 ): Promise<{
376 exclusiveOptionIds: string[]
377 alreadyLinkedOptionIds: string[]
378 }> {
379 if (!pairs.length) {
380 return { exclusiveOptionIds: [], alreadyLinkedOptionIds: [] }
381 }
382
383 // Reject duplicate (product, option) pairs within the input itself. Without
384 // this check, downstream `INSERT … ON CONFLICT DO NOTHING` silently dedupes
385 // the rows and the caller never finds out they double-assigned.
386 const seenKeys = new Set<string>()
387 const duplicateKeys: string[] = []
388 for (const pair of pairs) {
389 const key = `${pair.productId}_${pair.optionId}`
390 if (seenKeys.has(key)) {
391 duplicateKeys.push(key)
392 } else {
393 seenKeys.add(key)
394 }
395 }
396 if (duplicateKeys.length) {
397 throw new MedusaError(
398 MedusaError.Types.INVALID_DATA,
399 `Duplicate product option assignments are not allowed; remove duplicate pairs: ${duplicateKeys.join(
400 ", "
401 )}`
402 )
403 }
404
405 const optionToProductIds = new Map<string, Set<string>>()
406
407 pairs.forEach((pair) => {
408 const productIds = optionToProductIds.get(pair.optionId) ?? new Set()
409 productIds.add(pair.productId)
410 optionToProductIds.set(pair.optionId, productIds)
411 })
412
413 const optionIds = [...optionToProductIds.keys()]
414
415 const manager = this.getActiveManager<SqlEntityManager>(context)
416 // Use the transaction-bound knex so we see writes made earlier in the
417 // same transaction (e.g. pivot rows just inserted by another service call).
418 const knex = manager.getTransactionContext() ?? manager.getKnex()
419
420 const pairPlaceholders = pairs.map(() => "(?, ?)").join(", ")
421 const pairBindings = pairs.flatMap((p) => [p.productId, p.optionId])
422
423 const { rows: alreadyLinkedRows } = await knex.raw(
424 `SELECT DISTINCT product_option_id as option_id
425 FROM product_product_option
426 WHERE (product_id, product_option_id) IN (${pairPlaceholders})
427 AND deleted_at IS NULL`,
428 pairBindings
429 )
430
431 const alreadyLinkedOptionIds = alreadyLinkedRows.map(
432 (row: { option_id: string }) => row.option_id
433 )
434
435 const { rows: exclusiveConflictRows } = await knex.raw(
436 `WITH input_pairs(product_id, option_id) AS (VALUES ${pairPlaceholders})
437 SELECT DISTINCT po.id as option_id
438 FROM product_option po
439 WHERE po.is_exclusive = true
440 AND po.id IN (SELECT option_id FROM input_pairs)
441 AND (
442 (SELECT COUNT(DISTINCT ip.product_id) FROM input_pairs ip WHERE ip.option_id = po.id) > 1
443 OR EXISTS (
444 SELECT 1 FROM product_product_option ppo
445 WHERE ppo.product_option_id = po.id
446 AND ppo.deleted_at IS NULL
447 AND ppo.product_id NOT IN (SELECT ip.product_id FROM input_pairs ip WHERE ip.option_id = po.id)
448 )
449 )`,
450 pairBindings
451 )
452
453 const exclusiveOptionIds = exclusiveConflictRows.map(
454 (row: { option_id: string }) => row.option_id
455 )
456
457 return {
458 exclusiveOptionIds: optionIds.filter((id) =>
459 exclusiveOptionIds.includes(id)
460 ),
461 alreadyLinkedOptionIds: optionIds.filter((id) =>
462 alreadyLinkedOptionIds.includes(id)
463 ),
464 }
465 }
466
467 async getOptionIdsByProductIds(
468 productIds: string[],
469 context: Context = {}
470 ): Promise<Map<string, Set<string>>> {
471 const optionIdsByProduct = new Map<string, Set<string>>()
472
473 if (!productIds.length) {
474 return optionIdsByProduct
475 }
476
477 const manager = this.getActiveManager<SqlEntityManager>(context)
478 const knex = manager.getTransactionContext() ?? manager.getKnex()
479
480 const rows = await knex("product_product_option")
481 .select("product_id", "product_option_id")
482 .whereIn("product_id", productIds)
483 .whereNull("deleted_at")
484
485 rows.forEach((row) => {
486 if (!optionIdsByProduct.has(row.product_id)) {
487 optionIdsByProduct.set(row.product_id, new Set())
488 }
489 optionIdsByProduct.get(row.product_id)!.add(row.product_option_id)
490 })
491
492 return optionIdsByProduct
493 }
494
495 async getOptionValueIdsByProductIds(
496 productIds: string[],
497 context: Context = {}
498 ): Promise<Map<string, Set<string>>> {
499 const allowedValueIdsByProduct = new Map<string, Set<string>>()
500
501 if (!productIds.length) {
502 return allowedValueIdsByProduct
503 }
504
505 const manager = this.getActiveManager<SqlEntityManager>(context)
506 // Use the transaction-bound knex so we see pivot rows written earlier in
507 // the same transaction (e.g. by addProductOptionToProduct_).
508 const knex = manager.getTransactionContext() ?? manager.getKnex()
509
510 const rows = await knex("product_product_option_value as ppov")
511 .select("ppo.product_id", "ppov.product_option_value_id")
512 .innerJoin("product_product_option as ppo", function (this: any) {
513 this.on("ppo.id", "ppov.product_product_option_id").andOnNull(
514 "ppo.deleted_at"
515 )
516 })
517 .whereIn("ppo.product_id", productIds)
518 .whereNull("ppov.deleted_at")
519
520 rows.forEach((row) => {
521 if (!allowedValueIdsByProduct.has(row.product_id)) {
522 allowedValueIdsByProduct.set(row.product_id, new Set())
523 }
524 allowedValueIdsByProduct
525 .get(row.product_id)!
526 .add(row.product_option_value_id)
527 })
528
529 return allowedValueIdsByProduct
530 }
531
532 /**
533 * Returns every non-deleted variant of the given products together with the
534 * option values it is built on, keyed by product id then variant id.
535 */
536 async getVariantOptionValuesByProductIds(
537 productIds: string[],
538 context: Context = {}
539 ): Promise<
540 Map<string, Map<string, { title: string | null; valueIds: Set<string> }>>
541 > {
542 const variantsByProduct = new Map<
543 string,
544 Map<string, { title: string | null; valueIds: Set<string> }>
545 >()
546
547 if (!productIds.length) {
548 return variantsByProduct
549 }
550
551 const manager = this.getActiveManager<SqlEntityManager>(context)
552 // Use the transaction-bound knex so we see pivot rows written earlier in
553 // the same transaction.
554 const knex = manager.getTransactionContext() ?? manager.getKnex()
555
556 // Left join so a variant with no options at all still shows up — it takes
557 // part in the option-combination uniqueness check like any other.
558 const rows: Array<{
559 variant_id: string
560 title: string | null
561 product_id: string
562 option_value_id: string | null
563 }> = await knex
564 .select(
565 "pv.id as variant_id",
566 "pv.title",
567 "pv.product_id",
568 "pvo.option_value_id"
569 )
570 .from("product_variant as pv")
571 .leftJoin("product_variant_option as pvo", "pvo.variant_id", "pv.id")
572 .whereIn("pv.product_id", productIds)
573 .whereNull("pv.deleted_at")
574
575 for (const row of rows) {
576 if (!variantsByProduct.has(row.product_id)) {
577 variantsByProduct.set(row.product_id, new Map())
578 }
579
580 const productVariants = variantsByProduct.get(row.product_id)!
581
582 if (!productVariants.has(row.variant_id)) {
583 productVariants.set(row.variant_id, {
584 title: row.title,
585 valueIds: new Set(),
586 })
587 }
588
589 if (row.option_value_id) {
590 productVariants.get(row.variant_id)!.valueIds.add(row.option_value_id)
591 }
592 }
593
594 return variantsByProduct
595 }
596
597 /**
598 * Drops the given option values off the given variants. product_variant_option
599 * is a plain pivot with no deleted_at, so the rows are deleted outright.
600 */
601 async detachOptionValuesFromVariants(
602 variantIds: string[],
603 optionValueIds: string[],
604 context: Context = {}
605 ): Promise<void> {
606 if (!variantIds.length || !optionValueIds.length) {
607 return
608 }
609
610 const manager = this.getActiveManager<SqlEntityManager>(context)
611 const knex = manager.getTransactionContext() ?? manager.getKnex()
612
613 await knex("product_variant_option")
614 .whereIn("variant_id", variantIds)
615 .whereIn("option_value_id", optionValueIds)
616 .delete()
617 }
618 }