@managesome/eposmatic-toolkit 0.4.38 → 0.4.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1021,7 +1021,12 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
1021
1021
  subtotal: orderLevelDiscountBaseAmount,
1022
1022
  hasExcludedRefs: false,
1023
1023
  };
1024
- if (hasExcludedRefs && !is_discount_percentage) {
1024
+ // A fixed discount with exclusions is legitimate: the builder already
1025
+ // normalized it against the eligible subtotal. Only clear when there
1026
+ // is nothing left to discount - the capping branch below re-derives
1027
+ // the amount from the same base. (The voucher copy never had this
1028
+ // early clear, which is why the two drifted.)
1029
+ if (hasExcludedRefs && !is_discount_percentage && eligibleSubtotal <= 0) {
1025
1030
  clearOrderLevelDiscount('loyalty');
1026
1031
  }
1027
1032
  else {
@@ -1034,10 +1039,7 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
1034
1039
  Number.isFinite(max_discount_amount) &&
1035
1040
  max_discount_amount >= 0;
1036
1041
  const hasFlatMaxPercentage = !is_discount_percentage && hasRelevantPercentageCap;
1037
- if (hasExcludedRefs && !is_discount_percentage && !hasFlatMaxPercentage) {
1038
- clearOrderLevelDiscount('loyalty');
1039
- }
1040
- else if (hasExcludedRefs) {
1042
+ if (hasExcludedRefs) {
1041
1043
  // Excluded items present: must apply percentage against eligible subtotal only.
1042
1044
  const eligibleBase = hasFlatMaxPercentage
1043
1045
  ? (0, utils_1.parseNum)((0, utils_1.getNetItemsValueAfterItemDiscount)({
@@ -1165,7 +1167,10 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
1165
1167
  Number.isFinite(max_discount_amount) &&
1166
1168
  max_discount_amount >= 0;
1167
1169
  const hasFlatMaxPercentage = !is_discount_percentage && hasRelevantPercentageCap;
1168
- if (hasExcludedRefs && !is_discount_percentage && !hasFlatMaxPercentage) {
1170
+ // Same rule as the loyalty slot: a fixed discount with exclusions is
1171
+ // valid (the builder already normalized it against the eligible
1172
+ // subtotal), so only clear when nothing is left to discount.
1173
+ if (hasExcludedRefs && !is_discount_percentage && eligibleSubtotal <= 0) {
1169
1174
  clearOrderLevelDiscount('voucher');
1170
1175
  }
1171
1176
  else if (hasExcludedRefs) {
@@ -2517,6 +2522,7 @@ function getUpdateItemInCartData(data, payload, courses, listnerSettings, applie
2517
2522
  ...data,
2518
2523
  ...(iterations.length > 0 && { iterations }),
2519
2524
  categories,
2525
+ ...getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId: payload._id }),
2520
2526
  };
2521
2527
  const synced = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2522
2528
  if (appliedCustomDiscounts && appliedCustomDiscounts.length > 0) {
@@ -2569,6 +2575,47 @@ function getUpdateCartInfoData(data, payload, courses, listnerSettings, syncCont
2569
2575
  };
2570
2576
  }
2571
2577
  /* ======================><====================== */
2578
+ /**
2579
+ * Drop the claim for any offer whose last stamped item was just removed.
2580
+ *
2581
+ * An item reward lives both in `redeemed_offers` and on the item's own
2582
+ * `item_discount_details`. The offers sync is parked while an order is edited, so
2583
+ * removing a reward item used to leave its claim behind: the order could still be
2584
+ * settled against a reward that is no longer in it. This reconciles the one case
2585
+ * that needs no offer definition - nothing stamped is left.
2586
+ */
2587
+ function getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId, }) {
2588
+ if (removedItemId == null)
2589
+ return {};
2590
+ const removedOfferIds = [];
2591
+ for (let i = 0; i < (data.categories ?? []).length; i++) {
2592
+ const items = data.categories?.[i].items ?? [];
2593
+ for (let j = 0; j < items.length; j++) {
2594
+ if (items[j]._id !== removedItemId)
2595
+ continue;
2596
+ const discountDetails = items[j].item_discount_details;
2597
+ const offerId = discountDetails?.loyalty_discount_id ?? discountDetails?.voucher_discount_id;
2598
+ if (offerId != null)
2599
+ removedOfferIds.push(offerId);
2600
+ }
2601
+ }
2602
+ if (removedOfferIds.length === 0)
2603
+ return {};
2604
+ const nextRedeemedOffers = { ...(getRedeemedOffersMap(data.redeemed_offers) ?? {}) };
2605
+ for (let i = 0; i < removedOfferIds.length; i++) {
2606
+ const offerId = getNormalizedOfferId(removedOfferIds[i]);
2607
+ if (offerId == null)
2608
+ continue;
2609
+ const stillStamped = (categories ?? []).some((category) => (category.items ?? []).some((item) => {
2610
+ const details = item.item_discount_details;
2611
+ return (getNormalizedOfferId(details?.loyalty_discount_id) === offerId ||
2612
+ getNormalizedOfferId(details?.voucher_discount_id) === offerId);
2613
+ }));
2614
+ if (!stillStamped)
2615
+ delete nextRedeemedOffers[offerId];
2616
+ }
2617
+ return { redeemed_offers: getRedeemedOffersMap(nextRedeemedOffers) };
2618
+ }
2572
2619
  function getRemoveItemFromCartData(data, payload, courses, listnerSettings, appliedCustomDiscounts) {
2573
2620
  const orderItemIdsMap = {};
2574
2621
  let categories;
@@ -2647,6 +2694,7 @@ function getRemoveItemFromCartData(data, payload, courses, listnerSettings, appl
2647
2694
  ...data,
2648
2695
  ...(iterations.length > 0 && { iterations }),
2649
2696
  categories,
2697
+ ...getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId: payload._id }),
2650
2698
  };
2651
2699
  const synced = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2652
2700
  if (appliedCustomDiscounts && appliedCustomDiscounts.length > 0) {
@@ -51,7 +51,11 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
51
51
  return;
52
52
  let applyLoyalty;
53
53
  let applyVoucher;
54
- const excludeRefs = undefined;
54
+ // "hide these options" and "this option is not discountable" are two different
55
+ // lists and were previously crossed here: the hide list was never populated and
56
+ // the no-discount slot received the hide list, so editing a reward item hid
57
+ // nothing and price-protected the wrong options.
58
+ let excludeRefs = undefined;
55
59
  let excludedDiscountRefs = undefined;
56
60
  const zeroPriceRefs = undefined;
57
61
  // Step 1: Check if loyalty discount or voucher discount is applied
@@ -61,20 +65,24 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
61
65
  return;
62
66
  // const rewardItems = offer?.reward_items;
63
67
  let refs = [];
68
+ let offerHideRefs = [];
64
69
  let offerExcludedDiscountRefs = [];
65
70
  let applicable_quantity = 1;
66
71
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
67
72
  if (offer.reward_items == null)
68
73
  return;
69
74
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
70
- offerExcludedDiscountRefs = offer.reward_items.excluded_refs;
75
+ // excluded_refs hides options; exclusive_refs marks options as not discountable.
76
+ offerHideRefs = offer.reward_items.excluded_refs;
77
+ offerExcludedDiscountRefs = offer.reward_items.exclusive_refs;
71
78
  applicable_quantity = offer.reward_items.num_of_items || 1;
72
79
  }
73
80
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
74
81
  if (offer.reward_discount_items == null)
75
82
  return;
76
83
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
77
- offerExcludedDiscountRefs = offer.reward_discount_items.excluded_refs;
84
+ offerHideRefs = offer.reward_discount_items.excluded_refs;
85
+ offerExcludedDiscountRefs = offer.reward_discount_items.exclusive_refs;
78
86
  applicable_quantity = offer.reward_discount_items.num_of_items || 1;
79
87
  }
80
88
  let discount_details = null;
@@ -93,6 +101,7 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
93
101
  discount_details,
94
102
  applicable_quantity,
95
103
  };
104
+ excludeRefs = offerHideRefs;
96
105
  excludedDiscountRefs = offerExcludedDiscountRefs;
97
106
  }
98
107
  if (isVoucherDiscountApplied) {
@@ -101,20 +110,24 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
101
110
  return;
102
111
  // const rewardItems = offer?.reward_items;
103
112
  let refs = [];
113
+ let offerHideRefs = [];
104
114
  let offerExcludedDiscountRefs = [];
105
115
  let applicable_quantity = 1;
106
116
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
107
117
  if (offer.reward_items == null)
108
118
  return;
109
119
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
110
- offerExcludedDiscountRefs = offer.reward_items.excluded_refs;
120
+ // excluded_refs hides options; exclusive_refs marks options as not discountable.
121
+ offerHideRefs = offer.reward_items.excluded_refs;
122
+ offerExcludedDiscountRefs = offer.reward_items.exclusive_refs;
111
123
  applicable_quantity = offer.reward_items.num_of_items || 1;
112
124
  }
113
125
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
114
126
  if (offer.reward_discount_items == null)
115
127
  return;
116
128
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
117
- offerExcludedDiscountRefs = offer.reward_discount_items.excluded_refs;
129
+ offerHideRefs = offer.reward_discount_items.excluded_refs;
130
+ offerExcludedDiscountRefs = offer.reward_discount_items.exclusive_refs;
118
131
  applicable_quantity = offer.reward_discount_items.num_of_items || 1;
119
132
  }
