@managesome/eposmatic-toolkit 0.2.317 → 0.2.319

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;
@@ -478,19 +480,32 @@ function getWalletRedemptionsMap(walletRedemptions) {
478
480
  if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
479
481
  normalized.cashback_amount = cashbackAmount;
480
482
  }
481
- const giftCardRedemption = walletRedemptions.gift_cards;
482
- if (giftCardRedemption != null) {
483
- const giftCardId = giftCardRedemption.gift_card_id?.toString().trim();
484
- const valueRedeemed = Number(giftCardRedemption.value_redeemed);
485
- if (giftCardId != null && giftCardId.length > 0 && Number.isFinite(valueRedeemed) && valueRedeemed > 0) {
486
- normalized.gift_cards = {
483
+ const giftCardRedemptions = walletRedemptions.gift_cards;
484
+ if (Array.isArray(giftCardRedemptions)) {
485
+ const normalizedGiftCardRedemptionsMap = {};
486
+ for (let i = 0; i < giftCardRedemptions.length; i++) {
487
+ const giftCardRedemption = giftCardRedemptions[i];
488
+ const giftCardId = giftCardRedemption.gift_card_id?.toString().trim();
489
+ const legacyValueRedeemed = giftCardRedemption.value_redeemed;
490
+ const redeemedTimes = toPositiveInteger(giftCardRedemption.redeemed_times ?? legacyValueRedeemed, 0);
491
+ if (giftCardId == null || giftCardId.length === 0 || redeemedTimes <= 0) {
492
+ continue;
493
+ }
494
+ const existingRedemption = normalizedGiftCardRedemptionsMap[giftCardId];
495
+ normalizedGiftCardRedemptionsMap[giftCardId] = {
487
496
  gift_card_id: giftCardId,
488
- value_redeemed: valueRedeemed,
497
+ redeemed_times: (existingRedemption?.redeemed_times ?? 0) + redeemedTimes,
489
498
  ...(giftCardRedemption.mystery_gift_type != null
490
499
  ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
491
- : {}),
500
+ : existingRedemption?.mystery_gift_type != null
501
+ ? { mystery_gift_type: existingRedemption.mystery_gift_type }
502
+ : {}),
492
503
  };
493
504
  }
505
+ const normalizedGiftCardRedemptions = Object.values(normalizedGiftCardRedemptionsMap);
506
+ if (normalizedGiftCardRedemptions.length > 0) {
507
+ normalized.gift_cards = normalizedGiftCardRedemptions;
508
+ }
494
509
  }
495
510
  return Object.keys(normalized).length > 0 ? normalized : null;
496
511
  }
@@ -503,17 +518,23 @@ function getSyncedWalletRedemptionsAfterOrderDiscountOverflowCleanup({ walletRed
503
518
  if (previousLoyaltyDiscountId == null || previousLoyaltyDiscountId === nextLoyaltyDiscountId) {
504
519
  return walletRedemptions;
505
520
  }
506
- const walletGiftCardDiscountId = getNormalizedOfferId(walletRedemptions?.gift_cards?.gift_card_id);
521
+ const normalizedWalletRedemptions = getWalletRedemptionsMap(walletRedemptions);
522
+ const normalizedGiftCardRedemptions = normalizedWalletRedemptions?.gift_cards ?? [];
523
+ const filteredGiftCardRedemptions = normalizedGiftCardRedemptions.filter((giftCardRedemption) => getNormalizedOfferId(giftCardRedemption.gift_card_id) !== previousLoyaltyDiscountId);
507
524
  const shouldClearWalletCashback = previousLoyaltyDiscountId === constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID &&
508
525
  Number(walletRedemptions.cashback_amount ?? 0) > 0;
509
- const shouldClearGiftCardRedemption = walletGiftCardDiscountId != null && walletGiftCardDiscountId === previousLoyaltyDiscountId;
526
+ const shouldClearGiftCardRedemption = filteredGiftCardRedemptions.length !== normalizedGiftCardRedemptions.length;
510
527
  if (!shouldClearWalletCashback && !shouldClearGiftCardRedemption) {
511
528
  return walletRedemptions;
512
529
  }
513
530
  return getWalletRedemptionsMap({
514
- ...walletRedemptions,
531
+ ...(normalizedWalletRedemptions ?? {}),
515
532
  ...(shouldClearWalletCashback ? { cashback_amount: undefined } : {}),
516
- ...(shouldClearGiftCardRedemption ? { gift_cards: undefined } : {}),
533
+ ...(shouldClearGiftCardRedemption
534
+ ? {
535
+ gift_cards: filteredGiftCardRedemptions.length > 0 ? filteredGiftCardRedemptions : undefined,
536
+ }
537
+ : {}),
517
538
  });
518
539
  }
519
540
  function clearSpecialDiscountFields(orderDiscountDetails) {
@@ -536,8 +557,10 @@ function getSyncedOrderDiscountDetailsWithoutRewardSpecialDiscount({ orderDiscou
536
557
  return orderDiscountDetails;
537
558
  }
538
559
  const hasRedeemedOfferForSpecialDiscount = redeemedOffers?.[normalizedSpecialDiscountId] != null;
539
- const normalizedGiftCardId = getNormalizedOfferId(walletRedemptions?.gift_cards?.gift_card_id);
540
- const isGiftCardRewardDiscount = normalizedGiftCardId != null && normalizedGiftCardId === normalizedSpecialDiscountId;
560
+ const normalizedGiftCardIds = (walletRedemptions?.gift_cards ?? [])
561
+ .map((giftCardRedemption) => getNormalizedOfferId(giftCardRedemption.gift_card_id))
562
+ .filter((giftCardId) => giftCardId != null);
563
+ const isGiftCardRewardDiscount = normalizedGiftCardIds.includes(normalizedSpecialDiscountId);
541
564
  const isWalletCashbackRewardDiscount = normalizedSpecialDiscountId === constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID;
542
565
  const isRewardLinkedSpecialDiscount = hasRedeemedOfferForSpecialDiscount || isGiftCardRewardDiscount || isWalletCashbackRewardDiscount;
543
566
  if (!isRewardLinkedSpecialDiscount) {
@@ -598,11 +621,478 @@ function getSyncedWalletCashbackOrderDiscountDetails({ orderDiscountDetails, wal
598
621
  return {
599
622
  ...orderDiscountDetails,
600
623
  loyalty_discount_id: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID,
624
+ loyalty_discount_name: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_NAME,
601
625
  loyalty_discount: (0, utils_1.parseNum)(walletCashbackAmount),
602
626
  is_loyalty_discount_percentage: false,
627
+ loyalty_reference_number: constants_1.WALLET_CASHBACK_LOYALTY_REFERENCE,
628
+ };
629
+ }
630
+ function getOrderSubtotalFromCategoriesForOfferSync(categories) {
631
+ if (!categories?.length)
632
+ return 0;
633
+ let subtotal = 0;
634
+ for (let i = 0; i < categories.length; i++) {
635
+ const items = categories[i].items;
636
+ for (let j = 0; j < items.length; j++) {
637
+ subtotal += items[j].subtotal ?? 0;
638
+ }
639
+ }
640
+ return subtotal;
641
+ }
642
+ function isRedeemedOffersMapNormalizedForOfferSync(redeemedOffers) {
643
+ if (redeemedOffers == null) {
644
+ return true;
645
+ }
646
+ const normalizedRedeemedOffers = getRedeemedOffersMap(redeemedOffers);
647
+ const rawOfferIds = Object.keys(redeemedOffers);
648
+ const normalizedOfferIds = Object.keys(normalizedRedeemedOffers ?? {});
649
+ if (rawOfferIds.length !== normalizedOfferIds.length) {
650
+ return false;
651
+ }
652
+ for (let i = 0; i < rawOfferIds.length; i++) {
653
+ const rawOfferId = rawOfferIds[i];
654
+ const normalizedOfferId = getNormalizedOfferId(rawOfferId);
655
+ const safeCount = toPositiveInteger(redeemedOffers[rawOfferId], 0);
656
+ if (normalizedOfferId == null || rawOfferId !== normalizedOfferId || safeCount <= 0) {
657
+ return false;
658
+ }
659
+ if ((normalizedRedeemedOffers?.[normalizedOfferId] ?? 0) !== safeCount) {
660
+ return false;
661
+ }
662
+ }
663
+ return true;
664
+ }
665
+ function areRedeemedOffersEqualForOfferSync(currentRedeemedOffers, nextRedeemedOffers) {
666
+ const normalizedCurrentRedeemedOffers = getRedeemedOffersMap(currentRedeemedOffers);
667
+ const normalizedNextRedeemedOffers = getRedeemedOffersMap(nextRedeemedOffers);
668
+ if (normalizedCurrentRedeemedOffers == null || normalizedNextRedeemedOffers == null) {
669
+ return normalizedCurrentRedeemedOffers == null && normalizedNextRedeemedOffers == null;
670
+ }
671
+ const currentOfferIds = Object.keys(normalizedCurrentRedeemedOffers);
672
+ const nextOfferIds = Object.keys(normalizedNextRedeemedOffers);
673
+ if (currentOfferIds.length !== nextOfferIds.length) {
674
+ return false;
675
+ }
676
+ for (let i = 0; i < currentOfferIds.length; i++) {
677
+ const offerId = currentOfferIds[i];
678
+ if (normalizedCurrentRedeemedOffers[offerId] !== normalizedNextRedeemedOffers[offerId]) {
679
+ return false;
680
+ }
681
+ }
682
+ return true;
683
+ }
684
+ function getItemRewardApplicableQuantityForOfferSync(offer) {
685
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
686
+ return toPositiveInteger(offer.reward_items?.num_of_items, 1);
687
+ }
688
+ if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
689
+ return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
690
+ }
691
+ return null;
692
+ }
693
+ function getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, offerId) {
694
+ let totalSelectedOfferItems = 0;
695
+ for (let i = 0; i < categories.length; i++) {
696
+ const category = categories[i];
697
+ for (let j = 0; j < category.items.length; j++) {
698
+ const item = category.items[j];
699
+ const discountDetails = item.item_discount_details;
700
+ if (discountDetails == null)
701
+ continue;
702
+ const loyaltyDiscountId = getNormalizedOfferId(discountDetails.loyalty_discount_id);
703
+ const voucherDiscountId = getNormalizedOfferId(discountDetails.voucher_discount_id);
704
+ if (loyaltyDiscountId !== offerId && voucherDiscountId !== offerId)
705
+ continue;
706
+ totalSelectedOfferItems += toPositiveInteger(item.quantity, 0);
707
+ }
708
+ }
709
+ return totalSelectedOfferItems;
710
+ }
711
+ function getReconciledRedeemedOffersMapForOfferSync({ existingRedeemedOffers, categories, offers, removedOfferIds, unlockedOffersApplicableTimes, }) {
712
+ const nextRedeemedOffers = {
713
+ ...(getRedeemedOffersMap(existingRedeemedOffers) ?? {}),
714
+ };
715
+ const removedIds = Array.from(removedOfferIds);
716
+ for (let i = 0; i < removedIds.length; i++) {
717
+ const normalizedOfferId = getNormalizedOfferId(removedIds[i]);
718
+ if (normalizedOfferId == null)
719
+ continue;
720
+ delete nextRedeemedOffers[normalizedOfferId];
721
+ }
722
+ for (let i = 0; i < offers.length; i++) {
723
+ const offer = offers[i];
724
+ const normalizedOfferId = getNormalizedOfferId(offer._id);
725
+ if (normalizedOfferId == null)
726
+ continue;
727
+ const applicableQuantity = getItemRewardApplicableQuantityForOfferSync(offer);
728
+ if (applicableQuantity != null) {
729
+ const selectedItemsCount = getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, normalizedOfferId);
730
+ // Any partial usage of an item reward still counts as one redeemed slot.
731
+ const redeemedTimes = selectedItemsCount > 0 ? Math.ceil(selectedItemsCount / applicableQuantity) : 0;
732
+ if (redeemedTimes > 0) {
733
+ nextRedeemedOffers[normalizedOfferId] = redeemedTimes;
734
+ }
735
+ else {
736
+ delete nextRedeemedOffers[normalizedOfferId];
737
+ }
738
+ continue;
739
+ }
740
+ const existingRedeemedTimes = toPositiveInteger(nextRedeemedOffers[normalizedOfferId], 0);
741
+ if (existingRedeemedTimes <= 0) {
742
+ delete nextRedeemedOffers[normalizedOfferId];
743
+ continue;
744
+ }
745
+ const maxApplicableTimes = toPositiveInteger(unlockedOffersApplicableTimes?.[offer._id], 0);
746
+ if (maxApplicableTimes <= 0) {
747
+ // Keep non-item claim history when unlock context is temporarily unavailable.
748
+ nextRedeemedOffers[normalizedOfferId] = existingRedeemedTimes;
749
+ continue;
750
+ }
751
+ nextRedeemedOffers[normalizedOfferId] = Math.min(existingRedeemedTimes, maxApplicableTimes);
752
+ }
753
+ return getRedeemedOffersMap(nextRedeemedOffers);
754
+ }
755
+ function getOfferSynchronizedCartDataForCalculation({ data, syncContext, }) {
756
+ const unlockedOffersMap = {
757
+ ...syncContext.unlockedOffersApplicableTimes,
758
+ };
759
+ const removedOfferIds = new Set();
760
+ let hasChanges = false;
761
+ const categories = data.categories ?? [];
762
+ const orderLevelDiscountBaseAmount = getOrderSubtotalFromCategoriesForOfferSync(categories);
763
+ let order_discount_details = data.order_discount_details;
764
+ let redeemed_offers = getRedeemedOffersMap(data.redeemed_offers);
765
+ if (!isRedeemedOffersMapNormalizedForOfferSync(data.redeemed_offers)) {
766
+ hasChanges = true;
767
+ }
768
+ const hasOrderLevelLoyaltyDiscount = order_discount_details?.loyalty_discount_id != null;
769
+ const hasOrderLevelVoucherDiscount = order_discount_details?.voucher_discount_id != null;
770
+ // Empty carts should not keep offer-driven discount slots or redeemed-offers state.
771
+ if (orderLevelDiscountBaseAmount <= 0) {
772
+ if (hasOrderLevelLoyaltyDiscount && order_discount_details != null) {
773
+ order_discount_details = {
774
+ ...order_discount_details,
775
+ loyalty_discount_id: undefined,
776
+ loyalty_discount_name: undefined,
777
+ loyalty_discount: undefined,
778
+ is_loyalty_discount_percentage: false,
779
+ loyalty_reference_number: undefined,
780
+ total_discount: 0,
781
+ };
782
+ hasChanges = true;
783
+ }
784
+ if (hasOrderLevelVoucherDiscount && order_discount_details != null) {
785
+ order_discount_details = {
786
+ ...order_discount_details,
787
+ voucher_discount_id: undefined,
788
+ voucher_discount_name: undefined,
789
+ voucher_discount: undefined,
790
+ is_voucher_discount_percentage: false,
791
+ total_discount: 0,
792
+ };
793
+ hasChanges = true;
794
+ }
795
+ if (redeemed_offers != null) {
796
+ redeemed_offers = null;
797
+ hasChanges = true;
798
+ }
799
+ }
800
+ const redeemedOffersPresenceMap = getReconciledRedeemedOffersMapForOfferSync({
801
+ existingRedeemedOffers: redeemed_offers,
802
+ categories,
803
+ offers: syncContext.offers,
804
+ removedOfferIds: new Set(),
805
+ unlockedOffersApplicableTimes: syncContext.unlockedOffersApplicableTimes,
806
+ });
807
+ const clearOrderLevelDiscount = (discountType) => {
808
+ if (order_discount_details == null) {
809
+ return;
810
+ }
811
+ const appliedOfferId = discountType === 'loyalty'
812
+ ? order_discount_details.loyalty_discount_id
813
+ : order_discount_details.voucher_discount_id;
814
+ const normalizedAppliedOfferId = getNormalizedOfferId(appliedOfferId);
815
+ if (normalizedAppliedOfferId != null) {
816
+ removedOfferIds.add(normalizedAppliedOfferId);
817
+ }
818
+ if (discountType === 'loyalty') {
819
+ order_discount_details = {
820
+ ...order_discount_details,
821
+ loyalty_discount_id: undefined,
822
+ loyalty_discount_name: undefined,
823
+ loyalty_discount: undefined,
824
+ is_loyalty_discount_percentage: false,
825
+ loyalty_reference_number: undefined,
826
+ };
827
+ }
828
+ else {
829
+ order_discount_details = {
830
+ ...order_discount_details,
831
+ voucher_discount_id: undefined,
832
+ voucher_discount_name: undefined,
833
+ voucher_discount: undefined,
834
+ is_voucher_discount_percentage: false,
835
+ };
836
+ }
837
+ hasChanges = true;
838
+ };
839
+ if (order_discount_details != null) {
840
+ const loyaltyDiscountId = order_discount_details.loyalty_discount_id;
841
+ if (loyaltyDiscountId != null) {
842
+ if (loyaltyDiscountId !== constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID) {
843
+ const loyaltyOffer = syncContext.offers.find((o) => o._id === loyaltyDiscountId);
844
+ // Preserve non-offer loyalty discounts (e.g. gift-card discount IDs).
845
+ if (loyaltyOffer != null) {
846
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
847
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
848
+ if (!hasRedeemedEntryForLoyalty) {
849
+ clearOrderLevelDiscount('loyalty');
850
+ }
851
+ else if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
852
+ clearOrderLevelDiscount('loyalty');
853
+ }
854
+ else {
855
+ if (loyaltyOffer.reward_discount != null) {
856
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = loyaltyOffer.reward_discount;
857
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
858
+ ? calculateEligibleOfferDiscountDetails(categories, excluded_refs)
859
+ : {
860
+ subtotal: orderLevelDiscountBaseAmount,
861
+ hasExcludedRefs: false,
862
+ };
863
+ if (hasExcludedRefs && !is_discount_percentage) {
864
+ clearOrderLevelDiscount('loyalty');
865
+ }
866
+ else {
867
+ const hasRelevantCap = is_discount_percentage &&
868
+ max_discount_amount != null &&
869
+ Number.isFinite(max_discount_amount) &&
870
+ max_discount_amount >= 0;
871
+ const hasRelevantPercentageCap = !is_discount_percentage &&
872
+ max_discount_percentage != null &&
873
+ Number.isFinite(max_discount_percentage) &&
874
+ max_discount_percentage >= 0;
875
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
876
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
877
+ if (shouldNormalizeToStatic) {
878
+ if (discountBaseAmount <= 0) {
879
+ clearOrderLevelDiscount('loyalty');
880
+ }
881
+ else {
882
+ const calculatedDiscount = (0, utils_1.getCappedOfferDiscountAmount)({
883
+ baseAmount: discountBaseAmount,
884
+ discountValue: discount_value,
885
+ isDiscountPercentage: is_discount_percentage,
886
+ maxDiscountAmount: max_discount_amount,
887
+ maxDiscountPercentage: max_discount_percentage,
888
+ });
889
+ order_discount_details = {
890
+ ...order_discount_details,
891
+ loyalty_discount: (0, utils_1.parseNum)(calculatedDiscount),
892
+ is_loyalty_discount_percentage: false,
893
+ };
894
+ hasChanges = true;
895
+ }
896
+ }
897
+ }
898
+ }
899
+ unlockedOffersMap[loyaltyDiscountId] -= 1;
900
+ }
901
+ }
902
+ }
903
+ }
904
+ const voucherDiscountId = order_discount_details.voucher_discount_id;
905
+ if (voucherDiscountId != null) {
906
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
907
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
908
+ if (!hasRedeemedEntryForVoucher) {
909
+ clearOrderLevelDiscount('voucher');
910
+ }
911
+ else if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
912
+ clearOrderLevelDiscount('voucher');
913
+ }
914
+ else {
915
+ const voucherOffer = syncContext.offers.find((o) => o._id === voucherDiscountId);
916
+ if (voucherOffer?.reward_discount != null) {
917
+ const { discount_value, excluded_refs, is_discount_percentage, max_discount_amount, max_discount_percentage, } = voucherOffer.reward_discount;
918
+ const { subtotal: eligibleSubtotal, hasExcludedRefs } = excluded_refs != null && excluded_refs.length > 0
919
+ ? calculateEligibleOfferDiscountDetails(categories, excluded_refs)
920
+ : {
921
+ subtotal: orderLevelDiscountBaseAmount,
922
+ hasExcludedRefs: false,
923
+ };
924
+ if (hasExcludedRefs && !is_discount_percentage) {
925
+ clearOrderLevelDiscount('voucher');
926
+ }
927
+ else {
928
+ const hasRelevantCap = is_discount_percentage &&
929
+ max_discount_amount != null &&
930
+ Number.isFinite(max_discount_amount) &&
931
+ max_discount_amount >= 0;
932
+ const hasRelevantPercentageCap = !is_discount_percentage &&
933
+ max_discount_percentage != null &&
934
+ Number.isFinite(max_discount_percentage) &&
935
+ max_discount_percentage >= 0;
936
+ const shouldNormalizeToStatic = hasExcludedRefs || hasRelevantCap || hasRelevantPercentageCap;
937
+ const discountBaseAmount = hasExcludedRefs ? eligibleSubtotal : orderLevelDiscountBaseAmount;
938
+ if (shouldNormalizeToStatic) {
939
+ if (discountBaseAmount <= 0) {
940
+ clearOrderLevelDiscount('voucher');
941
+ }
942
+ else {
943
+ const calculatedDiscount = (0, utils_1.getCappedOfferDiscountAmount)({
944
+ baseAmount: discountBaseAmount,
945
+ discountValue: discount_value,
946
+ isDiscountPercentage: is_discount_percentage,
947
+ maxDiscountAmount: max_discount_amount,
948
+ maxDiscountPercentage: max_discount_percentage,
949
+ });
950
+ order_discount_details = {
951
+ ...order_discount_details,
952
+ voucher_discount: (0, utils_1.parseNum)(calculatedDiscount),
953
+ is_voucher_discount_percentage: false,
954
+ };
955
+ hasChanges = true;
956
+ }
957
+ }
958
+ }
959
+ }
960
+ unlockedOffersMap[voucherDiscountId] -= 1;
961
+ }
962
+ }
963
+ }
964
+ const newCategories = [];
965
+ for (let i = 0; i < categories.length; i++) {
966
+ const category = categories[i];
967
+ const newItems = [];
968
+ for (let j = 0; j < category.items.length; j++) {
969
+ const item = category.items[j];
970
+ if (item.item_discount_details != null) {
971
+ const loyaltyDiscountId = item.item_discount_details.loyalty_discount_id;
972
+ if (loyaltyDiscountId != null) {
973
+ const normalizedLoyaltyDiscountId = getNormalizedOfferId(loyaltyDiscountId);
974
+ const hasRedeemedEntryForLoyalty = normalizedLoyaltyDiscountId != null && (redeemedOffersPresenceMap?.[normalizedLoyaltyDiscountId] ?? 0) > 0;
975
+ if (!hasRedeemedEntryForLoyalty) {
976
+ hasChanges = true;
977
+ if (normalizedLoyaltyDiscountId != null) {
978
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
979
+ }
980
+ continue;
981
+ }
982
+ if (unlockedOffersMap[loyaltyDiscountId] == null || unlockedOffersMap[loyaltyDiscountId] <= 0) {
983
+ hasChanges = true;
984
+ if (normalizedLoyaltyDiscountId != null) {
985
+ removedOfferIds.add(normalizedLoyaltyDiscountId);
986
+ }
987
+ continue;
988
+ }
989
+ unlockedOffersMap[loyaltyDiscountId] -= toPositiveInteger(item.quantity, 1);
990
+ }
991
+ const voucherDiscountId = item.item_discount_details.voucher_discount_id;
992
+ if (voucherDiscountId != null) {
993
+ const normalizedVoucherDiscountId = getNormalizedOfferId(voucherDiscountId);
994
+ const hasRedeemedEntryForVoucher = normalizedVoucherDiscountId != null && (redeemedOffersPresenceMap?.[normalizedVoucherDiscountId] ?? 0) > 0;
995
+ if (!hasRedeemedEntryForVoucher) {
996
+ hasChanges = true;
997
+ if (normalizedVoucherDiscountId != null) {
998
+ removedOfferIds.add(normalizedVoucherDiscountId);
999
+ }
1000
+ continue;
1001
+ }
1002
+ if (unlockedOffersMap[voucherDiscountId] == null || unlockedOffersMap[voucherDiscountId] <= 0) {
1003
+ hasChanges = true;
1004
+ if (normalizedVoucherDiscountId != null) {
1005
+ removedOfferIds.add(normalizedVoucherDiscountId);
1006
+ }
1007
+ continue;
1008
+ }
1009
+ unlockedOffersMap[voucherDiscountId] -= toPositiveInteger(item.quantity, 1);
1010
+ }
1011
+ }
1012
+ newItems.push(item);
1013
+ }
1014
+ newCategories.push({
1015
+ ...category,
1016
+ items: newItems,
1017
+ });
1018
+ }
1019
+ const reconciledRedeemedOffers = getReconciledRedeemedOffersMapForOfferSync({
1020
+ existingRedeemedOffers: redeemed_offers,
1021
+ categories: newCategories,
1022
+ offers: syncContext.offers,
1023
+ removedOfferIds,
1024
+ unlockedOffersApplicableTimes: syncContext.unlockedOffersApplicableTimes,
1025
+ });
1026
+ if (!areRedeemedOffersEqualForOfferSync(redeemed_offers, reconciledRedeemedOffers)) {
1027
+ redeemed_offers = reconciledRedeemedOffers;
1028
+ hasChanges = true;
1029
+ }
1030
+ if (!hasChanges) {
1031
+ return null;
1032
+ }
1033
+ return {
1034
+ ...data,
1035
+ categories: newCategories,
1036
+ order_discount_details,
1037
+ redeemed_offers,
603
1038
  };
604
1039
  }
