@managesome/eposmatic-toolkit 0.2.316 → 0.2.318

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.
@@ -27,11 +27,13 @@ exports.getChangeCourseStatusData = getChangeCourseStatusData;
27
27
  exports.getCartItemsObj = getCartItemsObj;
28
28
  exports.getRemoveOfferFromCartData = getRemoveOfferFromCartData;
29
29
  exports.getRemoveAllOffersFromCartData = getRemoveAllOffersFromCartData;
30
+ exports.getClearVoucherCodeAndOffersFromCartData = getClearVoucherCodeAndOffersFromCartData;
30
31
  exports.calculateEligibleOfferDiscountDetails = calculateEligibleOfferDiscountDetails;
31
32
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
32
33
  const lodash_1 = require("lodash");
33
34
  const constants_1 = require("../../constants");
34
35
  const utils_1 = require("../utils");
36
+ const offers_helpers_1 = require("../utils/offers-helpers");
35
37
  const platform_catalog_1 = require("../utils/platform-catalog");
36
38
  function getItemQuantityChangeResults({ prevQuantity, newQuantity, prevItemDiscountDetails, }) {
37
39
  let item_discount_details = prevItemDiscountDetails;
@@ -229,34 +231,78 @@ function getDiscountDetails(item_discount_details, itemTotalWithTaxAmount) {
229
231
  ...item_discount_details,
230
232
  total_discount: 0,
231
233
  };
234
+ let remainingPositiveDiscountableAmount = (0, utils_1.parseNum)(Math.max(0, itemTotalWithTaxAmount));
235
+ const consumePositiveDiscountAmount = (discountAmount) => {
236
+ if (discountAmount <= 0)
237
+ return;
238
+ remainingPositiveDiscountableAmount = (0, utils_1.parseNum)(Math.max(0, remainingPositiveDiscountableAmount - discountAmount));
239
+ };
240
+ const clearSpecialDiscountSlot = () => {
241
+ discount_details.special_discount_id = undefined;
242
+ discount_details.special_discount_name = undefined;
243
+ discount_details.special_discount = undefined;
244
+ discount_details.is_special_discount_percentage = false;
245
+ discount_details.special_discount_reason = undefined;
246
+ discount_details.special_reference_number = undefined;
247
+ };
248
+ const clearLoyaltyDiscountSlot = () => {
249
+ discount_details.loyalty_discount_id = undefined;
250
+ discount_details.loyalty_discount_name = undefined;
251
+ discount_details.loyalty_discount = undefined;
252
+ discount_details.is_loyalty_discount_percentage = false;
253
+ discount_details.loyalty_discount_reason = undefined;
254
+ discount_details.loyalty_reference_number = undefined;
255
+ };
256
+ const clearVoucherDiscountSlot = () => {
257
+ discount_details.voucher_discount_id = undefined;
258
+ discount_details.voucher_discount_name = undefined;
259
+ discount_details.voucher_discount = undefined;
260
+ discount_details.is_voucher_discount_percentage = false;
261
+ discount_details.voucher_discount_reason = undefined;
262
+ discount_details.voucher_reference_number = undefined;
263
+ };
232
264
  if (special_discount_id && special_discount) {
233
- if (is_special_discount_percentage) {
234
- discount_details.total_discount += (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, special_discount);
265
+ const specialDiscountAmount = is_special_discount_percentage
266
+ ? (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, special_discount)
267
+ : special_discount;
268
+ if (specialDiscountAmount > remainingPositiveDiscountableAmount) {
269
+ clearSpecialDiscountSlot();
235
270
  }
236
271
  else {
237
- discount_details.total_discount += special_discount;
272
+ discount_details.total_discount += specialDiscountAmount;
273
+ consumePositiveDiscountAmount(specialDiscountAmount);
238
274
  }
275
+ // NOTE: we only keep the slot if it can be fully applied.
276
+ // Partial application is avoided so stale/invalid discounts are removed explicitly.
239
277
  }
240
278
  else {
241
279
  delete discount_details.special_discount_reason;
242
280
  }
243
281
  if (loyalty_discount_id && loyalty_discount) {
244
- if (is_loyalty_discount_percentage) {
245
- discount_details.total_discount += (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, loyalty_discount);
282
+ const loyaltyDiscountAmount = is_loyalty_discount_percentage
283
+ ? (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, loyalty_discount)
284
+ : loyalty_discount;
285
+ if (loyaltyDiscountAmount > remainingPositiveDiscountableAmount) {
286
+ clearLoyaltyDiscountSlot();
246
287
  }
247
288
  else {
248
- discount_details.total_discount += loyalty_discount;
289
+ discount_details.total_discount += loyaltyDiscountAmount;
290
+ consumePositiveDiscountAmount(loyaltyDiscountAmount);
249
291
  }
250
292
  }
251
293
  else {
252
294
  delete discount_details.loyalty_discount_reason;
253
295
  }
254
296
  if (voucher_discount_id && voucher_discount) {
255
- if (is_voucher_discount_percentage) {
256
- discount_details.total_discount += (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, voucher_discount);
297
+ const voucherDiscountAmount = is_voucher_discount_percentage
298
+ ? (0, utils_1.getPercentageAmount)(itemTotalWithTaxAmount, voucher_discount)
299
+ : voucher_discount;
300
+ if (voucherDiscountAmount > remainingPositiveDiscountableAmount) {
301
+ clearVoucherDiscountSlot();
257
302
  }
258
303
  else {
259
- discount_details.total_discount += voucher_discount;
304
+ discount_details.total_discount += voucherDiscountAmount;
305
+ consumePositiveDiscountAmount(voucherDiscountAmount);
260
306
  }
261
307
  }
262
308
  else {
@@ -388,11 +434,195 @@ function getNormalizedRedeemedOffersMap(redeemedOffers) {
388
434
  }
389
435
  return Object.keys(normalizedRedeemedOffers).length > 0 ? normalizedRedeemedOffers : null;
390
436
  }
391
- function isRedeemedOffersMapNormalized(redeemedOffers) {
437
+ function getRedeemedOffersMap(existingRedeemedOffers) {
438
+ return getNormalizedRedeemedOffersMap(existingRedeemedOffers);
439
+ }
440
+ function decrementRedeemedOfferUsageCount(redeemedOffers, offerId) {
441
+ const normalizedOfferId = getNormalizedOfferId(offerId);
442
+ if (normalizedOfferId == null || redeemedOffers == null) {
443
+ return redeemedOffers;
444
+ }
445
+ const previousCount = toPositiveInteger(redeemedOffers[normalizedOfferId], 0);
446
+ if (previousCount <= 0) {
447
+ return redeemedOffers;
448
+ }
449
+ const nextRedeemedOffers = {
450
+ ...redeemedOffers,
451
+ };
452
+ const nextCount = previousCount - 1;
453
+ if (nextCount <= 0) {
454
+ delete nextRedeemedOffers[normalizedOfferId];
455
+ }
456
+ else {
457
+ nextRedeemedOffers[normalizedOfferId] = nextCount;
458
+ }
459
+ return getRedeemedOffersMap(nextRedeemedOffers);
460
+ }
461
+ function getSyncedRedeemedOffersAfterOrderDiscountOverflowCleanup({ redeemedOffers, previousOrderDiscountDetails, nextOrderDiscountDetails, }) {
462
+ let nextRedeemedOffers = redeemedOffers;
463
+ const previousLoyaltyDiscountId = getNormalizedOfferId(previousOrderDiscountDetails?.loyalty_discount_id);
464
+ const nextLoyaltyDiscountId = getNormalizedOfferId(nextOrderDiscountDetails?.loyalty_discount_id);
465
+ if (previousLoyaltyDiscountId != null && previousLoyaltyDiscountId !== nextLoyaltyDiscountId) {
466
+ nextRedeemedOffers = decrementRedeemedOfferUsageCount(nextRedeemedOffers, previousLoyaltyDiscountId);
467
+ }
468
+ const previousVoucherDiscountId = getNormalizedOfferId(previousOrderDiscountDetails?.voucher_discount_id);
469
+ const nextVoucherDiscountId = getNormalizedOfferId(nextOrderDiscountDetails?.voucher_discount_id);
470
+ if (previousVoucherDiscountId != null && previousVoucherDiscountId !== nextVoucherDiscountId) {
471
+ nextRedeemedOffers = decrementRedeemedOfferUsageCount(nextRedeemedOffers, previousVoucherDiscountId);
472
+ }
473
+ return getRedeemedOffersMap(nextRedeemedOffers);
474
+ }
475
+ function getWalletRedemptionsMap(walletRedemptions) {
476
+ if (walletRedemptions == null)
477
+ return null;
478
+ const normalized = {};
479
+ const cashbackAmount = Number(walletRedemptions.cashback_amount);
480
+ if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
481
+ normalized.cashback_amount = cashbackAmount;
482
+ }
483
+ const giftCardRedemption = walletRedemptions.gift_cards;
484
+ if (giftCardRedemption != null) {
485
+ const giftCardId = giftCardRedemption.gift_card_id?.toString().trim();
486
+ const valueRedeemed = Number(giftCardRedemption.value_redeemed);
487
+ if (giftCardId != null && giftCardId.length > 0 && Number.isFinite(valueRedeemed) && valueRedeemed > 0) {
488
+ normalized.gift_cards = {
489
+ gift_card_id: giftCardId,
490
+ value_redeemed: valueRedeemed,
491
+ ...(giftCardRedemption.mystery_gift_type != null
492
+ ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
493
+ : {}),
494
+ };
495
+ }
496
+ }
497
+ return Object.keys(normalized).length > 0 ? normalized : null;
498
+ }
499
+ function getSyncedWalletRedemptionsAfterOrderDiscountOverflowCleanup({ walletRedemptions, previousOrderDiscountDetails, nextOrderDiscountDetails, }) {
500
+ if (walletRedemptions == null) {
501
+ return walletRedemptions;
502
+ }
503
+ const previousLoyaltyDiscountId = getNormalizedOfferId(previousOrderDiscountDetails?.loyalty_discount_id);
504
+ const nextLoyaltyDiscountId = getNormalizedOfferId(nextOrderDiscountDetails?.loyalty_discount_id);
505
+ if (previousLoyaltyDiscountId == null || previousLoyaltyDiscountId === nextLoyaltyDiscountId) {
506
+ return walletRedemptions;
507
+ }
508
+ const walletGiftCardDiscountId = getNormalizedOfferId(walletRedemptions?.gift_cards?.gift_card_id);
509
+ const shouldClearWalletCashback = previousLoyaltyDiscountId === constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID &&
510
+ Number(walletRedemptions.cashback_amount ?? 0) > 0;
511
+ const shouldClearGiftCardRedemption = walletGiftCardDiscountId != null && walletGiftCardDiscountId === previousLoyaltyDiscountId;
512
+ if (!shouldClearWalletCashback && !shouldClearGiftCardRedemption) {
513
+ return walletRedemptions;
514
+ }
515
+ return getWalletRedemptionsMap({
516
+ ...walletRedemptions,
517
+ ...(shouldClearWalletCashback ? { cashback_amount: undefined } : {}),
518
+ ...(shouldClearGiftCardRedemption ? { gift_cards: undefined } : {}),
519
+ });
520
+ }
521
+ function clearSpecialDiscountFields(orderDiscountDetails) {
522
+ return {
523
+ ...orderDiscountDetails,
524
+ special_discount_id: undefined,
525
+ special_discount_name: undefined,
526
+ special_discount: undefined,
527
+ is_special_discount_percentage: false,
528
+ special_discount_reason: undefined,
529
+ special_reference_number: undefined,
530
+ };
531
+ }
532
+ function getSyncedOrderDiscountDetailsWithoutRewardSpecialDiscount({ orderDiscountDetails, redeemedOffers, walletRedemptions, }) {
533
+ if (orderDiscountDetails == null) {
534
+ return orderDiscountDetails;
535
+ }
536
+ const normalizedSpecialDiscountId = getNormalizedOfferId(orderDiscountDetails.special_discount_id);
537
+ if (normalizedSpecialDiscountId == null) {
538
+ return orderDiscountDetails;
539
+ }
540
+ const hasRedeemedOfferForSpecialDiscount = redeemedOffers?.[normalizedSpecialDiscountId] != null;
541
+ const normalizedGiftCardId = getNormalizedOfferId(walletRedemptions?.gift_cards?.gift_card_id);
542
+ const isGiftCardRewardDiscount = normalizedGiftCardId != null && normalizedGiftCardId === normalizedSpecialDiscountId;
543
+ const isWalletCashbackRewardDiscount = normalizedSpecialDiscountId === constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID;
544
+ const isRewardLinkedSpecialDiscount = hasRedeemedOfferForSpecialDiscount || isGiftCardRewardDiscount || isWalletCashbackRewardDiscount;
545
+ if (!isRewardLinkedSpecialDiscount) {
546
+ return orderDiscountDetails;
547
+ }
548
+ const hasExistingRewardSlot = orderDiscountDetails.loyalty_discount_id != null || orderDiscountDetails.voucher_discount_id != null;
549
+ if (hasExistingRewardSlot) {
550
+ return clearSpecialDiscountFields(orderDiscountDetails);
551
+ }
552
+ return {
553
+ ...clearSpecialDiscountFields(orderDiscountDetails),
554
+ loyalty_discount_id: normalizedSpecialDiscountId,
555
+ loyalty_discount_name: orderDiscountDetails.loyalty_discount_name ?? orderDiscountDetails.special_discount_name,
556
+ loyalty_discount: orderDiscountDetails.loyalty_discount ?? orderDiscountDetails.special_discount,
557
+ is_loyalty_discount_percentage: orderDiscountDetails.loyalty_discount_id != null || orderDiscountDetails.loyalty_discount != null
558
+ ? orderDiscountDetails.is_loyalty_discount_percentage
559
+ : orderDiscountDetails.is_special_discount_percentage,
560
+ loyalty_discount_reason: orderDiscountDetails.loyalty_discount_reason ?? orderDiscountDetails.special_discount_reason,
561
+ loyalty_reference_number: orderDiscountDetails.loyalty_reference_number ?? orderDiscountDetails.special_reference_number,
562
+ };
563
+ }
564
+ function getSyncedItemDiscountDetailsWithoutRewardSpecialDiscount({ itemDiscountDetails, redeemedOffers, walletRedemptions, }) {
565
+ return getSyncedOrderDiscountDetailsWithoutRewardSpecialDiscount({
566
+ orderDiscountDetails: itemDiscountDetails,
567
+ redeemedOffers,
568
+ walletRedemptions,
569
+ });
570
+ }
571
+ function isWalletCashbackLoyaltyDiscount(orderDiscountDetails) {
572
+ return orderDiscountDetails?.loyalty_discount_id === constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID;
573
+ }
574
+ function getWalletCashbackAmountFromOrderData({ orderDiscountDetails, walletRedemptions, }) {
575
+ if (!isWalletCashbackLoyaltyDiscount(orderDiscountDetails)) {
576
+ return 0;
577
+ }
578
+ const loyaltyDiscountAmount = Number(orderDiscountDetails?.loyalty_discount ?? 0);
579
+ if (Number.isFinite(loyaltyDiscountAmount) && loyaltyDiscountAmount > 0) {
580
+ return loyaltyDiscountAmount;
581
+ }
582
+ const walletRedemptionAmount = Number(walletRedemptions?.cashback_amount ?? 0);
583
+ return Number.isFinite(walletRedemptionAmount) && walletRedemptionAmount > 0 ? walletRedemptionAmount : 0;
584
+ }
585
+ function getSyncedWalletCashbackOrderDiscountDetails({ orderDiscountDetails, walletCashbackAmount, }) {
586
+ if (orderDiscountDetails == null) {
587
+ return orderDiscountDetails;
588
+ }
589
+ if (walletCashbackAmount <= 0) {
590
+ return {
591
+ ...orderDiscountDetails,
592
+ loyalty_discount_id: undefined,
593
+ loyalty_discount_name: undefined,
594
+ loyalty_discount: undefined,
595
+ is_loyalty_discount_percentage: false,
596
+ loyalty_reference_number: undefined,
597
+ total_discount: 0,
598
+ };
599
+ }
600
+ return {
601
+ ...orderDiscountDetails,
602
+ loyalty_discount_id: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID,
603
+ loyalty_discount_name: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_NAME,
604
+ loyalty_discount: (0, utils_1.parseNum)(walletCashbackAmount),
605
+ is_loyalty_discount_percentage: false,
606
+ loyalty_reference_number: constants_1.WALLET_CASHBACK_LOYALTY_REFERENCE,
607
+ };
608
+ }
609
+ function getOrderSubtotalFromCategoriesForOfferSync(categories) {
610
+ if (!categories?.length)
611
+ return 0;
612
+ let subtotal = 0;
613
+ for (let i = 0; i < categories.length; i++) {
614
+ const items = categories[i].items;
615
+ for (let j = 0; j < items.length; j++) {
616
+ subtotal += items[j].subtotal ?? 0;
617
+ }
618
+ }
619
+ return subtotal;
620
+ }
621
+ function isRedeemedOffersMapNormalizedForOfferSync(redeemedOffers) {
392
622
  if (redeemedOffers == null) {
393
623
  return true;
394
624
  }
395
- const normalizedRedeemedOffers = getNormalizedRedeemedOffersMap(redeemedOffers);
625
+ const normalizedRedeemedOffers = getRedeemedOffersMap(redeemedOffers);
396
626
  const rawOfferIds = Object.keys(redeemedOffers);
397
627
  const normalizedOfferIds = Object.keys(normalizedRedeemedOffers ?? {});
398
628
  if (rawOfferIds.length !== normalizedOfferIds.length) {
@@ -411,9 +641,9 @@ function isRedeemedOffersMapNormalized(redeemedOffers) {
411
641
  }
412
642
  return true;
413
643
  }
414
- function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
415
- const normalizedCurrentRedeemedOffers = getNormalizedRedeemedOffersMap(currentRedeemedOffers);
416
- const normalizedNextRedeemedOffers = getNormalizedRedeemedOffersMap(nextRedeemedOffers);
644
+ function areRedeemedOffersEqualForOfferSync(currentRedeemedOffers, nextRedeemedOffers) {
645
+ const normalizedCurrentRedeemedOffers = getRedeemedOffersMap(currentRedeemedOffers);
646
+ const normalizedNextRedeemedOffers = getRedeemedOffersMap(nextRedeemedOffers);
417
647
  if (normalizedCurrentRedeemedOffers == null || normalizedNextRedeemedOffers == null) {
418
648
  return normalizedCurrentRedeemedOffers == null && normalizedNextRedeemedOffers == null;
419
649
  }
@@ -430,7 +660,7 @@ function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
430
660
  }
431
661
  return true;
432
662
  }
433
- function getItemRewardApplicableQuantity(offer) {
663
+ function getItemRewardApplicableQuantityForOfferSync(offer) {
434
664
  if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
435
665
  return toPositiveInteger(offer.reward_items?.num_of_items, 1);
436
666
  }
@@ -439,7 +669,7 @@ function getItemRewardApplicableQuantity(offer) {
439
669
  }
440
670
  return null;
441
671
  }
442
- function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
672
+ function getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, offerId) {
443
673
  let totalSelectedOfferItems = 0;
444
674
  for (let i = 0; i < categories.length; i++) {
445
675
  const category = categories[i];
@@ -457,9 +687,9 @@ function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
457
687
  }
458
688
  return totalSelectedOfferItems;
459
689
  }
460
- function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, offers, removedOfferIds, unlockedOffersApplicableTimes, }) {
690
+ function getReconciledRedeemedOffersMapForOfferSync({ existingRedeemedOffers, categories, offers, removedOfferIds, unlockedOffersApplicableTimes, }) {
461
691
  const nextRedeemedOffers = {
462
- ...(getNormalizedRedeemedOffersMap(existingRedeemedOffers) ?? {}),
692
+ ...(getRedeemedOffersMap(existingRedeemedOffers) ?? {}),
463
693
  };
464
694
  const removedIds = Array.from(removedOfferIds);
465
695
  for (let i = 0; i < removedIds.length; i++) {
@@ -473,10 +703,10 @@ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, of
473
703
  const normalizedOfferId = getNormalizedOfferId(offer._id);
474
704
  if (normalizedOfferId == null)
475
705
  continue;
476
- const applicableQuantity = getItemRewardApplicableQuantity(offer);
706
+ const applicableQuantity = getItemRewardApplicableQuantityForOfferSync(offer);
477
707
  if (applicableQuantity != null) {
478
- const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, normalizedOfferId);
479
- // Percentage strategy: any partial usage of an item reward counts as a redeemed slot.
708
+ const selectedItemsCount = getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, normalizedOfferId);
709
+ // Any partial usage of an item reward still counts as one redeemed slot.
480
710
  const redeemedTimes = selectedItemsCount > 0 ? Math.ceil(selectedItemsCount / applicableQuantity) : 0;
481
711
  if (redeemedTimes > 0) {
482
712
  nextRedeemedOffers[normalizedOfferId] = redeemedTimes;
@@ -493,83 +723,351 @@ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, of
493
723
  }
494
724
  const maxApplicableTimes = toPositiveInteger(unlockedOffersApplicableTimes?.[offer._id], 0);
495
725
  if (maxApplicableTimes <= 0) {
496
- // Preserve non-item claims as positive claimed-times when unlock state is temporarily unavailable.
726
+ // Keep non-item claim history when unlock context is temporarily unavailable.
497
727
  nextRedeemedOffers[normalizedOfferId] = existingRedeemedTimes;
498
728
  continue;
499
729
  }
500
730
  nextRedeemedOffers[normalizedOfferId] = Math.min(existingRedeemedTimes, maxApplicableTimes);
501
731
  }
502
- return getNormalizedRedeemedOffersMap(nextRedeemedOffers);
503
- }
504
- function getRedeemedOffersMap(existingRedeemedOffers) {
505
- return getNormalizedRedeemedOffersMap(existingRedeemedOffers);
732
+ return getRedeemedOffersMap(nextRedeemedOffers);
506
733
  }
507
- function getWalletRedemptionsMap(walletRedemptions) {
508
- if (walletRedemptions == null)
509
- return null;
510
- const normalized = {};
511
- const cashbackAmount = Number(walletRedemptions.cashback_amount);
512
- if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
513
- normalized.cashback_amount = cashbackAmount;
514
- }
515
- const giftCardRedemption = walletRedemptions.gift_cards;
516
- if (giftCardRedemption != null) {
517
- const giftCardId = giftCardRedemption.gift_card_id?.toString().trim();
518
- const valueRedeemed = Number(giftCardRedemption.value_redeemed);
519
- if (giftCardId != null && giftCardId.length > 0 && Number.isFinite(valueRedeemed) && valueRedeemed > 0) {
520
- normalized.gift_cards = {
521
- gift_card_id: giftCardId,
522
- value_redeemed: valueRedeemed,
523
- ...(giftCardRedemption.mystery_gift_type != null
524
- ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
525
- : {}),
734
+ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
735
+ const unlockedOffersMap = {
736
+ ...syncContext.unlockedOffersApplicableTimes,
737
+ };
738
+ const removedOfferIds = new Set();
739
+ let hasChanges = false;
740
+ const categories = data.categories ?? [];
741
+ const orderLevelDiscountBaseAmount = getOrderSubtotalFromCategoriesForOfferSync(categories);
742
+ let order_discount_details = data.order_discount_details;
743
+ let redeemed_offers = getRedeemedOffersMap(data.redeemed_offers);
744
+ if (!isRedeemedOffersMapNormalizedForOfferSync(data.redeemed_offers)) {
745
+ hasChanges = true;
746
+ }
747
+ const hasOrderLevelLoyaltyDiscount = order_discount_details?.loyalty_discount_id != null;
748
+ const hasOrderLevelVoucherDiscount = order_discount_details?.voucher_discount_id != null;
749
+ // Empty carts should not keep offer-driven discount slots or redeemed-offers state.
750
+ if (orderLevelDiscountBaseAmount <= 0) {
751
+ if (hasOrderLevelLoyaltyDiscount && order_discount_details != null) {
752
+ order_discount_details = {
753
+ ...order_discount_details,
754
+ loyalty_discount_id: undefined,
755
+ loyalty_discount_name: undefined,
756
+ loyalty_discount: undefined,
757
+ is_loyalty_discount_percentage: false,
758
+ loyalty_reference_number: undefined,
759
+ total_discount: 0,
526
760
  };
761
+ hasChanges = true;
762
+ }
763
+ if (hasOrderLevelVoucherDiscount && order_discount_details != null) {
764
+ order_discount_details = {
765
+ ...order_discount_details,
766
+ voucher_discount_id: undefined,
767
+ voucher_discount_name: undefined,
768
+ voucher_discount: undefined,
769
+ is_voucher_discount_percentage: false,
770
+ total_discount: 0,
771
+ };
772
+ hasChanges = true;
773
+ }
774
+ if (redeemed_offers != null) {
775
+ redeemed_offers = null;
776
+ hasChanges = true;
527
777
  }
528
778
  }
529
- return Object.keys(normalized).length > 0 ? normalized : null;
530
- }
531
- function isWalletCashbackSpecialDiscount(orderDiscountDetails) {
532
- return orderDiscountDetails?.special_discount_id === constants_1.WALLET_CASHBACK_SPECIAL_DISCOUNT_ID;
533
- }
534
- function getWalletCashbackAmountFromOrderData({ orderDiscountDetails, walletRedemptions, }) {
535
- if (!isWalletCashbackSpecialDiscount(orderDiscountDetails)) {
536
- return 0;
537
- }
538
- const specialDiscountAmount = Number(orderDiscountDetails?.special_discount ?? 0);
539
- if (Number.isFinite(specialDiscountAmount) && specialDiscountAmount > 0) {
540
- return specialDiscountAmount;
779
+ const redeemedOffersPresenceMap = getReconciledRedeemedOffersMapForOfferSync({
780
+ existingRedeemedOffers: redeemed_offers,
781
+ categories,
782
+ offers: syncContext.offers,
783
+ removedOfferIds: new Set(),
784
+ unlockedOffersApplicableTimes: syncContext.unlockedOffersApplicableTimes,
785
+ });
786
+ const clearOrderLevelDiscount = (discountType) => {
787
+ if (order_discount_details == null) {
788
+ return;
789
+ }
790
+ const appliedOfferId = discountType === 'loyalty'
791
+ ? order_discount_details.loyalty_discount_id
792
+ : order_discount_details.voucher_discount_id;
793
+ const normalizedAppliedOfferId = getNormalizedOfferId(appliedOfferId);
794
+ if (normalizedAppliedOfferId != null) {
795
+ removedOfferIds.add(normalizedAppliedOfferId);
796
+ }
797
+ if (discountType === 'loyalty') {
798
+ order_discount_details = {
799
+ ...order_discount_details,
800
+ loyalty_discount_id: undefined,
801
+ loyalty_discount_name: undefined,
802
+ loyalty_discount: undefined,
803
+ is_loyalty_discount_percentage: false,
804
+ loyalty_reference_number: undefined,
805
+ };
806
+ }
807
+ else {
808
+ order_discount_details = {
809
+ ...order_discount_details,
810
+ voucher_discount_id: undefined,
811
+ voucher_discount_name: undefined,
812
+ voucher_discount: undefined,
813
+ is_voucher_discount_percentage: false,
814
+ };
815
+ }
816
+ hasChanges = true;
817
+ };
818
+ if (order_discount_details != null) {
819
+ const loyaltyDiscountId = order_discount_details.loyalty_discount_id;
820
+ if (loyaltyDiscountId != null) {
821
+ if (loyaltyDiscountId !== constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID) {
822
+ const loyaltyOffer = syncContext.offers.find((o) => o._id === loyaltyDiscountId);
823
+ // Preserve non-offer loyalty discounts (e.g. gift-card discount IDs).
824
+ if (loyaltyOffer != null) {
825
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
826
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
827
+ if (!hasRedeemedEntryForLoyalty) {
828
+ clearOrderLevelDiscount('loyalty');
829
+ }
830
+ else if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
831
+ clearOrderLevelDiscount('loyalty');
832
+ }
833
+ else {
834
+ if (loyaltyOffer.reward_discount != null) {
835
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = loyaltyOffer.reward_discount;
836
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
837
+ ? calculateEligibleOfferDiscountDetails(categories, excluded_refs)
838
+ : {
839
+ subtotal: orderLevelDiscountBaseAmount,
840
+ hasExcludedRefs: false,
841
+ };
842
+ if (hasExcludedRefs && !is_discount_percentage) {
843
+ clearOrderLevelDiscount('loyalty');
844
+ }
845
+ else {
846
+ const hasRelevantCap = is_discount_percentage &&
847
+ max_discount_amount != null &&
848
+ Number.isFinite(max_discount_amount) &&
849
+ max_discount_amount >= 0;
850
+ const hasRelevantPercentageCap = !is_discount_percentage &&
851
+ max_discount_percentage != null &&
852
+ Number.isFinite(max_discount_percentage) &&
853
+ max_discount_percentage >= 0;
854
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
855
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
856
+ if (shouldNormalizeToStatic) {
857
+ if (discountBaseAmount <= 0) {
858
+ clearOrderLevelDiscount('loyalty');
859
+ }
860
+ else {
861
+ const calculatedDiscount = (0, utils_1.getCappedOfferDiscountAmount)({
862
+ baseAmount: discountBaseAmount,
863
+ discountValue: discount_value,
864
+ isDiscountPercentage: is_discount_percentage,
865
+ maxDiscountAmount: max_discount_amount,
866
+ maxDiscountPercentage: max_discount_percentage,
867
+ });
868
+ order_discount_details = {
869
+ ...order_discount_details,
870
+ loyalty_discount: (0, utils_1.parseNum)(calculatedDiscount),
871
+ is_loyalty_discount_percentage: false,
872
+ };
873
+ hasChanges = true;
874
+ }
875
+ }
876
+ }
877
+ }
878
+ unlockedOffersMap[loyaltyDiscountId] -= 1;
879
+ }
880
+ }
881
+ }
882
+ }
883
+ const voucherDiscountId = order_discount_details.voucher_discount_id;
884
+ if (voucherDiscountId != null) {
885
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
886
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
887
+ if (!hasRedeemedEntryForVoucher) {
888
+ clearOrderLevelDiscount('voucher');
889
+ }
890
+ else if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
891
+ clearOrderLevelDiscount('voucher');
892
+ }
893
+ else {
894
+ const voucherOffer = syncContext.offers.find((o) => o._id === voucherDiscountId);
895
+ if (voucherOffer?.reward_discount != null) {
896
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = voucherOffer.reward_discount;
897
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
898
+ ? calculateEligibleOfferDiscountDetails(categories, excluded_refs)
899
+ : {
900
+ subtotal: orderLevelDiscountBaseAmount,
901
+ hasExcludedRefs: false,
902
+ };
903
+ if (hasExcludedRefs && !is_discount_percentage) {
904
+ clearOrderLevelDiscount('voucher');
905
+ }
906
+ else {
907
+ const hasRelevantCap = is_discount_percentage &&
908
+ max_discount_amount != null &&
909
+ Number.isFinite(max_discount_amount) &&
910
+ max_discount_amount >= 0;
911
+ const hasRelevantPercentageCap = !is_discount_percentage &&
912
+ max_discount_percentage != null &&
913
+ Number.isFinite(max_discount_percentage) &&
914
+ max_discount_percentage >= 0;
915
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
916
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
917
+ if (shouldNormalizeToStatic) {
918
+ if (discountBaseAmount <= 0) {
919
+ clearOrderLevelDiscount('voucher');
920
+ }
921
+ else {
922
+ const calculatedDiscount = (0, utils_1.getCappedOfferDiscountAmount)({
923
+ baseAmount: discountBaseAmount,
924
+ discountValue: discount_value,
925
+ isDiscountPercentage: is_discount_percentage,
926
+ maxDiscountAmount: max_discount_amount,
927
+ maxDiscountPercentage: max_discount_percentage,
928
+ });
929
+ order_discount_details = {
930
+ ...order_discount_details,
931
+ voucher_discount: (0, utils_1.parseNum)(calculatedDiscount),
932
+ is_voucher_discount_percentage: false,
933
+ };
934
+ hasChanges = true;
935
+ }
936
+ }
937
+ }
938
+ }
939
+ unlockedOffersMap[voucherDiscountId] -= 1;
940
+ }
941
+ }
541
942
  }
542
- const walletRedemptionAmount = Number(walletRedemptions?.cashback_amount ?? 0);
543
- return Number.isFinite(walletRedemptionAmount) && walletRedemptionAmount > 0 ? walletRedemptionAmount : 0;
544
- }
545
- function getSyncedWalletCashbackOrderDiscountDetails({ orderDiscountDetails, walletCashbackAmount, }) {
546
- if (orderDiscountDetails == null) {
547
- return orderDiscountDetails;
943
+ const newCategories = [];
944
+ for (let i = 0; i < categories.length; i++) {
945
+ const category = categories[i];
946
+ const newItems = [];
947
+ for (let j = 0; j < category.items.length; j++) {
948
+ const item = category.items[j];
949
+ if (item.item_discount_details != null) {
950
+ const loyaltyDiscountId = item.item_discount_details.loyalty_discount_id;
951
+ if (loyaltyDiscountId != null) {
952
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
953
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
954
+ if (!hasRedeemedEntryForLoyalty) {
955
+ hasChanges = true;
956
+ if (normalizedLoyaltyDiscountId != null) {
957
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
958
+ }
959
+ continue;
960
+ }
961
+ if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
962
+ hasChanges = true;
963
+ if (normalizedLoyaltyDiscountId != null) {
964
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
965
+ }
966
+ continue;
967
+ }
968
+ unlockedOffersMap[loyaltyDiscountId] -= toPositiveInteger(item.quantity, 1);
969
+ }
970
+ const voucherDiscountId = item.item_discount_details.voucher_discount_id;
971
+ if (voucherDiscountId != null) {
972
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
973
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
974
+ if (!hasRedeemedEntryForVoucher) {
975
+ hasChanges = true;
976
+ if (normalizedVoucherDiscountId != null) {
977
+ removedOfferIds.add(normalizedVoucherDiscountId);
978
+ }
979
+ continue;
980
+ }
981
+ if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
982
+ hasChanges = true;
983
+ if (normalizedVoucherDiscountId != null) {
984
+ removedOfferIds.add(normalizedVoucherDiscountId);
985
+ }
986
+ continue;
987
+ }
988
+ unlockedOffersMap[voucherDiscountId] -= toPositiveInteger(item.quantity, 1);
989
+ }
990
+ }
991
+ newItems.push(item);
992
+ }
993
+ newCategories.push({
994
+ ...category,
995
+ items: newItems,
996
+ });
548
997
  }
549
- if (walletCashbackAmount <= 0) {
550
- return {
551
- ...orderDiscountDetails,
552
- special_discount_id: undefined,
553
- special_discount_name: undefined,
554
- special_discount: undefined,
555
- is_special_discount_percentage: false,
556
- special_reference_number: undefined,
557
- total_discount: 0,
558
- };
998
+ const reconciledRedeemedOffers = getReconciledRedeemedOffersMapForOfferSync({
999
+ existingRedeemedOffers: redeemed_offers,
1000
+ categories: newCategories,
1001
+ offers: syncContext.offers,
1002
+ removedOfferIds,
1003
+ unlockedOffersApplicableTimes: syncContext.unlockedOffersApplicableTimes,
1004
+ });
1005
+ if (!areRedeemedOffersEqualForOfferSync(redeemed_offers, reconciledRedeemedOffers)) {
1006
+ redeemed_offers = reconciledRedeemedOffers;
1007
+ hasChanges = true;
1008
+ }
1009
+ if (!hasChanges) {
1010
+ return null;
559
1011
  }
560
1012
  return {
561
- ...orderDiscountDetails,
562
- special_discount_id: constants_1.WALLET_CASHBACK_SPECIAL_DISCOUNT_ID,
563
- special_discount: (0, utils_1.parseNum)(walletCashbackAmount),
564
- is_special_discount_percentage: false,
1013
+ ...data,
1014
+ categories: newCategories,
1015
+ order_discount_details,
1016
+ redeemed_offers,
565
1017
  };
566
1018
  }
567
- function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calculateItemMetadata) {
1019
+ function hasItemLevelLoyaltyDiscountForId(categories, discountId) {
1020
+ for (let categoryIndex = 0; categoryIndex < categories.length; categoryIndex++) {
1021
+ const items = categories[categoryIndex].items;
1022
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
1023
+ if (items[itemIndex].item_discount_details?.loyalty_discount_id === discountId) {
1024
+ return true;
1025
+ }
1026
+ }
1027
+ }
1028
+ return false;
1029
+ }
1030
+ function getSyncedWalletRedemptionsAfterGiftCardItemRewardCleanup({ walletRedemptions, orderDiscountDetails, categories, }) {
1031
+ const claimedGiftCardId = walletRedemptions?.gift_cards?.gift_card_id?.trim();
1032
+ const claimedTimes = Number(walletRedemptions?.gift_cards?.value_redeemed ?? 0);
1033
+ if (claimedGiftCardId == null ||
1034
+ claimedGiftCardId.length === 0 ||
1035
+ !Number.isFinite(claimedTimes) ||
1036
+ claimedTimes <= 0) {
1037
+ return walletRedemptions;
1038
+ }
1039
+ const rewardType = walletRedemptions?.gift_cards?.mystery_gift_type;
1040
+ const isItemRewardType = rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.ITEMS || rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.DISCOUNT_ITEMS;
1041
+ if (!isItemRewardType) {
1042
+ return walletRedemptions;
1043
+ }
1044
+ const hasOrderLevelDiscount = getNormalizedOfferId(orderDiscountDetails?.loyalty_discount_id) === claimedGiftCardId;
1045
+ const hasItemLevelDiscount = hasItemLevelLoyaltyDiscountForId(categories, claimedGiftCardId);
1046
+ if (hasOrderLevelDiscount || hasItemLevelDiscount) {
1047
+ return walletRedemptions;
1048
+ }
1049
+ return getWalletRedemptionsMap({
1050
+ ...walletRedemptions,
1051
+ gift_cards: undefined,
1052
+ });
1053
+ }
1054
+ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calculateItemMetadata, syncContext) {
1055
+ if (syncContext?.offers != null && syncContext.unlockedOffersApplicableTimes != null) {
1056
+ const offerSynchronizedData = getOfferSynchronizedCartDataForCalculation({
1057
+ data,
1058
+ syncContext,
1059
+ });
1060
+ if (offerSynchronizedData != null) {
1061
+ return calculateCartOrderInfoAndSyncData(offerSynchronizedData, courses, listnerSettings, calculateItemMetadata);
1062
+ }
1063
+ }
568
1064
  const isCompleted = data.order_status === constants_1.ORDER_STATUS_ENUM.COMPLETED;
569
1065
  /* ===============================><=============================== */
570
1066
  let subtotal = 0;
571
1067
  let totalItemsDiscount = 0;
572
1068
  const categories = [];
1069
+ let syncedRedeemedOffers = getRedeemedOffersMap(data.redeemed_offers);
1070
+ let syncedWalletRedemptions = getWalletRedemptionsMap(data.wallet_redemptions);
573
1071
  const length = data.categories?.length ?? 0;
574
1072
  for (let c = 0; c < length; c++) {
575
1073
  const category = data.categories[c];
@@ -577,7 +1075,15 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
577
1075
  const itemsLength = category.items.length;
578
1076
  for (let i = 0; i < itemsLength; i++) {
579
1077
  const item = category.items[i];
580
- const { itemSubtotal, item_discount_details } = calculateItemTotalWithTax(item);
1078
+ const syncedItemDiscountDetails = getSyncedItemDiscountDetailsWithoutRewardSpecialDiscount({
1079
+ itemDiscountDetails: item.item_discount_details,
1080
+ redeemedOffers: syncedRedeemedOffers,
1081
+ walletRedemptions: syncedWalletRedemptions,
1082
+ });
1083
+ const { itemSubtotal, item_discount_details } = calculateItemTotalWithTax({
1084
+ ...item,
1085
+ item_discount_details: syncedItemDiscountDetails ?? null,
1086
+ });
581
1087
  const newItem = {
582
1088
  ...item,
583
1089
  is_ready: item.is_ready || isCompleted,
@@ -602,11 +1108,14 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
602
1108
  });
603
1109
  }
604
1110
  let syncedOrderDiscountDetails = data.order_discount_details;
605
- let syncedRedeemedOffers = getRedeemedOffersMap(data.redeemed_offers);
606
- let syncedWalletRedemptions = getWalletRedemptionsMap(data.wallet_redemptions);
607
- const hasWalletCashbackSpecialDiscount = isWalletCashbackSpecialDiscount(syncedOrderDiscountDetails);
1111
+ syncedOrderDiscountDetails = getSyncedOrderDiscountDetailsWithoutRewardSpecialDiscount({
1112
+ orderDiscountDetails: syncedOrderDiscountDetails,
1113
+ redeemedOffers: syncedRedeemedOffers,
1114
+ walletRedemptions: syncedWalletRedemptions,
1115
+ });
1116
+ const hasWalletCashbackLoyaltyDiscount = isWalletCashbackLoyaltyDiscount(syncedOrderDiscountDetails);
608
1117
  const hasWalletCashbackMetadata = Number(syncedWalletRedemptions?.cashback_amount ?? 0) > 0;
609
- if (hasWalletCashbackSpecialDiscount) {
1118
+ if (hasWalletCashbackLoyaltyDiscount) {
610
1119
  const requestedWalletCashbackAmount = getWalletCashbackAmountFromOrderData({
611
1120
  orderDiscountDetails: syncedOrderDiscountDetails,
612
1121
  walletRedemptions: syncedWalletRedemptions,
@@ -629,26 +1138,18 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
629
1138
  cashback_amount: undefined,
630
1139
  });
631
1140
  }
632
- const hasNonWalletSpecialDiscount = syncedOrderDiscountDetails?.special_discount_id != null &&
633
- syncedOrderDiscountDetails.special_discount_id !== constants_1.WALLET_CASHBACK_SPECIAL_DISCOUNT_ID;
1141
+ syncedWalletRedemptions = getSyncedWalletRedemptionsAfterGiftCardItemRewardCleanup({
1142
+ walletRedemptions: syncedWalletRedemptions,
1143
+ orderDiscountDetails: syncedOrderDiscountDetails,
1144
+ categories,
1145
+ });
634
1146
  const walletGiftCardRedeemedTimes = Number(syncedWalletRedemptions?.gift_cards?.value_redeemed ?? 0);
635
1147
  const hasWalletGiftCardMetadata = syncedWalletRedemptions?.gift_cards?.gift_card_id != null &&
636
1148
  syncedWalletRedemptions.gift_cards.gift_card_id.trim().length > 0 &&
637
1149
  Number.isFinite(walletGiftCardRedeemedTimes) &&
638
1150
  walletGiftCardRedeemedTimes > 0;
639
- // Empty carts must not retain non-wallet special discounts or gift-card wallet claims.
1151
+ // Empty carts must not retain offer-redemption state or gift-card wallet claims.
640
1152
  if (subtotal <= 0) {
641
- if (hasNonWalletSpecialDiscount && syncedOrderDiscountDetails != null) {
642
- syncedOrderDiscountDetails = {
643
- ...syncedOrderDiscountDetails,
644
- special_discount_id: undefined,
645
- special_discount_name: undefined,
646
- special_discount: undefined,
647
- is_special_discount_percentage: false,
648
- special_reference_number: undefined,
649
- total_discount: 0,
650
- };
651
- }
652
1153
  if (syncedRedeemedOffers != null) {
653
1154
  syncedRedeemedOffers = null;
654
1155
  }
@@ -660,7 +1161,18 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
660
1161
  }
661
1162
  }
662
1163
  const applyGSTOnOriginalPrice = data.exclude_discount_from_gst;
663
- const order_discount_details = getDiscountDetails(syncedOrderDiscountDetails, subtotal);
1164
+ const previousOrderDiscountDetails = syncedOrderDiscountDetails;
1165
+ const order_discount_details = getDiscountDetails(previousOrderDiscountDetails, subtotal);
1166
+ syncedRedeemedOffers = getSyncedRedeemedOffersAfterOrderDiscountOverflowCleanup({
1167
+ redeemedOffers: syncedRedeemedOffers,
1168
+ previousOrderDiscountDetails,
1169
+ nextOrderDiscountDetails: order_discount_details,
1170
+ });
1171
+ syncedWalletRedemptions = getSyncedWalletRedemptionsAfterOrderDiscountOverflowCleanup({
1172
+ walletRedemptions: syncedWalletRedemptions,
1173
+ previousOrderDiscountDetails,
1174
+ nextOrderDiscountDetails: order_discount_details,
1175
+ });
664
1176
  // This can be both negative or positive
665
1177
  const orderDiscount = order_discount_details?.total_discount ?? 0;
666
1178
  // However total order discount can never be negative
@@ -913,6 +1425,41 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
913
1425
  }