120
133
  let discount_details = null;
@@ -133,6 +146,7 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
133
146
  discount_details,
134
147
  applicable_quantity,
135
148
  };
149
+ excludeRefs = offerHideRefs;
136
150
  excludedDiscountRefs = offerExcludedDiscountRefs;
137
151
  }
138
152
  // TODO: We need to add use case for HalfHalf and Specials
@@ -38,11 +38,26 @@ interface IGetCappedOfferDiscountAmount {
38
38
  maxDiscountPercentage?: number | null;
39
39
  }
40
40
  export declare function getCappedOfferDiscountAmount({ baseAmount, discountValue, isDiscountPercentage, maxDiscountAmount, maxDiscountPercentage, }: IGetCappedOfferDiscountAmount): number;
41
+ /**
42
+ * Does this order line match any of the given refs?
43
+ *
44
+ * A ref is an **item-level** id: an item id, and - because a SPECIAL or
45
+ * HALF_HALF order line stores its own document id in `item_id` - a special or
46
+ * half-half id too. Modifier/option refs never appear here: those belong to the
47
+ * reward's "Hide Options" / "Discount Not Applicable" lists, which act on the
48
+ * modifier tree at selection time, not on spend qualification.
49
+ */
50
+ export declare function doesOrderItemMatchRefs(item: {
51
+ item_id?: string | null;
52
+ }, refs: string[]): boolean;
41
53
  /**
42
54
  * Calculate the eligible subtotal by excluding items/categories in excluded_refs.
43
55
  *
44
56
  * Shared by the cart engine (discount application/re-sync) and the offer-stats
45
57
  * engine (spend qualification) so both use the exact same exclusion math.
58
+ *
59
+ * A ref matches a whole category (`category_id`) or an item - where "item" means
60
+ * the item id, one of its modifier refs, or one of its option refs.
46
61
  */
