@managesome/eposmatic-toolkit 0.3.4 → 0.3.7

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.
@@ -225,8 +225,18 @@ interface IGetOffersWithStats {
225
225
  * inflating eligibility thresholds (e.g. ORDER_FROM max_num_of_orders).
226
226
  */
227
227
  isEdit?: boolean;
228
+ /**
229
+ * The edited order's `redeemed_offers` EXACTLY as loaded from the server
230
+ * (frozen snapshot taken when the edit session started). Together with
231
+ * `isEdit`, it keeps the edited order's own settled claims from counting
232
+ * against per-customer limits (`max_uses_per_customer`): the USED
233
+ * redemption fingerprints still include this order until its update
234
+ * settles, so the raw count must not mark the offer exhausted for the
235
+ * order that consumed it. Omit for new orders / flows without an edit.
236
+ */
237
+ editedOrderRedeemedOffers?: IOrder['redeemed_offers'] | null | undefined;
228
238
  }
229
- export declare function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, isEdit, }: IGetOffersWithStats): {
239
+ export declare function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, isEdit, editedOrderRedeemedOffers, }: IGetOffersWithStats): {
230
240
  offersWithStats: IOfferWithStats[];
231
241
  totalClaimableOffers: string[];
232
242
  unlockedOffersApplicableTimes: Record<string, number>;
@@ -1571,7 +1571,7 @@ function getOffersWithStatsHashKey({ offersWithStats, totalClaimableOffers, isEd
1571
1571
  }
1572
1572
  return result;
1573
1573
  }
1574
- function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, isEdit, }) {
1574
+ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, isEdit, editedOrderRedeemedOffers, }) {
1575
1575
  const offersWithStats = [];
1576
1576
  const { baseAmount: orderLevelDiscountBaseAmount, itemsCount } = getOrderLevelDiscountBaseAmountForOfferStats({
1577
1577
  categories,
@@ -1625,6 +1625,31 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1625
1625
  orderDiscountDetails: order_discount_details,
1626
1626
  });
1627
1627
  const redeemedOffersById = redeemed_offers ?? null;
1628
+ // Frozen baseline of the edited order's own claims (captured when the edit
1629
+ // session started). Normalized once here so the per-offer evaluation below
1630
+ // can subtract them from the customer's lifetime USED counters without the
1631
+ // edited order counting itself out of `max_uses_per_customer`.
1632
+ const editedOrderBaselineClaims = new Map();
1633
+ if (isEdit && editedOrderRedeemedOffers != null) {
1634
+ const baselineOfferIds = Object.keys(editedOrderRedeemedOffers);
1635
+ for (let i = 0; i < baselineOfferIds.length; i++) {
1636
+ const baselineOfferId = baselineOfferIds[i];
1637
+ const normalizedBaselineOfferId = normalizeOfferId(baselineOfferId);
1638
+ const rawBaselineCount = Number(editedOrderRedeemedOffers[baselineOfferId]);
1639
+ if (normalizedBaselineOfferId == null || !Number.isFinite(rawBaselineCount) || rawBaselineCount <= 0) {
1640
+ continue;
1641
+ }
1642
+ editedOrderBaselineClaims.set(normalizedBaselineOfferId, Math.floor(rawBaselineCount));
1643
+ }
1644
+ }
1645
+ const getBaselineRedeemedClaimsForOffer = (offerId) => {
1646
+ const normalizedOfferId = normalizeOfferId(offerId);
1647
+ if (normalizedOfferId == null)
1648
+ return 0;
1649
+ return editedOrderBaselineClaims.get(normalizedOfferId) ?? 0;
1650
+ };
1651
+ const getEffectiveUsedRedemptionCount = (offerId) => Math.max(0, getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, offerId) -
1652
+ getBaselineRedeemedClaimsForOffer(offerId));
1628
1653
  const vouchersById = new Map();
1629
1654
  const allVouchersById = new Map();
