@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,8 +1,7 @@
1
- import { OFFER_REWARD_TYPE_ENUM, PLATFORMS_ENUM } from '../../constants';
1
+ import { GIFT_CARD_REWARD_TYPE_ENUM, OFFER_REWARD_TYPE_ENUM, PLATFORMS_ENUM } from '../../constants';
2
2
  import { ICustomer, IDiscountDetails, IGiftCard, IOffer, IOrder, IOrderCategory, ITenant, IVoucher } from '../../schemas';
3
3
  export declare function getOfferWithPrice<T extends Partial<IOffer> | IOffer>(offer: T, writeable?: boolean): T;
4
4
  export declare function convertOffersToWorkableOffers(offers: IOffer[], platform: PLATFORMS_ENUM): IOffer[];
5
- export declare function calculatePointsRedeemedForOffer(redeemedOffer: IOffer, totalOrderPrice: number, categories: IOrderCategory[] | undefined, claimedTimes?: number): number;
6
5
  interface ICalculateCustomerLoyaltyPoints {
7
6
  customerLoyaltyPoints: number | undefined;
8
7
  orderDiscountDetails: IDiscountDetails | null | undefined;
@@ -20,6 +19,37 @@ interface ICalculateCustomerSpendableVoucherCodes {
20
19
  offers: IOffer[];
21
20
  vouchers: IVoucher[] | undefined;
22
21
  }
22
+ /**
23
+ * Determines whether a voucher-type offer should show "already claimed"
24
+ * instead of the toolkit's generic "not eligible" message.
25
+ *
26
+ * Returns `true` when the offer itself has been redeemed AND the voucher's
27
+ * per-customer usage count has been reached.
28
+ */
29
+ export declare function isExhaustedVoucherOffer({ offer, vouchers, customerOfferRedemptionCounts, redeemedOffers, isRedeemed, }: {
30
+ offer: IOffer | null | undefined;
31
+ vouchers: IVoucher[] | undefined;
32
+ customerOfferRedemptionCounts: Record<string, number> | null | undefined;
33
+ redeemedOffers: IOrder['redeemed_offers'] | null | undefined;
34
+ isRedeemed: boolean;
35
+ }): boolean;
36
+ /**
37
+ * Find all offers linked to a given voucher code.
38
+ * Works with raw IOffer[] — no stats needed.
39
+ */
40
+ export declare function findLinkedVoucherOffers({ voucherCode, offers, vouchers, }: {
41
+ voucherCode: string;
42
+ offers: IOffer[];
43
+ vouchers: IVoucher[];
44
+ }): {
45
+ matchedVoucher: IVoucher | null;
46
+ linkedOffers: IOffer[];
47
+ };
48
+ /**
49
+ * Returns a discount details object with all voucher-related fields cleared.
50
+ * Use when removing a voucher code from the cart (no offers claimed).
51
+ */
52
+ export declare function buildClearVoucherDiscountDetails(currentDetails: IDiscountDetails | null | undefined): IDiscountDetails;
23
53
  export declare function calculateCustomerSpendableVoucherCodes({ customerVoucherCodes, orderDiscountDetails, redeemedOffers, offers, vouchers, }: ICalculateCustomerSpendableVoucherCodes): {
24
54
  voucherCodes: Record<string, number>;
25
55
  totalVouchers: number;
@@ -32,7 +62,7 @@ export declare function calculateCustomerLoyaltyPoints({ customerLoyaltyPoints,
32
62
  deductedLoyaltyPoints: number;
33
63
  };
34
64
  export declare const getTotalSelectedOfferItemsAgainstOffer: (categories: IOrderCategory[] | undefined, offer_id: string) => number;
35
- export interface IRewardPreview {
65
+ interface IRewardPreview {
36
66
  type: OFFER_REWARD_TYPE_ENUM;
37
67
  label: string;
38
68
  discount_value?: number;
@@ -44,7 +74,7 @@ export interface IRewardPreview {
44
74
  cashback_value?: number;
45
75
  gift_card_value?: number;
46
76
  }
47
- export interface IOfferStats {
77
+ interface IOfferStats {
48
78
  progress: number;
49
79
  message: string;
50
80
  invalid_offer: boolean;
@@ -61,7 +91,6 @@ export type IOfferWithStats = {
61
91
  offer: IOffer;
62
92
  stats: IOfferStats;
63
93
  };
64
- export declare function getOfferRemainingClaimsFromStats(stats: Pick<IOfferStats, 'applicable_quantity' | 'redeemed_times'> | null | undefined): number;
65
94
  export declare function getOfferClaimIncrementFromStats({ stats, fallbackClaims, }: {
66
95
  stats: Pick<IOfferStats, 'applicable_quantity' | 'redeemed_times'> | null | undefined;
67
96
  fallbackClaims?: number;
@@ -71,6 +100,57 @@ export declare function buildRedeemedOffersClaimPatch({ currentRedeemedOffers, o
71
100
  offerId: string | null | undefined;
72
101
  claimsIncrement?: number;
73
102
  }): Partial<Pick<IOrder, 'redeemed_offers'>>;
103
+ export declare function getNetItemsValueAfterItemDiscount({ itemsPrice, totalDiscountApplied, orderLevelDiscount, }: {
104
+ itemsPrice: number | null | undefined;
105
+ totalDiscountApplied: number | null | undefined;
106
+ orderLevelDiscount: number | null | undefined;
107
+ }): number;
108
+ export declare function getMaxApplicableWalletCashback({ cashbackBalance, itemsPrice, totalDiscountApplied, orderLevelDiscount, }: {
109
+ cashbackBalance: number | null | undefined;
110
+ itemsPrice: number | null | undefined;
111
+ totalDiscountApplied: number | null | undefined;
112
+ orderLevelDiscount: number | null | undefined;
113
+ }): number;
114
+ export declare const DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS: readonly [25, 50, 75, 100];
115
+ export declare function getWalletCashbackRecommendedBreakpoints({ maxApplicableCashback, percentageSteps, }: {
116
+ maxApplicableCashback: number | null | undefined;
117
+ percentageSteps?: readonly number[];
118
+ }): {
119
+ value: number;
120
+ percentage: number;
121
+ }[];
122
+ export declare function getWalletCashbackRecommendedValues({ maxApplicableCashback, percentageSteps, }: {
123
+ maxApplicableCashback: number | null | undefined;
124
+ percentageSteps?: readonly number[];
125
+ }): number[];
126
+ type TGiftCardRedemptionPayload = NonNullable<NonNullable<IOrder['wallet_redemptions']>['gift_cards']>;
127
+ export declare function buildWalletRedemptionsPatch({ walletRedemptions, }: {
128
+ walletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
129
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
130
+ export declare function buildWalletRedemptionsMergePatch({ currentWalletRedemptions, walletRedemptionsPatch, }: {
131
+ currentWalletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
132
+ walletRedemptionsPatch: Partial<NonNullable<IOrder['wallet_redemptions']>> | null | undefined;
133
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
134
+ export declare function buildWalletCashbackRedemptionPatch({ currentWalletRedemptions, cashbackAmount, }: {
135
+ currentWalletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
136
+ cashbackAmount: number | null | undefined;
137
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
138
+ export declare function buildWalletGiftCardRedemptionPatch({ currentWalletRedemptions, giftCardRedemption, }: {
139
+ currentWalletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
140
+ giftCardRedemption: TGiftCardRedemptionPayload | null | undefined;
141
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
142
+ export declare function buildWalletGiftCardRedemptionClaimPatch({ currentWalletRedemptions, giftCardId, claimsIncrement, mysteryGiftType, }: {
143
+ currentWalletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
144
+ giftCardId: string | null | undefined;
145
+ claimsIncrement?: number;
146
+ mysteryGiftType?: GIFT_CARD_REWARD_TYPE_ENUM | null;
147
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
148
+ export declare function buildClearWalletRedemptionsPatch({ currentWalletRedemptions, clearCashbackAmount, clearGiftCardRedemption, clearAll, }: {
149
+ currentWalletRedemptions: IOrder['wallet_redemptions'] | null | undefined;
150
+ clearCashbackAmount?: boolean;
151
+ clearGiftCardRedemption?: boolean;
152
+ clearAll?: boolean;
153
+ }): Partial<Pick<IOrder, 'wallet_redemptions'>>;
74
154
  interface IGetOffersWithStats {
75
155
  offers: IOffer[];
76
156
  customer: Partial<ICustomer> | null;
@@ -92,5 +172,4 @@ export declare function getOffersWithStats({ offers, customer, vouchers, giftCar
92
172
  offersWithStatsHashKey: string;
93
173
  unlockedOffersApplicableTimesHashKey: string;
94
174
  };
95
- export declare const getAppliedOfferIds: (order_discount_details: IOrder["order_discount_details"] | undefined, categories: IOrderCategory[] | undefined) => string[];
96
175
  export {};
@@ -1,14 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAppliedOfferIds = exports.getTotalSelectedOfferItemsAgainstOffer = void 0;
3
+ exports.DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS = exports.getTotalSelectedOfferItemsAgainstOffer = void 0;
4
4
  exports.getOfferWithPrice = getOfferWithPrice;
5
5
  exports.convertOffersToWorkableOffers = convertOffersToWorkableOffers;
6
- exports.calculatePointsRedeemedForOffer = calculatePointsRedeemedForOffer;
6
+ exports.isExhaustedVoucherOffer = isExhaustedVoucherOffer;
7
+ exports.findLinkedVoucherOffers = findLinkedVoucherOffers;
8
+ exports.buildClearVoucherDiscountDetails = buildClearVoucherDiscountDetails;
7
9
  exports.calculateCustomerSpendableVoucherCodes = calculateCustomerSpendableVoucherCodes;
8
10
  exports.calculateCustomerLoyaltyPoints = calculateCustomerLoyaltyPoints;
9
- exports.getOfferRemainingClaimsFromStats = getOfferRemainingClaimsFromStats;
10
11
  exports.getOfferClaimIncrementFromStats = getOfferClaimIncrementFromStats;
11
12
  exports.buildRedeemedOffersClaimPatch = buildRedeemedOffersClaimPatch;
13
+ exports.getNetItemsValueAfterItemDiscount = getNetItemsValueAfterItemDiscount;
14
+ exports.getMaxApplicableWalletCashback = getMaxApplicableWalletCashback;
15
+ exports.getWalletCashbackRecommendedBreakpoints = getWalletCashbackRecommendedBreakpoints;
16
+ exports.getWalletCashbackRecommendedValues = getWalletCashbackRecommendedValues;
17
+ exports.buildWalletRedemptionsPatch = buildWalletRedemptionsPatch;
18
+ exports.buildWalletRedemptionsMergePatch = buildWalletRedemptionsMergePatch;
19
+ exports.buildWalletCashbackRedemptionPatch = buildWalletCashbackRedemptionPatch;
20
+ exports.buildWalletGiftCardRedemptionPatch = buildWalletGiftCardRedemptionPatch;
21
+ exports.buildWalletGiftCardRedemptionClaimPatch = buildWalletGiftCardRedemptionClaimPatch;
22
+ exports.buildClearWalletRedemptionsPatch = buildClearWalletRedemptionsPatch;
12
23
  exports.getOffersWithStats = getOffersWithStats;
13
24
  const constants_1 = require("../../constants");
14
25
  const common_1 = require("./common");
@@ -301,6 +312,88 @@ function getOfferRedeemedClaims(redeemedOffers, offerId) {
301
312
  }
302
313
  return 0;
303
314
  }
315
+ // ================================><================================= //
316
+ // === isExhaustedVoucherOffer === //
317
+ // ================================><================================= //
318
+ /**
319
+ * Determines whether a voucher-type offer should show "already claimed"
320
+ * instead of the toolkit's generic "not eligible" message.
321
+ *
322
+ * Returns `true` when the offer itself has been redeemed AND the voucher's
323
+ * per-customer usage count has been reached.
324
+ */
325
+ function isExhaustedVoucherOffer({ offer, vouchers, customerOfferRedemptionCounts, redeemedOffers, isRedeemed, }) {
326
+ if (offer == null ||
327
+ offer.pathway_to_unlock_type !== constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER ||
328
+ offer.pathway_to_unlock_type_vouchers == null ||
329
+ customerOfferRedemptionCounts == null) {
330
+ return false;
331
+ }
332
+ const isThisOfferRedeemed = isRedeemed || (redeemedOffers != null && Number(redeemedOffers[offer._id]) > 0);
333
+ if (!isThisOfferRedeemed)
334
+ return false;
335
+ const pathwayMaxUsesPerCustomer = offer.pathway_to_unlock_type_vouchers.max_uses_per_customer;
336
+ if (pathwayMaxUsesPerCustomer != null &&
337
+ (customerOfferRedemptionCounts[offer._id] ?? 0) >= pathwayMaxUsesPerCustomer) {
338
+ return true;
339
+ }
340
+ if (vouchers == null || vouchers.length === 0) {
341
+ return false;
342
+ }
343
+ const vouchersById = new Map();
344
+ for (let i = 0; i < vouchers.length; i++) {
345
+ vouchersById.set(vouchers[i]._id, vouchers[i]);
346
+ }
347
+ const voucherIds = offer.pathway_to_unlock_type_vouchers.voucher_ids;
348
+ for (let i = 0; i < voucherIds.length; i++) {
349
+ const voucherId = voucherIds[i];
350
+ const voucher = vouchersById.get(voucherId);
351
+ if (voucher?.max_uses_per_customer == null) {
352
+ continue;
353
+ }
354
+ if ((customerOfferRedemptionCounts[voucherId] ?? 0) >= voucher.max_uses_per_customer) {
355
+ return true;
356
+ }
357
+ }
358
+ return false;
359
+ }
360
+ // ================================><================================= //
361
+ // === findLinkedVoucherOffers === //
362
+ // ================================><================================= //
363
+ /**
364
+ * Find all offers linked to a given voucher code.
365
+ * Works with raw IOffer[] — no stats needed.
366
+ */
367
+ function findLinkedVoucherOffers({ voucherCode, offers, vouchers, }) {
368
+ const normalizedCode = voucherCode.trim().toUpperCase();
369
+ if (!normalizedCode)
370
+ return { matchedVoucher: null, linkedOffers: [] };
371
+ const matchedVoucher = vouchers.find((v) => v.code.trim().toUpperCase() === normalizedCode) ?? null;
372
+ if (!matchedVoucher)
373
+ return { matchedVoucher: null, linkedOffers: [] };
374
+ const linkedOffers = offers.filter((offer) => offer.pathway_to_unlock_type === constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.VOUCHER &&
375
+ offer.pathway_to_unlock_type_vouchers?.voucher_ids.includes(matchedVoucher._id));
376
+ return { matchedVoucher, linkedOffers };
377
+ }
378
+ // ================================><================================= //
379
+ // === buildClearVoucherDiscountDetails === //
380
+ // ================================><================================= //
381
+ /**
382
+ * Returns a discount details object with all voucher-related fields cleared.
383
+ * Use when removing a voucher code from the cart (no offers claimed).
384
+ */
385
+ function buildClearVoucherDiscountDetails(currentDetails) {
386
+ return {
387
+ ...(currentDetails ?? { total_discount: 0 }),
388
+ voucher_discount_id: undefined,
389
+ voucher_discount_name: undefined,
390
+ voucher_discount: undefined,
391
+ is_voucher_discount_percentage: undefined,
392
+ voucher_discount_reason: undefined,
393
+ voucher_reference_number: undefined,
394
+ total_discount: 0,
395
+ };
396
+ }
304
397
  function calculateCustomerSpendableVoucherCodes({ customerVoucherCodes, orderDiscountDetails, redeemedOffers, offers, vouchers, }) {
305
398
  const voucherCodes = {};
306
399
  if (customerVoucherCodes != null) {
@@ -354,7 +447,10 @@ function calculateCustomerSpendableVoucherCodes({ customerVoucherCodes, orderDis
354
447
  continue;
355
448
  const redeemedTimes = getOfferRedeemedClaims(redeemedOffers, offer._id);
356
449
  if (redeemedTimes > 0) {
357
- consumedVoucherClaims += redeemedTimes;
450
+ // Count 1 voucher use per redeemed offer (not redeemedTimes which
451
+ // can be > 1 for repeat claims). Each distinct offer consumes one
452
+ // voucher code use, regardless of how many times it was redeemed.
453
+ consumedVoucherClaims += 1;
358
454
  }
359
455
  }
360
456
  }
@@ -665,6 +761,164 @@ function buildRedeemedOffersClaimPatch({ currentRedeemedOffers, offerId, claimsI
665
761
  redeemed_offers: Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null,
666
762
  };
667
763
  }
764
+ function getNetItemsValueAfterItemDiscount({ itemsPrice, totalDiscountApplied, orderLevelDiscount, }) {
765
+ const safeItemsPrice = Number.isFinite(itemsPrice) ? Math.max(0, Number(itemsPrice)) : 0;
766
+ const safeTotalDiscountApplied = Number.isFinite(totalDiscountApplied)
767
+ ? Math.max(0, Number(totalDiscountApplied))
768
+ : 0;
769
+ const safeOrderLevelDiscount = Number.isFinite(orderLevelDiscount) ? Math.max(0, Number(orderLevelDiscount)) : 0;
770
+ const itemDiscount = (0, common_1.parseNum)(Math.max(0, safeTotalDiscountApplied - safeOrderLevelDiscount));
771
+ return (0, common_1.parseNum)(Math.max(0, safeItemsPrice - itemDiscount));
772
+ }
773
+ function getMaxApplicableWalletCashback({ cashbackBalance, itemsPrice, totalDiscountApplied, orderLevelDiscount, }) {
774
+ const safeCashbackBalance = Number.isFinite(cashbackBalance) ? Math.max(0, Number(cashbackBalance)) : 0;
775
+ const netItemsValue = getNetItemsValueAfterItemDiscount({
776
+ itemsPrice,
777
+ totalDiscountApplied,
778
+ orderLevelDiscount,
779
+ });
780
+ return (0, common_1.parseNum)(Math.min(safeCashbackBalance, netItemsValue));
781
+ }
782
+ exports.DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS = [25, 50, 75, 100];
783
+ function getWalletCashbackRecommendedBreakpoints({ maxApplicableCashback, percentageSteps = exports.DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS, }) {
784
+ const safeMaxApplicableCashback = Number.isFinite(maxApplicableCashback)
785
+ ? Math.max(0, Number(maxApplicableCashback))
786
+ : 0;
787
+ if (safeMaxApplicableCashback <= 0) {
788
+ return [];
789
+ }
790
+ const percentageByValue = new Map();
791
+ for (let i = 0; i < percentageSteps.length; i++) {
792
+ const percentageStep = Number(percentageSteps[i]);
793
+ if (!Number.isFinite(percentageStep)) {
794
+ continue;
795
+ }
796
+ const safePercentageStep = (0, common_1.parseNum)(Math.max(0, Math.min(100, percentageStep)));
797
+ const computedValue = (0, common_1.parseNum)((safeMaxApplicableCashback * safePercentageStep) / 100);
798
+ const normalizedValue = (0, common_1.parseNum)(Math.max(0, Math.min(computedValue, safeMaxApplicableCashback)));
799
+ if (normalizedValue <= 0) {
800
+ continue;
801
+ }
802
+ percentageByValue.set(normalizedValue, safePercentageStep);
803
+ }
804
+ return Array.from(percentageByValue.entries())
805
+ .sort((a, b) => a[0] - b[0])
806
+ .map(([value, percentage]) => ({ value, percentage }));
807
+ }
808
+ function getWalletCashbackRecommendedValues({ maxApplicableCashback, percentageSteps = exports.DEFAULT_WALLET_CASHBACK_PERCENTAGE_STEPS, }) {
809
+ return getWalletCashbackRecommendedBreakpoints({
810
+ maxApplicableCashback,
811
+ percentageSteps,
812
+ }).map((breakpoint) => breakpoint.value);
813
+ }
814
+ function normalizeGiftCardId(giftCardId) {
815
+ if (giftCardId == null)
816
+ return null;
817
+ const normalizedGiftCardId = giftCardId.toString().trim();
818
+ return normalizedGiftCardId.length > 0 ? normalizedGiftCardId : null;
819
+ }
820
+ function normalizeWalletRedemptions(walletRedemptions) {
821
+ if (walletRedemptions == null) {
822
+ return null;
823
+ }
824
+ const normalizedWalletRedemptions = {};
825
+ const cashbackAmount = Number(walletRedemptions.cashback_amount);
826
+ if (Number.isFinite(cashbackAmount) && cashbackAmount > 0) {
827
+ normalizedWalletRedemptions.cashback_amount = (0, common_1.parseNum)(cashbackAmount);
828
+ }
829
+ const giftCardRedemption = walletRedemptions.gift_cards;
830
+ if (giftCardRedemption != null) {
831
+ const giftCardId = normalizeGiftCardId(giftCardRedemption.gift_card_id);
832
+ const redeemedTimes = toPositiveInteger(giftCardRedemption.value_redeemed, 0);
833
+ if (giftCardId != null && redeemedTimes > 0) {
834
+ normalizedWalletRedemptions.gift_cards = {
835
+ gift_card_id: giftCardId,
836
+ value_redeemed: redeemedTimes,
837
+ ...(giftCardRedemption.mystery_gift_type != null
838
+ ? { mystery_gift_type: giftCardRedemption.mystery_gift_type }
839
+ : {}),
840
+ };
841
+ }
842
+ }
843
+ return Object.keys(normalizedWalletRedemptions).length > 0 ? normalizedWalletRedemptions : null;
844
+ }
845
+ function buildWalletRedemptionsPatch({ walletRedemptions, }) {
846
+ return {
847
+ wallet_redemptions: normalizeWalletRedemptions(walletRedemptions),
848
+ };
849
+ }
850
+ function buildWalletRedemptionsMergePatch({ currentWalletRedemptions, walletRedemptionsPatch, }) {
851
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
852
+ const mergedWalletRedemptions = {
853
+ ...(normalizedCurrentWalletRedemptions ?? {}),
854
+ ...(walletRedemptionsPatch ?? {}),
855
+ };
856
+ return {
857
+ wallet_redemptions: normalizeWalletRedemptions(mergedWalletRedemptions),
858
+ };
859
+ }
860
+ function buildWalletCashbackRedemptionPatch({ currentWalletRedemptions, cashbackAmount, }) {
861
+ return buildWalletRedemptionsMergePatch({
862
+ currentWalletRedemptions,
863
+ walletRedemptionsPatch: {
864
+ cashback_amount: cashbackAmount,
865
+ },
866
+ });
867
+ }
868
+ function buildWalletGiftCardRedemptionPatch({ currentWalletRedemptions, giftCardRedemption, }) {
869
+ return buildWalletRedemptionsMergePatch({
870
+ currentWalletRedemptions,
871
+ walletRedemptionsPatch: {
872
+ gift_cards: giftCardRedemption,
873
+ },
874
+ });
875
+ }
876
+ function buildWalletGiftCardRedemptionClaimPatch({ currentWalletRedemptions, giftCardId, claimsIncrement = 1, mysteryGiftType, }) {
877
+ const normalizedGiftCardId = normalizeGiftCardId(giftCardId);
878
+ if (normalizedGiftCardId == null) {
879
+ return {};
880
+ }
881
+ const safeClaimsIncrement = toPositiveInteger(claimsIncrement, 1);
882
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
883
+ const existingGiftCardRedemption = normalizedCurrentWalletRedemptions?.gift_cards;
884
+ const currentRedeemedTimes = existingGiftCardRedemption?.gift_card_id === normalizedGiftCardId
885
+ ? toPositiveInteger(existingGiftCardRedemption.value_redeemed, 0)
886
+ : 0;
887
+ return buildWalletGiftCardRedemptionPatch({
888
+ currentWalletRedemptions,
889
+ giftCardRedemption: {
890
+ gift_card_id: normalizedGiftCardId,
891
+ value_redeemed: currentRedeemedTimes + safeClaimsIncrement,
892
+ ...(mysteryGiftType != null ? { mystery_gift_type: mysteryGiftType } : {}),
893
+ },
894
+ });
895
+ }
896
+ function buildClearWalletRedemptionsPatch({ currentWalletRedemptions, clearCashbackAmount = false, clearGiftCardRedemption = false, clearAll = false, }) {
897
+ if (clearAll) {
898
+ return {
899
+ wallet_redemptions: null,
900
+ };
901
+ }
902
+ if (!clearCashbackAmount && !clearGiftCardRedemption) {
903
+ return {
904
+ wallet_redemptions: normalizeWalletRedemptions(currentWalletRedemptions),
905
+ };
906
+ }
907
+ const normalizedCurrentWalletRedemptions = normalizeWalletRedemptions(currentWalletRedemptions);
908
+ if (normalizedCurrentWalletRedemptions == null) {
909
+ return {
910
+ wallet_redemptions: null,
911
+ };
912
+ }
913
+ const nextWalletRedemptions = {
914
+ ...normalizedCurrentWalletRedemptions,
915
+ ...(clearCashbackAmount ? { cashback_amount: undefined } : {}),
916
+ ...(clearGiftCardRedemption ? { gift_cards: undefined } : {}),
917
+ };
918
+ return {
919
+ wallet_redemptions: normalizeWalletRedemptions(nextWalletRedemptions),
920
+ };
921
+ }
668
922
  function buildRewardPreview(offer) {
669
923
  switch (offer.reward_type) {
670
924
  case constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT: {
@@ -837,9 +1091,8 @@ function getOffersWithStatsHashKey(offersWithStats, totalClaimableOffers) {
837
1091
  function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOfferRedemptionCounts, redeemed_offers, platform, currency_symbol, currentItemsPrice, totalDiscountApplied, categories, order_discount_details, }) {
838
1092
  const offersWithStats = [];
839
1093
  const orderPrice = currentItemsPrice ?? 0;
840
- const totalDiscount = totalDiscountApplied ?? 0;
841
- const orderDiscount = order_discount_details?.total_discount ?? 0;
842
- const itemsDiscount = totalDiscount - orderDiscount;
1094
+ // Spend qualification policy: use basket subtotal before discounts.
1095
+ const qualifyingOrderValue = orderPrice;
843
1096
  const unlockedOffersApplicableTimes = {};
844
1097
  let totalClaimableOffers = [];
845
1098
  let totalLoyaltyPointsOfCustomer = null;
@@ -968,6 +1221,26 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
968
1221
  const safeRequiredAmount = Math.max(1, minAmount || 1);
969
1222
  return Math.max(1, Math.floor(orderValue / safeRequiredAmount));
970
1223
  };
1224
+ const getOrdersBetweenUnlocksStats = ({ totalOrders, ordersBetweenUnlocks, }) => {
1225
+ const normalizedTotalOrders = Math.max(0, Math.floor(Number.isFinite(totalOrders) ? totalOrders : 0));
1226
+ const normalizedOrdersBetweenUnlocks = toPositiveInteger(ordersBetweenUnlocks, 0);
1227
+ if (normalizedOrdersBetweenUnlocks <= 0) {
1228
+ return {
1229
+ isUnlockOrder: true,
1230
+ ordersAwayFromNextUnlock: 0,
1231
+ progress: 100,
1232
+ };
1233
+ }
1234
+ const unlockInterval = normalizedOrdersBetweenUnlocks + 1;
1235
+ const remainder = normalizedTotalOrders % unlockInterval;
1236
+ const isUnlockOrder = normalizedTotalOrders > 0 && remainder === 0;
1237
+ const ordersAwayFromNextUnlock = isUnlockOrder ? 0 : remainder === 0 ? unlockInterval : unlockInterval - remainder;
1238
+ return {
1239
+ isUnlockOrder,
1240
+ ordersAwayFromNextUnlock,
1241
+ progress: getPreUnlockProgressPercentage(remainder, unlockInterval),
1242
+ };
1243
+ };
971
1244
  const getPointsMaxRedeemableClaims = ({ offerToCheck, pathwayUnlockableClaims, }) => {
972
1245
  if (offerToCheck.reward_type !== constants_1.OFFER_REWARD_TYPE_ENUM.POINTS || offerToCheck.reward_points == null) {
973
1246
  return 1;
@@ -1019,9 +1292,9 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1019
1292
  offersWithStats.push({ offer, stats });
1020
1293
  continue;
1021
1294
  }
1022
- const orderValue = orderPrice - itemsDiscount;
1295
+ const orderValue = qualifyingOrderValue;
1023
1296
  // Need to check if offer is unlocked
1024
- const { scope = constants_1.PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.OVERALL, min_num_of_orders, max_num_of_orders, total_amount, max_amount, } = offer.pathway_to_unlock_type_orders;
1297
+ const { scope = constants_1.PATHWAY_TO_UNLOCK_TYPE_ORDERS_SCOPE_ENUM.OVERALL, min_num_of_orders, max_num_of_orders, total_amount, max_amount, orders_between_unlocks, } = offer.pathway_to_unlock_type_orders;
1025
1298
  const scopedStats = getOrdersScopedStats({
1026
1299
  scope,
1027
1300
  currentOrderValue: orderValue,
@@ -1041,15 +1314,25 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1041
1314
  const ordersProgress = getPreUnlockProgressPercentage(totalOrders, min_num_of_orders || 1);
1042
1315
  const amountProgress = getPreUnlockProgressPercentage(totalAmount, total_amount || 1);
1043
1316
  const combinedProgress = Math.min(ordersProgress, amountProgress);
1317
+ const ordersBetweenUnlocksStats = getOrdersBetweenUnlocksStats({
1318
+ totalOrders,
1319
+ ordersBetweenUnlocks: orders_between_unlocks,
1320
+ });
1044
1321
  if (totalOrders >= min_num_of_orders) {
1045
1322
  // Either the max_num_of_orders is infinity, or the customer has not reached the max_num_of_orders
1046
1323
  if ((max_num_of_orders == null || totalOrders <= max_num_of_orders) &&
1047
1324
  (max_amount == null || totalAmount <= max_amount)) {
1048
1325
  if (totalAmount >= total_amount) {
1049
- stats.progress = 100;
1050
- stats.claimable = false;
1051
- stats.message = `🎉 You have unlocked this offer 🎉`;
1052
- stats.applicable_quantity = 1;
1326
+ if (ordersBetweenUnlocksStats.isUnlockOrder) {
1327
+ stats.progress = 100;
1328
+ stats.claimable = false;
1329
+ stats.message = `🎉 You have unlocked this offer 🎉`;
1330
+ stats.applicable_quantity = 1;
1331
+ }
1332
+ else {
1333
+ stats.progress = Math.min(combinedProgress, ordersBetweenUnlocksStats.progress);
1334
+ stats.message = `You are ${ordersBetweenUnlocksStats.ordersAwayFromNextUnlock} orders away from unlocking this offer`;
1335
+ }
1053
1336
  }
1054
1337
  else {
1055
1338
  // This means that the customer has not spent enough to unlock the offer
@@ -1120,7 +1403,8 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1120
1403
  applicableQuantity,
1121
1404
  });
1122
1405
  const maxRedeemableClaims = 1;
1123
- const isClaimable = redeemedTimes < maxRedeemableClaims;
1406
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
1407
+ const isClaimable = redeemedTimes < maxRedeemableClaims && !discountSlotOccupied;
1124
1408
  stats.redeemed_times = redeemedTimes;
1125
1409
  stats.applicable_quantity = applicableQuantity * maxRedeemableClaims;
1126
1410
  if (isClaimable) {
@@ -1130,7 +1414,12 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1130
1414
  }
1131
1415
  else {
1132
1416
  stats.claimable = false;
1133
- stats.message = `This offer is redeemed ✅`;
1417
+ stats.message =
1418
+ redeemedTimes > 0
1419
+ ? `This offer is redeemed ✅`
1420
+ : discountSlotOccupied
1421
+ ? 'You already have an offer applied to your order.'
1422
+ : `🎉 You have unlocked this offer 🎉`;
1134
1423
  }
1135
1424
  unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
1136
1425
  }
@@ -1310,7 +1599,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1310
1599
  offersWithStats.push({ offer, stats });
1311
1600
  continue;
1312
1601
  }
1313
- const orderValue = orderPrice - totalDiscount;
1602
+ const orderValue = qualifyingOrderValue;
1314
1603
  const { num_of_items, max_claims, min_same_item_quantity, max_same_item_quantity, total_amount, excluded_refs, exclusive_refs, item_ids, category_ids, } = offer.pathway_to_unlock_type_items;
1315
1604
  const bachelorItems = getCartItemsApplicableToOfferItemsQuantity({
1316
1605
  categories,
@@ -1396,7 +1685,8 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1396
1685
  totalOfferItemsSelected,
1397
1686
  applicableQuantity,
1398
1687
  });
1399
- const isClaimable = redeemedTimes < totalUnlockableClaims;
1688
+ const discountSlotOccupied = isDiscountSlotOccupiedForOffer(offer);
1689
+ const isClaimable = redeemedTimes < totalUnlockableClaims && !discountSlotOccupied;
1400
1690
  stats.redeemed_times = redeemedTimes;
1401
1691
  stats.applicable_quantity = applicableQuantity * Math.max(1, totalUnlockableClaims);
1402
1692
  stats.claimable = isClaimable;
@@ -1405,7 +1695,12 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1405
1695
  stats.message = `🎉 You have unlocked this offer 🎉`;
1406
1696
  }
1407
1697
  else {
1408
- stats.message = `This offer is redeemed ✅`;
1698
+ stats.message =
1699
+ redeemedTimes >= totalUnlockableClaims
1700
+ ? `This offer is redeemed ✅`
1701
+ : discountSlotOccupied
1702
+ ? 'You already have an offer applied to your order.'
1703
+ : `🎉 You have unlocked this offer 🎉`;
1409
1704
  }
1410
1705
  unlockedOffersApplicableTimes[offer._id] = stats.applicable_quantity;
1411
1706
  }
@@ -1569,7 +1864,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1569
1864
  offersWithStats.push({ offer, stats });
1570
1865
  continue;
1571
1866
  }
1572
- const orderValue = orderPrice - totalDiscount;
1867
+ const orderValue = qualifyingOrderValue;
1573
1868
  const { num_of_points, total_amount, max_claims } = offer.pathway_to_unlock_type_points;
1574
1869
  const maxClaimsPerOrder = max_claims == null ? Infinity : Math.max(1, max_claims);
1575
1870
  if (totalLoyaltyPointsOfCustomer == null) {
@@ -1839,7 +2134,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1839
2134
  });
1840
2135
  continue;
1841
2136
  }
1842
- const orderValue = orderPrice - totalDiscount;
2137
+ const orderValue = qualifyingOrderValue;
1843
2138
  const { total_amount, max_amount, max_claims, voucher_ids } = offer.pathway_to_unlock_type_vouchers;
1844
2139
  const voucherReferenceNumber = order_discount_details?.voucher_reference_number;
1845
2140
  const normalizedVoucherRef = voucherReferenceNumber?.trim().toUpperCase();
@@ -1853,6 +2148,7 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
1853
2148
  const normalizedMatchedVoucherCode = matchedVoucher?.code.trim().toUpperCase() ?? null;
1854
2149
  const redeemedTimesForOffer = getOfferRedeemedTimes(offer._id);
1855
2150
  const spendableVoucherCount = normalizedMatchedVoucherCode == null ? 0 : (spendableVoucherCodesByCode[normalizedMatchedVoucherCode] ?? 0);
2151
+ // Voucher max_uses_per_customer is resource-scoped by voucher id.
1856
2152
  const customerVoucherUsageCount = matchedVoucher == null ? 0 : (customerOfferRedemptionCounts?.[matchedVoucher._id] ?? 0);
1857
2153
  const voucherUsesPerCustomerExhausted = matchedVoucher?.max_uses_per_customer != null &&
1858
2154
  (customerOfferRedemptionCounts == null || customerVoucherUsageCount >= matchedVoucher.max_uses_per_customer);
@@ -2164,31 +2460,3 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
2164
2460
  unlockedOffersApplicableTimesHashKey: getUnlockedOffersApplicableTimesHashKey(unlockedOffersApplicableTimes),
2165
2461
  };
2166
2462
  }
2167
- const getAppliedOfferIds = (order_discount_details, categories) => {
2168
- const appliedOfferIds = new Set();
2169
- if (order_discount_details != null) {
2170
- if (order_discount_details.loyalty_discount_id) {
2171
- appliedOfferIds.add(order_discount_details.loyalty_discount_id);
2172
- }
2173
- if (order_discount_details.voucher_discount_id) {
2174
- appliedOfferIds.add(order_discount_details.voucher_discount_id);
2175
- }
2176
- }
2177
- const totalCategories = categories?.length ?? 0;
2178
- for (let i = 0; i < totalCategories; i++) {
2179
- const category = categories[i];
2180
- for (let j = 0; j < category.items.length; j++) {
2181
- const item = category.items[j];
2182
- if (item.item_discount_details != null) {
2183
- if (item.item_discount_details.loyalty_discount_id) {
2184
- appliedOfferIds.add(item.item_discount_details.loyalty_discount_id);
2185
- }
2186
- if (item.item_discount_details.voucher_discount_id) {
2187
- appliedOfferIds.add(item.item_discount_details.voucher_discount_id);
2188
- }
2189
- }
2190
- }
2191
- }
2192
- return Array.from(appliedOfferIds);
2193
- };
2194
- exports.getAppliedOfferIds = getAppliedOfferIds;
@@ -382,6 +382,7 @@ export declare const OfferSchema: Schema<any, import("mongoose").Model<any, any,
382
382
  max_uses_per_customer?: number | null | undefined;
383
383
  max_claims?: number | null | undefined;
384
384
  max_num_of_orders?: number | null | undefined;
385
+ orders_between_unlocks?: number | null | undefined;
385
386
  } | null | undefined;
386
387
  pathway_to_unlock_type_points?: {
387
388
  num_of_points: number;
@@ -777,6 +778,7 @@ export declare const OfferSchema: Schema<any, import("mongoose").Model<any, any,
777
778
  max_uses_per_customer?: number | null | undefined;
778
779
  max_claims?: number | null | undefined;
779
780
  max_num_of_orders?: number | null | undefined;
781
+ orders_between_unlocks?: number | null | undefined;
780
782
  } | null | undefined;
781
783
  pathway_to_unlock_type_points?: {
782
784
  num_of_points: number;
@@ -1172,6 +1174,7 @@ export declare const OfferSchema: Schema<any, import("mongoose").Model<any, any,
1172
1174
  max_uses_per_customer?: number | null | undefined;
1173
1175
  max_claims?: number | null | undefined;
1174
1176
  max_num_of_orders?: number | null | undefined;
1177
+ orders_between_unlocks?: number | null | undefined;
1175
1178
  } | null | undefined;
1176
1179
  pathway_to_unlock_type_points?: {
1177
1180
  num_of_points: number;
@@ -91,6 +91,11 @@ const PathwayToUnlockTypeOrdersSchema = new mongoose_1.Schema({
91
91
  required: false,
92
92
  default: null,
93
93
  },
94
+ orders_between_unlocks: {
95
+ type: Number,
96
+ required: false,
97
+ default: null,
98
+ },
94
99
  }, {
95
100
  _id: false,
96
101
  minimize: false,
@@ -8,6 +8,7 @@ export interface IPathwayToUnlockTypeOrders {
8
8
  max_num_of_orders: number | null;
9
9
  total_amount: number;
10
10
  max_amount: number | null;
11
+ orders_between_unlocks: number | null;
11
12
  }
12
13
  export interface IPathwayToUnlockTypeItems {
13
14
  num_of_items: number;