1 import {
2 BigNumberInput,
3 ComputeActionItemLine,
4 InferEntityType,
5 PromotionTypes,
6 } from "@medusajs/framework/types"
7 import {
8 ApplicationMethodTargetType,
9 ApplicationMethodType,
10 ComputedActions,
11 MathBN,
12 MedusaError,
13 PromotionType,
14 } from "@medusajs/framework/utils"
15 import { areRulesValidForContext } from "../validations"
16 import { computeActionForBudgetExceeded } from "./usage"
17 import { Promotion } from "@models"
18
19 export type EligibleItem = {
20 item_id: string
21 quantity: BigNumberInput
22 }
23
24 function sortByPrice(a: ComputeActionItemLine, b: ComputeActionItemLine) {
25 // Returning a non-zero value for equal subtotals makes this an inconsistent
26 // comparator, which leaves the order of equally priced items up to the sort
27 // implementation rather than keeping it stable. Since the resulting order
28 // decides which items are reserved for the buy side below, that turned into
29 // the promotion being applied or not depending on line item order.
30 if (MathBN.eq(a.subtotal, b.subtotal)) {
31 return 0
32 }
33
34 return MathBN.lt(a.subtotal, b.subtotal) ? 1 : -1
35 }
36
37 function isValidPromotionContext(
38 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>,
39 itemsContext: ComputeActionItemLine[]
40 ): boolean {
41 if (!itemsContext) {
42 throw new MedusaError(
43 MedusaError.Types.INVALID_DATA,
44 `"items" should be present as an array in the context to compute actions`
45 )
46 }
47
48 if (!itemsContext?.length) {
49 return false
50 }
51
52 const minimumBuyQuantity = MathBN.convert(
53 promotion.application_method?.buy_rules_min_quantity ?? 0
54 )
55
56 if (
57 MathBN.lte(minimumBuyQuantity, 0) ||
58 !promotion.application_method?.buy_rules?.length
59 ) {
60 return false
61 }
62
63 return true
64 }
65
66 function normalizePromotionApplicationConfiguration(
67 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>
68 ) {
69 const minimumBuyQuantity = MathBN.convert(
70 promotion.application_method?.buy_rules_min_quantity ?? 0
71 )
72 const targetApplyQuantity = MathBN.convert(
73 promotion.application_method?.apply_to_quantity ?? 0
74 )
75 const maximumApplyQuantity = MathBN.convert(
76 promotion.application_method?.max_quantity ?? 1
77 )
78 const promotionValue = promotion.application_method?.value ?? 0
79
80 return {
81 minimumBuyQuantity,
82 targetApplyQuantity,
83 maximumApplyQuantity,
84 promotionValue,
85 }
86 }
87
88 function calculateRemainingQuantities(
89 eligibleItems: ComputeActionItemLine[],
90 itemsMap: Map<string, EligibleItem[]>,
91 currentPromotionCode: string
92 ): Map<string, BigNumberInput> {
93 const remainingQuantities = new Map<string, BigNumberInput>()
94
95 for (const item of eligibleItems) {
96 let consumedByOtherPromotions = MathBN.convert(0)
97
98 for (const [code, eligibleItems] of itemsMap) {
99 if (code === currentPromotionCode) {
100 continue
101 }
102
103 for (const eligibleItem of eligibleItems) {
104 if (eligibleItem.item_id === item.id) {
105 consumedByOtherPromotions = MathBN.add(
106 consumedByOtherPromotions,
107 eligibleItem.quantity
108 )
109 }
110 }
111 }
112
113 const remaining = MathBN.sub(item.quantity, consumedByOtherPromotions)
114 remainingQuantities.set(item.id, MathBN.max(remaining, 0))
115 }
116
117 return remainingQuantities
118 }
119
120 type PromotionConfig = {
121 minimumBuyQuantity: BigNumberInput
122 targetApplyQuantity: BigNumberInput
123 maximumApplyQuantity: BigNumberInput
124 promotionValue: number
125 }
126
127 type PromotionApplication = {
128 buyItems: EligibleItem[]
129 targetItems: EligibleItem[]
130 isValid: boolean
131 }
132
133 /*
134 Determines which buy and target items should be used for a promotion application.
135
136 We run the following steps to prepare the promotion application state to be used within an application loop:
137 1. Selecting enough buy items to satisfy the minimum buy quantity requirement from the remaining buy quantities
138 2. Identifying target eligible items for application (excluding those used in buy rules) from the remaining target quantities
139 3. Ensuring the application doesn't exceed max_quantity limits for the target items
140 4. Returns a valid application state or marks it invalid if requirements can't be met
141 */
142 function preparePromotionApplicationState(
143 eligibleBuyItems: ComputeActionItemLine[],
144 eligibleTargetItems: ComputeActionItemLine[],
145 remainingBuyQuantities: Map<string, BigNumberInput>,
146 remainingTargetQuantities: Map<string, BigNumberInput>,
147 applicationConfig: PromotionConfig,
148 appliedPromotionQuantity: BigNumberInput
149 ): PromotionApplication {
150 const totalRemainingBuyQuantity = MathBN.sum(
151 ...Array.from(remainingBuyQuantities.values())
152 )
153
154 if (
155 MathBN.lt(totalRemainingBuyQuantity, applicationConfig.minimumBuyQuantity)
156 ) {
157 return { buyItems: [], targetItems: [], isValid: false }
158 }
159
160 const eligibleItemsByPromotion: EligibleItem[] = []
161 let accumulatedQuantity = MathBN.convert(0)
162
163 // Quantity reserved for the buy side is subtracted from what the target side
164 // can use, so reserving a target eligible item can leave the promotion with
165 // no target and drop it entirely - even when a valid assignment exists. For
166 // "buy 2 of {A,B,C}, get 1 A" with one unit each of A, B and C, reserving B
167 // and C leaves A free to be discounted, while reserving A does not.
168 //
169 // Prefer items that cannot serve as targets, keeping the price order within
170 // each group. When every buy eligible item is also target eligible (buy X
171 // get X on a single product) this leaves the order untouched.
172 const targetEligibleItemIds = new Set(
173 eligibleTargetItems.map((eligibleTargetItem) => eligibleTargetItem.id)
174 )
175
176 const buyItemsInReservationOrder = [
177 ...eligibleBuyItems.filter(
178 (eligibleBuyItem) => !targetEligibleItemIds.has(eligibleBuyItem.id)
179 ),
180 ...eligibleBuyItems.filter((eligibleBuyItem) =>
181 targetEligibleItemIds.has(eligibleBuyItem.id)
182 ),
183 ]
184
185 for (const eligibleBuyItem of buyItemsInReservationOrder) {
186 if (MathBN.gte(accumulatedQuantity, applicationConfig.minimumBuyQuantity)) {
187 break
188 }
189
190 const availableQuantity =
191 remainingBuyQuantities.get(eligibleBuyItem.id) || MathBN.convert(0)
192
193 if (MathBN.lte(availableQuantity, 0)) {
194 continue
195 }
196
197 const reservableQuantity = MathBN.min(
198 availableQuantity,
199 MathBN.sub(applicationConfig.minimumBuyQuantity, accumulatedQuantity)
200 )
201
202 if (MathBN.lte(reservableQuantity, 0)) {
203 continue
204 }
205
206 eligibleItemsByPromotion.push({
207 item_id: eligibleBuyItem.id,
208 quantity: reservableQuantity.toNumber(),
209 })
210
211 accumulatedQuantity = MathBN.add(accumulatedQuantity, reservableQuantity)
212 }
213
214 if (MathBN.lt(accumulatedQuantity, applicationConfig.minimumBuyQuantity)) {
215 return { buyItems: [], targetItems: [], isValid: false }
216 }
217
218 const quantitiesUsedInBuyRules = new Map<string, BigNumberInput>()
219
220 for (const buyItem of eligibleItemsByPromotion) {
221 const currentValue =
222 quantitiesUsedInBuyRules.get(buyItem.item_id) || MathBN.convert(0)
223
224 quantitiesUsedInBuyRules.set(
225 buyItem.item_id,
226 MathBN.add(currentValue, buyItem.quantity)
227 )
228 }
229
230 const targetItemsByPromotion: EligibleItem[] = []
231 let availableTargetQuantity = MathBN.convert(0)
232
233 for (const eligibleTargetItem of eligibleTargetItems) {
234 const availableTargetQuantityForItem =
235 remainingTargetQuantities.get(eligibleTargetItem.id) || MathBN.convert(0)
236
237 const quantityUsedInBuyRules =
238 quantitiesUsedInBuyRules.get(eligibleTargetItem.id) || MathBN.convert(0)
239
240 const applicableQuantity = MathBN.sub(
241 availableTargetQuantityForItem,
242 quantityUsedInBuyRules
243 )
244
245 if (MathBN.lte(applicableQuantity, 0)) {
246 continue
247 }
248
249 const remainingNeeded = MathBN.sub(
250 applicationConfig.targetApplyQuantity,
251 availableTargetQuantity
252 )
253
254 const remainingMaxQuantityAllowance = MathBN.sub(
255 applicationConfig.maximumApplyQuantity,
256 appliedPromotionQuantity
257 )
258
259 const fulfillableQuantity = MathBN.min(
260 remainingNeeded,
261 applicableQuantity,
262 remainingMaxQuantityAllowance
263 )
264
265 if (MathBN.lte(fulfillableQuantity, 0)) {
266 continue
267 }
268
269 targetItemsByPromotion.push({
270 item_id: eligibleTargetItem.id,
271 quantity: fulfillableQuantity.toNumber(),
272 })
273
274 availableTargetQuantity = MathBN.add(
275 availableTargetQuantity,
276 fulfillableQuantity
277 )
278
279 if (
280 MathBN.gte(availableTargetQuantity, applicationConfig.targetApplyQuantity)
281 ) {
282 break
283 }
284 }
285
286 const isValid = MathBN.gte(
287 availableTargetQuantity,
288 applicationConfig.targetApplyQuantity
289 )
290
291 return {
292 buyItems: eligibleItemsByPromotion,
293 targetItems: targetItemsByPromotion,
294 isValid,
295 }
296 }
297
298 /*
299 Applies promotion to the target items selected by preparePromotionApplicationState.
300
301 This function performs the application by:
302 1. Calculating promotion amounts based on item prices and promotion value (percentage or fixed)
303 2. Checking promotion budget limits to prevent overspending
304 3. Updating promotional value tracking maps for cross-promotion coordination
305 4. Accumulating total promotion amounts per item across all applications
306 5. Returns computed actions
307 */
308 function applyPromotionToTargetItems(
309 targetItems: EligibleItem[],
310 itemIdPromotionAmountMap: Map<string, BigNumberInput>,
311 methodIdPromoValueMap: Map<string, BigNumberInput>,
312 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>,
313 itemsMap: Map<string, ComputeActionItemLine>,
314 applicationConfig: PromotionConfig
315 ): {
316 computedActions: PromotionTypes.ComputeActions[]
317 appliedPromotionQuantity: BigNumberInput
318 } {
319 const computedActions: PromotionTypes.ComputeActions[] = []
320 let appliedPromotionQuantity = MathBN.convert(0)
321 let remainingQtyToApply = MathBN.convert(
322 applicationConfig.targetApplyQuantity
323 )
324
325 for (const targetItem of targetItems) {
326 if (MathBN.lte(remainingQtyToApply, 0)) {
327 break
328 }
329
330 const item = itemsMap.get(targetItem.item_id)!
331 const appliedPromoValue =
332 methodIdPromoValueMap.get(item.id) ?? MathBN.convert(0)
333 const multiplier = MathBN.min(targetItem.quantity, remainingQtyToApply)
334 const pricePerUnit = MathBN.div(item.subtotal, item.quantity)
335 const applicableAmount = MathBN.mult(pricePerUnit, multiplier)
336
337 let amount
338 if (promotion.application_method?.type === ApplicationMethodType.FIXED) {
339 // Fixed: apply value per unit, capped at item price
340 amount = MathBN.min(
341 MathBN.mult(applicationConfig.promotionValue, multiplier),
342 applicableAmount
343 )
344 } else {
345 amount = MathBN.mult(
346 applicableAmount,
347 applicationConfig.promotionValue
348 ).div(100)
349 }
350
351 if (MathBN.lte(amount, 0)) {
352 continue
353 }
354
355 remainingQtyToApply = MathBN.sub(remainingQtyToApply, multiplier)
356
357 const budgetExceededAction = computeActionForBudgetExceeded(
358 promotion,
359 amount
360 )
361
362 if (budgetExceededAction) {
363 computedActions.push(budgetExceededAction)
364 continue
365 }
366
367 methodIdPromoValueMap.set(
368 item.id,
369 MathBN.add(appliedPromoValue, amount).toNumber()
370 )
371
372 const currentPromotionAmount =
373 itemIdPromotionAmountMap.get(item.id) ?? MathBN.convert(0)
374
375 itemIdPromotionAmountMap.set(
376 item.id,
377 MathBN.add(currentPromotionAmount, amount)
378 )
379
380 appliedPromotionQuantity = MathBN.add(appliedPromotionQuantity, multiplier)
381 }
382
383 return { computedActions, appliedPromotionQuantity }
384 }
385
386 /*
387 Updates the remaining quantities of the eligible items (buy and target) based on the application.
388 This is used to prevent double-usage of the same item in the next iteration of the
389 application loop.
390
391 We track the total consumed quantities per item to handle buy+target scenarios of the same item.
392 */
393 function updateEligibleItemQuantities(
394 remainingBuyQuantities: Map<string, BigNumberInput>,
395 remainingTargetQuantities: Map<string, BigNumberInput>,
396 application: PromotionApplication
397 ): void {
398 const totalConsumedQuantities = new Map<string, BigNumberInput>()
399
400 for (const buyItem of application.buyItems) {
401 const currentConsumed =
402 totalConsumedQuantities.get(buyItem.item_id) || MathBN.convert(0)
403
404 totalConsumedQuantities.set(
405 buyItem.item_id,
406 MathBN.add(currentConsumed, buyItem.quantity)
407 )
408 }
409
410 for (const targetItem of application.targetItems) {
411 const currentConsumed =
412 totalConsumedQuantities.get(targetItem.item_id) || MathBN.convert(0)
413
414 totalConsumedQuantities.set(
415 targetItem.item_id,
416 MathBN.add(currentConsumed, targetItem.quantity)
417 )
418 }
419
420 // Update remaining quantities of buy and target items based on totalConsumedQuantities tracked from previous iterations
421 for (const [itemId, consumedQuantity] of totalConsumedQuantities) {
422 if (remainingBuyQuantities.has(itemId)) {
423 const currentBuyRemaining =
424 remainingBuyQuantities.get(itemId) || MathBN.convert(0)
425
426 remainingBuyQuantities.set(
427 itemId,
428 MathBN.sub(currentBuyRemaining, consumedQuantity)
429 )
430 }
431
432 if (remainingTargetQuantities.has(itemId)) {
433 const currentTargetRemaining =
434 remainingTargetQuantities.get(itemId) || MathBN.convert(0)
435
436 remainingTargetQuantities.set(
437 itemId,
438 MathBN.sub(currentTargetRemaining, consumedQuantity)
439 )
440 }
441 }
442 }
443
444 function updateEligibleItems(
445 totalEligibleItemsMap: Map<string, EligibleItem>,
446 applicationItems: EligibleItem[]
447 ): void {
448 for (const item of applicationItems) {
449 const existingItem = totalEligibleItemsMap.get(item.item_id)
450
451 // If the item already exists, we add the quantity to the existing item
452 if (existingItem) {
453 existingItem.quantity = MathBN.add(
454 existingItem.quantity,
455 item.quantity
456 ).toNumber()
457 } else {
458 totalEligibleItemsMap.set(item.item_id, { ...item })
459 }
460 }
461 }
462
463 function createComputedActionsFromPromotionApplication(
464 itemIdPromotionAmountMap: Map<string, BigNumberInput>,
465 promotionCode: string
466 ): PromotionTypes.ComputeActions[] {
467 const computedActions: PromotionTypes.ComputeActions[] = []
468
469 for (const [itemId, totalAmount] of itemIdPromotionAmountMap) {
470 if (MathBN.gt(totalAmount, 0)) {
471 computedActions.push({
472 action: ComputedActions.ADD_ITEM_ADJUSTMENT,
473 item_id: itemId,
474 amount: totalAmount,
475 code: promotionCode,
476 })
477 }
478 }
479
480 return computedActions
481 }
482
483 /*
484 Grabs all the items in the context where the rules apply
485 We then sort by price to prioritize most valuable item
486 */
487 function filterItemsByPromotionRules(
488 itemsContext: ComputeActionItemLine[],
489 rules?: PromotionTypes.PromotionRuleDTO[]
490 ) {
491 return itemsContext
492 .filter((item) =>
493 areRulesValidForContext(
494 rules || [],
495 item,
496 ApplicationMethodTargetType.ITEMS
497 )
498 )
499 .sort(sortByPrice)
500 }
501
502 export function getComputedActionsForBuyGet(
503 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>,
504 itemsContext: ComputeActionItemLine[],
505 methodIdPromoValueMap: Map<string, BigNumberInput>,
506 eligibleBuyItemMap: Map<string, EligibleItem[]>,
507 eligibleTargetItemMap: Map<string, EligibleItem[]>
508 ): PromotionTypes.ComputeActions[] {
509 if (!isValidPromotionContext(promotion, itemsContext)) {
510 return []
511 }
512
513 const applicationConfig =
514 normalizePromotionApplicationConfiguration(promotion)
515
516 const itemsMap = new Map<string, ComputeActionItemLine>(
517 itemsContext.map((i) => [i.id, i])
518 )
519
520 const eligibleBuyItems = filterItemsByPromotionRules(
521 itemsContext,
522 promotion.application_method?.buy_rules
523 )
524
525 const eligibleTargetItems = filterItemsByPromotionRules(
526 itemsContext,
527 promotion.application_method?.target_rules
528 )
529
530 const remainingBuyQuantities = calculateRemainingQuantities(
531 eligibleBuyItems,
532 eligibleBuyItemMap,
533 promotion.code!
534 )
535
536 const remainingTargetQuantities = calculateRemainingQuantities(
537 eligibleTargetItems,
538 eligibleTargetItemMap,
539 promotion.code!
540 )
541
542 const totalEligibleBuyItemsMap = new Map<string, EligibleItem>()
543 const totalEligibleTargetItemsMap = new Map<string, EligibleItem>()
544 const itemIdPromotionAmountMap = new Map<string, BigNumberInput>()
545 const computedActions: PromotionTypes.ComputeActions[] = []
546
547 const MAX_PROMOTION_ITERATIONS = 1000
548 let iterationCount = 0
549 let appliedPromotionQuantity = MathBN.convert(0)
550
551 /*
552 This loop continues applying the promotion until one of the stopping conditions is met:
553 - No more items satisfy the minimum buy quantity requirement
554 - Maximum applicable promotion quantity is reached
555 - No valid target items can be found for promotion application
556 - Maximum iteration count is reached (safety check)
557
558 Each iteration:
559 1. Prepares an application state (selects buy items + eligible target items)
560 2. Applies promotion to the selected target items
561 3. Updates remaining quantities to prevent double-usage in next iteration
562 4. Updates the total eligible items for next iteration
563 */
564 while (true) {
565 iterationCount++
566
567 if (iterationCount > MAX_PROMOTION_ITERATIONS) {
568 console.warn(
569 `Buy-get promotion ${promotion.code} exceeded maximum iterations (${MAX_PROMOTION_ITERATIONS}). Breaking loop to prevent infinite execution.`
570 )
571
572 break
573 }
574 // We prepare an application state for the promotion to be applied on all eligible items
575 // We use this as a source of truth to update the remaining quantities of the eligible items
576 // and the total eligible items
577 const applicationState = preparePromotionApplicationState(
578 eligibleBuyItems,
579 eligibleTargetItems,
580 remainingBuyQuantities,
581 remainingTargetQuantities,
582 applicationConfig,
583 appliedPromotionQuantity
584 )
585
586 // If the application state is not valid, we break the loop
587 // If it is not valid, it means that there are no more eligible items to apply the promotion to
588 // for the configuration of the promotion
589 if (!applicationState.isValid) {
590 break
591 }
592
593 // We apply the promotion to the target items based on the target items that are eligible
594 // and the remaining quantities of the target items
595 const application = applyPromotionToTargetItems(
596 applicationState.targetItems,
597 itemIdPromotionAmountMap,
598 methodIdPromoValueMap,
599 promotion,
600 itemsMap,
601 applicationConfig
602 )
603
604 computedActions.push(...application.computedActions)
605
606 // Computed actions being generated means that the promotion is applied.
607 // We now need to update the remaining quantities of the eligible items and the total eligible items
608 // to be used in the next iteration of the loop
609 appliedPromotionQuantity = MathBN.add(
610 appliedPromotionQuantity,
611 application.appliedPromotionQuantity
612 )
613
614 updateEligibleItemQuantities(
615 remainingBuyQuantities,
616 remainingTargetQuantities,
617 applicationState
618 )
619
620 updateEligibleItems(totalEligibleBuyItemsMap, applicationState.buyItems)
621 updateEligibleItems(
622 totalEligibleTargetItemsMap,
623 applicationState.targetItems
624 )
625 }
626
627 const finalActions = createComputedActionsFromPromotionApplication(
628 itemIdPromotionAmountMap,
629 promotion.code!
630 )
631 computedActions.push(...finalActions)
632
633 eligibleBuyItemMap.set(
634 promotion.code!,
635 Array.from(totalEligibleBuyItemsMap.values())
636 )
637 eligibleTargetItemMap.set(
638 promotion.code!,
639 Array.from(totalEligibleTargetItemsMap.values())
640 )
641
642 return computedActions
643 }
644
645 export function sortByBuyGetType(a, b) {
646 if (a.type === PromotionType.BUYGET && b.type !== PromotionType.BUYGET) {
647 return -1 // BuyGet promotions come first
648 } else if (
649 a.type !== PromotionType.BUYGET &&
650 b.type === PromotionType.BUYGET
651 ) {
652 return 1 // BuyGet promotions come first
653 } else if (a.type === b.type) {
654 // If types are equal, sort by application_method.value in descending order when types are equal
655 if (a.application_method.value < b.application_method.value) {
656 return 1 // Higher value comes first
657 } else if (a.application_method.value > b.application_method.value) {
658 return -1 // Lower value comes later
659 }
660
661 /*
662 If the promotion is a BuyGet & the value is the same, we need to sort by the following criteria:
663 - buy_rules_min_quantity in descending order
664 - apply_to_quantity in descending order
665 */
666 if (a.type === PromotionType.BUYGET) {
667 if (
668 a.application_method.buy_rules_min_quantity <
669 b.application_method.buy_rules_min_quantity
670 ) {
671 return 1
672 } else if (
673 a.application_method.buy_rules_min_quantity >
674 b.application_method.buy_rules_min_quantity
675 ) {
676 return -1
677 }
678
679 if (
680 a.application_method.apply_to_quantity <
681 b.application_method.apply_to_quantity
682 ) {
683 return 1
684 } else if (
685 a.application_method.apply_to_quantity >
686 b.application_method.apply_to_quantity
687 ) {
688 return -1
689 }
690 }
691
692 return 0 // If all criteria are equal, keep original order
693 } else {
694 return 0 // If types are different (and not BuyGet), keep original order
695 }
696 }