@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.
Files changed (55) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +3 -5
  2. package/esm/constants/enums/offers.js +0 -6
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  5. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
  6. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -9
  7. package/esm/helpers/materialized-reports/materialized-prep-time-read-helpers.js +613 -0
  8. package/esm/helpers/store/cart-actions.js +3 -12
  9. package/esm/helpers/types/materialized-reports-apis.js +10 -0
  10. package/esm/helpers/utils/offer-apply-helpers.js +2 -10
  11. package/esm/helpers/utils/offers-helpers.js +117 -2
  12. package/esm/schemas/models/index.js +0 -1
  13. package/esm/schemas/types/index.js +0 -1
  14. package/lib/constants/MATERIALIZED_REPORTS.d.ts +3 -2
  15. package/lib/constants/MATERIALIZED_REPORTS.js +3 -5
  16. package/lib/constants/enums/offers.d.ts +0 -5
  17. package/lib/constants/enums/offers.js +1 -7
  18. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  19. package/lib/helpers/materialized-reports/index.js +1 -0
  20. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  21. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
  22. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +15 -0
  23. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -8
  24. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.d.ts +179 -0
  25. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.js +639 -0
  26. package/lib/helpers/store/cart-actions.js +1 -10
  27. package/lib/helpers/types/materialized-reports-apis.d.ts +145 -1
  28. package/lib/helpers/types/materialized-reports-apis.js +11 -0
  29. package/lib/helpers/utils/offer-apply-helpers.js +2 -10
  30. package/lib/helpers/utils/offers-helpers.d.ts +50 -0
  31. package/lib/helpers/utils/offers-helpers.js +120 -2
  32. package/lib/schemas/models/index.d.ts +0 -1
  33. package/lib/schemas/models/index.js +0 -1
  34. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +6 -6
  35. package/lib/schemas/types/index.d.ts +0 -1
  36. package/lib/schemas/types/index.js +0 -1
  37. package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +7 -5
  38. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +28 -5
  39. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +17 -4
  40. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +6 -4
  41. package/lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.js +135 -0
  42. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +71 -3
  43. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.d.ts +1 -0
  44. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.js +620 -0
  45. package/lib/tests/offers-helpers-points-evidence.test.d.ts +1 -0
  46. package/lib/tests/offers-helpers-points-evidence.test.js +338 -0
  47. package/lib/tests/offers-matrix.test.d.ts +1 -0
  48. package/lib/tests/offers-matrix.test.js +401 -0
  49. package/package.json +1 -1
  50. package/esm/schemas/models/rewards_usage.js +0 -61
  51. package/lib/schemas/models/rewards_usage.d.ts +0 -53
  52. package/lib/schemas/models/rewards_usage.js +0 -64
  53. package/lib/schemas/types/rewards_usage.d.ts +0 -13
  54. package/lib/schemas/types/rewards_usage.js +0 -2
  55. /package/{esm/schemas/types/rewards_usage.js → lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.d.ts} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
2
- import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM, MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, MATERIALIZED_REPORT_KEY_FILTER_ENUM, SALES_COMPARISON_BASELINE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM, MATERIALIZED_DISCOUNT_LEVEL_ENUM, MATERIALIZED_DISCOUNT_RATE_KIND_ENUM, MATERIALIZED_DISCOUNT_SLOT_ENUM, MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM, MATERIALIZED_DISCOUNT_SUB_KIND_ENUM, MATERIALIZED_PREP_TIME_ANCHOR_ENUM, MATERIALIZED_REPORT_KEY_FILTER_ENUM, SALES_COMPARISON_BASELINE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { IMaterializedDiscountOrderCounters } from '../../schemas/types/materialized_tenant_discount_reports';
4
4
  import { IMaterializedPrepTimeCounters } from '../../schemas/types/materialized_tenant_prep_time_reports';
5
5
  import { IMaterializedSalesComparisonCounters, IMaterializedSalesComparisonCounterRow } from '../../schemas/types/materialized_tenant_sales_comparison_reports';
@@ -344,6 +344,150 @@ export interface IMaterializedTenantPrepTimeAggregatedReport {
344
344
  schema_version?: number;
345
345
  max_updated_at?: Date | null;
346
346
  }
