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