1630
1655
  if (vouchers != null) {
@@ -1794,9 +1819,37 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1794
1819
  const maxUsesPerCustomer = getOfferMaxUsesPerCustomer(offerToCheck);
1795
1820
  if (maxUsesPerCustomer == null)
1796
1821
  return false;
1797
- if (customerOfferRedemptionCounts == null)
1798
- return true;
1799
- return getCustomerUsedRedemptionCount(customerOfferRedemptionCounts, offerToCheck._id) >= maxUsesPerCustomer;
1822
+ const baselineRedeemedClaims = getBaselineRedeemedClaimsForOffer(offerToCheck._id);
1823
+ // Unknown counts must never destroy claims the edited order verifiably
1824
+ // carried at load; for everything else keep the conservative
1825
+ // "counts unknown = exhausted" behavior so new claims stay blocked.
1826
+ if (customerOfferRedemptionCounts == null) {
1827
+ return baselineRedeemedClaims <= 0;
1828
+ }
1829
+ return getEffectiveUsedRedemptionCount(offerToCheck._id) >= maxUsesPerCustomer;
1830
+ };
1831
+ // Remaining lifetime budget for this offer expressed in CLAIMS:
1832
+ // max_uses_per_customer minus the customer's effective (baseline-adjusted)
1833
+ // settled usage. Null when the offer has no per-customer limit.
1834
+ const getRemainingClaimBudgetForOffer = (offerToCheck) => {
1835
+ const maxUsesPerCustomer = getOfferMaxUsesPerCustomer(offerToCheck);
1836
+ if (maxUsesPerCustomer == null)
1837
+ return null;
1838
+ // Unknown counts must not grant new claims: preserve only when the
1839
+ // edited order verifiably carried claims (mirrors
1840
+ // isOfferUsesPerCustomerExhausted). With a baseline the full limit stays
1841
+ // available because the customer's true used count is unknown.
1842
+ if (customerOfferRedemptionCounts == null) {
1843
+ return getBaselineRedeemedClaimsForOffer(offerToCheck._id) > 0 ? maxUsesPerCustomer : 0;
1844
+ }
1845
+ return Math.max(0, maxUsesPerCustomer - getEffectiveUsedRedemptionCount(offerToCheck._id));
1846
+ };
1847
+ // Per-order claim counts (value chunks / max_claims) must never exceed the
1848
+ // customer's remaining budget, otherwise a multi-claim reward could be
1849
+ // claimed more times in one order than max_uses_per_customer allows.
1850
+ const clampClaimsToRemainingClaimBudget = (offerToCheck, perOrderClaims) => {
1851
+ const remainingBudget = getRemainingClaimBudgetForOffer(offerToCheck);
1852
+ return remainingBudget == null ? perOrderClaims : Math.min(perOrderClaims, remainingBudget);
1800
1853
  };
1801
1854
  const getOrderValueClaimTimes = (orderValue, minAmount) => {
1802
1855
  const safeRequiredAmount = Math.max(1, minAmount || 1);
@@ -1833,10 +1886,10 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1833
1886
  if (normalizedUnlockableClaims === 0) {
1834
1887
  return 0;
1835
1888
  }
1836
- // max_uses_per_customer is a lifetime gate checked separately against
1837
- // the customer's settled-claim history (wallet USED counter,
1838
- // isOfferUsesPerCustomerExhausted); it must not shrink the per-order
1839
- // claim count — max_claims governs the ongoing session only.
1889
+ // The incoming claim count is already clamped to the customer's
1890
+ // remaining lifetime budget (max_uses_per_customer − effectiveUsed, via
1891
+ // clampClaimsToRemainingClaimBudget at the call site); the reward's own
1892
+ // max_claims governs the ongoing session only.
1840
1893
  return normalizedUnlockableClaims;
1841
1894
  };
1842
1895
  const getPathwayMaxRedeemableClaims = (pathwayUnlockableClaims) => {
@@ -1844,8 +1897,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1844
1897
  if (normalizedUnlockableClaims === 0) {
1845
1898
  return 0;
1846
1899
  }
1847
- // Same lifetime-vs-session separation as getPointsMaxRedeemableClaims:
1848
- // max_uses_per_customer only gates on settled-claim history.
1900
+ // Same as getPointsMaxRedeemableClaims: the incoming claim count is
1901
+ // already clamped to the customer's remaining lifetime budget at the
1902
+ // call site.
1849
1903
  return normalizedUnlockableClaims;
1850
1904
  };
