@managesome/eposmatic-toolkit 0.4.32 → 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 (46) 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/types/materialized-reports-apis.js +10 -0
  9. package/esm/schemas/models/index.js +0 -1
  10. package/esm/schemas/types/index.js +0 -1
  11. package/lib/constants/MATERIALIZED_REPORTS.d.ts +3 -2
  12. package/lib/constants/MATERIALIZED_REPORTS.js +3 -5
  13. package/lib/constants/enums/offers.d.ts +0 -5
  14. package/lib/constants/enums/offers.js +1 -7
  15. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  16. package/lib/helpers/materialized-reports/index.js +1 -0
  17. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  18. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
  19. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +15 -0
  20. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -8
  21. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.d.ts +179 -0
  22. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.js +639 -0
  23. package/lib/helpers/types/materialized-reports-apis.d.ts +145 -1
  24. package/lib/helpers/types/materialized-reports-apis.js +11 -0
  25. package/lib/schemas/models/index.d.ts +0 -1
  26. package/lib/schemas/models/index.js +0 -1
  27. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +6 -6
  28. package/lib/schemas/types/index.d.ts +0 -1
  29. package/lib/schemas/types/index.js +0 -1
  30. package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +7 -5
  31. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +28 -5
  32. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +17 -4
  33. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +6 -4
  34. package/lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.js +135 -0
  35. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +71 -3
  36. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.d.ts +1 -0
  37. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.js +620 -0
  38. package/lib/tests/offers-matrix.test.d.ts +1 -0
  39. package/lib/tests/offers-matrix.test.js +401 -0
  40. package/package.json +1 -1
  41. package/esm/schemas/models/rewards_usage.js +0 -61
  42. package/lib/schemas/models/rewards_usage.d.ts +0 -53
  43. package/lib/schemas/models/rewards_usage.js +0 -64
  44. package/lib/schemas/types/rewards_usage.d.ts +0 -13
  45. package/lib/schemas/types/rewards_usage.js +0 -2
  46. /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';
