@managesome/eposmatic-toolkit 0.2.281 → 0.2.283

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.
@@ -330,66 +330,114 @@ function calculateGstForItem({ subtotal, totalOrderDiscount, applyGSTOnOriginalP
330
330
  }
331
331
  return gst_amount;
332
332
  }
333
- function getRedeemedOffersMap(orderDiscountDetails, categories, existingRedeemedOffers) {
334
- const normalizedExistingRedeemedOffers = {};
335
- const derivedRedeemedOffers = {};
336
- const getNormalizedOfferId = (offerId) => {
337
- if (offerId == null)
338
- return null;
339
- const normalizedOfferId = offerId.toString().trim();
340
- return normalizedOfferId.length > 0 ? normalizedOfferId : null;
341
- };
342
- const getSafeCount = (value, fallback = 1) => {
343
- const parsedCount = Number(value);
344
- if (!Number.isFinite(parsedCount) || parsedCount <= 0) {
345
- return fallback;
346
- }
347
- return Math.floor(parsedCount);
348
- };
349
- const incrementOfferCount = (offerId, quantity = 1) => {
333
+ function getNormalizedOfferId(offerId) {
334
+ if (offerId == null)
335
+ return null;
336
+ const normalizedOfferId = offerId.toString().trim();
337
+ return normalizedOfferId.length > 0 ? normalizedOfferId : null;
338
+ }
339
+ function toPositiveInteger(value, fallback = 0) {
340
+ const parsedValue = Number(value);
341
+ if (!Number.isFinite(parsedValue) || parsedValue <= 0) {
342
+ return fallback;
343
+ }
344
+ return Math.floor(parsedValue);
345
+ }
346
+ function getNormalizedRedeemedOffersMap(redeemedOffers) {
347
+ if (redeemedOffers == null)
348
+ return null;
349
+ const normalizedRedeemedOffers = {};
350
+ const offerIds = Object.keys(redeemedOffers);
351
+ for (let i = 0; i < offerIds.length; i++) {
352
+ const offerId = offerIds[i];
350
353
  const normalizedOfferId = getNormalizedOfferId(offerId);
351
354
  if (normalizedOfferId == null)
352
- return;
353
- const safeQuantity = getSafeCount(quantity, 1);
354
- derivedRedeemedOffers[normalizedOfferId] = (derivedRedeemedOffers[normalizedOfferId] ?? 0) + safeQuantity;
355
- };
356
- if (existingRedeemedOffers != null) {
357
- const entries = Object.entries(existingRedeemedOffers);
358
- for (let i = 0; i < entries.length; i++) {
359
- const [offerId, count] = entries[i];
360
- const normalizedOfferId = getNormalizedOfferId(offerId);
361
- if (normalizedOfferId == null)
362
- continue;
363
- normalizedExistingRedeemedOffers[normalizedOfferId] = getSafeCount(count, 0);
355
+ continue;
356
+ const safeCount = toPositiveInteger(redeemedOffers[offerId], 0);
357
+ if (safeCount <= 0)
358
+ continue;
359
+ normalizedRedeemedOffers[normalizedOfferId] = safeCount;
360
+ }
361
+ return Object.keys(normalizedRedeemedOffers).length > 0 ? normalizedRedeemedOffers : null;
362
+ }
363
+ function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
364
+ const normalizedCurrentRedeemedOffers = getNormalizedRedeemedOffersMap(currentRedeemedOffers);
365
+ const normalizedNextRedeemedOffers = getNormalizedRedeemedOffersMap(nextRedeemedOffers);
366
+ if (normalizedCurrentRedeemedOffers == null || normalizedNextRedeemedOffers == null) {
367
+ return normalizedCurrentRedeemedOffers == null && normalizedNextRedeemedOffers == null;
368
+ }
369
+ const currentOfferIds = Object.keys(normalizedCurrentRedeemedOffers);
370
+ const nextOfferIds = Object.keys(normalizedNextRedeemedOffers);
371
+ if (currentOfferIds.length !== nextOfferIds.length) {
372
+ return false;
373
+ }
374
+ for (let i = 0; i < currentOfferIds.length; i++) {
375
+ const offerId = currentOfferIds[i];
376
+ if (normalizedCurrentRedeemedOffers[offerId] !== normalizedNextRedeemedOffers[offerId]) {
377
+ return false;
364
378
  }
365
379
  }
366
- incrementOfferCount(orderDiscountDetails?.loyalty_discount_id, 1);
367
- incrementOfferCount(orderDiscountDetails?.voucher_discount_id, 1);
380
+ return true;
381
+ }
382
+ function getItemRewardApplicableQuantity(offer) {
383
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
384
+ return toPositiveInteger(offer.reward_items?.num_of_items, 1);
385
+ }
386
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
387
+ return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
388
+ }
389
+ return null;
390
+ }
391
+ function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
392
+ let totalSelectedOfferItems = 0;
368
393
  for (let i = 0; i < categories.length; i++) {
369
394
  const category = categories[i];
370
395
  for (let j = 0; j < category.items.length; j++) {
371
396
  const item = category.items[j];
372
- if (item.item_discount_details == null)
397
+ const discountDetails = item.item_discount_details;
398
+ if (discountDetails == null)
399
+ continue;
400
+ const loyaltyDiscountId = getNormalizedOfferId(discountDetails.loyalty_discount_id);
401
+ const voucherDiscountId = getNormalizedOfferId(discountDetails.voucher_discount_id);
402
+ if (loyaltyDiscountId !== offerId && voucherDiscountId !== offerId)
373
403
  continue;
374
- const itemQuantity = Number.isFinite(item.quantity) && item.quantity > 0 ? Math.floor(item.quantity) : 1;
375
- incrementOfferCount(item.item_discount_details.loyalty_discount_id, itemQuantity);
376
- incrementOfferCount(item.item_discount_details.voucher_discount_id, itemQuantity);
404
+ totalSelectedOfferItems += toPositiveInteger(item.quantity, 0);
377
405
  }
378
406
  }
