1 import { HttpTypes } from "@medusajs/types"
2 import { i18n } from "../components/utilities/i18n"
3
4 export enum PromotionStatus {
5 SCHEDULED = "SCHEDULED",
6 EXPIRED = "EXPIRED",
7 ACTIVE = "ACTIVE",
8 INACTIVE = "INACTIVE",
9 DRAFT = "DRAFT",
10 }
11
12 export type StatusColors = "grey" | "orange" | "green" | "red" | "grey"
13 export type StatusMap = Record<string, [StatusColors, string]>
14 export const promotionStatusMap: StatusMap = {
15 [PromotionStatus.ACTIVE]: ["green", i18n.t("statuses.active")],
16 [PromotionStatus.INACTIVE]: ["red", i18n.t("statuses.inactive")],
17 [PromotionStatus.DRAFT]: ["grey", i18n.t("statuses.draft")],
18 [PromotionStatus.SCHEDULED]: [
19 "orange",
20 `${i18n.t("promotions.fields.campaign")} ${i18n
21 .t("statuses.scheduled")
22 .toLowerCase()}`,
23 ],
24 [PromotionStatus.EXPIRED]: [
25 "red",
26 `${i18n.t("promotions.fields.campaign")} ${i18n
27 .t("statuses.expired")
28 .toLowerCase()}`,
29 ],
30 }
31
32 export const getPromotionStatus = (promotion: HttpTypes.AdminPromotion) => {
33 const date = new Date()
34 const campaign = promotion.campaign
35
36 if (!campaign) {
37 return promotionStatusMap[promotion.status!.toUpperCase()]
38 }
39
40 if (campaign.starts_at && new Date(campaign.starts_at!) > date) {
41 return promotionStatusMap[PromotionStatus.SCHEDULED]
42 }
43
44 const campaignBudget = campaign.budget
45 // For per-attribute budgets, `used` aggregates usage across all attribute
46 // values while `limit` applies to each attribute value individually, so
47 // comparing them cannot tell whether the budget is exhausted.
48 const isPerAttributeBudget =
49 campaignBudget?.type === "use_by_attribute" ||
50 campaignBudget?.type === "spend_by_attribute"
51 const overBudget =
52 campaignBudget &&
53 !isPerAttributeBudget &&
54 campaignBudget.limit &&
55 campaignBudget.used! > campaignBudget.limit!
56
57 if ((campaign.ends_at && new Date(campaign.ends_at) < date) || overBudget) {
58 return promotionStatusMap[PromotionStatus.EXPIRED]
59 }
60
61 return promotionStatusMap[promotion.status!.toUpperCase()]
62 }