@managesome/eposmatic-toolkit 0.4.30 → 0.4.32
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.
- package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +19 -0
- package/esm/helpers/store/cart-actions.js +3 -12
- package/esm/helpers/utils/offer-apply-helpers.js +2 -10
- package/esm/helpers/utils/offers-helpers.js +117 -2
- package/esm/schemas/models/tenant_active_jobs.js +7 -0
- package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +19 -0
- package/lib/helpers/store/cart-actions.js +1 -10
- package/lib/helpers/utils/offer-apply-helpers.js +2 -10
- package/lib/helpers/utils/offers-helpers.d.ts +50 -0
- package/lib/helpers/utils/offers-helpers.js +120 -2
- package/lib/schemas/models/tenant_active_jobs.d.ts +7 -0
- package/lib/schemas/models/tenant_active_jobs.js +8 -1
- package/lib/tests/offers-helpers-points-evidence.test.d.ts +1 -0
- package/lib/tests/offers-helpers-points-evidence.test.js +338 -0
- package/package.json +1 -1
|
@@ -6,6 +6,7 @@ import { MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME, MATERIALIZED_TE
|
|
|
6
6
|
import { MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_COLLECTION_NAME, MATERIALIZED_TENANT_SALES_OVERVIEW_REPORTS_INDEX_OPTIONS, } from '../../schemas/models/materialized_tenant_sales_overview_reports';
|
|
7
7
|
import { MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME, MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS, MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME, MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS, } from '../../schemas/models/materialized_report_drilldown_rows';
|
|
8
8
|
import { TENANT_CALENDAR_COLLECTION_NAME, TENANT_CALENDAR_INDEX_OPTIONS } from '../../schemas/models/tenant_calendar';
|
|
9
|
+
import { TENANT_ACTIVE_JOBS_COLLECTION_NAME, TENANT_ACTIVE_JOBS_INDEX_OPTIONS, } from '../../schemas/models/tenant_active_jobs';
|
|
9
10
|
/**
|
|
10
11
|
* BOOTSTRAP the indexes the materialized reads/writes assume.
|
|
11
12
|
*
|
|
@@ -28,6 +29,7 @@ const INDEXES = {
|
|
|
28
29
|
[MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME]: MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS,
|
|
29
30
|
[MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME]: MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS,
|
|
30
31
|
[TENANT_CALENDAR_COLLECTION_NAME]: TENANT_CALENDAR_INDEX_OPTIONS,
|
|
32
|
+
[TENANT_ACTIVE_JOBS_COLLECTION_NAME]: TENANT_ACTIVE_JOBS_INDEX_OPTIONS,
|
|
31
33
|
};
|
|
32
34
|
export const MATERIALIZED_REPORT_INDEX_COLLECTIONS = Object.keys(INDEXES);
|
|
33
35
|
export async function ensureMaterializedReportIndexes(connection, options = {}) {
|
|
@@ -42,6 +44,23 @@ export async function ensureMaterializedReportIndexes(connection, options = {})
|
|
|
42
44
|
}
|
|
43
45
|
const collection = db.collection(collectionName);
|
|
44
46
|
const indexes = definitions.filter((definition) => definition.name !== '_id_');
|
|
47
|
+
// One-time migration for the old discount-entry identity index. A page
|
|
48
|
+
// design cannot coexist with a unique index that omits `page`.
|
|
49
|
+
if (collectionName === MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME) {
|
|
50
|
+
const existing = await collection
|
|
51
|
+
.listIndexes()
|
|
52
|
+
.toArray()
|
|
53
|
+
.catch(() => []);
|
|
54
|
+
const legacy = existing.find((index) => index.name === 'tenant_id__scope_context__scope_field__day_index' ||
|
|
55
|
+
(index.unique === true &&
|
|
56
|
+
index.key?.tenant_id === 1 &&
|
|
57
|
+
index.key?.scope_context === 1 &&
|
|
58
|
+
index.key?.scope_field === 1 &&
|
|
59
|
+
index.key?.day_index === 1 &&
|
|
60
|
+
index.key?.page == null));
|
|
61
|
+
if (legacy != null)
|
|
62
|
+
await collection.dropIndex(legacy.name);
|
|
63
|
+
}
|
|
45
64
|
try {
|
|
46
65
|
await collection.createIndexes(indexes);
|
|
47
66
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import ObjectID from 'bson-objectid';
|
|
2
2
|
import isEqual from 'lodash/isEqual';
|
|
3
|
-
import { DISCOUNT_APPLICABILITY_ENUM, GIFT_CARD_REWARD_TYPE_ENUM, OFFER_NO_LONGER_QUALIFIED_VOID_REASON,
|
|
3
|
+
import { DISCOUNT_APPLICABILITY_ENUM, GIFT_CARD_REWARD_TYPE_ENUM, OFFER_NO_LONGER_QUALIFIED_VOID_REASON, ORDER_STATUS_ENUM, ORDER_TYPE_ENUM, PLATFORMS_BY_ORDER_TYPE, SORT_TYPE_ENUM, TAX_INVOICE_PROVIDER_CHARGES_MAP, TAX_INVOICE_PROVIDER_ENUM, WALLET_CASHBACK_LOYALTY_DISCOUNT_ID, WALLET_CASHBACK_LOYALTY_DISCOUNT_NAME, WALLET_CASHBACK_LOYALTY_REFERENCE, } from '../../constants';
|
|
4
4
|
import { calculateEligibleOfferDiscountDetails, getCappedOfferDiscountAmount, getCardChargesAndAmountCollected, getDeliveryAmt, getNetItemsValueAfterItemDiscount, getPercentageAmount, getPriceEnum, parseFloatCeil, parseNum, } from '../utils';
|
|
5
|
-
import { buildClearVoucherDiscountDetails } from '../utils/offers-helpers';
|
|
5
|
+
import { buildClearVoucherDiscountDetails, getOfferRewardApplicableQuantity } from '../utils/offers-helpers';
|
|
6
6
|
import { convertItemToWorkableItem, convertOptionToWorkableOption } from '../utils/platform-catalog';
|
|
7
7
|
export function getItemQuantityChangeResults({ prevQuantity, newQuantity, prevItemDiscountDetails, }) {
|
|
8
8
|
let item_discount_details = prevItemDiscountDetails;
|
|
@@ -810,15 +810,6 @@ function areRedeemedOffersEqualForOfferSync(currentRedeemedOffers, nextRedeemedO
|
|
|
810
810
|
}
|
|
811
811
|
return true;
|
|
812
812
|
}
|
|
813
|
-
function getItemRewardApplicableQuantityForOfferSync(offer) {
|
|
814
|
-
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
815
|
-
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
816
|
-
}
|
|
817
|
-
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
818
|
-
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
819
|
-
}
|
|
820
|
-
return null;
|
|
821
|
-
}
|
|
822
813
|
function getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, offerId) {
|
|
823
814
|
let totalSelectedOfferItems = 0;
|
|
824
815
|
for (let i = 0; i < categories.length; i++) {
|
|
@@ -853,7 +844,7 @@ function getReconciledRedeemedOffersMapForOfferSync({ existingRedeemedOffers, ca
|
|
|
853
844
|
const normalizedOfferId = getNormalizedOfferId(offer._id);
|
|
854
845
|
if (normalizedOfferId == null)
|
|
855
846
|
continue;
|
|
856
|
-
const applicableQuantity =
|
|
847
|
+
const applicableQuantity = getOfferRewardApplicableQuantity(offer);
|
|
857
848
|
if (applicableQuantity != null) {
|
|
858
849
|
const selectedItemsCount = getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, normalizedOfferId);
|
|
859
850
|
// Any partial usage of an item reward still counts as one redeemed slot.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { GIFT_CARD_REWARD_TYPE_ENUM, OFFER_REWARD_TYPE_ENUM, PATHWAY_TO_UNLOCK_TYPE_ENUM, WALLET_CASHBACK_LOYALTY_DISCOUNT_ID, WALLET_CASHBACK_LOYALTY_DISCOUNT_NAME, WALLET_CASHBACK_LOYALTY_REFERENCE, } from '../../constants';
|
|
2
2
|
import { calculateCartOrderInfoAndSyncData } from '../store/cart-actions';
|
|
3
3
|
import { calculateEligibleOfferDiscountDetails, getCappedOfferDiscountAmount, parseNum } from './common';
|
|
4
|
+
import { getOfferRewardApplicableQuantity } from './offers-helpers';
|
|
4
5
|
// ================================><================================= //
|
|
5
6
|
// === Shared order subtotal for discount logic === //
|
|
6
7
|
// ================================><================================= //
|
|
@@ -428,15 +429,6 @@ function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
|
|
|
428
429
|
}
|
|
429
430
|
return true;
|
|
430
431
|
}
|
|
431
|
-
function getItemRewardApplicableQuantity(offer) {
|
|
432
|
-
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
433
|
-
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
434
|
-
}
|
|
435
|
-
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
436
|
-
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
437
|
-
}
|
|
438
|
-
return null;
|
|
439
|
-
}
|
|
440
432
|
function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
|
|
441
433
|
let totalSelectedOfferItems = 0;
|
|
442
434
|
for (let i = 0; i < categories.length; i++) {
|
|
@@ -471,7 +463,7 @@ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, of
|
|
|
471
463
|
const normalizedOfferId = getNormalizedOfferId(offer._id);
|
|
472
464
|
if (normalizedOfferId == null)
|
|
473
465
|
continue;
|
|
474
|
-
const applicableQuantity =
|
|
466
|
+
const applicableQuantity = getOfferRewardApplicableQuantity(offer);
|
|
475
467
|
if (applicableQuantity != null) {
|
|
476
468
|
const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, normalizedOfferId);
|
|
477
469
|
// Percentage strategy: any partial usage of an item reward counts as a redeemed slot.
|
|
@@ -829,6 +829,101 @@ export const getTotalSelectedOfferItemsAgainstOffer = (categories, offer_id) =>
|
|
|
829
829
|
}, 0) ?? 0;
|
|
830
830
|
return totalOfferItems;
|
|
831
831
|
};
|
|
832
|
+
// ====================================================================================================================
|
|
833
|
+
/**
|
|
834
|
+
* Number of reward units one claim of `offer` grants, or `null` when the offer is
|
|
835
|
+
* not an item reward (only ITEMS / DISCOUNT_ITEMS are claimed through cart items).
|
|
836
|
+
*
|
|
837
|
+
* Shared by the eligibility engine and both cart reconciles so the three cannot
|
|
838
|
+
* drift on what "one claim" means for an item reward.
|
|
839
|
+
*/
|
|
840
|
+
export function getOfferRewardApplicableQuantity(offer) {
|
|
841
|
+
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
842
|
+
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
843
|
+
}
|
|
844
|
+
if (offer.reward_type === OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
845
|
+
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
846
|
+
}
|
|
847
|
+
return null;
|
|
848
|
+
}
|
|
849
|
+
// ====================================================================================================================
|
|
850
|
+
/**
|
|
851
|
+
* Claims of `offer` evidenced by stamped cart items.
|
|
852
|
+
*
|
|
853
|
+
* ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
|
|
854
|
+
* selection is persisted on each item's `item_discount_details`. That entry is
|
|
855
|
+
* folded into `redeemed_offers` later, by the cart reconcile — which itself runs
|
|
856
|
+
* only after the cart has already been evaluated. Eligibility that reads ONLY
|
|
857
|
+
* `redeemed_offers` therefore misses the claim for exactly one cycle, and
|
|
858
|
+
* because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
|
|
859
|
+
* points spent by the claim are deducted but never credited back. The offer then
|
|
860
|
+
* reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
|
|
861
|
+
* reconcile strips the reward item that granted it.
|
|
862
|
+
*
|
|
863
|
+
* Counting the same evidence here breaks that cycle. The claim count mirrors the
|
|
864
|
+
* reconcile: any partial usage of a multi-item reward still costs one claim.
|
|
865
|
+
*/
|
|
866
|
+
export function getOfferItemEvidenceClaims({ offer, categories, }) {
|
|
867
|
+
const applicableQuantity = getOfferRewardApplicableQuantity(offer);
|
|
868
|
+
if (applicableQuantity == null) {
|
|
869
|
+
return 0;
|
|
870
|
+
}
|
|
871
|
+
const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, offer._id);
|
|
872
|
+
return selectedItemsCount > 0 ? Math.ceil(selectedItemsCount / applicableQuantity) : 0;
|
|
873
|
+
}
|
|
874
|
+
// ====================================================================================================================
|
|
875
|
+
/**
|
|
876
|
+
* Derive the claim ledger an order SHOULD carry from the state actually applied
|
|
877
|
+
* to it: item rewards from the stamped cart items, order-level rewards from the
|
|
878
|
+
* `order_discount_details` slot they occupy.
|
|
879
|
+
*
|
|
880
|
+
* The ledger is the settlement engine's only input for what the customer spent
|
|
881
|
+
* (`collectCustomerRewardDeltasForOrder` reads `order.redeemed_offers`), so a
|
|
882
|
+
* client that fails to record a claim lets the customer keep the reward for
|
|
883
|
+
* free. This function is the repair/validation counterpart: additive only —
|
|
884
|
+
* it never removes an entry, so it can run on every order write without
|
|
885
|
+
* discarding claims the derivation cannot see (POINTS / CASHBACK / VOUCHER /
|
|
886
|
+
* GIFT_CARDS rewards live in the ledger alone).
|
|
887
|
+
*/
|
|
888
|
+
export function getRedeemedOffersFromAppliedState({ categories, orderDiscountDetails, offers, existingRedeemedOffers, }) {
|
|
889
|
+
const nextRedeemedOffers = {};
|
|
890
|
+
const existingEntries = Object.entries(existingRedeemedOffers ?? {});
|
|
891
|
+
for (let i = 0; i < existingEntries.length; i++) {
|
|
892
|
+
const [offerId, count] = existingEntries[i];
|
|
893
|
+
const normalizedOfferId = normalizeOfferId(offerId);
|
|
894
|
+
const safeCount = toPositiveInteger(count, 0);
|
|
895
|
+
if (normalizedOfferId == null || safeCount <= 0)
|
|
896
|
+
continue;
|
|
897
|
+
nextRedeemedOffers[normalizedOfferId] = safeCount;
|
|
898
|
+
}
|
|
899
|
+
const missingOfferIds = [];
|
|
900
|
+
const recordDerivedClaim = (offerId, derivedClaims) => {
|
|
901
|
+
const normalizedOfferId = normalizeOfferId(offerId);
|
|
902
|
+
if (normalizedOfferId == null || derivedClaims <= 0)
|
|
903
|
+
return;
|
|
904
|
+
const currentCount = toPositiveInteger(nextRedeemedOffers[normalizedOfferId], 0);
|
|
905
|
+
if (currentCount >= derivedClaims)
|
|
906
|
+
return;
|
|
907
|
+
if (currentCount <= 0) {
|
|
908
|
+
missingOfferIds.push(normalizedOfferId);
|
|
909
|
+
}
|
|
910
|
+
nextRedeemedOffers[normalizedOfferId] = derivedClaims;
|
|
911
|
+
};
|
|
912
|
+
for (let i = 0; i < offers.length; i++) {
|
|
913
|
+
const offer = offers[i];
|
|
914
|
+
recordDerivedClaim(offer._id, getOfferItemEvidenceClaims({ offer, categories }));
|
|
915
|
+
}
|
|
916
|
+
// Order-level rewards are proven by the slot they hold, not by cart items.
|
|
917
|
+
const loyaltyDiscountId = orderDiscountDetails?.loyalty_discount_id;
|
|
918
|
+
if (loyaltyDiscountId != null && loyaltyDiscountId !== WALLET_CASHBACK_LOYALTY_DISCOUNT_ID) {
|
|
919
|
+
recordDerivedClaim(loyaltyDiscountId, 1);
|
|
920
|
+
}
|
|
921
|
+
recordDerivedClaim(orderDiscountDetails?.voucher_discount_id, 1);
|
|
922
|
+
return {
|
|
923
|
+
redeemed_offers: Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null,
|
|
924
|
+
missingOfferIds,
|
|
925
|
+
};
|
|
926
|
+
}
|
|
832
927
|
function normalizeOfferId(offerId) {
|
|
833
928
|
if (offerId == null)
|
|
834
929
|
return null;
|
|
@@ -2568,8 +2663,28 @@ export function getOffersWithStats({ offers, customer, vouchers, giftCards, cust
|
|
|
2568
2663
|
totalLoyaltyPointsOfCustomer = loyaltyPoints;
|
|
2569
2664
|
}
|
|
2570
2665
|
const orderLevelClaimSignal = order_discount_details?.loyalty_discount_id === offer._id ? 1 : 0;
|
|
2571
|
-
|
|
2572
|
-
|
|
2666
|
+
// An item reward (ITEMS / DISCOUNT_ITEMS) is claimed by selecting items, so the
|
|
2667
|
+
// cart is its authoritative evidence — the ledger entry is derived from the
|
|
2668
|
+
// cart by the reconcile, never the other way round. Reading the ledger for
|
|
2669
|
+
// these would let a stale entry outlive the item that was removed.
|
|
2670
|
+
// Every other reward is claimed through the ledger (or the order-level discount
|
|
2671
|
+
// slot), so the ledger is authoritative there.
|
|
2672
|
+
const redeemedTimesForCurrentOffer = getOfferRewardApplicableQuantity(offer) != null
|
|
2673
|
+
? getOfferItemEvidenceClaims({ offer, categories })
|
|
2674
|
+
: Math.max(getOfferRedeemedTimes(offer._id), orderLevelClaimSignal);
|
|
2675
|
+
// Edit-only: the order's own consumption was already debited when it was
|
|
2676
|
+
// created, so the balance being evaluated is net of it. Credit it back, or an
|
|
2677
|
+
// order whose reward was paid for reads as unaffordable the moment it is
|
|
2678
|
+
// edited — the reward is then stripped and, because settlement never
|
|
2679
|
+
// re-applies pathway consumption, the customer loses it permanently.
|
|
2680
|
+
//
|
|
2681
|
+
// Clamped to the claims the cart still carries: removing the reward mid-edit
|
|
2682
|
+
// must not mint points, it must just go back to requiring the full cost.
|
|
2683
|
+
const alreadyPaidClaimTimes = isEdit
|
|
2684
|
+
? Math.min(getBaselineRedeemedClaimsForOffer(offer._id), redeemedTimesForCurrentOffer)
|
|
2685
|
+
: 0;
|
|
2686
|
+
const effectiveLoyaltyPointsForCurrentOffer = (totalLoyaltyPointsOfCustomer ?? 0) +
|
|
2687
|
+
(redeemedTimesForCurrentOffer + alreadyPaidClaimTimes) * (num_of_points ?? 0);
|
|
2573
2688
|
const pointsProgress = getPreUnlockProgressPercentage(effectiveLoyaltyPointsForCurrentOffer, num_of_points);
|
|
2574
2689
|
const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
|
|
2575
2690
|
const combinedProgress = Math.min(pointsProgress, amountProgress);
|
|
@@ -83,3 +83,10 @@ export const TENANT_ACTIVE_JOBS_COLLECTION_INDEXES = {
|
|
|
83
83
|
_id: { _id: 1 }, // Unique Index
|
|
84
84
|
tenant_id: { tenant_id: 1 }, // Unique Index — one document per tenant
|
|
85
85
|
};
|
|
86
|
+
export const TENANT_ACTIVE_JOBS_INDEX_OPTIONS = [
|
|
87
|
+
{
|
|
88
|
+
key: TENANT_ACTIVE_JOBS_COLLECTION_INDEXES.tenant_id,
|
|
89
|
+
name: 'tenant_id',
|
|
90
|
+
unique: true,
|
|
91
|
+
},
|
|
92
|
+
];
|
|
@@ -10,6 +10,7 @@ const materialized_tenant_reports_iterations_1 = require("../../schemas/models/m
|
|
|
10
10
|
const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
|
|
11
11
|
const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
|
|
12
12
|
const tenant_calendar_1 = require("../../schemas/models/tenant_calendar");
|
|
13
|
+
const tenant_active_jobs_1 = require("../../schemas/models/tenant_active_jobs");
|
|
13
14
|
/**
|
|
14
15
|
* BOOTSTRAP the indexes the materialized reads/writes assume.
|
|
15
16
|
*
|
|
@@ -32,6 +33,7 @@ const INDEXES = {
|
|
|
32
33
|
[materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS,
|
|
33
34
|
[materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS,
|
|
34
35
|
[tenant_calendar_1.TENANT_CALENDAR_COLLECTION_NAME]: tenant_calendar_1.TENANT_CALENDAR_INDEX_OPTIONS,
|
|
36
|
+
[tenant_active_jobs_1.TENANT_ACTIVE_JOBS_COLLECTION_NAME]: tenant_active_jobs_1.TENANT_ACTIVE_JOBS_INDEX_OPTIONS,
|
|
35
37
|
};
|
|
36
38
|
exports.MATERIALIZED_REPORT_INDEX_COLLECTIONS = Object.keys(INDEXES);
|
|
37
39
|
async function ensureMaterializedReportIndexes(connection, options = {}) {
|
|
@@ -46,6 +48,23 @@ async function ensureMaterializedReportIndexes(connection, options = {}) {
|
|
|
46
48
|
}
|
|
47
49
|
const collection = db.collection(collectionName);
|
|
48
50
|
const indexes = definitions.filter((definition) => definition.name !== '_id_');
|
|
51
|
+
// One-time migration for the old discount-entry identity index. A page
|
|
52
|
+
// design cannot coexist with a unique index that omits `page`.
|
|
53
|
+
if (collectionName === materialized_tenant_discount_entries_1.MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME) {
|
|
54
|
+
const existing = await collection
|
|
55
|
+
.listIndexes()
|
|
56
|
+
.toArray()
|
|
57
|
+
.catch(() => []);
|
|
58
|
+
const legacy = existing.find((index) => index.name === 'tenant_id__scope_context__scope_field__day_index' ||
|
|
59
|
+
(index.unique === true &&
|
|
60
|
+
index.key?.tenant_id === 1 &&
|
|
61
|
+
index.key?.scope_context === 1 &&
|
|
62
|
+
index.key?.scope_field === 1 &&
|
|
63
|
+
index.key?.day_index === 1 &&
|
|
64
|
+
index.key?.page == null));
|
|
65
|
+
if (legacy != null)
|
|
66
|
+
await collection.dropIndex(legacy.name);
|
|
67
|
+
}
|
|
49
68
|
try {
|
|
50
69
|
await collection.createIndexes(indexes);
|
|
51
70
|
}
|
|
@@ -844,15 +844,6 @@ function areRedeemedOffersEqualForOfferSync(currentRedeemedOffers, nextRedeemedO
|
|
|
844
844
|
}
|
|
845
845
|
return true;
|
|
846
846
|
}
|
|
847
|
-
function getItemRewardApplicableQuantityForOfferSync(offer) {
|
|
848
|
-
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
849
|
-
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
850
|
-
}
|
|
851
|
-
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
852
|
-
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
853
|
-
}
|
|
854
|
-
return null;
|
|
855
|
-
}
|
|
856
847
|
function getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, offerId) {
|
|
857
848
|
let totalSelectedOfferItems = 0;
|
|
858
849
|
for (let i = 0; i < categories.length; i++) {
|
|
@@ -887,7 +878,7 @@ function getReconciledRedeemedOffersMapForOfferSync({ existingRedeemedOffers, ca
|
|
|
887
878
|
const normalizedOfferId = getNormalizedOfferId(offer._id);
|
|
888
879
|
if (normalizedOfferId == null)
|
|
889
880
|
continue;
|
|
890
|
-
const applicableQuantity =
|
|
881
|
+
const applicableQuantity = (0, offers_helpers_1.getOfferRewardApplicableQuantity)(offer);
|
|
891
882
|
if (applicableQuantity != null) {
|
|
892
883
|
const selectedItemsCount = getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, normalizedOfferId);
|
|
893
884
|
// Any partial usage of an item reward still counts as one redeemed slot.
|
|
@@ -10,6 +10,7 @@ exports.getSyncOffersWithCartData = getSyncOffersWithCartData;
|
|
|
10
10
|
const constants_1 = require("../../constants");
|
|
11
11
|
const cart_actions_1 = require("../store/cart-actions");
|
|
12
12
|
const common_1 = require("./common");
|
|
13
|
+
const offers_helpers_1 = require("./offers-helpers");
|
|
13
14
|
// ================================><================================= //
|
|
14
15
|
// === Shared order subtotal for discount logic === //
|
|
15
16
|
// ================================><================================= //
|
|
@@ -437,15 +438,6 @@ function areRedeemedOffersEqual(currentRedeemedOffers, nextRedeemedOffers) {
|
|
|
437
438
|
}
|
|
438
439
|
return true;
|
|
439
440
|
}
|
|
440
|
-
function getItemRewardApplicableQuantity(offer) {
|
|
441
|
-
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
442
|
-
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
443
|
-
}
|
|
444
|
-
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
445
|
-
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
446
|
-
}
|
|
447
|
-
return null;
|
|
448
|
-
}
|
|
449
441
|
function getTotalSelectedOfferItemsAgainstOffer(categories, offerId) {
|
|
450
442
|
let totalSelectedOfferItems = 0;
|
|
451
443
|
for (let i = 0; i < categories.length; i++) {
|
|
@@ -480,7 +472,7 @@ function getReconciledRedeemedOffersMap({ existingRedeemedOffers, categories, of
|
|
|
480
472
|
const normalizedOfferId = getNormalizedOfferId(offer._id);
|
|
481
473
|
if (normalizedOfferId == null)
|
|
482
474
|
continue;
|
|
483
|
-
const applicableQuantity =
|
|
475
|
+
const applicableQuantity = (0, offers_helpers_1.getOfferRewardApplicableQuantity)(offer);
|
|
484
476
|
if (applicableQuantity != null) {
|
|
485
477
|
const selectedItemsCount = getTotalSelectedOfferItemsAgainstOffer(categories, normalizedOfferId);
|
|
486
478
|
// Percentage strategy: any partial usage of an item reward counts as a redeemed slot.
|
|
@@ -91,6 +91,56 @@ export declare function calculateCustomerLoyaltyPoints({ customerLoyaltyPoints,
|
|
|
91
91
|
deductedLoyaltyPoints: number;
|
|
92
92
|
};
|
|
93
93
|
export declare const getTotalSelectedOfferItemsAgainstOffer: (categories: IOrderCategory[] | undefined, offer_id: string) => number;
|
|
94
|
+
/**
|
|
95
|
+
* Number of reward units one claim of `offer` grants, or `null` when the offer is
|
|
96
|
+
* not an item reward (only ITEMS / DISCOUNT_ITEMS are claimed through cart items).
|
|
97
|
+
*
|
|
98
|
+
* Shared by the eligibility engine and both cart reconciles so the three cannot
|
|
99
|
+
* drift on what "one claim" means for an item reward.
|
|
100
|
+
*/
|
|
101
|
+
export declare function getOfferRewardApplicableQuantity(offer: IOffer): number | null;
|
|
102
|
+
/**
|
|
103
|
+
* Claims of `offer` evidenced by stamped cart items.
|
|
104
|
+
*
|
|
105
|
+
* ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
|
|
106
|
+
* selection is persisted on each item's `item_discount_details`. That entry is
|
|
107
|
+
* folded into `redeemed_offers` later, by the cart reconcile — which itself runs
|
|
108
|
+
* only after the cart has already been evaluated. Eligibility that reads ONLY
|
|
109
|
+
* `redeemed_offers` therefore misses the claim for exactly one cycle, and
|
|
110
|
+
* because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
|
|
111
|
+
* points spent by the claim are deducted but never credited back. The offer then
|
|
112
|
+
* reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
|
|
113
|
+
* reconcile strips the reward item that granted it.
|
|
114
|
+
*
|
|
115
|
+
* Counting the same evidence here breaks that cycle. The claim count mirrors the
|
|
116
|
+
* reconcile: any partial usage of a multi-item reward still costs one claim.
|
|
117
|
+
*/
|
|
118
|
+
export declare function getOfferItemEvidenceClaims({ offer, categories, }: {
|
|
119
|
+
offer: IOffer;
|
|
120
|
+
categories: IOrderCategory[] | undefined;
|
|
121
|
+
}): number;
|
|
122
|
+
/**
|
|
123
|
+
* Derive the claim ledger an order SHOULD carry from the state actually applied
|
|
124
|
+
* to it: item rewards from the stamped cart items, order-level rewards from the
|
|
125
|
+
* `order_discount_details` slot they occupy.
|
|
126
|
+
*
|
|
127
|
+
* The ledger is the settlement engine's only input for what the customer spent
|
|
128
|
+
* (`collectCustomerRewardDeltasForOrder` reads `order.redeemed_offers`), so a
|
|
129
|
+
* client that fails to record a claim lets the customer keep the reward for
|
|
130
|
+
* free. This function is the repair/validation counterpart: additive only —
|
|
131
|
+
* it never removes an entry, so it can run on every order write without
|
|
132
|
+
* discarding claims the derivation cannot see (POINTS / CASHBACK / VOUCHER /
|
|
133
|
+
* GIFT_CARDS rewards live in the ledger alone).
|
|
134
|
+
*/
|
|
135
|
+
export declare function getRedeemedOffersFromAppliedState({ categories, orderDiscountDetails, offers, existingRedeemedOffers, }: {
|
|
136
|
+
categories: IOrderCategory[] | undefined;
|
|
137
|
+
orderDiscountDetails: IDiscountDetails | null | undefined;
|
|
138
|
+
offers: IOffer[];
|
|
139
|
+
existingRedeemedOffers: IOrder['redeemed_offers'] | null | undefined;
|
|
140
|
+
}): {
|
|
141
|
+
redeemed_offers: IOrder['redeemed_offers'];
|
|
142
|
+
missingOfferIds: string[];
|
|
143
|
+
};
|
|
94
144
|
interface IRewardPreview {
|
|
95
145
|
type: OFFER_REWARD_TYPE_ENUM;
|
|
96
146
|
label: string;
|
|
@@ -11,6 +11,9 @@ exports.buildClearVoucherDiscountDetails = buildClearVoucherDiscountDetails;
|
|
|
11
11
|
exports.calculateCustomerSpendableVoucherCodes = calculateCustomerSpendableVoucherCodes;
|
|
12
12
|
exports.calculateCustomerSpendableGiftCardCodes = calculateCustomerSpendableGiftCardCodes;
|
|
13
13
|
exports.calculateCustomerLoyaltyPoints = calculateCustomerLoyaltyPoints;
|
|
14
|
+
exports.getOfferRewardApplicableQuantity = getOfferRewardApplicableQuantity;
|
|
15
|
+
exports.getOfferItemEvidenceClaims = getOfferItemEvidenceClaims;
|
|
16
|
+
exports.getRedeemedOffersFromAppliedState = getRedeemedOffersFromAppliedState;
|
|
14
17
|
exports.getOfferUsageLimitMeta = getOfferUsageLimitMeta;
|
|
15
18
|
exports.getOfferConsumedUses = getOfferConsumedUses;
|
|
16
19
|
exports.isOfferFullyConsumedForCustomer = isOfferFullyConsumedForCustomer;
|
|
@@ -863,6 +866,101 @@ const getTotalSelectedOfferItemsAgainstOffer = (categories, offer_id) => {
|
|
|
863
866
|
return totalOfferItems;
|
|
864
867
|
};
|
|
865
868
|
exports.getTotalSelectedOfferItemsAgainstOffer = getTotalSelectedOfferItemsAgainstOffer;
|
|
869
|
+
// ====================================================================================================================
|
|
870
|
+
/**
|
|
871
|
+
* Number of reward units one claim of `offer` grants, or `null` when the offer is
|
|
872
|
+
* not an item reward (only ITEMS / DISCOUNT_ITEMS are claimed through cart items).
|
|
873
|
+
*
|
|
874
|
+
* Shared by the eligibility engine and both cart reconciles so the three cannot
|
|
875
|
+
* drift on what "one claim" means for an item reward.
|
|
876
|
+
*/
|
|
877
|
+
function getOfferRewardApplicableQuantity(offer) {
|
|
878
|
+
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
879
|
+
return toPositiveInteger(offer.reward_items?.num_of_items, 1);
|
|
880
|
+
}
|
|
881
|
+
if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
|
|
882
|
+
return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
|
|
883
|
+
}
|
|
884
|
+
return null;
|
|
885
|
+
}
|
|
886
|
+
// ====================================================================================================================
|
|
887
|
+
/**
|
|
888
|
+
* Claims of `offer` evidenced by stamped cart items.
|
|
889
|
+
*
|
|
890
|
+
* ITEMS / DISCOUNT_ITEMS rewards are claimed by selecting items, and the
|
|
891
|
+
* selection is persisted on each item's `item_discount_details`. That entry is
|
|
892
|
+
* folded into `redeemed_offers` later, by the cart reconcile — which itself runs
|
|
893
|
+
* only after the cart has already been evaluated. Eligibility that reads ONLY
|
|
894
|
+
* `redeemed_offers` therefore misses the claim for exactly one cycle, and
|
|
895
|
+
* because `calculateCustomerLoyaltyPoints` does count the cart-item evidence, the
|
|
896
|
+
* points spent by the claim are deducted but never credited back. The offer then
|
|
897
|
+
* reads unaffordable, `unlockedOffersApplicableTimes` drops to 0 and the cart
|
|
898
|
+
* reconcile strips the reward item that granted it.
|
|
899
|
+
*
|
|
900
|
+
* Counting the same evidence here breaks that cycle. The claim count mirrors the
|
|
901
|
+
* reconcile: any partial usage of a multi-item reward still costs one claim.
|
|
902
|
+
*/
|
|
903
|
+
function getOfferItemEvidenceClaims({ offer, categories, }) {
|
|
904
|
+
const applicableQuantity = getOfferRewardApplicableQuantity(offer);
|
|
905
|
+
if (applicableQuantity == null) {
|
|
906
|
+
return 0;
|
|
907
|
+
}
|
|
908
|
+
const selectedItemsCount = (0, exports.getTotalSelectedOfferItemsAgainstOffer)(categories, offer._id);
|
|
909
|
+
return selectedItemsCount > 0 ? Math.ceil(selectedItemsCount / applicableQuantity) : 0;
|
|
910
|
+
}
|
|
911
|
+
// ====================================================================================================================
|
|
912
|
+
/**
|
|
913
|
+
* Derive the claim ledger an order SHOULD carry from the state actually applied
|
|
914
|
+
* to it: item rewards from the stamped cart items, order-level rewards from the
|
|
915
|
+
* `order_discount_details` slot they occupy.
|
|
916
|
+
*
|
|
917
|
+
* The ledger is the settlement engine's only input for what the customer spent
|
|
918
|
+
* (`collectCustomerRewardDeltasForOrder` reads `order.redeemed_offers`), so a
|
|
919
|
+
* client that fails to record a claim lets the customer keep the reward for
|
|
920
|
+
* free. This function is the repair/validation counterpart: additive only —
|
|
921
|
+
* it never removes an entry, so it can run on every order write without
|
|
922
|
+
* discarding claims the derivation cannot see (POINTS / CASHBACK / VOUCHER /
|
|
923
|
+
* GIFT_CARDS rewards live in the ledger alone).
|
|
924
|
+
*/
|
|
925
|
+
function getRedeemedOffersFromAppliedState({ categories, orderDiscountDetails, offers, existingRedeemedOffers, }) {
|
|
926
|
+
const nextRedeemedOffers = {};
|
|
927
|
+
const existingEntries = Object.entries(existingRedeemedOffers ?? {});
|
|
928
|
+
for (let i = 0; i < existingEntries.length; i++) {
|
|
929
|
+
const [offerId, count] = existingEntries[i];
|
|
930
|
+
const normalizedOfferId = normalizeOfferId(offerId);
|
|
931
|
+
const safeCount = toPositiveInteger(count, 0);
|
|
932
|
+
if (normalizedOfferId == null || safeCount <= 0)
|
|
933
|
+
continue;
|
|
934
|
+
nextRedeemedOffers[normalizedOfferId] = safeCount;
|
|
935
|
+
}
|
|
936
|
+
const missingOfferIds = [];
|
|
937
|
+
const recordDerivedClaim = (offerId, derivedClaims) => {
|
|
938
|
+
const normalizedOfferId = normalizeOfferId(offerId);
|
|
939
|
+
if (normalizedOfferId == null || derivedClaims <= 0)
|
|
940
|
+
return;
|
|
941
|
+
const currentCount = toPositiveInteger(nextRedeemedOffers[normalizedOfferId], 0);
|
|
942
|
+
if (currentCount >= derivedClaims)
|
|
943
|
+
return;
|
|
944
|
+
if (currentCount <= 0) {
|
|
945
|
+
missingOfferIds.push(normalizedOfferId);
|
|
946
|
+
}
|
|
947
|
+
nextRedeemedOffers[normalizedOfferId] = derivedClaims;
|
|
948
|
+
};
|
|
949
|
+
for (let i = 0; i < offers.length; i++) {
|
|
950
|
+
const offer = offers[i];
|
|
951
|
+
recordDerivedClaim(offer._id, getOfferItemEvidenceClaims({ offer, categories }));
|
|
952
|
+
}
|
|
953
|
+
// Order-level rewards are proven by the slot they hold, not by cart items.
|
|
954
|
+
const loyaltyDiscountId = orderDiscountDetails?.loyalty_discount_id;
|
|
955
|
+
if (loyaltyDiscountId != null && loyaltyDiscountId !== constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID) {
|
|
956
|
+
recordDerivedClaim(loyaltyDiscountId, 1);
|
|
957
|
+
}
|
|
958
|
+
recordDerivedClaim(orderDiscountDetails?.voucher_discount_id, 1);
|
|
959
|
+
return {
|
|
960
|
+
redeemed_offers: Object.keys(nextRedeemedOffers).length > 0 ? nextRedeemedOffers : null,
|
|
961
|
+
missingOfferIds,
|
|
962
|
+
};
|
|
963
|
+
}
|
|
866
964
|
function normalizeOfferId(offerId) {
|
|
867
965
|
if (offerId == null)
|
|
868
966
|
return null;
|
|
@@ -2602,8 +2700,28 @@ function getOffersWithStats({ offers, customer, vouchers, giftCards, customerOff
|
|
|
2602
2700
|
totalLoyaltyPointsOfCustomer = loyaltyPoints;
|
|
2603
2701
|
}
|
|
2604
2702
|
const orderLevelClaimSignal = order_discount_details?.loyalty_discount_id === offer._id ? 1 : 0;
|
|
2605
|
-
|
|
2606
|
-
|
|
2703
|
+
// An item reward (ITEMS / DISCOUNT_ITEMS) is claimed by selecting items, so the
|
|
2704
|
+
// cart is its authoritative evidence — the ledger entry is derived from the
|
|
2705
|
+
// cart by the reconcile, never the other way round. Reading the ledger for
|
|
2706
|
+
// these would let a stale entry outlive the item that was removed.
|
|
2707
|
+
// Every other reward is claimed through the ledger (or the order-level discount
|
|
2708
|
+
// slot), so the ledger is authoritative there.
|
|
2709
|
+
const redeemedTimesForCurrentOffer = getOfferRewardApplicableQuantity(offer) != null
|
|
2710
|
+
? getOfferItemEvidenceClaims({ offer, categories })
|
|
2711
|
+
: Math.max(getOfferRedeemedTimes(offer._id), orderLevelClaimSignal);
|
|
2712
|
+
// Edit-only: the order's own consumption was already debited when it was
|
|
2713
|
+
// created, so the balance being evaluated is net of it. Credit it back, or an
|
|
2714
|
+
// order whose reward was paid for reads as unaffordable the moment it is
|
|
2715
|
+
// edited — the reward is then stripped and, because settlement never
|
|
2716
|
+
// re-applies pathway consumption, the customer loses it permanently.
|
|
2717
|
+
//
|
|
2718
|
+
// Clamped to the claims the cart still carries: removing the reward mid-edit
|
|
2719
|
+
// must not mint points, it must just go back to requiring the full cost.
|
|
2720
|
+
const alreadyPaidClaimTimes = isEdit
|
|
2721
|
+
? Math.min(getBaselineRedeemedClaimsForOffer(offer._id), redeemedTimesForCurrentOffer)
|
|
2722
|
+
: 0;
|
|
2723
|
+
const effectiveLoyaltyPointsForCurrentOffer = (totalLoyaltyPointsOfCustomer ?? 0) +
|
|
2724
|
+
(redeemedTimesForCurrentOffer + alreadyPaidClaimTimes) * (num_of_points ?? 0);
|
|
2607
2725
|
const pointsProgress = getPreUnlockProgressPercentage(effectiveLoyaltyPointsForCurrentOffer, num_of_points);
|
|
2608
2726
|
const amountProgress = getPreUnlockProgressPercentage(orderValue, total_amount);
|
|
2609
2727
|
const combinedProgress = Math.min(pointsProgress, amountProgress);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.TENANT_ACTIVE_JOBS_COLLECTION_INDEXES = exports.TENANT_ACTIVE_JOBS_COLLECTION_NAME = exports.TenantActiveJobSchema = void 0;
|
|
3
|
+
exports.TENANT_ACTIVE_JOBS_INDEX_OPTIONS = exports.TENANT_ACTIVE_JOBS_COLLECTION_INDEXES = exports.TENANT_ACTIVE_JOBS_COLLECTION_NAME = exports.TenantActiveJobSchema = void 0;
|
|
4
4
|
const mongoose_1 = require("mongoose");
|
|
5
5
|
const constants_1 = require("../../constants");
|
|
6
6
|
exports.TenantActiveJobSchema = new mongoose_1.Schema({
|
|
@@ -86,3 +86,10 @@ exports.TENANT_ACTIVE_JOBS_COLLECTION_INDEXES = {
|
|
|
86
86
|
_id: { _id: 1 }, // Unique Index
|
|
87
87
|
tenant_id: { tenant_id: 1 }, // Unique Index — one document per tenant
|
|
88
88
|
};
|
|
89
|
+
exports.TENANT_ACTIVE_JOBS_INDEX_OPTIONS = [
|
|
90
|
+
{
|
|
91
|
+
key: exports.TENANT_ACTIVE_JOBS_COLLECTION_INDEXES.tenant_id,
|
|
92
|
+
name: 'tenant_id',
|
|
93
|
+
unique: true,
|
|
94
|
+
},
|
|
95
|
+
];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const constants_1 = require("../constants");
|
|
4
|
+
const offer_apply_helpers_1 = require("../helpers/utils/offer-apply-helpers");
|
|
5
|
+
const offers_helpers_1 = require("../helpers/utils/offers-helpers");
|
|
6
|
+
/**
|
|
7
|
+
* A POINTS-pathway offer pays for its reward with the customer's points. The
|
|
8
|
+
* claim is evidenced by the stamped cart item (ITEMS / DISCOUNT_ITEMS rewards)
|
|
9
|
+
* and only folded into `redeemed_offers` later, by the cart reconcile.
|
|
10
|
+
*
|
|
11
|
+
* Eligibility used to read only `redeemed_offers` when crediting the claim back,
|
|
12
|
+
* while `calculateCustomerLoyaltyPoints` did count the cart-item evidence when
|
|
13
|
+
* deducting it. The points were therefore deducted twice-ish (once from the
|
|
14
|
+
* balance, once ignored on the way back), the offer read unaffordable, and the
|
|
15
|
+
* cart reconcile stripped the reward item that had just been claimed.
|
|
16
|
+
*
|
|
17
|
+
* These tests pin the boundary: the reward must survive as soon as the customer
|
|
18
|
+
* can actually afford it (balance >= num_of_points), not at 2x that.
|
|
19
|
+
*/
|
|
20
|
+
const PAID_ITEM_ID = 'item-half-broast';
|
|
21
|
+
const CATEGORY_ID = 'category-broast';
|
|
22
|
+
const REWARD_OFFER_ID = 'offer-redeem-points';
|
|
23
|
+
const EARN_OFFER_ID = 'offer-buy-one-earn-point';
|
|
24
|
+
const PAID_ITEM = {
|
|
25
|
+
_id: 'cart-item-paid',
|
|
26
|
+
item_id: PAID_ITEM_ID,
|
|
27
|
+
name: 'Half Broast Mix',
|
|
28
|
+
quantity: 1,
|
|
29
|
+
price: 1206.03,
|
|
30
|
+
subtotal: 1025.13,
|
|
31
|
+
tax_rate: 0,
|
|
32
|
+
modifiers: [],
|
|
33
|
+
special_instructions: '',
|
|
34
|
+
item_discount_details: {
|
|
35
|
+
special_discount: 15,
|
|
36
|
+
special_discount_id: PAID_ITEM_ID,
|
|
37
|
+
special_discount_name: 'Special Discount',
|
|
38
|
+
is_special_discount_percentage: true,
|
|
39
|
+
total_discount: 180.9,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
function makeRewardItem() {
|
|
43
|
+
return {
|
|
44
|
+
_id: 'cart-item-reward',
|
|
45
|
+
item_id: PAID_ITEM_ID,
|
|
46
|
+
name: 'Half Broast Mix',
|
|
47
|
+
quantity: 1,
|
|
48
|
+
price: 1206.03,
|
|
49
|
+
subtotal: 0,
|
|
50
|
+
tax_rate: 0,
|
|
51
|
+
modifiers: [],
|
|
52
|
+
special_instructions: '',
|
|
53
|
+
item_discount_details: {
|
|
54
|
+
loyalty_discount: 100,
|
|
55
|
+
loyalty_discount_id: REWARD_OFFER_ID,
|
|
56
|
+
loyalty_discount_name: 'Redeem 7 Loyalty Points & Get 1 Half Broast Free',
|
|
57
|
+
is_loyalty_discount_percentage: true,
|
|
58
|
+
total_discount: 1206.03,
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function makeCategories(items) {
|
|
63
|
+
return [{ category_id: CATEGORY_ID, name: 'BROAST', items }];
|
|
64
|
+
}
|
|
65
|
+
function makeEarnOffer() {
|
|
66
|
+
return {
|
|
67
|
+
_id: EARN_OFFER_ID,
|
|
68
|
+
name: 'Buy 1 Broast & Get 1 Loyalty Point',
|
|
69
|
+
active: true,
|
|
70
|
+
auto_apply: true,
|
|
71
|
+
sort_id: 7,
|
|
72
|
+
included_platforms: [constants_1.PLATFORMS_ENUM.APP_DELIVERY],
|
|
73
|
+
offer_special_hours: null,
|
|
74
|
+
pathway_to_unlock_type: constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.ITEMS,
|
|
75
|
+
pathway_to_unlock_type_items: {
|
|
76
|
+
num_of_items: 1,
|
|
77
|
+
max_uses_per_customer: null,
|
|
78
|
+
max_claims: 10000,
|
|
79
|
+
min_same_item_quantity: null,
|
|
80
|
+
max_same_item_quantity: null,
|
|
81
|
+
total_amount: 1,
|
|
82
|
+
excluded_refs: [],
|
|
83
|
+
exclusive_refs: [],
|
|
84
|
+
item_ids: [PAID_ITEM_ID],
|
|
85
|
+
category_ids: [CATEGORY_ID],
|
|
86
|
+
},
|
|
87
|
+
reward_type: constants_1.OFFER_REWARD_TYPE_ENUM.POINTS,
|
|
88
|
+
reward_points: { num_of_points: 1, once_per_order: false },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function makeRewardOffer({ rewardType = constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS, numOfPoints = 7, } = {}) {
|
|
92
|
+
const base = {
|
|
93
|
+
_id: REWARD_OFFER_ID,
|
|
94
|
+
name: 'Redeem 7 Loyalty Points & Get 1 Half Broast Free',
|
|
95
|
+
active: true,
|
|
96
|
+
auto_apply: false,
|
|
97
|
+
sort_id: 8,
|
|
98
|
+
included_platforms: [constants_1.PLATFORMS_ENUM.APP_DELIVERY],
|
|
99
|
+
offer_special_hours: null,
|
|
100
|
+
pathway_to_unlock_type: constants_1.PATHWAY_TO_UNLOCK_TYPE_ENUM.POINTS,
|
|
101
|
+
pathway_to_unlock_type_points: {
|
|
102
|
+
num_of_points: numOfPoints,
|
|
103
|
+
total_amount: 0,
|
|
104
|
+
max_uses_per_customer: null,
|
|
105
|
+
max_claims: 1,
|
|
106
|
+
},
|
|
107
|
+
reward_type: rewardType,
|
|
108
|
+
};
|
|
109
|
+
if (rewardType === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
|
|
110
|
+
base.reward_items = {
|
|
111
|
+
num_of_items: 1,
|
|
112
|
+
excluded_refs: [],
|
|
113
|
+
exclusive_refs: [],
|
|
114
|
+
item_ids: [PAID_ITEM_ID],
|
|
115
|
+
allocation: null,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
else if (rewardType === constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK) {
|
|
119
|
+
base.reward_cashback = {
|
|
120
|
+
cashback_value: 10,
|
|
121
|
+
is_cashback_percentage: false,
|
|
122
|
+
max_cashback_amount: null,
|
|
123
|
+
excluded_refs: [],
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
return base;
|
|
127
|
+
}
|
|
128
|
+
function makeCustomer(loyaltyPoints) {
|
|
129
|
+
return {
|
|
130
|
+
phone_number: '+923218852198',
|
|
131
|
+
loyalty_points: loyaltyPoints,
|
|
132
|
+
cashback_balance: 0,
|
|
133
|
+
total_orders: 13,
|
|
134
|
+
total_orders_per_platform_type: { [constants_1.PLATFORMS_ENUM.APP_DELIVERY]: 6 },
|
|
135
|
+
voucher_codes: {},
|
|
136
|
+
gift_cards: {},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function runStats({ loyaltyPoints, items, redeemedOffers = { [EARN_OFFER_ID]: 1 }, offers = [makeEarnOffer(), makeRewardOffer()], isEdit = false, editedOrderRedeemedOffers = null, }) {
|
|
140
|
+
const result = (0, offers_helpers_1.getOffersWithStats)({
|
|
141
|
+
offers,
|
|
142
|
+
customer: makeCustomer(loyaltyPoints),
|
|
143
|
+
vouchers: [],
|
|
144
|
+
giftCards: [],
|
|
145
|
+
customerOfferRedemptionCounts: { ASSIGNED: {}, USED: { [EARN_OFFER_ID]: 9 } },
|
|
146
|
+
redeemed_offers: redeemedOffers,
|
|
147
|
+
platform: constants_1.PLATFORMS_ENUM.APP_DELIVERY,
|
|
148
|
+
currency_symbol: constants_1.CURRENCY_SYMBOL_ENUM.Rs,
|
|
149
|
+
currentItemsPrice: 1206.03,
|
|
150
|
+
totalDiscountApplied: 180.9,
|
|
151
|
+
categories: makeCategories(items),
|
|
152
|
+
order_discount_details: null,
|
|
153
|
+
...(isEdit ? { isEdit, editedOrderRedeemedOffers } : {}),
|
|
154
|
+
});
|
|
155
|
+
return {
|
|
156
|
+
result,
|
|
157
|
+
stats: result.offersWithStats.find((entry) => entry.offer._id === REWARD_OFFER_ID).stats,
|
|
158
|
+
unlocked: result.unlockedOffersApplicableTimes[REWARD_OFFER_ID],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
describe('item-reward claim evidence', () => {
|
|
162
|
+
it('reports one claim per num_of_items for item rewards and null otherwise', () => {
|
|
163
|
+
expect((0, offers_helpers_1.getOfferRewardApplicableQuantity)(makeRewardOffer())).toBe(1);
|
|
164
|
+
expect((0, offers_helpers_1.getOfferRewardApplicableQuantity)(makeEarnOffer())).toBeNull();
|
|
165
|
+
expect((0, offers_helpers_1.getOfferRewardApplicableQuantity)(makeRewardOffer({ rewardType: constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK }))).toBeNull();
|
|
166
|
+
});
|
|
167
|
+
it('counts stamped cart items as claims, rounding partial usage up', () => {
|
|
168
|
+
expect((0, offers_helpers_1.getOfferItemEvidenceClaims)({ offer: makeRewardOffer(), categories: makeCategories([PAID_ITEM]) })).toBe(0);
|
|
169
|
+
expect((0, offers_helpers_1.getOfferItemEvidenceClaims)({ offer: makeRewardOffer(), categories: makeCategories([makeRewardItem()]) })).toBe(1);
|
|
170
|
+
expect((0, offers_helpers_1.getOfferItemEvidenceClaims)({
|
|
171
|
+
offer: makeRewardOffer(),
|
|
172
|
+
categories: makeCategories([{ ...makeRewardItem(), quantity: 2 }]),
|
|
173
|
+
})).toBe(2);
|
|
174
|
+
});
|
|
175
|
+
it('ignores cart items for a reward that is not an item reward', () => {
|
|
176
|
+
expect((0, offers_helpers_1.getOfferItemEvidenceClaims)({
|
|
177
|
+
offer: makeRewardOffer({ rewardType: constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK }),
|
|
178
|
+
categories: makeCategories([makeRewardItem()]),
|
|
179
|
+
})).toBe(0);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
describe('POINTS-pathway eligibility with a claimed item reward', () => {
|
|
183
|
+
it('keeps the reward unlocked once the customer can afford it, before the ledger is written', () => {
|
|
184
|
+
const { stats, unlocked } = runStats({ loyaltyPoints: 7, items: [PAID_ITEM, makeRewardItem()] });
|
|
185
|
+
expect(unlocked).toBe(1);
|
|
186
|
+
expect(stats.message).not.toContain('away from unlocking');
|
|
187
|
+
});
|
|
188
|
+
it('regression: the claim no longer self-destructs at balance == num_of_points (was: required 2x)', () => {
|
|
189
|
+
for (const loyaltyPoints of [7, 8, 13, 14]) {
|
|
190
|
+
const { unlocked } = runStats({ loyaltyPoints, items: [PAID_ITEM, makeRewardItem()] });
|
|
191
|
+
expect(unlocked).toBe(1);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
it('still strips the reward when the customer genuinely cannot afford it', () => {
|
|
195
|
+
const { stats, unlocked } = runStats({ loyaltyPoints: 6, items: [PAID_ITEM, makeRewardItem()] });
|
|
196
|
+
expect(unlocked).toBeUndefined();
|
|
197
|
+
expect(stats.message).toBe('You are 1 points away from unlocking this offer');
|
|
198
|
+
});
|
|
199
|
+
it('does not double-credit when the claim is already in the ledger', () => {
|
|
200
|
+
const { unlocked } = runStats({
|
|
201
|
+
loyaltyPoints: 7,
|
|
202
|
+
items: [PAID_ITEM, makeRewardItem()],
|
|
203
|
+
redeemedOffers: { [EARN_OFFER_ID]: 1, [REWARD_OFFER_ID]: 1 },
|
|
204
|
+
});
|
|
205
|
+
expect(unlocked).toBe(1);
|
|
206
|
+
});
|
|
207
|
+
it('leaves a non-item reward on the POS-pathway driven by the ledger only', () => {
|
|
208
|
+
const offers = [makeEarnOffer(), makeRewardOffer({ rewardType: constants_1.OFFER_REWARD_TYPE_ENUM.CASHBACK })];
|
|
209
|
+
const { stats } = runStats({
|
|
210
|
+
loyaltyPoints: 7,
|
|
211
|
+
items: [PAID_ITEM, makeRewardItem()],
|
|
212
|
+
offers,
|
|
213
|
+
});
|
|
214
|
+
expect(stats.invalid_offer).toBe(false);
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
describe('getRedeemedOffersFromAppliedState (repair / validation)', () => {
|
|
218
|
+
it('adds a missing item-reward claim derived from the stamped items', () => {
|
|
219
|
+
const result = (0, offers_helpers_1.getRedeemedOffersFromAppliedState)({
|
|
220
|
+
categories: makeCategories([PAID_ITEM, makeRewardItem()]),
|
|
221
|
+
orderDiscountDetails: null,
|
|
222
|
+
offers: [makeEarnOffer(), makeRewardOffer()],
|
|
223
|
+
existingRedeemedOffers: { [EARN_OFFER_ID]: 1 },
|
|
224
|
+
});
|
|
225
|
+
expect(result.redeemed_offers).toEqual({ [EARN_OFFER_ID]: 1, [REWARD_OFFER_ID]: 1 });
|
|
226
|
+
expect(result.missingOfferIds).toEqual([REWARD_OFFER_ID]);
|
|
227
|
+
});
|
|
228
|
+
it('adds the claim held by an order-level discount slot', () => {
|
|
229
|
+
const result = (0, offers_helpers_1.getRedeemedOffersFromAppliedState)({
|
|
230
|
+
categories: makeCategories([PAID_ITEM]),
|
|
231
|
+
orderDiscountDetails: { total_discount: 5, loyalty_discount_id: EARN_OFFER_ID },
|
|
232
|
+
offers: [makeEarnOffer(), makeRewardOffer()],
|
|
233
|
+
existingRedeemedOffers: null,
|
|
234
|
+
});
|
|
235
|
+
expect(result.redeemed_offers).toEqual({ [EARN_OFFER_ID]: 1 });
|
|
236
|
+
expect(result.missingOfferIds).toEqual([EARN_OFFER_ID]);
|
|
237
|
+
});
|
|
238
|
+
it('keeps ledger-only claims it cannot derive from applied state', () => {
|
|
239
|
+
const result = (0, offers_helpers_1.getRedeemedOffersFromAppliedState)({
|
|
240
|
+
categories: makeCategories([PAID_ITEM]),
|
|
241
|
+
orderDiscountDetails: null,
|
|
242
|
+
offers: [makeEarnOffer(), makeRewardOffer()],
|
|
243
|
+
existingRedeemedOffers: { [REWARD_OFFER_ID]: 2 },
|
|
244
|
+
});
|
|
245
|
+
expect(result.redeemed_offers).toEqual({ [REWARD_OFFER_ID]: 2 });
|
|
246
|
+
expect(result.missingOfferIds).toEqual([]);
|
|
247
|
+
});
|
|
248
|
+
it('never lowers an existing count', () => {
|
|
249
|
+
const result = (0, offers_helpers_1.getRedeemedOffersFromAppliedState)({
|
|
250
|
+
categories: makeCategories([PAID_ITEM, makeRewardItem()]),
|
|
251
|
+
orderDiscountDetails: null,
|
|
252
|
+
offers: [makeRewardOffer()],
|
|
253
|
+
existingRedeemedOffers: { [REWARD_OFFER_ID]: 3 },
|
|
254
|
+
});
|
|
255
|
+
expect(result.redeemed_offers).toEqual({ [REWARD_OFFER_ID]: 3 });
|
|
256
|
+
});
|
|
257
|
+
it('ignores the wallet-cashback sentinel discount id', () => {
|
|
258
|
+
const result = (0, offers_helpers_1.getRedeemedOffersFromAppliedState)({
|
|
259
|
+
categories: makeCategories([PAID_ITEM]),
|
|
260
|
+
orderDiscountDetails: {
|
|
261
|
+
total_discount: 5,
|
|
262
|
+
loyalty_discount_id: constants_1.WALLET_CASHBACK_LOYALTY_DISCOUNT_ID,
|
|
263
|
+
},
|
|
264
|
+
offers: [],
|
|
265
|
+
existingRedeemedOffers: null,
|
|
266
|
+
});
|
|
267
|
+
expect(result.redeemed_offers).toBeNull();
|
|
268
|
+
expect(result.missingOfferIds).toEqual([]);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
describe('editing an order whose points were already debited', () => {
|
|
272
|
+
const fullLedger = { [EARN_OFFER_ID]: 1, [REWARD_OFFER_ID]: 1 };
|
|
273
|
+
it('keeps the already-paid reward when the net balance alone cannot cover it', () => {
|
|
274
|
+
const { stats, unlocked } = runStats({
|
|
275
|
+
loyaltyPoints: 1,
|
|
276
|
+
items: [PAID_ITEM, makeRewardItem()],
|
|
277
|
+
redeemedOffers: fullLedger,
|
|
278
|
+
isEdit: true,
|
|
279
|
+
editedOrderRedeemedOffers: fullLedger,
|
|
280
|
+
});
|
|
281
|
+
expect(unlocked).toBe(1);
|
|
282
|
+
expect(stats.message).not.toContain('away from unlocking');
|
|
283
|
+
});
|
|
284
|
+
it('does not mint points when the reward was removed from the cart mid-edit', () => {
|
|
285
|
+
const { unlocked, stats } = runStats({
|
|
286
|
+
loyaltyPoints: 1,
|
|
287
|
+
items: [PAID_ITEM],
|
|
288
|
+
redeemedOffers: fullLedger,
|
|
289
|
+
isEdit: true,
|
|
290
|
+
editedOrderRedeemedOffers: fullLedger,
|
|
291
|
+
});
|
|
292
|
+
expect(unlocked).toBeUndefined();
|
|
293
|
+
expect(stats.message).toContain('away from unlocking');
|
|
294
|
+
});
|
|
295
|
+
it('is unchanged for a new order (no baseline exemption)', () => {
|
|
296
|
+
const { unlocked } = runStats({
|
|
297
|
+
loyaltyPoints: 1,
|
|
298
|
+
items: [PAID_ITEM, makeRewardItem()],
|
|
299
|
+
redeemedOffers: fullLedger,
|
|
300
|
+
isEdit: false,
|
|
301
|
+
});
|
|
302
|
+
expect(unlocked).toBeUndefined();
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
describe('end-to-end: claim then sync must not remove the reward', () => {
|
|
306
|
+
it('keeps both items and records the claim in redeemed_offers', () => {
|
|
307
|
+
const items = [PAID_ITEM, makeRewardItem()];
|
|
308
|
+
const offers = [makeEarnOffer(), makeRewardOffer()];
|
|
309
|
+
const { result } = runStats({ loyaltyPoints: 7, items, offers });
|
|
310
|
+
const synced = (0, offer_apply_helpers_1.getSyncOffersWithCartData)({
|
|
311
|
+
categories: makeCategories(items),
|
|
312
|
+
redeemed_offers: { [EARN_OFFER_ID]: 1 },
|
|
313
|
+
order_discount_details: null,
|
|
314
|
+
price: 2412.06,
|
|
315
|
+
total_discount_applied: 1386.93,
|
|
316
|
+
wallet_redemptions: null,
|
|
317
|
+
platform: constants_1.PLATFORMS_ENUM.APP_DELIVERY,
|
|
318
|
+
}, [], {}, result.unlockedOffersApplicableTimes, offers);
|
|
319
|
+
expect((synced.categories ?? []).flatMap((category) => category.items ?? [])).toHaveLength(2);
|
|
320
|
+
expect(synced.redeemed_offers).toEqual({ [EARN_OFFER_ID]: 1, [REWARD_OFFER_ID]: 1 });
|
|
321
|
+
});
|
|
322
|
+
it('drops the claim with the reward when the customer cannot afford it', () => {
|
|
323
|
+
const items = [PAID_ITEM, makeRewardItem()];
|
|
324
|
+
const offers = [makeEarnOffer(), makeRewardOffer()];
|
|
325
|
+
const { result } = runStats({ loyaltyPoints: 6, items, offers });
|
|
326
|
+
const synced = (0, offer_apply_helpers_1.getSyncOffersWithCartData)({
|
|
327
|
+
categories: makeCategories(items),
|
|
328
|
+
redeemed_offers: { [EARN_OFFER_ID]: 1 },
|
|
329
|
+
order_discount_details: null,
|
|
330
|
+
price: 2412.06,
|
|
331
|
+
total_discount_applied: 1386.93,
|
|
332
|
+
wallet_redemptions: null,
|
|
333
|
+
platform: constants_1.PLATFORMS_ENUM.APP_DELIVERY,
|
|
334
|
+
}, [], {}, result.unlockedOffersApplicableTimes, offers);
|
|
335
|
+
expect((synced.categories ?? []).flatMap((category) => category.items ?? [])).toHaveLength(1);
|
|
336
|
+
expect(synced.redeemed_offers).toEqual({ [EARN_OFFER_ID]: 1 });
|
|
337
|
+
});
|
|
338
|
+
});
|