@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.
@@ -987,7 +987,12 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
987
987
  subtotal: orderLevelDiscountBaseAmount,
988
988
  hasExcludedRefs: false,
989
989
  };
990
- if (hasExcludedRefs && !is_discount_percentage) {
990
+ // A fixed discount with exclusions is legitimate: the builder already
991
+ // normalized it against the eligible subtotal. Only clear when there
992
+ // is nothing left to discount - the capping branch below re-derives
993
+ // the amount from the same base. (The voucher copy never had this
994
+ // early clear, which is why the two drifted.)
995
+ if (hasExcludedRefs && !is_discount_percentage && eligibleSubtotal <= 0) {
991
996
  clearOrderLevelDiscount('loyalty');
992
997
  }
993
998
  else {
@@ -1000,10 +1005,7 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
1000
1005
  Number.isFinite(max_discount_amount) &&
1001
1006
  max_discount_amount >= 0;
1002
1007
  const hasFlatMaxPercentage = !is_discount_percentage && hasRelevantPercentageCap;
1003
- if (hasExcludedRefs && !is_discount_percentage && !hasFlatMaxPercentage) {
1004
- clearOrderLevelDiscount('loyalty');
1005
- }
1006
- else if (hasExcludedRefs) {
1008
+ if (hasExcludedRefs) {
1007
1009
  // Excluded items present: must apply percentage against eligible subtotal only.
1008
1010
  const eligibleBase = hasFlatMaxPercentage
1009
1011
  ? parseNum(getNetItemsValueAfterItemDiscount({
@@ -1131,7 +1133,10 @@ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
1131
1133
  Number.isFinite(max_discount_amount) &&
1132
1134
  max_discount_amount >= 0;
1133
1135
  const hasFlatMaxPercentage = !is_discount_percentage && hasRelevantPercentageCap;
1134
- if (hasExcludedRefs && !is_discount_percentage && !hasFlatMaxPercentage) {
1136
+ // Same rule as the loyalty slot: a fixed discount with exclusions is
1137
+ // valid (the builder already normalized it against the eligible
1138
+ // subtotal), so only clear when nothing is left to discount.
1139
+ if (hasExcludedRefs && !is_discount_percentage && eligibleSubtotal <= 0) {
1135
1140
  clearOrderLevelDiscount('voucher');
1136
1141
  }
1137
1142
  else if (hasExcludedRefs) {
@@ -2482,6 +2487,7 @@ export function getUpdateItemInCartData(data, payload, courses, listnerSettings,
2482
2487
  ...data,
2483
2488
  ...(iterations.length > 0 && { iterations }),
2484
2489
  categories,
2490
+ ...getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId: payload._id }),
2485
2491
  };
2486
2492
  const synced = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2487
2493
  if (appliedCustomDiscounts && appliedCustomDiscounts.length > 0) {
@@ -2534,6 +2540,47 @@ export function getUpdateCartInfoData(data, payload, courses, listnerSettings, s
2534
2540
  };
2535
2541
  }
2536
2542
  /* ======================><====================== */
2543
+ /**
2544
+ * Drop the claim for any offer whose last stamped item was just removed.
2545
+ *
2546
+ * An item reward lives both in `redeemed_offers` and on the item's own
2547
+ * `item_discount_details`. The offers sync is parked while an order is edited, so
2548
+ * removing a reward item used to leave its claim behind: the order could still be
2549
+ * settled against a reward that is no longer in it. This reconciles the one case
2550
+ * that needs no offer definition - nothing stamped is left.
2551
+ */
2552
+ function getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId, }) {
2553
+ if (removedItemId == null)
2554
+ return {};
2555
+ const removedOfferIds = [];
2556
+ for (let i = 0; i < (data.categories ?? []).length; i++) {
2557
+ const items = data.categories?.[i].items ?? [];
2558
+ for (let j = 0; j < items.length; j++) {
2559
+ if (items[j]._id !== removedItemId)
2560
+ continue;
2561
+ const discountDetails = items[j].item_discount_details;
2562
+ const offerId = discountDetails?.loyalty_discount_id ?? discountDetails?.voucher_discount_id;
2563
+ if (offerId != null)
2564
+ removedOfferIds.push(offerId);
2565
+ }
2566
+ }
2567
+ if (removedOfferIds.length === 0)
2568
+ return {};
2569
+ const nextRedeemedOffers = { ...(getRedeemedOffersMap(data.redeemed_offers) ?? {}) };
2570
+ for (let i = 0; i < removedOfferIds.length; i++) {
2571
+ const offerId = getNormalizedOfferId(removedOfferIds[i]);
2572
+ if (offerId == null)
2573
+ continue;
2574
+ const stillStamped = (categories ?? []).some((category) => (category.items ?? []).some((item) => {
2575
+ const details = item.item_discount_details;
2576
+ return (getNormalizedOfferId(details?.loyalty_discount_id) === offerId ||
2577
+ getNormalizedOfferId(details?.voucher_discount_id) === offerId);
2578
+ }));
2579
+ if (!stillStamped)
2580
+ delete nextRedeemedOffers[offerId];
2581
+ }
2582
+ return { redeemed_offers: getRedeemedOffersMap(nextRedeemedOffers) };
2583
+ }
2537
2584
  export function getRemoveItemFromCartData(data, payload, courses, listnerSettings, appliedCustomDiscounts) {
2538
2585
  const orderItemIdsMap = {};
2539
2586
  let categories;
@@ -2612,6 +2659,7 @@ export function getRemoveItemFromCartData(data, payload, courses, listnerSetting
2612
2659
  ...data,
2613
2660
  ...(iterations.length > 0 && { iterations }),
2614
2661
  categories,
2662
+ ...getItemRemovalRedeemedOffersPatch({ data, categories, removedItemId: payload._id }),
2615
2663
  };
2616
2664
  const synced = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2617
2665
  if (appliedCustomDiscounts && appliedCustomDiscounts.length > 0) {
@@ -43,7 +43,11 @@ export function getEditItemProps({ item, orderItemCategoryId, orderItem, offers,
43
43
  return;
44
44
  let applyLoyalty;
45
45
  let applyVoucher;
46
- const excludeRefs = undefined;
46
+ // "hide these options" and "this option is not discountable" are two different
47
+ // lists and were previously crossed here: the hide list was never populated and
48
+ // the no-discount slot received the hide list, so editing a reward item hid
49
+ // nothing and price-protected the wrong options.
50
+ let excludeRefs = undefined;
47
51
  let excludedDiscountRefs = undefined;
48
52
  const zeroPriceRefs = undefined;
49
53
  // Step 1: Check if loyalty discount or voucher discount is applied
@@ -53,20 +57,24 @@ export function getEditItemProps({ item, orderItemCategoryId, orderItem, offers,
53
57
  return;
54
58
  // const rewardItems = offer?.reward_items;
55
59
  let refs = [];
60
+ let offerHideRefs = [];
56
61
  let offerExcludedDiscountRefs = [];
57
62
  let applicable_quantity = 1;
58
63
  if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
59
64
  if (offer.reward_items == null)
60
65
  return;
61
66
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
62
- offerExcludedDiscountRefs = offer.reward_items.excluded_refs;
67
+ // excluded_refs hides options; exclusive_refs marks options as not discountable.
68
+ offerHideRefs = offer.reward_items.excluded_refs;
69
+ offerExcludedDiscountRefs = offer.reward_items.exclusive_refs;
63
70
  applicable_quantity = offer.reward_items.num_of_items || 1;
64
71
  }
65
72
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
66
73
  if (offer.reward_discount_items == null)
67
74
  return;
68
75
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
69
- offerExcludedDiscountRefs = offer.reward_discount_items.excluded_refs;
76
+ offerHideRefs = offer.reward_discount_items.excluded_refs;
77
+ offerExcludedDiscountRefs = offer.reward_discount_items.exclusive_refs;
70
78
  applicable_quantity = offer.reward_discount_items.num_of_items || 1;
71
79
  }
72
80
  let discount_details = null;
@@ -85,6 +93,7 @@ export function getEditItemProps({ item, orderItemCategoryId, orderItem, offers,
85
93
  discount_details,
86
94
  applicable_quantity,
87
95
  };
96
+ excludeRefs = offerHideRefs;
88
97
  excludedDiscountRefs = offerExcludedDiscountRefs;
89
98
  }
90
99
  if (isVoucherDiscountApplied) {
@@ -93,20 +102,24 @@ export function getEditItemProps({ item, orderItemCategoryId, orderItem, offers,
93
102
  return;
94
103
  // const rewardItems = offer?.reward_items;
95
104
  let refs = [];
105
+ let offerHideRefs = [];
96
106
  let offerExcludedDiscountRefs = [];
97
107
  let applicable_quantity = 1;
98
108
  if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
99
109
  if (offer.reward_items == null)
100
110
  return;
101
111
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
102
- offerExcludedDiscountRefs = offer.reward_items.excluded_refs;
112
+ // excluded_refs hides options; exclusive_refs marks options as not discountable.
113
+ offerHideRefs = offer.reward_items.excluded_refs;
114
+ offerExcludedDiscountRefs = offer.reward_items.exclusive_refs;
103
115
  applicable_quantity = offer.reward_items.num_of_items || 1;
104
116
  }
105
117
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
106
118
  if (offer.reward_discount_items == null)
107
119
  return;
108
120
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
109
- offerExcludedDiscountRefs = offer.reward_discount_items.excluded_refs;
121
+ offerHideRefs = offer.reward_discount_items.excluded_refs;
122
+ offerExcludedDiscountRefs = offer.reward_discount_items.exclusive_refs;
110
123
  applicable_quantity = offer.reward_discount_items.num_of_items || 1;
111
124
  }
112
125
  let discount_details = null;
@@ -125,6 +138,7 @@ export function getEditItemProps({ item, orderItemCategoryId, orderItem, offers,
125
138
  discount_details,
126
139
  applicable_quantity,
127
140
  };
141
+ excludeRefs = offerHideRefs;
128
142
  excludedDiscountRefs = offerExcludedDiscountRefs;
129
143
  }
130
144
  // TODO: We need to add use case for HalfHalf and Specials
@@ -291,11 +291,28 @@ export function getCappedOfferDiscountAmount({ baseAmount, discountValue, isDisc
291
291
  }
292
292
  return Math.min(amount, normalizedBaseAmount);
293
293
  }
294
+ /**
295
+ * Does this order line match any of the given refs?
296
+ *
297
+ * A ref is an **item-level** id: an item id, and - because a SPECIAL or
298
+ * HALF_HALF order line stores its own document id in `item_id` - a special or
299
+ * half-half id too. Modifier/option refs never appear here: those belong to the
300
+ * reward's "Hide Options" / "Discount Not Applicable" lists, which act on the
301
+ * modifier tree at selection time, not on spend qualification.
302
+ */
303
+ export function doesOrderItemMatchRefs(item, refs) {
304
+ if (refs.length === 0)
305
+ return false;
306
+ return item.item_id != null && refs.includes(item.item_id);
307
+ }
294
308
  /**
295
309
  * Calculate the eligible subtotal by excluding items/categories in excluded_refs.
296
310
  *
297
311
  * Shared by the cart engine (discount application/re-sync) and the offer-stats
298
312
  * engine (spend qualification) so both use the exact same exclusion math.
313
+ *
314
+ * A ref matches a whole category (`category_id`) or an item - where "item" means
315
+ * the item id, one of its modifier refs, or one of its option refs.
299
316
  */
300
317
  export function calculateEligibleOfferDiscountDetails(categories, excluded_refs) {
301
318
  if (!categories?.length)
@@ -310,7 +327,7 @@ export function calculateEligibleOfferDiscountDetails(categories, excluded_refs)
310
327
  }
311
328
  // Otherwise, check each item
312
329
  for (const item of category.items ?? []) {
313
- if (excluded_refs.includes(item.item_id)) {
330
+ if (doesOrderItemMatchRefs(item, excluded_refs)) {
314
331
  hasExcludedRefs = true;
315
332
  }
316
333
  else {
@@ -88,12 +88,14 @@ export function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categori
88
88
  if (excluded_refs != null && excluded_refs.length > 0) {
89
89
  const { subtotal: eligibleSubtotal, hasExcludedRefs } = calculateEligibleOfferDiscountDetails(categories, excluded_refs);
90
90
  if (hasExcludedRefs) {
91
- if (!is_discount_percentage) {
92
- return { success: false, discountDetails: null, errorMessage: null };
93
- }
94
91
  if (eligibleSubtotal <= 0) {
95
92
  return { success: false, discountDetails: null, errorMessage: null };
96
93
  }
94
+ // Both shapes resolve against the eligible subtotal. A fixed amount used to
95
+ // bail out here while the eligibility engine still reported the offer as
96
+ // claimable, so the claim button always failed with a generic error. Capping
97
+ // is the same contract the gift-card path already uses: a discount may never
98
+ // exceed the amount it is allowed to discount.
97
99
  discount_value = parseNum(getCappedOfferDiscountAmount({
98
100
  baseAmount: eligibleSubtotal,
99
101
  discountValue: discount_value,
@@ -1,5 +1,5 @@
1
1
  import { CUSTOMER_REDEMPTION_TYPE_ENUM, OFFER_REWARD_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM, PLATFORMS_BY_ORDER_FROM, WALLET_CASHBACK_LOYALTY_DISCOUNT_ID, } from '../../constants';
2
- import { calculateEligibleOfferDiscountDetails, parseNum } from './common';
2
+ import { calculateEligibleOfferDiscountDetails, doesOrderItemMatchRefs, parseNum } from './common';
3
3
  import { findApplicableSchedule } from './platform-catalog';
4
4
  import { convertSpecialHoursFromCents, convertSpecialHoursToCents } from './platform-num';
5
5
  import { convertPriceFromCents, convertPriceToCents } from './price-conversion';
@@ -214,9 +214,15 @@ function calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categor
214
214
  }
215
215
  let times = 1;
216
216
  if (!redeemedOffer.reward_points.once_per_order) {
217
+ // A spend threshold chunks the reward: one claim per "threshold" of spend.
218
+ // No threshold (`0` / null) means the offer simply has no minimum spend - it
219
+ // must NOT be read as "one claim per currency unit", which would multiply the
220
+ // reward by the cart total.
217
221
  const getUnlockTimesByOrderAmount = (orderValue, totalAmount) => {
218
- const safeRequiredAmount = Math.max(1, totalAmount || 1);
219
- return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
222
+ const requiredAmount = Number(totalAmount);
223
+ if (!Number.isFinite(requiredAmount) || requiredAmount <= 0)
224
+ return 1;
225
+ return Math.max(1, Math.floor(orderValue / requiredAmount));
220
226
  };
221
227
  // This means that we need to see if the condition to unlock the redeemedOffer is met multiple times
222
228
  // i.e. if the customer has ordered 2 pizzas, and the redeemedOffer is applicable for 1 pizza
@@ -237,7 +243,7 @@ function calculatePointsRedeemedForOffer(redeemedOffer, totalOrderPrice, categor
237
243
  if (bachelorItems >= num_of_items) {
238
244
  if (totalOrderPrice >= total_amount) {
239
245
  const timesForItems = Math.floor(bachelorItems / (num_of_items || 1));
240
- const timesForAmount = Math.floor(totalOrderPrice / (total_amount || 1));
246
+ const timesForAmount = getUnlockTimesByOrderAmount(totalOrderPrice, total_amount);
241
247
  // we need to find the minimum of the two
242
248
  const minTimes = Math.min(timesForItems, timesForAmount);
243
249
  const maxClaims = max_claims == null ? Infinity : Math.max(1, max_claims);
@@ -805,9 +811,11 @@ function hasEligibleItemsForDiscount(categories, excluded_refs) {
805
811
  if (excluded_refs.includes(category.category_id)) {
806
812
  continue;
807
813
  }
808
- // Check if any item in this category is NOT excluded
814
+ // Item-level only: these lists hold item ids, and an excluded category is
815
+ // skipped above. Modifier/option refs belong to the reward's "Hide Options" /
816
+ // "Discount Not Applicable" lists and never reach this gate.
809
817
  for (const item of category.items ?? []) {
810
- if (!excluded_refs.includes(item.item_id)) {
818
+ if (!doesOrderItemMatchRefs(item, excluded_refs)) {
811
819
  return true; // Found at least one eligible item
812
820
  }
813
821
  }
@@ -848,15 +856,31 @@ export function getOfferRewardApplicableQuantity(offer) {
848
856
  }
849
857
  // ====================================================================================================================
850
858
  /**
851
- * Claims of `offer` evidenced by stamped cart items.
859
+ * True when an offer's pathway and reward both draw on the same wallet resource
860
+ * (points to earn points, a voucher to earn a voucher). The admin blocks both
861
+ * cells, so they are only reachable through legacy or externally written rows;
862
+ * the engine refuses them rather than counting the resource twice.
863
+ *
864
+ * Deliberately a function rather than an inline test: it keeps the runtime guard
865
+ * without letting the compiler narrow the offer union (which would mark the
866
+ * remaining reward branches as unreachable).
867
+ */
868
+ export function isOfferPathwayAndRewardSharingResource(offer) {
869
+ return ((offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS &&
870
+ offer.reward_type === OFFER_REWARD_TYPE_ENUM.POINTS) ||
871
+ (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER &&
872
+ offer.reward_type === OFFER_REWARD_TYPE_ENUM.VOUCHER));
873
+ }
874
+ /**
875
+ * Claims of `offer` evidenced by the stamped cart items.
852
876
  *
853
877
  * ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
854
878
  * selection is persisted on each item's `item_discount_details`. That entry is
855
879
  * folded into `redeemed_offers` later, by the cart reconcile — which itself runs
856
880
  * only after the cart has already been evaluated. Eligibility that reads ONLY
857
- * `redeemed_offers` therefore misses the claim for exactly one cycle, and
858
- * because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
859
- * points spent by the claim are deducted but never credited back. The offer then
881
+ * `redeemed_offers` misses the claim for exactly one cycle, and because
882
+ * `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the points
883
+ * spent by the claim would be deducted and never credited back. The offer then
860
884
  * reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
861
885
  * reconcile strips the reward item that granted it.
862
886
  *
@@ -1239,9 +1263,10 @@ function getOfferOrderValueExcludedRefs(offer) {
1239
1263
  if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
1240
1264
  return offer.reward_discount?.excluded_refs ?? [];
1241
1265
  }
1242
- if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
1243
- return offer.reward_discount_items?.excluded_refs ?? [];
1244
- }
1266
+ // DISCOUNT_ITEMS deliberately does NOT contribute here: its excluded_refs /
1267
+ // exclusive_refs are option-level lists (same as an ITEMS reward) that act on
1268
+ // the modifier tree at selection time. Which items are eligible is decided by
1269
+ // `item_ids`, not by the spend-qualification base.
1245
1270
  if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.CASHBACK) {
1246
1271
  return offer.reward_cashback?.excluded_refs ?? [];
1247
1272
  }
@@ -1912,9 +1937,14 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
1912
1937
  const remainingBudget = getRemainingClaimBudgetForOffer(offerToCheck);
1913
1938
  return remainingBudget == null ? perOrderClaims : Math.min(perOrderClaims, remainingBudget);
1914
1939
  };
1940
+ // Same rule as getUnlockTimesByOrderAmount: a threshold chunks the reward, but
1941
+ // an absent threshold means "no minimum spend" = a single claim, never
1942
+ // `floor(orderValue / 1)` claims.
1915
1943
  const getOrderValueClaimTimes = (orderValue, minAmount) => {
1916
- const safeRequiredAmount = Math.max(1, minAmount || 1);
1917
- return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
1944
+ const requiredAmount = Number(minAmount);
1945
+ if (!Number.isFinite(requiredAmount) || requiredAmount <= 0)
1946
+ return 1;
1947
+ return Math.max(1, Math.floor(orderValue / requiredAmount));
1918
1948
  };
1919
1949
  const getOrdersBetweenUnlocksStats = ({ totalOrders, ordersBetweenUnlocks, }) => {
1920
1950
  const normalizedTotalOrders = Math.max(0, Math.floor(Number.isFinite(totalOrders) ? totalOrders : 0));
@@ -2030,6 +2060,13 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2030
2060
  action_hint: null,
2031
2061
  auto_apply: offer.auto_apply ?? false,
2032
2062
  };
2063
+ if (isOfferPathwayAndRewardSharingResource(offer)) {
2064
+ stats.invalid_offer = true;
2065
+ stats.claimable = false;
2066
+ stats.message = `This offer is misconfigured: its pathway and reward use the same resource`;
2067
+ offersWithStats.push({ offer, stats });
2068
+ continue;
2069
+ }
2033
2070
  if (offer.pathway_to_unlock_type === PATHWAY_TO_UNLOCK_TYPE_ENUM.ORDERS) {
2034
2071
  if (offer.pathway_to_unlock_type_orders == null) {
2035
2072
  stats.invalid_offer = true;
@@ -2139,16 +2176,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2139
2176
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2140
2177
  if (offer.reward_discount_items == null)
2141
2178
  continue;
2142
- // Check if at least one item is eligible for the discount (not in excluded_refs)
2143
- const excluded_refs = offer.reward_discount_items.excluded_refs ?? [];
2144
- if (excluded_refs.length > 0 && !hasEligibleItemsForDiscount(categories, excluded_refs)) {
2145
- // All items are excluded, offer cannot be unlocked
2146
- stats.progress = 0;
2147
- stats.claimable = false;
2148
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2149
- offersWithStats.push({ offer, stats });
2150
- continue;
2151
- }
2179
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2180
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2181
+ // item_ids, not by an item-level exclusion list.
2152
2182
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2153
2183
  const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2154
2184
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -2445,14 +2475,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2445
2475
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2446
2476
  if (offer.reward_discount_items == null)
2447
2477
  continue;
2448
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2449
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2450
- stats.progress = 0;
2451
- stats.claimable = false;
2452
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2453
- offersWithStats.push({ offer, stats });
2454
- continue;
2455
- }
2478
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2479
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2480
+ // item_ids, not by an item-level exclusion list.
2456
2481
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2457
2482
  const redeemedTimes = getItemRewardRedeemedTimes({
2458
2483
  totalOfferItemsSelected,
@@ -2690,14 +2715,10 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2690
2715
  const combinedProgress = Math.min(pointsProgress, amountProgress);
2691
2716
  if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2692
2717
  if (orderValue >= total_amount) {
2693
- if (effectiveLoyaltyPointsForCurrentOffer >= num_of_points) {
2694
- stats.progress = 100;
2695
- stats.message = `🎉 You have unlocked this offer 🎉`;
2696
- }
2697
- else {
2698
- stats.progress = combinedProgress;
2699
- stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2700
- }
2718
+ // The points axis is already satisfied by the outer condition; only the
2719
+ // spend axis was in question here.
2720
+ stats.progress = 100;
2721
+ stats.message = `🎉 You have unlocked this offer 🎉`;
2701
2722
  }
2702
2723
  else {
2703
2724
  stats.progress = combinedProgress;
@@ -2709,7 +2730,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2709
2730
  stats.message = `You are ${(num_of_points - effectiveLoyaltyPointsForCurrentOffer).toFixed(0)} points away from unlocking this offer`;
2710
2731
  }
2711
2732
  if (stats.progress >= 100) {
2712
- const pointBurnTimes = Math.floor(effectiveLoyaltyPointsForCurrentOffer / (num_of_points || 1));
2733
+ // A reward that costs zero points is free - it must not burn the whole
2734
+ // balance into claims (same rule as a zero spend threshold).
2735
+ const pointBurnTimes = num_of_points > 0 ? Math.floor(effectiveLoyaltyPointsForCurrentOffer / num_of_points) : 1;
2713
2736
  const amountTimes = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : pointBurnTimes;
2714
2737
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(pointBurnTimes, amountTimes, maxClaimsPerOrder));
2715
2738
  if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
@@ -2744,14 +2767,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2744
2767
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
2745
2768
  if (offer.reward_discount_items == null)
2746
2769
  continue;
2747
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
2748
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
2749
- stats.progress = 0;
2750
- stats.claimable = false;
2751
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
2752
- offersWithStats.push({ offer, stats });
2753
- continue;
2754
- }
2770
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
2771
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
2772
+ // item_ids, not by an item-level exclusion list.
2755
2773
  const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
2756
2774
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
2757
2775
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -2991,6 +3009,14 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2991
3009
  firstReferencedVoucherWithWalletInventory ??
2992
3010
  singleReferencedVoucherForRedeemedClaim ??
2993
3011
  null;
3012
+ // Distinguish "the customer has not entered a code" from "this offer's
3013
+ // voucher cannot be used at all". When the tenant configured voucher ids
3014
+ // but none resolves to a usable voucher (inactive, expired, used up, or
3015
+ // deleted), telling the customer to "enter a matching voucher code" is a
3016
+ // dead end - they may already hold the code.
3017
+ const hasUnavailableReferencedVoucher = referencedVouchers.length === 0 &&
3018
+ voucher_ids.length > 0 &&
3019
+ voucher_ids.every((voucherId) => !vouchersById.has(voucherId));
2994
3020
  const hasMatchingVoucher = matchingVoucherContext != null;
2995
3021
  const normalizedMatchedVoucherCode = matchingVoucherContext != null ? getVoucherCode(matchingVoucherContext) : null;
2996
3022
  const spendableVoucherCount = normalizedMatchedVoucherCode == null ? 0 : (spendableVoucherCodesByCode[normalizedMatchedVoucherCode] ?? 0);
@@ -2998,7 +3024,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
2998
3024
  const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
2999
3025
  if (!hasMatchingVoucher) {
3000
3026
  stats.progress = 0;
3001
- stats.message = `Enter a matching voucher code to unlock this offer`;
3027
+ stats.message = hasUnavailableReferencedVoucher
3028
+ ? `⛔️ This offer's voucher is no longer available ⛔️`
3029
+ : `Enter a matching voucher code to unlock this offer`;
3002
3030
  }
3003
3031
  else if (!hasVoucherAccess) {
3004
3032
  stats.progress = 0;
@@ -3049,14 +3077,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
3049
3077
  else if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
3050
3078
  if (offer.reward_discount_items == null)
3051
3079
  continue;
3052
- const rewardExcludedRefs = offer.reward_discount_items.excluded_refs ?? [];
3053
- if (rewardExcludedRefs.length > 0 && !hasEligibleItemsForDiscount(categories, rewardExcludedRefs)) {
3054
- stats.progress = 0;
3055
- stats.claimable = false;
3056
- stats.message = `⛔️ No eligible items for this offer ⛔️`;
3057
- offersWithStats.push({ offer, stats });
3058
- continue;
3059
- }
3080
+ // No "all items excluded" gate here: DISCOUNT_ITEMS acts on the modifier
3081
+ // tree (excluded_refs / exclusive_refs), and item eligibility is driven by
3082
+ // item_ids, not by an item-level exclusion list.
3060
3083
  const totalOfferItemsSelected = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
3061
3084
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
3062
3085
  const redeemedTimes = getItemRewardRedeemedTimes({
@@ -3064,7 +3087,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
3064
3087
  applicableQuantity,
3065
3088
  });
3066
3089
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3067
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3090
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3091
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3092
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3068
3093
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3069
3094
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3070
3095
  const isClaimable = redeemedTimes < totalUnlockableClaims;
@@ -3085,7 +3110,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
3085
3110
  continue;
3086
3111
  const redeemedTimes = getOfferRedeemedTimes(offer._id);
3087
3112
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3088
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3113
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3114
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3115
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3089
3116
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3090
3117
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3091
3118
  const maxRedeemableClaims = getPointsMaxRedeemableClaims({
@@ -3161,7 +3188,7 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
3161
3188
  // (every total_amount unlocks one claim), capped by max_claims
3162
3189
  // and the voucher inventory available for this order.
3163
3190
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3164
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3191
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3165
3192
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3166
3193
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3167
3194
  const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
@@ -3213,7 +3240,9 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
3213
3240
  applicableQuantity,
3214
3241
  });
3215
3242
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3216
- const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3243
+ // No spend threshold on a voucher pathway means "no minimum spend", so the
3244
+ // vouchers held - not a spend chunk count - decide how many claims fit.
3245
+ const unlockTimesForAmount = total_amount > 0 ? getOrderValueClaimTimes(orderValue, total_amount) : Infinity;
3217
3246
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3218
3247
  const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3219
3248
  const isClaimable = redeemedTimes < totalUnlockableClaims;