@managesome/eposmatic-toolkit 0.2.312 → 0.2.314

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.
@@ -1,16 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getOrderSubtotalFromCategories = getOrderSubtotalFromCategories;
4
3
  exports.buildOfferDiscountUpdate = buildOfferDiscountUpdate;
5
4
  exports.buildOfferPointsUpdate = buildOfferPointsUpdate;
6
5
  exports.buildOfferCashbackUpdate = buildOfferCashbackUpdate;
7
6
  exports.buildOfferRewardUpdate = buildOfferRewardUpdate;
8
7
  exports.buildGiftCardDiscountUpdate = buildGiftCardDiscountUpdate;
9
8
  exports.buildVoucherDiscountUpdate = buildVoucherDiscountUpdate;
9
+ exports.getSyncOffersWithCartData = getSyncOffersWithCartData;
10
10
  const constants_1 = require("../../constants");
11
- const common_1 = require("./common");
12
11
  const cart_actions_1 = require("../store/cart-actions");
13
- // ================================><================================= //
12
+ const common_1 = require("./common");
13
+ // =================><================================= //
14
14
  // === Shared order subtotal for discount logic === //
15
15
  // ================================><================================= //
16
16
  function getOrderSubtotalFromCategories(categories) {
@@ -25,12 +25,57 @@ function getOrderSubtotalFromCategories(categories) {
25
25
  }
26
26
  return subtotal;
27
27
  }
28
+ const WALLET_CASHBACK_SPECIAL_DISCOUNT_ID = 'wallet_cashback_redemption';
29
+ function isWalletCashbackSpecialDiscount(orderDiscountDetails) {
30
+ return orderDiscountDetails?.special_discount_id === WALLET_CASHBACK_SPECIAL_DISCOUNT_ID;
31
+ }
32
+ function getWalletCashbackAmountFromOrderData({ orderDiscountDetails, walletRedemptions, }) {
33
+ if (!isWalletCashbackSpecialDiscount(orderDiscountDetails)) {
34
+ return 0;
35
+ }
36
+ const specialDiscountAmount = Number(orderDiscountDetails?.special_discount ?? 0);
37
+ if (Number.isFinite(specialDiscountAmount) && specialDiscountAmount > 0) {
38
+ return (0, common_1.parseNum)(specialDiscountAmount);
39
+ }
40
+ const walletCashbackAmount = Number(walletRedemptions?.cashback_amount ?? 0);
41
+ if (Number.isFinite(walletCashbackAmount) && walletCashbackAmount > 0) {
42
+ return (0, common_1.parseNum)(walletCashbackAmount);
43
+ }
44
+ return 0;
45
+ }
46
+ function getSyncedWalletCashbackOrderDiscountDetails({ orderDiscountDetails, walletCashbackAmount, }) {
47
+ if (orderDiscountDetails == null) {
48
+ return orderDiscountDetails;
49
+ }
50
+ if (walletCashbackAmount <= 0) {
51
+ return {
52
+ ...orderDiscountDetails,
53
+ special_discount_id: undefined,
54
+ special_discount_name: undefined,
55
+ special_discount: undefined,
56
+ is_special_discount_percentage: false,
57
+ special_reference_number: undefined,
58
+ total_discount: 0,
59
+ };
60
+ }
61
+ return {
62
+ ...orderDiscountDetails,
63
+ special_discount_id: WALLET_CASHBACK_SPECIAL_DISCOUNT_ID,
64
+ special_discount: (0, common_1.parseNum)(walletCashbackAmount),
65
+ is_special_discount_percentage: false,
66
+ };
67
+ }
28
68
  // ================================><================================= //
29
69
  // === buildOfferDiscountUpdate === //
30
70
  // ================================><================================= //
31
71
  function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, }) {
32
72
  if (offer.reward_discount == null) {
33
- return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
73
+ return {
74
+ success: false,
75
+ discountDetails: null,
76
+ errorMessage: null,
77
+ redeemedOfferId: null,
78
+ };
34
79
  }
35
80
  const discountSlot = offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ? 'loyalty' : 'voucher';
36
81
  // Already-applied guard
@@ -102,14 +147,24 @@ function buildOfferDiscountUpdate({ offer, orderDiscountDetails, categories, })
102
147
  }),