1851
1905
  const isDiscountSlotOccupiedForOffer = (offerToCheck) => {
@@ -2044,7 +2098,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2044
2098
  ? Infinity
2045
2099
  : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2046
2100
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2047
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder);
2101
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2048
2102
  const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
2049
2103
  const isClaimable = redeemedTimes < totalUnlockableClaims && !discountSlotOccupied;
2050
2104
  stats.redeemed_times = redeemedTimes;
@@ -2073,7 +2127,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2073
2127
  ? Infinity
2074
2128
  : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2075
2129
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2076
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder);
2130
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2077
2131
  const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2078
2132
  offerToCheck: offer,
2079
2133
  pathwayUnlockableClaims: totalUnlockableClaims,
@@ -2152,7 +2206,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2152
2206
  ? Infinity
2153
2207
  : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2154
2208
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2155
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder);
2209
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2156
2210
  const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
2157
2211
  const isClaimable = redeemedTimes < maxRedeemableClaims;
2158
2212
  stats.redeemed_times = redeemedTimes;
@@ -2208,7 +2262,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2208
2262
  ? Infinity
2209
2263
  : Math.max(1, offer.pathway_to_unlock_type_orders.max_claims);
2210
2264
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, offer.pathway_to_unlock_type_orders?.total_amount);
2211
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder);
2265
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder));
2212
2266
  const isClaimable = redeemedTimes < totalUnlockableClaims;
2213
2267
  stats.redeemed_times = redeemedTimes;
2214
2268
  stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
@@ -2273,7 +2327,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2273
2327
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2274
2328
  const unlockTimesForItems = Math.floor(totalItemsSelected / (num_of_items || 1));
2275
2329
  const unlockTimesForAmount = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : unlockTimesForItems;
2276
- const totalUnlockableClaims = Math.min(unlockTimesForItems, unlockTimesForAmount, maxClaimsPerOrder);
2330
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForItems, unlockTimesForAmount, maxClaimsPerOrder));
2277
2331
  const itemsProgress = getPreUnlockProgressPercentage(bachelorItems, num_of_items);
2278
2332
  const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
2279
2333
  const combinedProgress = Math.min(itemsProgress, amountProgress);
@@ -2576,7 +2630,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2576
2630
  if (stats.progress >= 100) {
2577
2631
  const pointBurnTimes = Math.floor(effectiveLoyaltyPointsForCurrentOffer / (num_of_points || 1));
2578
2632
  const amountTimes = total_amount != null && total_amount > 0 ? Math.floor(orderValue / total_amount) : pointBurnTimes;
2579
- const totalUnlockableClaims = Math.min(pointBurnTimes, amountTimes, maxClaimsPerOrder);
2633
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(pointBurnTimes, amountTimes, maxClaimsPerOrder));
2580
2634
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
2581
2635
  if (offer.reward_discount == null)
2582
2636
  continue;
@@ -2931,7 +2985,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2931
2985
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2932
2986
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
2933
2987
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
2934
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap);
2988
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
2935
2989
  const isClaimable = redeemedTimes < totalUnlockableClaims;
2936
2990
  stats.redeemed_times = redeemedTimes;
2937
2991
  stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
@@ -2952,7 +3006,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2952
3006
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
2953
3007
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
2954
3008
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
2955
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap);
3009
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
2956
3010
  const maxRedeemableClaims = getPointsMaxRedeemableClaims({
2957
3011
  offerToCheck: offer,
2958
3012
  pathwayUnlockableClaims: totalUnlockableClaims,
@@ -3028,7 +3082,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3028
3082
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3029
3083
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3030
3084
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3031
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap);
3085
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3032
3086
  const maxRedeemableClaims = getPathwayMaxRedeemableClaims(totalUnlockableClaims);
3033
3087
  const isClaimable = redeemedTimes < maxRedeemableClaims;
3034
3088
  stats.redeemed_times = redeemedTimes;
@@ -3080,7 +3134,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
3080
3134
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
3081
3135
  const unlockTimesForAmount = getOrderValueClaimTimes(orderValue, total_amount);
3082
3136
  const voucherInventoryClaimCap = matchingVoucherContext != null ? Math.max(0, spendableVoucherCount + redeemedTimesForOffer) : Infinity;
3083
- const totalUnlockableClaims = Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap);
3137
+ const totalUnlockableClaims = clampClaimsToRemainingClaimBudget(offer, Math.min(unlockTimesForAmount, maxClaimsPerOrder, voucherInventoryClaimCap));
3084
3138
  const isClaimable = redeemedTimes < totalUnlockableClaims;