605
- function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calculateItemMetadata) {
1040
+ function hasItemLevelLoyaltyDiscountForId(categories, discountId) {
1041
+ for (let categoryIndex = 0; categoryIndex < categories.length; categoryIndex++) {
1042
+ const items = categories[categoryIndex].items;
1043
+ for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
1044
+ if (items[itemIndex].item_discount_details?.loyalty_discount_id === discountId) {
1045
+ return true;
1046
+ }
1047
+ }
1048
+ }
1049
+ return false;
1050
+ }
1051
+ function getSyncedWalletRedemptionsAfterGiftCardItemRewardCleanup({ walletRedemptions, orderDiscountDetails, categories, }) {
1052
+ const giftCardRedemptions = walletRedemptions?.gift_cards;
1053
+ if (!Array.isArray(giftCardRedemptions) || giftCardRedemptions.length === 0) {
1054
+ return walletRedemptions;
1055
+ }
1056
+ let hasRemovedGiftCardRedemptions = false;
1057
+ const nextGiftCardRedemptions = giftCardRedemptions.filter((giftCardRedemption) => {
1058
+ const claimedGiftCardId = giftCardRedemption.gift_card_id?.trim();
1059
+ const legacyValueRedeemed = giftCardRedemption.value_redeemed;
1060
+ const claimedTimes = toPositiveInteger(giftCardRedemption.redeemed_times ?? legacyValueRedeemed, 0);
1061
+ if (claimedGiftCardId == null || claimedGiftCardId.length === 0 || claimedTimes <= 0) {
1062
+ hasRemovedGiftCardRedemptions = true;
1063
+ return false;
1064
+ }
1065
+ const rewardType = giftCardRedemption.mystery_gift_type;
1066
+ const isItemRewardType = rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.ITEMS || rewardType === constants_1.GIFT_CARD_REWARD_TYPE_ENUM.DISCOUNT_ITEMS;
1067
+ if (!isItemRewardType) {
1068
+ return true;
1069
+ }
1070
+ const hasOrderLevelDiscount = getNormalizedOfferId(orderDiscountDetails?.loyalty_discount_id) === claimedGiftCardId;
1071
+ const hasItemLevelDiscount = hasItemLevelLoyaltyDiscountForId(categories, claimedGiftCardId);
1072
+ if (hasOrderLevelDiscount || hasItemLevelDiscount) {
1073
+ return true;
1074
+ }
1075
+ hasRemovedGiftCardRedemptions = true;
1076
+ return false;
1077
+ });
1078
+ if (!hasRemovedGiftCardRedemptions) {
1079
+ return walletRedemptions;
1080
+ }
1081
+ return getWalletRedemptionsMap({
1082
+ ...walletRedemptions,
1083
+ gift_cards: nextGiftCardRedemptions.length > 0 ? nextGiftCardRedemptions : undefined,
1084
+ });
1085
+ }
1086
+ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calculateItemMetadata, syncContext) {
1087
+ if (syncContext?.offers != null && syncContext.unlockedOffersApplicableTimes != null) {
1088
+ const offerSynchronizedData = getOfferSynchronizedCartDataForCalculation({
1089
+ data,
1090
+ syncContext,
1091
+ });
1092
+ if (offerSynchronizedData != null) {
1093
+ return calculateCartOrderInfoAndSyncData(offerSynchronizedData, courses, listnerSettings, calculateItemMetadata);
1094
+ }
1095
+ }
606
1096
  const isCompleted = data.order_status === constants_1.ORDER_STATUS_ENUM.COMPLETED;
607
1097
  /* ===============================><=============================== */
608
1098
  let subtotal = 0;
@@ -680,11 +1170,12 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
680
1170
  cashback_amount: undefined,
681
1171
  });
