1 import {
2 ApplicationMethodAllocationValues,
3 BigNumberInput,
4 InferEntityType,
5 PromotionTypes,
6 } from "@medusajs/framework/types"
7 import {
8 ApplicationMethodAllocation,
9 ApplicationMethodTargetType,
10 calculateAdjustmentAmountFromPromotion,
11 ComputedActions,
12 MathBN,
13 MedusaError,
14 ApplicationMethodTargetType as TargetType,
15 } from "@medusajs/framework/utils"
16 import { Promotion } from "@models"
17 import { areRulesValidForContext } from "../validations"
18 import { sortLineItemByPriceAscending } from "./sort-by-price"
19 import { computeActionForBudgetExceeded } from "./usage"
20
21 function validateContext(
22 contextKey: string,
23 context: PromotionTypes.ComputeActionContext[TargetType]
24 ) {
25 if (!context) {
26 throw new MedusaError(
27 MedusaError.Types.INVALID_DATA,
28 `"${contextKey}" should be present as an array in the context for computeActions`
29 )
30 }
31 }
32
33 export function getComputedActionsForItems(
34 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>,
35 items: PromotionTypes.ComputeActionContext[TargetType.ITEMS],
36 appliedPromotionsMap: Map<string, number>,
37 allocationOverride?: ApplicationMethodAllocationValues
38 ): PromotionTypes.ComputeActions[] {
39 validateContext("items", items)
40
41 return applyPromotionToItems(
42 promotion,
43 items,
44 appliedPromotionsMap,
45 allocationOverride
46 )
47 }
48
49 function applyPromotionToItems(
50 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>,
51 items: PromotionTypes.ComputeActionContext[TargetType.ITEMS],
52 appliedPromotionsMap: Map<string, BigNumberInput>,
53 allocationOverride?: ApplicationMethodAllocationValues
54 ): PromotionTypes.ComputeActions[] {
55 const { application_method: applicationMethod } = promotion
56
57 if (!applicationMethod) {
58 return []
59 }
60
61 const allocation = applicationMethod?.allocation! || allocationOverride
62 const target = applicationMethod?.target_type
63
64 if (!items?.length || !target) {
65 return []
66 }
67
68 const computedActions: PromotionTypes.ComputeActions[] = []
69
70 let applicableItems = getValidItemsForPromotion(
71 items,
72 promotion
73 ) as PromotionTypes.ComputeActionItemLine[]
74
75 if (!applicableItems.length) {
76 return computedActions
77 }
78
79 if (allocation === ApplicationMethodAllocation.ONCE) {
80 applicableItems = applicableItems.sort(sortLineItemByPriceAscending)
81 }
82
83 const isTargetLineItems = target === TargetType.ITEMS
84 const isTargetOrder = target === TargetType.ORDER
85 const promotionValue = applicationMethod?.value ?? 0
86 const maxQuantity = applicationMethod?.max_quantity!
87 let remainingQuota = maxQuantity ?? 0
88
89 let lineItemsAmount = MathBN.convert(0)
90 if (allocation === ApplicationMethodAllocation.ACROSS) {
91 lineItemsAmount = applicableItems.reduce((acc, item) => {
92 const itemBase = promotion.is_tax_inclusive
93 ? item.original_total
94 : item.subtotal
95 const appliedExclTax = appliedPromotionsMap.get(item.id) ?? 0
96 const appliedInBase = promotion.is_tax_inclusive
97 ? MathBN.mult(
98 appliedExclTax,
99 MathBN.div(item.original_total, item.subtotal)
100 )
101 : appliedExclTax
102
103 return MathBN.sub(MathBN.add(acc, itemBase), appliedInBase)
104 }, MathBN.convert(0))
105
106 if (MathBN.lte(lineItemsAmount, 0)) {
107 return computedActions
108 }
109 }
110
111 for (const item of applicableItems) {
112 if (
113 allocation === ApplicationMethodAllocation.ONCE &&
114 remainingQuota <= 0
115 ) {
116 break
117 }
118 if (
119 MathBN.lte(
120 promotion.is_tax_inclusive ? item.original_total : item.subtotal,
121 0
122 )
123 ) {
124 continue
125 }
126
127 const appliedPromoValue = appliedPromotionsMap.get(item.id) ?? 0
128
129 const effectiveMaxQuantity =
130 allocation === ApplicationMethodAllocation.ONCE
131 ? Math.min(remainingQuota ?? 0, Number(item.quantity))
132 : maxQuantity
133
134 // If the allocation is once, we rely on the existing logic for each allocation, as the calculate is the same: apply the promotion value to the line item
135 const effectiveAllocation =
136 allocation === ApplicationMethodAllocation.ONCE
137 ? ApplicationMethodAllocation.EACH
138 : allocation
139
140 const amount = calculateAdjustmentAmountFromPromotion(
141 item,
142 {
143 value: promotionValue,
144 applied_value: appliedPromoValue,
145 is_tax_inclusive: promotion.is_tax_inclusive,
146 max_quantity: effectiveMaxQuantity,
147 type: applicationMethod?.type!,
148 allocation: effectiveAllocation,
149 },
150 lineItemsAmount
151 )
152
153 if (MathBN.lte(amount, 0)) {
154 continue
155 }
156
157 const budgetExceededAction = computeActionForBudgetExceeded(
158 promotion,
159 amount
160 )
161
162 if (budgetExceededAction) {
163 computedActions.push(budgetExceededAction)
164 continue
165 }
166
167 const appliedAmountExclTax = promotion.is_tax_inclusive
168 ? MathBN.mult(amount, MathBN.div(item.subtotal, item.original_total))
169 : amount
170
171 appliedPromotionsMap.set(
172 item.id,
173 MathBN.add(appliedPromoValue, appliedAmountExclTax)
174 )
175
176 if (allocation === ApplicationMethodAllocation.ONCE) {
177 // We already know exactly how many units we applied via effectiveMaxQuantity
178 const quantityApplied = Math.min(
179 effectiveMaxQuantity,
180 Number(item.quantity)
181 )
182 remainingQuota -= quantityApplied
183 }
184
185 if (isTargetLineItems || isTargetOrder) {
186 computedActions.push({
187 action: ComputedActions.ADD_ITEM_ADJUSTMENT,
188 item_id: item.id,
189 amount,
190 code: promotion.code!,
191 is_tax_inclusive: promotion.is_tax_inclusive,
192 })
193 }
194 }
195
196 return computedActions
197 }
198
199 function getValidItemsForPromotion(
200 items:
201 | PromotionTypes.ComputeActionContext[TargetType.ITEMS]
202 | PromotionTypes.ComputeActionContext[TargetType.SHIPPING_METHODS],
203 promotion: PromotionTypes.PromotionDTO | InferEntityType<typeof Promotion>
204 ) {
205 if (!items?.length || !promotion?.application_method) {
206 return []
207 }
208
209 const isTargetShippingMethod =
210 promotion.application_method?.target_type === TargetType.SHIPPING_METHODS
211
212 const targetRules = promotion.application_method?.target_rules ?? []
213 const hasTargetRules = targetRules.length > 0
214
215 if (isTargetShippingMethod && !hasTargetRules) {
216 return items.filter(
217 (item) => item && "subtotal" in item && MathBN.gt(item.subtotal, 0)
218 )
219 }
220
221 return items.filter((item) => {
222 if (!item) {
223 return false
224 }
225
226 if ("is_discountable" in item && !item.is_discountable) {
227 return false
228 }
229
230 if (!("subtotal" in item) || MathBN.lte(item.subtotal, 0)) {
231 return false
232 }
233
234 if (!isTargetShippingMethod && !("quantity" in item)) {
235 return false
236 }
237
238 if (!hasTargetRules) {
239 return true
240 }
241
242 return areRulesValidForContext(
243 promotion?.application_method?.target_rules!,
244 item,
245 ApplicationMethodTargetType.ITEMS
246 )
247 })
248 }