@@ -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.
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_prep_time_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-prep-time-compile-helpers");
5
+ const tenant_prep_time_formatter_1 = require("../../helpers/materialized-reports/tenant-prep-time-formatter");
6
+ const materialized_prep_time_read_helpers_1 = require("../../helpers/materialized-reports/materialized-prep-time-read-helpers");
7
+ /**
8
+ * ONE duration population across the WHOLE report.
9
+ *
10
+ * The bug this pins: the Summary used to include an out-of-range (or negative)
11
+ * duration in `duration.count` while excluding it from `duration.sum`, so
12
+ * `avg = sum / count` was silently understated and disagreed with the
13
+ * item/category reads. VALID durations alone now feed count/sum/min/max/buckets/
14
+ * instant count, and the Summary average equals the item/category weighted
15
+ * average over the same population.
16
+ */
17
+ const TENANT = 'tenant-consistency';
18
+ const BRAND = 'brand-consistency';
19
+ const DAY = '2026-09-10';
20
+ const BASE = new Date(`${DAY}T10:00:00.000Z`);
21
+ const item = (id, minutes) => ({
22
+ _id: id,
23
+ name: id,
24
+ is_ready: true,
25
+ ready_minutes: minutes,
26
+ prep_started_at: BASE,
27
+ quantity: 1,
28
+ });
29
+ const order = () => ({
30
+ _id: 'order-consistency',
31
+ tenant_id: TENANT,
32
+ order_number: 1,
33
+ order_status: 'COMPLETED',
34
+ platform: 'POS_WALK-IN',
35
+ localHour: 10,
36
+ localDate: DAY,
37
+ is_deleted: false,
38
+ createdAt: BASE,
39
+ updatedAt: BASE,
40
+ categories: [
41
+ {
42
+ name: 'Mains',
43
+ items: [item('a', 8), item('c', 30)],
44
+ },
45
+ {
46
+ name: 'Other',
47
+ items: [item('b', 20), item('invalid-high', MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_MAX_MINUTES + 1), item('invalid-negative', -3)],
48
+ },
49
+ ],
50
+ });
51
+ const compiled = (0, materialized_prep_time_compile_helpers_1.compileTenantPrepTimeReports)({
52
+ tenantId: TENANT,
53
+ brandId: BRAND,
54
+ localDate: DAY,
55
+ orders: [order()],
56
+ computedAt: new Date(`${DAY}T23:00:00.000Z`),
57
+ });
58
+ const dayReport = compiled.reports.find((report) => report.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
59
+ report.scope_field === DAY);
60
+ const dayEntry = compiled.entries.find((entry) => entry.scope_context === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE &&
61
+ entry.scope_field === DAY);
62
+ const readRows = Object.values(dayEntry.prep_time_entries ?? {}).flatMap((section) => (section.rows ?? []).map((row) => ({
63
+ tenant_id: TENANT,
64
+ order_id: row.order_id,
65
+ item_id: String(row.item_id),
66
+ item_name: row.item_name,
67
+ category_name: row.category_name,
68
+ anchor: row.anchor,
69
+ duration_minutes: row.duration_minutes,
70
+ delta_minutes: row.delta_minutes,
71
+ order_status: row.order_status,
72
+ platform: row.platform,
73
+ created_at: row.created_at,
74
+ source_local_date: DAY,
75
+ })));
76
+ describe('prep time duration population - summary vs item/category', () => {
77
+ it('excludes invalid durations from count, sum, buckets and instant count', () => {
78
+ const formatted = (0, tenant_prep_time_formatter_1.getFormattedTenantPrepTimeReporting)([dayReport]);
79
+ const summary = formatted[0][0].summary;
80
+ // Valid: 8, 30, 20. Invalid: MAX+1 and -3 — measured coverage still counts
81
+ // all five, but the duration population has three observations.
82
+ expect(dayReport.prep_time_counters['COMPLETED:POS_WALK-IN'].coverage.own_anchor_count).toBe(5);
83
+ expect(dayReport.prep_time_counters['COMPLETED:POS_WALK-IN'].duration.count).toBe(3);
84
+ expect(summary.own_anchor_items).toBe(5);
85
+ expect(summary.avg_minutes).toBe(19.3);
86
+ const buckets = dayReport.prep_time_counters['COMPLETED:POS_WALK-IN'].duration.buckets;
87
+ expect(Object.values(buckets).reduce((sum, value) => sum + value, 0)).toBe(3);
88
+ });
89
+ it('has NO split denominator: summary avg equals the item weighted avg', () => {
90
+ const formatted = (0, tenant_prep_time_formatter_1.getFormattedTenantPrepTimeReporting)([dayReport]);
91
+ const summary = formatted[0][0].summary;
92
+ const items = (0, materialized_prep_time_read_helpers_1.groupMaterializedPrepTimeItemRows)(readRows);
93
+ // Weight by each item's VALID duration count (the same population the
94
+ // summary uses). Items whose only durations are invalid have avg null and
95
+ // contribute 0 observations.
96
+ let weightedSum = 0;
97
+ let validCount = 0;
98
+ for (const itemRow of items) {
99
+ const count = readRows.filter((row) => row.item_id === itemRow.item_id &&
100
+ row.anchor === 'MEASURED' &&
101
+ (0, materialized_prep_time_read_helpers_1.isMaterializedPrepTimeDurationCountable)(row.duration_minutes)).length;
102
+ expect(itemRow.measured_count).toBe(readRows.filter((row) => row.item_id === itemRow.item_id).length);
103
+ if (count === 0) {
104
+ expect(itemRow.avg_minutes).toBeNull();
105
+ continue;
106
+ }
107
+ weightedSum += (itemRow.avg_minutes ?? 0) * count;
108
+ validCount += count;
109
+ }
110
+ expect(validCount).toBe(3);
111
+ expect(Math.abs(weightedSum / validCount - summary.avg_minutes)).toBeLessThan(0.1);
112
+ // The invalid-only item is measured but has no duration statistics.
113
+ const invalidOnly = items.find((row) => row.item_id === 'invalid-negative');
114
+ expect(invalidOnly.measured_count).toBe(1);
115
+ expect(invalidOnly.avg_minutes).toBeNull();
116
+ expect(invalidOnly.median_minutes).toBeNull();
117
+ expect(invalidOnly.p90_minutes).toBeNull();
118
+ });
119
+ it('has summary avg equal to the CATEGORY weighted avg for the same population', () => {
120
+ const formatted = (0, tenant_prep_time_formatter_1.getFormattedTenantPrepTimeReporting)([dayReport]);
121
+ const summary = formatted[0][0].summary;
122
+ const categories = (0, materialized_prep_time_read_helpers_1.groupMaterializedPrepTimeCategoryRows)(readRows);
123
+ let weightedSum = 0;
124
+ let validCount = 0;
125
+ for (const category of categories) {
126
+ const count = readRows.filter((row) => row.category_name === category.category_name &&
127
+ row.anchor === 'MEASURED' &&
128
+ (0, materialized_prep_time_read_helpers_1.isMaterializedPrepTimeDurationCountable)(row.duration_minutes)).length;
129
+ weightedSum += (category.avg_minutes ?? 0) * count;
130
+ validCount += count;
131
+ }
132
+ expect(validCount).toBe(3);
133
+ expect(Math.abs(weightedSum / validCount - summary.avg_minutes)).toBeLessThan(0.1);
134
+ });
135
+ });
@@ -76,11 +76,8 @@ describe('buildTenantPrepTimeCloseDayPlan', () => {
76
76
  const periodWrites = plan.writes.filter((write) => write.report.scope_context !== 'localDate');
77
77
  expect(periodWrites.map((write) => write.report.scope_context).sort()).toEqual([
78
78
  'localMonth',
79
- 'localQuarter',
80
- 'localSemester',
81
79
  'localWeek',
82
80
  'localWeekOfYear',
83
- 'localYear',
84
81
  ]);
85
82
  for (const write of periodWrites) {
86
83
  expect(write.report.prep_time_counters[KEY].coverage.item_count).toBe(3);
@@ -174,3 +171,74 @@ describe('buildTenantPrepTimeCloseDayPlan', () => {
174
171
  expect((0, materialized_prep_time_close_day_helpers_1.needsMaterializedPrepTimeReportWrite)(stored, newer)).toBe(true);
175
172
  });
176
173
  });
174
+ /** A day/period entry document (rows are irrelevant to the iteration contract). */
175
+ const entry = (scope, field, over = {}) => ({
176
+ _id: scope + '|' + field,
177
+ tenant_id: 'tenant-a',
178
+ brand_id: 'brand-a',
179
+ scope_context: scope,
180
+ scope_field: field,
181
+ day_index: scope === 'localDate' ? 'MON' : null,
182
+ sale_type_key_filters: ['ORDER_STATUS', 'PLATFORM'],
183
+ prep_time_entries: { [KEY]: { rows: [] } },
184
+ schema_version: 1,
185
+ source_watermark: new Date('2026-09-14T23:00:00.000Z'),
186
+ computed_at: new Date('2026-09-14T23:00:00.000Z'),
187
+ createdAt: new Date('2026-09-14T23:00:00.000Z'),
188
+ updatedAt: new Date('2026-09-14T23:00:00.000Z'),
189
+ ...over,
190
+ });
191
+ describe('buildTenantPrepTimeCloseDayPlan - reclose iterations + force', () => {
192
+ it('ADVANCES the report and entry iterations on a forced reclose', () => {
193
+ const existingDay = report('localDate', '2026-09-14', {
194
+ coverage: { item_count: 2 },
195
+ iteration: 4,
196
+ });
197
+ const existingDayEntry = entry('localDate', '2026-09-14', { iteration: 6 });
198
+ const plan = build({
199
+ reports: [report('localDate', '2026-09-14', { coverage: { item_count: 3 } })],
200
+ entries: [entry('localDate', '2026-09-14')],
201
+ existing: [existingDay],
202
+ existingEntries: [existingDayEntry],
203
+ reason: 'RECLOSE',
204
+ force: true,
205
+ });
206
+ const dayWrite = plan.writes.find((write) => write.report.scope_context === 'localDate');
207
+ expect(dayWrite.report.iteration).toBe(5);
208
+ expect(dayWrite.iteration.iteration).toBe(5);
209
+ const dayEntryWrite = plan.entryWrites.find((write) => write.report.scope_context === 'localDate');
210
+ expect(dayEntryWrite.report.iteration).toBe(7);
211
+ expect(dayEntryWrite.iteration.iteration).toBe(7);
212
+ });
213
+ it('SKIPS an unchanged reclose without force and writes nothing', () => {
214
+ const existingDay = report('localDate', '2026-09-14', {
215
+ coverage: { item_count: 3 },
216
+ iteration: 4,
217
+ source_watermark: new Date('2026-09-14T23:05:00.000Z'),
218
+ });
219
+ const existingDayEntry = entry('localDate', '2026-09-14', {
220
+ iteration: 6,
221
+ source_watermark: new Date('2026-09-14T23:05:00.000Z'),
222
+ });
223
+ const plan = build({
224
+ reports: [
225
+ report('localDate', '2026-09-14', {
226
+ coverage: { item_count: 3 },
227
+ source_watermark: new Date('2026-09-14T23:00:00.000Z'),
228
+ }),
229
+ ],
230
+ entries: [
231
+ entry('localDate', '2026-09-14', {
232
+ source_watermark: new Date('2026-09-14T23:00:00.000Z'),
233
+ }),
234
+ ],
235
+ existing: [existingDay],
236
+ existingEntries: [existingDayEntry],
237
+ reason: 'RECLOSE',
238
+ });
239
+ expect(plan.writes.some((write) => write.report.scope_context === 'localDate')).toBe(false);
240
+ expect(plan.entryWrites.some((write) => write.report.scope_context === 'localDate')).toBe(false);
241
+ expect(plan.skippedDocuments.length).toBeGreaterThan(0);
242
+ expect(plan.skippedEntryDocuments.length).toBeGreaterThan(0);
243
+ });
244
+ });