379
- const redeemedOffers = {};
380
- const derivedOfferIds = Object.keys(derivedRedeemedOffers);
381
- for (let i = 0; i < derivedOfferIds.length; i++) {
382
- const offerId = derivedOfferIds[i];
383
- const existingCount = normalizedExistingRedeemedOffers[offerId] ?? 0;
384
- const derivedCount = derivedRedeemedOffers[offerId] ?? 0;
385
- // Keep counts monotonic only for offers that are still derived from the
386
- // current cart snapshot. This prevents stale redeemed badges from
387
- // surviving after an offer is removed from cart/order discount details.
388
- if (derivedCount > 0) {
389
- redeemedOffers[offerId] = Math.max(existingCount, derivedCount);
407
+ return totalSelectedOfferItems;
408
+ }
409
+ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, offers, removedOfferIds, }) {
410
+ const nextRedeemedOffers = {
411
+ ...(getNormalizedRedeemedOffersMap(existingRedeemedOffers) ?? {}),
412
+ };
413
+ const removedIds = Array.from(removedOfferIds);
414
+ for (let i = 0; i < removedIds.length; i++) {
415
+ const normalizedOfferId = getNormalizedOfferId(removedIds[i]);
416
+ if (normalizedOfferId == null)
417
+ continue;
418
+ delete nextRedeemedOffers[normalizedOfferId];
419
+ }
420
+ for (let i = 0; i < offers.length; i++) {
421
+ const offer = offers[i];
422
+ const normalizedOfferId = getNormalizedOfferId(offer._id);
423
+ if (normalizedOfferId == null)
424
+ continue;
425
+ const applicableQuantity = getItemRewardApplicableQuantity(offer);
426
+ if (applicableQuantity == null)
427
+ continue;
428
+ const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, normalizedOfferId);
429
+ const redeemedTimes = Math.floor(selectedItemsCount / applicableQuantity);
430
+ if (redeemedTimes > 0) {
431
+ nextRedeemedOffers[normalizedOfferId] = redeemedTimes;
432
+ }
433
+ else {
434
+ delete nextRedeemedOffers[normalizedOfferId];
390
435
  }
391
436
  }
392
- return Object.keys(redeemedOffers).length > 0 ? redeemedOffers : null;
437
+ return getNormalizedRedeemedOffersMap(nextRedeemedOffers);
438
+ }
439
+ function getRedeemedOffersMap(existingRedeemedOffers) {
440
+ return getNormalizedRedeemedOffersMap(existingRedeemedOffers);
393
441
  }
