Raw
1 import {
2 CampaignBudgetTypeValues,
3 CampaignBudgetUsageDTO,
4 Context,
5 DAL,
6 FilterablePromotionProps,
7 FindConfig,
8 InferEntityType,
9 InternalModuleDeclaration,
10 ModulesSdkTypes,
11 PromotionDTO,
12 PromotionTypes,
13 } from "@medusajs/framework/types"
14 import {
15 ApplicationMethodAllocation,
16 ApplicationMethodTargetType,
17 arrayDifference,
18 CampaignBudgetType,
19 ComputedActions,
20 deduplicate,
21 EmitEvents,
22 InjectManager,
23 InjectTransactionManager,
24 isDefined,
25 isPresent,
26 isString,
27 MathBN,
28 MedusaContext,
29 MedusaError,
30 MedusaService,
31 PromotionStatus,
32 PromotionType,
33 toMikroORMEntity,
34 transformPropertiesToBigNumber,
35 } from "@medusajs/framework/utils"
36 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
37 import {
38 ApplicationMethod,
39 Campaign,
40 CampaignBudget,
41 CampaignBudgetUsage,
42 Promotion,
43 PromotionRule,
44 PromotionRuleValue,
45 } from "@models"
46 import {
47 ApplicationMethodRuleTypes,
48 CreateApplicationMethodDTO,
49 CreateCampaignBudgetDTO,
50 CreateCampaignDTO,
51 CreatePromotionDTO,
52 CreatePromotionRuleDTO,
53 UpdateApplicationMethodDTO,
54 UpdateCampaignBudgetDTO,
55 UpdateCampaignDTO,
56 UpdatePromotionDTO,
57 } from "@types"
58 import {
59 allowedAllocationForQuantity,
60 areRulesValidForContext,
61 ComputeActionUtils,
62 validateApplicationMethodAttributes,
63 validatePromotionRuleAttributes,
64 } from "@utils"
65 import { CreatePromotionRuleValueDTO } from "../types/promotion-rule-value"
66 import { buildPromotionRuleQueryFilterFromContext } from "../utils/compute-actions/build-promotion-rule-query-filter-from-context"
67
68 type InjectedDependencies = {
69 baseRepository: DAL.RepositoryService
70 promotionService: ModulesSdkTypes.IMedusaInternalService<any>
71 applicationMethodService: ModulesSdkTypes.IMedusaInternalService<any>
72 promotionRuleService: ModulesSdkTypes.IMedusaInternalService<any>
73 promotionRuleValueService: ModulesSdkTypes.IMedusaInternalService<any>
74 campaignService: ModulesSdkTypes.IMedusaInternalService<any>
75 campaignBudgetService: ModulesSdkTypes.IMedusaInternalService<any>
76 campaignBudgetUsageService: ModulesSdkTypes.IMedusaInternalService<any>
77 }
78
79 export default class PromotionModuleService
80 extends MedusaService<{
81 Promotion: { dto: PromotionTypes.PromotionDTO }
82 ApplicationMethod: { dto: PromotionTypes.ApplicationMethodDTO }
83 Campaign: { dto: PromotionTypes.CampaignDTO }
84 CampaignBudget: { dto: PromotionTypes.CampaignBudgetDTO }
85 CampaignBudgetUsage: { dto: PromotionTypes.CampaignBudgetUsageDTO }
86 PromotionRule: { dto: PromotionTypes.PromotionRuleDTO }
87 PromotionRuleValue: { dto: PromotionTypes.PromotionRuleValueDTO }
88 }>({
89 Promotion,
90 ApplicationMethod,
91 Campaign,
92 CampaignBudget,
93 CampaignBudgetUsage,
94 PromotionRule,
95 PromotionRuleValue,
96 })
97 implements PromotionTypes.IPromotionModuleService
98 {
99 protected baseRepository_: DAL.RepositoryService
100 protected promotionService_: ModulesSdkTypes.IMedusaInternalService<
101 InferEntityType<typeof Promotion>
102 >
103 protected applicationMethodService_: ModulesSdkTypes.IMedusaInternalService<
104 InferEntityType<typeof ApplicationMethod>
105 >
106 protected promotionRuleService_: ModulesSdkTypes.IMedusaInternalService<
107 InferEntityType<typeof PromotionRule>
108 >
109 protected promotionRuleValueService_: ModulesSdkTypes.IMedusaInternalService<
110 InferEntityType<typeof PromotionRuleValue>
111 >
112 protected campaignService_: ModulesSdkTypes.IMedusaInternalService<
113 InferEntityType<typeof Campaign>
114 >
115 protected campaignBudgetService_: ModulesSdkTypes.IMedusaInternalService<
116 InferEntityType<typeof CampaignBudget>
117 >
118
119 protected campaignBudgetUsageService_: ModulesSdkTypes.IMedusaInternalService<
120 InferEntityType<typeof CampaignBudgetUsage>
121 >
122
123 constructor(
124 {
125 baseRepository,
126 promotionService,
127 applicationMethodService,
128 promotionRuleService,
129 promotionRuleValueService,
130 campaignService,
131 campaignBudgetService,
132 campaignBudgetUsageService,
133 }: InjectedDependencies,
134 protected readonly moduleDeclaration: InternalModuleDeclaration
135 ) {
136 // @ts-ignore
137 super(...arguments)
138
139 this.baseRepository_ = baseRepository
140 this.promotionService_ = promotionService
141 this.applicationMethodService_ = applicationMethodService
142 this.promotionRuleService_ = promotionRuleService
143 this.promotionRuleValueService_ = promotionRuleValueService
144 this.campaignService_ = campaignService
145 this.campaignBudgetService_ = campaignBudgetService
146 this.campaignBudgetUsageService_ = campaignBudgetUsageService
147 }
148
149 @InjectManager()
150 async listActivePromotions(
151 filters?: FilterablePromotionProps,
152 config?: FindConfig<PromotionDTO>,
153 sharedContext?: Context
154 ): Promise<PromotionDTO[]> {
155 const activePromotions = await this.listActivePromotions_(
156 filters,
157 config,
158 sharedContext
159 )
160
161 return this.baseRepository_.serialize<PromotionDTO[]>(activePromotions)
162 }
163
164 @InjectManager()
165 protected async listActivePromotions_(
166 filters?: FilterablePromotionProps,
167 config?: FindConfig<PromotionDTO>,
168 @MedusaContext() sharedContext?: Context
169 ): Promise<InferEntityType<typeof Promotion>[]> {
170 // Ensure we share the same now date across all filters
171 const now = new Date()
172 const activeFilters = {
173 status: PromotionStatus.ACTIVE,
174 $or: [
175 {
176 campaign_id: null,
177 ...filters,
178 },
179 {
180 ...filters,
181 campaign: {
182 ...filters?.campaign,
183 $and: [
184 {
185 $or: [{ starts_at: null }, { starts_at: { $lte: now } }],
186 },
187 {
188 $or: [{ ends_at: null }, { ends_at: { $gt: now } }],
189 },
190 ],
191 },
192 },
193 ],
194 }
195
196 return await this.promotionService_.list(
197 activeFilters,
198 config,
199 sharedContext
200 )
201 }
202
203 @InjectTransactionManager()
204 protected async registerCampaignBudgetUsageByAttribute_(
205 budgetId: string,
206 attributeValue: string,
207 @MedusaContext() sharedContext: Context = {}
208 ): Promise<void> {
209 // Re-read the per-attribute usage row under the budget row lock held by the
210 // caller (`registerUsage`). The lock lives on `promotion_campaign_budget`,
211 // not on this usage row, so `refresh: true` is required to read the
212 // committed value rather than a stale identity-map copy; otherwise a
213 // concurrent registration's guard could pass on a stale count.
214 const [campaignBudgetUsagePerAttributeValue] =
215 await this.campaignBudgetUsageService_.list(
216 {
217 budget_id: budgetId,
218 attribute_value: attributeValue,
219 },
220 { relations: ["budget"], options: { refresh: true } },
221 sharedContext
222 )
223
224 if (!campaignBudgetUsagePerAttributeValue) {
225 await this.campaignBudgetUsageService_.create(
226 {
227 budget_id: budgetId,
228 attribute_value: attributeValue,
229 used: MathBN.convert(1),
230 },
231 sharedContext
232 )
233 } else {
234 const limit = campaignBudgetUsagePerAttributeValue.budget.limit
235 const newUsedValue = MathBN.add(
236 campaignBudgetUsagePerAttributeValue.used ?? 0,
237 1
238 )
239
240 if (limit && MathBN.gt(newUsedValue, limit)) {
241 throw new MedusaError(
242 MedusaError.Types.NOT_ALLOWED,
243 "Promotion usage exceeds the budget limit."
244 )
245 }
246
247 await this.campaignBudgetUsageService_.update(
248 {
249 id: campaignBudgetUsagePerAttributeValue.id,
250 used: newUsedValue,
251 },
252 sharedContext
253 )
254 }
255 }
256
257 @InjectTransactionManager()
258 protected async revertCampaignBudgetUsageByAttribute_(
259 budgetId: string,
260 attributeValue: string,
261 @MedusaContext() sharedContext: Context = {}
262 ): Promise<void> {
263 const [campaignBudgetUsagePerAttributeValue] =
264 await this.campaignBudgetUsageService_.list(
265 {
266 budget_id: budgetId,
267 attribute_value: attributeValue,
268 },
269 {},
270 sharedContext
271 )
272
273 if (!campaignBudgetUsagePerAttributeValue) {
274 return
275 }
276
277 if (MathBN.lte(campaignBudgetUsagePerAttributeValue.used ?? 0, 1)) {
278 await this.campaignBudgetUsageService_.delete(
279 campaignBudgetUsagePerAttributeValue.id,
280 sharedContext
281 )
282 } else {
283 await this.campaignBudgetUsageService_.update(
284 {
285 id: campaignBudgetUsagePerAttributeValue.id,
286 used: MathBN.sub(campaignBudgetUsagePerAttributeValue.used ?? 0, 1),
287 },
288 sharedContext
289 )
290 }
291 }
292
293 @InjectTransactionManager()
294 @EmitEvents()
295 /**
296 * Register the usage of promotions in the campaign budget and
297 * increment the used value if the budget is not exceeded,
298 * throws an error if the budget is exceeded.
299 *
300 * @param computedActions - The computed actions to register usage for.
301 * @param registrationContext - The context of the campaign budget usage.
302 * @returns void
303 * @throws {MedusaError} - If the promotion usage exceeds the budget limit.
304 */
305 async registerUsage(
306 computedActions: PromotionTypes.UsageComputedActions[],
307 registrationContext: PromotionTypes.CampaignBudgetUsageContext,
308 @MedusaContext() sharedContext: Context = {}
309 ): Promise<void> {
310 const promotionCodes = computedActions
311 .map((computedAction) => computedAction.code)
312 .filter(Boolean)
313
314 const campaignBudgetMap = new Map<string, UpdateCampaignBudgetDTO>()
315 const promotionCodeUsageMap = new Map<string, boolean>()
316 const promotionUsageMap = new Map<string, { id: string; used: number }>()
317
318 let existingPromotions = await this.listActivePromotions_(
319 { code: promotionCodes },
320 { relations: ["campaign", "campaign.budget", "campaign.budget.usages"] },
321 sharedContext
322 )
323
324 // Serialize concurrent usage registration against the same promotions and
325 // budgets. Two concurrent registrations that read the same used value would
326 // both pass the limit guard below and both write, over-spending a spend
327 // budget or exceeding a usage limit. Lock the promotion and budget rows for
328 // the remainder of this transaction, then re-read the usage totals under the
329 // lock so the guards see committed values. Rows are locked in a stable id
330 // order to avoid deadlocks between concurrent multi-promotion registrations,
331 // and the re-read uses `refresh: true` (rather than detaching the identity
332 // map) so a surrounding transaction's pending state is preserved.
333 // Only promotions with a numeric usage limit have their `promotion` row
334 // updated below (see the `typeof promotion.limit === "number"` guard), so
335 // lock only those rows; budgets are locked separately just below.
336 const lockPromotionIds = existingPromotions
337 .filter((promotion) => typeof promotion.limit === "number")
338 .map((promotion) => promotion.id)
339 const lockBudgetIds = Array.from(
340 new Set(
341 existingPromotions
342 .map((promotion) => promotion.campaign?.budget?.id)
343 .filter(Boolean) as string[]
344 )
345 )
346 // The transaction context is required: a FOR UPDATE issued on a pooled
347 // (autocommit) connection would release the lock immediately and silently
348 // stop serializing, so fail explicitly instead of falling back.
349 const manager = sharedContext.transactionManager as SqlEntityManager
350 const knex = manager?.getTransactionContext()
351 if (!knex) {
352 throw new MedusaError(
353 MedusaError.Types.UNEXPECTED_STATE,
354 "registerUsage must run inside a transaction to serialize concurrent usage registration."
355 )
356 }
357 // Bound the wait for these row locks so a contended registration fails fast
358 // instead of hanging: `SET LOCAL` scopes the timeout to this transaction.
359 await knex.raw("SET LOCAL lock_timeout = '3s'")
360 if (lockPromotionIds.length) {
361 await knex("promotion")
362 .whereIn("id", lockPromotionIds)
363 .orderBy("id")
364 .forUpdate()
365 .select("id")
366 }
367 if (lockBudgetIds.length) {
368 await knex("promotion_campaign_budget")
369 .whereIn("id", lockBudgetIds)
370 .orderBy("id")
371 .forUpdate()
372 .select("id")
373 }
374
375 existingPromotions = await this.listActivePromotions_(
376 { code: promotionCodes },
377 {
378 relations: ["campaign", "campaign.budget", "campaign.budget.usages"],
379 options: { refresh: true },
380 },
381 sharedContext
382 )
383
384 for (const promotion of existingPromotions) {
385 if (promotion.campaign?.budget) {
386 campaignBudgetMap.set(
387 promotion.campaign?.budget.id,
388 promotion.campaign?.budget
389 )
390 }
391 }
392
393 const existingPromotionsMap = new Map<
394 string,
395 InferEntityType<typeof Promotion>
396 >(existingPromotions.map((promotion) => [promotion.code!, promotion]))
397
398 for (let computedAction of computedActions) {
399 const promotion = existingPromotionsMap.get(computedAction.code)
400
401 if (!promotion) {
402 continue
403 }
404
405 if (typeof promotion.limit === "number") {
406 const newUsedValue = (promotion.used ?? 0) + 1
407
408 if (newUsedValue > promotion.limit) {
409 throw new MedusaError(
410 MedusaError.Types.NOT_ALLOWED,
411 "Promotion usage exceeds the limit."
412 )
413 }
414
415 promotionUsageMap.set(promotion.id, {
416 id: promotion.id,
417 used: newUsedValue,
418 })
419 }
420
421 const campaignBudget = promotion.campaign?.budget
422
423 if (!campaignBudget) {
424 continue
425 }
426
427 if (campaignBudget.type === CampaignBudgetType.SPEND) {
428 const campaignBudgetData = campaignBudgetMap.get(campaignBudget.id)
429
430 if (!campaignBudgetData) {
431 continue
432 }
433
434 // Calculate the new budget value
435 const newUsedValue = MathBN.add(
436 campaignBudgetData.used ?? 0,
437 computedAction.amount
438 )
439
440 if (
441 campaignBudget.limit &&
442 MathBN.gt(newUsedValue, campaignBudget.limit)
443 ) {
444 throw new MedusaError(
445 MedusaError.Types.NOT_ALLOWED,
446 "Promotion usage exceeds the budget limit."
447 )
448 }
449
450 campaignBudgetData.used = newUsedValue
451
452 campaignBudgetMap.set(campaignBudget.id, campaignBudgetData)
453 }
454
455 if (campaignBudget.type === CampaignBudgetType.USAGE) {
456 const promotionAlreadyUsed =
457 promotionCodeUsageMap.get(promotion.code!) || false
458
459 if (promotionAlreadyUsed) {
460 continue
461 }
462
463 const newUsedValue = MathBN.add(campaignBudget.used ?? 0, 1)
464
465 if (
466 campaignBudget.limit &&
467 MathBN.gt(newUsedValue, campaignBudget.limit)
468 ) {
469 throw new MedusaError(
470 MedusaError.Types.NOT_ALLOWED,
471 "Promotion usage exceeds the budget limit."
472 )
473 }
474
475 campaignBudgetMap.set(campaignBudget.id, {
476 id: campaignBudget.id,
477 used: newUsedValue,
478 })
479
480 promotionCodeUsageMap.set(promotion.code!, true)
481 }
482
483 if (campaignBudget.type === CampaignBudgetType.USE_BY_ATTRIBUTE) {
484 const promotionAlreadyUsed =
485 promotionCodeUsageMap.get(promotion.code!) || false
486
487 if (promotionAlreadyUsed) {
488 continue
489 }
490
491 const attribute = campaignBudget.attribute!
492 const attributeValue = registrationContext[attribute]
493
494 if (!attributeValue) {
495 continue
496 }
497
498 await this.registerCampaignBudgetUsageByAttribute_(
499 campaignBudget.id,
500 attributeValue,
501 sharedContext
502 )
503
504 const newUsedValue = MathBN.add(campaignBudget.used ?? 0, 1)
505
506 // update the global budget usage to keep track but it is not used anywhere atm
507 campaignBudgetMap.set(campaignBudget.id, {
508 id: campaignBudget.id,
509 used: newUsedValue,
510 })
511
512 promotionCodeUsageMap.set(promotion.code!, true)
513 }
514 }
515
516 if (promotionUsageMap.size > 0) {
517 await this.promotionService_.update(
518 Array.from(promotionUsageMap.values()),
519 sharedContext
520 )
521 }
522
523 if (campaignBudgetMap.size > 0) {
524 const campaignBudgetsData: UpdateCampaignBudgetDTO[] = []
525 for (const [_, campaignBudgetData] of campaignBudgetMap) {
526 // usages by attribute are updated separatley
527 if (campaignBudgetData.usages) {
528 const { usages, ...campaignBudgetDataWithoutUsages } =
529 campaignBudgetData
530 campaignBudgetsData.push(campaignBudgetDataWithoutUsages)
531 continue
532 }
533 campaignBudgetsData.push(campaignBudgetData)
534 }
535
536 await this.campaignBudgetService_.update(
537 campaignBudgetsData,
538 sharedContext
539 )
540 }
541 }
542
543 @InjectTransactionManager()
544 @EmitEvents()
545 async revertUsage(
546 computedActions: PromotionTypes.UsageComputedActions[],
547 registrationContext: PromotionTypes.CampaignBudgetUsageContext,
548 @MedusaContext() sharedContext: Context = {}
549 ): Promise<void> {
550 const promotionCodeUsageMap = new Map<string, boolean>()
551 const campaignBudgetMap = new Map<string, UpdateCampaignBudgetDTO>()
552 const promotionUsageMap = new Map<string, { id: string; used: number }>()
553
554 const existingPromotions = await this.listActivePromotions_(
555 {
556 code: computedActions
557 .map((computedAction) => computedAction.code)
558 .filter(Boolean),
559 },
560 { relations: ["campaign", "campaign.budget"] },
561 sharedContext
562 )
563
564 for (const promotion of existingPromotions) {
565 if (promotion.campaign?.budget) {
566 campaignBudgetMap.set(
567 promotion.campaign?.budget.id,
568 promotion.campaign?.budget
569 )
570 }
571 }
572
573 const existingPromotionsMap = new Map<
574 string,
575 InferEntityType<typeof Promotion>
576 >(existingPromotions.map((promotion) => [promotion.code!, promotion]))
577
578 for (let computedAction of computedActions) {
579 const promotion = existingPromotionsMap.get(computedAction.code)
580
581 if (!promotion) {
582 continue
583 }
584
585 if (typeof promotion.limit === "number") {
586 const newUsedValue = Math.max(0, (promotion.used ?? 0) - 1)
587
588 promotionUsageMap.set(promotion.id, {
589 id: promotion.id,
590 used: newUsedValue,
591 })
592 }
593
594 const campaignBudget = promotion.campaign?.budget
595
596 if (!campaignBudget) {
597 continue
598 }
599
600 if (campaignBudget.type === CampaignBudgetType.SPEND) {
601 const campaignBudgetData = campaignBudgetMap.get(campaignBudget.id)
602
603 if (!campaignBudgetData) {
604 continue
605 }
606
607 // Calculate new used value and ensure it doesn't go below 0
608 const newUsedValue = MathBN.sub(
609 campaignBudgetData.used ?? 0,
610 computedAction.amount
611 )
612
613 campaignBudgetData.used = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue
614 campaignBudgetMap.set(campaignBudget.id, campaignBudgetData)
615 }
616
617 if (campaignBudget.type === CampaignBudgetType.USAGE) {
618 const promotionAlreadyUsed =
619 promotionCodeUsageMap.get(promotion.code!) || false
620
621 if (promotionAlreadyUsed) {
622 continue
623 }
624
625 // Calculate new used value and ensure it doesn't go below 0
626 const newUsedValue = MathBN.sub(campaignBudget.used ?? 0, 1)
627 const usedValue = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue
628
629 campaignBudgetMap.set(campaignBudget.id, {
630 id: campaignBudget.id,
631 used: usedValue,
632 })
633
634 promotionCodeUsageMap.set(promotion.code!, true)
635 }
636
637 if (campaignBudget.type === CampaignBudgetType.USE_BY_ATTRIBUTE) {
638 const promotionAlreadyUsed =
639 promotionCodeUsageMap.get(promotion.code!) || false
640
641 if (promotionAlreadyUsed) {
642 continue
643 }
644
645 const attribute = campaignBudget.attribute!
646 const attributeValue = registrationContext[attribute]
647
648 if (!attributeValue) {
649 continue
650 }
651
652 await this.revertCampaignBudgetUsageByAttribute_(
653 campaignBudget.id,
654 attributeValue,
655 sharedContext
656 )
657 const newUsedValue = MathBN.sub(campaignBudget.used ?? 0, 1)
658 const usedValue = MathBN.lt(newUsedValue, 0) ? 0 : newUsedValue
659
660 // update the global budget usage to keep track but it is not used anywhere atm
661 campaignBudgetMap.set(campaignBudget.id, {
662 id: campaignBudget.id,
663 used: usedValue,
664 })
665
666 promotionCodeUsageMap.set(promotion.code!, true)
667 }
668 }
669
670 if (promotionUsageMap.size > 0) {
671 await this.promotionService_.update(
672 Array.from(promotionUsageMap.values()),
673 sharedContext
674 )
675 }
676
677 if (campaignBudgetMap.size > 0) {
678 const campaignBudgetsData: UpdateCampaignBudgetDTO[] = []
679 for (const [_, campaignBudgetData] of campaignBudgetMap) {
680 if (campaignBudgetData.usages) {
681 const { usages, ...campaignBudgetDataWithoutUsages } =
682 campaignBudgetData
683 campaignBudgetsData.push(campaignBudgetDataWithoutUsages)
684 continue
685 }
686 campaignBudgetsData.push(campaignBudgetData)
687 }
688
689 await this.campaignBudgetService_.update(
690 campaignBudgetsData,
691 sharedContext
692 )
693 }
694 }
695
696 @InjectManager()
697 async computeActions(
698 promotionCodes: string[],
699 applicationContext: PromotionTypes.ComputeActionContext,
700 options: PromotionTypes.ComputeActionOptions = {},
701 @MedusaContext() sharedContext: Context = {}
702 ): Promise<PromotionTypes.ComputeActions[]> {
703 const {
704 prevent_auto_promotions: preventAutoPromotions,
705 skip_usage_limit_checks: skipUsageLimitChecks,
706 } = options
707 const computedActions: PromotionTypes.ComputeActions[] = []
708 const { items = [], shipping_methods: shippingMethods = [] } =
709 applicationContext
710
711 const codeAdjustmentMap = new Map<
712 string,
713 {
714 items: PromotionTypes.ComputeActionAdjustmentLine[]
715 shipping: PromotionTypes.ComputeActionAdjustmentLine[]
716 }
717 >()
718
719 // Pre-process items and shipping methods to build adjustment map efficiently
720 for (const item of items) {
721 if (!item.adjustments?.length) continue
722
723 for (const adjustment of item.adjustments) {
724 if (!isString(adjustment.code)) continue
725
726 if (!codeAdjustmentMap.has(adjustment.code)) {
727 codeAdjustmentMap.set(adjustment.code, { items: [], shipping: [] })
728 }
729
730 codeAdjustmentMap.get(adjustment.code)!.items.push(adjustment)
731 }
732 }
733
734 for (const shippingMethod of shippingMethods) {
735 if (!shippingMethod.adjustments?.length) continue
736
737 for (const adjustment of shippingMethod.adjustments) {
738 if (!isString(adjustment.code)) continue
739
740 if (!codeAdjustmentMap.has(adjustment.code)) {
741 codeAdjustmentMap.set(adjustment.code, { items: [], shipping: [] })
742 }
743
744 codeAdjustmentMap.get(adjustment.code)!.shipping.push(adjustment)
745 }
746 }
747
748 const appliedCodes = Array.from(codeAdjustmentMap.keys())
749
750 const methodIdPromoValueMap = new Map<string, number>()
751
752 const promotionCodesToApply = [...promotionCodes, ...appliedCodes]
753
754 const uniquePromotionCodes = Array.from(new Set(promotionCodesToApply))
755
756 let queryFilter: DAL.FilterQuery<any> = { code: uniquePromotionCodes }
757
758 if (!preventAutoPromotions) {
759 const rulePrefilteringFilters =
760 await buildPromotionRuleQueryFilterFromContext(
761 applicationContext,
762 sharedContext
763 )
764
765 let prefilteredAutomaticPromotionIds: string[] = []
766
767 if (rulePrefilteringFilters) {
768 const promotions = await this.promotionService_.list(
769 {
770 $and: [{ is_automatic: true }, rulePrefilteringFilters],
771 },
772 { select: ["id"] },
773 sharedContext
774 )
775
776 prefilteredAutomaticPromotionIds = promotions.map(
777 (promotion) => promotion.id!
778 )
779 }
780
781 const automaticPromotionFilter = rulePrefilteringFilters
782 ? {
783 id: { $in: prefilteredAutomaticPromotionIds },
784 }
785 : { is_automatic: true }
786
787 queryFilter = automaticPromotionFilter
788 ? {
789 $or: [{ code: uniquePromotionCodes }, automaticPromotionFilter],
790 }
791 : queryFilter
792 }
793
794 const promotions = await this.listActivePromotions_(
795 queryFilter,
796 {
797 order: { application_method: { value: "DESC" } },
798 relations: [
799 "application_method",
800 "application_method.target_rules",
801 "application_method.target_rules.values",
802 "application_method.buy_rules",
803 "application_method.buy_rules.values",
804 "rules",
805 "rules.values",
806 "campaign",
807 "campaign.budget",
808 ],
809 },
810 sharedContext
811 )
812
813 const existingPromotionsMap = new Map<
814 string,
815 InferEntityType<typeof Promotion>
816 >(promotions.map((promotion) => [promotion.code!, promotion]))
817
818 const automaticPromotionCodes: string[] = []
819
820 for (const promotion of promotions) {
821 if (promotion.is_automatic) {
822 automaticPromotionCodes.push(promotion.code!)
823 }
824 }
825
826 for (const [code, adjustments] of codeAdjustmentMap.entries()) {
827 for (const adjustment of adjustments.items) {
828 computedActions.push({
829 action: ComputedActions.REMOVE_ITEM_ADJUSTMENT,
830 adjustment_id: adjustment.id,
831 code,
832 item_id: adjustment.item_id as string,
833 })
834 }
835
836 for (const adjustment of adjustments.shipping) {
837 computedActions.push({
838 action: ComputedActions.REMOVE_SHIPPING_METHOD_ADJUSTMENT,
839 adjustment_id: adjustment.id,
840 code,
841 shipping_method_id: adjustment.shipping_method_id as string,
842 })
843 }
844 }
845
846 const promotionCodeSet = new Set<string>(promotionCodes) // TODO: uniquePromotionCodes
847 const automaticPromotionCodeSet = new Set<string>(automaticPromotionCodes)
848
849 const sortedPromotionsToApply = promotions
850 .filter(
851 (p) =>
852 promotionCodeSet.has(p.code!) ||
853 automaticPromotionCodeSet.has(p.code!)
854 )
855 .sort(ComputeActionUtils.sortByBuyGetType)
856
857 const eligibleBuyItemMap = new Map<
858 string,
859 ComputeActionUtils.EligibleItem[]
860 >()
861 const eligibleTargetItemMap = new Map<
862 string,
863 ComputeActionUtils.EligibleItem[]
864 >()
865
866 for (const promotionToApply of sortedPromotionsToApply) {
867 const promotion = existingPromotionsMap.get(promotionToApply.code!)!
868 if (!promotion.application_method) {
869 continue
870 }
871
872 const {
873 application_method: applicationMethod,
874 rules: promotionRules = [],
875 } = promotion
876
877 if (
878 !skipUsageLimitChecks &&
879 promotion.campaign?.budget?.type === CampaignBudgetType.USE_BY_ATTRIBUTE
880 ) {
881 const attribute = promotion.campaign?.budget?.attribute!
882 const budgetUsageContext =
883 ComputeActionUtils.getBudgetUsageContextFromComputeActionContext(
884 applicationContext
885 )
886 const attributeValue = budgetUsageContext[attribute]
887
888 if (!attributeValue) {
889 throw new MedusaError(
890 MedusaError.Types.INVALID_DATA,
891 `Attribute value for "${attribute}" is required by promotion campaing budget`
892 )
893 }
894
895 const [campaignBudgetUsagePerAttribute] =
896 (await this.campaignBudgetUsageService_.list(
897 {
898 budget_id: promotion.campaign?.budget?.id,
899 attribute_value: attributeValue,
900 },
901 {},
902 sharedContext
903 )) as unknown as CampaignBudgetUsageDTO[]
904
905 if (campaignBudgetUsagePerAttribute) {
906 const action = ComputeActionUtils.computeActionForBudgetExceeded(
907 promotion,
908 1,
909 campaignBudgetUsagePerAttribute
910 )
911
912 if (action) {
913 computedActions.push(action)
914 continue
915 }
916 }
917 }
918
919 // Check promotion usage limit
920 if (!skipUsageLimitChecks && typeof promotion.limit === "number") {
921 if ((promotion.used ?? 0) >= promotion.limit) {
922 computedActions.push({
923 action: ComputedActions.PROMOTION_LIMIT_EXCEEDED,
924 code: promotion.code!,
925 })
926 continue
927 }
928 }
929
930 const isCurrencyCodeValid =
931 !isPresent(applicationMethod.currency_code) ||
932 applicationContext.currency_code === applicationMethod.currency_code
933
934 const isPromotionApplicable = areRulesValidForContext(
935 promotionRules,
936 applicationContext,
937 ApplicationMethodTargetType.ORDER
938 )
939
940 if (!isPromotionApplicable || !isCurrencyCodeValid) {
941 continue
942 }
943
944 if (promotion.type === PromotionType.BUYGET) {
945 const computedActionsForItems =
946 ComputeActionUtils.getComputedActionsForBuyGet(
947 promotion,
948 applicationContext[ApplicationMethodTargetType.ITEMS]!,
949 methodIdPromoValueMap,
950 eligibleBuyItemMap,
951 eligibleTargetItemMap
952 )
953
954 computedActions.push(...computedActionsForItems)
955 } else if (promotion.type === PromotionType.STANDARD) {
956 const isTargetOrder =
957 applicationMethod.target_type === ApplicationMethodTargetType.ORDER
958 const isTargetItems =
959 applicationMethod.target_type === ApplicationMethodTargetType.ITEMS
960 const isTargetShipping =
961 applicationMethod.target_type ===
962 ApplicationMethodTargetType.SHIPPING_METHODS
963 const allocationOverride = isTargetOrder
964 ? ApplicationMethodAllocation.ACROSS
965 : undefined
966
967 if (isTargetOrder || isTargetItems) {
968 const computedActionsForItems =
969 ComputeActionUtils.getComputedActionsForItems(
970 promotion,
971 applicationContext[ApplicationMethodTargetType.ITEMS],
972 methodIdPromoValueMap,
973 allocationOverride
974 )
975
976 computedActions.push(...computedActionsForItems)
977 }
978
979 if (isTargetShipping) {
980 const computedActionsForShippingMethods =
981 ComputeActionUtils.getComputedActionsForShippingMethods(
982 promotion,
983 applicationContext[ApplicationMethodTargetType.SHIPPING_METHODS],
984 methodIdPromoValueMap
985 )
986
987 computedActions.push(...computedActionsForShippingMethods)
988 }
989 }
990 }
991
992 transformPropertiesToBigNumber(computedActions, { include: ["amount"] })
993
994 return computedActions
995 }
996
997 // @ts-expect-error
998 async createPromotions(
999 data: PromotionTypes.CreatePromotionDTO,
1000 sharedContext?: Context
1001 ): Promise<PromotionTypes.PromotionDTO>
1002
1003 // @ts-expect-error
1004 async createPromotions(
1005 data: PromotionTypes.CreatePromotionDTO[],
1006 sharedContext?: Context
1007 ): Promise<PromotionTypes.PromotionDTO[]>
1008
1009 @InjectManager()
1010 @EmitEvents()
1011 // @ts-expect-error
1012 async createPromotions(
1013 data:
1014 | PromotionTypes.CreatePromotionDTO
1015 | PromotionTypes.CreatePromotionDTO[],
1016 @MedusaContext() sharedContext: Context = {}
1017 ): Promise<PromotionTypes.PromotionDTO | PromotionTypes.PromotionDTO[]> {
1018 const input = Array.isArray(data) ? data : [data]
1019 const createdPromotions = await this.createPromotions_(input, sharedContext)
1020
1021 const promotions = await this.listPromotions(
1022 { id: createdPromotions.map((p) => p!.id) },
1023 {
1024 relations: [
1025 "application_method",
1026 "application_method.target_rules",
1027 "application_method.target_rules.values",
1028 "application_method.buy_rules",
1029 "application_method.buy_rules.values",
1030 "rules",
1031 "rules.values",
1032 "campaign",
1033 "campaign.budget",
1034 ],
1035 },
1036 sharedContext
1037 )
1038
1039 return await this.baseRepository_.serialize<
1040 PromotionTypes.PromotionDTO | PromotionTypes.PromotionDTO[]
1041 >(Array.isArray(data) ? promotions : promotions[0])
1042 }
1043
1044 @InjectTransactionManager()
1045 protected async createPromotions_(
1046 data: PromotionTypes.CreatePromotionDTO[],
1047 @MedusaContext() sharedContext: Context = {}
1048 ) {
1049 const promotionsData: CreatePromotionDTO[] = []
1050 const applicationMethodsData: CreateApplicationMethodDTO[] = []
1051 const campaignsData: CreateCampaignDTO[] = []
1052
1053 const campaignIds = data
1054 .filter((d) => d.campaign_id)
1055 .map((d) => d.campaign_id)
1056 .filter((id): id is string => isString(id))
1057
1058 const existingCampaigns =
1059 campaignIds.length > 0
1060 ? await this.campaignService_.list(
1061 { id: campaignIds },
1062 { relations: ["budget"] },
1063 sharedContext
1064 )
1065 : []
1066
1067 const promotionCodeApplicationMethodDataMap = new Map<
1068 string,
1069 PromotionTypes.CreateApplicationMethodDTO
1070 >()
1071 const promotionCodeRulesDataMap = new Map<
1072 string,
1073 PromotionTypes.CreatePromotionRuleDTO[]
1074 >()
1075 const methodTargetRulesMap = new Map<
1076 string,
1077 PromotionTypes.CreatePromotionRuleDTO[]
1078 >()
1079 const methodBuyRulesMap = new Map<
1080 string,
1081 PromotionTypes.CreatePromotionRuleDTO[]
1082 >()
1083 const promotionCodeCampaignMap = new Map<
1084 string,
1085 PromotionTypes.CreateCampaignDTO
1086 >()
1087
1088 for (const {
1089 application_method: applicationMethodData,
1090 rules: rulesData,
1091 campaign: campaignData,
1092 campaign_id: campaignId,
1093 ...promotionData
1094 } of data) {
1095 promotionCodeApplicationMethodDataMap.set(
1096 promotionData.code,
1097 applicationMethodData
1098 )
1099
1100 if (rulesData) {
1101 promotionCodeRulesDataMap.set(promotionData.code, rulesData)
1102 }
1103
1104 if (campaignData && campaignId) {
1105 throw new MedusaError(
1106 MedusaError.Types.INVALID_DATA,
1107 `Provide either the 'campaign' or 'campaign_id' parameter; both cannot be used simultaneously.`
1108 )
1109 }
1110
1111 if (!campaignData && !campaignId) {
1112 promotionsData.push({ ...promotionData })
1113 continue
1114 }
1115
1116 const existingCampaign = existingCampaigns.find(
1117 (c) => c.id === campaignId
1118 )
1119
1120 if (campaignId && !existingCampaign) {
1121 throw new MedusaError(
1122 MedusaError.Types.NOT_FOUND,
1123 `Could not find campaign with id - ${campaignId}`
1124 )
1125 }
1126
1127 const campaignCurrency =
1128 campaignData?.budget?.currency_code ||
1129 existingCampaigns.find((c) => c.id === campaignId)?.budget
1130 ?.currency_code
1131
1132 if (
1133 campaignData?.budget?.type === CampaignBudgetType.SPEND &&
1134 campaignCurrency !== applicationMethodData?.currency_code
1135 ) {
1136 throw new MedusaError(
1137 MedusaError.Types.INVALID_DATA,
1138 `Currency between promotion and campaigns should match`
1139 )
1140 }
1141
1142 if (campaignData) {
1143 promotionCodeCampaignMap.set(promotionData.code, campaignData)
1144 }
1145
1146 promotionsData.push({
1147 ...promotionData,
1148 campaign_id: campaignId,
1149 })
1150 }
1151
1152 const createdPromotions = await this.promotionService_.create(
1153 promotionsData,
1154 sharedContext
1155 )
1156
1157 for (const promotion of createdPromotions) {
1158 const applMethodData = promotionCodeApplicationMethodDataMap.get(
1159 promotion.code
1160 )
1161
1162 const campaignData = promotionCodeCampaignMap.get(promotion.code)
1163
1164 if (campaignData) {
1165 campaignsData.push({
1166 ...campaignData,
1167 promotions: [promotion],
1168 })
1169 }
1170
1171 if (applMethodData) {
1172 const {
1173 target_rules: targetRulesData = [],
1174 buy_rules: buyRulesData = [],
1175 ...applicationMethodWithoutRules
1176 } = applMethodData
1177 const applicationMethodData = {
1178 ...applicationMethodWithoutRules,
1179 promotion,
1180 }
1181
1182 if (
1183 applicationMethodData.target_type ===
1184 ApplicationMethodTargetType.ORDER &&
1185 targetRulesData.length
1186 ) {
1187 throw new MedusaError(
1188 MedusaError.Types.INVALID_DATA,
1189 `Target rules for application method with target type (${ApplicationMethodTargetType.ORDER}) is not allowed`
1190 )
1191 }
1192
1193 if (promotion.type === PromotionType.BUYGET && !buyRulesData.length) {
1194 throw new MedusaError(
1195 MedusaError.Types.INVALID_DATA,
1196 `Buy rules are required for ${PromotionType.BUYGET} promotion type`
1197 )
1198 }
1199
1200 if (
1201 promotion.type === PromotionType.BUYGET &&
1202 !targetRulesData.length
1203 ) {
1204 throw new MedusaError(
1205 MedusaError.Types.INVALID_DATA,
1206 `Target rules are required for ${PromotionType.BUYGET} promotion type`
1207 )
1208 }
1209
1210 validateApplicationMethodAttributes(applicationMethodData, promotion)
1211
1212 applicationMethodsData.push(applicationMethodData)
1213
1214 if (targetRulesData.length) {
1215 methodTargetRulesMap.set(promotion.id, targetRulesData)
1216 }
1217
1218 if (buyRulesData.length) {
1219 methodBuyRulesMap.set(promotion.id, buyRulesData)
1220 }
1221 }
1222
1223 if (promotionCodeRulesDataMap.has(promotion.code)) {
1224 await this.createPromotionRulesAndValues_(
1225 promotionCodeRulesDataMap.get(promotion.code) || [],
1226 "promotions",
1227 promotion,
1228 sharedContext
1229 )
1230 }
1231 }
1232
1233 const createdApplicationMethods =
1234 applicationMethodsData.length > 0
1235 ? await this.applicationMethodService_.create(
1236 applicationMethodsData,
1237 sharedContext
1238 )
1239 : []
1240
1241 const createdCampaigns =
1242 campaignsData.length > 0
1243 ? await this.createCampaigns(campaignsData, sharedContext)
1244 : []
1245
1246 for (const campaignData of campaignsData) {
1247 const promotions = campaignData.promotions
1248 const campaign = createdCampaigns.find(
1249 (c) => c.campaign_identifier === campaignData.campaign_identifier
1250 )
1251
1252 if (campaign && promotions && promotions.length) {
1253 await this.addPromotionsToCampaign(
1254 { id: campaign.id, promotion_ids: promotions.map((p) => p.id) },
1255 sharedContext
1256 )
1257 }
1258 }
1259
1260 for (const applicationMethod of createdApplicationMethods) {
1261 const targetRules = methodTargetRulesMap.get(
1262 applicationMethod.promotion.id
1263 )
1264 if (targetRules && targetRules.length > 0) {
1265 await this.createPromotionRulesAndValues_(
1266 targetRules,
1267 "method_target_rules",
1268 applicationMethod,
1269 sharedContext
1270 )
1271 }
1272
1273 const buyRules = methodBuyRulesMap.get(applicationMethod.promotion.id)
1274 if (buyRules && buyRules.length > 0) {
1275 await this.createPromotionRulesAndValues_(
1276 buyRules,
1277 "method_buy_rules",
1278 applicationMethod,
1279 sharedContext
1280 )
1281 }
1282 }
1283
1284 return createdPromotions
1285 }
1286
1287 // @ts-expect-error
1288 async updatePromotions(
1289 data: PromotionTypes.UpdatePromotionDTO,
1290 sharedContext?: Context
1291 ): Promise<PromotionTypes.PromotionDTO>
1292
1293 // @ts-expect-error
1294 async updatePromotions(
1295 data: PromotionTypes.UpdatePromotionDTO[],
1296 sharedContext?: Context
1297 ): Promise<PromotionTypes.PromotionDTO[]>
1298
1299 @InjectManager()
1300 @EmitEvents()
1301 // @ts-expect-error
1302 async updatePromotions(
1303 data:
1304 | PromotionTypes.UpdatePromotionDTO
1305 | PromotionTypes.UpdatePromotionDTO[],
1306 @MedusaContext() sharedContext: Context = {}
1307 ): Promise<PromotionTypes.PromotionDTO | PromotionTypes.PromotionDTO[]> {
1308 const input = Array.isArray(data) ? data : [data]
1309 const updatedPromotions = await this.updatePromotions_(input, sharedContext)
1310
1311 const promotions = await this.listPromotions(
1312 { id: updatedPromotions.map((p) => p!.id) },
1313 {
1314 relations: [
1315 "application_method",
1316 "application_method.target_rules",
1317 "application_method.target_rules.values",
1318 "rules",
1319 "rules.values",
1320 "campaign",
1321 "campaign.budget",
1322 ],
1323 },
1324 sharedContext
1325 )
1326
1327 return Array.isArray(data) ? promotions : promotions[0]
1328 }
1329
1330 @InjectTransactionManager()
1331 protected async updatePromotions_(
1332 data: PromotionTypes.UpdatePromotionDTO[],
1333 @MedusaContext() sharedContext: Context = {}
1334 ) {
1335 const promotionIds = data.map((d) => d.id)
1336 const existingPromotions = await this.promotionService_.list(
1337 { id: promotionIds },
1338 { relations: ["application_method"] }
1339 )
1340 const existingCampaigns = await this.campaignService_.list(
1341 { id: data.map((d) => d.campaign_id).filter((d) => isPresent(d)) },
1342 { relations: ["budget"] }
1343 )
1344
1345 const existingPromotionsMap = new Map<
1346 string,
1347 InferEntityType<typeof Promotion>
1348 >(existingPromotions.map((promotion) => [promotion.id, promotion]))
1349
1350 const promotionsData: UpdatePromotionDTO[] = []
1351 const applicationMethodsData: UpdateApplicationMethodDTO[] = []
1352
1353 for (const {
1354 application_method: applicationMethodData,
1355 campaign_id: campaignId,
1356 ...promotionData
1357 } of data) {
1358 const existingCampaign = existingCampaigns.find(
1359 (c) => c.id === campaignId
1360 )
1361 const existingPromotion = existingPromotionsMap.get(promotionData.id)!
1362 const existingApplicationMethod = existingPromotion?.application_method
1363 const promotionCurrencyCode =
1364 existingApplicationMethod?.currency_code ||
1365 applicationMethodData?.currency_code
1366
1367 // Validate promotion limit cannot be less than current usage
1368 if (isDefined(promotionData.limit) && promotionData.limit !== null) {
1369 const currentUsed = existingPromotion.used ?? 0
1370 if (promotionData.limit < currentUsed) {
1371 throw new MedusaError(
1372 MedusaError.Types.INVALID_DATA,
1373 `Promotion limit (${promotionData.limit}) cannot be less than current usage (${currentUsed})`
1374 )
1375 }
1376 }
1377
1378 if (campaignId && !existingCampaign) {
1379 throw new MedusaError(
1380 MedusaError.Types.INVALID_DATA,
1381 `Could not find campaign with id ${campaignId}`
1382 )
1383 }
1384
1385 if (
1386 campaignId &&
1387 existingCampaign?.budget?.type === CampaignBudgetType.SPEND &&
1388 existingCampaign.budget.currency_code !== promotionCurrencyCode
1389 ) {
1390 throw new MedusaError(
1391 MedusaError.Types.INVALID_DATA,
1392 `Currency code doesn't match for campaign (${campaignId}) and promotion (${existingPromotion.id})`
1393 )
1394 }
1395
1396 if (isDefined(campaignId)) {
1397 promotionsData.push({ ...promotionData, campaign_id: campaignId })
1398 } else {
1399 promotionsData.push(promotionData)
1400 }
1401
1402 if (!applicationMethodData || !existingApplicationMethod) {
1403 continue
1404 }
1405
1406 if (
1407 applicationMethodData.allocation &&
1408 !allowedAllocationForQuantity.includes(applicationMethodData.allocation)
1409 ) {
1410 applicationMethodData.max_quantity = null
1411 existingApplicationMethod.max_quantity = null
1412 }
1413
1414 validateApplicationMethodAttributes(
1415 applicationMethodData,
1416 existingPromotion
1417 )
1418
1419 applicationMethodsData.push({
1420 ...applicationMethodData,
1421 id: existingApplicationMethod.id,
1422 })
1423 }
1424
1425 const updatedPromotions = this.promotionService_.update(
1426 promotionsData,
1427 sharedContext
1428 )
1429
1430 if (applicationMethodsData.length) {
1431 await this.applicationMethodService_.update(
1432 applicationMethodsData,
1433 sharedContext
1434 )
1435 }
1436
1437 return updatedPromotions
1438 }
1439
1440 @InjectManager()
1441 @EmitEvents()
1442 // @ts-ignore
1443 async updatePromotionRules(
1444 data: PromotionTypes.UpdatePromotionRuleDTO[],
1445 @MedusaContext() sharedContext: Context = {}
1446 ): Promise<PromotionTypes.PromotionRuleDTO[]> {
1447 const updatedPromotionRules = await this.updatePromotionRules_(
1448 data,
1449 sharedContext
1450 )
1451
1452 return await this.listPromotionRules(
1453 { id: updatedPromotionRules.map((r) => r.id) },
1454 { relations: ["values"] },
1455 sharedContext
1456 )
1457 }
1458
1459 @InjectTransactionManager()
1460 protected async updatePromotionRules_(
1461 data: PromotionTypes.UpdatePromotionRuleDTO[],
1462 @MedusaContext() sharedContext: Context = {}
1463 ) {
1464 const promotionRuleIds = data.map((d) => d.id)
1465
1466 const promotionRules = await this.promotionRuleService_.list(
1467 { id: promotionRuleIds },
1468 { relations: ["values"] },
1469 sharedContext
1470 )
1471
1472 const existingPromotionRuleIds: string[] = []
1473 const promotionRulesMap: Map<string, PromotionTypes.PromotionRuleDTO> =
1474 new Map()
1475
1476 for (const promotionRule of promotionRules) {
1477 existingPromotionRuleIds.push(promotionRule.id)
1478 promotionRulesMap.set(promotionRule.id, promotionRule)
1479 }
1480
1481 const invalidRuleId = arrayDifference(
1482 deduplicate(promotionRuleIds),
1483 existingPromotionRuleIds
1484 )
1485
1486 if (invalidRuleId.length) {
1487 throw new MedusaError(
1488 MedusaError.Types.INVALID_DATA,
1489 `Promotion rules with id - ${invalidRuleId.join(", ")} not found`
1490 )
1491 }
1492
1493 const rulesToUpdate: PromotionTypes.UpdatePromotionRuleDTO[] = []
1494 const ruleValueIdsToDelete: string[] = []
1495 const ruleValuesToCreate: CreatePromotionRuleValueDTO[] = []
1496
1497 for (const promotionRuleData of data) {
1498 const { values, ...rest } = promotionRuleData
1499 const normalizedValues = Array.isArray(values) ? values : [values]
1500 rulesToUpdate.push(rest)
1501
1502 if (isDefined(values)) {
1503 const promotionRule = promotionRulesMap.get(promotionRuleData.id)!
1504
1505 ruleValueIdsToDelete.push(...promotionRule.values.map((v) => v.id))
1506 ruleValuesToCreate.push(
1507 ...normalizedValues.map((value) => ({
1508 value,
1509 promotion_rule: promotionRule,
1510 }))
1511 )
1512 }
1513 }
1514
1515 const [updatedRules] = await Promise.all([
1516 this.promotionRuleService_.update(rulesToUpdate, sharedContext),
1517 this.promotionRuleValueService_.delete(
1518 ruleValueIdsToDelete,
1519 sharedContext
1520 ),
1521 this.promotionRuleValueService_.create(ruleValuesToCreate, sharedContext),
1522 ])
1523
1524 return updatedRules
1525 }
1526
1527 @InjectManager()
1528 @EmitEvents()
1529 async addPromotionRules(
1530 promotionId: string,
1531 rulesData: PromotionTypes.CreatePromotionRuleDTO[],
1532 @MedusaContext() sharedContext: Context = {}
1533 ): Promise<PromotionTypes.PromotionRuleDTO[]> {
1534 const promotion = await this.promotionService_.retrieve(promotionId)
1535
1536 const createdPromotionRules = await this.createPromotionRulesAndValues_(
1537 rulesData,
1538 "promotions",
1539 promotion,
1540 sharedContext
1541 )
1542
1543 return this.listPromotionRules(
1544 { id: createdPromotionRules.map((r) => r.id) },
1545 { relations: ["values"] },
1546 sharedContext
1547 )
1548 }
1549
1550 @InjectManager()
1551 @EmitEvents()
1552 async addPromotionTargetRules(
1553 promotionId: string,
1554 rulesData: PromotionTypes.CreatePromotionRuleDTO[],
1555 @MedusaContext() sharedContext: Context = {}
1556 ): Promise<PromotionTypes.PromotionRuleDTO[]> {
1557 const promotion = await this.promotionService_.retrieve(promotionId, {
1558 relations: ["application_method"],
1559 })
1560
1561 const applicationMethod = promotion.application_method
1562
1563 if (!applicationMethod) {
1564 throw new MedusaError(
1565 MedusaError.Types.INVALID_DATA,
1566 `application_method for promotion not found`
1567 )
1568 }
1569
1570 const createdPromotionRules = await this.createPromotionRulesAndValues_(
1571 rulesData,
1572 "method_target_rules",
1573 applicationMethod,
1574 sharedContext
1575 )
1576
1577 return await this.listPromotionRules(
1578 { id: createdPromotionRules.map((pr) => pr.id) },
1579 { relations: ["values"] },
1580 sharedContext
1581 )
1582 }
1583
1584 @InjectManager()
1585 @EmitEvents()
1586 async addPromotionBuyRules(
1587 promotionId: string,
1588 rulesData: PromotionTypes.CreatePromotionRuleDTO[],
1589 @MedusaContext() sharedContext: Context = {}
1590 ): Promise<PromotionTypes.PromotionRuleDTO[]> {
1591 const promotion = await this.promotionService_.retrieve(
1592 promotionId,
1593 { relations: ["application_method"] },
1594 sharedContext
1595 )
1596
1597 const applicationMethod = promotion.application_method
1598
1599 if (!applicationMethod) {
1600 throw new MedusaError(
1601 MedusaError.Types.INVALID_DATA,
1602 `application_method for promotion not found`
1603 )
1604 }
1605
1606 const createdPromotionRules = await this.createPromotionRulesAndValues_(
1607 rulesData,
1608 "method_buy_rules",
1609 applicationMethod,
1610 sharedContext
1611 )
1612
1613 return await this.listPromotionRules(
1614 { id: createdPromotionRules.map((pr) => pr.id) },
1615 { relations: ["values"] },
1616 sharedContext
1617 )
1618 }
1619
1620 @InjectTransactionManager()
1621 protected async createPromotionRulesAndValues_(
1622 rulesData: PromotionTypes.CreatePromotionRuleDTO[],
1623 relationName: "promotions" | "method_target_rules" | "method_buy_rules",
1624 relation:
1625 | InferEntityType<typeof Promotion>
1626 | InferEntityType<typeof ApplicationMethod>,
1627 @MedusaContext() sharedContext: Context = {}
1628 ): Promise<InferEntityType<typeof PromotionRule>[]> {
1629 const MikroORMApplicationMethod = toMikroORMEntity(ApplicationMethod)
1630 const createdPromotionRules: InferEntityType<typeof PromotionRule>[] = []
1631 const promotion =
1632 relation instanceof MikroORMApplicationMethod
1633 ? relation.promotion
1634 : relation
1635
1636 if (!rulesData.length) {
1637 return []
1638 }
1639
1640 if (
1641 relationName === "method_buy_rules" &&
1642 promotion.type === PromotionType.STANDARD
1643 ) {
1644 throw new MedusaError(
1645 MedusaError.Types.INVALID_DATA,
1646 `Can't add buy rules to a ${PromotionType.STANDARD} promotion`
1647 )
1648 }
1649
1650 validatePromotionRuleAttributes(rulesData)
1651
1652 const promotionRuleValuesDataToCreate: CreatePromotionRuleValueDTO[] = []
1653
1654 for (const ruleData of rulesData) {
1655 const { values, ...rest } = ruleData
1656 const promotionRuleData: CreatePromotionRuleDTO = {
1657 ...rest,
1658 [relationName]: [relation],
1659 }
1660
1661 const [createdPromotionRule] = await this.promotionRuleService_.create(
1662 [promotionRuleData],
1663 sharedContext
1664 )
1665
1666 createdPromotionRules.push(createdPromotionRule)
1667
1668 const ruleValues = Array.isArray(values) ? values : [values]
1669 const promotionRuleValuesData = ruleValues.map((ruleValue) => ({
1670 value: ruleValue,
1671 promotion_rule: createdPromotionRule,
1672 }))
1673
1674 promotionRuleValuesDataToCreate.push(...promotionRuleValuesData)
1675 }
1676
1677 await this.promotionRuleValueService_.create(
1678 promotionRuleValuesDataToCreate,
1679 sharedContext
1680 )
1681
1682 return createdPromotionRules
1683 }
1684
1685 @InjectManager()
1686 @EmitEvents()
1687 async removePromotionRules(
1688 promotionId: string,
1689 ruleIds: string[],
1690 @MedusaContext() sharedContext: Context = {}
1691 ): Promise<void> {
1692 await this.removePromotionRules_(promotionId, ruleIds, sharedContext)
1693 }
1694
1695 @InjectTransactionManager()
1696 protected async removePromotionRules_(
1697 promotionId: string,
1698 ruleIds: string[],
1699 @MedusaContext() sharedContext: Context = {}
1700 ): Promise<void> {
1701 const promotion = await this.promotionService_.retrieve(
1702 promotionId,
1703 { relations: ["rules"] },
1704 sharedContext
1705 )
1706
1707 const existingRuleIds = promotion.rules.map((rule) => rule.id)
1708 const idsToRemove = ruleIds.filter((id) => existingRuleIds.includes(id))
1709
1710 await this.promotionRuleService_.delete(idsToRemove, sharedContext)
1711 }
1712
1713 @InjectManager()
1714 @EmitEvents()
1715 async removePromotionTargetRules(
1716 promotionId: string,
1717 ruleIds: string[],
1718 @MedusaContext() sharedContext: Context = {}
1719 ): Promise<void> {
1720 await this.removeApplicationMethodRules_(
1721 promotionId,
1722 ruleIds,
1723 ApplicationMethodRuleTypes.TARGET_RULES,
1724 sharedContext
1725 )
1726 }
1727
1728 @InjectManager()
1729 async removePromotionBuyRules(
1730 promotionId: string,
1731 ruleIds: string[],
1732 @MedusaContext() sharedContext: Context = {}
1733 ): Promise<void> {
1734 await this.removeApplicationMethodRules_(
1735 promotionId,
1736 ruleIds,
1737 ApplicationMethodRuleTypes.BUY_RULES,
1738 sharedContext
1739 )
1740 }
1741
1742 @InjectTransactionManager()
1743 protected async removeApplicationMethodRules_(
1744 promotionId: string,
1745 ruleIds: string[],
1746 relation:
1747 | ApplicationMethodRuleTypes.TARGET_RULES
1748 | ApplicationMethodRuleTypes.BUY_RULES,
1749 @MedusaContext() sharedContext: Context = {}
1750 ): Promise<void> {
1751 const promotion = await this.promotionService_.retrieve(
1752 promotionId,
1753 { relations: [`application_method.${relation}`] },
1754 sharedContext
1755 )
1756
1757 const applicationMethod = promotion.application_method
1758
1759 if (!applicationMethod) {
1760 throw new MedusaError(
1761 MedusaError.Types.INVALID_DATA,
1762 `application_method for promotion not found`
1763 )
1764 }
1765
1766 const targetRuleIdsToRemove = applicationMethod[relation]
1767 .filter((rule) => ruleIds.includes(rule.id))
1768 .map((rule) => rule.id)
1769
1770 await this.promotionRuleService_.delete(
1771 targetRuleIdsToRemove,
1772 sharedContext
1773 )
1774 }
1775
1776 // @ts-expect-error
1777 async createCampaigns(
1778 data: PromotionTypes.CreateCampaignDTO,
1779 sharedContext?: Context
1780 ): Promise<PromotionTypes.CampaignDTO>
1781
1782 // @ts-expect-error
1783 async createCampaigns(
1784 data: PromotionTypes.CreateCampaignDTO[],
1785 sharedContext?: Context
1786 ): Promise<PromotionTypes.CampaignDTO[]>
1787
1788 @InjectManager()
1789 @EmitEvents()
1790 // @ts-expect-error
1791 async createCampaigns(
1792 data: PromotionTypes.CreateCampaignDTO | PromotionTypes.CreateCampaignDTO[],
1793 @MedusaContext() sharedContext: Context = {}
1794 ): Promise<PromotionTypes.CampaignDTO | PromotionTypes.CampaignDTO[]> {
1795 const input = Array.isArray(data) ? data : [data]
1796 const createdCampaigns = await this.createCampaigns_(input, sharedContext)
1797
1798 const campaigns = await this.listCampaigns(
1799 { id: createdCampaigns.map((p) => p!.id) },
1800 {
1801 relations: ["budget", "promotions"],
1802 },
1803 sharedContext
1804 )
1805
1806 return Array.isArray(data) ? campaigns : campaigns[0]
1807 }
1808
1809 @InjectTransactionManager()
1810 protected async createCampaigns_(
1811 data: PromotionTypes.CreateCampaignDTO[],
1812 @MedusaContext() sharedContext: Context = {}
1813 ) {
1814 const campaignsData: CreateCampaignDTO[] = []
1815 const campaignBudgetsData: CreateCampaignBudgetDTO[] = []
1816 const campaignIdentifierBudgetMap = new Map<
1817 string,
1818 CreateCampaignBudgetDTO
1819 >()
1820
1821 for (const createCampaignData of data) {
1822 const { budget: campaignBudgetData, ...campaignData } = createCampaignData
1823
1824 if (campaignBudgetData) {
1825 campaignIdentifierBudgetMap.set(
1826 campaignData.campaign_identifier,
1827 campaignBudgetData
1828 )
1829 }
1830
1831 campaignsData.push({
1832 ...campaignData,
1833 })
1834 }
1835
1836 const createdCampaigns = await this.campaignService_.create(
1837 campaignsData,
1838 sharedContext
1839 )
1840
1841 for (const createdCampaign of createdCampaigns) {
1842 const campaignBudgetData = campaignIdentifierBudgetMap.get(
1843 createdCampaign.campaign_identifier
1844 )
1845
1846 if (campaignBudgetData) {
1847 this.validateCampaignBudgetData(campaignBudgetData)
1848
1849 campaignBudgetsData.push({
1850 ...campaignBudgetData,
1851 campaign: createdCampaign.id,
1852 })
1853 }
1854 }
1855
1856 if (campaignBudgetsData.length) {
1857 await this.campaignBudgetService_.create(
1858 campaignBudgetsData,
1859 sharedContext
1860 )
1861 }
1862
1863 return createdCampaigns
1864 }
1865
1866 protected validateCampaignBudgetData(data: {
1867 type?: CampaignBudgetTypeValues
1868 currency_code?: string | null
1869 }) {
1870 if (!data.type) {
1871 throw new MedusaError(
1872 MedusaError.Types.INVALID_DATA,
1873 `Campaign Budget type is a required field`
1874 )
1875 }
1876
1877 if (
1878 data.type === CampaignBudgetType.SPEND &&
1879 !isPresent(data.currency_code)
1880 ) {
1881 throw new MedusaError(
1882 MedusaError.Types.INVALID_DATA,
1883 `Campaign Budget type is a required field`
1884 )
1885 }
1886 }
1887
1888 // @ts-expect-error
1889 async updateCampaigns(
1890 data: PromotionTypes.UpdateCampaignDTO,
1891 sharedContext?: Context
1892 ): Promise<PromotionTypes.CampaignDTO>
1893
1894 // @ts-expect-error
1895 async updateCampaigns(
1896 data: PromotionTypes.UpdateCampaignDTO[],
1897 sharedContext?: Context
1898 ): Promise<PromotionTypes.CampaignDTO[]>
1899
1900 @InjectManager()
1901 @EmitEvents()
1902 // @ts-expect-error
1903 async updateCampaigns(
1904 data: PromotionTypes.UpdateCampaignDTO | PromotionTypes.UpdateCampaignDTO[],
1905 @MedusaContext() sharedContext: Context = {}
1906 ): Promise<PromotionTypes.CampaignDTO | PromotionTypes.CampaignDTO[]> {
1907 const input = Array.isArray(data) ? data : [data]
1908 const updatedCampaigns = await this.updateCampaigns_(input, sharedContext)
1909
1910 const campaigns = await this.listCampaigns(
1911 { id: updatedCampaigns.map((p) => p!.id) },
1912 {
1913 relations: ["budget", "promotions"],
1914 },
1915 sharedContext
1916 )
1917
1918 return Array.isArray(data) ? campaigns : campaigns[0]
1919 }
1920
1921 @InjectTransactionManager()
1922 protected async updateCampaigns_(
1923 data: PromotionTypes.UpdateCampaignDTO[],
1924 @MedusaContext() sharedContext: Context = {}
1925 ) {
1926 const campaignIds = data.map((d) => d.id)
1927 const campaignsData: UpdateCampaignDTO[] = []
1928 const updateBudgetData: UpdateCampaignBudgetDTO[] = []
1929 const createBudgetData: CreateCampaignBudgetDTO[] = []
1930
1931 const existingCampaigns = await this.campaignService_.list(
1932 { id: campaignIds },
1933 { relations: ["budget"] },
1934 sharedContext
1935 )
1936
1937 const existingCampaignsMap = new Map<
1938 string,
1939 InferEntityType<typeof Campaign>
1940 >(existingCampaigns.map((campaign) => [campaign.id, campaign]))
1941
1942 for (const updateCampaignData of data) {
1943 const { budget: budgetData, ...campaignData } = updateCampaignData
1944 const existingCampaign = existingCampaignsMap.get(campaignData.id)!
1945
1946 campaignsData.push(campaignData)
1947
1948 // Type & currency code of the budget is immutable, we don't allow for it to be updated.
1949 // If an existing budget is present, we remove the type and currency from being updated
1950 if (
1951 (existingCampaign?.budget && budgetData?.type) ||
1952 budgetData?.currency_code
1953 ) {
1954 delete budgetData?.type
1955 delete budgetData?.currency_code
1956
1957 throw new MedusaError(
1958 MedusaError.Types.INVALID_DATA,
1959 `Campaign budget attributes (type, currency_code) are immutable`
1960 )
1961 }
1962
1963 if (budgetData) {
1964 if (existingCampaign?.budget) {
1965 updateBudgetData.push({
1966 id: existingCampaign.budget.id,
1967 ...budgetData,
1968 })
1969 } else {
1970 createBudgetData.push({
1971 ...budgetData,
1972 campaign: existingCampaign.id,
1973 })
1974 }
1975 }
1976 }
1977
1978 const updatedCampaigns = await this.campaignService_.update(
1979 campaignsData,
1980 sharedContext
1981 )
1982
1983 if (updateBudgetData.length) {
1984 await this.campaignBudgetService_.update(updateBudgetData, sharedContext)
1985 }
1986
1987 if (createBudgetData.length) {
1988 await this.campaignBudgetService_.create(createBudgetData, sharedContext)
1989 }
1990
1991 return updatedCampaigns
1992 }
1993
1994 @InjectManager()
1995 @EmitEvents()
1996 async addPromotionsToCampaign(
1997 data: PromotionTypes.AddPromotionsToCampaignDTO,
1998 @MedusaContext() sharedContext: Context = {}
1999 ): Promise<{ ids: string[] }> {
2000 const ids = await this.addPromotionsToCampaign_(data, sharedContext)
2001
2002 return { ids }
2003 }
2004
2005 // TODO:
2006 // - introduce currency_code to promotion
2007 // - allow promotions to be queried by currency code
2008 // - when the above is present, validate adding promotion to campaign based on currency code
2009 @InjectTransactionManager()
2010 protected async addPromotionsToCampaign_(
2011 data: PromotionTypes.AddPromotionsToCampaignDTO,
2012 @MedusaContext() sharedContext: Context = {}
2013 ) {
2014 const { id, promotion_ids: promotionIds = [] } = data
2015
2016 const campaign = await this.campaignService_.retrieve(id, {}, sharedContext)
2017 const promotionsToAdd = await this.promotionService_.list(
2018 { id: promotionIds, campaign_id: null },
2019 { relations: ["application_method"] },
2020 sharedContext
2021 )
2022
2023 const diff = arrayDifference(
2024 promotionsToAdd.map((p) => p.id),
2025 promotionIds
2026 )
2027
2028 if (diff.length > 0) {
2029 throw new MedusaError(
2030 MedusaError.Types.NOT_FOUND,
2031 `Cannot add promotions (${diff.join(
2032 ","
2033 )}) to campaign. These promotions are either already part of a campaign or not found.`
2034 )
2035 }
2036
2037 const promotionsWithInvalidCurrency = promotionsToAdd.filter(
2038 (promotion) =>
2039 campaign.budget?.type === CampaignBudgetType.SPEND &&
2040 promotion.application_method?.currency_code !==
2041 campaign?.budget?.currency_code
2042 )
2043
2044 if (promotionsWithInvalidCurrency.length > 0) {
2045 throw new MedusaError(
2046 MedusaError.Types.INVALID_DATA,
2047 `Cannot add promotions to campaign where currency_code don't match.`
2048 )
2049 }
2050
2051 await this.promotionService_.update(
2052 promotionsToAdd.map((promotion) => ({
2053 id: promotion.id,
2054 campaign_id: campaign.id,
2055 })),
2056 sharedContext
2057 )
2058
2059 return promotionsToAdd.map((promo) => promo.id)
2060 }
2061
2062 @InjectManager()
2063 @EmitEvents()
2064 async removePromotionsFromCampaign(
2065 data: PromotionTypes.AddPromotionsToCampaignDTO,
2066 @MedusaContext() sharedContext: Context = {}
2067 ): Promise<{ ids: string[] }> {
2068 const ids = await this.removePromotionsFromCampaign_(data, sharedContext)
2069
2070 return { ids }
2071 }
2072
2073 @InjectTransactionManager()
2074 protected async removePromotionsFromCampaign_(
2075 data: PromotionTypes.AddPromotionsToCampaignDTO,
2076 @MedusaContext() sharedContext: Context = {}
2077 ) {
2078 const { id, promotion_ids: promotionIds = [] } = data
2079
2080 await this.campaignService_.retrieve(id, {}, sharedContext)
2081 const promotionsToRemove = await this.promotionService_.list(
2082 { id: promotionIds },
2083 {},
2084 sharedContext
2085 )
2086
2087 const diff = arrayDifference(
2088 promotionsToRemove.map((p) => p.id),
2089 promotionIds
2090 )
2091
2092 if (diff.length > 0) {
2093 throw new MedusaError(
2094 MedusaError.Types.NOT_FOUND,
2095 `Promotions with ids (${diff.join(",")}) not found.`
2096 )
2097 }
2098
2099 await this.promotionService_.update(
2100 promotionsToRemove.map((promotion) => ({
2101 id: promotion.id,
2102 campaign_id: null,
2103 })),
2104 sharedContext
2105 )
2106
2107 return promotionsToRemove.map((promo) => promo.id)
2108 }
2109 }