3085
3139
  stats.redeemed_times = redeemedTimes;
3086
3140
  stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
@@ -1299,7 +1299,7 @@ function setCheckFieldInOrderEngineItem(orderEngineItem, identifier, shouldCheck
1299
1299
  return updatedOrderEngineItem;
1300
1300
  }
1301
1301
  function setIncrementOrderEngineItemQuantity(orderEngineItem, increment, isAbs) {
1302
- const newQuantity = isAbs ? Math.abs(increment) : increment + orderEngineItem.quantity;
1302
+ const newQuantity = isAbs ? Math.abs(increment) || 1 : increment + orderEngineItem.quantity;
1303
1303
  const item_discount_details = (0, store_1.getItemQuantityChangeResults)({
1304
1304
  newQuantity,
1305
1305
  prevQuantity: orderEngineItem.quantity,
@@ -15,6 +15,7 @@ export declare const TenantHrShiftSchema: Schema<any, import("mongoose").Model<a
15
15
  start_time: number;
16
16
  end_time: number;
17
17
  is_active: boolean;
18
+ grace_period_minutes: number;
18
19
  required_positions: import("mongoose").Types.DocumentArray<{
19
20
  count: number;
20
21
  position: string;
@@ -37,6 +38,7 @@ export declare const TenantHrShiftSchema: Schema<any, import("mongoose").Model<a
37
38
  start_time: number;
38
39
  end_time: number;
39
40
  is_active: boolean;
41
+ grace_period_minutes: number;
40
42
  required_positions: import("mongoose").Types.DocumentArray<{
41
43
  count: number;
42
44
  position: string;
@@ -59,6 +61,7 @@ export declare const TenantHrShiftSchema: Schema<any, import("mongoose").Model<a
59
61
  start_time: number;
60
62
  end_time: number;
61
63
  is_active: boolean;
64
+ grace_period_minutes: number;
62
65
  required_positions: import("mongoose").Types.DocumentArray<{
63
66
  count: number;
64
67
  position: string;
@@ -36,6 +36,10 @@ exports.TenantHrShiftSchema = new mongoose_1.Schema({
36
36
  type: Number,
37
37
  required: true,
38
38
  },
39
+ grace_period_minutes: {
40
+ type: Number,
41
+ default: null,
42
+ },
39
43
  required_positions: {
40
44
  type: [hrRequiredPositionSchema],
41
45
  default: [],
@@ -8,6 +8,7 @@ export interface ITenantHrShift {
8
8
  name: string;
9
9
  start_time: number;
10
10
  end_time: number;
11
+ grace_period_minutes?: number | null;
11
12
  required_positions: ITenantHrRequiredPosition[];
12
13
  is_active: boolean;
13
14
  createdAt: Date;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const constants_1 = require("../constants");
4
4
  const cart_actions_1 = require("../helpers/store/cart-actions");
5
5
  const offer_apply_helpers_1 = require("../helpers/utils/offer-apply-helpers");
6
+ const offers_helpers_1 = require("../helpers/utils/offers-helpers");
6
7
  const OFFER_ID = 'offer-reward-threshold';
7
8
  const POST_ORDER_REWARD_TYPES = ['POINTS', 'CASHBACK', 'VOUCHER', 'GIFT_CARDS'];
8
9
  function makeCategories({ itemDiscountDetails = null, quantity = 1, subtotal = 699, itemId = 'cart-item-1', voidReason = undefined, } = {}) {
@@ -110,6 +111,158 @@ describe('offer redeemed_offers sync', () => {
110
111
  expect(result.redeemed_offers?.[OFFER_ID]).toBe(1);
111
112
  });
112
113
  });
114
+ describe('edit-order baseline keeps the applied item reward through the full stats → sync chain', () => {
115
+ const getFlatItems = (categories) => (categories ?? []).flatMap((category) => category.items ?? []);
116
+ const itemDiscountDetails = { loyalty_discount_id: OFFER_ID };
117
+ const makeLimitedItemOffer = () => makeOffer('ITEMS', {
118
+ included_platforms: [constants_1.PLATFORMS_ENUM.WEB_TAKE_AWAY],
119
+ pathway_to_unlock_type_orders: {
120
+ scope: 'OVERALL',
121
+ min_num_of_orders: 0,
122
+ max_num_of_orders: null,
123
+ total_amount: 1000,
124
+ max_amount: null,
125
+ orders_between_unlocks: null,
126
+ max_claims: null,
127
+ max_uses_per_customer: 1,
128
+ },
129
+ });
130
+ const makeEditOrderStats = ({ isEdit, editedOrderRedeemedOffers, }) => (0, offers_helpers_1.getOffersWithStats)({
131
+ offers: [makeLimitedItemOffer()],
132
+ customer: { total_orders: 1, loyalty_points: 0 },
133
+ vouchers: [],
134
+ giftCards: [],
135
+ customerOfferRedemptionCounts: {
136
+ USED: { [OFFER_ID]: 1 },
137
+ ASSIGNED: {},
138
+ },
139
+ redeemed_offers: { [OFFER_ID]: 1 },
140
+ platform: constants_1.PLATFORMS_ENUM.WEB_TAKE_AWAY,
141
+ currency_symbol: constants_1.CURRENCY_SYMBOL_ENUM.$,
142
+ categories: makeCategories({ itemDiscountDetails, subtotal: 2000 }),
143
+ currentItemsPrice: 2000,
144
+ totalDiscountApplied: 0,
145
+ order_discount_details: null,
146
+ isEdit,
147
+ editedOrderRedeemedOffers,
148
+ });
149
+ it('keeps the applied reward item and stamps no void reason when editing the consuming order', () => {
150
+ // The edited order's own claim must not exhaust the customer's limit.
151
+ const stats = makeEditOrderStats({
152
+ isEdit: true,
153
+ editedOrderRedeemedOffers: { [OFFER_ID]: 1 },
154
+ });
155
+ expect(stats.unlockedOffersApplicableTimes[OFFER_ID]).toBe(1);
156
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeOrder({
157
+ categories: makeCategories({ itemDiscountDetails }),
158
+ iterations: [{ categories: makeCategories({ itemDiscountDetails }) }],
159
+ }), [], {}, stats.unlockedOffersApplicableTimes, [makeLimitedItemOffer()]);
160
+ expect(getFlatItems(result.categories)).toHaveLength(1);
161
+ expect(getFlatItems(result.iterations?.[0]?.categories)[0]?.void_reason).toBeUndefined();
162
+ });
163
+ it('removes the item with the auto void reason when the limit is genuinely exhausted (regression guard)', () => {
164
+ const stats = makeEditOrderStats({
165
+ isEdit: false,
166
+ editedOrderRedeemedOffers: null,
167
+ });
168
+ expect(stats.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
169
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeOrder({
170
+ categories: makeCategories({ itemDiscountDetails }),
171
+ iterations: [{ categories: makeCategories({ itemDiscountDetails }) }],
172
+ }), [], {}, stats.unlockedOffersApplicableTimes, [makeLimitedItemOffer()]);
173
+ expect(getFlatItems(result.categories)).toHaveLength(0);
174
+ expect(getFlatItems(result.iterations?.[0]?.categories)[0]?.void_reason).toBe(constants_1.OFFER_NO_LONGER_QUALIFIED_VOID_REASON);
175
+ });
176
+ });
177
+ describe('edit-order baseline keeps an applied order-level discount through the full stats → sync chain', () => {
178
+ const makeOrderLevelDiscountOffer = () => makeOffer('DISCOUNT', {
179
+ included_platforms: [constants_1.PLATFORMS_ENUM.WEB_TAKE_AWAY],
180
+ pathway_to_unlock_type_orders: {
181
+ scope: 'OVERALL',
182
+ min_num_of_orders: 0,
183
+ max_num_of_orders: null,
184
+ total_amount: 1000,
185
+ max_amount: null,
186
+ orders_between_unlocks: null,
187
+ max_claims: null,
188
+ max_uses_per_customer: 1,
189
+ },
190
+ reward_discount: {
191
+ discount_value: 10,
192
+ is_discount_percentage: true,
193
+ max_discount_amount: null,
194
+ max_discount_percentage: null,
195
+ excluded_refs: [],
196
+ },
197
+ });
198
+ const makeEditOrderStats = ({ isEdit, editedOrderRedeemedOffers, }) => (0, offers_helpers_1.getOffersWithStats)({
199
+ offers: [makeOrderLevelDiscountOffer()],
200
+ customer: { total_orders: 1, loyalty_points: 0 },
201
+ vouchers: [],
202
+ giftCards: [],
203
+ customerOfferRedemptionCounts: {
204
+ USED: { [OFFER_ID]: 1 },
205
+ ASSIGNED: {},
206
+ },
207
+ redeemed_offers: { [OFFER_ID]: 1 },
208
+ platform: constants_1.PLATFORMS_ENUM.WEB_TAKE_AWAY,
209
+ currency_symbol: constants_1.CURRENCY_SYMBOL_ENUM.$,
210
+ categories: makeCategories({ subtotal: 2000 }),
211
+ currentItemsPrice: 2000,
212
+ totalDiscountApplied: 0,
213
+ order_discount_details: null,
214
+ isEdit,
215
+ editedOrderRedeemedOffers,
216
+ });
217
+ const makeDiscountOrder = () => makeOrder({
218
+ order_discount_details: {
219
+ loyalty_discount_id: OFFER_ID,
220
+ loyalty_discount_name: 'DISCOUNT threshold reward',
221
+ loyalty_discount: 10,
222
+ is_loyalty_discount_percentage: true,
223
+ total_discount: 10,
224
+ },
225
+ iterations: [{ categories: makeCategories({ subtotal: 2000 }) }],
226
+ });
227
+ it('keeps the applied discount when editing the order that consumed it', () => {
228
+ const stats = makeEditOrderStats({
229
+ isEdit: true,
230
+ editedOrderRedeemedOffers: { [OFFER_ID]: 1 },
231
+ });
232
+ expect(stats.unlockedOffersApplicableTimes[OFFER_ID]).toBe(1);
233
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeDiscountOrder(), [], {}, stats.unlockedOffersApplicableTimes, [
234
+ makeOrderLevelDiscountOffer(),
235
+ ]);
236
+ expect(result.order_discount_details?.loyalty_discount_id).toBe(OFFER_ID);
237
+ });
238
+ it('clears the discount when the limit is genuinely exhausted (regression guard)', () => {
239
+ const stats = makeEditOrderStats({ isEdit: false, editedOrderRedeemedOffers: null });
240
+ expect(stats.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
241
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeDiscountOrder(), [], {}, stats.unlockedOffersApplicableTimes, [
242
+ makeOrderLevelDiscountOffer(),
243
+ ]);
244
+ expect(result.order_discount_details?.loyalty_discount_id).toBeUndefined();
245
+ });
246
+ });
247
+ describe('wallet cashback discount survives the sync while its evidence is present', () => {
248
+ const makeWalletCashbackOrder = (walletRedemptions) => makeOrder({
249
+ order_discount_details: {
250
+ loyalty_discount_id: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID,
251
+ loyalty_discount: 5,
252
+ is_loyalty_discount_percentage: false,
253
+ total_discount: 5,
254
+ },
255
+ wallet_redemptions: walletRedemptions,
256
+ });
257
+ it('keeps the wallet cashback loyalty discount when cashback evidence exists', () => {
258
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeWalletCashbackOrder({ cashback_amount: 5, gift_cards: [] }), [], {}, {}, []);
259
+ expect(result.order_discount_details?.loyalty_discount_id).toBe(constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID);
260
+ });
261
+ it('clears it when the wallet evidence is gone (legacy/empty state)', () => {
262
+ const result = (0, offer_apply_helpers_1.getSyncOffersWithCartData)(makeWalletCashbackOrder(null), [], {}, {}, []);
263
+ expect(result.order_discount_details?.loyalty_discount_id).toBeUndefined();
264
+ });
265
+ });
113
266
  describe('offer sync auto-removed items void reason', () => {
114
267
  const getFlatItems = (categories) => (categories ?? []).flatMap((category) => category.items ?? []);
115
268
  const makeIteration = (categories) => [{ categories }];
@@ -77,9 +77,22 @@ function makeUsedCounts(usedTimes) {
77
77
  [constants_1.CUSTOMER_REDEMPTION_TYPE_ENUM.ASSIGNED]: {},
78
78
  };
79
79
  }
80
+ function makeOrderLevelDiscountOffer(maxUsesPerCustomer = 1) {
81
+ return {
82
+ ...makeFreeBurgerOffer(maxUsesPerCustomer),
83
+ reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT,
84
+ reward_discount: {
85
+ discount_value: 10,
86
+ is_discount_percentage: true,
87
+ max_discount_amount: null,
88
+ max_discount_percentage: null,
89
+ excluded_refs: [],
90
+ },
91
+ };
92
+ }
80
93
  function runStats(options = {}) {
81
94
  return (0, offers_helpers_1.getOffersWithStats)({
82
- offers: [makeFreeBurgerOffer(options.maxUsesPerCustomer ?? 1)],
95
+ offers: [options.offer ?? makeFreeBurgerOffer(options.maxUsesPerCustomer ?? 1)],
83
96
  customer: { total_orders: 1, loyalty_points: 0 },
84
97
  vouchers: [],
85
98
  giftCards: [],
@@ -134,6 +147,25 @@ describe('getOffersWithStats — edited-order redemption baseline', () => {
134
147
  expect(result.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
135
148
  expect(stats.message).toContain('personal limit');
136
149
  });
150
+ it('ignores a provided baseline snapshot when the cart is not an edit (new order)', () => {
151
+ const result = runStats({
152
+ counts: makeUsedCounts(1),
153
+ editedOrderRedeemedOffers: { [OFFER_ID]: 1 },
154
+ });
155
+ const { stats } = result.offersWithStats[0];
156
+ // The baseline only applies to edit sessions — isEdit must be set, so a
157
+ // stray snapshot can never change new-order behavior.
158
+ expect(stats.applicable_quantity).toBe(0);
159
+ expect(result.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
160
+ expect(stats.message).toContain('personal limit');
161
+ });
162
+ it('stays fail-closed for new orders while counts are unknown (pre-change behavior)', () => {
163
+ const result = runStats({ counts: null });
164
+ const { stats } = result.offersWithStats[0];
165
+ expect(stats.applicable_quantity).toBe(0);
166
+ expect(result.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
167
+ expect(stats.message).toContain('personal limit');
168
+ });
137
169
  it('preserves the claim while counts are unknown if the edited order carried it', () => {
138
170
  const result = runStats({
139
171
  counts: null,
@@ -176,6 +208,20 @@ describe('getOffersWithStats — edited-order redemption baseline', () => {
176
208
  expect(result.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
177
209
  expect(stats.message).toContain('personal limit');
178
210
  });
211
+ it('keeps an order-level reward (discount) when editing the order that consumed it', () => {
212
+ const offer = makeOrderLevelDiscountOffer(1);
213
+ const edited = runStats({
214
+ counts: makeUsedCounts(1),
215
+ isEdit: true,
216
+ editedOrderRedeemedOffers: { [OFFER_ID]: 1 },
217
+ offer,
218
+ });
219
+ expect(edited.unlockedOffersApplicableTimes[OFFER_ID]).toBe(1);
220
+ expect(edited.offersWithStats[0].stats.message).not.toContain('personal limit');
221
+ const fresh = runStats({ counts: makeUsedCounts(1), offer });
222
+ expect(fresh.unlockedOffersApplicableTimes[OFFER_ID]).toBe(0);
223
+ expect(fresh.offersWithStats[0].stats.message).toContain('personal limit');
224
+ });
179
225
  });
180
226
  describe('getOffersWithStats — remaining-budget clamp (Q1)', () => {
181
227
  it('caps multi-chunk session claims at the remaining budget (counts known)', () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.3.4",
3
+ "version": "0.3.7",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",