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