@managesome/eposmatic-toolkit 0.4.31 → 0.4.34
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/constants/MATERIALIZED_REPORTS.js +3 -5
- package/esm/constants/enums/offers.js +0 -6
- package/esm/helpers/materialized-reports/index.js +1 -0
- package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
- package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
- package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -9
- package/esm/helpers/materialized-reports/materialized-prep-time-read-helpers.js +613 -0
- package/esm/helpers/store/cart-actions.js +3 -12
- package/esm/helpers/types/materialized-reports-apis.js +10 -0
- package/esm/helpers/utils/offer-apply-helpers.js +2 -10
- package/esm/helpers/utils/offers-helpers.js +117 -2
- package/esm/schemas/models/index.js +0 -1
- package/esm/schemas/types/index.js +0 -1
- package/lib/constants/MATERIALIZED_REPORTS.d.ts +3 -2
- package/lib/constants/MATERIALIZED_REPORTS.js +3 -5
- package/lib/constants/enums/offers.d.ts +0 -5
- package/lib/constants/enums/offers.js +1 -7
- package/lib/helpers/materialized-reports/index.d.ts +1 -0
- package/lib/helpers/materialized-reports/index.js +1 -0
- package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
- package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
- package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +15 -0
- package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -8
- package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.d.ts +179 -0
- package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.js +639 -0
- package/lib/helpers/store/cart-actions.js +1 -10
- package/lib/helpers/types/materialized-reports-apis.d.ts +145 -1
- package/lib/helpers/types/materialized-reports-apis.js +11 -0
- 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/index.d.ts +0 -1
- package/lib/schemas/models/index.js +0 -1
- package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +6 -6
- package/lib/schemas/types/index.d.ts +0 -1
- package/lib/schemas/types/index.js +0 -1
- package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +7 -5
- package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +28 -5
- package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +17 -4
- package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +6 -4
- package/lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.js +135 -0
- package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +71 -3
- package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.d.ts +1 -0
- package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.js +620 -0
- package/lib/tests/offers-helpers-points-evidence.test.d.ts +1 -0
- package/lib/tests/offers-helpers-points-evidence.test.js +338 -0
- package/lib/tests/offers-matrix.test.d.ts +1 -0
- package/lib/tests/offers-matrix.test.js +401 -0
- package/package.json +1 -1
- package/esm/schemas/models/rewards_usage.js +0 -61
- package/lib/schemas/models/rewards_usage.d.ts +0 -53
- package/lib/schemas/models/rewards_usage.js +0 -64
- package/lib/schemas/types/rewards_usage.d.ts +0 -13
- package/lib/schemas/types/rewards_usage.js +0 -2
- /package/{esm/schemas/types/rewards_usage.js → lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.d.ts} +0 -0
|
@@ -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);
|
|
@@ -57,7 +57,6 @@ export * from './printer_settings';
|
|
|
57
57
|
export * from './public_holidays';
|
|
58
58
|
export * from './reservations';
|
|
59
59
|
export * from './reviews';
|
|
60
|
-
export * from './rewards_usage';
|
|
61
60
|
export * from './riders';
|
|
62
61
|
export * from './specials';
|
|
63
62
|
export * from './staff_shifts';
|
|
@@ -55,7 +55,6 @@ export * from './printer_settings';
|
|
|
55
55
|
export * from './public_holidays';
|
|
56
56
|
export * from './reservations';
|
|
57
57
|
export * from './reviews';
|
|
58
|
-
export * from './rewards_usage';
|
|
59
58
|
export * from './riders';
|
|
60
59
|
export * from './specials';
|
|
61
60
|
export * from './staff_shifts';
|
|
@@ -341,8 +341,9 @@ export declare const MATERIALIZED_DELIVERY_AREA_LIMIT = 50;
|
|
|
341
341
|
*
|
|
342
342
|
* NO `localHour` (decision h2): the tracked population per hour is 2-3 items in
|
|
343
343
|
* the dev stores, so an hourly prep time would be noise. Day + periods only,
|
|
344
|
-
*
|
|
345
|
-
*
|
|
344
|
+
* CAPPED AT `LOCAL_MONTH`: quarter / semester / year are deliberately absent so
|
|
345
|
+
* the Summary, Details and the item-level reads all apply the SAME range policy,
|
|
346
|
+
* and the itemized rows in the sibling entries collection stay month-bounded.
|
|
346
347
|
*/
|
|
347
348
|
export declare const MATERIALIZED_PREP_TIME_REPORT_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
|
|
348
349
|
/** Ordered key filters of the prep time report (`COMPLETED:POS_WALK-IN`). */
|
|
@@ -425,17 +425,15 @@ exports.MATERIALIZED_DELIVERY_AREA_LIMIT = 50;
|
|
|
425
425
|
*
|
|
426
426
|
* NO `localHour` (decision h2): the tracked population per hour is 2-3 items in
|
|
427
427
|
* the dev stores, so an hourly prep time would be noise. Day + periods only,
|
|
428
|
-
*
|
|
429
|
-
*
|
|
428
|
+
* CAPPED AT `LOCAL_MONTH`: quarter / semester / year are deliberately absent so
|
|
429
|
+
* the Summary, Details and the item-level reads all apply the SAME range policy,
|
|
430
|
+
* and the itemized rows in the sibling entries collection stay month-bounded.
|
|
430
431
|
*/
|
|
431
432
|
exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = [
|
|
432
433
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
|
|
433
434
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
|
|
434
435
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
|
|
435
436
|
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
|
|
436
|
-
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
|
|
437
|
-
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
|
|
438
|
-
MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
|
|
439
437
|
];
|
|
440
438
|
/** Ordered key filters of the prep time report (`COMPLETED:POS_WALK-IN`). */
|
|
441
439
|
exports.PREP_TIME_KEY_FILTERS = [
|
|
@@ -51,11 +51,6 @@ export declare enum PATHWAY_TO_UNLOCK_TYPE_ENUM {
|
|
|
51
51
|
POINTS = "POINTS"
|
|
52
52
|
}
|
|
53
53
|
export declare const ALL_PATHWAY_TO_UNLOCK_TYPES: PATHWAY_TO_UNLOCK_TYPE_ENUM[];
|
|
54
|
-
export declare enum REWARDS_USAGE_REF_TYPE_ENUM {
|
|
55
|
-
VOUCHER = "VOUCHER",
|
|
56
|
-
GIFT_CARD = "GIFT_CARD"
|
|
57
|
-
}
|
|
58
|
-
export declare const ALL_REWARDS_USAGE_REF_TYPES: REWARDS_USAGE_REF_TYPE_ENUM[];
|
|
59
54
|
export declare enum RATING_TYPE_ENUM {
|
|
60
55
|
FOOD_QUALITY_RATING = "FOOD_QUALITY_RATING",
|
|
61
56
|
SERVICE_RATING = "SERVICE_RATING",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
// Auto-split from constants/ENUMS.ts — see ENUMS.ts barrel for exports.
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.ALL_DISCOUNT_APPLICABILITY_TYPES = exports.DISCOUNT_APPLICABILITY_ENUM = exports.ALL_DISCOUNT_TYPES = exports.DISCOUNT_TYPE_ENUM = exports.ALL_RATING_TYPES = exports.RATING_TYPE_ENUM = exports.
|
|
4
|
+
exports.ALL_DISCOUNT_APPLICABILITY_TYPES = exports.DISCOUNT_APPLICABILITY_ENUM = exports.ALL_DISCOUNT_TYPES = exports.DISCOUNT_TYPE_ENUM = exports.ALL_RATING_TYPES = exports.RATING_TYPE_ENUM = exports.ALL_PATHWAY_TO_UNLOCK_TYPES = exports.PATHWAY_TO_UNLOCK_TYPE_ENUM = exports.ALL_MYSTERY_GIFT_POPUP_TYPES = exports.MYSTERY_GIFT_POPUP_TYPE_ENUM = exports.ALL_MYSTERY_GIFT_TYPES = exports.MYSTERY_GIFT_TYPE_ENUM = exports.ALL_GIFT_CARD_REWARD_TYPES = exports.GIFT_CARD_REWARD_TYPE_ENUM = exports.ALL_CUSTOMER_REDEMPTION_TYPES = exports.CUSTOMER_REDEMPTION_TYPE_ENUM = exports.ALL_CUSTOMER_REDEMPTION_SOURCE_TYPES = exports.CUSTOMER_REDEMPTION_SOURCE_ENUM = exports.ALL_OFFER_REWARD_TYPES = exports.OFFER_REWARD_TYPE_ENUM = void 0;
|
|
5
5
|
var OFFER_REWARD_TYPE_ENUM;
|
|
6
6
|
(function (OFFER_REWARD_TYPE_ENUM) {
|
|
7
7
|
OFFER_REWARD_TYPE_ENUM["DISCOUNT"] = "DISCOUNT";
|
|
@@ -68,12 +68,6 @@ var PATHWAY_TO_UNLOCK_TYPE_ENUM;
|
|
|
68
68
|
PATHWAY_TO_UNLOCK_TYPE_ENUM["POINTS"] = "POINTS";
|
|
69
69
|
})(PATHWAY_TO_UNLOCK_TYPE_ENUM || (exports.PATHWAY_TO_UNLOCK_TYPE_ENUM = PATHWAY_TO_UNLOCK_TYPE_ENUM = {}));
|
|
70
70
|
exports.ALL_PATHWAY_TO_UNLOCK_TYPES = Object.values(PATHWAY_TO_UNLOCK_TYPE_ENUM);
|
|
71
|
-
var REWARDS_USAGE_REF_TYPE_ENUM;
|
|
72
|
-
(function (REWARDS_USAGE_REF_TYPE_ENUM) {
|
|
73
|
-
REWARDS_USAGE_REF_TYPE_ENUM["VOUCHER"] = "VOUCHER";
|
|
74
|
-
REWARDS_USAGE_REF_TYPE_ENUM["GIFT_CARD"] = "GIFT_CARD";
|
|
75
|
-
})(REWARDS_USAGE_REF_TYPE_ENUM || (exports.REWARDS_USAGE_REF_TYPE_ENUM = REWARDS_USAGE_REF_TYPE_ENUM = {}));
|
|
76
|
-
exports.ALL_REWARDS_USAGE_REF_TYPES = Object.values(REWARDS_USAGE_REF_TYPE_ENUM);
|
|
77
71
|
/* ================><================= */
|
|
78
72
|
var RATING_TYPE_ENUM;
|
|
79
73
|
(function (RATING_TYPE_ENUM) {
|
|
@@ -26,6 +26,7 @@ export * from './materialized-cash-compile-helpers';
|
|
|
26
26
|
export * from './materialized-prep-time-classification-helpers';
|
|
27
27
|
export * from './materialized-prep-time-close-day-helpers';
|
|
28
28
|
export * from './materialized-prep-time-compile-helpers';
|
|
29
|
+
export * from './materialized-prep-time-read-helpers';
|
|
29
30
|
export * from './materialized-report-drilldown-rows';
|
|
30
31
|
export * from './materialized-reports-read-helpers';
|
|
31
32
|
export * from './materialized-reports-scope-group-helpers';
|
|
@@ -42,6 +42,7 @@ __exportStar(require("./materialized-cash-compile-helpers"), exports);
|
|
|
42
42
|
__exportStar(require("./materialized-prep-time-classification-helpers"), exports);
|
|
43
43
|
__exportStar(require("./materialized-prep-time-close-day-helpers"), exports);
|
|
44
44
|
__exportStar(require("./materialized-prep-time-compile-helpers"), exports);
|
|
45
|
+
__exportStar(require("./materialized-prep-time-read-helpers"), exports);
|
|
45
46
|
__exportStar(require("./materialized-report-drilldown-rows"), exports);
|
|
46
47
|
__exportStar(require("./materialized-reports-read-helpers"), exports);
|
|
47
48
|
__exportStar(require("./materialized-reports-scope-group-helpers"), exports);
|
|
@@ -7,6 +7,8 @@ const materialized_tenant_discount_entries_1 = require("../../schemas/models/mat
|
|
|
7
7
|
const materialized_tenant_discount_reports_1 = require("../../schemas/models/materialized_tenant_discount_reports");
|
|
8
8
|
const materialized_tenant_discount_sources_1 = require("../../schemas/models/materialized_tenant_discount_sources");
|
|
9
9
|
const materialized_tenant_reports_iterations_1 = require("../../schemas/models/materialized_tenant_reports_iterations");
|
|
10
|
+
const materialized_tenant_prep_time_entries_1 = require("../../schemas/models/materialized_tenant_prep_time_entries");
|
|
11
|
+
const materialized_tenant_prep_time_reports_1 = require("../../schemas/models/materialized_tenant_prep_time_reports");
|
|
10
12
|
const materialized_tenant_sales_overview_reports_1 = require("../../schemas/models/materialized_tenant_sales_overview_reports");
|
|
11
13
|
const materialized_report_drilldown_rows_1 = require("../../schemas/models/materialized_report_drilldown_rows");
|
|
12
14
|
const tenant_calendar_1 = require("../../schemas/models/tenant_calendar");
|
|
@@ -29,6 +31,8 @@ const INDEXES = {
|
|
|
29
31
|
[materialized_tenant_discount_reports_1.MATERIALIZED_TENANT_DISCOUNT_REPORTS_COLLECTION_NAME]: materialized_tenant_discount_reports_1.MATERIALIZED_TENANT_DISCOUNT_REPORTS_INDEX_OPTIONS,
|
|
30
32
|
[materialized_tenant_discount_entries_1.MATERIALIZED_TENANT_DISCOUNT_ENTRIES_COLLECTION_NAME]: materialized_tenant_discount_entries_1.MATERIALIZED_TENANT_DISCOUNT_ENTRIES_INDEX_OPTIONS,
|
|
31
33
|
[materialized_tenant_discount_sources_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_COLLECTION_NAME]: materialized_tenant_discount_sources_1.MATERIALIZED_TENANT_DISCOUNT_SOURCES_INDEX_OPTIONS,
|
|
34
|
+
[materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_COLLECTION_NAME]: materialized_tenant_prep_time_reports_1.MATERIALIZED_TENANT_PREP_TIME_REPORTS_INDEX_OPTIONS,
|
|
35
|
+
[materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_COLLECTION_NAME]: materialized_tenant_prep_time_entries_1.MATERIALIZED_TENANT_PREP_TIME_ENTRIES_INDEX_OPTIONS,
|
|
32
36
|
[materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_COLLECTION_NAME]: materialized_tenant_reports_iterations_1.MATERIALIZED_TENANT_REPORTS_ITERATIONS_INDEX_OPTIONS,
|
|
33
37
|
[materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_ROWS_INDEX_OPTIONS,
|
|
34
38
|
[materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_COLLECTION_NAME]: materialized_report_drilldown_rows_1.MATERIALIZED_REPORT_DRILLDOWN_SCOPES_INDEX_OPTIONS,
|
|
@@ -151,14 +151,18 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
|
|
|
151
151
|
counters.coverage.own_anchor_count += 1;
|
|
152
152
|
// RECONSTRUCTED ready instant - the source field ready_at does not exist.
|
|
153
153
|
readyAt = new Date(prepStartedAt.getTime() + minutes * 60000);
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
//
|
|
160
|
-
|
|
161
|
-
|
|
154
|
+
// ONE canonical duration population: a duration is VALID only when it
|
|
155
|
+
// is finite, >= 0 and <= the outlier cap. Valid durations alone feed
|
|
156
|
+
// count / sum / min / max / buckets / instant count (and therefore
|
|
157
|
+
// avg = sum/count). An artefact must never understate the average by
|
|
158
|
+
// sitting in the denominator while being excluded from the numerator.
|
|
159
|
+
// Coverage still counts the MEASURED row (own_anchor_count above).
|
|
160
|
+
if (minutes >= 0 && minutes <= MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_MAX_MINUTES) {
|
|
161
|
+
counters.duration.count += 1;
|
|
162
|
+
if (minutes === 0)
|
|
163
|
+
counters.duration.instant_count += 1;
|
|
164
|
+
const bucket = resolveMaterializedPrepTimeBucket(minutes);
|
|
165
|
+
counters.duration.buckets[bucket] = (counters.duration.buckets[bucket] ?? 0) + 1;
|
|
162
166
|
counters.duration.sum += minutes;
|
|
163
167
|
if (counters.duration.count === 1 || minutes < counters.duration.min) {
|
|
164
168
|
counters.duration.min = minutes;
|
|
@@ -70,6 +70,15 @@ export declare function foldMaterializedPrepTimePeriodRows({ periodScopeField, p
|
|
|
70
70
|
}>;
|
|
71
71
|
/** The period scope contexts (everything except the day scope). */
|
|
72
72
|
export declare const MATERIALIZED_PREP_TIME_PERIOD_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
|
|
73
|
+
/**
|
|
74
|
+
* Every `localDate` label whose DAY entry document can contribute to a period
|
|
75
|
+
* the closing day rolls into (week / ISO week / month).
|
|
76
|
+
*
|
|
77
|
+
* The worker uses this to fetch exactly the sibling day entries the period
|
|
78
|
+
* fold needs — never a full-period entry document and never a year-wide scan.
|
|
79
|
+
* Returns `null` (never throws) for a malformed date.
|
|
80
|
+
*/
|
|
81
|
+
export declare function getMaterializedPrepTimePeriodDayScopeFields(localDate: string): string[] | null;
|
|
73
82
|
/** True when a stored prep counter document equals the incoming one (skip write). */
|
|
74
83
|
export declare function needsMaterializedPrepTimeReportWrite(existing: IMaterializedTenantPrepTimeReport | null | undefined, incoming: IMaterializedTenantPrepTimeReport | null | undefined): boolean;
|
|
75
84
|
/** One planned write: the document plus its shared-history iteration row. */
|
|
@@ -114,6 +123,12 @@ export interface IBuildTenantPrepTimeCloseDayPlanInput {
|
|
|
114
123
|
existing?: IMaterializedTenantPrepTimeReport[];
|
|
115
124
|
existingEntries?: IMaterializedTenantPrepTimeEntries[];
|
|
116
125
|
reason: string;
|
|
126
|
+
/**
|
|
127
|
+
* Structural writes even when the watermark says the day is unchanged
|
|
128
|
+
* (manual range repair). The period folds are idempotent, so a forced run
|
|
129
|
+
* rewrites the same values and advances the iteration.
|
|
130
|
+
*/
|
|
131
|
+
force?: boolean;
|
|
117
132
|
computedAt?: Date;
|
|
118
133
|
}
|
|
119
134
|
/**
|
|
@@ -8,6 +8,7 @@ exports.updateMaterializedPrepTimeEntries = updateMaterializedPrepTimeEntries;
|
|
|
8
8
|
exports.needsMaterializedPrepTimeEntriesWrite = needsMaterializedPrepTimeEntriesWrite;
|
|
9
9
|
exports.foldMaterializedPrepTimePeriodCounters = foldMaterializedPrepTimePeriodCounters;
|
|
10
10
|
exports.foldMaterializedPrepTimePeriodRows = foldMaterializedPrepTimePeriodRows;
|
|
11
|
+
exports.getMaterializedPrepTimePeriodDayScopeFields = getMaterializedPrepTimePeriodDayScopeFields;
|
|
11
12
|
exports.needsMaterializedPrepTimeReportWrite = needsMaterializedPrepTimeReportWrite;
|
|
12
13
|
exports.buildTenantPrepTimeCloseDayPlan = buildTenantPrepTimeCloseDayPlan;
|
|
13
14
|
const mongoose_1 = __importDefault(require("mongoose"));
|
|
@@ -168,6 +169,67 @@ function foldMaterializedPrepTimePeriodRows({ periodScopeField, periodScope, day
|
|
|
168
169
|
}
|
|
169
170
|
/** The period scope contexts (everything except the day scope). */
|
|
170
171
|
exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES.filter((scope) => !(0, exports.isMaterializedPrepTimeDayScope)(String(scope)));
|
|
172
|
+
/* ------------------------------------------------------------------------ */
|
|
173
|
+
/* Period sibling-day enumeration */
|
|
174
|
+
/* ------------------------------------------------------------------------ */
|
|
175
|
+
const pad2 = (value) => String(value).padStart(2, '0');
|
|
176
|
+
const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
|
|
177
|
+
const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
|
|
178
|
+
const addMonthDays = (year, month, days) => {
|
|
179
|
+
if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
|
|
180
|
+
return false;
|
|
181
|
+
const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
182
|
+
for (let day = 1; day <= last; day += 1) {
|
|
183
|
+
days.add(`${year}-${pad2(month)}-${pad2(day)}`);
|
|
184
|
+
}
|
|
185
|
+
return true;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Every `localDate` label whose DAY entry document can contribute to a period
|
|
189
|
+
* the closing day rolls into (week / ISO week / month).
|
|
190
|
+
*
|
|
191
|
+
* The worker uses this to fetch exactly the sibling day entries the period
|
|
192
|
+
* fold needs — never a full-period entry document and never a year-wide scan.
|
|
193
|
+
* Returns `null` (never throws) for a malformed date.
|
|
194
|
+
*/
|
|
195
|
+
function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
|
|
196
|
+
const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
|
|
197
|
+
if (periodFields == null)
|
|
198
|
+
return null;
|
|
199
|
+
const days = new Set([localDate]);
|
|
200
|
+
const weekField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
|
|
201
|
+
const weekParts = typeof weekField === 'string' ? (0, scope_helpers_1.parseMaterializedLocalDate)(weekField) : null;
|
|
202
|
+
if (weekParts == null)
|
|
203
|
+
return null;
|
|
204
|
+
const weekStart = new Date(Date.UTC(weekParts.year, weekParts.month - 1, weekParts.day));
|
|
205
|
+
if (weekStart.getUTCDay() !== 0)
|
|
206
|
+
return null;
|
|
207
|
+
for (let offset = 0; offset < 7; offset += 1) {
|
|
208
|
+
days.add(toLocalDateKey(addUtcDays(weekStart, offset)));
|
|
209
|
+
}
|
|
210
|
+
const isoWeekField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR];
|
|
211
|
+
const isoMatch = typeof isoWeekField === 'string' ? /^(\d{4})-W(\d{2})$/.exec(isoWeekField) : null;
|
|
212
|
+
if (isoMatch == null)
|
|
213
|
+
return null;
|
|
214
|
+
const weekYear = Number(isoMatch[1]);
|
|
215
|
+
const week = Number(isoMatch[2]);
|
|
216
|
+
if (!Number.isInteger(week) || week < 1 || week > 53)
|
|
217
|
+
return null;
|
|
218
|
+
const jan4 = new Date(Date.UTC(weekYear, 0, 4));
|
|
219
|
+
const isoWeekday = jan4.getUTCDay() || 7;
|
|
220
|
+
const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
|
|
221
|
+
const isoStart = addUtcDays(weekOneMonday, (week - 1) * 7);
|
|
222
|
+
for (let offset = 0; offset < 7; offset += 1) {
|
|
223
|
+
days.add(toLocalDateKey(addUtcDays(isoStart, offset)));
|
|
224
|
+
}
|
|
225
|
+
const monthField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
|
|
226
|
+
const monthMatch = typeof monthField === 'string' ? /^(\d{4})-(\d{2})$/.exec(monthField) : null;
|
|
227
|
+
if (monthMatch == null)
|
|
228
|
+
return null;
|
|
229
|
+
if (!addMonthDays(Number(monthMatch[1]), Number(monthMatch[2]), days))
|
|
230
|
+
return null;
|
|
231
|
+
return [...days].sort();
|
|
232
|
+
}
|
|
171
233
|
/** True when a stored prep counter document equals the incoming one (skip write). */
|
|
172
234
|
function needsMaterializedPrepTimeReportWrite(existing, incoming) {
|
|
173
235
|
if (existing == null || incoming == null)
|
|
@@ -208,6 +270,7 @@ function buildTenantPrepTimeCloseDayPlan(input) {
|
|
|
208
270
|
if (reports.some((doc) => doc == null || doc.tenant_id !== tenantId))
|
|
209
271
|
return null;
|
|
210
272
|
const computedAt = input.computedAt ?? new Date();
|
|
273
|
+
const force = input.force === true;
|
|
211
274
|
const existing = input.existing ?? [];
|
|
212
275
|
const existingEntries = input.existingEntries ?? [];
|
|
213
276
|
const dateDoc = reports.find((doc) => doc.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE) ?? null;
|
|
@@ -358,14 +421,14 @@ function buildTenantPrepTimeCloseDayPlan(input) {
|
|
|
358
421
|
sale_type_key_filters: existingDoc?.sale_type_key_filters ?? reports[0]?.sale_type_key_filters ?? [],
|
|
359
422
|
prep_time_counters: counters,
|
|
360
423
|
prep_time_counter_rows: counterRows,
|
|
361
|
-
iteration: existingDoc
|
|
424
|
+
iteration: existingDoc == null ? 1 : (existingDoc.iteration ?? 1) + 1,
|
|
362
425
|
schema_version: existingDoc?.schema_version ?? 1,
|
|
363
426
|
source_watermark: watermark ?? new Date(computedAt),
|
|
364
427
|
computed_at: computedAt,
|
|
365
428
|
createdAt: existingDoc?.createdAt ?? computedAt,
|
|
366
429
|
updatedAt: computedAt,
|
|
367
430
|
};
|
|
368
|
-
if (existingDoc != null && !needsMaterializedPrepTimeReportWrite(existingDoc, report)) {
|
|
431
|
+
if (!force && existingDoc != null && !needsMaterializedPrepTimeReportWrite(existingDoc, report)) {
|
|
369
432
|
skippedDocuments.push(existingDoc);
|
|
370
433
|
continue;
|
|
371
434
|
}
|
|
@@ -375,11 +438,20 @@ function buildTenantPrepTimeCloseDayPlan(input) {
|
|
|
375
438
|
// ---- the DAY scope: written straight from the compile --------------------
|
|
376
439
|
for (const doc of compiledDateDocs) {
|
|
377
440
|
const existingDoc = existingByScope.get(prepScopeKey(doc)) ?? null;
|
|
378
|
-
|
|
441
|
+
const report = {
|
|
442
|
+
...doc,
|
|
443
|
+
// A reclose REPLACES the stored day document: preserving its _id and
|
|
444
|
+
// createdAt keeps the identity + immutable fields stable (Mongo rejects a
|
|
445
|
+
// replace that alters _id).
|
|
446
|
+
_id: existingDoc?._id ?? doc._id,
|
|
447
|
+
createdAt: existingDoc?.createdAt ?? doc.createdAt,
|
|
448
|
+
iteration: existingDoc == null ? 1 : (existingDoc.iteration ?? 1) + 1,
|
|
449
|
+
};
|
|
450
|
+
if (!force && existingDoc != null && !needsMaterializedPrepTimeReportWrite(existingDoc, report)) {
|
|
379
451
|
skippedDocuments.push(existingDoc);
|
|
380
452
|
continue;
|
|
381
453
|
}
|
|
382
|
-
if (!addWrite(
|
|
454
|
+
if (!addWrite(report))
|
|
383
455
|
return null;
|
|
384
456
|
}
|
|
385
457
|
// ---- entry documents ------------------------------------------------------
|
|
@@ -455,14 +527,14 @@ function buildTenantPrepTimeCloseDayPlan(input) {
|
|
|
455
527
|
day_index: null,
|
|
456
528
|
sale_type_key_filters: existingDoc?.sale_type_key_filters ?? entries[0]?.sale_type_key_filters ?? [],
|
|
457
529
|
prep_time_entries: sections,
|
|
458
|
-
iteration: existingDoc
|
|
530
|
+
iteration: existingDoc == null ? 1 : (existingDoc.iteration ?? 1) + 1,
|
|
459
531
|
schema_version: existingDoc?.schema_version ?? 1,
|
|
460
532
|
source_watermark: entryWatermark ?? new Date(computedAt),
|
|
461
533
|
computed_at: computedAt,
|
|
462
534
|
createdAt: existingDoc?.createdAt ?? computedAt,
|
|
463
535
|
updatedAt: computedAt,
|
|
464
536
|
};
|
|
465
|
-
if (existingDoc != null && !needsMaterializedPrepTimeEntriesWrite(existingDoc, report)) {
|
|
537
|
+
if (!force && existingDoc != null && !needsMaterializedPrepTimeEntriesWrite(existingDoc, report)) {
|
|
466
538
|
skippedEntryDocuments.push(existingDoc);
|
|
467
539
|
continue;
|
|
468
540
|
}
|
|
@@ -473,11 +545,17 @@ function buildTenantPrepTimeCloseDayPlan(input) {
|
|
|
473
545
|
if (doc.scope_context !== MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE)
|
|
474
546
|
continue;
|
|
475
547
|
const existingDoc = existingEntriesByScope.get(prepScopeKey(doc)) ?? null;
|
|
476
|
-
|
|
548
|
+
const report = {
|
|
549
|
+
...doc,
|
|
550
|
+
_id: existingDoc?._id ?? doc._id,
|
|
551
|
+
createdAt: existingDoc?.createdAt ?? doc.createdAt,
|
|
552
|
+
iteration: existingDoc == null ? 1 : (existingDoc.iteration ?? 1) + 1,
|
|
553
|
+
};
|
|
554
|
+
if (!force && existingDoc != null && !needsMaterializedPrepTimeEntriesWrite(existingDoc, report)) {
|
|
477
555
|
skippedEntryDocuments.push(existingDoc);
|
|
478
556
|
continue;
|
|
479
557
|
}
|
|
480
|
-
if (!addEntryWrite(
|
|
558
|
+
if (!addEntryWrite(report))
|
|
481
559
|
return null;
|
|
482
560
|
}
|
|
483
561
|
return {
|