394
442
  function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calculateItemMetadata) {
395
443
  const isCompleted = data.order_status === constants_1.ORDER_STATUS_ENUM.COMPLETED;
@@ -659,7 +707,7 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
659
707
  ...data,
660
708
  categories,
661
709
  order_discount_details,
662
- redeemed_offers: getRedeemedOffersMap(order_discount_details, categories, data.redeemed_offers),
710
+ redeemed_offers: getRedeemedOffersMap(data.redeemed_offers),
663
711
  total_discount_applied,
664
712
  delivery_details,
665
713
  tax_amount,
@@ -1837,6 +1885,7 @@ function getCartItemsObj({ currentIterationCategories, currentDineinCourses, pre
1837
1885
  function getRemoveOfferFromCartData(data, offer_id, courses, listnerSettings) {
1838
1886
  const categories = data.categories ?? [];
1839
1887
  let order_discount_details = data.order_discount_details;
1888
+ let redeemed_offers = data.redeemed_offers;
1840
1889
  if (order_discount_details != null) {
1841
1890
  // we check if either the loyalty_discount_id or voucher_discount_id
1842
1891
  if (order_discount_details.loyalty_discount_id === offer_id) {
@@ -1858,6 +1907,11 @@ function getRemoveOfferFromCartData(data, offer_id, courses, listnerSettings) {
1858
1907
  };
1859
1908
  }
1860
1909
  }
1910
+ if (redeemed_offers != null && redeemed_offers[offer_id] != null) {
1911
+ const nextRedeemedOffers = { ...redeemed_offers };
1912
+ delete nextRedeemedOffers[offer_id];
1913
+ redeemed_offers = Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null;
1914
+ }
1861
1915
  const newCategories = [];
1862
1916
  for (let i = 0; i < categories.length; i++) {
1863
1917
  const category = categories[i];
@@ -1891,6 +1945,7 @@ function getRemoveOfferFromCartData(data, offer_id, courses, listnerSettings) {
1891
1945
  ...data,
1892
1946
  categories: newCategories,
1893
1947
  order_discount_details,
1948
+ redeemed_offers,
1894
1949
  };
1895
1950
  const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
1896
1951
  return newData;
@@ -1899,6 +1954,7 @@ function getRemoveOfferFromCartData(data, offer_id, courses, listnerSettings) {
1899
1954
  function getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds) {
1900
1955
  const categories = data.categories ?? [];
1901
1956
  let order_discount_details = data.order_discount_details;
1957
+ let redeemed_offers = data.redeemed_offers;
1902
1958
  if (order_discount_details != null) {
1903
1959
  // we check if either the loyalty_discount_id or voucher_discount_id
1904
1960
  if (order_discount_details.loyalty_discount_id != null &&
@@ -1922,6 +1978,18 @@ function getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds
1922
1978
  };
1923
1979
  }
1924
1980
  }
1981
+ if (redeemed_offers != null) {
1982
+ if (offerIds == null) {
1983
+ redeemed_offers = null;
1984
+ }
1985
+ else {
1986
+ const nextRedeemedOffers = { ...redeemed_offers };
1987
+ for (let i = 0; i < offerIds.length; i++) {
1988
+ delete nextRedeemedOffers[offerIds[i]];
1989
+ }
1990
+ redeemed_offers = Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null;
1991
+ }
1992
+ }
1925
1993
  const newCategories = [];
1926
1994
  for (let i = 0; i < categories.length; i++) {
1927
1995
  const category = categories[i];
@@ -1957,6 +2025,7 @@ function getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds
1957
2025
  ...data,
1958
2026
  categories: newCategories,
1959
2027
  order_discount_details,
2028
+ redeemed_offers,
1960
2029
  };
1961
2030
  const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
1962
2031
  return newData;
@@ -1994,14 +2063,23 @@ offers) {
1994
2063
  const unlockedOffersMap = {
1995
2064
  ...unlockedOffersApplicableTimes,
1996
2065
  };
2066
+ const removedOfferIds = new Set();
1997
2067
  let hasChanges = false;
1998
2068
  const categories = data.categories ?? [];
1999
2069
  const orderLevelDiscountBaseAmount = (0, utils_1.getOrderSubtotalFromCategories)(categories);
2000
2070
  let order_discount_details = data.order_discount_details;
2071
+ let redeemed_offers = getNormalizedRedeemedOffersMap(data.redeemed_offers);
2001
2072
  const clearOrderLevelDiscount = (discountType) => {
2002
2073
  if (order_discount_details == null) {
2003
2074
  return;
2004
2075
  }
2076
+ const appliedOfferId = discountType === 'loyalty'
2077
+ ? order_discount_details.loyalty_discount_id
2078
+ : order_discount_details.voucher_discount_id;
2079
+ const normalizedAppliedOfferId = getNormalizedOfferId(appliedOfferId);
2080
+ if (normalizedAppliedOfferId != null) {
2081
+ removedOfferIds.add(normalizedAppliedOfferId);
2082
+ }
2005
2083
  if (discountType === 'loyalty') {
2006
2084
  order_discount_details = {
2007
2085
  ...order_discount_details,
@@ -2151,20 +2229,28 @@ offers) {
2151
2229
  if (loyaltyDiscountId != null) {
2152
2230
  if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
2153
2231
  hasChanges = true;
2232
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
2233
+ if (normalizedLoyaltyDiscountId != null) {
2234
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
2235
+ }
2154
2236
  continue;
2155
2237
  }
2156
2238
  else {
2157
- unlockedOffersMap[loyaltyDiscountId] -= 1;
2239
+ unlockedOffersMap[loyaltyDiscountId] -= toPositiveInteger(item.quantity, 1);
2158
2240
  }
2159
2241
  }
2160
2242
  const voucherDiscountId = item.item_discount_details.voucher_discount_id;
2161
2243
  if (voucherDiscountId != null) {
2162
2244
  if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
2163
2245
  hasChanges = true;
2246
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
2247
+ if (normalizedVoucherDiscountId != null) {
2248
+ removedOfferIds.add(normalizedVoucherDiscountId);
2249
+ }
2164
2250
  continue;
2165
2251
  }
2166
2252
  else {
2167
- unlockedOffersMap[voucherDiscountId] -= 1;
2253
+ unlockedOffersMap[voucherDiscountId] -= toPositiveInteger(item.quantity, 1);
2168
2254
  }
2169
2255
  }
2170
2256
  newItems.push(item);
@@ -2178,11 +2264,22 @@ offers) {
2178
2264
  items: newItems,
2179
2265
  });
2180
2266
  }
2267
+ const reconciledRedeemedOffers = getReconciledRedeemedOffersMap({
2268
+ existingRedeemedOffers: redeemed_offers,
2269
+ categories: newCategories,
2270
+ offers,
2271
+ removedOfferIds,
2272
+ });
2273
+ if (!areRedeemedOffersEqual(redeemed_offers, reconciledRedeemedOffers)) {
2274
+ redeemed_offers = reconciledRedeemedOffers;
2275
+ hasChanges = true;
2276
+ }
2181
2277
  if (hasChanges) {
2182
2278
  const order = {
2183
2279
  ...data,
2184
2280
  categories: newCategories,
2185
2281
  order_discount_details,
2282
+ redeemed_offers,
2186
2283
  };
2187
2284
  const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2188
2285
  return newData;
@@ -27,6 +27,11 @@ export interface IWorker_CustomerUpdateOnSettleOrder {
27
27
  brand_id: string;
28
28
  phoneNumber: string;
29
29
  }
30
+ export interface IWorker_CustomerUpdateOnCancelOrder {
31
+ order: IOrder;
32
+ brand_id: string;
33
+ phoneNumber?: string;
34
+ }
30
35
  export interface IWorker_AddOfferFingerprintsOnSettleOrder {
31
36
  order: IOrder;
32
37
  brand_id: string;
@@ -29,6 +29,7 @@ export interface ICatalogItemOptionsDrawerProps<I extends ISimplifiedCatalogItem
29
29
  defaultOrderItem?: IOrderItem;
30
30
  excludeRefs?: string[];
31
31
  zeroPriceRefs?: string[];
32
+ maxQuantity?: number;
32
33
  applyLoyalty?: IApplyLoyalty;
33
34
  applyVoucher?: IApplyVoucher;
34
35
  onSelect?: (item: IOrderItem) => void;
@@ -61,17 +61,20 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
61
61
  // const rewardItems = offer?.reward_items;
62
62
  let refs = [];
63
63
  let excludeRefs = [];
64
+ let applicable_quantity = 1;
64
65
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
65
66
  if (offer.reward_items == null)
66
67
  return;
67
68
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
68
69
  excludeRefs = offer.reward_items.excluded_refs;
70
+ applicable_quantity = offer.reward_items.num_of_items || 1;
69
71
  }
70
72
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
71
73
  if (offer.reward_discount_items == null)
72
74
  return;
73
75
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
74
76
  excludeRefs = offer.reward_discount_items.excluded_refs;
77
+ applicable_quantity = offer.reward_discount_items.num_of_items || 1;
75
78
  }
76
79
  let discount_details = null;
77
80
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS && offer.reward_discount_items != null) {
@@ -87,6 +90,7 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
87
90
  name: offer.name,
88
91
  refs,
89
92
  discount_details,
93
+ applicable_quantity,
90
94
  };
91
95
  excludeRefs;
92
96
  }
@@ -97,17 +101,20 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
97
101
  // const rewardItems = offer?.reward_items;
98
102
  let refs = [];
99
103
  let excludeRefs = [];
104
+ let applicable_quantity = 1;
100
105
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
101
106
  if (offer.reward_items == null)
102
107
  return;
103
108
  refs = offer.reward_items.exclusive_refs.concat(item._id) ?? [];
104
109
  excludeRefs = offer.reward_items.excluded_refs;
110
+ applicable_quantity = offer.reward_items.num_of_items || 1;
105
111
  }