347
+ /**
348
+ * The item-level sort modes of `POST /reports/prep-time/items/:mode`.
349
+ *
350
+ * Every mode is TOTAL: `item_id` ascending is always the final tie-break, so a
351
+ * cursor page can never duplicate or skip a row when sort values collide.
352
+ */
353
+ export type TMaterializedPrepTimeItemSort = 'late_desc' | 'avg_desc' | 'avg_asc' | 'p90_desc' | 'on_time_asc' | 'name_asc';
354
+ export declare const ALL_MATERIALIZED_PREP_TIME_ITEM_SORTS: TMaterializedPrepTimeItemSort[];
355
+ /** The default Items sort (highest late volume first). */
356
+ export declare const DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT: TMaterializedPrepTimeItemSort;
357
+ /** Anchor provenance used as a READ filter (`MEASURED` | `UNMEASURED`). */
358
+ export type TMaterializedPrepTimeReadAnchor = `${MATERIALIZED_PREP_TIME_ANCHOR_ENUM}`;
359
+ /**
360
+ * Server-side filters of the prep-time item-level reads.
361
+ *
362
+ * Every filter applies BEFORE grouping, so the grouped rows describe the
363
+ * FILTERED population, never the unfiltered period.
364
+ *
365
+ * `anchor` is the VIEW selector: it filters which rows are LISTED (the Items tab
366
+ * switches between the measured and fallback views). It does NOT narrow
367
+ * `IPrepTimeCoverage` — coverage always spans BOTH anchor populations after
368
+ * every other filter, because "how much of the operation do we observe?" must
369
+ * stay visible on the measured view. Omitting it reads both populations (the
370
+ * categories / series default); the Items route defaults it to `MEASURED`.
371
+ */
372
+ export interface IPrepTimeReadFilters {
373
+ /** `PLATFORM` enum values; empty/omitted = all platforms. */
374
+ platforms?: string[] | null;
375
+ /** `ORDER_STATUS` enum values; empty/omitted = all statuses. */
376
+ order_statuses?: string[] | null;
377
+ /** EXACT category names; empty/omitted = all categories. */
378
+ category_names?: string[] | null;
379
+ /** Case-insensitive substring of the item name OR category name. */
380
+ search?: string | null;
381
+ /** Measured rows with a target and a delta above the on-time tolerance. */
382
+ late_only?: boolean | null;
383
+ /** Anchor provenance row filter (`MEASURED` | `UNMEASURED`). */
384
+ anchor?: TMaterializedPrepTimeReadAnchor | null;
385
+ }
386
+ /**
387
+ * Coverage of the population the read actually observed.
388
+ *
389
+ * Spans BOTH anchor populations (after every non-anchor filter): a
390
+ * `anchor: "MEASURED"` item read still reports the unmeasured rows here, so the
391
+ * UI can keep the measured-of-served banner while listing measured items only.
392
+ */
393
+ export interface IPrepTimeCoverage {
394
+ served_count: number;
395
+ measured_count: number;
396
+ unmeasured_count: number;
397
+ /** measured / served, one decimal; 0 when nothing was served. */
398
+ coverage_percent: number;
399
+ }
400
+ /** One grouped item row of `POST /reports/prep-time/items/:mode`. */
401
+ export interface IPrepTimeItemRow {
402
+ item_id: string;
403
+ item_name: string;
404
+ category_name: string | null;
405
+ /** Distinct `order_id`s among the filtered rows. */
406
+ orders_count: number;
407
+ /** All item rows (measured + unmeasured). */
408
+ served_count: number;
409
+ /** Rows whose anchor is the item's OWN prep clock. */
410
+ measured_count: number;
411
+ unmeasured_count: number;
412
+ /** MEASURED + valid duration only; null when none. */
413
+ avg_minutes: number | null;
414
+ /** MEASURED + valid duration only, exact (interpolated); null when none. */
415
+ median_minutes: number | null;
416
+ /** MEASURED + valid duration only, exact (interpolated); null when none. */
417
+ p90_minutes: number | null;
418
+ on_time_count: number;
419
+ late_count: number;
420
+ /** on_time / (on_time + late), one decimal; null when nothing was graded. */
421
+ on_time_percent: number | null;
422
+ /** Newest row instant (ISO) of the filtered rows; null when none. */
423
+ last_served_at: string | null;
424
+ }
425
+ /** Response of `POST /reports/prep-time/items/:mode`. */
426
+ export interface IPrepTimeItemsPage {
427
+ rows: IPrepTimeItemRow[];
428
+ /** Opaque to the client; pass back verbatim to read the next page. */
429
+ next_cursor: string | null;
430
+ coverage: IPrepTimeCoverage;
431
+ }
432
+ /**
433
+ * One grouped category row of `POST /reports/prep-time/categories/:mode`.
434
+ * Rows with no category name are not attributable and are excluded.
435
+ */
436
+ export interface IPrepTimeCategoryRow {
437
+ category_name: string;
438
+ served_count: number;
439
+ measured_count: number;
440
+ unmeasured_count: number;
441
+ avg_minutes: number | null;
442
+ median_minutes: number | null;
443
+ p90_minutes: number | null;
444
+ on_time_count: number;
445
+ late_count: number;
446
+ on_time_percent: number | null;
447
+ }
448
+ /** Response of `POST /reports/prep-time/categories/:mode`. */
449
+ export interface IPrepTimeCategoriesResult {
450
+ rows: IPrepTimeCategoryRow[];
451
+ coverage: IPrepTimeCoverage;
452
+ }
453
+ /** One source-local-date point of `POST /reports/prep-time/series/:mode`. */
454
+ export interface IPrepTimeSeriesPoint {
455
+ /** `YYYY-MM-DD` — the SOURCE local date, never a `created_at` UTC day. */
456
+ local_date: string;
457
+ served_count: number;
458
+ measured_count: number;
459
+ unmeasured_count: number;
460
+ avg_minutes: number | null;
461
+ median_minutes: number | null;
462
+ p90_minutes: number | null;
463
+ on_time_count: number;
464
+ late_count: number;
465
+ }
466
+ /** Response of `POST /reports/prep-time/series/:mode`. */
467
+ export interface IPrepTimeSeriesResult {
468
+ points: IPrepTimeSeriesPoint[];
469
+ coverage: IPrepTimeCoverage;
470
+ /** No tenant prep target exists yet — always null, never invented. */
471
+ target_minutes: number | null;
472
+ }
473
+ /** Body of `POST /reports/prep-time/items/:mode`. */
474
+ export interface IGetMaterializedPrepTimeItemsBody extends IGetMaterializedReportBody {
475
+ filters?: IPrepTimeReadFilters | null;
476
+ sort?: TMaterializedPrepTimeItemSort | null;
477
+ /** Opaque cursor returned by the previous page. */
478
+ cursor?: string | null;
479
+ /** Default 25, capped at 50. */
480
+ limit?: number;
481
+ }
482
+ /** Body of `POST /reports/prep-time/categories/:mode`. */
483
+ export interface IGetMaterializedPrepTimeCategoriesBody extends IGetMaterializedReportBody {
484
+ /** `category_names` is IGNORED here (the read groups by category). */
485
+ filters?: IPrepTimeReadFilters | null;
486
+ }
487
+ /** Body of `POST /reports/prep-time/series/:mode`. */
488
+ export interface IGetMaterializedPrepTimeSeriesBody extends IGetMaterializedReportBody {
489
+ filters?: IPrepTimeReadFilters | null;
490
+ }
347
491
  /**
348
492
  * Body of `POST /reports/sales-comparison` — the shared `{ tenants, selection }`
349
493
  * contract PLUS the baseline to compare against.
@@ -1,3 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT = exports.ALL_MATERIALIZED_PREP_TIME_ITEM_SORTS = void 0;
3
4
  const constants_1 = require("../../constants");
5
+ exports.ALL_MATERIALIZED_PREP_TIME_ITEM_SORTS = [
6
+ 'late_desc',
7
+ 'avg_desc',
8
+ 'avg_asc',
9
+ 'p90_desc',
10
+ 'on_time_asc',
11
+ 'name_asc',
12
+ ];
13
+ /** The default Items sort (highest late volume first). */
14
+ exports.DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT = 'late_desc';
@@ -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 = getItemRewardApplicableQuantity(offer);
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
- const redeemedTimesForCurrentOffer = Math.max(getOfferRedeemedTimes(offer._id), orderLevelClaimSignal);
2606
- const effectiveLoyaltyPointsForCurrentOffer = (totalLoyaltyPointsOfCustomer ?? 0) + redeemedTimesForCurrentOffer * (num_of_points ?? 0);
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);
@@ -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';
@@ -73,7 +73,6 @@ __exportStar(require("./printer_settings"), exports);
73
73
  __exportStar(require("./public_holidays"), exports);
