@managesome/eposmatic-toolkit 0.2.313 → 0.2.315

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