106
112
  else if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
107
113
  if (offer.reward_discount_items == null)
108
114
  return;
109
115
  refs = offer.reward_discount_items.exclusive_refs.concat(item._id) ?? [];
110
116
  excludeRefs = offer.reward_discount_items.excluded_refs;
117
+ applicable_quantity = offer.reward_discount_items.num_of_items || 1;
111
118
  }
112
119
  let discount_details = null;
113
120
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS && offer.reward_discount_items != null) {
@@ -123,6 +130,7 @@ function getEditItemProps({ item, orderItemCategoryId, orderItem, offers, isLoya
123
130
  name: offer.name,
124
131
  refs,
125
132
  discount_details,
133
+ applicable_quantity,
126
134
  };
127
135
  excludeRefs;
128
136
  }
@@ -4,6 +4,7 @@ export interface IApplyDiscountResult {
4
4
  success: boolean;
5
5
  discountDetails: IDiscountDetails | null;
6
6
  errorMessage: string | null;
7
+ redeemedOfferId?: string | null;
7
8
  }
8
9
  export declare function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, }: {
9
10
  offer: IOffer;
@@ -30,7 +30,7 @@ function getOrderSubtotalFromCategories(categories) {
30
30
  // ================================><================================= //
31
31
  function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, }) {
32
32
  if (offer.reward_discount == null) {
33
- return { success: false, discountDetails: null, errorMessage: null };
33
+ return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
34
34
  }
35
35
  const discountSlot = offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'loyalty' : 'voucher';
36
36
  // Already-applied guard
@@ -40,6 +40,7 @@ function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, })
40
40
  success: false,
41
41
  discountDetails: null,
42
42
  errorMessage: 'You already have an offer applied to your order.',
43
+ redeemedOfferId: null,
43
44
  };
44
45
  }
45
46
  let { discount_value, is_discount_percentage } = offer.reward_discount;
@@ -101,118 +102,58 @@ function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, })
101
102
  }),
102
103
  total_discount: 0,
103
104
  };
104
- return { success: true, discountDetails, errorMessage: null };
105
+ return { success: true, discountDetails, errorMessage: null, redeemedOfferId: null };
105
106
  }
106
107
  // ================================><================================= //
107
108
  // === buildOfferPointsUpdate === //
108
109
  // ================================><================================= //