914
1426
  return syncedData;
915
1427
  }
1428
+ function getOrderDataWithSyncedWalletGiftCardClaim({ data, walletGiftCardClaim, }) {
1429
+ if (walletGiftCardClaim == null) {
1430
+ return data;
1431
+ }
1432
+ const claimedGiftCardId = walletGiftCardClaim.giftCardId?.toString().trim();
1433
+ if (claimedGiftCardId == null || claimedGiftCardId.length === 0) {
1434
+ return data;
1435
+ }
1436
+ const normalizedWalletRedemptions = getWalletRedemptionsMap(data.wallet_redemptions);
1437
+ const currentClaimGiftCardId = normalizedWalletRedemptions?.gift_cards?.gift_card_id?.trim();
1438
+ const currentClaimCount = toPositiveInteger(normalizedWalletRedemptions?.gift_cards?.value_redeemed, 0);
1439
+ const hasExistingClaimForGiftCard = currentClaimGiftCardId === claimedGiftCardId && currentClaimCount > 0;
1440
+ if (hasExistingClaimForGiftCard) {
1441
+ return data;
1442
+ }
1443
+ const nextWalletRedemptions = getWalletRedemptionsMap({
1444
+ ...(normalizedWalletRedemptions ?? {}),
1445
+ gift_cards: {
1446
+ gift_card_id: claimedGiftCardId,
1447
+ value_redeemed: 1,
1448
+ ...(walletGiftCardClaim.mysteryGiftType != null
1449
+ ? {
1450
+ mystery_gift_type: walletGiftCardClaim.mysteryGiftType,
1451
+ }
1452
+ : {}),
1453
+ },
1454
+ });
1455
+ if ((0, lodash_1.isEqual)(nextWalletRedemptions, normalizedWalletRedemptions)) {
1456
+ return data;
1457
+ }
1458
+ return {
1459
+ ...data,
1460
+ wallet_redemptions: nextWalletRedemptions,
1461
+ };
1462
+ }
916
1463
  const getOrderItemComaparableData = (item) => ({
917
1464
  item_id: item.item_id,
918
1465
  menu_id: item.menu_id,
@@ -945,7 +1492,7 @@ function getAddItemToCartData(data, payload, courses, listnerSettings) {
945
1492
  modifiers: item.modifiers,
946
1493
  };
947
1494
  };
948
- const { category_id, name, item, chosen_course_id, replace_id } = payload;
1495
+ const { category_id, name, item, chosen_course_id, replace_id, walletGiftCardClaim } = payload;
949
1496
  const comparableItem = getComparableItem(item);
950
1497
  let mainItemId = item._id;
951
1498
  const orderData = { ...data };
@@ -1107,7 +1654,11 @@ function getAddItemToCartData(data, payload, courses, listnerSettings) {
1107
1654
  ...(iterations.length > 0 && { iterations }),
1108
1655
  categories,
1109
1656
  };
1110
- const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
1657
+ const orderWithSyncedWalletGiftCardClaim = getOrderDataWithSyncedWalletGiftCardClaim({
1658
+ data: order,
1659
+ walletGiftCardClaim,
1660
+ });
1661
+ const newData = calculateCartOrderInfoAndSyncData(orderWithSyncedWalletGiftCardClaim, courses, listnerSettings);
1111
1662
  return newData;
1112
1663
  }
1113
1664
  function getSplitCartItemToTwo({ data, orderItemId, courses, listnerSettings }) {
@@ -2216,6 +2767,13 @@ function getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds
2216
2767
  const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2217
2768
  return newData;
2218
2769
  }
2770
+ function getClearVoucherCodeAndOffersFromCartData(data, courses, listnerSettings, offerIds) {
2771
+ const orderWithoutOffers = getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds);
2772
+ const nextOrderDiscountDetails = (0, offers_helpers_1.buildClearVoucherDiscountDetails)(orderWithoutOffers.order_discount_details);
2773
+ return getUpdateCartInfoData(orderWithoutOffers, {
2774
+ order_discount_details: nextOrderDiscountDetails,
2775
+ }, courses, listnerSettings);
2776
+ }
2219
2777
  // ================================><================================= //
2220
2778
  /**
2221
2779
  * Calculate the eligible subtotal by excluding items/categories in excluded_refs