682
1172
  }
683
- const walletGiftCardRedeemedTimes = Number(syncedWalletRedemptions?.gift_cards?.value_redeemed ?? 0);
684
- const hasWalletGiftCardMetadata = syncedWalletRedemptions?.gift_cards?.gift_card_id != null &&
685
- syncedWalletRedemptions.gift_cards.gift_card_id.trim().length > 0 &&
686
- Number.isFinite(walletGiftCardRedeemedTimes) &&
687
- walletGiftCardRedeemedTimes > 0;
1173
+ syncedWalletRedemptions = getSyncedWalletRedemptionsAfterGiftCardItemRewardCleanup({
1174
+ walletRedemptions: syncedWalletRedemptions,
1175
+ orderDiscountDetails: syncedOrderDiscountDetails,
1176
+ categories,
1177
+ });
1178
+ const hasWalletGiftCardMetadata = (syncedWalletRedemptions?.gift_cards?.length ?? 0) > 0;
688
1179
  // Empty carts must not retain offer-redemption state or gift-card wallet claims.
689
1180
  if (subtotal <= 0) {
690
1181
  if (syncedRedeemedOffers != null) {
@@ -962,6 +1453,55 @@ function calculateCartOrderInfoAndSyncData(data, courses, listnerSettings, calcu
962
1453
  }
963
1454
  return syncedData;
964
1455
  }
1456
+ function getOrderDataWithSyncedWalletGiftCardClaim({ data, walletGiftCardClaim, }) {
1457
+ if (walletGiftCardClaim == null) {
1458
+ return data;
1459
+ }
1460
+ const claimedGiftCardId = walletGiftCardClaim.giftCardId?.toString().trim();
1461
+ if (claimedGiftCardId == null || claimedGiftCardId.length === 0) {
1462
+ return data;
1463
+ }
1464
+ const normalizedWalletRedemptions = getWalletRedemptionsMap(data.wallet_redemptions);
1465
+ const currentGiftCardRedemptions = normalizedWalletRedemptions?.gift_cards ?? [];
1466
+ let hasUpdatedExistingClaim = false;
1467
+ const nextGiftCardRedemptions = currentGiftCardRedemptions.map((giftCardRedemption) => {
1468
+ if (giftCardRedemption.gift_card_id !== claimedGiftCardId) {
1469
+ return giftCardRedemption;
1470
+ }
1471
+ hasUpdatedExistingClaim = true;
1472
+ return {
1473
+ ...giftCardRedemption,
1474
+ redeemed_times: toPositiveInteger(giftCardRedemption.redeemed_times, 0) + 1,
1475
+ ...(walletGiftCardClaim.mysteryGiftType != null
1476
+ ? {
1477
+ mystery_gift_type: walletGiftCardClaim.mysteryGiftType,
1478
+ }
1479
+ : {}),
1480
+ };
1481
+ });
1482
+ if (!hasUpdatedExistingClaim) {
1483
+ nextGiftCardRedemptions.push({
1484
+ gift_card_id: claimedGiftCardId,
1485
+ redeemed_times: 1,
1486
+ ...(walletGiftCardClaim.mysteryGiftType != null
1487
+ ? {
1488
+ mystery_gift_type: walletGiftCardClaim.mysteryGiftType,
1489
+ }
1490
+ : {}),
1491
+ });
1492
+ }
1493
+ const nextWalletRedemptions = getWalletRedemptionsMap({
1494
+ ...(normalizedWalletRedemptions ?? {}),
1495
+ gift_cards: nextGiftCardRedemptions,
1496
+ });
1497
+ if ((0, lodash_1.isEqual)(nextWalletRedemptions, normalizedWalletRedemptions)) {
1498
+ return data;
1499
+ }
1500
+ return {
1501
+ ...data,
1502
+ wallet_redemptions: nextWalletRedemptions,
1503
+ };
1504
+ }
965
1505
  const getOrderItemComaparableData = (item) => ({
966
1506
  item_id: item.item_id,
967
1507
  menu_id: item.menu_id,
@@ -994,7 +1534,7 @@ function getAddItemToCartData(data, payload, courses, listnerSettings) {
994
1534
  modifiers: item.modifiers,
995
1535
  };
996
1536
  };
997
- const { category_id, name, item, chosen_course_id, replace_id } = payload;
1537
+ const { category_id, name, item, chosen_course_id, replace_id, walletGiftCardClaim } = payload;
998
1538
  const comparableItem = getComparableItem(item);
999
1539
  let mainItemId = item._id;
1000
1540
  const orderData = { ...data };
@@ -1156,7 +1696,11 @@ function getAddItemToCartData(data, payload, courses, listnerSettings) {
1156
1696
  ...(iterations.length > 0 && { iterations }),
1157
1697
  categories,
1158
1698
  };
1159
- const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
1699
+ const orderWithSyncedWalletGiftCardClaim = getOrderDataWithSyncedWalletGiftCardClaim({
1700
+ data: order,
1701
+ walletGiftCardClaim,
1702
+ });
1703
+ const newData = calculateCartOrderInfoAndSyncData(orderWithSyncedWalletGiftCardClaim, courses, listnerSettings);
1160
1704
  return newData;
1161
1705
  }
1162
1706
  function getSplitCartItemToTwo({ data, orderItemId, courses, listnerSettings }) {
@@ -2265,6 +2809,13 @@ function getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds
2265
2809
  const newData = calculateCartOrderInfoAndSyncData(order, courses, listnerSettings);
2266
2810
  return newData;
2267
2811
  }
2812
+ function getClearVoucherCodeAndOffersFromCartData(data, courses, listnerSettings, offerIds) {
2813
+ const orderWithoutOffers = getRemoveAllOffersFromCartData(data, courses, listnerSettings, offerIds);
2814
+ const nextOrderDiscountDetails = (0, offers_helpers_1.buildClearVoucherDiscountDetails)(orderWithoutOffers.order_discount_details);
2815
+ return getUpdateCartInfoData(orderWithoutOffers, {
2816
+ order_discount_details: nextOrderDiscountDetails,
2817
+ }, courses, listnerSettings);
2818
+ }
2268
2819
  // ================================><================================= //
2269
2820
  /**
2270
2821
  * Calculate the eligible subtotal by excluding items/categories in excluded_refs