109
110
  function buildOfferPointsUpdate({ offer, orderDiscountDetails, }) {
110
111
  if (offer.reward_points == null) {
111
- return { success: false, discountDetails: null, errorMessage: null };
112
- }
113
- const discountSlot = offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'loyalty' : 'voucher';
114
- if (orderDiscountDetails != null &&
115
- (discountSlot === 'loyalty' ? orderDiscountDetails.loyalty_discount_id : orderDiscountDetails.voucher_discount_id)) {
116
- return {
117
- success: false,
118
- discountDetails: null,
119
- errorMessage: 'You already have an offer applied to your order.',
120
- };
112
+ return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
121
113
  }
122
- const discountDetails = {
123
- ...orderDiscountDetails,
124
- ...(discountSlot === 'loyalty'
125
- ? {
126
- loyalty_discount_id: offer._id,
127
- loyalty_discount_name: offer.name,
128
- loyalty_discount: 0,
129
- is_loyalty_discount_percentage: false,
130
- }
131
- : {
132
- voucher_discount_id: offer._id,
133
- voucher_discount_name: offer.name,
134
- voucher_discount: 0,
135
- is_voucher_discount_percentage: false,
136
- }),
137
- total_discount: 0,
114
+ const discountDetails = orderDiscountDetails ?? null;
115
+ return {
116
+ success: true,
117
+ discountDetails,
118
+ errorMessage: null,
119
+ redeemedOfferId: offer._id,
138
120
  };
139
- return { success: true, discountDetails, errorMessage: null };
140
121
  }
141
122
  // ================================><================================= //
142
123
  // === buildOfferCashbackUpdate === //
143
124
  // ================================><================================= //
144
125
  function buildOfferCashbackUpdate({ offer, orderDiscountDetails, categories, }) {
145
126
  if (offer.reward_cashback == null) {
146
- return { success: false, discountDetails: null, errorMessage: null };
127
+ return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
147
128
  }
148
129
  // Validate excluded_refs
149
130
  const excluded_refs = offer.reward_cashback.excluded_refs ?? [];
150
131
  if (excluded_refs.length > 0) {
151
132
  const { subtotal: eligibleSubtotal } = (0, cart_actions_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs);
152
133
  if (eligibleSubtotal <= 0) {
153
- return { success: false, discountDetails: null, errorMessage: null };
134
+ return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
154
135
  }
155
136
  }
156
- const discountSlot = offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'loyalty' : 'voucher';
157
- if (orderDiscountDetails != null &&
158
- (discountSlot === 'loyalty' ? orderDiscountDetails.loyalty_discount_id : orderDiscountDetails.voucher_discount_id)) {
159
- return {
160
- success: false,
161
- discountDetails: null,
162
- errorMessage: 'You already have an offer applied to your order.',
163
- };
164
- }
165
- const discountDetails = {
166
- ...orderDiscountDetails,
167
- ...(discountSlot === 'loyalty'
168
- ? {
169
- loyalty_discount_id: offer._id,
170
- loyalty_discount_name: offer.name,
171
- loyalty_discount: 0,
172
- is_loyalty_discount_percentage: false,
173
- }
174
- : {
175
- voucher_discount_id: offer._id,
176
- voucher_discount_name: offer.name,
177
- voucher_discount: 0,
178
- is_voucher_discount_percentage: false,
179
- }),
180
- total_discount: 0,
137
+ const discountDetails = orderDiscountDetails ?? null;
138
+ return {
139
+ success: true,
140
+ discountDetails,
141
+ errorMessage: null,
142
+ redeemedOfferId: offer._id,
181
143
  };
182
- return { success: true, discountDetails, errorMessage: null };
183
144
  }
184
145
  // ================================><================================= //
185
146
  // === buildOfferRewardUpdate === //
186
147
  // === (for GIFT_CARDS and VOUCHER reward types — post-order) === //
187
148
  // ================================><================================= //
188
149
  function buildOfferRewardUpdate({ offer, orderDiscountDetails, }) {
189
- const discountSlot = offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'loyalty' : 'voucher';
190
- if (orderDiscountDetails != null &&
191
- (discountSlot === 'loyalty' ? orderDiscountDetails.loyalty_discount_id : orderDiscountDetails.voucher_discount_id)) {
192
- return {
193
- success: false,
194
- discountDetails: null,
195
- errorMessage: 'You already have an offer applied to your order.',
196
- };
197
- }
198
- const discountDetails = {
199
- ...orderDiscountDetails,
200
- ...(discountSlot === 'loyalty'
201
- ? {
202
- loyalty_discount_id: offer._id,
203
- loyalty_discount_name: offer.name,
204
- loyalty_discount: 0,
205
- is_loyalty_discount_percentage: false,
206
- }
207
- : {
208
- voucher_discount_id: offer._id,
209
- voucher_discount_name: offer.name,
210
- voucher_discount: 0,
211
- is_voucher_discount_percentage: false,
212
- }),
213
- total_discount: 0,
150
+ const discountDetails = orderDiscountDetails ?? null;
151
+ return {
152
+ success: true,
153
+ discountDetails,
154
+ errorMessage: null,
155
+ redeemedOfferId: offer._id,
214
156
  };
215
- return { success: true, discountDetails, errorMessage: null };
216
157
  }
217
158
  // ================================><================================= //
218
159
  // === buildGiftCardDiscountUpdate === //
@@ -625,6 +625,18 @@ function getActionHint(offer, claimable) {
625
625
  return 'Select items for discount';
626
626
  return 'Ready to apply';
627
627
  }
628
+ function getProgressPercentage(currentValue, requiredValue) {
629
+ if (requiredValue <= 0)
630
+ return 100;
631
+ const safeCurrentValue = Number.isFinite(currentValue) ? Math.max(0, currentValue) : 0;
632
+ const safeRequiredValue = Number.isFinite(requiredValue) ? requiredValue : 0;
633
+ if (safeRequiredValue <= 0)
634
+ return 100;
635
+ return Math.max(0, Math.min(100, Math.round((safeCurrentValue / safeRequiredValue) * 100)));
636
+ }
637
+ function getPreUnlockProgressPercentage(currentValue, requiredValue) {
638
+ return Math.min(99, getProgressPercentage(currentValue, requiredValue));
639
+ }
628
640
  function getUnlockedOffersApplicableTimesHashKey(map) {
629
641
  const keys = Object.keys(map).sort();
630
642
  if (keys.length === 0)
@@ -731,11 +743,11 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
731
743
  }
732
744
  return 0;
733
745
  };
734
- const getItemRewardRedeemedTimes = ({ offerId, totalOfferItemsSelected, applicableQuantity, }) => {
735
- const selectedRewardTimes = Math.floor(totalOfferItemsSelected / applicableQuantity);
736
- const mappedRedeemedTimes = getOfferRedeemedTimes(offerId);
737
- // Keep item-based reward redemption in sync with the canonical redeemed_offers map.
738
- return Math.max(selectedRewardTimes, mappedRedeemedTimes);
746
+ const getItemRewardRedeemedTimes = ({ totalOfferItemsSelected, applicableQuantity, }) => {
747
+ const safeApplicableQuantity = Math.max(1, applicableQuantity || 1);
748
+ // Item reward claimability should follow the current cart snapshot so
749
+ // removing a claimed reward item re-opens one claim slot.
750
+ return Math.floor(totalOfferItemsSelected / safeApplicableQuantity);
739
751
  };
740
752
  const getOrdersScopedStats = ({ scope, currentOrderValue, }) => {
741
753
  if (scope === constants_1.PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.OVERALL) {
@@ -836,6 +848,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
836
848
  continue;
837
849
  }
838
850
  const { totalOrders, totalAmount } = scopedStats;
851
+ const ordersProgress = getPreUnlockProgressPercentage(totalOrders, min_num_of_orders || 1);
852
+ const amountProgress = getPreUnlockProgressPercentage(totalAmount, total_amount || 1);
853
+ const combinedProgress = Math.min(ordersProgress, amountProgress);
839
854
  if (totalOrders >= min_num_of_orders) {
840
855
  // Either the max_num_of_orders is infinity, or the customer has not reached the max_num_of_orders
841
856
  if ((max_num_of_orders == null || totalOrders <= max_num_of_orders) &&
@@ -849,8 +864,8 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
849
864
  else {
850
865
  // This means that the customer has not spent enough to unlock the offer
851
866
  // But they have enough orders to unlock the offer
852
- stats.progress = 90;
853
- stats.message = `You are almost there. Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - totalAmount)} more to unlock this offer 🔓`;
867
+ stats.progress = combinedProgress;
868
+ stats.message = `Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - totalAmount)} more to unlock this offer 🔓`;
854
869
  }
855
870
  }
856
871
  else {
@@ -860,7 +875,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
860
875
  }
861
876
  }
862
877
  else {
863
- stats.progress = Math.round((totalOrders / (min_num_of_orders || 1)) * 100);
878
+ stats.progress = combinedProgress;
864
879
  stats.message = `You are ${min_num_of_orders - totalOrders} orders away from unlocking this offer`;
865
880
  }
866
881
  if (stats.progress >= 100) {
@@ -907,7 +922,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
907
922
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
908
923
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
909
924
  const redeemedTimes = getItemRewardRedeemedTimes({
910
- offerId: offer._id,
911
925
  totalOfferItemsSelected,
912
926
  applicableQuantity,
913
927
  });
@@ -1046,7 +1060,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1046
1060
  const applicableQuantity = offer.reward_items.num_of_items || 1;
1047
1061
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
1048
1062
  const redeemedTimes = getItemRewardRedeemedTimes({
1049
- offerId: offer._id,
1050
1063
  totalOfferItemsSelected,
1051
1064
  applicableQuantity,
1052
1065
  });
@@ -1095,6 +1108,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1095
1108
  const unlockTimesForItems = Math.floor(totalItemsSelected / (num_of_items || 1));
1096
1109
  const unlockTimesForAmount = Math.floor(orderValue / (total_amount || 1));
1097
1110
  const totalUnlockableClaims = Math.min(unlockTimesForItems, unlockTimesForAmount, maxClaimsPerOrder);
1111
+ const itemsProgress = getPreUnlockProgressPercentage(bachelorItems, num_of_items || 1);
1112
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount || 1);
1113
+ const combinedProgress = Math.min(itemsProgress, amountProgress);
1098
1114
  if (totalItemsSelected >= num_of_items) {
1099
1115
  if (orderValue >= total_amount) {
1100
1116
  if (bachelorItems >= num_of_items) {
@@ -1102,17 +1118,17 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1102
1118
  stats.message = `🎉 You have unlocked this offer 🎉`;
1103
1119
  }
1104
1120
  else {
1105
- stats.progress = Math.round((bachelorItems / (num_of_items || 1)) * 100);
1121
+ stats.progress = combinedProgress;
1106
1122
  stats.message = `You are ${num_of_items - bachelorItems} items away from unlocking this offer`;
1107
1123
  }
1108
1124
  }
1109
1125
  else {
1110
- stats.progress = 90;
1111
- stats.message = `You are almost there. Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
1126
+ stats.progress = combinedProgress;
1127
+ stats.message = `Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
1112
1128
  }
1113
1129
  }
1114
1130
  else {
1115
- stats.progress = Math.round((bachelorItems / (num_of_items || 1)) * 100);
1131
+ stats.progress = combinedProgress;
1116
1132
  stats.message = `You are ${num_of_items - bachelorItems} items away from unlocking this offer`;
1117
1133
  }
1118
1134
  if (stats.progress >= 100) {
@@ -1154,7 +1170,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1154
1170
  }
1155
1171
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
1156
1172
  const redeemedTimes = getItemRewardRedeemedTimes({
1157
- offerId: offer._id,
1158
1173
  totalOfferItemsSelected,
1159
1174
  applicableQuantity,
1160
1175
  });
@@ -1284,7 +1299,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1284
1299
  continue;
1285
1300
  const applicableQuantity = offer.reward_items.num_of_items || 1;
1286
1301
  const redeemedTimes = getItemRewardRedeemedTimes({
1287
- offerId: offer._id,
1288
1302
  totalOfferItemsSelected,
1289
1303
  applicableQuantity,
1290
1304
  });
@@ -1330,6 +1344,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1330
1344
  totalLoyaltyPointsOfCustomer = loyaltyPoints;
1331
1345
  totalAddedLoyaltyPoints = addedLoyaltyPoints;
1332
1346
  }
1347
+ const pointsProgress = getPreUnlockProgressPercentage(totalLoyaltyPointsOfCustomer ?? 0, num_of_points || 1);
1348
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount || 1);
1349
+ const combinedProgress = Math.min(pointsProgress, amountProgress);
1333
1350
  if (totalAddedLoyaltyPoints >= num_of_points) {
1334
1351
  if (orderValue >= total_amount) {
1335
1352
  if ((totalLoyaltyPointsOfCustomer ?? 0) >= num_of_points) {
@@ -1337,21 +1354,17 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1337
1354
  stats.message = `🎉 You have unlocked this offer 🎉`;
1338
1355
  }
1339
1356
  else {
1340
- const pointsProgress = Math.floor(((totalLoyaltyPointsOfCustomer ?? 0) / (num_of_points || 1)) * 100);
1341
- // Keep below-threshold progress strictly below 100 to avoid false unlocks.
1342
- stats.progress = Math.max(0, Math.min(99, pointsProgress));
1357
+ stats.progress = combinedProgress;
1343
1358
  stats.message = `You are ${(num_of_points - (totalLoyaltyPointsOfCustomer ?? 0)).toFixed(0)} points away from unlocking this offer`;
1344
1359
  }
1345
1360
  }
1346
1361
  else {
1347
- stats.progress = 90;
1348
- stats.message = `You are almost there. Spend ${currency_symbol}${(0, common_1.parseNum)((0, common_1.parseNum)(total_amount - orderValue))} more in this order to unlock this offer 🔓`;
1362
+ stats.progress = combinedProgress;
1363
+ stats.message = `Spend ${currency_symbol}${(0, common_1.parseNum)((0, common_1.parseNum)(total_amount - orderValue))} more in this order to unlock this offer 🔓`;
1349
1364
  }
1350
1365
  }
1351
1366
  else {
1352
- const pointsProgress = Math.floor(((totalLoyaltyPointsOfCustomer ?? 0) / (num_of_points || 1)) * 100);
1353
- // Keep below-threshold progress strictly below 100 to avoid false unlocks.
1354
- stats.progress = Math.max(0, Math.min(99, pointsProgress));
1367
+ stats.progress = combinedProgress;
1355
1368
  stats.message = `You are ${(num_of_points - (totalLoyaltyPointsOfCustomer ?? 0)).toFixed(0)} points away from unlocking this offer`;
1356
1369
  }
1357
1370
  if (stats.progress >= 100) {
@@ -1397,7 +1410,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1397
1410
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
1398
1411
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
1399
1412
  const redeemedTimes = getItemRewardRedeemedTimes({
1400
- offerId: offer._id,
1401
1413
  totalOfferItemsSelected,
1402
1414
  applicableQuantity,
1403
1415
  });
@@ -1528,7 +1540,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1528
1540
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
1529
1541
  const applicableQuantity = offer.reward_items.num_of_items || 1;
1530
1542
  const redeemedTimes = getItemRewardRedeemedTimes({
1531
- offerId: offer._id,
1532
1543
  totalOfferItemsSelected,
1533
1544
  applicableQuantity,
1534
1545
  });
@@ -1580,6 +1591,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1580
1591
  const voucherUsesPerCustomerExhausted = matchedVoucher?.max_uses_per_customer != null &&
1581
1592
  customerVoucherUsageCount >= matchedVoucher.max_uses_per_customer;
1582
1593
  const hasVoucherAccess = matchedVoucher != null && (matchedVoucher.is_public || customerOwnedVoucherCount > 0);
1594
+ const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount || 1);
1583
1595
  if (!hasMatchingVoucher) {
1584
1596
  stats.progress = 0;
1585
1597
  stats.message = `Apply a matching voucher to unlock this offer`;
@@ -1597,8 +1609,8 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1597
1609
  stats.message = `🎉 You have unlocked this offer 🎉`;
1598
1610
  }
1599
1611
  else {
1600
- stats.progress = 90;
1601
- stats.message = `You are almost there. Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
1612
+ stats.progress = amountProgress;
1613
+ stats.message = `Spend ${currency_symbol}${(0, common_1.parseNum)(total_amount - orderValue)} more in this order to unlock this offer 🔓`;
1602
1614
  }
1603
1615
  if (stats.progress >= 100) {
1604
1616
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT) {
@@ -1640,7 +1652,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1640
1652
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
1641
1653
  const applicableQuantity = offer.reward_discount_items.num_of_items || 1;
1642
1654
  const redeemedTimes = getItemRewardRedeemedTimes({
1643
- offerId: offer._id,
1644
1655
  totalOfferItemsSelected,
1645
1656
  applicableQuantity,
1646
1657
  });
@@ -1772,7 +1783,6 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1772
1783
  const totalOfferItemsSelected = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
1773
1784
  const applicableQuantity = offer.reward_items.num_of_items || 1;
1774
1785
  const redeemedTimes = getItemRewardRedeemedTimes({
1775
- offerId: offer._id,
1776
1786
  totalOfferItemsSelected,
1777
1787
  applicableQuantity,
1778
1788
  });
@@ -17,12 +17,14 @@ export interface IApplyLoyalty {
17
17
  name: string;
18
18
  refs: string[];
19
19
  discount_details: TDiscountDetailsParams;
20
+ applicable_quantity?: number;
20
21
  }
21
22
  export interface IApplyVoucher {
22
23
  voucher_id: string;
23
24
  name: string;
24
25
  refs: string[];
25
26
  discount_details: TDiscountDetailsParams;
27
+ applicable_quantity?: number;
26
28
  }
27
29
  interface IConvertCatalogItemToOrderEngineItemParams {
28
30
  item: IItem;
@@ -230,6 +230,8 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
230
230
  if (excludeRefs != null && excludeRefs.includes(modifier.ref))
231
231
  continue;
232
232
  const orderItemModifier = orderItemModifiers?.find((orderModifier) => orderModifier._id === modifier._id);
233
+ const hasOrderItemSelectedOptions = orderItemModifier != null && orderItemModifier.options.length > 0;
234
+ const maxDefaultSelections = modifier.max_aggregate_options_quantity ?? modifier.max_num_options ?? modifier.options.length;
233
235
  const orderEngineSingleModifier = {
234
236
  ...modifier,
235
237
  depth,
@@ -249,11 +251,12 @@ function convertCatalogItemModifierToOrderEngineItemModifier({ modifiers, orderI
249
251
  const isSoldout = option.sold_out.includes(tenantId) || soldoutModifiers?.includes(option.ref);
250
252
  let isDefaultOption = false;
251
253
  if (!isSoldout && option.active) {
252
- if (_id != null) {
253
- isDefaultOption = true;
254
+ // In edit flow, use persisted selections as the source of truth.
255
+ if (hasOrderItemSelectedOptions) {
256
+ isDefaultOption = _id != null;
254
257
  }
255
258
  else {
256
- isDefaultOption = Boolean(option.default) && totalDefaultOptions < (modifier.max_num_options ?? 0);
259
+ isDefaultOption = Boolean(option.default) && totalDefaultOptions < maxDefaultSelections;
257
260
  }
258
261
  }
259
262
  if (isDefaultOption) {
@@ -432,12 +435,14 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
432
435
  discount_value: 100,
433
436
  is_discount_percentage: true,
434
437
  };
438
+ const loyaltyDiscountReason = applyLoyalty.name?.trim() || undefined;
435
439
  mergedItemDiscountDetails = {
436
440
  ...(mergedItemDiscountDetails ?? { total_discount: 0 }),
437
441
  loyalty_discount_id: applyLoyalty.loyalty_id,
438
442
  loyalty_discount_name: applyLoyalty.name,
439
443
  loyalty_discount: loyaltyDiscountDetails.discount_value,
440
444
  is_loyalty_discount_percentage: loyaltyDiscountDetails.is_discount_percentage,
445
+ loyalty_discount_reason: loyaltyDiscountReason,
441
446
  };
442
447
  }
443
448
  if (voucherApplied && applyVoucher != null) {
@@ -445,12 +450,14 @@ function convertCatalogItemToOrderEngineItem({ item, orderItem, platform, tenant
445
450
  discount_value: 100,
446
451
  is_discount_percentage: true,
447
452
  };
453
+ const voucherDiscountReason = applyVoucher.name?.trim() || undefined;
448
454
  mergedItemDiscountDetails = {
449
455
  ...(mergedItemDiscountDetails ?? { total_discount: 0 }),
450
456
  voucher_discount_id: applyVoucher.voucher_id,
451
457
  voucher_discount_name: applyVoucher.name,
452
458
  voucher_discount: voucherDiscountDetails.discount_value,
453
459
  is_voucher_discount_percentage: voucherDiscountDetails.is_discount_percentage,
460
+ voucher_discount_reason: voucherDiscountReason,
454
461
  };
455
462
  }
456
463
  const orderEngineItem = syncOrderEngineItem({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.2.281",
3
+ "version": "0.2.283",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",