47
62
  export declare function calculateEligibleOfferDiscountDetails(categories: IOrderCategory[] | undefined, excluded_refs: string[]): {
48
63
  subtotal: number;
@@ -23,6 +23,7 @@ exports.formattedStoreName = formattedStoreName;
23
23
  exports.getPercentage = getPercentage;
24
24
  exports.getPercentageAmount = getPercentageAmount;
25
25
  exports.getCappedOfferDiscountAmount = getCappedOfferDiscountAmount;
26
+ exports.doesOrderItemMatchRefs = doesOrderItemMatchRefs;
26
27
  exports.calculateEligibleOfferDiscountDetails = calculateEligibleOfferDiscountDetails;
27
28
  const constants_1 = require("../../constants");
28
29
  const price_conversion_1 = require("./price-conversion");
@@ -321,11 +322,28 @@ function getCappedOfferDiscountAmount({ baseAmount, discountValue, isDiscountPer
321
322
  }
322
323
  return Math.min(amount, normalizedBaseAmount);
323
324
  }
325
+ /**
326
+ * Does this order line match any of the given refs?
327
+ *
328
+ * A ref is an **item-level** id: an item id, and - because a SPECIAL or
329
+ * HALF_HALF order line stores its own document id in `item_id` - a special or
330
+ * half-half id too. Modifier/option refs never appear here: those belong to the
331
+ * reward's "Hide Options" / "Discount Not Applicable" lists, which act on the
332
+ * modifier tree at selection time, not on spend qualification.
333
+ */
334
+ function doesOrderItemMatchRefs(item, refs) {
335
+ if (refs.length === 0)
336
+ return false;
337
+ return item.item_id != null && refs.includes(item.item_id);
338
+ }
324
339
  /**
325
340
  * Calculate the eligible subtotal by excluding items/categories in excluded_refs.
326
341
  *
327
342
  * Shared by the cart engine (discount application/re-sync) and the offer-stats
328
343
  * engine (spend qualification) so both use the exact same exclusion math.
344
+ *
345
+ * A ref matches a whole category (`category_id`) or an item - where "item" means
346
+ * the item id, one of its modifier refs, or one of its option refs.
329
347
  */
330
348
  function calculateEligibleOfferDiscountDetails(categories, excluded_refs) {
331
349
  if (!categories?.length)
@@ -340,7 +358,7 @@ function calculateEligibleOfferDiscountDetails(categories, excluded_refs) {
340
358
  }
341
359
  // Otherwise, check each item
342
360
  for (const item of category.items ?? []) {
343
- if (excluded_refs.includes(item.item_id)) {
361
+ if (doesOrderItemMatchRefs(item, excluded_refs)) {
344
362
  hasExcludedRefs = true;
345
363
  }
346
364
  else {
@@ -97,12 +97,14 @@ function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, })
97
97
  if (excluded_refs != null && excluded_refs.length > 0) {
98
98
  const { subtotal: eligibleSubtotal, hasExcludedRefs } = (0, common_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs);
99
99
  if (hasExcludedRefs) {
100
- if (!is_discount_percentage) {
101
- return { success: false, discountDetails: null, errorMessage: null };
102
- }
103
100
  if (eligibleSubtotal <= 0) {
104
101
  return { success: false, discountDetails: null, errorMessage: null };
105
102
  }
103
+ // Both shapes resolve against the eligible subtotal. A fixed amount used to
104
+ // bail out here while the eligibility engine still reported the offer as
105
+ // claimable, so the claim button always failed with a generic error. Capping
106
+ // is the same contract the gift-card path already uses: a discount may never
107
+ // exceed the amount it is allowed to discount.
106
108
  discount_value = (0, common_1.parseNum)((0, common_1.getCappedOfferDiscountAmount)({
107
109
  baseAmount: eligibleSubtotal,
108
110
  discountValue: discount_value,
@@ -100,15 +100,26 @@ export declare const getTotalSelectedOfferItemsAgainstOffer: (categories: IOrder
100
100
  */
101
101
  export declare function getOfferRewardApplicableQuantity(offer: IOffer): number | null;
102
102
  /**
103
- * Claims of `offer` evidenced by stamped cart items.
103
+ * True when an offer's pathway and reward both draw on the same wallet resource
104
+ * (points to earn points, a voucher to earn a voucher). The admin blocks both
105
+ * cells, so they are only reachable through legacy or externally written rows;
106
+ * the engine refuses them rather than counting the resource twice.
107
+ *
108
+ * Deliberately a function rather than an inline test: it keeps the runtime guard
109
+ * without letting the compiler narrow the offer union (which would mark the
110
+ * remaining reward branches as unreachable).
111
+ */
112
+ export declare function isOfferPathwayAndRewardSharingResource(offer: Partial<IOffer>): boolean;
113
+ /**
114
+ * Claims of `offer` evidenced by the stamped cart items.
104
115
  *
105
116
  * ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
106
117
  * selection is persisted on each item's `item_discount_details`. That entry is
107
118
  * folded into `redeemed_offers` later, by the cart reconcile — which itself runs
108
119
  * only after the cart has already been evaluated. Eligibility that reads ONLY
109
- * `redeemed_offers` therefore misses the claim for exactly one cycle, and
110
- * because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
111
- * points spent by the claim are deducted but never credited back. The offer then
120
+ * `redeemed_offers` misses the claim for exactly one cycle, and because
121
+ * `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the points
122
+ * spent by the claim would be deducted and never credited back. The offer then
112
123
  * reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
113
124
  * reconcile strips the reward item that granted it.
114
125
  *
@@ -12,6 +12,7 @@ exports.calculateCustomerSpendableVoucherCodes = calculateCustomerSpendableVouch
12
12
  exports.calculateCustomerSpendableGiftCardCodes = calculateCustomerSpendableGiftCardCodes;
13
13
  exports.calculateCustomerLoyaltyPoints = calculateCustomerLoyaltyPoints;
14
14
  exports.getOfferRewardApplicableQuantity = getOfferRewardApplicableQuantity;
15
+ exports.isOfferPathwayAndRewardSharingResource = isOfferPathwayAndRewardSharingResource;
15
16
  exports.getOfferItemEvidenceClaims = getOfferItemEvidenceClaims;
16
17
  exports.getRedeemedOffersFromAppliedState = getRedeemedOffersFromAppliedState;
17
18
  exports.getOfferUsageLimitMeta = getOfferUsageLimitMeta;
@@ -250,9 +251,15 @@ function calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categor
250
251
  }
251
252
  let times = 1;
252
253
  if (!redeemedOffer.reward_points.once_per_order) {
254
+ // A spend threshold chunks the reward: one claim per "threshold" of spend.
255
+ // No threshold (`0` / null) means the offer simply has no minimum spend - it
256
+ // must NOT be read as "one claim per currency unit", which would multiply the
257
+ // reward by the cart total.
253
258
  const getUnlockTimesByOrderAmount = (orderValue, totalAmount) => {
254
- const safeRequiredAmount = Math.max(1, totalAmount || 1);
255
- return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
259
+ const requiredAmount = Number(totalAmount);
260
+ if (!Number.isFinite(requiredAmount) || requiredAmount <= 0)
261
+ return 1;
262
+ return Math.max(1, Math.floor(orderValue / requiredAmount));
256
263
  };
257
264
  // This means that we need to see if the condition to unlock the redeemedOffer is met multiple times
258
265
  // i.e. if the customer has ordered 2 pizzas, and the redeemedOffer is applicable for 1 pizza
@@ -273,7 +280,7 @@ function calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categor
273
280
  if (bachelorItems >= num_of_items) {
274
281
  if (totalOrderPrice >= total_amount) {
275
282
  const timesForItems = Math.floor(bachelorItems / (num_of_items || 1));
276
- const timesForAmount = Math.floor(totalOrderPrice / (total_amount || 1));
283
+ const timesForAmount = getUnlockTimesByOrderAmount(totalOrderPrice, total_amount);
277
284
  // we need to find the minimum of the two
278
285
  const minTimes = Math.min(timesForItems, timesForAmount);
279
286
  const maxClaims = max_claims == null ? Infinity : Math.max(1, max_claims);
@@ -841,9 +848,11 @@ function hasEligibleItemsForDiscount(categories, excluded_refs) {
841
848
  if (excluded_refs.includes(category.category_id)) {
842
849
  continue;
843
850
  }
844
- // Check if any item in this category is NOT excluded
851
+ // Item-level only: these lists hold item ids, and an excluded category is
852
+ // skipped above. Modifier/option refs belong to the reward's "Hide Options" /
853
+ // "Discount Not Applicable" lists and never reach this gate.
845
854
  for (const item of category.items ?? []) {
846
- if (!excluded_refs.includes(item.item_id)) {
855
+ if (!(0, common_1.doesOrderItemMatchRefs)(item, excluded_refs)) {
847
856
  return true; // Found at least one eligible item
848
857
  }
849
858
  }
@@ -885,15 +894,31 @@ function getOfferRewardApplicableQuantity(offer) {
885
894
  }
886
895
  // ====================================================================================================================
887
896
  /**
888
- * Claims of `offer` evidenced by stamped cart items.
897
+ * True when an offer's pathway and reward both draw on the same wallet resource
898
+ * (points to earn points, a voucher to earn a voucher). The admin blocks both
899
+ * cells, so they are only reachable through legacy or externally written rows;
900
+ * the engine refuses them rather than counting the resource twice.
901
+ *
902
+ * Deliberately a function rather than an inline test: it keeps the runtime guard
903
+ * without letting the compiler narrow the offer union (which would mark the
904
+ * remaining reward branches as unreachable).
905
+ */
906
+ function isOfferPathwayAndRewardSharingResource(offer) {
907
+ return ((offer.pathway_to_unlock_type === constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS &&
908
+ offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.POINTS) ||
909
+ (offer.pathway_to_unlock_type === constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER &&
910
+ offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.VOUCHER));
911
+ }
912
+ /**
913
+ * Claims of `offer` evidenced by the stamped cart items.
889
914
  *
890
915
  * ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
891
916
  * selection is persisted on each item's `item_discount_details`. That entry is
892
917
  * folded into `redeemed_offers` later, by the cart reconcile — which itself runs
893
918
  * only after the cart has already been evaluated. Eligibility that reads ONLY
894
- * `redeemed_offers` therefore misses the claim for exactly one cycle, and
895
- * because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
896
- * points spent by the claim are deducted but never credited back. The offer then
919
+ * `redeemed_offers` misses the claim for exactly one cycle, and because
920
+ * `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the points
921
+ * spent by the claim would be deducted and never credited back. The offer then
897
922
  * reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
898
923
  * reconcile strips the reward item that granted it.
899
924
  *
@@ -1276,9 +1301,10 @@ function getOfferOrderValueExcludedRefs(offer) {
1276
1301
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
1277
1302
  return offer.reward_discount?.excluded_refs ?? [];
1278
1303
  }
1279
- if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
1280
- return offer.reward_discount_items?.excluded_refs ?? [];
1281
- }
1304
+ // DISCOUNT_ITEMS deliberately does NOT contribute here: its excluded_refs /
1305
+ // exclusive_refs are option-level lists (same as an ITEMS reward) that act on
1306
+ // the modifier tree at selection time. Which items are eligible is decided by
1307
+ // `item_ids`, not by the spend-qualification base.
1282
1308
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK) {
1283
1309
  return offer.reward_cashback?.excluded_refs ?? [];
1284
1310
  }
@@ -1949,9 +1975,14 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1949
1975
  const remainingBudget = getRemainingClaimBudgetForOffer(offerToCheck);
1950
1976
  return remainingBudget == null ? perOrderClaims : Math.min(perOrderClaims, remainingBudget);
1951
1977
  };
1978
+ // Same rule as getUnlockTimesByOrderAmount: a threshold chunks the reward, but
1979
+ // an absent threshold means "no minimum spend" = a single claim, never
1980
+ // `floor(orderValue / 1)` claims.
1952
1981
  const getOrderValueClaimTimes = (orderValue, minAmount) => {
1953
- const safeRequiredAmount = Math.max(1, minAmount || 1);
1954
- return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
1982
+ const requiredAmount = Number(minAmount);
1983
+ if (!Number.isFinite(requiredAmount) || requiredAmount <= 0)
1984
+ return 1;
1985
+ return Math.max(1, Math.floor(orderValue / requiredAmount));
1955
1986
  };
1956
1987
  const getOrdersBetweenUnlocksStats = ({ totalOrders, ordersBetweenUnlocks, }) => {
1957
1988
  const normalizedTotalOrders = Math.max(0, Math.floor(Number.isFinite(totalOrders) ? totalOrders : 0));
@@ -2067,6 +2098,13 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2067
2098
  action_hint: null,
2068
2099
  auto_apply: offer.auto_apply ?? false,
2069
2100
  };
2101
+ if (isOfferPathwayAndRewardSharingResource(offer)) {
2102
+ stats.invalid_offer = true;
2103
+ stats.claimable = false;
2104
+ stats.message = `This offer is misconfigured: its pathway and reward use the same resource`;
2105
+ offersWithStats.push({ offer, stats });
2106
+ continue;
2107
+ }
2070
2108
  if (offer.pathway_to_unlock_type === constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
2071
2109
  if (offer.pathway_to_unlock_type_orders == null) {
2072
2110
  stats.invalid_offer = true;
@@ -2176,16 +2214,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2176
2214
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2177
2215
  if (offer.reward_discount_items == null)
2178
2216
  continue;
2179
- // Check if at least one item is eligible for the discount (not in excluded_refs)
2180
- const excluded_refs = offer.reward_discount_items.excluded_refs ?? [];
2181
- if (excluded_refs.length > 0 && !hasEligibleItemsForDiscount(categories, excluded_refs)) {
2182
- // All items are excluded, offer cannot be unlocked
2183
- stats.progress = 0;
2184
- stats.claimable = false;
2185
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2186
- offersWithStats.push({ offer, stats });
2187
- continue;
2188
- }
2217
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2218
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2219
+ // item_ids, not by an item-level exclusion list.
2189
2220
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2190
2221
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
2191
2222
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -2482,14 +2513,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2482
2513
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2483
2514
  if (offer.reward_discount_items == null)
2484
2515
  continue;
2485
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2486
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2487
- stats.progress = 0;
2488
- stats.claimable = false;
2489
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2490
- offersWithStats.push({ offer, stats });
2491
- continue;
2492
- }
2516
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2517
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2518
+ // item_ids, not by an item-level exclusion list.
2493
2519
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2494
2520
  const redeemedTimes = getItemRewardRedeemedTimes({
2495
2521
  totalOfferItemsSelected,
@@ -2727,14 +2753,10 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2727
2753
  const combinedProgress = Math.min(pointsProgress, amountProgress);
2728
2754
  if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2729
2755
  if (orderValue >= total_amount) {
2730
- if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2731
- stats.progress = 100;
2732
- stats.message = `🎉 You have unlocked this offer 🎉`;
2733
- }
2734
- else {
2735
- stats.progress = combinedProgress;
2736
- stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2737
- }
2756
+ // The points axis is already satisfied by the outer condition; only the
2757
+ // spend axis was in question here.
2758
+ stats.progress = 100;
2759
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2738
2760
  }
2739
2761
  else {
2740
2762
  stats.progress = combinedProgress;
@@ -2746,7 +2768,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2746
2768
  stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2747
2769
  }
2748
2770
  if (stats.progress >= 100) {
2749
- const pointBurnTimes = Math.floor(effectiveLoyaltyPointsForCurrentOffer / (num_of_points || 1));
2771
+ // A reward that costs zero points is free - it must not burn the whole
2772
+ // balance into claims (same rule as a zero spend threshold).
2773
+ const pointBurnTimes = num_of_points > 0 ? Math.floor(effectiveLoyaltyPointsForCurrentOffer / num_of_points) : 1;
2750
2774
  const amountTimes = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : pointBurnTimes;
2751
2775
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(pointBurnTimes, amountTimes, maxClaimsPerOrder));
2752
2776
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
@@ -2781,14 +2805,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2781
2805
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2782
2806
  if (offer.reward_discount_items == null)
2783
2807
  continue;
2784
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2785
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2786
- stats.progress = 0;
2787
- stats.claimable = false;
2788
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2789
- offersWithStats.push({ offer, stats });
2790
- continue;
2791
- }
2808
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2809
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2810
+ // item_ids, not by an item-level exclusion list.
2792
2811
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
2793
2812
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2794
2813
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -3028,6 +3047,14 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3028
3047
  firstReferencedVoucherWithWalletInventory ??
3029
3048
  singleReferencedVoucherForRedeemedClaim ??
3030
3049
  null;
3050
+ // Distinguish "the customer has not entered a code" from "this offer's
3051
+ // voucher cannot be used at all". When the tenant configured voucher ids
3052
+ // but none resolves to a usable voucher (inactive, expired, used up, or
3053
+ // deleted), telling the customer to "enter a matching voucher code" is a
3054
+ // dead end - they may already hold the code.
3055
+ const hasUnavailableReferencedVoucher = referencedVouchers.length === 0 &&
3056
+ voucher_ids.length > 0 &&
3057
+ voucher_ids.every((voucherId) => !vouchersById.has(voucherId));
3031
3058
  const hasMatchingVoucher = matchingVoucherContext != null;
3032
3059
  const normalizedMatchedVoucherCode = matchingVoucherContext != null ? getVoucherCode(matchingVoucherContext) : null;
3033
3060
  const spendableVoucherCount = normalizedMatchedVoucherCode == null ? 0 : (spendableVoucherCodesByCode[normalizedMatchedVoucherCode] ?? 0);
@@ -3035,7 +3062,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3035
3062
  const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
3036
3063
  if (!hasMatchingVoucher) {
3037
3064
  stats.progress = 0;
3038
- stats.message = `Enter a matching voucher code to unlock this offer`;
3065
+ stats.message = hasUnavailableReferencedVoucher
3066
+ ? `⛔️ This offer's voucher is no longer available ⛔️`
3067
+ : `Enter a matching voucher code to unlock this offer`;
3039
3068
  }
3040
3069
  else if (!hasVoucherAccess) {
3041
3070
  stats.progress = 0;
@@ -3086,14 +3115,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3086
3115
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
3087
3116
  if (offer.reward_discount_items == null)
3088
3117
  continue;
3089
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
3090
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
3091
- stats.progress = 0;
3092
- stats.claimable = false;
3093
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
3094
- offersWithStats.push({ offer, stats });
3095
- continue;
3096
- }
3118
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
3119
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
3120
+ // item_ids, not by an item-level exclusion list.
3097
3121
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
3098
3122
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
3099
3123
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -3101,7 +3125,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3101
3125
  applicableQuantity,
3102
3126
  });
3103
3127
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3104
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3128
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3129
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3130
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3105
3131
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3106
3132
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3107
3133
  const isClaimable = redeemedTimes < totalUnlockableClaims;
@@ -3122,7 +3148,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3122
3148
  continue;
3123
3149
  const redeemedTimes = getOfferRedeemedTimes(offer._id);
3124
3150
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3125
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3151
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3152
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3153
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3126
3154
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3127
3155
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3128
3156
  const maxRedeemableClaims = getPointsMaxRedeemableClaims({
@@ -3198,7 +3226,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3198
3226
  // (every total_amount unlocks one claim), capped by max_claims
3199
3227
  // and the voucher inventory available for this order.
3200
3228
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3201
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3229
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3202
3230
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3203
3231
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3204
3232
  const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
@@ -3250,7 +3278,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3250
3278
  applicableQuantity,
3251
3279
  });
3252
3280
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3253
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3281
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3282
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3283
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3254
3284
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3255
3285
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3256
3286
  const isClaimable = redeemedTimes < totalUnlockableClaims;
@@ -60,9 +60,7 @@ function editProps(rewardType, appliedAs) {
60
60
  _id: 'order-item-1',
61
61
  item_type: 'ITEM',
62
62
  quantity: 1,
63
- item_discount_details: appliedAs === 'loyalty'
64
- ? { loyalty_discount_id: 'offer-1' }
65
- : { voucher_discount_id: 'offer-1' },
63
+ item_discount_details: appliedAs === 'loyalty' ? { loyalty_discount_id: 'offer-1' } : { voucher_discount_id: 'offer-1' },
66
64
  },
67
65
  offers: [makeOffer(rewardType)],
68
66
  isLoyaltyDiscountApplied: appliedAs === 'loyalty',
@@ -87,7 +85,12 @@ describe('getEditItemProps ref mapping', () => {
87
85
  expect((0, cart_helpers_1.getEditItemProps)({
88
86
  item: { _id: 'item-1' },
89
87
  orderItemCategoryId: 'category-1',
90
- orderItem: { _id: 'oi-1', item_type: 'ITEM', quantity: 1, item_discount_details: { loyalty_discount_id: 'missing' } },
88
+ orderItem: {
89
+ _id: 'oi-1',
90
+ item_type: 'ITEM',
91
+ quantity: 1,
92
+ item_discount_details: { loyalty_discount_id: 'missing' },
93
+ },
91
94
  offers: [],
92
95
  isLoyaltyDiscountApplied: true,
93
96
  isVoucherDiscountApplied: false,