103
148
  total_discount: 0,
104
149
  };
105
- return { success: true, discountDetails, errorMessage: null, redeemedOfferId: null };
150
+ return {
151
+ success: true,
152
+ discountDetails,
153
+ errorMessage: null,
154
+ redeemedOfferId: null,
155
+ };
106
156
  }
107
157
  // ================================><================================= //
108
158
  // === buildOfferPointsUpdate === //
109
159
  // ================================><================================= //
110
160
  function buildOfferPointsUpdate({ offer, orderDiscountDetails, }) {
111
161
  if (offer.reward_points == null) {
112
- return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
162
+ return {
163
+ success: false,
164
+ discountDetails: null,
165
+ errorMessage: null,
166
+ redeemedOfferId: null,
167
+ };
113
168
  }
114
169
  const discountDetails = orderDiscountDetails ?? null;
115
170
  return {
@@ -124,14 +179,24 @@ function buildOfferPointsUpdate({ offer, orderDiscountDetails, }) {
124
179
  // ================================><================================= //
125
180
  function buildOfferCashbackUpdate({ offer, orderDiscountDetails, categories, }) {
126
181
  if (offer.reward_cashback == null) {
127
- return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
182
+ return {
183
+ success: false,
184
+ discountDetails: null,
185
+ errorMessage: null,
186
+ redeemedOfferId: null,
187
+ };
128
188
  }
129
189
  // Validate excluded_refs
130
190
  const excluded_refs = offer.reward_cashback.excluded_refs ?? [];
131
191
  if (excluded_refs.length > 0) {
132
192
  const { subtotal: eligibleSubtotal } = (0, cart_actions_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs);
133
193
  if (eligibleSubtotal <= 0) {
134
- return { success: false, discountDetails: null, errorMessage: null, redeemedOfferId: null };
194
+ return {
195
+ success: false,
196
+ discountDetails: null,
197
+ errorMessage: null,
198
+ redeemedOfferId: null,
199
+ };
135
200
  }
136
201
  }
137
202
  const discountDetails = orderDiscountDetails ?? null;
@@ -159,16 +224,16 @@ function buildOfferRewardUpdate({ offer, orderDiscountDetails, }) {
159
224
  // === buildGiftCardDiscountUpdate === //
160
225
  // ================================><================================= //
161
226
  function buildGiftCardDiscountUpdate({ giftCard, orderDiscountDetails, categories, }) {
162
- // Already-applied guard
163
- if (orderDiscountDetails != null && orderDiscountDetails.special_discount_id) {
164
- return {
165
- success: false,
166
- discountDetails: null,
167
- errorMessage: 'You already have a gift card or special discount applied.',
168
- };
169
- }
170
227
  const rewardType = giftCard.reward_type;
171
228
  if (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.DISCOUNT) {
229
+ // Already-applied guard for discount-slot-based rewards.
230
+ if (orderDiscountDetails != null && orderDiscountDetails.special_discount_id) {
231
+ return {
232
+ success: false,
233
+ discountDetails: null,
234
+ errorMessage: 'You already have a gift card or special discount applied.',
235
+ };
236
+ }
172
237
  const reward = giftCard.reward_discount;
173
238
  if (!reward)
174
239
  return { success: false, discountDetails: null, errorMessage: null };
@@ -214,17 +279,50 @@ function buildGiftCardDiscountUpdate({ giftCard, orderDiscountDetails, categorie
214
279
  };
215
280
  return { success: true, discountDetails, errorMessage: null };
216
281
  }
217
- // POINTS, CASHBACK, VOUCHER, ITEMS, DISCOUNT_ITEMS, MYSTERY_GIFT — tag for backend resolution
218
- const discountDetails = {
219
- ...orderDiscountDetails,
220
- special_discount_id: giftCard._id,
221
- special_discount_name: giftCard.name,
222
- special_discount: 0,
223
- is_special_discount_percentage: false,
224
- special_reference_number: giftCard.code,
225
- total_discount: 0,
282
+ // Cashback rewards are post-order wallet credits and must not consume a discount slot.
283
+ if (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.CASHBACK) {
284
+ if (giftCard.reward_cashback == null) {
285
+ return {
286
+ success: false,
287
+ discountDetails: null,
288
+ errorMessage: null,
289
+ };
290
+ }
291
+ const excluded_refs = giftCard.reward_cashback.excluded_refs ?? [];
292
+ if (excluded_refs.length > 0) {
293
+ const { subtotal: eligibleSubtotal } = (0, cart_actions_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs);
294
+ if (eligibleSubtotal <= 0) {
295
+ return {
296
+ success: false,
297
+ discountDetails: null,
298
+ errorMessage: 'Gift card is not applicable to current cart items.',
299
+ };
300
+ }
301
+ }
302
+ return {
303
+ success: true,
304
+ discountDetails: orderDiscountDetails ?? null,
305
+ errorMessage: null,
306
+ };
307
+ }
308
+ const hasValidRewardPayload = (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.POINTS && giftCard.reward_points != null) ||
309
+ (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.VOUCHER && giftCard.reward_voucher != null) ||
310
+ (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.ITEMS && giftCard.reward_items != null) ||
311
+ (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.DISCOUNT_ITEMS && giftCard.reward_discount_items != null) ||
312
+ (rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.MYSTERY_GIFT && giftCard.reward_mystery_gift != null);
313
+ if (!hasValidRewardPayload) {
314
+ return {
315
+ success: false,
316
+ discountDetails: null,
317
+ errorMessage: 'Gift card reward data is not available right now.',
318
+ };
319
+ }
320
+ // POINTS, VOUCHER, ITEMS, DISCOUNT_ITEMS, MYSTERY_GIFT are post-order rewards.
321
+ return {
322
+ success: true,
323
+ discountDetails: orderDiscountDetails ?? null,
324
+ errorMessage: null,
226
325
  };
227
- return { success: true, discountDetails, errorMessage: null };
228
326
  }
229
327
  // ================================><================================= //
230
328
  // === buildVoucherDiscountUpdate === //
@@ -236,3 +334,488 @@ function buildVoucherDiscountUpdate({ code, orderDiscountDetails, }) {
236
334
  total_discount: 0,
237
335
  };
238
336
  }
337
+ // ===============================>Cart Actions<================================= //
338
+ function getNormalizedOfferId(offerId) {
339
+ if (offerId == null)
340
+ return null;
341
+ const normalizedOfferId = offerId.toString().trim();
342
+ return normalizedOfferId.length > 0 ? normalizedOfferId : null;
343
+ }
344
+ function toPositiveInteger(value, fallback = 0) {
345
+ const parsedValue = Number(value);
346
+ if (!Number.isFinite(parsedValue) || parsedValue <= 0) {
347
+ return fallback;
348
+ }
349
+ return Math.floor(parsedValue);
350
+ }
351
+ function getNormalizedRedeemedOffersMap(redeemedOffers) {
352
+ if (redeemedOffers == null)
353
+ return null;
354
+ const normalizedRedeemedOffers = {};
355
+ const offerIds = Object.keys(redeemedOffers);
356
+ for (let i = 0; i < offerIds.length; i++) {
357
+ const offerId = offerIds[i];
358
+ const normalizedOfferId = getNormalizedOfferId(offerId);
359
+ if (normalizedOfferId == null)
360
+ continue;
361
+ const safeCount = toPositiveInteger(redeemedOffers[offerId], 0);
362
+ if (safeCount <= 0)
363
+ continue;
364
+ normalizedRedeemedOffers[normalizedOfferId] = safeCount;
365
+ }
366
+ return Object.keys(normalizedRedeemedOffers).length > 0 ? normalizedRedeemedOffers : null;
367
+ }
368
+ function isRedeemedOffersMapNormalized(redeemedOffers) {
369
+ if (redeemedOffers == null) {
370
+ return true;
371
+ }
372
+ const normalizedRedeemedOffers = getNormalizedRedeemedOffersMap(redeemedOffers);
373
+ const rawOfferIds = Object.keys(redeemedOffers);
374
+ const normalizedOfferIds = Object.keys(normalizedRedeemedOffers ?? {});
375
+ if (rawOfferIds.length !== normalizedOfferIds.length) {
376
+ return false;
377
+ }
378
+ for (let i = 0; i < rawOfferIds.length; i++) {
379
+ const rawOfferId = rawOfferIds[i];
380
+ const normalizedOfferId = getNormalizedOfferId(rawOfferId);
381
+ const safeCount = toPositiveInteger(redeemedOffers[rawOfferId], 0);
382
+ if (normalizedOfferId == null || rawOfferId !== normalizedOfferId || safeCount <= 0) {
383
+ return false;
384
+ }
385
+ if ((normalizedRedeemedOffers?.[normalizedOfferId] ?? 0) !== safeCount) {
386
+ return false;
387
+ }
388
+ }
389
+ return true;
390
+ }
391
+ function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
392
+ const normalizedCurrentRedeemedOffers = getNormalizedRedeemedOffersMap(currentRedeemedOffers);
393
+ const normalizedNextRedeemedOffers = getNormalizedRedeemedOffersMap(nextRedeemedOffers);
394
+ if (normalizedCurrentRedeemedOffers == null || normalizedNextRedeemedOffers == null) {
395
+ return normalizedCurrentRedeemedOffers == null && normalizedNextRedeemedOffers == null;
396
+ }
397
+ const currentOfferIds = Object.keys(normalizedCurrentRedeemedOffers);
398
+ const nextOfferIds = Object.keys(normalizedNextRedeemedOffers);
399
+ if (currentOfferIds.length !== nextOfferIds.length) {
400
+ return false;
401
+ }
402
+ for (let i = 0; i < currentOfferIds.length; i++) {
403
+ const offerId = currentOfferIds[i];
404
+ if (normalizedCurrentRedeemedOffers[offerId] !== normalizedNextRedeemedOffers[offerId]) {
405
+ return false;
406
+ }
407
+ }
408
+ return true;
409
+ }
410
+ function getItemRewardApplicableQuantity(offer) {
411
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
412
+ return toPositiveInteger(offer.reward_items?.num_of_items, 1);
413
+ }
414
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
415
+ return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
416
+ }
417
+ return null;
418
+ }
419
+ function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
420
+ let totalSelectedOfferItems = 0;
421
+ for (let i = 0; i < categories.length; i++) {
422
+ const category = categories[i];
423
+ for (let j = 0; j < category.items.length; j++) {
424
+ const item = category.items[j];
425
+ const discountDetails = item.item_discount_details;
426
+ if (discountDetails == null)
427
+ continue;
428
+ const loyaltyDiscountId = getNormalizedOfferId(discountDetails.loyalty_discount_id);
429
+ const voucherDiscountId = getNormalizedOfferId(discountDetails.voucher_discount_id);
430
+ if (loyaltyDiscountId !== offerId && voucherDiscountId !== offerId)
431
+ continue;
432
+ totalSelectedOfferItems += toPositiveInteger(item.quantity, 0);
433
+ }
434
+ }
435
+ return totalSelectedOfferItems;
436
+ }
437
+ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, offers, removedOfferIds, unlockedOffersApplicableTimes, }) {
438
+ const nextRedeemedOffers = {
439
+ ...(getNormalizedRedeemedOffersMap(existingRedeemedOffers) ?? {}),
440
+ };
441
+ const removedIds = Array.from(removedOfferIds);
442
+ for (let i = 0; i < removedIds.length; i++) {
443
+ const normalizedOfferId = getNormalizedOfferId(removedIds[i]);
444
+ if (normalizedOfferId == null)
445
+ continue;
446
+ delete nextRedeemedOffers[normalizedOfferId];
447
+ }
448
+ for (let i = 0; i < offers.length; i++) {
449
+ const offer = offers[i];
450
+ const normalizedOfferId = getNormalizedOfferId(offer._id);
451
+ if (normalizedOfferId == null)
452
+ continue;
453
+ const applicableQuantity = getItemRewardApplicableQuantity(offer);
454
+ if (applicableQuantity != null) {
455
+ const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, normalizedOfferId);
456
+ // Percentage strategy: any partial usage of an item reward counts as a redeemed slot.
457
+ const redeemedTimes = selectedItemsCount > 0 ? Math.ceil(selectedItemsCount / applicableQuantity) : 0;
458
+ if (redeemedTimes > 0) {
459
+ nextRedeemedOffers[normalizedOfferId] = redeemedTimes;
460
+ }
461
+ else {
462
+ delete nextRedeemedOffers[normalizedOfferId];
463
+ }
464
+ continue;
465
+ }
466
+ const existingRedeemedTimes = toPositiveInteger(nextRedeemedOffers[normalizedOfferId], 0);
467
+ if (existingRedeemedTimes <= 0) {
468
+ delete nextRedeemedOffers[normalizedOfferId];
469
+ continue;
470
+ }
471
+ const maxApplicableTimes = toPositiveInteger(unlockedOffersApplicableTimes?.[offer._id], 0);
472
+ if (maxApplicableTimes <= 0) {
473
+ // Preserve non-item claims as positive claimed-times when unlock state is temporarily unavailable.
474
+ nextRedeemedOffers[normalizedOfferId] = existingRedeemedTimes;
475
+ continue;
476
+ }
477
+ nextRedeemedOffers[normalizedOfferId] = Math.min(existingRedeemedTimes, maxApplicableTimes);
478
+ }
479
+ return getNormalizedRedeemedOffersMap(nextRedeemedOffers);
480
+ }
481
+ function getRedeemedOffersMap(existingRedeemedOffers) {
482
+ return getNormalizedRedeemedOffersMap(existingRedeemedOffers);
483
+ }
484
+ function getNormalizedWalletRedemptionsMap(walletRedemptions) {
485
+ if (walletRedemptions == null)
486
+ return null;
487
+ const normalized = {};
488
+ const cashbackAmount = Number(walletRedemptions.cashback_amount);
489
+ if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
490
+ normalized.cashback_amount = cashbackAmount;
491
+ }
492
+ const giftCardRedemption = walletRedemptions.gift_cards;
493
+ if (giftCardRedemption != null) {
494
+ const giftCardId = giftCardRedemption.gift_card_id?.toString().trim();
495
+ const redeemedTimes = toPositiveInteger(giftCardRedemption.value_redeemed, 0);
496
+ if (giftCardId != null && giftCardId.length > 0 && redeemedTimes > 0) {
497
+ normalized.gift_cards = {
498
+ gift_card_id: giftCardId,
499
+ value_redeemed: redeemedTimes,
500
+ ...(giftCardRedemption.mystery_gift_type != null
501
+ ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
502
+ : {}),
503
+ };
504
+ }
505
+ }
506
+ return Object.keys(normalized).length > 0 ? normalized : null;
507
+ }
508
+ function getWalletRedemptionsMap(existingWalletRedemptions) {
509
+ return getNormalizedWalletRedemptionsMap(existingWalletRedemptions);
510
+ }
511
+ function getSyncOffersWithCartData(data, courses, listnerSettings, unlockedOffersApplicableTimes, // Record<offer_id, times can be applied>
512
+ offers) {
513
+ const unlockedOffersMap = {
514
+ ...unlockedOffersApplicableTimes,
515
+ };
516
+ const removedOfferIds = new Set();
517
+ let hasChanges = false;
518
+ const categories = data.categories ?? [];
519
+ const orderLevelDiscountBaseAmount = getOrderSubtotalFromCategories(categories);
520
+ let order_discount_details = data.order_discount_details;
521
+ let redeemed_offers = getNormalizedRedeemedOffersMap(data.redeemed_offers);
522
+ let wallet_redemptions = getNormalizedWalletRedemptionsMap(data.wallet_redemptions);
523
+ if (!isRedeemedOffersMapNormalized(data.redeemed_offers)) {
524
+ hasChanges = true;
525
+ }
526
+ const previousWalletCashbackAmount = (0, common_1.parseNum)(Number(wallet_redemptions?.cashback_amount ?? 0));
527
+ const hasWalletCashbackSpecialDiscount = isWalletCashbackSpecialDiscount(order_discount_details);
528
+ if (hasWalletCashbackSpecialDiscount) {
529
+ const requestedWalletCashbackAmount = getWalletCashbackAmountFromOrderData({
530
+ orderDiscountDetails: order_discount_details,
531
+ walletRedemptions: wallet_redemptions,
532
+ });
533
+ const maxApplicableWalletCashback = (0, common_1.parseNum)(Math.max(0, orderLevelDiscountBaseAmount));
534
+ const syncedWalletCashbackAmount = (0, common_1.parseNum)(Math.min(requestedWalletCashbackAmount, maxApplicableWalletCashback));
535
+ const prevSpecialDiscountId = order_discount_details?.special_discount_id;
536
+ const prevSpecialDiscountAmount = (0, common_1.parseNum)(Number(order_discount_details?.special_discount ?? 0));
537
+ const prevIsSpecialDiscountPercentage = order_discount_details?.is_special_discount_percentage === true;
538
+ const nextOrderDiscountDetails = getSyncedWalletCashbackOrderDiscountDetails({
539
+ orderDiscountDetails: order_discount_details,
540
+ walletCashbackAmount: syncedWalletCashbackAmount,
541
+ });
542
+ const nextSpecialDiscountId = nextOrderDiscountDetails?.special_discount_id;
543
+ const nextSpecialDiscountAmount = (0, common_1.parseNum)(Number(nextOrderDiscountDetails?.special_discount ?? 0));
544
+ const nextIsSpecialDiscountPercentage = nextOrderDiscountDetails?.is_special_discount_percentage === true;
545
+ if (prevSpecialDiscountId !== nextSpecialDiscountId ||
546
+ prevSpecialDiscountAmount !== nextSpecialDiscountAmount ||
547
+ prevIsSpecialDiscountPercentage !== nextIsSpecialDiscountPercentage) {
548
+ hasChanges = true;
549
+ }
550
+ order_discount_details = nextOrderDiscountDetails;
551
+ wallet_redemptions = getNormalizedWalletRedemptionsMap({
552
+ ...(wallet_redemptions ?? {}),
553
+ cashback_amount: syncedWalletCashbackAmount > 0 ? syncedWalletCashbackAmount : undefined,
554
+ });
555
+ const nextWalletCashbackAmount = (0, common_1.parseNum)(Number(wallet_redemptions?.cashback_amount ?? 0));
556
+ if (previousWalletCashbackAmount !== nextWalletCashbackAmount) {
557
+ hasChanges = true;
558
+ }
559
+ }
560
+ else if (previousWalletCashbackAmount > 0) {
561
+ // Offers can reward cashback into wallet, but cannot activate cashback discount on current order.
562
+ wallet_redemptions = getNormalizedWalletRedemptionsMap({
563
+ ...(wallet_redemptions ?? {}),
564
+ cashback_amount: undefined,
565
+ });
566
+ hasChanges = true;
567
+ }
568
+ const redeemedOffersPresenceMap = getReconciledRedeemedOffersMap({
569
+ existingRedeemedOffers: redeemed_offers,
570
+ categories,
571
+ offers,
572
+ removedOfferIds: new Set(),
573
+ unlockedOffersApplicableTimes,
574
+ });
575
+ const clearOrderLevelDiscount = (discountType) => {
576
+ if (order_discount_details == null) {
577
+ return;
578
+ }
579
+ const appliedOfferId = discountType === 'loyalty'
580
+ ? order_discount_details.loyalty_discount_id
581
+ : order_discount_details.voucher_discount_id;
582
+ const normalizedAppliedOfferId = getNormalizedOfferId(appliedOfferId);
583
+ if (normalizedAppliedOfferId != null) {
584
+ removedOfferIds.add(normalizedAppliedOfferId);
585
+ }
586
+ if (discountType === 'loyalty') {
587
+ order_discount_details = {
588
+ ...order_discount_details,
589
+ loyalty_discount_id: undefined,
590
+ loyalty_discount_name: undefined,
591
+ loyalty_discount: undefined,
592
+ is_loyalty_discount_percentage: false,
593
+ };
594
+ }
595
+ else {
596
+ order_discount_details = {
597
+ ...order_discount_details,
598
+ voucher_discount_id: undefined,
599
+ voucher_discount_name: undefined,
600
+ voucher_discount: undefined,
601
+ is_voucher_discount_percentage: false,
602
+ };
603
+ }
604
+ hasChanges = true;
605
+ };
606
+ if (order_discount_details != null) {
607
+ // we check if either the loyalty_discount_id or voucher_discount_id
608
+ const loyaltyDiscountId = order_discount_details.loyalty_discount_id;
609
+ if (loyaltyDiscountId != null) {
610
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
611
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
612
+ if (!hasRedeemedEntryForLoyalty) {
613
+ clearOrderLevelDiscount('loyalty');
614
+ }
615
+ else if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
616
+ clearOrderLevelDiscount('loyalty');
617
+ }
618
+ else {
619
+ // Find the offer to check for excluded_refs
620
+ const loyaltyOffer = offers.find((o) => o._id === loyaltyDiscountId);
621
+ if (loyaltyOffer?.reward_discount != null) {
622
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = loyaltyOffer.reward_discount;
623
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
624
+ ? (0, cart_actions_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs)
625
+ : {
626
+ subtotal: orderLevelDiscountBaseAmount,
627
+ hasExcludedRefs: false,
628
+ };
629
+ // Static discounts with exclusions are not supported - silently skip
630
+ if (hasExcludedRefs && !is_discount_percentage) {
631
+ clearOrderLevelDiscount('loyalty');
632
+ }
633
+ else {
634
+ const hasRelevantCap = is_discount_percentage &&
635
+ max_discount_amount != null &&
636
+ Number.isFinite(max_discount_amount) &&
637
+ max_discount_amount >= 0;
638
+ const hasRelevantPercentageCap = !is_discount_percentage &&
639
+ max_discount_percentage != null &&
640
+ Number.isFinite(max_discount_percentage) &&
641
+ max_discount_percentage >= 0;
642
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
643
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
644
+ if (shouldNormalizeToStatic) {
645
+ if (discountBaseAmount <= 0) {
646
+ clearOrderLevelDiscount('loyalty');
647
+ }
648
+ else {
649
+ const calculatedDiscount = (0, common_1.getCappedOfferDiscountAmount)({
650
+ baseAmount: discountBaseAmount,
651
+ discountValue: discount_value,
652
+ isDiscountPercentage: is_discount_percentage,
653
+ maxDiscountAmount: max_discount_amount,
654
+ maxDiscountPercentage: max_discount_percentage,
655
+ });
656
+ order_discount_details = {
657
+ ...order_discount_details,
658
+ loyalty_discount: (0, common_1.parseNum)(calculatedDiscount),
659
+ is_loyalty_discount_percentage: false,
660
+ };
661
+ hasChanges = true;
662
+ }
663
+ }
664
+ }
665
+ }
666
+ unlockedOffersMap[loyaltyDiscountId] -= 1;
667
+ }
668
+ }
669
+ const voucherDiscountId = order_discount_details.voucher_discount_id;
670
+ if (voucherDiscountId != null) {
671
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
672
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
673
+ if (!hasRedeemedEntryForVoucher) {
674
+ clearOrderLevelDiscount('voucher');
675
+ }
676
+ else if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
677
+ clearOrderLevelDiscount('voucher');
678
+ }
679
+ else {
680
+ // Find the offer to check for excluded_refs
681
+ const voucherOffer = offers.find((o) => o._id === voucherDiscountId);
682
+ if (voucherOffer?.reward_discount != null) {
683
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = voucherOffer.reward_discount;
684
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
685
+ ? (0, cart_actions_1.calculateEligibleOfferDiscountDetails)(categories, excluded_refs)
686
+ : {
687
+ subtotal: orderLevelDiscountBaseAmount,
688
+ hasExcludedRefs: false,
689
+ };
690
+ // Static discounts with exclusions are not supported - silently skip
691
+ if (hasExcludedRefs && !is_discount_percentage) {
692
+ clearOrderLevelDiscount('voucher');
693
+ }
694
+ else {
695
+ const hasRelevantCap = is_discount_percentage &&
696
+ max_discount_amount != null &&
697
+ Number.isFinite(max_discount_amount) &&
698
+ max_discount_amount >= 0;
699
+ const hasRelevantPercentageCap = !is_discount_percentage &&
700
+ max_discount_percentage != null &&
701
+ Number.isFinite(max_discount_percentage) &&
702
+ max_discount_percentage >= 0;
703
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
704
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
705
+ if (shouldNormalizeToStatic) {
706
+ if (discountBaseAmount <= 0) {
707
+ clearOrderLevelDiscount('voucher');
708
+ }
709
+ else {
710
+ const calculatedDiscount = (0, common_1.getCappedOfferDiscountAmount)({
711
+ baseAmount: discountBaseAmount,
712
+ discountValue: discount_value,
713
+ isDiscountPercentage: is_discount_percentage,
714
+ maxDiscountAmount: max_discount_amount,
715
+ maxDiscountPercentage: max_discount_percentage,
716
+ });
717
+ order_discount_details = {
718
+ ...order_discount_details,
719
+ voucher_discount: (0, common_1.parseNum)(calculatedDiscount),
720
+ is_voucher_discount_percentage: false,
721
+ };
722
+ hasChanges = true;
723
+ }
724
+ }
725
+ }
726
+ }
727
+ unlockedOffersMap[voucherDiscountId] -= 1;
728
+ }
729
+ }
730
+ }
731
+ const newCategories = [];
732
+ for (let i = 0; i < categories.length; i++) {
733
+ const category = categories[i];
734
+ const newItems = [];
735
+ for (let j = 0; j < category.items.length; j++) {
736
+ const item = category.items[j];
737
+ // we check if either the loyalty_discount_id or voucher_discount_id
738
+ // is present in the item_discount_details
739
+ // if it is then we remove the items from cart
740
+ if (item.item_discount_details != null) {
741
+ const loyaltyDiscountId = item.item_discount_details.loyalty_discount_id;
742
+ if (loyaltyDiscountId != null) {
743
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
744
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
745
+ if (!hasRedeemedEntryForLoyalty) {
746
+ hasChanges = true;
747
+ if (normalizedLoyaltyDiscountId != null) {
748
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
749
+ }
750
+ continue;
751
+ }
752
+ if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
753
+ hasChanges = true;
754
+ if (normalizedLoyaltyDiscountId != null) {
755
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
756
+ }
757
+ continue;
758
+ }
759
+ else {
760
+ unlockedOffersMap[loyaltyDiscountId] -= toPositiveInteger(item.quantity, 1);
761
+ }
762
+ }
763
+ const voucherDiscountId = item.item_discount_details.voucher_discount_id;
764
+ if (voucherDiscountId != null) {
765
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
766
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
767
+ if (!hasRedeemedEntryForVoucher) {
768
+ hasChanges = true;
769
+ if (normalizedVoucherDiscountId != null) {
770
+ removedOfferIds.add(normalizedVoucherDiscountId);
771
+ }
772
+ continue;
773
+ }
774
+ if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
775
+ hasChanges = true;
776
+ if (normalizedVoucherDiscountId != null) {
777
+ removedOfferIds.add(normalizedVoucherDiscountId);
778
+ }
779
+ continue;
780
+ }
781
+ else {
782
+ unlockedOffersMap[voucherDiscountId] -= toPositiveInteger(item.quantity, 1);
783
+ }
784
+ }
785
+ newItems.push(item);
786
+ }
787
+ else {
788
+ newItems.push(item);
789
+ }
790
+ }
791
+ newCategories.push({
792
+ ...category,
793
+ items: newItems,
794
+ });
795
+ }
796
+ const reconciledRedeemedOffers = getReconciledRedeemedOffersMap({
797
+ existingRedeemedOffers: redeemed_offers,
798
+ categories: newCategories,
799
+ offers,
800
+ removedOfferIds,
801
+ unlockedOffersApplicableTimes,
802
+ });
803
+ if (!areRedeemedOffersEqual(redeemed_offers, reconciledRedeemedOffers)) {
804
+ redeemed_offers = reconciledRedeemedOffers;
805
+ hasChanges = true;
806
+ }
807
+ if (hasChanges) {
808
+ const order = {
809
+ ...data,
810
+ categories: newCategories,
811
+ order_discount_details,
812
+ redeemed_offers,
813
+ wallet_redemptions: getWalletRedemptionsMap(wallet_redemptions),
814
+ };
815
+ const newData = (0, cart_actions_1.calculateCartOrderInfoAndSyncData)(order, courses, listnerSettings);
816
+ return newData;
817
+ }
818
+ else {
819
+ return data;
820
+ }
821
+ }