74
74
  __exportStar(require("./reservations"), exports);
75
75
  __exportStar(require("./reviews"), exports);
76
- __exportStar(require("./rewards_usage"), exports);
77
76
  __exportStar(require("./riders"), exports);
78
77
  __exportStar(require("./specials"), exports);
79
78
  __exportStar(require("./staff_shifts"), exports);
@@ -37,11 +37,11 @@ declare const PrepTimeEntrySchema: Schema<any, import("mongoose").Model<any, any
37
37
  item_name: string;
38
38
  created_at: NativeDate;
39
39
  local_hour: string;
40
- target_at: NativeDate;
41
- target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
42
40
  category_name: string;
43
41
  duration_minutes: number;
44
42
  ready_at: NativeDate;
43
+ target_at: NativeDate;
44
+ target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
45
45
  delta_minutes: number;
46
46
  }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
47
47
  anchor: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_ANCHOR_ENUM;
@@ -58,11 +58,11 @@ declare const PrepTimeEntrySchema: Schema<any, import("mongoose").Model<any, any
58
58
  item_name: string;
59
59
  created_at: NativeDate;
60
60
  local_hour: string;
61
- target_at: NativeDate;
62
- target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
63
61
  category_name: string;
64
62
  duration_minutes: number;
65
63
  ready_at: NativeDate;
