Raw
1 import {
2 AddPricesDTO,
3 Context,
4 CreatePricePreferenceDTO,
5 CreatePriceRuleDTO,
6 CreatePricesDTO,
7 CreatePriceSetDTO,
8 DAL,
9 FindConfig,
10 InferEntityType,
11 InternalModuleDeclaration,
12 MedusaContainer,
13 ModuleJoinerConfig,
14 ModulesSdkTypes,
15 PricePreferenceDTO,
16 PriceSetDTO,
17 PricingContext,
18 PricingFilters,
19 PricingRepositoryService,
20 PricingRuleOperatorValues,
21 PricingTypes,
22 UpsertPricePreferenceDTO,
23 UpsertPriceSetDTO,
24 } from "@medusajs/framework/types"
25 import {
26 arrayDifference,
27 deduplicate,
28 EmitEvents,
29 GetIsoStringFromDate,
30 groupBy,
31 InjectManager,
32 InjectTransactionManager,
33 isDefined,
34 isPresent,
35 isString,
36 MathBN,
37 MedusaContext,
38 MedusaError,
39 mergeMetadata,
40 ModulesSdkUtils,
41 normalizeCurrencyCode,
42 PriceListType,
43 PricingRuleOperator,
44 promiseAll,
45 removeNullish,
46 } from "@medusajs/framework/utils"
47
48 import {
49 Price,
50 PriceList,
51 PriceListRule,
52 PricePreference,
53 PriceRule,
54 PriceSet,
55 } from "@models"
56
57 import { Collection } from "@medusajs/framework/mikro-orm/core"
58 import { ServiceTypes } from "@types"
59 import { validatePriceListDates } from "@utils"
60 import { joinerConfig } from "../joiner-config"
61
62 type InjectedDependencies = {
63 baseRepository: DAL.RepositoryService
64 pricingRepository: PricingRepositoryService
65 priceSetService: ModulesSdkTypes.IMedusaInternalService<any>
66 priceRuleService: ModulesSdkTypes.IMedusaInternalService<any>
67 priceService: ModulesSdkTypes.IMedusaInternalService<any>
68 priceListService: ModulesSdkTypes.IMedusaInternalService<any>
69 pricePreferenceService: ModulesSdkTypes.IMedusaInternalService<any>
70 priceListRuleService: ModulesSdkTypes.IMedusaInternalService<any>
71 }
72
73 const generateMethodForModels = {
74 PriceSet,
75 PriceList,
76 PriceListRule,
77 PriceRule,
78 Price,
79 PricePreference,
80 }
81
82 const BaseClass = ModulesSdkUtils.MedusaService<{
83 PriceSet: { dto: PricingTypes.PriceSetDTO }
84 Price: { dto: PricingTypes.PriceDTO }
85 PriceRule: {
86 dto: PricingTypes.PriceRuleDTO
87 create: PricingTypes.CreatePriceRuleDTO
88 update: PricingTypes.UpdatePriceRuleDTO
89 }
90 PriceList: { dto: PricingTypes.PriceListDTO }
91 PriceListRule: { dto: PricingTypes.PriceListRuleDTO }
92 // PricePreference: { dto: PricingTypes.PricePreferenceDTO }
93 PricePreference: { dto: any }
94 }>(generateMethodForModels)
95
96 export default class PricingModuleService
97 extends BaseClass
98 implements PricingTypes.IPricingModuleService
99 {
100 protected readonly container_: MedusaContainer
101 protected baseRepository_: DAL.RepositoryService
102 protected readonly pricingRepository_: PricingRepositoryService & {
103 clearAvailableAttributes?: () => Promise<void>
104 }
105 protected readonly priceSetService_: ModulesSdkTypes.IMedusaInternalService<
106 InferEntityType<typeof PriceSet>
107 >
108 protected readonly priceRuleService_: ModulesSdkTypes.IMedusaInternalService<
109 InferEntityType<typeof PriceRule>
110 >
111 protected readonly priceService_: ModulesSdkTypes.IMedusaInternalService<
112 InferEntityType<typeof Price>
113 >
114 protected readonly priceListService_: ModulesSdkTypes.IMedusaInternalService<
115 InferEntityType<typeof PriceList>
116 >
117 protected readonly priceListRuleService_: ModulesSdkTypes.IMedusaInternalService<
118 InferEntityType<typeof PriceListRule>
119 >
120 protected readonly pricePreferenceService_: ModulesSdkTypes.IMedusaInternalService<
121 InferEntityType<typeof PricePreference>
122 >
123
124 constructor(
125 {
126 baseRepository,
127 pricingRepository,
128 priceSetService,
129 priceRuleService,
130 priceService,
131 pricePreferenceService,
132 priceListService,
133 priceListRuleService,
134 }: InjectedDependencies,
135 protected readonly moduleDeclaration: InternalModuleDeclaration
136 ) {
137 // @ts-ignore
138 super(...arguments)
139
140 this.container_ = arguments[0]
141 this.baseRepository_ = baseRepository
142 this.pricingRepository_ = pricingRepository
143 this.priceSetService_ = priceSetService
144 this.priceRuleService_ = priceRuleService
145 this.priceService_ = priceService
146 this.pricePreferenceService_ = pricePreferenceService
147 this.priceListService_ = priceListService
148 this.priceListRuleService_ = priceListRuleService
149 }
150
151 __joinerConfig(): ModuleJoinerConfig {
152 return joinerConfig
153 }
154
155 private setupCalculatedPriceConfig_(
156 filters,
157 config
158 ): PricingContext["context"] | undefined {
159 const fieldIdx = config.relations?.indexOf("calculated_price")
160 const shouldCalculatePrice = fieldIdx > -1
161
162 const pricingContext = filters.context ?? {}
163
164 delete filters.context
165 if (!shouldCalculatePrice) {
166 return
167 }
168
169 // cleanup virtual field "calculated_price"
170 config.relations?.splice(fieldIdx, 1)
171
172 return pricingContext
173 }
174
175 @InjectTransactionManager()
176 @EmitEvents()
177 // @ts-expect-error
178 async createPriceRules(
179 ...args: Parameters<PricingTypes.IPricingModuleService["createPriceRules"]>
180 ): Promise<PricingTypes.PriceRuleDTO | PricingTypes.PriceRuleDTO[]> {
181 try {
182 return await super.createPriceRules(...args)
183 } finally {
184 this.pricingRepository_.clearAvailableAttributes?.()
185 }
186 }
187
188 @InjectTransactionManager()
189 @EmitEvents()
190 // @ts-expect-error
191 async updatePriceRules(
192 ...args: Parameters<PricingTypes.IPricingModuleService["updatePriceRules"]>
193 ): Promise<PricingTypes.PriceRuleDTO | PricingTypes.PriceRuleDTO[]> {
194 try {
195 return await super.updatePriceRules(...args)
196 } finally {
197 this.pricingRepository_.clearAvailableAttributes?.()
198 }
199 }
200
201 @InjectTransactionManager()
202 @EmitEvents()
203 // @ts-expect-error
204 async createPriceListRules(
205 ...args: any[]
206 ): Promise<PricingTypes.PriceListRuleDTO | PricingTypes.PriceListRuleDTO[]> {
207 try {
208 // @ts-ignore
209 return await super.createPriceListRules(...args)
210 } finally {
211 this.pricingRepository_.clearAvailableAttributes?.()
212 }
213 }
214
215 @InjectTransactionManager()
216 @EmitEvents()
217 // @ts-expect-error
218 async updatePriceListRules(
219 ...args: any[]
220 ): Promise<PricingTypes.PriceListRuleDTO | PricingTypes.PriceListRuleDTO[]> {
221 try {
222 // @ts-ignore
223 return await super.updatePriceListRules(...args)
224 } finally {
225 this.pricingRepository_.clearAvailableAttributes?.()
226 }
227 }
228
229 @InjectManager()
230 // @ts-expect-error
231 async retrievePriceSet(
232 id: string,
233 config?: FindConfig<PriceSetDTO> | undefined,
234 sharedContext?: Context | undefined
235 ): Promise<PriceSetDTO> {
236 const priceSet = await this.priceSetService_.retrieve(
237 id,
238 this.normalizePriceSetConfig(config),
239 sharedContext
240 )
241
242 return await this.baseRepository_.serialize<PriceSetDTO>(priceSet)
243 }
244
245 @InjectManager()
246 // @ts-expect-error
247 async listPriceSets(
248 filters: PricingTypes.FilterablePriceSetProps = {},
249 config: FindConfig<PricingTypes.PriceSetDTO> = {},
250 @MedusaContext() sharedContext: Context = {}
251 ): Promise<PriceSetDTO[]> {
252 const normalizedConfig = this.normalizePriceSetConfig(config)
253 const pricingContext = this.setupCalculatedPriceConfig_(
254 filters,
255 normalizedConfig
256 )
257
258 const priceSets = await super.listPriceSets(
259 filters,
260 normalizedConfig,
261 sharedContext
262 )
263 if (!pricingContext || !priceSets.length) {
264 return priceSets
265 }
266
267 const calculatedPrices = await this.calculatePrices(
268 { id: priceSets.map((p) => p.id) },
269 { context: pricingContext },
270 sharedContext
271 )
272
273 const calculatedPricesMap = new Map()
274 for (const calculatedPrice of calculatedPrices) {
275 calculatedPricesMap.set(calculatedPrice.id, calculatedPrice)
276 }
277
278 for (const priceSet of priceSets) {
279 const calculatedPrice = calculatedPricesMap.get(priceSet.id)
280 priceSet.calculated_price = calculatedPrice ?? null
281 }
282
283 return await this.baseRepository_.serialize<PriceSetDTO[]>(priceSets)
284 }
285
286 @InjectManager()
287 // @ts-expect-error
288 async listAndCountPriceSets(
289 filters: PricingTypes.FilterablePriceSetProps = {},
290 config: FindConfig<PricingTypes.PriceSetDTO> = {},
291 @MedusaContext() sharedContext: Context = {}
292 ): Promise<[PriceSetDTO[], number]> {
293 const normalizedConfig = this.normalizePriceSetConfig(config)
294 const pricingContext = this.setupCalculatedPriceConfig_(
295 filters,
296 normalizedConfig
297 )
298
299 const [priceSets, count] = await super.listAndCountPriceSets(
300 filters,
301 normalizedConfig,
302 sharedContext
303 )
304 if (!pricingContext || !priceSets.length) {
305 const serializedPriceSets = await this.baseRepository_.serialize<
306 PriceSetDTO[]
307 >(priceSets)
308 return [serializedPriceSets, count]
309 }
310
311 const calculatedPrices = await this.calculatePrices(
312 { id: priceSets.map((p) => p.id) },
313 { context: pricingContext },
314 sharedContext
315 )
316
317 const calculatedPricesMap = new Map()
318 for (const calculatedPrice of calculatedPrices) {
319 calculatedPricesMap.set(calculatedPrice.id, calculatedPrice)
320 }
321
322 for (const priceSet of priceSets) {
323 const calculatedPrice = calculatedPricesMap.get(priceSet.id)
324 priceSet.calculated_price = calculatedPrice ?? null
325 }
326
327 const serializedPriceSets = await this.baseRepository_.serialize<
328 PriceSetDTO[]
329 >(priceSets)
330
331 return [serializedPriceSets, count]
332 }
333
334 @InjectManager()
335 // @ts-expect-error
336 async listPriceRules(
337 filters: PricingTypes.FilterablePriceRuleProps,
338 config: FindConfig<PricingTypes.PriceRuleDTO> = {},
339 sharedContext?: Context
340 ): Promise<PricingTypes.PriceRuleDTO[]> {
341 const priceRules = await this.listPriceRules_(
342 filters,
343 config,
344 sharedContext
345 )
346
347 return await this.baseRepository_.serialize<PricingTypes.PriceRuleDTO[]>(
348 priceRules
349 )
350 }
351
352 protected async listPriceRules_(
353 filters: PricingTypes.FilterablePriceRuleProps,
354 config: FindConfig<PricingTypes.PriceRuleDTO> = {},
355 sharedContext?: Context
356 ): Promise<InferEntityType<typeof PriceRule>[]> {
357 return await this.priceRuleService_.list(filters, config, sharedContext)
358 }
359
360 @InjectManager()
361 // @ts-expect-error
362 async listPricePreferences(
363 filters: PricingTypes.FilterablePricePreferenceProps,
364 config: FindConfig<PricingTypes.PricePreferenceDTO> = {},
365 sharedContext?: Context
366 ): Promise<PricingTypes.PricePreferenceDTO[]> {
367 const pricePreferences = await this.listPricePreferences_(
368 filters,
369 config,
370 sharedContext
371 )
372
373 return await this.baseRepository_.serialize<
374 PricingTypes.PricePreferenceDTO[]
375 >(pricePreferences)
376 }
377
378 protected async listPricePreferences_(
379 filters: PricingTypes.FilterablePricePreferenceProps,
380 config: FindConfig<PricingTypes.PricePreferenceDTO> = {},
381 sharedContext?: Context
382 ): Promise<InferEntityType<typeof PricePreference>[]> {
383 return await this.pricePreferenceService_.list(
384 filters,
385 config,
386 sharedContext
387 )
388 }
389
390 @InjectManager()
391 async calculatePrices(
392 pricingFilters: PricingFilters,
393 pricingContext: PricingContext = { context: {} },
394 @MedusaContext() sharedContext: Context = {}
395 ): Promise<PricingTypes.CalculatedPriceSet[]> {
396 const results = await this.pricingRepository_.calculatePrices(
397 pricingFilters,
398 pricingContext,
399 sharedContext
400 )
401
402 const pricesSetPricesMap = groupBy(results, "price_set_id")
403 const priceIds: string[] = []
404 pricesSetPricesMap.forEach(
405 (prices: PricingTypes.CalculatedPriceSetDTO[], key) => {
406 const priceListPrice = prices.find((p) => p.price_list_id)
407 const defaultPrice = prices?.find((p) => !p.price_list_id)
408 if (!prices.length || (!priceListPrice && !defaultPrice)) {
409 pricesSetPricesMap.delete(key)
410 return
411 }
412
413 /**
414 * The original price is the customer's real (non-sale) reference price.
415 * It is the matching OVERRIDE price list price if one applies, otherwise
416 * the default price. Resolving it over the non-sale subset (rather than
417 * defaulting to the base price) ensures a stacked SALE does not anchor the
418 * reference to the base price when the customer has an OVERRIDE.
419 */
420 const nonSalePrices = prices.filter(
421 (p) => p.price_list_type !== PriceListType.SALE
422 )
423 const nonSalePriceListPrice = nonSalePrices.find((p) => p.price_list_id)
424
425 let calculatedPrice: PricingTypes.CalculatedPriceSetDTO | undefined =
426 defaultPrice
427 let originalPrice: PricingTypes.CalculatedPriceSetDTO | undefined =
428 nonSalePriceListPrice ?? defaultPrice
429
430 /**
431 * When deciding which price to use we follow the following logic:
432 * - If the price list is of type OVERRIDE, we always use the price list price.
433 * - If there are multiple price list prices of type OVERRIDE, we use the one with the lowest amount.
434 * - If the price list is of type SALE, we use the lowest price between the price list price and the default price
435 */
436 if (priceListPrice) {
437 switch (priceListPrice.price_list_type) {
438 case PriceListType.OVERRIDE:
439 calculatedPrice = priceListPrice
440 originalPrice = priceListPrice
441 break
442 case PriceListType.SALE: {
443 let lowestPrice = priceListPrice
444
445 if (defaultPrice?.amount && priceListPrice.amount) {
446 lowestPrice = MathBN.lte(
447 priceListPrice.amount,
448 defaultPrice.amount
449 )
450 ? priceListPrice
451 : defaultPrice
452 }
453
454 calculatedPrice = lowestPrice
455 break
456 }
457 }
458 }
459
460 pricesSetPricesMap.set(key, { calculatedPrice, originalPrice })
461 priceIds.push(
462 ...(deduplicate(
463 [calculatedPrice?.id, originalPrice?.id].filter(Boolean)
464 ) as string[])
465 )
466 }
467 )
468
469 // We use the price rules to get the right preferences for the price
470 const priceRulesForPrices = await this.listPriceRules(
471 { price_id: priceIds },
472 {},
473 sharedContext
474 )
475
476 const priceRulesPriceMap = groupBy(priceRulesForPrices, "price_id")
477
478 // Note: For now the preferences are intentionally kept very simple and explicit - they use either the region or currency,
479 // so we hard-code those as the possible filters here. This can be made more flexible if needed later on.
480 const preferenceContext = Object.entries(
481 pricingContext.context ?? {}
482 ).filter(([key, val]) => {
483 return key === "region_id" || key === "currency_code"
484 })
485 let pricingPreferences: InferEntityType<typeof PricePreference>[] = []
486 if (preferenceContext.length) {
487 const preferenceFilters = preferenceContext.length
488 ? {
489 $or: preferenceContext.map(([key, val]) => ({
490 attribute: key,
491 value: val,
492 })),
493 }
494 : {}
495 pricingPreferences = await this.listPricePreferences_(
496 preferenceFilters as PricingTypes.FilterablePricePreferenceProps,
497 {},
498 sharedContext
499 )
500 }
501
502 const calculatedPrices: PricingTypes.CalculatedPriceSet[] = []
503
504 for (const priceSetId of pricingFilters.id) {
505 const prices = pricesSetPricesMap.get(priceSetId)
506 if (!prices) {
507 continue
508 }
509
510 const {
511 calculatedPrice,
512 originalPrice,
513 }: {
514 calculatedPrice: PricingTypes.CalculatedPriceSetDTO
515 originalPrice: PricingTypes.CalculatedPriceSetDTO | undefined
516 } = prices
517
518 const calculatedPrice_: PricingTypes.CalculatedPriceSet = {
519 id: priceSetId,
520 is_calculated_price_price_list: !!calculatedPrice?.price_list_id,
521 is_calculated_price_tax_inclusive: isTaxInclusive(
522 priceRulesPriceMap.get(calculatedPrice.id),
523 pricingPreferences,
524 calculatedPrice.currency_code!,
525 pricingContext.context?.region_id as string
526 ),
527 calculated_amount: isPresent(calculatedPrice?.amount)
528 ? parseFloat(calculatedPrice?.amount as string)
529 : null,
530 raw_calculated_amount: calculatedPrice?.raw_amount || null,
531
532 is_original_price_price_list: !!originalPrice?.price_list_id,
533 is_original_price_tax_inclusive: originalPrice?.id
534 ? isTaxInclusive(
535 priceRulesPriceMap.get(originalPrice.id),
536 pricingPreferences,
537 originalPrice.currency_code || calculatedPrice.currency_code!,
538 pricingContext.context?.region_id as string
539 )
540 : false,
541 original_amount: isPresent(originalPrice?.amount)
542 ? parseFloat(originalPrice?.amount as string)
543 : null,
544 raw_original_amount: originalPrice?.raw_amount || null,
545
546 currency_code: calculatedPrice?.currency_code || null,
547
548 calculated_price: {
549 id: calculatedPrice?.id || null,
550 price_list_id: calculatedPrice?.price_list_id || null,
551 price_list_type: calculatedPrice?.price_list_type || null,
552 min_quantity: parseFloat(calculatedPrice?.min_quantity || "") || null,
553 max_quantity: parseFloat(calculatedPrice?.max_quantity || "") || null,
554 },
555
556 original_price: {
557 id: originalPrice?.id || null,
558 price_list_id: originalPrice?.price_list_id || null,
559 price_list_type: originalPrice?.price_list_type || null,
560 min_quantity: parseFloat(originalPrice?.min_quantity || "") || null,
561 max_quantity: parseFloat(originalPrice?.max_quantity || "") || null,
562 },
563 }
564
565 calculatedPrices.push(calculatedPrice_)
566 }
567
568 return calculatedPrices
569 }
570
571 // @ts-expect-error
572 async createPriceSets(
573 data: PricingTypes.CreatePriceSetDTO,
574 sharedContext?: Context
575 ): Promise<PriceSetDTO>
576
577 // @ts-expect-error
578 async createPriceSets(
579 data: PricingTypes.CreatePriceSetDTO[],
580 sharedContext?: Context
581 ): Promise<PriceSetDTO[]>
582
583 @InjectManager()
584 @EmitEvents()
585 // @ts-expect-error
586 async createPriceSets(
587 data: PricingTypes.CreatePriceSetDTO | PricingTypes.CreatePriceSetDTO[],
588 @MedusaContext() sharedContext: Context = {}
589 ): Promise<PriceSetDTO | PriceSetDTO[]> {
590 const input = Array.isArray(data) ? data : [data]
591 const priceSets = await this.createPriceSets_(input, sharedContext)
592
593 // TODO: Remove the need to refetch the data here
594 const dbPriceSets = await this.listPriceSets(
595 { id: priceSets.map((p) => p.id) },
596 this.normalizePriceSetConfig({
597 relations: ["prices", "prices.price_rules"],
598 }),
599 sharedContext
600 )
601
602 // Ensure the output to be in the same order as the input
603 const results = priceSets.map((priceSet) => {
604 return dbPriceSets.find((p) => p.id === priceSet.id)!
605 })
606
607 try {
608 return await this.baseRepository_.serialize<PriceSetDTO[] | PriceSetDTO>(
609 Array.isArray(data) ? results : results[0]
610 )
611 } finally {
612 this.pricingRepository_.clearAvailableAttributes?.()
613 }
614 }
615
616 async upsertPriceSets(
617 data: UpsertPriceSetDTO[],
618 sharedContext?: Context
619 ): Promise<PriceSetDTO[]>
620 async upsertPriceSets(
621 data: UpsertPriceSetDTO,
622 sharedContext?: Context
623 ): Promise<PriceSetDTO>
624
625 @InjectManager()
626 @EmitEvents()
627 async upsertPriceSets(
628 data: UpsertPriceSetDTO | UpsertPriceSetDTO[],
629 @MedusaContext() sharedContext: Context = {}
630 ): Promise<PriceSetDTO | PriceSetDTO[]> {
631 const result = await this.upsertPriceSets_(data, sharedContext)
632
633 try {
634 return await this.baseRepository_.serialize<PriceSetDTO[] | PriceSetDTO>(
635 Array.isArray(data) ? result : result[0]
636 )
637 } finally {
638 this.pricingRepository_.clearAvailableAttributes?.()
639 }
640 }
641
642 @InjectTransactionManager()
643 protected async upsertPriceSets_(
644 data: UpsertPriceSetDTO | UpsertPriceSetDTO[],
645 @MedusaContext() sharedContext: Context = {}
646 ): Promise<InferEntityType<typeof PriceSet>[]> {
647 const input = Array.isArray(data) ? data : [data]
648
649 const forUpdate = input.filter(
650 (priceSet): priceSet is ServiceTypes.UpdatePriceSetInput => !!priceSet.id
651 )
652 const forCreate = input.filter(
653 (priceSet): priceSet is CreatePriceSetDTO => !priceSet.id
654 )
655
656 const operations: Promise<InferEntityType<typeof PriceSet>[]>[] = []
657
658 if (forCreate.length) {
659 operations.push(this.createPriceSets_(forCreate, sharedContext))
660 }
661 if (forUpdate.length) {
662 operations.push(this.updatePriceSets_(forUpdate, sharedContext))
663 }
664
665 const result = (await promiseAll(operations)).flat()
666
667 return result
668 }
669
670 // @ts-expect-error
671 async updatePriceSets(
672 id: string,
673 data: PricingTypes.UpdatePriceSetDTO,
674 sharedContext?: Context
675 ): Promise<PriceSetDTO>
676 // @ts-expect-error
677 async updatePriceSets(
678 selector: PricingTypes.FilterablePriceSetProps,
679 data: PricingTypes.UpdatePriceSetDTO,
680 sharedContext?: Context
681 ): Promise<PriceSetDTO[]>
682
683 @InjectManager()
684 @EmitEvents()
685 // @ts-expect-error
686 async updatePriceSets(
687 idOrSelector: string | PricingTypes.FilterablePriceSetProps,
688 data: PricingTypes.UpdatePriceSetDTO,
689 @MedusaContext() sharedContext: Context = {}
690 ): Promise<PriceSetDTO | PriceSetDTO[]> {
691 let normalizedInput: ServiceTypes.UpdatePriceSetInput[] = []
692 if (isString(idOrSelector)) {
693 // Check if the ID exists, it will throw if not.
694 await this.priceSetService_.retrieve(idOrSelector, {}, sharedContext)
695 normalizedInput = [{ id: idOrSelector, ...data }]
696 } else {
697 const priceSets = await this.priceSetService_.list(
698 idOrSelector,
699 {},
700 sharedContext
701 )
702
703 normalizedInput = priceSets.map((priceSet) => ({
704 id: priceSet.id,
705 ...data,
706 }))
707 }
708
709 const updateResult = await this.updatePriceSets_(
710 normalizedInput,
711 sharedContext
712 )
713
714 const serializedUpdateResult = await this.baseRepository_.serialize<
715 PriceSetDTO[] | PriceSetDTO
716 >(isString(idOrSelector) ? updateResult[0] : updateResult)
717
718 try {
719 return serializedUpdateResult
720 } finally {
721 this.pricingRepository_.clearAvailableAttributes?.()
722 }
723 }
724
725 @InjectTransactionManager()
726 protected async updatePriceSets_(
727 data: ServiceTypes.UpdatePriceSetInput[],
728 @MedusaContext() sharedContext: Context = {}
729 ): Promise<InferEntityType<typeof PriceSet>[]> {
730 const normalizedData = await this.normalizeUpdateData(data)
731
732 const priceSetIds = normalizedData.map(({ id }) => id)
733 const existingPrices = await this.priceService_.list(
734 {
735 price_set_id: priceSetIds,
736 price_list_id: null,
737 },
738 {
739 relations: ["price_rules"],
740 take: null,
741 },
742 sharedContext
743 )
744
745 const existingPricesMap = new Map<string, InferEntityType<typeof Price>>(
746 existingPrices.map((p) => [p.id, p])
747 )
748
749 const prices = normalizedData.flatMap((priceSet) => priceSet.prices || [])
750
751 const pricesToCreate = prices.filter(
752 (price) => !price.id || !existingPricesMap.has(price.id)
753 )
754 const pricesToUpdate = prices.filter(
755 (price) => price.id && existingPricesMap.has(price.id)
756 )
757
758 const incomingPriceIds = new Set(prices.map((p) => p.id).filter(Boolean))
759 const pricesToDelete = existingPrices
760 .filter((existingPrice) => !incomingPriceIds.has(existingPrice.id))
761 .map((p) => p.id)
762
763 let createdPrices: InferEntityType<typeof Price>[] = []
764 let updatedPrices: InferEntityType<typeof Price>[] = []
765
766 if (pricesToCreate.length > 0) {
767 createdPrices = await this.priceService_.create(
768 pricesToCreate.map((price) => {
769 price.price_rules ??= []
770 return price
771 }),
772 sharedContext
773 )
774 }
775
776 if (pricesToUpdate.length > 0) {
777 // Handle price rules for updated prices
778 for (const priceToUpdate of pricesToUpdate) {
779 const existingPrice = existingPricesMap.get(priceToUpdate.id!)
780
781 if (priceToUpdate.price_rules?.length) {
782 const existingPriceRules = existingPrice?.price_rules || []
783
784 // Separate price rules for create, update, delete
785 const priceRulesToCreate = priceToUpdate.price_rules.filter(
786 (rule) => !("id" in rule)
787 )
788 const priceRulesToUpdate = priceToUpdate.price_rules.filter(
789 (rule) => "id" in rule
790 )
791
792 const incomingPriceRuleIds = new Set(
793 priceToUpdate.price_rules
794 .map((r) => "id" in r && r.id)
795 .filter(Boolean)
796 )
797 const priceRulesToDelete = existingPriceRules
798 .filter(
799 (existingRule) => !incomingPriceRuleIds.has(existingRule.id)
800 )
801 .map((r) => r.id)
802
803 let createdPriceRules: InferEntityType<typeof PriceRule>[] = []
804 let updatedPriceRules: InferEntityType<typeof PriceRule>[] = []
805
806 // Bulk operations for price rules
807 if (priceRulesToCreate.length > 0) {
808 createdPriceRules = await this.priceRuleService_.create(
809 priceRulesToCreate.map((rule) => ({
810 ...rule,
811 price_id: priceToUpdate.id,
812 })),
813 sharedContext
814 )
815 }
816
817 if (priceRulesToUpdate.length > 0) {
818 updatedPriceRules = await this.priceRuleService_.update(
819 priceRulesToUpdate,
820 sharedContext
821 )
822 }
823
824 if (priceRulesToDelete.length > 0) {
825 await this.priceRuleService_.delete(
826 priceRulesToDelete,
827 sharedContext
828 )
829 }
830
831 const upsertedPriceRules = [
832 ...createdPriceRules,
833 ...updatedPriceRules,
834 ]
835
836 priceToUpdate.price_rules = upsertedPriceRules
837 ;(priceToUpdate as InferEntityType<typeof Price>).rules_count =
838 upsertedPriceRules.length
839 } else if (
840 // In the case price_rules is provided but without any rules, we delete the existing rules
841 isDefined(priceToUpdate.price_rules) &&
842 priceToUpdate.price_rules.length === 0
843 ) {
844 const priceRuleToDelete = existingPrice?.price_rules?.map((r) => r.id)
845
846 if (priceRuleToDelete?.length) {
847 await this.priceRuleService_.delete(
848 priceRuleToDelete,
849 sharedContext
850 )
851 }
852
853 ;(priceToUpdate as InferEntityType<typeof Price>).rules_count = 0
854 } else {
855 // @ts-expect-error - we want to delete the rules_count property in any case even if provided by mistake
856 delete (priceToUpdate as InferEntityType<typeof Price>).rules_count
857 }
858 // We don't want to persist the price_rules in the database through the price service as it would not work
859 delete priceToUpdate.price_rules
860 }
861
862 updatedPrices = await this.priceService_.update(
863 pricesToUpdate,
864 sharedContext
865 )
866 }
867
868 if (pricesToDelete.length > 0) {
869 await this.priceService_.delete(pricesToDelete, sharedContext)
870 }
871
872 const priceSets = await this.priceSetService_.list(
873 { id: normalizedData.map(({ id }) => id) },
874 {
875 relations: ["prices", "prices.price_rules"],
876 },
877 sharedContext
878 )
879
880 const upsertedPricesMap = new Map<string, InferEntityType<typeof Price>[]>()
881
882 const upsertedPrices = [...createdPrices, ...updatedPrices]
883 upsertedPrices.forEach((price) => {
884 upsertedPricesMap.set(price.price_set_id, [
885 ...(upsertedPricesMap.get(price.price_set_id) || []),
886 price,
887 ])
888 })
889
890 // re assign the prices to the price sets to not have to refetch after the transaction and keep the bahaviour the same as expected. If the user needs more data, he can still re list the price set with the expected fields and relations that he needs
891
892 priceSets.forEach((ps) => {
893 ps.prices = upsertedPricesMap.get(ps.id) || []
894 })
895
896 return priceSets
897 }
898
899 private async normalizeUpdateData(data: ServiceTypes.UpdatePriceSetInput[]) {
900 return data.map((priceSet) => {
901 return {
902 ...priceSet,
903 prices: this.normalizePrices(
904 priceSet.prices?.map((p) => ({ ...p, price_set_id: priceSet.id })),
905 []
906 ),
907 }
908 })
909 }
910
911 private normalizePrices(
912 data: CreatePricesDTO[] | undefined,
913 existingPrices: PricingTypes.PriceDTO[],
914 priceListId?: string | undefined
915 ) {
916 const pricesToUpsert = new Map<
917 string,
918 CreatePricesDTO & { price_rules?: CreatePriceRuleDTO[] }
919 >()
920 const existingPricesMap = new Map<string, PricingTypes.PriceDTO>()
921 Array.from(existingPrices ?? []).forEach((price) => {
922 existingPricesMap.set(hashPrice(price), price)
923 })
924
925 const ruleOperatorsSet = new Set<PricingRuleOperatorValues>(
926 Object.values(PricingRuleOperator)
927 )
928 const validOperatorsList = Array.from(ruleOperatorsSet).join(", ")
929 const invalidOperatorError = `operator should be one of ${validOperatorsList}`
930
931 data?.forEach((price) => {
932 const cleanRules = price.rules ? removeNullish(price.rules) : {}
933
934 const rules = Object.entries(cleanRules).flatMap(([attribute, value]) => {
935 if (Array.isArray(value)) {
936 return value.map((customRule) => {
937 if (!ruleOperatorsSet.has(customRule.operator)) {
938 throw new MedusaError(
939 MedusaError.Types.INVALID_DATA,
940 invalidOperatorError
941 )
942 }
943
944 if (typeof customRule.value !== "number") {
945 throw new MedusaError(
946 MedusaError.Types.INVALID_DATA,
947 `value should be a number`
948 )
949 }
950
951 return {
952 attribute,
953 operator: customRule.operator,
954 // TODO: we throw above if value is not a number, but the model expect the value to be a string
955 value: customRule.value.toString(),
956 }
957 })
958 }
959
960 return {
961 attribute,
962 value,
963 }
964 })
965
966 const entry = price as ServiceTypes.UpsertPriceDTO
967
968 const hasRulesInput = isDefined(price.rules)
969 entry.price_list_id = priceListId
970 if (hasRulesInput) {
971 entry.price_rules = rules
972 entry.rules_count = rules.length
973 delete (entry as CreatePricesDTO).rules
974 }
975
976 if (isDefined(entry.currency_code)) {
977 entry.currency_code = normalizeCurrencyCode(entry.currency_code)!
978 }
979
980 const entryHash = hashPrice(entry)
981
982 // We want to keep the existing rules as they might already have ids, but any other data should come from the updated input
983 const existing = existingPricesMap.get(entryHash)
984
985 if (existing) {
986 entry.id = existing.id ?? entry.id
987 entry.price_rules = existing.price_rules ?? entry.price_rules
988 }
989
990 pricesToUpsert.set(entryHash, entry)
991 })
992
993 return Array.from(pricesToUpsert.values())
994 }
995
996 async addPrices(
997 data: AddPricesDTO,
998 sharedContext?: Context
999 ): Promise<PricingTypes.PriceSetDTO>
1000
1001 async addPrices(
1002 data: AddPricesDTO[],
1003 sharedContext?: Context
1004 ): Promise<PricingTypes.PriceSetDTO[]>
1005
1006 @InjectManager()
1007 @EmitEvents()
1008 async addPrices(
1009 data: AddPricesDTO | AddPricesDTO[],
1010 @MedusaContext() sharedContext: Context = {}
1011 ): Promise<PricingTypes.PriceSetDTO[] | PricingTypes.PriceSetDTO> {
1012 const input = Array.isArray(data) ? data : [data]
1013
1014 await this.addPrices_(input, sharedContext)
1015
1016 const dbPrices = await this.listPriceSets(
1017 { id: input.map((d) => d.priceSetId) },
1018 { relations: ["prices"] },
1019 sharedContext
1020 )
1021
1022 const orderedPriceSets = input.map((inputItem) => {
1023 return dbPrices.find((p) => p.id === inputItem.priceSetId)!
1024 })
1025
1026 const serializedOrderedPriceSets = await this.baseRepository_.serialize<
1027 PricingTypes.PriceSetDTO[]
1028 >(Array.isArray(data) ? orderedPriceSets : orderedPriceSets[0])
1029
1030 try {
1031 return serializedOrderedPriceSets
1032 } finally {
1033 this.pricingRepository_.clearAvailableAttributes?.()
1034 }
1035 }
1036
1037 @InjectManager()
1038 @EmitEvents()
1039 // @ts-ignore
1040 async createPriceLists(
1041 data: PricingTypes.CreatePriceListDTO[],
1042 @MedusaContext() sharedContext: Context = {}
1043 ): Promise<PricingTypes.PriceListDTO[]> {
1044 const priceLists = await this.createPriceLists_(data, sharedContext)
1045
1046 try {
1047 return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
1048 priceLists
1049 )
1050 } finally {
1051 this.pricingRepository_.clearAvailableAttributes?.()
1052 }
1053 }
1054
1055 @InjectManager()
1056 @EmitEvents()
1057 // @ts-ignore
1058 async updatePriceLists(
1059 data: PricingTypes.UpdatePriceListDTO[],
1060 @MedusaContext() sharedContext: Context = {}
1061 ): Promise<PricingTypes.PriceListDTO[]> {
1062 const priceLists = await this.updatePriceLists_(data, sharedContext)
1063
1064 try {
1065 return await this.baseRepository_.serialize<PricingTypes.PriceListDTO[]>(
1066 priceLists
1067 )
1068 } finally {
1069 this.pricingRepository_.clearAvailableAttributes?.()
1070 }
1071 }
1072
1073 @InjectManager()
1074 @EmitEvents()
1075 async updatePriceListPrices(
1076 data: PricingTypes.UpdatePriceListPricesDTO[],
1077 @MedusaContext() sharedContext: Context = {}
1078 ): Promise<PricingTypes.PriceDTO[]> {
1079 const prices = await this.updatePriceListPrices_(data, sharedContext)
1080
1081 try {
1082 return await this.baseRepository_.serialize<PricingTypes.PriceDTO[]>(
1083 prices
1084 )
1085 } finally {
1086 this.pricingRepository_.clearAvailableAttributes?.()
1087 }
1088 }
1089
1090 @InjectManager()
1091 @EmitEvents()
1092 async removePrices(
1093 ids: string[],
1094 @MedusaContext() sharedContext: Context = {}
1095 ): Promise<void> {
1096 try {
1097 await this.removePrices_(ids, sharedContext)
1098 } finally {
1099 this.pricingRepository_.clearAvailableAttributes?.()
1100 }
1101 }
1102
1103 @InjectManager()
1104 @EmitEvents()
1105 async addPriceListPrices(
1106 data: PricingTypes.AddPriceListPricesDTO[],
1107 @MedusaContext() sharedContext: Context = {}
1108 ): Promise<PricingTypes.PriceDTO[]> {
1109 const prices = await this.addPriceListPrices_(data, sharedContext)
1110
1111 try {
1112 return await this.baseRepository_.serialize<PricingTypes.PriceDTO[]>(
1113 prices
1114 )
1115 } finally {
1116 this.pricingRepository_.clearAvailableAttributes?.()
1117 }
1118 }
1119
1120 @InjectManager()
1121 @EmitEvents()
1122 async setPriceListRules(
1123 data: PricingTypes.SetPriceListRulesDTO,
1124 @MedusaContext() sharedContext: Context = {}
1125 ): Promise<PricingTypes.PriceListDTO> {
1126 const [priceList] = await this.setPriceListRules_([data], sharedContext)
1127
1128 try {
1129 return await this.baseRepository_.serialize<PricingTypes.PriceListDTO>(
1130 priceList
1131 )
1132 } finally {
1133 this.pricingRepository_.clearAvailableAttributes?.()
1134 }
1135 }
1136
1137 @InjectManager()
1138 @EmitEvents()
1139 async removePriceListRules(
1140 data: PricingTypes.RemovePriceListRulesDTO,
1141 @MedusaContext() sharedContext: Context = {}
1142 ): Promise<PricingTypes.PriceListDTO> {
1143 const [priceList] = await this.removePriceListRules_([data], sharedContext)
1144
1145 return await this.baseRepository_.serialize<PricingTypes.PriceListDTO>(
1146 priceList
1147 )
1148 }
1149
1150 // @ts-expect-error
1151 async createPricePreferences(
1152 data: PricingTypes.CreatePricePreferenceDTO,
1153 sharedContext?: Context
1154 ): Promise<PricePreferenceDTO>
1155 async createPricePreferences(
1156 data: PricingTypes.CreatePricePreferenceDTO[],
1157 sharedContext?: Context
1158 ): Promise<PricePreferenceDTO[]>
1159
1160 @InjectManager()
1161 @EmitEvents()
1162 async createPricePreferences(
1163 data:
1164 | PricingTypes.CreatePricePreferenceDTO
1165 | PricingTypes.CreatePricePreferenceDTO[],
1166 @MedusaContext() sharedContext: Context = {}
1167 ): Promise<PricePreferenceDTO | PricePreferenceDTO[]> {
1168 const normalized = Array.isArray(data) ? data : [data]
1169 const preferences = await this.createPricePreferences_(
1170 normalized,
1171 sharedContext
1172 )
1173
1174 const serialized = await this.baseRepository_.serialize<
1175 PricePreferenceDTO[]
1176 >(preferences)
1177 return Array.isArray(data) ? serialized : serialized[0]
1178 }
1179
1180 async upsertPricePreferences(
1181 data: UpsertPricePreferenceDTO[],
1182 sharedContext?: Context
1183 ): Promise<PricePreferenceDTO[]>
1184 async upsertPricePreferences(
1185 data: UpsertPricePreferenceDTO,
1186 sharedContext?: Context
1187 ): Promise<PricePreferenceDTO>
1188
1189 @InjectManager()
1190 @EmitEvents()
1191 async upsertPricePreferences(
1192 data: UpsertPricePreferenceDTO | UpsertPricePreferenceDTO[],
1193 @MedusaContext() sharedContext: Context = {}
1194 ): Promise<PricePreferenceDTO | PricePreferenceDTO[]> {
1195 const result = await this.upsertPricePreferences_(data, sharedContext)
1196
1197 return await this.baseRepository_.serialize<
1198 PricePreferenceDTO[] | PricePreferenceDTO
1199 >(Array.isArray(data) ? result : result[0])
1200 }
1201
1202 @InjectTransactionManager()
1203 protected async upsertPricePreferences_(
1204 data: UpsertPricePreferenceDTO | UpsertPricePreferenceDTO[],
1205 @MedusaContext() sharedContext: Context = {}
1206 ): Promise<InferEntityType<typeof PricePreference>[]> {
1207 const input = Array.isArray(data) ? data : [data]
1208 const forUpdate = input.filter(
1209 (
1210 pricePreference
1211 ): pricePreference is ServiceTypes.UpdatePricePreferenceInput =>
1212 !!pricePreference.id
1213 )
1214 const forCreate = input.filter(
1215 (pricePreference): pricePreference is CreatePricePreferenceDTO =>
1216 !pricePreference.id
1217 )
1218
1219 const operations: Promise<InferEntityType<typeof PricePreference>[]>[] = []
1220
1221 if (forCreate.length) {
1222 operations.push(this.createPricePreferences_(forCreate, sharedContext))
1223 }
1224 if (forUpdate.length) {
1225 operations.push(this.updatePricePreferences_(forUpdate, sharedContext))
1226 }
1227
1228 const result = (await promiseAll(operations)).flat()
1229
1230 return result
1231 }
1232
1233 // @ts-expect-error
1234 async updatePricePreferences(
1235 id: string,
1236 data: PricingTypes.UpdatePricePreferenceDTO,
1237 sharedContext?: Context
1238 ): Promise<PricePreferenceDTO>
1239 // @ts-expect-error
1240 async updatePricePreferences(
1241 selector: PricingTypes.FilterablePricePreferenceProps,
1242 data: PricingTypes.UpdatePricePreferenceDTO,
1243 sharedContext?: Context
1244 ): Promise<PricePreferenceDTO[]>
1245
1246 @InjectManager()
1247 @EmitEvents()
1248 // @ts-expect-error
1249 async updatePricePreferences(
1250 idOrSelector: string | PricingTypes.FilterablePricePreferenceProps,
1251 data: PricingTypes.UpdatePricePreferenceDTO,
1252 @MedusaContext() sharedContext: Context = {}
1253 ): Promise<PricePreferenceDTO | PricePreferenceDTO[]> {
1254 let normalizedInput: ServiceTypes.UpdatePricePreferenceInput[] = []
1255 if (isString(idOrSelector)) {
1256 // Check if the ID exists, it will throw if not.
1257 await this.pricePreferenceService_.retrieve(
1258 idOrSelector,
1259 {},
1260 sharedContext
1261 )
1262 normalizedInput = [{ id: idOrSelector, ...data }]
1263 } else {
1264 const pricePreferences = await this.pricePreferenceService_.list(
1265 idOrSelector,
1266 {},
1267 sharedContext
1268 )
1269
1270 normalizedInput = pricePreferences.map((pricePreference) => ({
1271 id: pricePreference.id,
1272 ...data,
1273 }))
1274 }
1275
1276 const updateResult = await this.updatePricePreferences_(
1277 normalizedInput,
1278 sharedContext
1279 )
1280
1281 const pricePreferences = await this.baseRepository_.serialize<
1282 PricePreferenceDTO[] | PricePreferenceDTO
1283 >(updateResult)
1284
1285 return isString(idOrSelector) ? pricePreferences[0] : pricePreferences
1286 }
1287
1288 @InjectTransactionManager()
1289 protected async createPricePreferences_(
1290 data: PricingTypes.CreatePricePreferenceDTO[],
1291 @MedusaContext() sharedContext: Context = {}
1292 ) {
1293 const preferences = await this.pricePreferenceService_.create(
1294 data.map((d) => ({
1295 ...d,
1296 is_tax_inclusive: d.is_tax_inclusive ?? false,
1297 })),
1298 sharedContext
1299 )
1300
1301 return preferences
1302 }
1303
1304 @InjectTransactionManager()
1305 protected async updatePricePreferences_(
1306 data: PricingTypes.UpdatePricePreferenceDTO[],
1307 @MedusaContext() sharedContext: Context = {}
1308 ) {
1309 const preferences = await this.pricePreferenceService_.update(
1310 data,
1311 sharedContext
1312 )
1313
1314 return preferences
1315 }
1316
1317 @InjectTransactionManager()
1318 protected async createPriceSets_(
1319 data: PricingTypes.CreatePriceSetDTO[],
1320 @MedusaContext() sharedContext: Context = {}
1321 ) {
1322 const input = Array.isArray(data) ? data : [data]
1323
1324 const toCreate = input.map((inputData) => {
1325 const entry = {
1326 ...inputData,
1327 prices: this.normalizePrices(inputData.prices, []),
1328 }
1329 return entry
1330 })
1331
1332 // Bulk create price sets
1333 const priceSets = await this.priceSetService_.create(
1334 toCreate,
1335 sharedContext
1336 )
1337
1338 return priceSets
1339 }
1340
1341 @InjectTransactionManager()
1342 protected async addPrices_(
1343 input: AddPricesDTO[],
1344 @MedusaContext() sharedContext: Context = {}
1345 ) {
1346 const prices = input.flatMap((data) => {
1347 return data.prices.map((price) => {
1348 ;(price as PricingTypes.PriceDTO).price_set_id = data.priceSetId
1349 return price
1350 })
1351 })
1352
1353 const priceConstraints =
1354 buildPreNormalizationPriceConstraintsFromData(prices)
1355
1356 const [priceSets, priceSetPrices] = await promiseAll([
1357 this.listPriceSets(
1358 { id: input.map((d) => d.priceSetId) },
1359 {},
1360 sharedContext
1361 ),
1362 this.priceService_.list(
1363 priceConstraints,
1364 { relations: ["price_rules"] },
1365 sharedContext
1366 ),
1367 ])
1368
1369 const existingPrices = priceSetPrices as unknown as PricingTypes.PriceDTO[]
1370
1371 const pricesToUpsert = input
1372 .flatMap((addPrice) =>
1373 this.normalizePrices(addPrice.prices, existingPrices)
1374 )
1375 .filter(Boolean) as ServiceTypes.UpsertPriceDTO[]
1376
1377 const priceSetMap = new Map<string, PriceSetDTO>(
1378 priceSets.map((p) => [p.id, p])
1379 )
1380 pricesToUpsert.forEach((price) => {
1381 const priceSet = priceSetMap.get(price.price_set_id)
1382
1383 if (!priceSet) {
1384 throw new MedusaError(
1385 MedusaError.Types.INVALID_DATA,
1386 `Price set with id: ${price.price_set_id} not found`
1387 )
1388 }
1389 })
1390
1391 const { entities } = await this.priceService_.upsertWithReplace(
1392 pricesToUpsert,
1393 { relations: ["price_rules"] },
1394 sharedContext
1395 )
1396
1397 return entities
1398 }
1399
1400 @InjectTransactionManager()
1401 protected async createPriceLists_(
1402 data: PricingTypes.CreatePriceListDTO[],
1403 @MedusaContext() sharedContext: Context = {}
1404 ) {
1405 const normalized = this.normalizePriceListDate(data)
1406
1407 const priceListsToCreate: ServiceTypes.CreatePriceListDTO[] =
1408 normalized.map((priceListData) => {
1409 const entry = {
1410 ...priceListData,
1411 rules: undefined,
1412 } as ServiceTypes.CreatePriceListDTO
1413
1414 if (priceListData.prices) {
1415 entry.prices = this.normalizePrices(
1416 priceListData.prices,
1417 []
1418 ) as ServiceTypes.UpsertPriceDTO[]
1419 }
1420
1421 if (priceListData.rules) {
1422 const cleanRules = priceListData.rules
1423 ? removeNullish(priceListData.rules)
1424 : {}
1425 const rules = Object.entries(cleanRules)
1426 const numberOfRules = rules.length
1427
1428 const rulesDataMap = new Map()
1429 rules.map(([attribute, value]) => {
1430 const rule = {
1431 attribute,
1432 value,
1433 }
1434 rulesDataMap.set(JSON.stringify(rule), rule)
1435 })
1436
1437 entry.price_list_rules = Array.from(rulesDataMap.values())
1438 entry.rules_count = numberOfRules
1439 }
1440
1441 return entry
1442 })
1443
1444 const priceLists = await this.priceListService_.create(
1445 priceListsToCreate,
1446 sharedContext
1447 )
1448
1449 return priceLists
1450 }
1451
1452 @InjectTransactionManager()
1453 protected async updatePriceLists_(
1454 data: PricingTypes.UpdatePriceListDTO[],
1455 @MedusaContext() sharedContext: Context = {}
1456 ) {
1457 const existingPriceLists = await this.priceListService_.list(
1458 { id: data.map((d) => d.id) },
1459 {},
1460 sharedContext
1461 )
1462
1463 if (existingPriceLists.length !== data.length) {
1464 const diff = arrayDifference(
1465 data.map((d) => d.id),
1466 existingPriceLists.map((p) => p.id)
1467 )
1468 throw new MedusaError(
1469 MedusaError.Types.INVALID_DATA,
1470 `Price lists with ids: '${diff.join(", ")}' not found`
1471 )
1472 }
1473
1474 const existingByIdMap = new Map(existingPriceLists.map((p) => [p.id, p]))
1475
1476 const normalizedData = this.normalizePriceListDate(data).map(
1477 (priceList) => {
1478 const entry: Partial<ServiceTypes.CreatePriceListDTO> = {
1479 ...priceList,
1480 rules: undefined,
1481 price_list_rules: undefined,
1482 }
1483
1484 if (isPresent(priceList.metadata)) {
1485 const existing = existingByIdMap.get(priceList.id as string)
1486 entry.metadata = mergeMetadata(
1487 existing?.metadata ?? {},
1488 priceList.metadata as Record<string, unknown>
1489 )
1490 }
1491
1492 if (typeof priceList.rules === "object") {
1493 const cleanRules = priceList.rules
1494 ? removeNullish(priceList.rules)
1495 : {}
1496 const rules = Object.entries(cleanRules)
1497 const numberOfRules = rules.length
1498
1499 const rulesDataMap = new Map()
1500 rules.map(([attribute, value]) => {
1501 const rule = {
1502 attribute,
1503 value,
1504 }
1505 rulesDataMap.set(JSON.stringify(rule), rule)
1506 })
1507
1508 entry.price_list_rules = Array.from(rulesDataMap.values())
1509 entry.rules_count = numberOfRules
1510 }
1511
1512 return entry
1513 }
1514 )
1515
1516 const { entities } = await this.priceListService_.upsertWithReplace(
1517 normalizedData,
1518 {
1519 relations: ["price_list_rules"],
1520 }
1521 )
1522
1523 return entities
1524 }
1525
1526 @InjectTransactionManager()
1527 protected async updatePriceListPrices_(
1528 data: PricingTypes.UpdatePriceListPricesDTO[],
1529 sharedContext: Context = {}
1530 ): Promise<InferEntityType<typeof Price>[]> {
1531 const priceListIds = data.map((p) => p.price_list_id)
1532 const prices = data.flatMap((p) => p.prices)
1533
1534 const priceConstraints = buildPreNormalizationPriceConstraintsFromData(
1535 prices,
1536 priceListIds
1537 )
1538
1539 const [priceLists, priceListPrices] = await promiseAll([
1540 this.priceListService_.list({ id: priceListIds }, {}, sharedContext),
1541 this.priceService_.list(
1542 priceConstraints,
1543 { relations: ["price_rules"] },
1544 sharedContext
1545 ),
1546 ])
1547
1548 const existingPrices = priceListPrices as unknown as PricingTypes.PriceDTO[]
1549
1550 const pricesToUpsert = data
1551 .flatMap((addPrice) =>
1552 this.normalizePrices(
1553 addPrice.prices as ServiceTypes.UpsertPriceDTO[],
1554 existingPrices,
1555 addPrice.price_list_id
1556 )
1557 )
1558 .filter(Boolean) as ServiceTypes.UpsertPriceDTO[]
1559
1560 const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
1561
1562 for (const { price_list_id: priceListId } of data) {
1563 const priceList = priceListMap.get(priceListId)
1564
1565 if (!priceList) {
1566 throw new MedusaError(
1567 MedusaError.Types.INVALID_DATA,
1568 `Price list with id: ${priceListId} not found`
1569 )
1570 }
1571 }
1572
1573 const { entities } = await this.priceService_.upsertWithReplace(
1574 pricesToUpsert,
1575 { relations: ["price_rules"] },
1576 sharedContext
1577 )
1578
1579 return entities
1580 }
1581
1582 @InjectTransactionManager()
1583 protected async removePrices_(
1584 ids: string[],
1585 sharedContext: Context = {}
1586 ): Promise<void> {
1587 await this.priceService_.delete(ids, sharedContext)
1588 }
1589
1590 @InjectTransactionManager()
1591 protected async addPriceListPrices_(
1592 data: PricingTypes.AddPriceListPricesDTO[],
1593 sharedContext: Context = {}
1594 ): Promise<InferEntityType<typeof Price>[]> {
1595 const priceListIds = data.map((p) => p.price_list_id)
1596 const prices = data.flatMap((p) => p.prices)
1597
1598 const priceConstraints = buildPreNormalizationPriceConstraintsFromData(
1599 prices,
1600 priceListIds
1601 )
1602 const [priceLists, priceListPrices] = await promiseAll([
1603 this.priceListService_.list({ id: priceListIds }, {}, sharedContext),
1604 this.priceService_.list(
1605 priceConstraints,
1606 { relations: ["price_rules"] },
1607 sharedContext
1608 ),
1609 ])
1610
1611 const existingPrices = priceListPrices as unknown as PricingTypes.PriceDTO[]
1612
1613 const pricesToUpsert = data
1614 .flatMap((addPrice) =>
1615 this.normalizePrices(
1616 addPrice.prices,
1617 existingPrices,
1618 addPrice.price_list_id
1619 )
1620 )
1621 .filter(Boolean) as ServiceTypes.UpsertPriceDTO[]
1622
1623 const priceListMap = new Map(priceLists.map((p) => [p.id, p]))
1624 pricesToUpsert.forEach((price) => {
1625 const priceList = priceListMap.get(price.price_list_id!)
1626
1627 if (!priceList) {
1628 throw new MedusaError(
1629 MedusaError.Types.INVALID_DATA,
1630 `Price list with id: ${price.price_list_id} not found`
1631 )
1632 }
1633 })
1634
1635 const { entities } = await this.priceService_.upsertWithReplace(
1636 pricesToUpsert,
1637 { relations: ["price_rules"] },
1638 sharedContext
1639 )
1640
1641 return entities
1642 }
1643
1644 @InjectTransactionManager()
1645 protected async setPriceListRules_(
1646 data: PricingTypes.SetPriceListRulesDTO[],
1647 sharedContext: Context = {}
1648 ): Promise<InferEntityType<typeof PriceList>[]> {
1649 // TODO: re think this method
1650 const priceLists = await this.priceListService_.list(
1651 { id: data.map((d) => d.price_list_id) },
1652 {
1653 relations: ["price_list_rules"],
1654 },
1655 sharedContext
1656 )
1657
1658 const rulesMap = new Map()
1659 data.forEach((rule) => {
1660 if (!rulesMap.has(rule.price_list_id)) {
1661 rulesMap.set(rule.price_list_id, [])
1662 }
1663
1664 Object.entries(rule.rules).forEach(([key, value]) => {
1665 rulesMap.get(rule.price_list_id).push([key, value])
1666 })
1667 })
1668
1669 const priceListsUpsert = priceLists
1670 .map((priceList) => {
1671 const priceListRules =
1672 priceList.price_list_rules as unknown as Collection<
1673 InferEntityType<typeof PriceListRule>
1674 >
1675 const allRules = new Map(
1676 priceListRules.toArray().map((r) => [r.attribute, r.value])
1677 )
1678
1679 const rules = rulesMap.get(priceList.id)
1680 if (!rules?.length) {
1681 return
1682 }
1683
1684 rules.forEach(([key, value]) => {
1685 allRules.set(key, value)
1686 })
1687
1688 return {
1689 ...priceList,
1690 rules_count: allRules.size,
1691 price_list_rules: Array.from(allRules).map(([attribute, value]) => ({
1692 attribute,
1693 value,
1694 })),
1695 }
1696 })
1697 .filter(Boolean)
1698
1699 const { entities } = await this.priceListService_.upsertWithReplace(
1700 priceListsUpsert,
1701 { relations: ["price_list_rules"] },
1702 sharedContext
1703 )
1704
1705 return entities
1706 }
1707
1708 @InjectTransactionManager()
1709 protected async removePriceListRules_(
1710 data: PricingTypes.RemovePriceListRulesDTO[],
1711 sharedContext: Context = {}
1712 ): Promise<InferEntityType<typeof PriceList>[]> {
1713 // TODO: re think this method
1714 const priceLists = await this.priceListService_.list(
1715 { id: data.map((d) => d.price_list_id) },
1716 {
1717 relations: ["price_list_rules"],
1718 },
1719 sharedContext
1720 )
1721
1722 const rulesMap = new Map()
1723 data.forEach((rule) => {
1724 if (!rulesMap.has(rule.price_list_id)) {
1725 rulesMap.set(rule.price_list_id, [])
1726 }
1727
1728 rule.rules.forEach((key) => {
1729 rulesMap.get(rule.price_list_id).push([key, undefined])
1730 })
1731 })
1732
1733 const priceListsUpsert = priceLists
1734 .map((priceList) => {
1735 const priceListRules =
1736 priceList.price_list_rules as unknown as Collection<
1737 InferEntityType<typeof PriceListRule>
1738 >
1739
1740 const allRules = new Map(
1741 priceListRules.toArray().map((r) => [r.attribute, r.value])
1742 )
1743
1744 const rules = rulesMap.get(priceList.id)
1745 if (!rules?.length) {
1746 return
1747 }
1748
1749 rules.forEach(([key, value]) => {
1750 allRules.set(key, value)
1751 })
1752
1753 return {
1754 ...priceList,
1755 rules_count: allRules.size,
1756 price_list_rules: Array.from(allRules)
1757 .map(([attribute, value]) => ({
1758 attribute,
1759 value,
1760 }))
1761 .filter((r) => !!r.value),
1762 }
1763 })
1764 .filter(Boolean)
1765
1766 const { entities } = await this.priceListService_.upsertWithReplace(
1767 priceListsUpsert,
1768 { relations: ["price_list_rules"] },
1769 sharedContext
1770 )
1771
1772 return entities
1773 }
1774
1775 protected normalizePriceListDate(
1776 data: (
1777 | ServiceTypes.UpdatePriceListDTO
1778 | ServiceTypes.CreatePriceListDTO
1779 | ServiceTypes.CreatePriceListDTO
1780 )[]
1781 ) {
1782 return data.map((priceListData: any) => {
1783 validatePriceListDates(priceListData)
1784
1785 if (!!priceListData.starts_at) {
1786 priceListData.starts_at = GetIsoStringFromDate(priceListData.starts_at)
1787 }
1788
1789 if (!!priceListData.ends_at) {
1790 priceListData.ends_at = GetIsoStringFromDate(priceListData.ends_at)
1791 }
1792
1793 return priceListData
1794 })
1795 }
1796
1797 protected normalizePriceSetConfig(
1798 config: FindConfig<PricingTypes.PriceSetDTO> | undefined
1799 ) {
1800 return {
1801 options: {
1802 populateWhere: { prices: { price_list_id: null } },
1803 },
1804 ...config,
1805 }
1806 }
1807 }
1808
1809 const isTaxInclusive = (
1810 priceRules: InferEntityType<typeof PriceRule>[],
1811 preferences: InferEntityType<typeof PricePreference>[],
1812 currencyCode: string,
1813 regionId?: string
1814 ) => {
1815 const regionRule = priceRules?.find(
1816 (rule) => rule.attribute === "region_id" && rule.value === regionId
1817 )
1818
1819 const regionPreference = preferences.find(
1820 (p) => p.attribute === "region_id" && p.value === regionId
1821 )
1822
1823 const currencyPreference = preferences.find(
1824 (p) => p.attribute === "currency_code" && p.value === currencyCode
1825 )
1826
1827 if (regionRule && regionPreference) {
1828 return regionPreference.is_tax_inclusive
1829 }
1830
1831 if (currencyPreference) {
1832 return currencyPreference.is_tax_inclusive
1833 }
1834
1835 return false
1836 }
1837
1838 const hashPrice = (
1839 price: PricingTypes.PriceDTO | PricingTypes.CreatePricesDTO
1840 ): string => {
1841 // Build hash using deterministic property order to avoid expensive sort operation
1842 // Using a direct string concatenation approach for better performance
1843 const parts: string[] = []
1844
1845 if ("currency_code" in price) {
1846 parts.push(`cc:${normalizeCurrencyCode(price.currency_code ?? "")}`)
1847 }
1848 if ("price_set_id" in price) {
1849 parts.push(`ps:${price.price_set_id ?? ""}`)
1850 }
1851 if ("price_list_id" in price) {
1852 parts.push(`pl:${price.price_list_id ?? ""}`)
1853 }
1854 if ("min_quantity" in price) {
1855 parts.push(`min:${price.min_quantity ?? ""}`)
1856 }
1857 if ("max_quantity" in price) {
1858 parts.push(`max:${price.max_quantity ?? ""}`)
1859 }
1860
1861 // Add price rules in a deterministic way if present
1862 if ("price_rules" in price && price.price_rules) {
1863 const sortedRules = price.price_rules.map(
1864 (pr) => `${pr.attribute}=${pr.value}`
1865 )
1866 if (sortedRules.length) {
1867 parts.push(`rules:${sortedRules.join(",")}`)
1868 }
1869 }
1870
1871 return parts.sort().join("|")
1872 }
1873
1874 /**
1875 * Build targeted database constraints to fetch only prices that could match the incoming data.
1876 * Uses the same properties as hashPrice to ensure consistency.
1877 */
1878 const buildPreNormalizationPriceConstraintsFromData = (
1879 prices: (
1880 | PricingTypes.CreatePricesDTO
1881 | ServiceTypes.UpsertPriceDTO
1882 | PricingTypes.UpdatePriceListPriceDTO
1883 )[],
1884 priceListIds?: string | string[]
1885 ): any => {
1886 // Separate prices with explicit IDs from those without
1887 const pricesWithIds = prices.filter((p) => p.id).map((p) => p.id)
1888
1889 // Build unique constraints based on hash properties
1890 const constraintSet = new Set<string>()
1891 const constraints: any[] = []
1892
1893 for (const price of prices) {
1894 // Skip if price has explicit ID (will be queried separately)
1895 if (price.id) continue
1896
1897 const constraint: any = {}
1898
1899 if (!!price.currency_code) {
1900 constraint.currency_code = normalizeCurrencyCode(price.currency_code)
1901 }
1902 if ("price_set_id" in price && price.price_set_id !== undefined) {
1903 constraint.price_set_id = price.price_set_id
1904 }
1905 if ("price_list_id" in price && price.price_list_id !== undefined) {
1906 constraint.price_list_id = price.price_list_id
1907 }
1908 if (price.min_quantity !== undefined) {
1909 constraint.min_quantity = price.min_quantity
1910 }
1911 if (price.max_quantity !== undefined) {
1912 constraint.max_quantity = price.max_quantity
1913 }
1914
1915 // Use hash to deduplicate constraints
1916 const constraintHash = JSON.stringify(constraint)
1917 if (!constraintSet.has(constraintHash)) {
1918 constraintSet.add(constraintHash)
1919 constraints.push(constraint)
1920 }
1921 }
1922
1923 // Build final query
1924 const query: any = {}
1925
1926 if (priceListIds) {
1927 if (Array.isArray(priceListIds) && priceListIds.length > 0) {
1928 query.price_list_id = {
1929 $in: priceListIds,
1930 }
1931 } else {
1932 query.price_list_id = priceListIds
1933 }
1934 }
1935
1936 // Combine ID-based and property-based constraints
1937 if (pricesWithIds.length && constraints.length) {
1938 query.$or = [{ id: pricesWithIds }, ...constraints]
1939 } else if (pricesWithIds.length) {
1940 query.id = pricesWithIds
1941 } else if (constraints.length) {
1942 if (constraints.length === 1) {
1943 Object.assign(query, constraints[0])
1944 } else {
1945 query.$or = constraints
1946 }
1947 }
1948
1949 return query
1950 }