1 import {
2 BigNumberInput,
3 CampaignBudgetExceededAction,
4 CampaignBudgetUsageContext,
5 CampaignBudgetUsageDTO,
6 ComputeActionContext,
7 InferEntityType,
8 PromotionDTO,
9 } from "@medusajs/framework/types"
10 import {
11 CampaignBudgetType,
12 ComputedActions,
13 MathBN,
14 } from "@medusajs/framework/utils"
15 import { Promotion } from "@models"
16
17 /**
18 * Compute the action for a budget exceeded.
19 * @param promotion - the promotion being applied
20 * @param amount - amount can be:
21 * 1. discounted amount in case of spend budget
22 * 2. number of times the promotion has been used in case of usage budget
23 * 3. number of times the promotion has been used by a specific attribute value in case of use_by_attribute budget
24 * @param attributeUsage - the attribute usage in case of use_by_attribute budget
25 * @returns the exceeded action if the budget is exceeded, otherwise undefined
26 */
27 export function computeActionForBudgetExceeded(
28 promotion: PromotionDTO | InferEntityType<typeof Promotion>,
29 amount: BigNumberInput,
30 attributeUsage?: CampaignBudgetUsageDTO
31 ): CampaignBudgetExceededAction | void {
32 const campaignBudget = promotion.campaign?.budget
33
34 if (!campaignBudget) {
35 return
36 }
37
38 if (
39 campaignBudget.type === CampaignBudgetType.USE_BY_ATTRIBUTE &&
40 !attributeUsage
41 ) {
42 return
43 }
44
45 const campaignBudgetUsed = attributeUsage
46 ? attributeUsage.used
47 : campaignBudget.used ?? 0
48
49 const totalUsed =
50 campaignBudget.type === CampaignBudgetType.SPEND
51 ? MathBN.add(campaignBudgetUsed, amount)
52 : MathBN.add(campaignBudgetUsed, 1)
53
54 if (campaignBudget.limit && MathBN.gt(totalUsed, campaignBudget.limit)) {
55 return {
56 action: ComputedActions.CAMPAIGN_BUDGET_EXCEEDED,
57 code: promotion.code!,
58 }
59 }
60 }
61
62 export function getBudgetUsageContextFromComputeActionContext(
63 computeActionContext: ComputeActionContext
64 ): CampaignBudgetUsageContext {
65 return {
66 customer_id:
67 computeActionContext.customer_id ??
68 (computeActionContext.customer as any)?.id ??
69 null,
70 customer_email:
71 (computeActionContext.email as string | undefined | null) ?? null,
72 }
73 }