64
+ target_at: NativeDate;
65
+ target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
66
66
  delta_minutes: number;
67
67
  }>> & import("mongoose").FlatRecord<{
68
68
  anchor: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_ANCHOR_ENUM;
@@ -79,11 +79,11 @@ declare const PrepTimeEntrySchema: Schema<any, import("mongoose").Model<any, any
79
79
  item_name: string;
80
80
  created_at: NativeDate;
81
81
  local_hour: string;
82
- target_at: NativeDate;
83
- target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
84
82
  category_name: string;
85
83
  duration_minutes: number;
86
84
  ready_at: NativeDate;
85
+ target_at: NativeDate;
86
+ target_source: import("../../constants/MATERIALIZED_REPORTS").MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
87
87
  delta_minutes: number;
88
88
  }> & {
89
89
  _id: import("mongoose").Types.ObjectId;
@@ -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';
@@ -71,7 +71,6 @@ __exportStar(require("./printer_settings"), exports);
71
71
  __exportStar(require("./public_holidays"), exports);
72
72
  __exportStar(require("./reservations"), exports);
73
73
  __exportStar(require("./reviews"), exports);
74
- __exportStar(require("./rewards_usage"), exports);
75
74
  __exportStar(require("./riders"), exports);
76
75
  __exportStar(require("./specials"), exports);
77
76
  __exportStar(require("./staff_shifts"), exports);
@@ -29,12 +29,14 @@ export interface IMaterializedPrepTimeCoverage {
29
29
  order_count: number;
30
30
  }
31
31
  /**
32
- * Duration statistics - MEASURED items ONLY.
32
+ * Duration statistics - MEASURED items with a VALID duration ONLY.
33
33
  *
34
- * Durations are whole MINUTES. `min` / `max` / `sum` ignore values beyond
35
- * `MATERIALIZED_PREP_TIME_MAX_MINUTES` (clock/backfill artefacts) while the
36
- * `buckets` counts stay complete, so `count` is the trustworthy denominator and
37
- * the extremes are never a single bad row.
34
+ * Durations are whole MINUTES. A duration is valid when it is finite, `>= 0`
35
+ * and `<= MATERIALIZED_PREP_TIME_MAX_MINUTES` (clock/backfill artefacts are
36
+ * excluded). Valid durations alone feed `count` / `sum` / `min` / `max` /
37
+ * `instant_count` / `buckets`, so `avg = sum / count` has ONE denominator and
38
+ * an artefact can never understate it. `coverage.own_anchor_count` still counts
39
+ * every MEASURED row (valid or not), so coverage stays honest.
38
40
  */
39
41
  export interface IMaterializedPrepTimeDuration {
40
42
  min: number;
@@ -163,7 +163,7 @@ describe('accumulateOrderPrepTime - the EXCLUSION rule', () => {
163
163
  expect(result.counters.duration.buckets['0']).toBe(1);
164
164
  expect(result.counters.duration.count).toBe(1);
165
165
  });
166
- it('buckets an OUTLIER but keeps it out of min/max/sum', () => {
166
+ it('EXCLUDES an outlier from count / buckets / min / max / sum (one valid population)', () => {
167
167
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
168
168
  order: order({
169
169
  categories: [
@@ -179,13 +179,36 @@ describe('accumulateOrderPrepTime - the EXCLUSION rule', () => {
179
179
  context,
180
180
  });
181
181
  const duration = result.counters.duration;
182
- // The COUNT is complete (both items are real rows)...
183
- expect(duration.count).toBe(2);
184
- expect(duration.buckets['60+']).toBe(1);
185
- // ...but the outlier cannot define the extremes.
182
+ // ONE valid duration population: the artefact is excluded everywhere, so the
183
+ // denominator can never understate avg = sum / count.
184
+ expect(duration.count).toBe(1);
185
+ expect(duration.buckets['60+']).toBe(0);
186
186
  expect(duration.sum).toBe(7);
187
187
  expect(duration.max).toBe(7);
188
188
  expect(duration.min).toBe(7);
189
+ // Coverage still counts BOTH measured rows.
190
+ expect(result.counters.coverage.own_anchor_count).toBe(2);
191
+ });
192
+ it('EXCLUDES a NEGATIVE duration from every duration statistic', () => {
193
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
194
+ order: order({
195
+ categories: [
196
+ {
197
+ name: 'Mains',
198
+ items: [item({ _id: 'neg', ready_minutes: -3 })],
199
+ },
200
+ ],
201
+ }),
202
+ context,
203
+ });
204
+ const duration = result.counters.duration;
205
+ expect(result.counters.coverage.own_anchor_count).toBe(1);
206
+ expect(duration.count).toBe(0);
207
+ expect(duration.sum).toBe(0);
208
+ expect(duration.min).toBe(0);
209
+ expect(duration.max).toBe(0);
210
+ expect(duration.instant_count).toBe(0);
211
+ expect(Object.values(duration.buckets).every((count) => count === 0)).toBe(true);
189
212
  });
190
213
  });
191
214
  describe('accumulateOrderPrepTime - promise grading', () => {
@@ -65,16 +65,29 @@ describe('day vs period scope classification', () => {
65
65
  expect((0, materialized_prep_time_close_day_helpers_1.isMaterializedPrepTimeDayScope)(String(scope))).toBe(false);
66
66
  }
67
67
  });
68
- it('exposes exactly the six accumulating period scopes', () => {
68
+ it('exposes exactly the month-capped accumulating period scopes', () => {
69
69
  expect(materialized_prep_time_close_day_helpers_1.MATERIALIZED_PREP_TIME_PERIOD_SCOPES.sort()).toEqual([
70
70
  'localMonth',
71
- 'localQuarter',
72
- 'localSemester',
73
71
  'localWeek',
74
72
  'localWeekOfYear',
75
- 'localYear',
76
73
  ]);
77
74
  });
75
+ it('enumerates the EXACT week / ISO-week / month sibling days', () => {
76
+ const days = (0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimePeriodDayScopeFields)('2026-09-14');
77
+ expect(days).not.toBeNull();
78
+ // Month: the whole of September; week (Sunday-start) and ISO week are both
79
+ // inside September for this Monday, so no August day is needed.
80
+ expect(days).toHaveLength(30);
81
+ expect(days[0]).toBe('2026-09-01');
82
+ expect(days[days.length - 1]).toBe('2026-09-30');
83
+ expect(new Set(days).size).toBe(days.length);
84
+ // A month boundary: the week + ISO week reach into August.
85
+ const boundary = (0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimePeriodDayScopeFields)('2026-09-01');
86
+ expect(boundary).toContain('2026-08-30'); // Sunday-start week
87
+ expect(boundary).toContain('2026-08-31'); // ISO week
88
+ expect(boundary).toContain('2026-09-30');
89
+ expect((0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimePeriodDayScopeFields)('not-a-date')).toBeNull();
90
+ });
78
91
  });
79
92
  describe('mergeMaterializedPrepTimeEntrySections', () => {
80
93
  it('ADDS a new day of rows', () => {
@@ -10,17 +10,19 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
10
10
  * tests pin the tiling, the scope cap and the two-bucket vocabulary.
11
11
  */
12
12
  describe('prep time report constants (M2)', () => {
13
- it('scopes are day + periods with NO hour scope (decision h2)', () => {
13
+ it('scopes are month-capped day + periods with NO hour scope (decision h2)', () => {
14
14
  expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES).toEqual([
15
15
  MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
16
16
  MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
17
17
  MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
18
18
  MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
19
- MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
20
- MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
21
- MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
22
19
  ]);
23
20
  expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR);
21
+ // ONE range policy: no quarter / semester / year anywhere (Summary, Details
22
+ // and the item-level reads all share this list).
23
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER);
24
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER);
25
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR);
24
26
  });
25
27
  it('buckets TILE the range with no gap and no overlap', () => {
26
28
  // Contiguous: each bucket starts exactly one minute after the previous ends.