Raw
1 import {
2 Context,
3 DAL,
4 FilterableProductOptionValueProps,
5 FindConfig,
6 IEventBusModuleService,
7 InferEntityType,
8 InternalModuleDeclaration,
9 ModuleJoinerConfig,
10 ModulesSdkTypes,
11 ProductTypes,
12 RestoreReturn,
13 SoftDeleteReturn,
14 } from "@medusajs/framework/types"
15 import { CreateProductOptionDTO } from "@medusajs/types"
16 import {
17 Product,
18 ProductCategory,
19 ProductCollection,
20 ProductImage,
21 ProductOption,
22 ProductOptionValue,
23 ProductProductOption,
24 ProductProductOptionValue,
25 ProductTag,
26 ProductType,
27 ProductVariant,
28 ProductVariantProductImage,
29 } from "@models"
30 import { ProductCategoryService } from "@services"
31
32 import {
33 arrayDifference,
34 createMedusaMikroOrmEventSubscriber,
35 EmitEvents,
36 generateEntityId,
37 InjectManager,
38 InjectTransactionManager,
39 isDefined,
40 isPresent,
41 isString,
42 isValidHandle,
43 kebabCase,
44 MedusaContext,
45 MedusaError,
46 MedusaService,
47 mergeMetadata,
48 MessageAggregator,
49 Modules,
50 partitionArray,
51 ProductStatus,
52 promiseAll,
53 removeUndefined,
54 toHandle,
55 } from "@medusajs/framework/utils"
56 import { EntityManager } from "@medusajs/framework/mikro-orm/core"
57 import { ProductRepository } from "../repositories"
58 import {
59 UpdateCategoryInput,
60 UpdateCollectionInput,
61 UpdateProductInput,
62 FilterableProduct,
63 UpdateProductOptionInput,
64 UpdateProductVariantInput,
65 UpdateTagInput,
66 UpdateTypeInput,
67 VariantImageInputArray,
68 } from "../types"
69 import {
70 applyPublishedProductsContext,
71 computeOptionLinkChanges,
72 eventBuilders,
73 } from "../utils"
74 import { joinerConfig } from "./../joiner-config"
75 import { buildOptionValueFilterQuery } from "../utils/build-option-value-filter-query"
76 import { resolveAllowedOptionValues } from "../utils/resolve-allowed-option-values"
77
78 type InjectedDependencies = {
79 baseRepository: DAL.RepositoryService
80 productRepository: ProductRepository
81 productService: ModulesSdkTypes.IMedusaInternalService<any, any>
82 productVariantService: ModulesSdkTypes.IMedusaInternalService<any, any>
83 productTagService: ModulesSdkTypes.IMedusaInternalService<any>
84 productCategoryService: ProductCategoryService
85 productCollectionService: ModulesSdkTypes.IMedusaInternalService<any>
86 productImageService: ModulesSdkTypes.IMedusaInternalService<any>
87 productImageProductService: ModulesSdkTypes.IMedusaInternalService<any>
88 productTypeService: ModulesSdkTypes.IMedusaInternalService<any>
89 productOptionService: ModulesSdkTypes.IMedusaInternalService<any>
90 productProductOptionService: ModulesSdkTypes.IMedusaInternalService<any>
91 productProductOptionValueService: ModulesSdkTypes.IMedusaInternalService<any>
92 productOptionValueService: ModulesSdkTypes.IMedusaInternalService<any>
93 productVariantProductImageService: ModulesSdkTypes.IMedusaInternalService<any>
94 [Modules.EVENT_BUS]?: IEventBusModuleService
95 }
96
97 export default class ProductModuleService
98 extends MedusaService<{
99 Product: {
100 dto: ProductTypes.ProductDTO
101 }
102 ProductCategory: {
103 dto: ProductTypes.ProductCategoryDTO
104 }
105 ProductCollection: {
106 dto: ProductTypes.ProductCollectionDTO
107 }
108 ProductOption: {
109 dto: ProductTypes.ProductOptionDTO
110 }
111 ProductOptionValue: {
112 dto: ProductTypes.ProductOptionValueDTO
113 }
114 ProductTag: {
115 dto: ProductTypes.ProductTagDTO
116 }
117 ProductType: {
118 dto: ProductTypes.ProductTypeDTO
119 }
120 ProductVariant: {
121 dto: ProductTypes.ProductVariantDTO
122 }
123 ProductImage: {
124 dto: ProductTypes.ProductImageDTO
125 }
126 ProductProductOption: {
127 dto: ProductTypes.ProductProductOptionDTO
128 }
129 }>({
130 Product,
131 ProductCategory,
132 ProductCollection,
133 ProductOption,
134 ProductOptionValue,
135 ProductTag,
136 ProductType,
137 ProductVariant,
138 ProductImage,
139 ProductProductOption,
140 })
141 implements ProductTypes.IProductModuleService
142 {
143 protected baseRepository_: DAL.RepositoryService
144 protected readonly productRepository_: ProductRepository
145 protected readonly productService_: ModulesSdkTypes.IMedusaInternalService<
146 InferEntityType<typeof Product>
147 >
148 protected readonly productVariantService_: ModulesSdkTypes.IMedusaInternalService<
149 InferEntityType<typeof ProductVariant>
150 >
151 protected readonly productCategoryService_: ProductCategoryService
152 protected readonly productTagService_: ModulesSdkTypes.IMedusaInternalService<
153 InferEntityType<typeof ProductTag>
154 >
155 protected readonly productCollectionService_: ModulesSdkTypes.IMedusaInternalService<
156 InferEntityType<typeof ProductCollection>
157 >
158 protected readonly productImageService_: ModulesSdkTypes.IMedusaInternalService<
159 InferEntityType<typeof ProductImage>
160 >
161 protected readonly productTypeService_: ModulesSdkTypes.IMedusaInternalService<
162 InferEntityType<typeof ProductType>
163 >
164 protected readonly productOptionService_: ModulesSdkTypes.IMedusaInternalService<
165 InferEntityType<typeof ProductOption>
166 >
167 protected readonly productOptionValueService_: ModulesSdkTypes.IMedusaInternalService<
168 InferEntityType<typeof ProductOptionValue>
169 >
170 protected readonly productProductOptionService_: ModulesSdkTypes.IMedusaInternalService<
171 InferEntityType<typeof ProductProductOption>
172 >
173 protected readonly productProductOptionValueService_: ModulesSdkTypes.IMedusaInternalService<
174 InferEntityType<typeof ProductProductOptionValue>
175 >
176 protected readonly productVariantProductImageService_: ModulesSdkTypes.IMedusaInternalService<
177 InferEntityType<typeof ProductVariantProductImage>
178 >
179 protected readonly eventBusModuleService_?: IEventBusModuleService
180
181 constructor(
182 {
183 baseRepository,
184 productRepository,
185 productService,
186 productVariantService,
187 productTagService,
188 productCategoryService,
189 productCollectionService,
190 productImageService,
191 productTypeService,
192 productOptionService,
193 productProductOptionService,
194 productProductOptionValueService,
195 productOptionValueService,
196 productVariantProductImageService,
197 [Modules.EVENT_BUS]: eventBusModuleService,
198 }: InjectedDependencies,
199 protected readonly moduleDeclaration: InternalModuleDeclaration
200 ) {
201 // @ts-ignore
202 // eslint-disable-next-line prefer-rest-params
203 super(...arguments)
204
205 this.baseRepository_ = baseRepository
206 this.productRepository_ = productRepository
207 this.productService_ = productService
208 this.productVariantService_ = productVariantService
209 this.productTagService_ = productTagService
210 this.productCategoryService_ = productCategoryService
211 this.productCollectionService_ = productCollectionService
212 this.productImageService_ = productImageService
213 this.productTypeService_ = productTypeService
214 this.productOptionService_ = productOptionService
215 this.productProductOptionService_ = productProductOptionService
216 this.productProductOptionValueService_ = productProductOptionValueService
217 this.productOptionValueService_ = productOptionValueService
218 this.productVariantProductImageService_ = productVariantProductImageService
219 this.eventBusModuleService_ = eventBusModuleService
220 }
221
222 __joinerConfig(): ModuleJoinerConfig {
223 return joinerConfig
224 }
225
226 @InjectManager()
227 // @ts-ignore
228 async retrieveProduct(
229 productId: string,
230 config?: FindConfig<ProductTypes.ProductDTO>,
231 @MedusaContext() sharedContext?: Context
232 ): Promise<ProductTypes.ProductDTO> {
233 const relationsSet = new Set(config?.relations ?? [])
234
235 relationsSet.delete("product_options")
236 relationsSet.delete("product_options.values")
237 relationsSet.delete("product_options.product_option")
238
239 const shouldLoadVariantImages = relationsSet.has("variants.images")
240 const shouldFilterOptionValues = relationsSet.has("options.values")
241
242 if (shouldLoadVariantImages) {
243 relationsSet.add("variants")
244 relationsSet.add("images")
245 }
246
247 if (shouldFilterOptionValues) {
248 relationsSet.add("options")
249 relationsSet.add("options.values")
250 }
251
252 const product = await this.productService_.retrieve(
253 productId,
254 this.getProductFindConfig_({
255 ...config,
256 relations: Array.from(relationsSet),
257 }),
258 sharedContext
259 )
260
261 const serializedProduct =
262 await this.baseRepository_.serialize<ProductTypes.ProductDTO>(product)
263
264 if (shouldLoadVariantImages) {
265 await this.assignImagesToVariants([serializedProduct], sharedContext)
266 }
267
268 if (shouldFilterOptionValues) {
269 await this.filterOptionValues(serializedProduct, sharedContext)
270 }
271
272 return serializedProduct
273 }
274
275 // @ts-ignore
276 async listProductTags(
277 filters?: ProductTypes.FilterableProductTagProps,
278 config?: FindConfig<ProductTypes.ProductTagDTO>,
279 sharedContext?: Context
280 ): Promise<ProductTypes.ProductTagDTO[]> {
281 const applied = applyPublishedProductsContext(filters, config)
282
283 return await super.listProductTags(
284 applied.filters,
285 applied.config,
286 sharedContext
287 )
288 }
289
290 // @ts-ignore
291 async listAndCountProductTags(
292 filters?: ProductTypes.FilterableProductTagProps,
293 config?: FindConfig<ProductTypes.ProductTagDTO>,
294 sharedContext?: Context
295 ): Promise<[ProductTypes.ProductTagDTO[], number]> {
296 const applied = applyPublishedProductsContext(filters, config)
297
298 return await super.listAndCountProductTags(
299 applied.filters,
300 applied.config,
301 sharedContext
302 )
303 }
304
305 // @ts-ignore
306 async listProductTypes(
307 filters?: ProductTypes.FilterableProductTypeProps,
308 config?: FindConfig<ProductTypes.ProductTypeDTO>,
309 sharedContext?: Context
310 ): Promise<ProductTypes.ProductTypeDTO[]> {
311 const applied = applyPublishedProductsContext(filters, config)
312
313 return await super.listProductTypes(
314 applied.filters,
315 applied.config,
316 sharedContext
317 )
318 }
319
320 // @ts-ignore
321 async listAndCountProductTypes(
322 filters?: ProductTypes.FilterableProductTypeProps,
323 config?: FindConfig<ProductTypes.ProductTypeDTO>,
324 sharedContext?: Context
325 ): Promise<[ProductTypes.ProductTypeDTO[], number]> {
326 const applied = applyPublishedProductsContext(filters, config)
327
328 return await super.listAndCountProductTypes(
329 applied.filters,
330 applied.config,
331 sharedContext
332 )
333 }
334
335 // @ts-ignore
336 async listProductCollections(
337 filters?: ProductTypes.FilterableProductCollectionProps,
338 config?: FindConfig<ProductTypes.ProductCollectionDTO>,
339 sharedContext?: Context
340 ): Promise<ProductTypes.ProductCollectionDTO[]> {
341 const applied = applyPublishedProductsContext(filters, config)
342
343 return await super.listProductCollections(
344 applied.filters,
345 applied.config,
346 sharedContext
347 )
348 }
349
350 // @ts-ignore
351 async listAndCountProductCollections(
352 filters?: ProductTypes.FilterableProductCollectionProps,
353 config?: FindConfig<ProductTypes.ProductCollectionDTO>,
354 sharedContext?: Context
355 ): Promise<[ProductTypes.ProductCollectionDTO[], number]> {
356 const applied = applyPublishedProductsContext(filters, config)
357
358 return await super.listAndCountProductCollections(
359 applied.filters,
360 applied.config,
361 sharedContext
362 )
363 }
364
365 // @ts-ignore
366 async listProductCategories(
367 filters?: ProductTypes.FilterableProductCategoryProps,
368 config?: FindConfig<ProductTypes.ProductCategoryDTO>,
369 sharedContext?: Context
370 ): Promise<ProductTypes.ProductCategoryDTO[]> {
371 const applied = applyPublishedProductsContext(filters, config)
372
373 return await super.listProductCategories(
374 applied.filters,
375 applied.config,
376 sharedContext
377 )
378 }
379
380 // @ts-ignore
381 async listAndCountProductCategories(
382 filters?: ProductTypes.FilterableProductCategoryProps,
383 config?: FindConfig<ProductTypes.ProductCategoryDTO>,
384 sharedContext?: Context
385 ): Promise<[ProductTypes.ProductCategoryDTO[], number]> {
386 const applied = applyPublishedProductsContext(filters, config)
387
388 return await super.listAndCountProductCategories(
389 applied.filters,
390 applied.config,
391 sharedContext
392 )
393 }
394
395 @InjectManager()
396 // @ts-ignore
397 async listProducts(
398 filters?: ProductTypes.FilterableProductProps,
399 config?: FindConfig<ProductTypes.ProductDTO>,
400 sharedContext?: Context
401 ): Promise<ProductTypes.ProductDTO[]> {
402 const { filters: normalizedFilters, shouldReturnEmpty } =
403 await this.applyOptionValueFilter_(filters, sharedContext)
404
405 if (shouldReturnEmpty) {
406 return []
407 }
408
409 const relationsSet = new Set(config?.relations ?? [])
410 const shouldLoadVariantImages = relationsSet.has("variants.images")
411 if (shouldLoadVariantImages) {
412 relationsSet.add("variants")
413 relationsSet.add("images")
414 }
415
416 const shouldFilterOptionValues = relationsSet.has("options.values")
417
418 if (shouldFilterOptionValues) {
419 relationsSet.add("options")
420 relationsSet.add("options.values")
421 }
422
423 const products = await this.productService_.list(
424 normalizedFilters,
425 this.getProductFindConfig_({
426 ...config,
427 relations: Array.from(relationsSet),
428 }),
429 sharedContext
430 )
431
432 const serializedProducts = await this.baseRepository_.serialize<
433 ProductTypes.ProductDTO[]
434 >(products)
435
436 if (shouldLoadVariantImages) {
437 await this.assignImagesToVariants(serializedProducts, sharedContext)
438 }
439
440 if (shouldFilterOptionValues) {
441 await this.filterOptionValues(serializedProducts, sharedContext)
442 }
443
444 return serializedProducts
445 }
446
447 @InjectManager()
448 // @ts-ignore
449 async listAndCountProducts(
450 filters?: ProductTypes.FilterableProductProps,
451 config?: FindConfig<ProductTypes.ProductDTO>,
452 sharedContext?: Context
453 ): Promise<[ProductTypes.ProductDTO[], number]> {
454 const { filters: normalizedFilters, shouldReturnEmpty } =
455 await this.applyOptionValueFilter_(filters, sharedContext)
456
457 if (shouldReturnEmpty) {
458 return [[], 0]
459 }
460
461 const shouldLoadVariantImages =
462 config?.relations?.includes("variants.images")
463 const shouldFilterOptionValues =
464 config?.relations?.includes("options.values")
465
466 // Ensure we load necessary relations
467 let relations = [...(config?.relations || [])]
468 relations = relations.filter(
469 (relation) =>
470 relation !== "product_options" &&
471 relation !== "product_options.values" &&
472 relation !== "product_options.product_option"
473 )
474 if (shouldLoadVariantImages) {
475 if (!relations.includes("variants")) {
476 relations.push("variants")
477 }
478 if (!relations.includes("images")) {
479 relations.push("images")
480 }
481 }
482
483 if (shouldFilterOptionValues) {
484 if (!relations.includes("options")) {
485 relations.push("options")
486 }
487 if (!relations.includes("options.values")) {
488 relations.push("options.values")
489 }
490 }
491
492 const [products, count] = await this.productService_.listAndCount(
493 normalizedFilters,
494 this.getProductFindConfig_({ ...config, relations }),
495 sharedContext
496 )
497
498 const serializedProducts = await this.baseRepository_.serialize<
499 ProductTypes.ProductDTO[]
500 >(products)
501
502 if (shouldLoadVariantImages) {
503 await this.assignImagesToVariants(serializedProducts, sharedContext)
504 }
505
506 if (shouldFilterOptionValues) {
507 await this.filterOptionValues(serializedProducts, sharedContext)
508 }
509
510 return [serializedProducts, count]
511 }
512
513 protected async applyOptionValueFilter_(
514 filters?: ProductTypes.FilterableProductProps,
515 sharedContext?: Context
516 ): Promise<{
517 filters?: ProductTypes.FilterableProductProps
518 shouldReturnEmpty: boolean
519 }> {
520 if (!filters?.option_value_id) {
521 return {
522 filters: filters,
523 shouldReturnEmpty: false,
524 }
525 }
526
527 const optionValueIds = Array.isArray(filters.option_value_id)
528 ? filters.option_value_id
529 : [filters.option_value_id]
530
531 if (!optionValueIds.length) {
532 return {
533 filters: filters,
534 shouldReturnEmpty: false,
535 }
536 }
537
538 const optionValueFilter = await buildOptionValueFilterQuery(
539 optionValueIds,
540 sharedContext
541 )
542
543 if (!optionValueFilter) {
544 return {
545 filters: filters,
546 shouldReturnEmpty: true,
547 }
548 }
549
550 const { option_value_id, ...restFilters } = filters
551
552 return {
553 filters: {
554 ...restFilters,
555 ...optionValueFilter,
556 },
557 shouldReturnEmpty: false,
558 }
559 }
560
561 protected getProductFindConfig_(
562 config?: FindConfig<ProductTypes.ProductDTO>
563 ): FindConfig<ProductTypes.ProductDTO> {
564 const hasImagesRelation = config?.relations?.includes("images")
565
566 return {
567 ...config,
568 order: {
569 ...(config?.order ?? { id: "ASC" }),
570 ...(hasImagesRelation
571 ? {
572 images: {
573 rank: "ASC",
574 ...((config?.order?.images as object) ?? {}),
575 },
576 }
577 : {}),
578 },
579 }
580 }
581
582 // @ts-expect-error
583 createProductVariants(
584 data: ProductTypes.CreateProductVariantDTO[],
585 sharedContext?: Context
586 ): Promise<ProductTypes.ProductVariantDTO[]>
587 // @ts-expect-error
588 createProductVariants(
589 data: ProductTypes.CreateProductVariantDTO,
590 sharedContext?: Context
591 ): Promise<ProductTypes.ProductVariantDTO>
592
593 @InjectManager()
594 @EmitEvents()
595 // @ts-expect-error
596 async createProductVariants(
597 data:
598 | ProductTypes.CreateProductVariantDTO[]
599 | ProductTypes.CreateProductVariantDTO,
600 @MedusaContext() sharedContext: Context = {}
601 ): Promise<
602 ProductTypes.ProductVariantDTO[] | ProductTypes.ProductVariantDTO
603 > {
604 const input = Array.isArray(data) ? data : [data]
605
606 const variants = await this.createVariants_(input, sharedContext)
607
608 const createdVariants = await this.baseRepository_.serialize<
609 ProductTypes.ProductVariantDTO[]
610 >(variants)
611
612 return Array.isArray(data) ? createdVariants : createdVariants[0]
613 }
614
615 @InjectTransactionManager()
616 protected async createVariants_(
617 data: ProductTypes.CreateProductVariantDTO[],
618 @MedusaContext() sharedContext: Context = {}
619 ): Promise<InferEntityType<typeof ProductVariant>[]> {
620 if (data.some((v) => !v.product_id)) {
621 throw new MedusaError(
622 MedusaError.Types.INVALID_DATA,
623 "Unable to create variants without specifying a product_id"
624 )
625 }
626
627 const productIds = [...new Set<string>(data.map((v) => v.product_id!))]
628 const [variants, { optionsByProductId, valueIdsByProductId }] =
629 await promiseAll([
630 this.productVariantService_.list(
631 { product_id: productIds },
632 { relations: ["options"] },
633 sharedContext
634 ),
635 this.loadOptionsAndValuesByProductId_(productIds, sharedContext),
636 ])
637
638 const productVariantsWithOptions =
639 ProductModuleService.assignOptionsToVariants(
640 data,
641 optionsByProductId,
642 valueIdsByProductId
643 )
644
645 ProductModuleService.checkIfVariantWithOptionsAlreadyExists(
646 productVariantsWithOptions as any,
647 variants
648 )
649
650 const createdVariants = await this.productVariantService_.create(
651 productVariantsWithOptions,
652 sharedContext
653 )
654
655 return createdVariants
656 }
657
658 async upsertProductVariants(
659 data: ProductTypes.UpsertProductVariantDTO[],
660 sharedContext?: Context
661 ): Promise<ProductTypes.ProductVariantDTO[]>
662 async upsertProductVariants(
663 data: ProductTypes.UpsertProductVariantDTO,
664 sharedContext?: Context
665 ): Promise<ProductTypes.ProductVariantDTO>
666
667 @InjectTransactionManager()
668 @EmitEvents()
669 async upsertProductVariants(
670 data:
671 | ProductTypes.UpsertProductVariantDTO[]
672 | ProductTypes.UpsertProductVariantDTO,
673 @MedusaContext() sharedContext: Context = {}
674 ): Promise<
675 ProductTypes.ProductVariantDTO[] | ProductTypes.ProductVariantDTO
676 > {
677 const input = Array.isArray(data) ? data : [data]
678 const forUpdate = input.filter(
679 (variant): variant is UpdateProductVariantInput => !!variant.id
680 )
681 const forCreate = input.filter(
682 (variant): variant is ProductTypes.CreateProductVariantDTO => !variant.id
683 )
684
685 let created: ProductTypes.ProductVariantDTO[] = []
686 let updated: InferEntityType<typeof ProductVariant>[] = []
687
688 if (forCreate.length) {
689 created = await this.createProductVariants(forCreate, sharedContext)
690 }
691 if (forUpdate.length) {
692 updated = await this.updateVariants_(forUpdate, sharedContext)
693 }
694
695 const result = [...created, ...updated]
696 const allVariants = await this.baseRepository_.serialize<
697 ProductTypes.ProductVariantDTO[] | ProductTypes.ProductVariantDTO
698 >(result)
699
700 return Array.isArray(data) ? allVariants : allVariants[0]
701 }
702
703 // @ts-expect-error
704 updateProductVariants(
705 id: string,
706 data: ProductTypes.UpdateProductVariantDTO,
707 sharedContext?: Context
708 ): Promise<ProductTypes.ProductVariantDTO>
709 // @ts-expect-error
710 updateProductVariants(
711 selector: ProductTypes.FilterableProductVariantProps,
712 data: ProductTypes.UpdateProductVariantDTO,
713 sharedContext?: Context
714 ): Promise<ProductTypes.ProductVariantDTO[]>
715
716 @InjectManager()
717 @EmitEvents()
718 // @ts-expect-error
719 async updateProductVariants(
720 idOrSelector: string | ProductTypes.FilterableProductVariantProps,
721 data: ProductTypes.UpdateProductVariantDTO,
722 @MedusaContext() sharedContext: Context = {}
723 ): Promise<
724 ProductTypes.ProductVariantDTO[] | ProductTypes.ProductVariantDTO
725 > {
726 let normalizedInput: UpdateProductVariantInput[] = []
727 if (isString(idOrSelector)) {
728 normalizedInput = [{ id: idOrSelector, ...data }]
729 } else {
730 const variants = await this.productVariantService_.list(
731 idOrSelector,
732 {},
733 sharedContext
734 )
735
736 normalizedInput = variants.map((variant) => ({
737 id: variant.id,
738 ...data,
739 }))
740 }
741
742 const variants = await this.updateVariants_(normalizedInput, sharedContext)
743
744 const updatedVariants = await this.baseRepository_.serialize<
745 ProductTypes.ProductVariantDTO[]
746 >(variants)
747
748 return isString(idOrSelector) ? updatedVariants[0] : updatedVariants
749 }
750
751 @InjectTransactionManager()
752 protected async updateVariants_(
753 data: UpdateProductVariantInput[],
754 @MedusaContext() sharedContext: Context = {}
755 ): Promise<InferEntityType<typeof ProductVariant>[]> {
756 // Whether any variant in this batch is changing its options. The option
757 // resolution + uniqueness validation + relation reconcile below are ONLY
758 // needed in that case. When no variant carries `options`, all of that work is
759 // dead weight — and on a product with a large number of variants it is very
760 // expensive (see below), so we skip it.
761 const hasOptions = data.some((d) => !!d.options)
762
763 // Validation step
764 const variantIdsToUpdate = data.map(({ id }) => id)
765 const variants = await this.productVariantService_.list(
766 { id: variantIdsToUpdate },
767 {},
768 sharedContext
769 )
770
771 if (variants.length !== data.length) {
772 throw new MedusaError(
773 MedusaError.Types.INVALID_DATA,
774 `Cannot update non-existing variants with ids: ${arrayDifference(
775 variantIdsToUpdate,
776 variants.map(({ id }) => id)
777 ).join(", ")}`
778 )
779 }
780
781 // Data normalization
782 const variantsWithProductId: UpdateProductVariantInput[] = variants.map(
783 (variant) => {
784 const update = data.find(({ id }) => id === variant.id)!
785
786 return {
787 ...update,
788 id: variant.id,
789 product_id: variant.product_id,
790 ...(isPresent(update.metadata)
791 ? {
792 metadata: mergeMetadata(
793 variant.metadata ?? {},
794 update.metadata!
795 ),
796 }
797 : {}),
798 }
799 }
800 )
801
802 let productVariantsWithOptions: UpdateProductVariantInput[] =
803 variantsWithProductId
804
805 if (hasOptions) {
806 // Loading EVERY variant of the affected products (with their options) and
807 // the option-tuple uniqueness scan are O(product's total variant count) and
808 // synchronous. They are only required to validate that an options change
809 // does not create a duplicate option combination — so only run them when an
810 // options change is actually being made. For products with many variants
811 // (thousands), doing this unconditionally on a scalar-only update blocks the
812 // event loop for tens of seconds.
813 const allVariants = await this.productVariantService_.list(
814 { product_id: variants.map((v) => v.product_id) },
815 { relations: ["options"] },
816 sharedContext
817 )
818
819 const productIds = Array.from(
820 new Set(variantsWithProductId.map((v) => v.product_id!))
821 )
822 const { optionsByProductId, valueIdsByProductId } =
823 await this.loadOptionsAndValuesByProductId_(productIds, sharedContext)
824
825 productVariantsWithOptions = ProductModuleService.assignOptionsToVariants(
826 variantsWithProductId,
827 optionsByProductId,
828 valueIdsByProductId
829 ) as UpdateProductVariantInput[]
830
831 ProductModuleService.checkIfVariantWithOptionsAlreadyExists(
832 productVariantsWithOptions as any,
833 allVariants
834 )
835 }
836
837 const { entities: productVariants } =
838 await this.productVariantService_.upsertWithReplace(
839 productVariantsWithOptions,
840 {
841 // Only reconcile the options relation when options are actually being
842 // updated. With no options in the payload the relation loop is a no-op
843 // for these entries anyway, so this avoids the relation setup entirely.
844 relations: hasOptions ? ["options"] : [],
845 },
846 sharedContext
847 )
848
849 return productVariants
850 }
851
852 // @ts-expect-error
853 createProductTags(
854 data: ProductTypes.CreateProductTagDTO[],
855 sharedContext?: Context
856 ): Promise<ProductTypes.ProductTagDTO[]>
857 // @ts-expect-error
858 createProductTags(
859 data: ProductTypes.CreateProductTagDTO,
860 sharedContext?: Context
861 ): Promise<ProductTypes.ProductTagDTO>
862
863 @InjectManager()
864 @EmitEvents()
865 // @ts-expect-error
866 async createProductTags(
867 data: ProductTypes.CreateProductTagDTO[] | ProductTypes.CreateProductTagDTO,
868 @MedusaContext() sharedContext: Context = {}
869 ): Promise<ProductTypes.ProductTagDTO[] | ProductTypes.ProductTagDTO> {
870 const input = Array.isArray(data) ? data : [data]
871
872 const tags = await this.productTagService_.create(input, sharedContext)
873
874 const createdTags = await this.baseRepository_.serialize<
875 ProductTypes.ProductTagDTO[]
876 >(tags)
877
878 return Array.isArray(data) ? createdTags : createdTags[0]
879 }
880
881 async upsertProductTags(
882 data: ProductTypes.UpsertProductTagDTO[],
883 sharedContext?: Context
884 ): Promise<ProductTypes.ProductTagDTO[]>
885 async upsertProductTags(
886 data: ProductTypes.UpsertProductTagDTO,
887 sharedContext?: Context
888 ): Promise<ProductTypes.ProductTagDTO>
889
890 @InjectManager()
891 @EmitEvents()
892 async upsertProductTags(
893 data: ProductTypes.UpsertProductTagDTO[] | ProductTypes.UpsertProductTagDTO,
894 @MedusaContext() sharedContext: Context = {}
895 ): Promise<ProductTypes.ProductTagDTO[] | ProductTypes.ProductTagDTO> {
896 const tags = await this.upsertProductTags_(data, sharedContext)
897
898 const allTags = await this.baseRepository_.serialize<
899 ProductTypes.ProductTagDTO[] | ProductTypes.ProductTagDTO
900 >(Array.isArray(data) ? tags : tags[0])
901
902 return allTags
903 }
904
905 @InjectTransactionManager()
906 protected async upsertProductTags_(
907 data: ProductTypes.UpsertProductTagDTO[] | ProductTypes.UpsertProductTagDTO,
908 @MedusaContext() sharedContext: Context = {}
909 ): Promise<InferEntityType<typeof ProductTag>[]> {
910 const input = Array.isArray(data) ? data : [data]
911 const forUpdate = input.filter((tag): tag is UpdateTagInput => !!tag.id)
912 const forCreate = input.filter(
913 (tag): tag is ProductTypes.CreateProductTagDTO => !tag.id
914 )
915
916 let created: InferEntityType<typeof ProductTag>[] = []
917 let updated: InferEntityType<typeof ProductTag>[] = []
918
919 if (forCreate.length) {
920 created = await this.productTagService_.create(forCreate, sharedContext)
921 }
922 if (forUpdate.length) {
923 updated = await this.productTagService_.update(forUpdate, sharedContext)
924 }
925
926 return [...created, ...updated]
927 }
928
929 // @ts-expect-error
930 updateProductTags(
931 id: string,
932 data: ProductTypes.UpdateProductTagDTO,
933 sharedContext?: Context
934 ): Promise<ProductTypes.ProductTagDTO>
935 // @ts-expect-error
936 updateProductTags(
937 selector: ProductTypes.FilterableProductTagProps,
938 data: ProductTypes.UpdateProductTagDTO,
939 sharedContext?: Context
940 ): Promise<ProductTypes.ProductTagDTO[]>
941
942 @InjectManager()
943 @EmitEvents()
944 // @ts-expect-error
945 async updateProductTags(
946 idOrSelector: string | ProductTypes.FilterableProductTagProps,
947 data: ProductTypes.UpdateProductTagDTO,
948 @MedusaContext() sharedContext: Context = {}
949 ): Promise<ProductTypes.ProductTagDTO[] | ProductTypes.ProductTagDTO> {
950 let normalizedInput: UpdateTagInput[] = []
951 if (isString(idOrSelector)) {
952 // Check if the tag exists in the first place
953 await this.productTagService_.retrieve(idOrSelector, {}, sharedContext)
954 normalizedInput = [{ id: idOrSelector, ...data }]
955 } else {
956 const tags = await this.productTagService_.list(
957 idOrSelector,
958 {},
959 sharedContext
960 )
961
962 normalizedInput = tags.map((tag) => ({
963 id: tag.id,
964 ...data,
965 }))
966 }
967
968 const tags = await this.productTagService_.update(
969 normalizedInput,
970 sharedContext
971 )
972
973 const updatedTags = await this.baseRepository_.serialize<
974 ProductTypes.ProductTagDTO[]
975 >(tags)
976
977 return isString(idOrSelector) ? updatedTags[0] : updatedTags
978 }
979
980 // @ts-expect-error
981 createProductTypes(
982 data: ProductTypes.CreateProductTypeDTO[],
983 sharedContext?: Context
984 ): Promise<ProductTypes.ProductTypeDTO[]>
985 // @ts-expect-error
986 createProductTypes(
987 data: ProductTypes.CreateProductTypeDTO,
988 sharedContext?: Context
989 ): Promise<ProductTypes.ProductTypeDTO>
990
991 @InjectManager()
992 @EmitEvents()
993 // @ts-expect-error
994 async createProductTypes(
995 data:
996 | ProductTypes.CreateProductTypeDTO[]
997 | ProductTypes.CreateProductTypeDTO,
998 @MedusaContext() sharedContext: Context = {}
999 ): Promise<ProductTypes.ProductTypeDTO[] | ProductTypes.ProductTypeDTO> {
1000 const input = Array.isArray(data) ? data : [data]
1001
1002 const types = await this.productTypeService_.create(input, sharedContext)
1003
1004 const createdTypes = await this.baseRepository_.serialize<
1005 ProductTypes.ProductTypeDTO[]
1006 >(types)
1007
1008 return Array.isArray(data) ? createdTypes : createdTypes[0]
1009 }
1010
1011 async upsertProductTypes(
1012 data: ProductTypes.UpsertProductTypeDTO[],
1013 sharedContext?: Context
1014 ): Promise<ProductTypes.ProductTypeDTO[]>
1015 async upsertProductTypes(
1016 data: ProductTypes.UpsertProductTypeDTO,
1017 sharedContext?: Context
1018 ): Promise<ProductTypes.ProductTypeDTO>
1019
1020 @InjectManager()
1021 @EmitEvents()
1022 async upsertProductTypes(
1023 data:
1024 | ProductTypes.UpsertProductTypeDTO[]
1025 | ProductTypes.UpsertProductTypeDTO,
1026 @MedusaContext() sharedContext: Context = {}
1027 ): Promise<ProductTypes.ProductTypeDTO[] | ProductTypes.ProductTypeDTO> {
1028 const types = await this.upsertProductTypes_(data, sharedContext)
1029
1030 const result = await this.baseRepository_.serialize<
1031 ProductTypes.ProductTypeDTO[] | ProductTypes.ProductTypeDTO
1032 >(types)
1033
1034 return Array.isArray(data) ? result : result[0]
1035 }
1036
1037 @InjectTransactionManager()
1038 protected async upsertProductTypes_(
1039 data:
1040 | ProductTypes.UpsertProductTypeDTO
1041 | ProductTypes.UpsertProductTypeDTO[],
1042 sharedContext?: Context
1043 ): Promise<InferEntityType<typeof ProductType>[]> {
1044 const input = Array.isArray(data) ? data : [data]
1045 const forUpdate = input.filter((type): type is UpdateTypeInput => !!type.id)
1046 const forCreate = input.filter(
1047 (type): type is ProductTypes.CreateProductTypeDTO => !type.id
1048 )
1049
1050 let created: InferEntityType<typeof ProductType>[] = []
1051 let updated: InferEntityType<typeof ProductType>[] = []
1052
1053 if (forCreate.length) {
1054 created = await this.productTypeService_.create(forCreate, sharedContext)
1055 }
1056 if (forUpdate.length) {
1057 updated = await this.productTypeService_.update(forUpdate, sharedContext)
1058 }
1059
1060 return [...created, ...updated]
1061 }
1062
1063 // @ts-expect-error
1064 updateProductTypes(
1065 id: string,
1066 data: ProductTypes.UpdateProductTypeDTO,
1067 sharedContext?: Context
1068 ): Promise<ProductTypes.ProductTypeDTO>
1069 // @ts-expect-error
1070 updateProductTypes(
1071 selector: ProductTypes.FilterableProductTypeProps,
1072 data: ProductTypes.UpdateProductTypeDTO,
1073 sharedContext?: Context
1074 ): Promise<ProductTypes.ProductTypeDTO[]>
1075
1076 @InjectManager()
1077 @EmitEvents()
1078 // @ts-expect-error
1079 async updateProductTypes(
1080 idOrSelector: string | ProductTypes.FilterableProductTypeProps,
1081 data: ProductTypes.UpdateProductTypeDTO,
1082 @MedusaContext() sharedContext: Context = {}
1083 ): Promise<ProductTypes.ProductTypeDTO[] | ProductTypes.ProductTypeDTO> {
1084 let normalizedInput: UpdateTypeInput[] = []
1085 if (isString(idOrSelector)) {
1086 // Check if the type exists in the first place
1087 await this.productTypeService_.retrieve(idOrSelector, {}, sharedContext)
1088 normalizedInput = [{ id: idOrSelector, ...data }]
1089 } else {
1090 const types = await this.productTypeService_.list(
1091 idOrSelector,
1092 {},
1093 sharedContext
1094 )
1095
1096 normalizedInput = types.map((type) => ({
1097 id: type.id,
1098 ...data,
1099 }))
1100 }
1101
1102 const types = await this.productTypeService_.update(
1103 normalizedInput,
1104 sharedContext
1105 )
1106
1107 const updatedTypes = await this.baseRepository_.serialize<
1108 ProductTypes.ProductTypeDTO[]
1109 >(types)
1110
1111 return isString(idOrSelector) ? updatedTypes[0] : updatedTypes
1112 }
1113
1114 // @ts-expect-error
1115 createProductOptions(
1116 data: ProductTypes.CreateProductOptionDTO[],
1117 sharedContext?: Context
1118 ): Promise<ProductTypes.ProductOptionDTO[]>
1119 // @ts-expect-error
1120 createProductOptions(
1121 data: ProductTypes.CreateProductOptionDTO,
1122 sharedContext?: Context
1123 ): Promise<ProductTypes.ProductOptionDTO>
1124
1125 @InjectManager()
1126 @EmitEvents()
1127 // @ts-expect-error
1128 async createProductOptions(
1129 data:
1130 | ProductTypes.CreateProductOptionDTO[]
1131 | ProductTypes.CreateProductOptionDTO,
1132 @MedusaContext() sharedContext: Context = {}
1133 ): Promise<ProductTypes.ProductOptionDTO[] | ProductTypes.ProductOptionDTO> {
1134 const input = Array.isArray(data) ? data : [data]
1135
1136 const options = await this.createOptions_(input, sharedContext)
1137
1138 const createdOptions = await this.baseRepository_.serialize<
1139 ProductTypes.ProductOptionDTO[]
1140 >(options)
1141
1142 return Array.isArray(data) ? createdOptions : createdOptions[0]
1143 }
1144
1145 @InjectTransactionManager()
1146 protected async createOptions_(
1147 data: ProductTypes.CreateProductOptionDTO[],
1148 @MedusaContext() sharedContext: Context = {}
1149 ): Promise<InferEntityType<typeof ProductOption>[]> {
1150 const normalizedInput = data.map((opt) => {
1151 Object.keys(opt.ranks ?? []).forEach((value) => {
1152 if (!opt.values.includes(value)) {
1153 throw new MedusaError(
1154 MedusaError.Types.INVALID_DATA,
1155 `Value "${value}" is assigned a rank but is not defined in the list of values.`
1156 )
1157 }
1158 })
1159
1160 return {
1161 ...opt,
1162 values: opt.values?.map((v) => {
1163 // Normalize each value into an object and attach rank if available
1164 const valueObj = isString(v) ? { value: v } : v
1165 const rank =
1166 opt.ranks && isString(v)
1167 ? opt.ranks[v]
1168 : opt.ranks?.[valueObj.value]
1169
1170 return rank !== undefined ? { ...valueObj, rank } : valueObj
1171 }),
1172 }
1173 })
1174
1175 return this.productOptionService_.create(normalizedInput, sharedContext)
1176 }
1177
1178 async upsertProductOptions(
1179 data: ProductTypes.UpsertProductOptionDTO[],
1180 sharedContext?: Context
1181 ): Promise<ProductTypes.ProductOptionDTO[]>
1182 async upsertProductOptions(
1183 data: ProductTypes.UpsertProductOptionDTO,
1184 sharedContext?: Context
1185 ): Promise<ProductTypes.ProductOptionDTO>
1186
1187 @InjectTransactionManager()
1188 @EmitEvents()
1189 async upsertProductOptions(
1190 data:
1191 | ProductTypes.UpsertProductOptionDTO[]
1192 | ProductTypes.UpsertProductOptionDTO,
1193 @MedusaContext() sharedContext: Context = {}
1194 ): Promise<ProductTypes.ProductOptionDTO[] | ProductTypes.ProductOptionDTO> {
1195 const input = Array.isArray(data) ? data : [data]
1196 const forUpdate = input.filter(
1197 (option): option is UpdateProductOptionInput => !!option.id
1198 )
1199 const forCreate = input.filter(
1200 (option): option is ProductTypes.CreateProductOptionDTO => !option.id
1201 )
1202
1203 let created: InferEntityType<typeof ProductOption>[] = []
1204 let updated: InferEntityType<typeof ProductOption>[] = []
1205
1206 if (forCreate.length) {
1207 created = await this.createOptions_(forCreate, sharedContext)
1208 }
1209 if (forUpdate.length) {
1210 updated = await this.updateOptions_(forUpdate, sharedContext)
1211 }
1212
1213 const result = [...created, ...updated]
1214 const allOptions = await this.baseRepository_.serialize<
1215 ProductTypes.ProductOptionDTO[] | ProductTypes.ProductOptionDTO
1216 >(result)
1217
1218 return Array.isArray(data) ? allOptions : allOptions[0]
1219 }
1220
1221 // @ts-expect-error
1222 updateProductOptions(
1223 id: string,
1224 data: ProductTypes.UpdateProductOptionDTO,
1225 sharedContext?: Context
1226 ): Promise<ProductTypes.ProductOptionDTO>
1227 // @ts-expect-error
1228 updateProductOptions(
1229 selector: ProductTypes.FilterableProductOptionProps,
1230 data: ProductTypes.UpdateProductOptionDTO,
1231 sharedContext?: Context
1232 ): Promise<ProductTypes.ProductOptionDTO[]>
1233
1234 @InjectManager()
1235 @EmitEvents()
1236 // @ts-expect-error
1237 async updateProductOptions(
1238 idOrSelector: string | ProductTypes.FilterableProductOptionProps,
1239 data: ProductTypes.UpdateProductOptionDTO,
1240 @MedusaContext() sharedContext: Context = {}
1241 ): Promise<ProductTypes.ProductOptionDTO[] | ProductTypes.ProductOptionDTO> {
1242 let normalizedInput: UpdateProductOptionInput[] = []
1243 if (isString(idOrSelector)) {
1244 const option = await this.productOptionService_.retrieve(
1245 idOrSelector,
1246 {},
1247 sharedContext
1248 )
1249 normalizedInput = [{ id: idOrSelector, ...data }]
1250
1251 if (data.is_exclusive && option.is_exclusive === false) {
1252 // disable changing global option to exclusive
1253 throw new MedusaError(
1254 MedusaError.Types.INVALID_DATA,
1255 `Cannot change product option: ${option.id} from global to exclusive.`
1256 )
1257 }
1258 } else {
1259 const options = await this.productOptionService_.list(
1260 idOrSelector,
1261 {},
1262 sharedContext
1263 )
1264
1265 normalizedInput = options.map((option) => {
1266 if (data.is_exclusive && option.is_exclusive === false) {
1267 throw new MedusaError(
1268 MedusaError.Types.INVALID_DATA,
1269 `Cannot change product option: ${option.id} from global to exclusive.`
1270 )
1271 }
1272
1273 return {
1274 id: option.id,
1275 ...data,
1276 }
1277 })
1278 }
1279
1280 const options = await this.updateOptions_(normalizedInput, sharedContext)
1281
1282 const updatedOptions = await this.baseRepository_.serialize<
1283 ProductTypes.ProductOptionDTO[]
1284 >(options)
1285
1286 return isString(idOrSelector) ? updatedOptions[0] : updatedOptions
1287 }
1288
1289 @InjectTransactionManager()
1290 protected async updateOptions_(
1291 data: UpdateProductOptionInput[],
1292 @MedusaContext() sharedContext: Context = {}
1293 ): Promise<InferEntityType<typeof ProductOption>[]> {
1294 // Validation step
1295 if (data.some((option) => !option.id)) {
1296 throw new MedusaError(
1297 MedusaError.Types.INVALID_DATA,
1298 "Tried to update options without specifying an ID"
1299 )
1300 }
1301
1302 const dbOptions = await this.productOptionService_.list(
1303 { id: data.map(({ id }) => id) },
1304 { relations: ["values"] },
1305 sharedContext
1306 )
1307
1308 if (dbOptions.length !== data.length) {
1309 throw new MedusaError(
1310 MedusaError.Types.INVALID_DATA,
1311 `Cannot update non-existing options with ids: ${arrayDifference(
1312 data.map(({ id }) => id),
1313 dbOptions.map(({ id }) => id)
1314 ).join(", ")}`
1315 )
1316 }
1317
1318 const dbOptionsMap = new Map<string, InferEntityType<typeof ProductOption>>(
1319 dbOptions.map((option) => [option.id, option])
1320 )
1321
1322 // Check if any option values are being removed and if they're associated with products
1323 const removedValueIds = new Set<string>()
1324 for (const opt of data) {
1325 if (!isDefined(opt.values)) {
1326 continue
1327 }
1328
1329 const dbOption = dbOptionsMap.get(opt.id)
1330
1331 if (!dbOption) {
1332 continue
1333 }
1334
1335 const newValues = new Set<string>(
1336 opt.values.map((v) => {
1337 if (isString(v)) {
1338 return v
1339 }
1340 return (v as any).value
1341 })
1342 )
1343
1344 for (const existingValue of dbOption.values || []) {
1345 if (!newValues.has(existingValue.value)) {
1346 removedValueIds.add(existingValue.id)
1347 }
1348 }
1349 }
1350
1351 await this.validateOptionValuesNotAssociatedWithProducts_(
1352 [...removedValueIds],
1353 sharedContext
1354 )
1355
1356 // Data normalization
1357 const normalizedInput = data.map((opt) => {
1358 const dbOption = dbOptions.find(({ id }) => id === opt.id)
1359 const dbValues = dbOption?.values || []
1360
1361 if (opt.ranks) {
1362 const validValues = opt.values ?? dbValues.map((v) => v.value)
1363
1364 Object.keys(opt.ranks).forEach((value) => {
1365 if (!validValues.includes(value)) {
1366 throw new MedusaError(
1367 MedusaError.Types.INVALID_DATA,
1368 `Value "${value}" is assigned a rank but is not defined in the list of values.`
1369 )
1370 }
1371 })
1372 }
1373
1374 let normalizedValues
1375 if (opt.values) {
1376 // If new values are provided → normalize and apply ranks
1377 normalizedValues = opt.values.map((v) => {
1378 const valueObj = isString(v) ? { value: v } : v
1379
1380 const rank =
1381 opt.ranks && isString(v)
1382 ? opt.ranks[v]
1383 : opt.ranks?.[valueObj.value]
1384
1385 const rankedValue =
1386 rank !== undefined ? { ...valueObj, rank } : valueObj
1387
1388 if ("id" in rankedValue) {
1389 return rankedValue
1390 }
1391
1392 const dbVal = dbValues.find(
1393 (dbVal) => dbVal.value === rankedValue.value
1394 )
1395 if (!dbVal) {
1396 return rankedValue
1397 }
1398
1399 return {
1400 id: dbVal.id,
1401 ...rankedValue,
1402 }
1403 })
1404 } else if (opt.ranks) {
1405 // If only ranks were provided → update existing DB values with ranks
1406 normalizedValues = dbValues.map((dbVal) => {
1407 const rank = opt.ranks![dbVal.value]
1408 return rank !== undefined
1409 ? { id: dbVal.id, value: dbVal.value, rank }
1410 : { id: dbVal.id, value: dbVal.value }
1411 })
1412 }
1413
1414 const { ranks, ...cleanOpt } = opt
1415 return {
1416 ...cleanOpt,
1417 ...(normalizedValues ? { values: normalizedValues } : {}),
1418 } as UpdateProductOptionInput
1419 })
1420
1421 const { entities: productOptions } =
1422 await this.productOptionService_.upsertWithReplace(
1423 normalizedInput,
1424 { relations: ["values"] },
1425 sharedContext
1426 )
1427
1428 return productOptions
1429 }
1430
1431 /**
1432 * Guards against removing product option values that are still associated
1433 * with products. Shared by the option update flow (when values are removed)
1434 * and the option value deletion flow.
1435 */
1436 protected async validateOptionValuesNotAssociatedWithProducts_(
1437 valueIds: string[],
1438 @MedusaContext() sharedContext: Context = {}
1439 ): Promise<void> {
1440 if (!valueIds.length) {
1441 return
1442 }
1443
1444 const productProductOptionValues =
1445 await this.productProductOptionValueService_.list(
1446 {
1447 product_option_value_id: valueIds,
1448 },
1449 {
1450 select: ["id"],
1451 take: 1,
1452 },
1453 sharedContext
1454 )
1455
1456 if (productProductOptionValues.length > 0) {
1457 throw new MedusaError(
1458 MedusaError.Types.INVALID_DATA,
1459 "Cannot delete product option values that are associated with products."
1460 )
1461 }
1462 }
1463
1464 @InjectManager()
1465 // @ts-expect-error
1466 async softDeleteProductOptions<
1467 TReturnableLinkableKeys extends string = string
1468 >(
1469 primaryKeyValues: string | object | string[] | object[],
1470 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
1471 @MedusaContext() sharedContext: Context = {}
1472 ): Promise<Record<string, string[]> | void> {
1473 return await this.softDeleteProductOptions_(
1474 primaryKeyValues,
1475 config,
1476 sharedContext
1477 )
1478 }
1479
1480 @InjectTransactionManager()
1481 protected async softDeleteProductOptions_<
1482 TReturnableLinkableKeys extends string = string
1483 >(
1484 primaryKeyValues: string | object | string[] | object[],
1485 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
1486 @MedusaContext() sharedContext: Context = {}
1487 ): Promise<Record<string, string[]> | void> {
1488 const optionIds = Array.isArray(primaryKeyValues)
1489 ? primaryKeyValues.map((v) => (isString(v) ? v : (v as any).id))
1490 : [
1491 isString(primaryKeyValues)
1492 ? primaryKeyValues
1493 : (primaryKeyValues as any).id,
1494 ]
1495
1496 const canDelete = await this.productRepository_.canDeleteProductOption(
1497 optionIds,
1498 sharedContext
1499 )
1500
1501 if (!canDelete) {
1502 throw new MedusaError(
1503 MedusaError.Types.INVALID_DATA,
1504 "Cannot delete product options that are associated with products."
1505 )
1506 }
1507
1508 const productProductOptions = await this.productProductOptionService_.list(
1509 {
1510 product_option_id: optionIds,
1511 },
1512 {
1513 select: ["id"],
1514 },
1515 sharedContext
1516 )
1517
1518 const productProductOptionIds = productProductOptions.map((ppo) => ppo.id)
1519
1520 if (productProductOptionIds.length) {
1521 const productProductOptionValues =
1522 await this.productProductOptionValueService_.list(
1523 {
1524 product_product_option_id: productProductOptionIds,
1525 },
1526 {
1527 select: ["id"],
1528 },
1529 sharedContext
1530 )
1531
1532 const productProductOptionValueIds = productProductOptionValues.map(
1533 (ppov) => ppov.id
1534 )
1535
1536 if (productProductOptionValueIds.length) {
1537 await this.productProductOptionValueService_.softDelete(
1538 productProductOptionValueIds,
1539 sharedContext
1540 )
1541 }
1542 }
1543
1544 if (productProductOptionIds.length) {
1545 await this.productProductOptionService_.softDelete(
1546 productProductOptionIds,
1547 sharedContext
1548 )
1549 }
1550
1551 return await super.softDeleteProductOptions(
1552 primaryKeyValues,
1553 config,
1554 sharedContext
1555 )
1556 }
1557
1558 @InjectManager()
1559 // @ts-expect-error
1560 async softDeleteProductOptionValues<
1561 TReturnableLinkableKeys extends string = string
1562 >(
1563 primaryKeyValues: string | object | string[] | object[],
1564 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
1565 @MedusaContext() sharedContext: Context = {}
1566 ): Promise<Record<string, string[]> | void> {
1567 return await this.softDeleteProductOptionValues_(
1568 primaryKeyValues,
1569 config,
1570 sharedContext
1571 )
1572 }
1573
1574 @InjectTransactionManager()
1575 protected async softDeleteProductOptionValues_<
1576 TReturnableLinkableKeys extends string = string
1577 >(
1578 primaryKeyValues: string | object | string[] | object[],
1579 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
1580 @MedusaContext() sharedContext: Context = {}
1581 ): Promise<Record<string, string[]> | void> {
1582 const valueIds = (
1583 Array.isArray(primaryKeyValues) ? primaryKeyValues : [primaryKeyValues]
1584 ).map((v) => (isString(v) ? v : (v as any).id))
1585
1586 await this.validateOptionValuesNotAssociatedWithProducts_(
1587 valueIds,
1588 sharedContext
1589 )
1590
1591 return await super.softDeleteProductOptionValues(
1592 primaryKeyValues,
1593 config,
1594 sharedContext
1595 )
1596 }
1597
1598 @InjectManager()
1599 @EmitEvents()
1600 // @ts-ignore
1601 async restoreProductOptions<TReturnableLinkableKeys extends string>(
1602 ids: string | object | string[] | object[],
1603 config?: RestoreReturn<TReturnableLinkableKeys>,
1604 @MedusaContext() sharedContext: Context = {}
1605 ): Promise<Record<string, string[]> | void> {
1606 return await this.restoreProductOptions_(ids, config, sharedContext)
1607 }
1608
1609 @InjectTransactionManager()
1610 protected async restoreProductOptions_<
1611 TReturnableLinkableKeys extends string
1612 >(
1613 ids: string | object | string[] | object[],
1614 config?: RestoreReturn<TReturnableLinkableKeys>,
1615 @MedusaContext() sharedContext: Context = {}
1616 ): Promise<Record<string, string[]> | void> {
1617 const optionIds = Array.isArray(ids)
1618 ? ids.map((v) => (isString(v) ? v : (v as any).id))
1619 : [isString(ids) ? ids : (ids as any).id]
1620
1621 const productProductOptions = await this.productProductOptionService_.list(
1622 {
1623 product_option_id: optionIds,
1624 },
1625 {
1626 select: ["id"],
1627 withDeleted: true,
1628 },
1629 sharedContext
1630 )
1631
1632 const productProductOptionIds = productProductOptions.map((ppo) => ppo.id)
1633
1634 if (productProductOptionIds.length) {
1635 const productProductOptionValues =
1636 await this.productProductOptionValueService_.list(
1637 {
1638 product_product_option_id: productProductOptionIds,
1639 },
1640 {
1641 select: ["id"],
1642 withDeleted: true,
1643 },
1644 sharedContext
1645 )
1646
1647 const productProductOptionValueIds = productProductOptionValues.map(
1648 (ppov) => ppov.id
1649 )
1650
1651 if (productProductOptionValueIds.length) {
1652 await this.productProductOptionValueService_.restore(
1653 productProductOptionValueIds,
1654 sharedContext
1655 )
1656 }
1657 }
1658
1659 if (productProductOptionIds.length) {
1660 await this.productProductOptionService_.restore(
1661 productProductOptionIds,
1662 sharedContext
1663 )
1664 }
1665
1666 return await super.restoreProductOptions(ids, config, sharedContext)
1667 }
1668
1669 async addProductOptionToProduct(
1670 productOptionProductPair: ProductTypes.ProductOptionProductPair,
1671 sharedContext?: Context
1672 ): Promise<{ id: string }>
1673
1674 async addProductOptionToProduct(
1675 productOptionProductPairs: ProductTypes.ProductOptionProductPair[],
1676 sharedContext?: Context
1677 ): Promise<{ id: string }[]>
1678
1679 @InjectManager()
1680 @EmitEvents()
1681 async addProductOptionToProduct(
1682 data:
1683 | ProductTypes.ProductOptionProductPair
1684 | ProductTypes.ProductOptionProductPair[],
1685 @MedusaContext() sharedContext: Context = {}
1686 ): Promise<{ id: string } | { id: string }[]> {
1687 const productOptionProducts = await this.addProductOptionToProduct_(
1688 data,
1689 sharedContext
1690 )
1691
1692 return productOptionProducts
1693 }
1694
1695 @InjectTransactionManager()
1696 protected async addProductOptionToProduct_(
1697 data:
1698 | ProductTypes.ProductOptionProductPair
1699 | ProductTypes.ProductOptionProductPair[],
1700 @MedusaContext() sharedContext: Context = {}
1701 ): Promise<{ id: string } | { id: string }[]> {
1702 const pairs = Array.isArray(data) ? data : [data]
1703 if (Array.isArray(data) && !data.length) {
1704 return []
1705 }
1706
1707 const uniqueOptionIds = [...new Set(pairs.map((p) => p.product_option_id))]
1708
1709 // Read option values via a direct knex query rather than
1710 // productOptionService_.list({...,relations:["values"]}). That MikroORM
1711 // path can return an option whose `.values` collection is stale (cached
1712 // empty in the identity map) when the option was created earlier in the
1713 // same transaction — which silently produces no value pivot rows below.
1714 // Callers that persist options in the same transaction (e.g.
1715 // createProducts_) are responsible for flushing before calling this.
1716 // Use the transaction-bound knex so we see writes that have been flushed
1717 // but not committed yet.
1718 const manager = (sharedContext.transactionManager ??
1719 sharedContext.manager) as any
1720 const knex = manager.getTransactionContext() ?? manager.getKnex()
1721 const optionValuesRows: { id: string; option_id: string }[] = await knex(
1722 "product_option_value"
1723 )
1724 .select("id", "option_id")
1725 .whereIn("option_id", uniqueOptionIds)
1726 .whereNull("deleted_at")
1727
1728 const optionValuesMap = new Map<string, { id: string }[]>()
1729 for (const row of optionValuesRows) {
1730 const list = optionValuesMap.get(row.option_id) ?? []
1731 list.push({ id: row.id })
1732 optionValuesMap.set(row.option_id, list)
1733 }
1734
1735 const assignmentConflicts =
1736 await this.productRepository_.canAssignProductOptionToProduct(
1737 pairs.map((pair) => ({
1738 productId: pair.product_id,
1739 optionId: pair.product_option_id,
1740 })),
1741 sharedContext
1742 )
1743
1744 if (assignmentConflicts.alreadyLinkedOptionIds.length) {
1745 throw new MedusaError(
1746 MedusaError.Types.INVALID_DATA,
1747 `Product options are already linked to products: ${assignmentConflicts.alreadyLinkedOptionIds.join(
1748 ", "
1749 )}`
1750 )
1751 }
1752
1753 if (assignmentConflicts.exclusiveOptionIds.length) {
1754 throw new MedusaError(
1755 MedusaError.Types.INVALID_DATA,
1756 `Product options are already assigned to another product: ${assignmentConflicts.exclusiveOptionIds.join(
1757 ", "
1758 )}`
1759 )
1760 }
1761
1762 const pposToCreate: Array<{
1763 product_id: string
1764 product_option_id: string
1765 }> = []
1766
1767 for (const pair of pairs) {
1768 pposToCreate.push({
1769 product_id: pair.product_id,
1770 product_option_id: pair.product_option_id,
1771 })
1772 }
1773
1774 const createdPPOs = pposToCreate.length
1775 ? await this.productProductOptionService_.create(
1776 pposToCreate,
1777 sharedContext
1778 )
1779 : []
1780
1781 const ppoIdByKey = new Map<string, string>()
1782 for (const ppo of createdPPOs) {
1783 const key = `${ppo.product_id}_${ppo.product_option_id}`
1784 ppoIdByKey.set(key, ppo.id)
1785 }
1786
1787 const ppovToCreate: Array<{
1788 product_product_option_id: string
1789 product_option_value_id: string
1790 }> = []
1791 for (const pair of pairs) {
1792 const key = `${pair.product_id}_${pair.product_option_id}`
1793 const productProductOptionId = ppoIdByKey.get(key)
1794 if (!productProductOptionId) {
1795 continue
1796 }
1797
1798 const allValues = optionValuesMap.get(pair.product_option_id) || []
1799 const valueIds =
1800 pair.product_option_value_ids ?? allValues.map((v) => v.id)
1801
1802 for (const valueId of valueIds) {
1803 ppovToCreate.push({
1804 product_product_option_id: productProductOptionId,
1805 product_option_value_id: valueId,
1806 })
1807 }
1808 }
1809
1810 if (ppovToCreate.length) {
1811 await this.productProductOptionValueService_.create(
1812 ppovToCreate,
1813 sharedContext
1814 )
1815 }
1816
1817 const result = pairs.map((pair) => ({
1818 id: ppoIdByKey.get(`${pair.product_id}_${pair.product_option_id}`)!,
1819 }))
1820
1821 return Array.isArray(data) ? result : result[0]
1822 }
1823
1824 async removeProductOptionFromProduct(
1825 groupCustomerPair: ProductTypes.ProductOptionProductPair,
1826 sharedContext?: Context
1827 ): Promise<string[]>
1828
1829 async removeProductOptionFromProduct(
1830 groupCustomerPairs: ProductTypes.ProductOptionProductPair[],
1831 sharedContext?: Context
1832 ): Promise<string[]>
1833
1834 @InjectManager()
1835 @EmitEvents()
1836 async removeProductOptionFromProduct(
1837 data:
1838 | ProductTypes.ProductOptionProductPair
1839 | ProductTypes.ProductOptionProductPair[],
1840 @MedusaContext() sharedContext: Context = {}
1841 ): Promise<string[]> {
1842 return await this.removeProductOptionFromProduct_(
1843 data,
1844 new Set(),
1845 sharedContext
1846 )
1847 }
1848
1849 @InjectTransactionManager()
1850 protected async removeProductOptionFromProduct_(
1851 data:
1852 | ProductTypes.ProductOptionProductPair
1853 | ProductTypes.ProductOptionProductPair[],
1854 productIdsWithReconciledVariants: Set<string>,
1855 @MedusaContext() sharedContext: Context = {}
1856 ): Promise<string[]> {
1857 const pairs = Array.isArray(data) ? data : [data]
1858 const productOptionsProducts = await this.productProductOptionService_.list(
1859 {
1860 $or: pairs,
1861 },
1862 {},
1863 sharedContext
1864 )
1865
1866 const cascadePairs = productOptionsProducts
1867 .map((productOptionProduct) => {
1868 const productId = productOptionProduct.product_id
1869 const optionId = productOptionProduct.product_option_id
1870 if (
1871 productId &&
1872 optionId &&
1873 !productIdsWithReconciledVariants.has(productId)
1874 ) {
1875 return { productId, optionId }
1876 }
1877 return null
1878 })
1879 .filter((p): p is { productId: string; optionId: string } => p !== null)
1880
1881 if (cascadePairs.length > 0) {
1882 await this.detachOptionFromVariants_(cascadePairs, sharedContext)
1883 }
1884
1885 const productOptionsProductIds = productOptionsProducts.map(({ id }) => id)
1886 const unlinkedOptionIds = [
1887 ...new Set(
1888 productOptionsProducts
1889 .map((ppo) => ppo.product_option_id)
1890 .filter((id): id is string => !!id)
1891 ),
1892 ]
1893
1894 await this.productProductOptionValueService_.delete(
1895 productOptionsProductIds.map((id) => ({ product_product_option_id: id })),
1896 sharedContext
1897 )
1898
1899 await this.productProductOptionService_.delete(
1900 productOptionsProductIds,
1901 sharedContext
1902 )
1903
1904 // Soft-delete exclusive options that are now orphaned.
1905 if (!unlinkedOptionIds.length) {
1906 return []
1907 }
1908
1909 const [unlinkedOptions, remainingLinks] = await promiseAll([
1910 this.productOptionService_.list(
1911 { id: unlinkedOptionIds },
1912 {},
1913 sharedContext
1914 ),
1915 this.productProductOptionService_.list(
1916 { product_option_id: unlinkedOptionIds },
1917 {},
1918 sharedContext
1919 ),
1920 ])
1921
1922 const stillLinkedOptionIds = new Set(
1923 remainingLinks.map((link) => link.product_option_id)
1924 )
1925
1926 const orphanedExclusiveOptionIds = unlinkedOptions
1927 .filter(
1928 (option) => option.is_exclusive && !stillLinkedOptionIds.has(option.id)
1929 )
1930 .map((option) => option.id)
1931
1932 if (orphanedExclusiveOptionIds.length) {
1933 await this.productOptionService_.softDelete(
1934 orphanedExclusiveOptionIds,
1935 sharedContext
1936 )
1937 }
1938
1939 return orphanedExclusiveOptionIds
1940 }
1941
1942 /**
1943 * Strips the values of the given options off the variants of the given
1944 * products, so an option can be unassigned from a product that already has
1945 * variants built on it. Throws if dropping the values would collapse two
1946 * variants onto the same option combination.
1947 */
1948 @InjectTransactionManager()
1949 protected async detachOptionFromVariants_(
1950 pairs: Array<{ productId: string; optionId: string }>,
1951 @MedusaContext() sharedContext: Context = {}
1952 ): Promise<void> {
1953 const productIds = [...new Set(pairs.map((pair) => pair.productId))]
1954 const optionIds = [...new Set(pairs.map((pair) => pair.optionId))]
1955
1956 const [options, variantsByProductId] = await promiseAll([
1957 this.productOptionService_.list(
1958 { id: optionIds },
1959 { relations: ["values"] },
1960 sharedContext
1961 ),
1962 this.productRepository_.getVariantOptionValuesByProductIds(
1963 productIds,
1964 sharedContext
1965 ),
1966 ])
1967
1968 const valueIdsByOptionId = new Map(
1969 options.map((option) => [
1970 option.id,
1971 (option.values ?? []).map((value) => value.id),
1972 ])
1973 )
1974
1975 const removedValueIdsByProductId = new Map<string, Set<string>>()
1976 for (const pair of pairs) {
1977 const removedValueIds =
1978 removedValueIdsByProductId.get(pair.productId) ?? new Set<string>()
1979 valueIdsByOptionId
1980 .get(pair.optionId)
1981 ?.forEach((valueId) => removedValueIds.add(valueId))
1982 removedValueIdsByProductId.set(pair.productId, removedValueIds)
1983 }
1984
1985 for (const [productId, removedValueIds] of removedValueIdsByProductId) {
1986 const productVariants = variantsByProductId.get(productId)
1987 if (!removedValueIds.size || !productVariants?.size) {
1988 continue
1989 }
1990
1991 const buckets = new Map<
1992 string,
1993 Array<{ before: string; title: string | null }>
1994 >()
1995 const variantIdsToDetach: string[] = []
1996
1997 for (const [variantId, variant] of productVariants) {
1998 const remainingValueIds = [...variant.valueIds].filter(
1999 (valueId) => !removedValueIds.has(valueId)
2000 )
2001
2002 if (remainingValueIds.length !== variant.valueIds.size) {
2003 variantIdsToDetach.push(variantId)
2004 }
2005
2006 const key = remainingValueIds.sort().join("|")
2007 const bucket = buckets.get(key) ?? []
2008 bucket.push({
2009 before: [...variant.valueIds].sort().join("|"),
2010 title: variant.title,
2011 })
2012 buckets.set(key, bucket)
2013 }
2014
2015 // Only a bucket whose variants were distinct beforehand is a collision we
2016 // are causing; variants that already shared a combination stay as they were.
2017 const collision = [...buckets.values()].find(
2018 (bucket) =>
2019 bucket.length > 1 &&
2020 new Set(bucket.map((entry) => entry.before)).size > 1
2021 )
2022
2023 if (collision) {
2024 throw new MedusaError(
2025 MedusaError.Types.INVALID_DATA,
2026 `Cannot unassign product option from product because the following variant(s) would end up with the same option combination: ${collision
2027 .map((entry) => entry.title)
2028 .join(", ")}`
2029 )
2030 }
2031
2032 await this.productRepository_.detachOptionValuesFromVariants(
2033 variantIdsToDetach,
2034 [...removedValueIds],
2035 sharedContext
2036 )
2037 }
2038 }
2039
2040 async updateProductOptionValuesOnProduct(
2041 update: ProductTypes.ProductOptionProductValueUpdate,
2042 sharedContext?: Context
2043 ): Promise<void>
2044
2045 async updateProductOptionValuesOnProduct(
2046 updates: ProductTypes.ProductOptionProductValueUpdate[],
2047 sharedContext?: Context
2048 ): Promise<void>
2049
2050 @InjectManager()
2051 @EmitEvents()
2052 async updateProductOptionValuesOnProduct(
2053 data:
2054 | ProductTypes.ProductOptionProductValueUpdate
2055 | ProductTypes.ProductOptionProductValueUpdate[],
2056 @MedusaContext() sharedContext: Context = {}
2057 ): Promise<void> {
2058 await this.updateProductOptionValuesOnProduct_(data, sharedContext)
2059 }
2060
2061 @InjectTransactionManager()
2062 protected async updateProductOptionValuesOnProduct_(
2063 data:
2064 | ProductTypes.ProductOptionProductValueUpdate
2065 | ProductTypes.ProductOptionProductValueUpdate[],
2066 @MedusaContext() sharedContext: Context = {}
2067 ): Promise<void> {
2068 const updates = Array.isArray(data) ? data : [data]
2069 const effectiveUpdates = updates.filter(
2070 (pair) => pair.add?.length || pair.remove?.length
2071 )
2072
2073 if (!effectiveUpdates.length) {
2074 return
2075 }
2076
2077 const existingProductOptions = await this.productProductOptionService_.list(
2078 {
2079 $or: effectiveUpdates.map((pair) => ({
2080 product_id: pair.product_id,
2081 product_option_id: pair.product_option_id,
2082 })),
2083 },
2084 { relations: ["values"] },
2085 sharedContext
2086 )
2087
2088 const existingPPOMap = new Map<
2089 string,
2090 InferEntityType<typeof ProductProductOption>
2091 >()
2092 existingProductOptions.forEach((ppo) => {
2093 const key = `${ppo.product_id}_${ppo.product_option_id}`
2094 existingPPOMap.set(key, ppo)
2095 })
2096
2097 const missingPairs = effectiveUpdates.filter((pair) => {
2098 const key = `${pair.product_id}_${pair.product_option_id}`
2099 return !existingPPOMap.has(key)
2100 })
2101
2102 if (missingPairs.length) {
2103 const missingPairsLabel = missingPairs
2104 .map((pair) => `${pair.product_id}:${pair.product_option_id}`)
2105 .join(", ")
2106 throw new MedusaError(
2107 MedusaError.Types.INVALID_DATA,
2108 `Some product options are not linked to products: [${missingPairsLabel}]`
2109 )
2110 }
2111
2112 const validationPairs = effectiveUpdates
2113 .filter((pair) => pair.remove?.length)
2114 .map((pair) => ({
2115 productId: pair.product_id,
2116 optionId: pair.product_option_id,
2117 valueIdsToCheck: pair.remove!,
2118 }))
2119
2120 if (validationPairs.length) {
2121 await this.validateOptionRemoval_(validationPairs, sharedContext)
2122 }
2123
2124 // if some values are passed as a create object - create those option values first and return array of value ids to assign to PPOs
2125 const normalizedUpdates = await this.normalizeProductOptionValueUpdates_(
2126 effectiveUpdates,
2127 sharedContext
2128 )
2129
2130 const ppovToCreate: Array<{
2131 product_product_option_id: string
2132 product_option_value_id: string
2133 }> = []
2134 const ppovToDelete: Array<{
2135 product_product_option_id: string
2136 product_option_value_id: string
2137 }> = []
2138
2139 normalizedUpdates.forEach((pair) => {
2140 const key = `${pair.product_id}_${pair.product_option_id}`
2141 const existingPPO = existingPPOMap.get(key)!
2142 const existingValueIds = new Set(
2143 (existingPPO.values ?? []).map((value) => value.id)
2144 )
2145
2146 Array.from(new Set(pair.add ?? [])).forEach((valueId) => {
2147 if (existingValueIds.has(valueId)) {
2148 return
2149 }
2150
2151 ppovToCreate.push({
2152 product_product_option_id: existingPPO.id,
2153 product_option_value_id: valueId,
2154 })
2155 })
2156
2157 Array.from(new Set(pair.remove ?? [])).forEach((valueId) => {
2158 ppovToDelete.push({
2159 product_product_option_id: existingPPO.id,
2160 product_option_value_id: valueId,
2161 })
2162 })
2163 })
2164
2165 if (ppovToDelete.length) {
2166 await this.productProductOptionValueService_.delete(
2167 ppovToDelete,
2168 sharedContext
2169 )
2170 }
2171
2172 if (ppovToCreate.length) {
2173 await this.productProductOptionValueService_.create(
2174 ppovToCreate,
2175 sharedContext
2176 )
2177 }
2178 }
2179
2180 protected async normalizeProductOptionValueUpdates_(
2181 updates: ProductTypes.ProductOptionProductValueUpdate[],
2182 sharedContext: Context
2183 ): Promise<
2184 Array<
2185 Omit<ProductTypes.ProductOptionProductValueUpdate, "add"> & {
2186 add?: string[]
2187 }
2188 >
2189 > {
2190 const valueNamesByOptionId = new Map<string, Set<string>>()
2191 const existingAddIdsByIndex: Array<Set<string>> = []
2192 const valueNamesByIndex: Array<Set<string>> = []
2193
2194 updates.forEach((pair, index) => {
2195 const existingAddIds = new Set<string>()
2196 const valueNames = new Set<string>()
2197
2198 const addEntries = pair.add ?? []
2199
2200 addEntries.forEach((valueEntry) => {
2201 if (isString(valueEntry)) {
2202 existingAddIds.add(valueEntry)
2203 return
2204 }
2205
2206 const normalizedValue = valueEntry.value.trim()
2207 if (!normalizedValue) {
2208 return
2209 }
2210
2211 if (!valueNamesByOptionId.has(pair.product_option_id)) {
2212 valueNamesByOptionId.set(pair.product_option_id, new Set())
2213 }
2214
2215 valueNamesByOptionId.get(pair.product_option_id)!.add(normalizedValue)
2216 valueNames.add(normalizedValue)
2217 })
2218
2219 existingAddIdsByIndex[index] = existingAddIds
2220 valueNamesByIndex[index] = valueNames
2221 })
2222
2223 /*
2224 * Return early if no new values need to be created
2225 */
2226
2227 if (!valueNamesByOptionId.size) {
2228 return updates.map((pair, index) => ({
2229 ...pair,
2230 add: existingAddIdsByIndex[index].size
2231 ? [...existingAddIdsByIndex[index]]
2232 : undefined,
2233 }))
2234 }
2235
2236 /*
2237 * Create values for options for passed create objects
2238 */
2239
2240 const optionIds = [...valueNamesByOptionId.keys()]
2241 const options = await this.productOptionService_.list(
2242 { id: optionIds },
2243 { relations: ["values"] },
2244 sharedContext
2245 )
2246
2247 if (options.length !== optionIds.length) {
2248 const existingIds = new Set(options.map((option) => option.id))
2249 const missingId = optionIds.find((id) => !existingIds.has(id))
2250
2251 throw new MedusaError(
2252 MedusaError.Types.INVALID_DATA,
2253 `Cannot find product option with id: ${missingId}`
2254 )
2255 }
2256
2257 const optionsById = new Map(options.map((option) => [option.id, option]))
2258 const updateOptionsInput: UpdateProductOptionInput[] = []
2259
2260 valueNamesByOptionId.forEach((valueNames, optionId) => {
2261 const option = optionsById.get(optionId)
2262 if (!option) {
2263 return
2264 }
2265
2266 const existingValueNames = new Set(
2267 option.values?.map((value) => value.value) ?? []
2268 )
2269 const newValueNames = [...valueNames].filter(
2270 (value) => !existingValueNames.has(value)
2271 )
2272
2273 if (!newValueNames.length) {
2274 return
2275 }
2276
2277 updateOptionsInput.push({
2278 id: optionId,
2279 values: [...existingValueNames, ...newValueNames],
2280 })
2281 })
2282
2283 if (updateOptionsInput.length) {
2284 // todo: we could consider just `upsert` here but `updateOptions` handles validation and rank
2285 const updatedOptions = await this.updateOptions_(
2286 updateOptionsInput,
2287 sharedContext
2288 )
2289
2290 updatedOptions.forEach((option) => optionsById.set(option.id, option))
2291 }
2292
2293 const valueIdsByOptionId = new Map<string, Map<string, string>>(
2294 [...optionsById.values()].map((option) => [
2295 option.id,
2296 new Map(option.values?.map((value) => [value.value, value.id]) ?? []),
2297 ])
2298 )
2299
2300 return updates.map((pair, index) => {
2301 const addIds = new Set(existingAddIdsByIndex[index])
2302 const valueMap = valueIdsByOptionId.get(pair.product_option_id)
2303 const valueNames = valueNamesByIndex[index] ?? new Set()
2304
2305 valueNames.forEach((valueName) => {
2306 const resolvedId = valueMap?.get(valueName)
2307 if (resolvedId) {
2308 addIds.add(resolvedId)
2309 }
2310 })
2311
2312 return {
2313 ...pair,
2314 add: addIds.size ? [...addIds] : undefined,
2315 }
2316 })
2317 }
2318
2319 // @ts-expect-error
2320 createProductCollections(
2321 data: ProductTypes.CreateProductCollectionDTO[],
2322 sharedContext?: Context
2323 ): Promise<ProductTypes.ProductCollectionDTO[]>
2324 // @ts-expect-error
2325 createProductCollections(
2326 data: ProductTypes.CreateProductCollectionDTO,
2327 sharedContext?: Context
2328 ): Promise<ProductTypes.ProductCollectionDTO>
2329
2330 @InjectManager()
2331 @EmitEvents()
2332 // @ts-expect-error
2333 async createProductCollections(
2334 data:
2335 | ProductTypes.CreateProductCollectionDTO[]
2336 | ProductTypes.CreateProductCollectionDTO,
2337 @MedusaContext() sharedContext: Context = {}
2338 ): Promise<
2339 ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
2340 > {
2341 const input = Array.isArray(data) ? data : [data]
2342
2343 const collections = await this.createCollections_(input, sharedContext)
2344
2345 const createdCollections = await this.baseRepository_.serialize<
2346 ProductTypes.ProductCollectionDTO[]
2347 >(collections)
2348
2349 return Array.isArray(data) ? createdCollections : createdCollections[0]
2350 }
2351
2352 @InjectTransactionManager()
2353 async createCollections_(
2354 data: ProductTypes.CreateProductCollectionDTO[],
2355 @MedusaContext() sharedContext: Context = {}
2356 ): Promise<InferEntityType<typeof ProductCollection>[]> {
2357 const normalizedInput = data.map(
2358 ProductModuleService.normalizeCreateProductCollectionInput
2359 )
2360
2361 // It's safe to use upsertWithReplace here since we only have product IDs and the only operation to do is update the product
2362 // with the collection ID
2363 const { entities: productCollections } =
2364 await this.productCollectionService_.upsertWithReplace(
2365 normalizedInput,
2366 { relations: ["products"] },
2367 sharedContext
2368 )
2369
2370 return productCollections
2371 }
2372
2373 async upsertProductCollections(
2374 data: ProductTypes.UpsertProductCollectionDTO[],
2375 sharedContext?: Context
2376 ): Promise<ProductTypes.ProductCollectionDTO[]>
2377 async upsertProductCollections(
2378 data: ProductTypes.UpsertProductCollectionDTO,
2379 sharedContext?: Context
2380 ): Promise<ProductTypes.ProductCollectionDTO>
2381
2382 @InjectManager()
2383 @EmitEvents()
2384 async upsertProductCollections(
2385 data:
2386 | ProductTypes.UpsertProductCollectionDTO[]
2387 | ProductTypes.UpsertProductCollectionDTO,
2388 @MedusaContext() sharedContext: Context = {}
2389 ): Promise<
2390 ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
2391 > {
2392 const collections = await this.upsertCollections_(data, sharedContext)
2393
2394 const serializedCollections = await this.baseRepository_.serialize<
2395 ProductTypes.ProductCollectionDTO[]
2396 >(collections)
2397
2398 return Array.isArray(data)
2399 ? serializedCollections
2400 : serializedCollections[0]
2401 }
2402
2403 @InjectTransactionManager()
2404 protected async upsertCollections_(
2405 data:
2406 | ProductTypes.UpsertProductCollectionDTO[]
2407 | ProductTypes.UpsertProductCollectionDTO,
2408 @MedusaContext() sharedContext: Context = {}
2409 ): Promise<InferEntityType<typeof ProductCollection>[]> {
2410 const input = Array.isArray(data) ? data : [data]
2411 const forUpdate = input.filter(
2412 (collection): collection is UpdateCollectionInput => !!collection.id
2413 )
2414 const forCreate = input.filter(
2415 (collection): collection is ProductTypes.CreateProductCollectionDTO =>
2416 !collection.id
2417 )
2418
2419 let created: InferEntityType<typeof ProductCollection>[] = []
2420 let updated: InferEntityType<typeof ProductCollection>[] = []
2421
2422 if (forCreate.length) {
2423 created = await this.createCollections_(forCreate, sharedContext)
2424 }
2425
2426 if (forUpdate.length) {
2427 updated = await this.updateCollections_(forUpdate, sharedContext)
2428 }
2429
2430 return [...created, ...updated]
2431 }
2432
2433 // @ts-expect-error
2434 updateProductCollections(
2435 id: string,
2436 data: ProductTypes.UpdateProductCollectionDTO,
2437 sharedContext?: Context
2438 ): Promise<ProductTypes.ProductCollectionDTO>
2439 // @ts-expect-error
2440 updateProductCollections(
2441 selector: ProductTypes.FilterableProductCollectionProps,
2442 data: ProductTypes.UpdateProductCollectionDTO,
2443 sharedContext?: Context
2444 ): Promise<ProductTypes.ProductCollectionDTO[]>
2445
2446 @InjectManager()
2447 @EmitEvents()
2448 // @ts-expect-error
2449 async updateProductCollections(
2450 idOrSelector: string | ProductTypes.FilterableProductCollectionProps,
2451 data: ProductTypes.UpdateProductCollectionDTO,
2452 @MedusaContext() sharedContext: Context = {}
2453 ): Promise<
2454 ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
2455 > {
2456 let normalizedInput: UpdateCollectionInput[] = []
2457 if (isString(idOrSelector)) {
2458 await this.productCollectionService_.retrieve(
2459 idOrSelector,
2460 {},
2461 sharedContext
2462 )
2463 normalizedInput = [{ id: idOrSelector, ...data }]
2464 } else {
2465 const collections = await this.productCollectionService_.list(
2466 idOrSelector,
2467 {},
2468 sharedContext
2469 )
2470
2471 normalizedInput = collections.map((collection) => ({
2472 id: collection.id,
2473 ...data,
2474 }))
2475 }
2476
2477 const collections = await this.updateCollections_(
2478 normalizedInput,
2479 sharedContext
2480 )
2481
2482 const updatedCollections = await this.baseRepository_.serialize<
2483 ProductTypes.ProductCollectionDTO[]
2484 >(collections)
2485
2486 return isString(idOrSelector) ? updatedCollections[0] : updatedCollections
2487 }
2488
2489 @InjectTransactionManager()
2490 protected async updateCollections_(
2491 data: UpdateCollectionInput[],
2492 @MedusaContext() sharedContext: Context = {}
2493 ): Promise<InferEntityType<typeof ProductCollection>[]> {
2494 const normalizedInput = data.map(
2495 ProductModuleService.normalizeUpdateProductCollectionInput
2496 ) as UpdateCollectionInput[]
2497
2498 // TODO: Maybe we can update upsertWithReplace to not remove oneToMany entities, but just disassociate them? With that we can remove the code below.
2499 // Another alternative is to not allow passing product_ids to a collection, and instead set the collection_id through the product update call.
2500 const updatedCollections = await this.productCollectionService_.update(
2501 normalizedInput.map((c) =>
2502 removeUndefined({ ...c, products: undefined })
2503 ),
2504 sharedContext
2505 )
2506
2507 const collections: InferEntityType<typeof ProductCollection>[] = []
2508 const toUpdate: {
2509 selector: ProductTypes.FilterableProductProps
2510 data: ProductTypes.UpdateProductDTO
2511 }[] = []
2512
2513 updatedCollections.forEach((collectionData) => {
2514 const input = normalizedInput.find((c) => c.id === collectionData.id)
2515 const productsToUpdate = (input as any)?.products
2516
2517 const dissociateSelector = {
2518 collection_id: collectionData.id,
2519 }
2520 const associateSelector = {}
2521
2522 if (isDefined(productsToUpdate)) {
2523 const productIds = productsToUpdate.map((p) => p.id)
2524
2525 dissociateSelector["id"] = { $nin: productIds }
2526 associateSelector["id"] = { $in: productIds }
2527 }
2528
2529 if (isPresent(dissociateSelector["id"])) {
2530 toUpdate.push({
2531 selector: dissociateSelector,
2532 data: {
2533 collection_id: null,
2534 },
2535 })
2536 }
2537
2538 if (isPresent(associateSelector["id"])) {
2539 toUpdate.push({
2540 selector: associateSelector,
2541 data: {
2542 collection_id: collectionData.id,
2543 },
2544 })
2545 }
2546
2547 collections.push({
2548 ...collectionData,
2549 products: productsToUpdate ?? [],
2550 } as InferEntityType<typeof ProductCollection>)
2551 })
2552
2553 if (toUpdate.length) {
2554 await this.productService_.update(toUpdate, sharedContext)
2555 }
2556
2557 return collections
2558 }
2559
2560 // @ts-expect-error
2561 createProductCategories(
2562 data: ProductTypes.CreateProductCategoryDTO[],
2563 sharedContext?: Context
2564 ): Promise<ProductTypes.ProductCategoryDTO[]>
2565 // @ts-expect-error
2566 createProductCategories(
2567 data: ProductTypes.CreateProductCategoryDTO,
2568 sharedContext?: Context
2569 ): Promise<ProductTypes.ProductCategoryDTO>
2570
2571 @InjectManager()
2572 @EmitEvents()
2573 // @ts-expect-error
2574 async createProductCategories(
2575 data:
2576 | ProductTypes.CreateProductCategoryDTO[]
2577 | ProductTypes.CreateProductCategoryDTO,
2578 @MedusaContext() sharedContext: Context = {}
2579 ): Promise<
2580 ProductTypes.ProductCategoryDTO[] | ProductTypes.ProductCategoryDTO
2581 > {
2582 const input = (Array.isArray(data) ? data : [data]).map(
2583 (productCategory) => {
2584 productCategory.handle ??= kebabCase(productCategory.name)
2585 return productCategory
2586 }
2587 )
2588
2589 const categories = await this.productCategoryService_.create(
2590 input,
2591 sharedContext
2592 )
2593
2594 const createdCategories = await this.baseRepository_.serialize<
2595 ProductTypes.ProductCategoryDTO[]
2596 >(categories)
2597
2598 // TODO: Same as the update categories, for some reason I cant get the tree repository update
2599 eventBuilders.createdProductCategory({
2600 data: createdCategories,
2601 sharedContext,
2602 })
2603
2604 return Array.isArray(data) ? createdCategories : createdCategories[0]
2605 }
2606
2607 async upsertProductCategories(
2608 data: ProductTypes.UpsertProductCategoryDTO[],
2609 sharedContext?: Context
2610 ): Promise<ProductTypes.ProductCategoryDTO[]>
2611 async upsertProductCategories(
2612 data: ProductTypes.UpsertProductCategoryDTO,
2613 sharedContext?: Context
2614 ): Promise<ProductTypes.ProductCategoryDTO>
2615
2616 @InjectManager()
2617 @EmitEvents()
2618 async upsertProductCategories(
2619 data:
2620 | ProductTypes.UpsertProductCategoryDTO[]
2621 | ProductTypes.UpsertProductCategoryDTO,
2622 @MedusaContext() sharedContext: Context = {}
2623 ): Promise<
2624 ProductTypes.ProductCategoryDTO[] | ProductTypes.ProductCategoryDTO
2625 > {
2626 const categories = await this.upsertProductCategories_(data, sharedContext)
2627
2628 const serializedCategories = await this.baseRepository_.serialize<
2629 ProductTypes.ProductCategoryDTO[]
2630 >(categories)
2631
2632 return Array.isArray(data) ? serializedCategories : serializedCategories[0]
2633 }
2634
2635 @InjectTransactionManager()
2636 protected async upsertProductCategories_(
2637 data:
2638 | ProductTypes.UpsertProductCategoryDTO[]
2639 | ProductTypes.UpsertProductCategoryDTO,
2640 @MedusaContext() sharedContext: Context = {}
2641 ): Promise<InferEntityType<typeof ProductCategory>[]> {
2642 const input = Array.isArray(data) ? data : [data]
2643 const forUpdate = input.filter(
2644 (category): category is UpdateCategoryInput => !!category.id
2645 )
2646 let forCreate = input.filter(
2647 (category): category is ProductTypes.CreateProductCategoryDTO =>
2648 !category.id
2649 )
2650
2651 let created: InferEntityType<typeof ProductCategory>[] = []
2652 let updated: InferEntityType<typeof ProductCategory>[] = []
2653
2654 if (forCreate.length) {
2655 forCreate = forCreate.map((productCategory) => {
2656 productCategory.handle ??= kebabCase(productCategory.name)
2657 return productCategory
2658 })
2659
2660 created = await this.productCategoryService_.create(
2661 forCreate,
2662 sharedContext
2663 )
2664 }
2665 if (forUpdate.length) {
2666 updated = await this.productCategoryService_.update(
2667 forUpdate,
2668 sharedContext
2669 )
2670 }
2671
2672 // TODO: Same as the update categories, for some reason I cant get the tree repository update
2673 // event. I ll need to investigate this
2674 if (created.length) {
2675 eventBuilders.createdProductCategory({
2676 data: created,
2677 sharedContext,
2678 })
2679 }
2680 if (updated.length) {
2681 eventBuilders.updatedProductCategory({
2682 data: updated,
2683 sharedContext,
2684 })
2685 }
2686
2687 return [...created, ...updated]
2688 }
2689
2690 // @ts-expect-error
2691 updateProductCategories(
2692 id: string,
2693 data: ProductTypes.UpdateProductCategoryDTO,
2694 sharedContext?: Context
2695 ): Promise<ProductTypes.ProductCategoryDTO>
2696 // @ts-expect-error
2697 updateProductCategories(
2698 selector: ProductTypes.FilterableProductTypeProps,
2699 data: ProductTypes.UpdateProductCategoryDTO,
2700 sharedContext?: Context
2701 ): Promise<ProductTypes.ProductCategoryDTO[]>
2702
2703 @InjectManager()
2704 @EmitEvents()
2705 // @ts-expect-error
2706 async updateProductCategories(
2707 idOrSelector: string | ProductTypes.FilterableProductTypeProps,
2708 data: ProductTypes.UpdateProductCategoryDTO,
2709 @MedusaContext() sharedContext: Context = {}
2710 ): Promise<
2711 ProductTypes.ProductCategoryDTO | ProductTypes.ProductCategoryDTO[]
2712 > {
2713 const categories = await this.updateProductCategories_(
2714 idOrSelector,
2715 data,
2716 sharedContext
2717 )
2718
2719 const serializedCategories = await this.baseRepository_.serialize<
2720 ProductTypes.ProductCategoryDTO[]
2721 >(categories)
2722
2723 // TODO: for some reason I cant get the tree repository update
2724 // event. I ll need to investigate this
2725 eventBuilders.updatedProductCategory({
2726 data: serializedCategories,
2727 sharedContext,
2728 })
2729
2730 return isString(idOrSelector)
2731 ? serializedCategories[0]
2732 : serializedCategories
2733 }
2734
2735 @InjectTransactionManager()
2736 protected async updateProductCategories_(
2737 idOrSelector: string | ProductTypes.FilterableProductTypeProps,
2738 data: ProductTypes.UpdateProductCategoryDTO,
2739 @MedusaContext() sharedContext: Context = {}
2740 ): Promise<InferEntityType<typeof ProductCategory>[]> {
2741 let normalizedInput: UpdateCategoryInput[] = []
2742 if (isString(idOrSelector)) {
2743 // Check if the type exists in the first place
2744 await this.productCategoryService_.retrieve(
2745 idOrSelector,
2746 {},
2747 sharedContext
2748 )
2749 normalizedInput = [{ id: idOrSelector, ...data }]
2750 } else {
2751 const categories = await this.productCategoryService_.list(
2752 idOrSelector,
2753 {},
2754 sharedContext
2755 )
2756
2757 normalizedInput = categories.map((type) => ({
2758 id: type.id,
2759 ...data,
2760 }))
2761 }
2762
2763 const categories = await this.productCategoryService_.update(
2764 normalizedInput,
2765 sharedContext
2766 )
2767
2768 return categories
2769 }
2770
2771 @InjectManager()
2772 @EmitEvents()
2773 // @ts-expect-error
2774 async softDeleteProductCategories<
2775 TReturnableLinkableKeys extends string = string
2776 >(
2777 primaryKeyValues: string | object | string[] | object[],
2778 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
2779 @MedusaContext() sharedContext: Context = {}
2780 ): Promise<Record<string, string[]> | void> {
2781 const primaryKeyValuesArray = Array.isArray(primaryKeyValues)
2782 ? primaryKeyValues
2783 : [primaryKeyValues]
2784
2785 const categoryIds = primaryKeyValuesArray.map((primaryKeyValue) =>
2786 isString(primaryKeyValue)
2787 ? primaryKeyValue
2788 : (primaryKeyValue as { id: string }).id
2789 )
2790
2791 const result = await super.softDeleteProductCategories(
2792 primaryKeyValues,
2793 config,
2794 sharedContext
2795 )
2796
2797 eventBuilders.deletedProductCategory({
2798 data: categoryIds.map((id) => ({ id })),
2799 sharedContext,
2800 })
2801
2802 return result
2803 }
2804
2805 //@ts-expect-error
2806 createProducts(
2807 data: ProductTypes.CreateProductDTO[],
2808 sharedContext?: Context
2809 ): Promise<ProductTypes.ProductDTO[]>
2810 // @ts-expect-error
2811 createProducts(
2812 data: ProductTypes.CreateProductDTO,
2813 sharedContext?: Context
2814 ): Promise<ProductTypes.ProductDTO>
2815
2816 @InjectManager()
2817 @EmitEvents()
2818 // @ts-expect-error
2819 async createProducts(
2820 data: ProductTypes.CreateProductDTO[] | ProductTypes.CreateProductDTO,
2821 @MedusaContext() sharedContext: Context = {}
2822 ): Promise<ProductTypes.ProductDTO[] | ProductTypes.ProductDTO> {
2823 const input = Array.isArray(data) ? data : [data]
2824 const products = await this.createProducts_(input, sharedContext)
2825
2826 const createdProducts = await this.baseRepository_.serialize<
2827 ProductTypes.ProductDTO[]
2828 >(products)
2829
2830 await this.filterOptionValues(createdProducts, sharedContext)
2831
2832 return Array.isArray(data) ? createdProducts : createdProducts[0]
2833 }
2834
2835 async upsertProducts(
2836 data: ProductTypes.UpsertProductDTO[],
2837 sharedContext?: Context
2838 ): Promise<ProductTypes.ProductDTO[]>
2839 async upsertProducts(
2840 data: ProductTypes.UpsertProductDTO,
2841 sharedContext?: Context
2842 ): Promise<ProductTypes.ProductDTO>
2843
2844 @InjectTransactionManager()
2845 @EmitEvents()
2846 async upsertProducts(
2847 data: ProductTypes.UpsertProductDTO[] | ProductTypes.UpsertProductDTO,
2848 @MedusaContext() sharedContext: Context = {}
2849 ): Promise<ProductTypes.ProductDTO[] | ProductTypes.ProductDTO> {
2850 const input = Array.isArray(data) ? data : [data]
2851 const forUpdate = input.filter(
2852 (product): product is UpdateProductInput => !!product.id
2853 )
2854 const forCreate = input.filter((product) => !product.id)
2855
2856 let created: ProductTypes.ProductDTO[] = []
2857 let updated: InferEntityType<typeof Product>[] = []
2858
2859 if (forCreate.length) {
2860 created = await this.createProducts(
2861 forCreate as ProductTypes.CreateProductDTO[],
2862 sharedContext
2863 )
2864 }
2865 if (forUpdate.length) {
2866 updated = await this.updateProducts_(forUpdate, sharedContext)
2867 }
2868
2869 const result = [...created, ...updated]
2870 const allProducts = await this.baseRepository_.serialize<
2871 ProductTypes.ProductDTO[] | ProductTypes.ProductDTO
2872 >(result)
2873
2874 return Array.isArray(data) ? allProducts : allProducts[0]
2875 }
2876
2877 // @ts-expect-error
2878 updateProducts(
2879 id: string,
2880 data: ProductTypes.UpdateProductDTO,
2881 sharedContext?: Context
2882 ): Promise<ProductTypes.ProductDTO>
2883 // @ts-expect-error
2884 updateProducts(
2885 selector: ProductTypes.FilterableProductProps,
2886 data: ProductTypes.UpdateProductDTO,
2887 sharedContext?: Context
2888 ): Promise<ProductTypes.ProductDTO[]>
2889
2890 @InjectManager()
2891 @EmitEvents()
2892 // @ts-expect-error
2893 async updateProducts(
2894 idOrSelector: string | ProductTypes.FilterableProductProps,
2895 data: ProductTypes.UpdateProductDTO,
2896 @MedusaContext() sharedContext: Context = {}
2897 ): Promise<ProductTypes.ProductDTO[] | ProductTypes.ProductDTO> {
2898 let normalizedInput: UpdateProductInput[] = []
2899 if (isString(idOrSelector)) {
2900 // This will throw if the product does not exist
2901 await this.productService_.retrieve(idOrSelector, {}, sharedContext)
2902
2903 normalizedInput = [{ id: idOrSelector, ...data }]
2904 } else {
2905 const products = await this.productService_.list(
2906 idOrSelector,
2907 {},
2908 sharedContext
2909 )
2910
2911 normalizedInput = products.map((product) => ({
2912 id: product.id,
2913 ...data,
2914 }))
2915 }
2916
2917 const products = await this.updateProducts_(normalizedInput, sharedContext)
2918
2919 const updatedProducts = await this.baseRepository_.serialize<
2920 ProductTypes.ProductDTO[]
2921 >(products)
2922
2923 await this.filterOptionValues(updatedProducts, sharedContext)
2924
2925 return isString(idOrSelector) ? updatedProducts[0] : updatedProducts
2926 }
2927
2928 @InjectTransactionManager()
2929 protected async createProducts_(
2930 data: ProductTypes.CreateProductDTO[],
2931 @MedusaContext() sharedContext: Context = {}
2932 ): Promise<InferEntityType<typeof Product>[]> {
2933 const existingOptionIds = data
2934 .flatMap((p) => p.options ?? [])
2935 .filter((o) => "id" in o)
2936 .map((o) => o.id)
2937
2938 let existingOptions: InferEntityType<typeof ProductOption>[] = []
2939 if (existingOptionIds.length > 0) {
2940 existingOptions = await this.productOptionService_.list(
2941 { id: existingOptionIds },
2942 { relations: ["values"] },
2943 sharedContext
2944 )
2945
2946 const fetchedIds = new Set(existingOptions.map((opt) => opt.id))
2947 const missingIds = existingOptionIds.filter((id) => !fetchedIds.has(id))
2948 if (missingIds.length) {
2949 throw new MedusaError(
2950 MedusaError.Types.INVALID_DATA,
2951 `Some product options were not found: [${missingIds.join(", ")}]`
2952 )
2953 }
2954 }
2955
2956 const existingOptionsMap = new Map(
2957 existingOptions.map((opt) => [opt.id, opt])
2958 )
2959
2960 const hydratedData = data.map((product) => {
2961 if (!product.options?.length) return product
2962
2963 const hydratedOptions = product.options.map((option) => {
2964 if ("id" in option) {
2965 // options guaranteed to be in the map since we throw if any are missing above
2966 const dbOption = existingOptionsMap.get(option.id)!
2967
2968 // Preserve the value id alongside the value name so downstream
2969 // normalization can enforce the per-product `value_ids` subset.
2970 return {
2971 id: dbOption.id,
2972 title: dbOption.title,
2973 values: dbOption.values?.map((v) => ({ id: v.id, value: v.value })),
2974 value_ids: option.value_ids,
2975 }
2976 }
2977 return option
2978 })
2979
2980 return { ...product, options: hydratedOptions }
2981 })
2982
2983 const normalizedProducts = (await this.normalizeCreateProductInput(
2984 hydratedData,
2985 sharedContext
2986 )) as ProductTypes.CreateProductDTO[]
2987
2988 for (const product of normalizedProducts) {
2989 this.validateProductCreatePayload(product)
2990 }
2991
2992 const tagIds = normalizedProducts
2993 .flatMap((d) => (d as any).tags ?? [])
2994 .map((t) => t.id)
2995 let existingTags: InferEntityType<typeof ProductTag>[] = []
2996
2997 if (tagIds.length) {
2998 existingTags = await this.productTagService_.list(
2999 {
3000 id: tagIds,
3001 },
3002 {},
3003 sharedContext
3004 )
3005 }
3006
3007 const existingTagsMap = new Map(existingTags.map((tag) => [tag.id, tag]))
3008
3009 const productOptionsToCreate = new Map<
3010 string,
3011 ProductTypes.CreateProductOptionDTO[]
3012 >()
3013
3014 const productIdHydratedData = new Map<
3015 string,
3016 (typeof hydratedData)[number]
3017 >()
3018 const productsToCreate = normalizedProducts.map((product, index) => {
3019 const productId = generateEntityId(product.id, "prod")
3020 product.id = productId
3021 productIdHydratedData.set(productId, hydratedData[index])
3022
3023 if ((product as any).categories?.length) {
3024 ;(product as any).categories = (product as any).categories.map(
3025 (category: { id: string }) => category.id
3026 )
3027 }
3028
3029 if (product.options?.length) {
3030 const newOptions = product.options.filter(
3031 (o) => !("id" in o)
3032 ) as CreateProductOptionDTO[]
3033 if (newOptions.length) {
3034 productOptionsToCreate.set(productId, newOptions)
3035 }
3036 }
3037
3038 if (product.variants?.length) {
3039 const normalizedVariants = product.variants.map((variant) => {
3040 const variantId = generateEntityId((variant as any).id, "variant")
3041 ;(variant as any).id = variantId
3042
3043 Object.entries(variant.options ?? {}).forEach(([key, value]) => {
3044 const productOption = product.options?.find(
3045 (option) => (option as any).title === key
3046 )!
3047 // Respect the per-product value subset on the input: if the option
3048 // was linked with `value_ids`, only those values are allowed for
3049 // this product's variants.
3050 const allowedValueIds = Array.isArray(
3051 (productOption as any)?.value_ids
3052 )
3053 ? new Set<string>((productOption as any).value_ids as string[])
3054 : undefined
3055 const allValues = (productOption as any).values
3056 // Values may be wrapped a second time by normalizeCreateProductInput
3057 // (e.g. {value: {id, value: "red"}}). Read both shapes.
3058 const productOptionValue = resolveAllowedOptionValues({
3059 optionTitle: key,
3060 value,
3061 optionValues: allValues,
3062 allowedValueIds,
3063 })
3064 ;(productOptionValue as any).variants ??= []
3065 ;(productOptionValue as any).variants.push(variant)
3066 })
3067
3068 delete variant.options
3069
3070 return variant
3071 })
3072
3073 product.variants = normalizedVariants
3074 }
3075
3076 if ((product as any).tags?.length) {
3077 ;(product as any).tags = (product as any).tags.map(
3078 (tag: { id: string }) => {
3079 const existingTag = existingTagsMap.get(tag.id)
3080 if (existingTag) {
3081 return existingTag
3082 }
3083
3084 throw new MedusaError(
3085 MedusaError.Types.INVALID_DATA,
3086 `Tag with id ${tag.id} not found. Please create the tag before associating it with the product.`
3087 )
3088 }
3089 )
3090 }
3091
3092 delete product.options
3093
3094 return product
3095 })
3096
3097 const productToOptionIdsMap = new Map<string, string[]>()
3098 const allOptionsWithIds: (ProductTypes.CreateProductOptionDTO & {
3099 id: string
3100 })[] = []
3101
3102 for (const [productId, options] of productOptionsToCreate.entries()) {
3103 const optionIds: string[] = []
3104
3105 for (const option of options) {
3106 const optionId = generateEntityId(undefined, "opt")
3107 optionIds.push(optionId)
3108 allOptionsWithIds.push({
3109 ...option,
3110 id: optionId,
3111 })
3112 }
3113
3114 productToOptionIdsMap.set(productId, optionIds)
3115 }
3116
3117 const [createdProducts] = await Promise.all([
3118 this.productService_.create(productsToCreate, sharedContext),
3119 allOptionsWithIds.length > 0
3120 ? this.createOptions_(allOptionsWithIds, sharedContext)
3121 : Promise.resolve([]),
3122 ])
3123
3124 const linkPairs: ProductTypes.ProductOptionProductPair[] = []
3125 for (const product of createdProducts) {
3126 const hydratedProduct = productIdHydratedData.get(product.id)
3127 const existingOptions: { id: string; value_ids?: string[] }[] = []
3128
3129 if (hydratedProduct?.options?.length) {
3130 for (const option of hydratedProduct.options) {
3131 if ("id" in option) {
3132 existingOptions.push({
3133 id: option.id,
3134 value_ids: option.value_ids,
3135 })
3136 }
3137 }
3138 }
3139
3140 const newOptionIds = productToOptionIdsMap.get(product.id) ?? []
3141 const newOptions = newOptionIds.map((id) => ({ id }))
3142 const allOptions = [...existingOptions, ...newOptions]
3143
3144 for (const option of allOptions) {
3145 const pair: ProductTypes.ProductOptionProductPair = {
3146 product_id: product.id,
3147 product_option_id: option.id,
3148 product_option_value_ids: (option as any).value_ids
3149 ? (option as any).value_ids
3150 : undefined,
3151 }
3152
3153 linkPairs.push(pair)
3154 }
3155 }
3156
3157 if (linkPairs.length > 0) {
3158 // Flush the just-created options + values to the DB before
3159 // addProductOptionToProduct_ runs — it reads option values via raw knex
3160 // to build the value-pivot rows, and that read can't see entities that
3161 // are still only in MikroORM's Unit of Work.
3162 if (allOptionsWithIds.length > 0) {
3163 await (sharedContext.transactionManager as any).flush()
3164 }
3165 await this.addProductOptionToProduct_(linkPairs, sharedContext)
3166 }
3167
3168 await (sharedContext.transactionManager as any).flush()
3169
3170 const productIds = createdProducts.map((p) => p.id)
3171 // Use the split-populate helper to avoid the MikroORM combined-populate
3172 // slow path
3173 const productsWithOptions =
3174 await this.productRepository_.findByIdsWithSplitPopulate(
3175 productIds,
3176 ["options", "options.values", "variants", "images", "tags"],
3177 sharedContext
3178 )
3179
3180 const productIdOrder = new Map(productIds.map((id, index) => [id, index]))
3181
3182 const orderedProductsWithOptions = [...productsWithOptions].sort(
3183 (a, b) =>
3184 (productIdOrder.get(a.id) ?? 0) - (productIdOrder.get(b.id) ?? 0)
3185 )
3186
3187 return orderedProductsWithOptions
3188 }
3189
3190 @InjectTransactionManager()
3191 protected async updateProducts_(
3192 data: UpdateProductInput[],
3193 @MedusaContext() sharedContext: Context = {}
3194 ): Promise<InferEntityType<typeof Product>[]> {
3195 // We have to do that manually because this method is bypassing the product service and goes
3196 // directly to the custom product repository
3197 const manager = (sharedContext.transactionManager ??
3198 sharedContext.manager) as EntityManager
3199 const subscriber = createMedusaMikroOrmEventSubscriber(
3200 ["updateProducts_"],
3201 this as unknown as ReturnType<typeof MedusaService<any>>
3202 )
3203
3204 if (manager && subscriber) {
3205 manager
3206 .getEventManager()
3207 .registerSubscriber(new subscriber(sharedContext))
3208 }
3209
3210 const allOptionIds = data
3211 .flatMap((p) => p.option_ids ?? [])
3212 .filter((id) => !!id)
3213
3214 const [originalProducts, existingOptions] = await promiseAll([
3215 this.productService_.list(
3216 { id: data.map((d) => d.id) },
3217 {
3218 relations: ["options", "options.values", "tags"],
3219 },
3220 sharedContext
3221 ),
3222 allOptionIds.length
3223 ? this.productOptionService_.list(
3224 { id: allOptionIds },
3225 {},
3226 sharedContext
3227 )
3228 : Promise.resolve([]),
3229 ])
3230
3231 if (allOptionIds.length && existingOptions.length !== allOptionIds.length) {
3232 const found = new Set(existingOptions.map((opt) => opt.id))
3233 const missing = allOptionIds.filter((id) => !found.has(id))
3234 if (missing.length) {
3235 throw new MedusaError(
3236 MedusaError.Types.INVALID_DATA,
3237 `Some product options were not found: [${missing.join(", ")}]`
3238 )
3239 }
3240 }
3241
3242 const { linkPairs, unlinkPairs, expectedOptionIdsMap } =
3243 computeOptionLinkChanges(data, originalProducts)
3244
3245 for (const product of data) {
3246 delete product.option_ids
3247 }
3248
3249 if (linkPairs.length) {
3250 await this.addProductOptionToProduct_(linkPairs, sharedContext)
3251 }
3252
3253 await (sharedContext.transactionManager as any).flush()
3254
3255 const normalizedProducts = (await this.normalizeUpdateProductInput(
3256 data
3257 )) as UpdateProductInput[]
3258
3259 for (const product of normalizedProducts) {
3260 this.validateProductUpdatePayload(product)
3261 }
3262
3263 // Load the per-product allowed value subset *after* the link flush so the
3264 // map reflects the just-created pivot rows. deepUpdate uses this to enforce
3265 // that variant.options only reference values inside the subset.
3266 const valueIdsByProductId =
3267 await this.productRepository_.getOptionValueIdsByProductIds(
3268 normalizedProducts.map((p) => p.id),
3269 sharedContext
3270 )
3271
3272 const updatedProducts = await this.productRepository_.deepUpdate(
3273 normalizedProducts,
3274 ProductModuleService.validateVariantOptions,
3275 expectedOptionIdsMap,
3276 valueIdsByProductId,
3277 sharedContext
3278 )
3279
3280 if (unlinkPairs.length) {
3281 const alreadyValidatedProductIds = new Set(expectedOptionIdsMap.keys())
3282 await this.removeProductOptionFromProduct_(
3283 unlinkPairs,
3284 alreadyValidatedProductIds,
3285 sharedContext
3286 )
3287 }
3288
3289 return updatedProducts
3290 }
3291
3292 // @ts-expect-error
3293 updateProductOptionValues(
3294 idOrSelector: string,
3295 data: ProductTypes.UpdateProductOptionValueDTO,
3296 sharedContext?: Context
3297 ): Promise<ProductTypes.ProductOptionValueDTO>
3298 // @ts-expect-error
3299 updateProductOptionValues(
3300 selector: FilterableProductOptionValueProps,
3301 data: ProductTypes.UpdateProductOptionValueDTO,
3302 sharedContext?: Context
3303 ): Promise<ProductTypes.ProductOptionValueDTO[]>
3304
3305 @InjectManager()
3306 @EmitEvents()
3307 // @ts-expect-error
3308 async updateProductOptionValues(
3309 idOrSelector: string | FilterableProductOptionValueProps,
3310 data: ProductTypes.UpdateProductOptionValueDTO,
3311 @MedusaContext() sharedContext: Context = {}
3312 ): Promise<
3313 ProductTypes.ProductOptionValueDTO | ProductTypes.ProductOptionValueDTO[]
3314 > {
3315 // TODO: There is a mismatch in the API which lead to function with different number of
3316 // arguments. Therefore, applying the MedusaContext() decorator to the function will not work
3317 // because the context arg index will differ from method to method.
3318 sharedContext.messageAggregator ??= new MessageAggregator()
3319
3320 let normalizedInput: ({
3321 id: string
3322 } & ProductTypes.UpdateProductOptionValueDTO)[] = []
3323 if (isString(idOrSelector)) {
3324 // This will throw if the product option value does not exist
3325 await this.productOptionValueService_.retrieve(
3326 idOrSelector,
3327 {},
3328 sharedContext
3329 )
3330
3331 normalizedInput = [{ id: idOrSelector, ...data }]
3332 } else {
3333 const productOptionValues = await this.productOptionValueService_.list(
3334 idOrSelector,
3335 {},
3336 sharedContext
3337 )
3338
3339 normalizedInput = productOptionValues.map((product) => ({
3340 id: product.id,
3341 ...data,
3342 }))
3343 }
3344
3345 const productOptionValues = await this.updateProductOptionValues_(
3346 normalizedInput,
3347 sharedContext
3348 )
3349
3350 const updatedProductOptionValues = await this.baseRepository_.serialize<
3351 ProductTypes.ProductOptionValueDTO[]
3352 >(productOptionValues)
3353
3354 // TODO: Because of the wrong method override, we have to compensate to prevent breaking
3355 // changes right now
3356 const groupedEvents = sharedContext.messageAggregator!.getMessages()
3357 if (
3358 Object.values(groupedEvents).flat().length > 0 &&
3359 this.eventBusModuleService_
3360 ) {
3361 const promises: Promise<void>[] = []
3362 for (const group of Object.keys(groupedEvents)) {
3363 promises.push(
3364 this.eventBusModuleService_!.emit(groupedEvents[group], {
3365 internal: true,
3366 })
3367 )
3368 }
3369
3370 await Promise.all(promises)
3371
3372 sharedContext.messageAggregator.clearMessages()
3373 }
3374
3375 return isString(idOrSelector)
3376 ? updatedProductOptionValues[0]
3377 : updatedProductOptionValues
3378 }
3379
3380 @InjectTransactionManager()
3381 protected async updateProductOptionValues_(
3382 normalizedInput: ({
3383 id: string
3384 } & ProductTypes.UpdateProductOptionValueDTO)[],
3385 @MedusaContext() sharedContext: Context = {}
3386 ): Promise<InferEntityType<typeof ProductOptionValue>[]> {
3387 return await this.productOptionValueService_.update(
3388 normalizedInput,
3389 sharedContext
3390 )
3391 }
3392
3393 /**
3394 * Validates the manually provided handle value of the product
3395 * to be URL-safe
3396 */
3397 protected validateProductPayload(
3398 productData: UpdateProductInput | ProductTypes.CreateProductDTO
3399 ) {
3400 if (productData.handle && !isValidHandle(productData.handle)) {
3401 throw new MedusaError(
3402 MedusaError.Types.INVALID_DATA,
3403 `Invalid product handle '${productData.handle}'. It must contain URL safe characters`
3404 )
3405 }
3406 }
3407
3408 protected validateProductCreatePayload(
3409 productData: ProductTypes.CreateProductDTO
3410 ) {
3411 this.validateProductPayload(productData)
3412
3413 if (!productData.title) {
3414 throw new MedusaError(
3415 MedusaError.Types.INVALID_DATA,
3416 `Product title is required`
3417 )
3418 }
3419
3420 const options = productData.options
3421
3422 if (options?.length) {
3423 const seenOptionIds = new Set<string>()
3424 const duplicateOptionIds: string[] = []
3425 for (const option of options) {
3426 if ("id" in option) {
3427 if (seenOptionIds.has(option.id)) {
3428 duplicateOptionIds.push(option.id)
3429 } else {
3430 seenOptionIds.add(option.id)
3431 }
3432 }
3433 }
3434 if (duplicateOptionIds.length) {
3435 throw new MedusaError(
3436 MedusaError.Types.INVALID_DATA,
3437 `Product "${
3438 productData.title
3439 }" has duplicate option assignments: [${duplicateOptionIds.join(
3440 ", "
3441 )}]`
3442 )
3443 }
3444 }
3445
3446 const missingOptionsVariants: string[] = []
3447
3448 if (options?.length) {
3449 productData.variants?.forEach((variant) => {
3450 options.forEach((option) => {
3451 if (!variant.options?.[(option as any).title]) {
3452 missingOptionsVariants.push(variant.title)
3453 }
3454 })
3455 })
3456 }
3457
3458 if (missingOptionsVariants.length) {
3459 throw new MedusaError(
3460 MedusaError.Types.INVALID_DATA,
3461 `Product "${
3462 productData.title
3463 }" has variants with missing options: [${missingOptionsVariants.join(
3464 ", "
3465 )}]`
3466 )
3467 }
3468 }
3469
3470 protected validateProductUpdatePayload(productData: UpdateProductInput) {
3471 this.validateProductPayload(productData)
3472 }
3473
3474 protected async normalizeCreateProductInput<
3475 T extends ProductTypes.CreateProductDTO | ProductTypes.CreateProductDTO[],
3476 TOutput = T extends ProductTypes.CreateProductDTO[]
3477 ? ProductTypes.CreateProductDTO[]
3478 : ProductTypes.CreateProductDTO
3479 >(
3480 products: T,
3481 @MedusaContext() sharedContext: Context = {}
3482 ): Promise<TOutput> {
3483 const products_ = Array.isArray(products) ? products : [products]
3484
3485 const normalizedProducts = (await this.normalizeUpdateProductInput(
3486 products_ as UpdateProductInput[]
3487 )) as ProductTypes.CreateProductDTO[]
3488
3489 for await (const productData of normalizedProducts) {
3490 if (productData.options?.length) {
3491 ;(productData as any).options = productData.options?.map((option) => {
3492 return {
3493 title: (option as any).title,
3494 values: (option as any).values?.map((value) => {
3495 return {
3496 value: value,
3497 }
3498 }),
3499 is_exclusive: (option as any).is_exclusive ?? true, // Always default to true for options created from product creation
3500 ...((option as any).id ? { id: (option as any).id } : {}),
3501 // Preserve the per-product value subset so downstream variant
3502 // normalization can enforce it.
3503 ...((option as any).value_ids
3504 ? { value_ids: (option as any).value_ids }
3505 : {}),
3506 }
3507 })
3508 }
3509
3510 if (!productData.handle && productData.title) {
3511 productData.handle = toHandle(productData.title)
3512 }
3513
3514 if (!productData.status) {
3515 productData.status = ProductStatus.DRAFT
3516 }
3517
3518 if (!productData.thumbnail && productData.images?.length) {
3519 productData.thumbnail = productData.images[0].url
3520 }
3521
3522 if (productData.images?.length) {
3523 productData.images = productData.images.map((image, index) =>
3524 (image as { rank?: number }).rank != null
3525 ? image
3526 : {
3527 ...image,
3528 rank: index,
3529 }
3530 )
3531 }
3532 }
3533
3534 return (
3535 Array.isArray(products) ? normalizedProducts : normalizedProducts[0]
3536 ) as TOutput
3537 }
3538
3539 /**
3540 * Normalizes the input for the update product input
3541 * @param products - The products to normalize
3542 * @param originalProducts - The original products to use for the normalization (must include options and option values relations)
3543 * @returns The normalized products
3544 */
3545 protected async normalizeUpdateProductInput<
3546 T extends UpdateProductInput | UpdateProductInput[],
3547 TOutput = T extends UpdateProductInput[]
3548 ? UpdateProductInput[]
3549 : UpdateProductInput
3550 >(
3551 products: T,
3552 originalProducts?: InferEntityType<typeof Product>[]
3553 ): Promise<TOutput> {
3554 const products_ = Array.isArray(products) ? products : [products]
3555
3556 const normalizedProducts: UpdateProductInput[] = []
3557
3558 for (const product of products_) {
3559 const productData = { ...product }
3560 if (productData.is_giftcard) {
3561 productData.discountable = false
3562 }
3563
3564 if (productData.tag_ids) {
3565 ;(productData as any).tags = productData.tag_ids.map((cid) => ({
3566 id: cid,
3567 }))
3568 delete productData.tag_ids
3569 }
3570
3571 if (productData.category_ids) {
3572 ;(productData as any).categories = productData.category_ids.map(
3573 (cid) => ({
3574 id: cid,
3575 })
3576 )
3577 delete productData.category_ids
3578 }
3579
3580 normalizedProducts.push(productData)
3581 }
3582
3583 return (
3584 Array.isArray(products) ? normalizedProducts : normalizedProducts[0]
3585 ) as TOutput
3586 }
3587
3588 protected static normalizeCreateProductCollectionInput(
3589 collection: ProductTypes.CreateProductCollectionDTO
3590 ): ProductTypes.CreateProductCollectionDTO {
3591 const collectionData =
3592 ProductModuleService.normalizeUpdateProductCollectionInput(
3593 collection
3594 ) as ProductTypes.CreateProductCollectionDTO
3595
3596 if (!collectionData.handle && collectionData.title) {
3597 collectionData.handle = kebabCase(collectionData.title)
3598 }
3599
3600 return collectionData
3601 }
3602
3603 protected static normalizeUpdateProductCollectionInput(
3604 collection: ProductTypes.CreateProductCollectionDTO | UpdateCollectionInput
3605 ): ProductTypes.CreateProductCollectionDTO | UpdateCollectionInput {
3606 const collectionData = { ...collection }
3607 if (Array.isArray(collectionData.product_ids)) {
3608 ;(collectionData as any).products = collectionData.product_ids.map(
3609 (pid) => ({ id: pid })
3610 )
3611
3612 delete collectionData.product_ids
3613 }
3614
3615 return collectionData
3616 }
3617
3618 protected static validateVariantOptions(
3619 variants:
3620 | ProductTypes.CreateProductVariantDTO[]
3621 | ProductTypes.UpdateProductVariantDTO[],
3622 options: InferEntityType<typeof ProductOption>[],
3623 productId: string,
3624 allowedValueIds?: Set<string>
3625 ) {
3626 const optionsByProductId = new Map([[productId, options]])
3627 const valueIdsByProductId = allowedValueIds
3628 ? new Map([[productId, allowedValueIds]])
3629 : undefined
3630 const variantsWithOptions = ProductModuleService.assignOptionsToVariants(
3631 variants.map((v) => ({ ...v, product_id: productId })),
3632 optionsByProductId,
3633 valueIdsByProductId
3634 )
3635
3636 ProductModuleService.checkIfVariantsHaveUniqueOptionsCombinations(
3637 variantsWithOptions as any
3638 )
3639 }
3640
3641 protected static assignOptionsToVariants(
3642 variants:
3643 | ProductTypes.CreateProductVariantDTO[]
3644 | ProductTypes.UpdateProductVariantDTO[],
3645 optionsByProductId: Map<string, InferEntityType<typeof ProductOption>[]>,
3646 // When provided, each product's allowed option-value subset
3647 // (product_product_option_value pivot) is enforced — a variant cannot
3648 // reference a value that exists on the option but is not in the product's
3649 // subset. Without it, the helper falls back to using the option's full
3650 // value list, which is the legacy (1:1 product↔option) behavior.
3651 valueIdsByProductId?: Map<string, Set<string>>
3652 ):
3653 | ProductTypes.CreateProductVariantDTO[]
3654 | ProductTypes.UpdateProductVariantDTO[] {
3655 if (!variants.length) {
3656 return variants
3657 }
3658 const variantsWithOptions = variants.map((variant: any) => {
3659 const numOfProvidedVariantOptionValues = Object.keys(
3660 variant.options || {}
3661 ).length
3662
3663 const productsOptions = optionsByProductId.get(variant.product_id) ?? []
3664 const allowedValueIds = valueIdsByProductId?.get(variant.product_id)
3665
3666 if (
3667 numOfProvidedVariantOptionValues &&
3668 productsOptions.length !== numOfProvidedVariantOptionValues
3669 ) {
3670 throw new MedusaError(
3671 MedusaError.Types.INVALID_DATA,
3672 `Product has ${productsOptions.length} option values but there were ${numOfProvidedVariantOptionValues} provided option values for the variant: ${variant.title}.`
3673 )
3674 }
3675
3676 const variantOptions = Object.entries(variant.options || {}).map(
3677 ([key, val]) => {
3678 const option = productsOptions.find((o) => o.title === key)
3679 const optionValue = resolveAllowedOptionValues({
3680 optionTitle: key,
3681 value: val,
3682 optionValues: option?.values,
3683 allowedValueIds,
3684 })
3685
3686 return {
3687 id: optionValue.id,
3688 }
3689 }
3690 )
3691
3692 if (!variantOptions.length) {
3693 return variant
3694 }
3695
3696 return {
3697 ...variant,
3698 options: variantOptions,
3699 }
3700 })
3701
3702 return variantsWithOptions
3703 }
3704
3705 /**
3706 * Validate that `data` doesn't create or update a variant to have same options combination
3707 * as an existing variant on the product.
3708 * @param data - create / update payloads
3709 * @param variants - existing variants
3710 * @protected
3711 */
3712 protected static checkIfVariantWithOptionsAlreadyExists(
3713 data: ((
3714 | ProductTypes.CreateProductVariantDTO
3715 | UpdateProductVariantInput
3716 ) & { options: { id: string }[]; product_id: string })[],
3717 variants: InferEntityType<typeof ProductVariant>[]
3718 ) {
3719 for (const variantData of data) {
3720 const existingVariant = variants.find((v) => {
3721 if (
3722 variantData.product_id! !== v.product_id ||
3723 !variantData.options?.length
3724 ) {
3725 return false
3726 }
3727
3728 if ((variantData as UpdateProductVariantInput)?.id === v.id) {
3729 return false
3730 }
3731
3732 return (variantData.options as unknown as { id: string }[])!.every(
3733 (optionValue) => {
3734 const variantOptionValue = v.options.find(
3735 (vo) => vo.id === optionValue.id
3736 )
3737 return !!variantOptionValue
3738 }
3739 )
3740 })
3741
3742 if (existingVariant) {
3743 throw new MedusaError(
3744 MedusaError.Types.INVALID_DATA,
3745 `Variant (${existingVariant.title}) with provided options already exists.`
3746 )
3747 }
3748 }
3749 }
3750
3751 /**
3752 * Validate that array of variants that we are upserting doesn't have variants with the same options.
3753 * @param variants -
3754 * @protected
3755 */
3756 protected static checkIfVariantsHaveUniqueOptionsCombinations(
3757 variants: (ProductTypes.UpdateProductVariantDTO & {
3758 options: { id: string }[]
3759 })[]
3760 ) {
3761 for (let i = 0; i < variants.length; i++) {
3762 const variant = variants[i]
3763 for (let j = i + 1; j < variants.length; j++) {
3764 const compareVariant = variants[j]
3765
3766 const exists = variant.options?.every(
3767 (optionValue) =>
3768 !!compareVariant.options.find(
3769 (compareOptionValue) => compareOptionValue.id === optionValue.id
3770 )
3771 )
3772
3773 if (exists) {
3774 throw new MedusaError(
3775 MedusaError.Types.INVALID_DATA,
3776 `Variant "${variant.title}" has same combination of option values as "${compareVariant.title}".`
3777 )
3778 }
3779 }
3780 }
3781 }
3782
3783 @InjectManager()
3784 // @ts-ignore
3785 async listProductVariants(
3786 filters?: ProductTypes.FilterableProductVariantProps,
3787 config?: FindConfig<ProductTypes.ProductVariantDTO>,
3788 @MedusaContext() sharedContext: Context = {}
3789 ): Promise<ProductTypes.ProductVariantDTO[]> {
3790 const shouldLoadImages = config?.relations?.includes("images")
3791
3792 const relations = [...(config?.relations || [])]
3793 if (shouldLoadImages) {
3794 relations.push("product.images")
3795 }
3796
3797 const variants = await this.productVariantService_.list(
3798 filters,
3799 {
3800 ...config,
3801 relations,
3802 },
3803 sharedContext
3804 )
3805
3806 if (shouldLoadImages) {
3807 // Get variant images for all variants
3808 const variantImagesMap = await this.getVariantImages(
3809 variants,
3810 sharedContext
3811 )
3812
3813 for (const variant of variants) {
3814 variant.images = variantImagesMap.get(variant.id) || []
3815 }
3816 }
3817
3818 return this.baseRepository_.serialize<ProductTypes.ProductVariantDTO[]>(
3819 variants
3820 )
3821 }
3822
3823 @InjectManager()
3824 // @ts-ignore
3825 async listAndCountProductVariants(
3826 filters?: ProductTypes.FilterableProductVariantProps,
3827 config?: FindConfig<ProductTypes.ProductVariantDTO>,
3828 @MedusaContext() sharedContext: Context = {}
3829 ): Promise<[ProductTypes.ProductVariantDTO[], number]> {
3830 const shouldLoadImages = config?.relations?.includes("images")
3831
3832 const relations = [...(config?.relations || [])]
3833 if (shouldLoadImages) {
3834 relations.push("product.images")
3835 }
3836
3837 const [variants, count] = await this.productVariantService_.listAndCount(
3838 filters,
3839 {
3840 ...config,
3841 relations,
3842 },
3843 sharedContext
3844 )
3845
3846 if (shouldLoadImages) {
3847 // Get variant images for all variants
3848 const variantImagesMap = await this.getVariantImages(
3849 variants,
3850 sharedContext
3851 )
3852
3853 for (const variant of variants) {
3854 variant.images = variantImagesMap.get(variant.id) || []
3855 }
3856 }
3857
3858 const serializedVariants = await this.baseRepository_.serialize<
3859 ProductTypes.ProductVariantDTO[]
3860 >(variants)
3861 return [serializedVariants, count]
3862 }
3863
3864 @InjectManager()
3865 // @ts-ignore
3866 async retrieveProductVariant(
3867 id: string,
3868 config?: FindConfig<any>,
3869 @MedusaContext() sharedContext: Context = {}
3870 ): Promise<any> {
3871 const shouldLoadImages = config?.relations?.includes("images")
3872
3873 const relations = [...(config?.relations || [])]
3874 if (shouldLoadImages) {
3875 relations.push("images", "product", "product.images")
3876 }
3877
3878 const variant = await this.productVariantService_.retrieve(
3879 id,
3880 {
3881 ...config,
3882 relations,
3883 },
3884 sharedContext
3885 )
3886
3887 if (shouldLoadImages) {
3888 const variantImages = await this.getVariantImages(
3889 [variant],
3890 sharedContext
3891 )
3892 variant.images = variantImages.get(id) || []
3893 }
3894
3895 return this.baseRepository_.serialize(variant)
3896 }
3897
3898 @InjectManager()
3899 async addImageToVariant(
3900 data: VariantImageInputArray,
3901 @MedusaContext() sharedContext: Context = {}
3902 ): Promise<{ id: string }[]> {
3903 const productVariantProductImage = await this.addImageToVariant_(
3904 data,
3905 sharedContext
3906 )
3907
3908 return productVariantProductImage as { id: string }[]
3909 }
3910
3911 @InjectTransactionManager()
3912 protected async addImageToVariant_(
3913 data: VariantImageInputArray,
3914 @MedusaContext() sharedContext: Context = {}
3915 ): Promise<{ id: string } | { id: string }[]> {
3916 // TODO: consider validation that image and variant are on the same product
3917
3918 const productVariantProductImage =
3919 await this.productVariantProductImageService_.create(data, sharedContext)
3920
3921 return (
3922 productVariantProductImage as unknown as InferEntityType<
3923 typeof ProductVariantProductImage
3924 >[]
3925 ).map((vi) => ({ id: vi.id }))
3926 }
3927
3928 @InjectManager()
3929 async removeImageFromVariant(
3930 data: VariantImageInputArray,
3931 @MedusaContext() sharedContext: Context = {}
3932 ): Promise<void> {
3933 await this.removeImageFromVariant_(data, sharedContext)
3934 }
3935
3936 @InjectTransactionManager()
3937 protected async removeImageFromVariant_(
3938 data: VariantImageInputArray,
3939 @MedusaContext() sharedContext: Context = {}
3940 ): Promise<void> {
3941 const pairs = Array.isArray(data) ? data : [data]
3942 const productVariantProductImages =
3943 await this.productVariantProductImageService_.list({
3944 $or: pairs,
3945 })
3946
3947 await this.productVariantProductImageService_.delete(
3948 productVariantProductImages.map((p) => p.id as string),
3949 sharedContext
3950 )
3951 }
3952
3953 @InjectManager()
3954 private async getVariantImages(
3955 variants: Pick<
3956 InferEntityType<typeof ProductVariant>,
3957 "id" | "product_id"
3958 >[],
3959 context: Context = {}
3960 ): Promise<Map<string, InferEntityType<typeof ProductImage>[]>> {
3961 if (variants.length === 0) {
3962 return new Map()
3963 }
3964
3965 // Create lookup maps for efficient processing
3966 const uniqueProductIds = new Set<string>()
3967
3968 // Build lookup maps
3969 for (const variant of variants) {
3970 if (variant.product_id) {
3971 uniqueProductIds.add(variant.product_id)
3972 }
3973 }
3974
3975 const allProductImages = (await this.listProductImages(
3976 { product_id: Array.from(uniqueProductIds) },
3977 {
3978 relations: ["variants"],
3979 },
3980 context
3981 )) as (ProductTypes.ProductImageDTO & {
3982 product_id: string
3983 variants: InferEntityType<typeof ProductVariant>[]
3984 })[]
3985
3986 // all product images
3987 const imagesByProductId = new Map<string, typeof allProductImages>()
3988 // variant specific images
3989 const variantSpecificImageIds = new Map<string, Set<string>>()
3990
3991 // Single pass to build both lookup maps
3992 for (const img of allProductImages) {
3993 // Group by product_id
3994 if (!imagesByProductId.has(img.product_id)) {
3995 imagesByProductId.set(img.product_id, [])
3996 }
3997 imagesByProductId.get(img.product_id)!.push(img)
3998
3999 // Track variant-specific images
4000 if (img.variants.length > 0) {
4001 for (const variant of img.variants) {
4002 if (!variantSpecificImageIds.has(variant.id)) {
4003 variantSpecificImageIds.set(variant.id, new Set())
4004 }
4005 variantSpecificImageIds.get(variant.id)!.add(img.id || "")
4006 }
4007 }
4008 }
4009
4010 const result = new Map<string, InferEntityType<typeof ProductImage>[]>()
4011
4012 for (const variant of variants) {
4013 const productId = variant.product_id!
4014
4015 const productImages = imagesByProductId.get(productId) || []
4016 const specificImageIds =
4017 variantSpecificImageIds.get(variant.id) || new Set()
4018
4019 const variantImages = productImages.filter((img) => {
4020 // general product image
4021 if (!img.variants.length) {
4022 return true
4023 }
4024 // Check if this image is specifically associated with this variant
4025 return specificImageIds.has(img.id || "")
4026 })
4027
4028 result.set(
4029 variant.id,
4030 variantImages as InferEntityType<typeof ProductImage>[]
4031 )
4032 }
4033
4034 return result
4035 }
4036
4037 /*
4038 * Validates that no variants are using the specified option values before
4039 * they are removed from a product.
4040 *
4041 * @param pairs - Array of validation pairs: { productId, optionId, valueIdsToCheck }
4042 * @param sharedContext - The shared context
4043 * @throws MedusaError if any variants are using the values
4044 */
4045 @InjectTransactionManager()
4046 protected async validateOptionRemoval_(
4047 pairs: Array<{
4048 productId: string
4049 optionId: string
4050 valueIdsToCheck: string[]
4051 }>,
4052 @MedusaContext() sharedContext: Context = {}
4053 ): Promise<void> {
4054 const bulkValidationPairs = pairs
4055 .filter((pair) => pair.valueIdsToCheck.length)
4056 .map((pair) => ({
4057 productId: pair.productId,
4058 optionValueIds: pair.valueIdsToCheck,
4059 }))
4060
4061 if (bulkValidationPairs.length > 0) {
4062 const conflictingVariantsMap =
4063 await this.productRepository_.checkVariantsUsingOptionValues(
4064 bulkValidationPairs.map((p) => ({
4065 productId: p.productId,
4066 optionValueIds: p.optionValueIds,
4067 })),
4068 sharedContext
4069 )
4070
4071 for (const bulkPair of bulkValidationPairs) {
4072 const allConflictingVariants: Array<{
4073 variant_id: string
4074 title: string | null
4075 }> = []
4076
4077 for (const valueId of bulkPair.optionValueIds) {
4078 const key = `${bulkPair.productId}_${valueId}`
4079 const variants = conflictingVariantsMap.get(key) || []
4080 // Deduplicate variants by variant_id
4081 for (const variant of variants) {
4082 if (
4083 !allConflictingVariants.some(
4084 (v) => v.variant_id === variant.variant_id
4085 )
4086 ) {
4087 allConflictingVariants.push({
4088 variant_id: variant.variant_id,
4089 title: variant.title,
4090 })
4091 }
4092 }
4093 }
4094
4095 if (allConflictingVariants.length > 0) {
4096 const variantNames = allConflictingVariants.map(
4097 (v) => v.title || v.variant_id
4098 )
4099
4100 throw new MedusaError(
4101 MedusaError.Types.INVALID_DATA,
4102 `Cannot unassign option values from product because the following variant(s) are using it: ${variantNames.join(
4103 ", "
4104 )}`
4105 )
4106 }
4107 }
4108 }
4109 }
4110
4111 private async filterOptionValues(
4112 products: FilterableProduct | FilterableProduct[],
4113 sharedContext: Context = {}
4114 ): Promise<void> {
4115 const productsList = Array.isArray(products) ? products : [products]
4116
4117 if (!productsList.length) {
4118 return
4119 }
4120
4121 const productsWithOptions = productsList.filter(
4122 (product) => (product.options ?? []).length > 0
4123 )
4124
4125 if (!productsWithOptions.length) {
4126 return
4127 }
4128
4129 const productIds = productsWithOptions
4130 .map((product) => product.id)
4131 .filter((id): id is string => !!id)
4132
4133 if (!productIds.length) {
4134 return
4135 }
4136
4137 const allowedValueIdsByProduct =
4138 await this.productRepository_.getOptionValueIdsByProductIds(
4139 productIds,
4140 sharedContext
4141 )
4142
4143 for (const product of productsWithOptions) {
4144 const allowedValueIds =
4145 allowedValueIdsByProduct.get(product.id) ?? new Set<string>()
4146
4147 const options = product.options ?? []
4148
4149 for (const option of options) {
4150 const values = option.values ?? []
4151
4152 option.values = values.filter((value) => allowedValueIds.has(value.id))
4153 }
4154
4155 product.options = options
4156 }
4157 }
4158
4159 /**
4160 * Assigns the computed `images` value to each variant of the given products:
4161 * every variant receives the product's general images (images not assigned
4162 * to any variant), and variants with specific assignments additionally
4163 * receive those images. This union is what `variants.images` exposes — it
4164 * cannot be loaded through the m:n relation, which only contains explicit
4165 * assignments.
4166 *
4167 * The products are expected to be serialized already. The assignment is
4168 * intentionally performed on plain DTOs (after serialization) so that no
4169 * ORM entity ever leaks into the returned payload, and the variant <> image
4170 * relations are fetched in a single query for all products.
4171 */
4172 private async assignImagesToVariants(
4173 products: {
4174 variants?: { id: string; images?: ProductTypes.ProductImageDTO[] }[]
4175 images?: ProductTypes.ProductImageDTO[]
4176 }[],
4177 sharedContext: Context = {}
4178 ): Promise<void> {
4179 const productsToProcess = products.filter(
4180 (product) => product.variants?.length && product.images
4181 )
4182
4183 const variantIds = productsToProcess.flatMap((product) =>
4184 product.variants!.map((variant) => variant.id)
4185 )
4186
4187 if (!variantIds.length) {
4188 return
4189 }
4190
4191 const variantImageRelations =
4192 await this.productVariantProductImageService_.list(
4193 { variant_id: variantIds },
4194 { select: ["variant_id", "image_id"] },
4195 sharedContext
4196 )
4197
4198 const variantIdImageIdsMap = new Map<string, Set<string>>()
4199 const imageIdsWithVariants = new Set<string>()
4200
4201 // build both lookup
4202 for (const relation of variantImageRelations) {
4203 if (!variantIdImageIdsMap.has(relation.variant_id)) {
4204 variantIdImageIdsMap.set(relation.variant_id, new Set())
4205 }
4206 variantIdImageIdsMap.get(relation.variant_id)!.add(relation.image_id)
4207
4208 imageIdsWithVariants.add(relation.image_id)
4209 }
4210
4211 for (const product of productsToProcess) {
4212 const [generalImages, variantImages] = partitionArray(
4213 product.images!,
4214 (img) => !imageIdsWithVariants.has(img.id) // if image doesn't have any variants, it is a general image
4215 )
4216
4217 for (const variant of product.variants!) {
4218 const variantImageIds = variantIdImageIdsMap.get(variant.id)
4219
4220 variant.images = [...generalImages]
4221
4222 if (!variantImageIds?.size) {
4223 continue
4224 }
4225
4226 for (const image of variantImages) {
4227 if (variantImageIds.has(image.id)) {
4228 variant.images.push(image)
4229 }
4230 }
4231 }
4232 }
4233 }
4234
4235 protected async loadOptionsAndValuesByProductId_(
4236 productIds: string[],
4237 sharedContext: Context = {}
4238 ): Promise<{
4239 optionsByProductId: Map<string, InferEntityType<typeof ProductOption>[]>
4240 valueIdsByProductId: Map<string, Set<string>>
4241 }> {
4242 const [productOptions, optionIdsByProductId, valueIdsByProductId] =
4243 await promiseAll([
4244 this.productOptionService_.list(
4245 { products: { id: productIds } },
4246 { relations: ["values"] },
4247 sharedContext
4248 ),
4249 this.productRepository_.getOptionIdsByProductIds(
4250 productIds,
4251 sharedContext
4252 ),
4253 this.productRepository_.getOptionValueIdsByProductIds(
4254 productIds,
4255 sharedContext
4256 ),
4257 ])
4258
4259 const optionsById = new Map(productOptions.map((o) => [o.id, o]))
4260 const optionsByProductId = new Map<
4261 string,
4262 InferEntityType<typeof ProductOption>[]
4263 >()
4264 for (const [productId, optionIds] of optionIdsByProductId) {
4265 const opts: InferEntityType<typeof ProductOption>[] = []
4266 optionIds.forEach((id) => {
4267 const opt = optionsById.get(id)
4268 if (opt) {
4269 opts.push(opt)
4270 }
4271 })
4272 optionsByProductId.set(productId, opts)
4273 }
4274
4275 return { optionsByProductId, valueIdsByProductId }
4276 }
4277 }