@managesome/eposmatic-toolkit 0.4.34 → 0.4.36

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 (29) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +25 -5
  2. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +30 -9
  3. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +98 -44
  4. package/esm/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +7 -3
  5. package/esm/helpers/materialized-reports/materialized-prep-time-read-helpers.js +35 -10
  6. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +3 -1
  7. package/esm/schemas/models/materialized_tenant_prep_time_entries.js +3 -2
  8. package/lib/constants/MATERIALIZED_REPORTS.d.ts +17 -5
  9. package/lib/constants/MATERIALIZED_REPORTS.js +27 -7
  10. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.d.ts +10 -2
  11. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +30 -9
  12. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +13 -6
  13. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +99 -44
  14. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +6 -2
  15. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.d.ts +19 -0
  16. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.js +37 -10
  17. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +3 -1
  18. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +3 -0
  19. package/lib/schemas/models/materialized_tenant_prep_time_entries.js +2 -1
  20. package/lib/schemas/types/materialized_tenant_prep_time_entries.d.ts +3 -0
  21. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +9 -2
  22. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +20 -1
  23. package/lib/tests/materialized-reports/materialized-prep-time-compile.test.js +22 -3
  24. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +17 -6
  25. package/lib/tests/materialized-reports/materialized-prep-time-identity.test.d.ts +1 -0
  26. package/lib/tests/materialized-reports/materialized-prep-time-identity.test.js +163 -0
  27. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +38 -0
  28. package/lib/tests/materialized-reports/materialized-report-drilldown-rows.test.js +19 -2
  29. package/package.json +1 -1
@@ -417,20 +417,40 @@ export const MATERIALIZED_DELIVERY_AREA_LIMIT = 50;
417
417
  /* Prep time report (M2) */
418
418
  /* ======================================================================== */
419
419
  /**
420
- * Scopes materialized by `materialized_tenant_prep_time_reports`.
420
+ * Scopes materialized by `materialized_tenant_prep_time_reports` — the SUMMARY
421
+ * range (and the writer's COUNTER scopes).
421
422
  *
422
423
  * NO `localHour` (decision h2): the tracked population per hour is 2-3 items in
423
- * the dev stores, so an hourly prep time would be noise. Day + periods only,
424
- * CAPPED AT `LOCAL_MONTH`: quarter / semester / year are deliberately absent so
425
- * the Summary, Details and the item-level reads all apply the SAME range policy,
426
- * and the itemized rows in the sibling entries collection stay month-bounded.
424
+ * the dev stores, so an hourly prep time would be noise.
425
+ *
426
+ * The Summary is CHEAP for a year because it reads these pre-aggregated counters,
427
+ * not item rows. The itemized reads are a DIFFERENT, month-capped list
428
+ * (`MATERIALIZED_PREP_TIME_ITEM_SCOPES`); the writer therefore materializes the
429
+ * full counter range but only month-capped ENTRY rows / flat period rows.
427
430
  */
428
431
  export const MATERIALIZED_PREP_TIME_REPORT_SCOPES = [
429
432
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
430
433
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
431
434
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
432
435
  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
+ ];
440
+ /**
441
+ * Scopes the ITEMIZED prep reads support — Items, Categories and the Details
442
+ * drill-down. Capped at `LOCAL_MONTH` so item rows can never grow into a
443
+ * quarter/year document; the service additionally enforces a 31-effective-day
444
+ * cap (see `MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS`).
445
+ */
446
+ export const MATERIALIZED_PREP_TIME_ITEM_SCOPES = [
447
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
448
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
449
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
450
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
433
451
  ];
452
+ /** Max EFFECTIVE days (after weekday/date refinement) an item read may cover. */
453
+ export const MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS = 31;
434
454
  /** Ordered key filters of the prep time report (`COMPLETED:POS_WALK-IN`). */
435
455
  export const PREP_TIME_KEY_FILTERS = [
436
456
  MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
@@ -96,8 +96,21 @@ export function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes) {
96
96
  }
97
97
  return { target_at: null, target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
98
98
  }
99
- /** Stable identity of a row inside its order - part of the page cursor. */
100
- export const buildMaterializedPrepTimeEntryKey = (itemId) => 'item:' + String(itemId ?? 'unknown');
99
+ /**
100
+ * Stable identity of ONE served item row inside its order - part of the page
101
+ * cursor and the flat projection identity.
102
+ *
103
+ * The catalogue item id is the GROUPING key; the order-line id keeps two lines
104
+ * of the same catalogue item distinct. A line is appended only when it differs
105
+ * from the catalogue id, so the common (and legacy) one-line shape is stable.
106
+ */
107
+ export const buildMaterializedPrepTimeEntryKey = (itemId, lineId) => {
108
+ const parts = [String(itemId ?? 'unknown')];
109
+ if (lineId != null && String(lineId) !== '' && String(lineId) !== String(itemId ?? '')) {
110
+ parts.push(String(lineId));
111
+ }
112
+ return 'item:' + parts.join(':');
113
+ };
101
114
  /**
102
115
  * Accumulates ONE order's items into the prep counters + drill-down rows.
103
116
  *
@@ -191,12 +204,19 @@ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes =
191
204
  else {
192
205
  counters.promise.no_target_count += 1;
193
206
  }
194
- const itemId = item?._id != null ? String(item._id) : null;
207
+ // CATALOGUE item id: the grouping identity the Items tab reads. The
208
+ // order-line id is a DIFFERENT identity and is preserved as line_id, so
209
+ // two lines of one menu item remain two served events.
210
+ const lineId = item?._id != null ? String(item._id) : null;
211
+ const catalogueItemId = item?.item_id != null && String(item.item_id) !== ''
212
+ ? String(item.item_id)
213
+ : lineId;
195
214
  const row = {
196
- entry_key: buildMaterializedPrepTimeEntryKey(itemId),
215
+ entry_key: buildMaterializedPrepTimeEntryKey(catalogueItemId, lineId),
197
216
  order_id: orderId,
198
217
  order_number: order.order_number ?? null,
199
- item_id: itemId,
218
+ item_id: catalogueItemId,
219
+ line_id: lineId,
200
220
  item_name: item?.name != null ? String(item.name) : null,
201
221
  category_name: category?.name != null ? String(category.name) : null,
202
222
  anchor,
@@ -214,10 +234,11 @@ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes =
214
234
  created_at: createdAt,
215
235
  local_hour: context.local_hour_label,
216
236
  };
217
- // Only items with a prep signal become rows: an untouched item has nothing
218
- // to inspect, and the drill-down exists to explain the numbers.
219
- if (minutes != null || prepStartedValid)
220
- entries.push(row);
237
+ // EVERY served item becomes a row - including an item with no prep
238
+ // signal. Coverage uses ALL served items as its denominator; a no-signal
239
+ // row is an UNMEASURED row with null duration and is visible in the
240
+ // Unmeasured view.
241
+ entries.push(row);
221
242
  }
222
243
  }
223
244
  if (tracked > 0)
@@ -1,5 +1,5 @@
1
1
  import mongoose from 'mongoose';
2
- import { MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { MATERIALIZED_PREP_TIME_ITEM_SCOPES, MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { freshMaterializedPrepTimeCounters } from './materialized-prep-time-classification-helpers';
4
4
  import { mergeMaterializedPrepTimeCounters } from './materialized-prep-time-compile-helpers';
5
5
  import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
@@ -154,66 +154,116 @@ export function foldMaterializedPrepTimePeriodRows({ periodScopeField, periodSco
154
154
  }
155
155
  /** The period scope contexts (everything except the day scope). */
156
156
  export const MATERIALIZED_PREP_TIME_PERIOD_SCOPES = MATERIALIZED_PREP_TIME_REPORT_SCOPES.filter((scope) => !isMaterializedPrepTimeDayScope(String(scope)));
157
+ /** Period scopes that carry ENTRY rows / flat rows (month-capped). */
158
+ export const MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES = MATERIALIZED_PREP_TIME_ITEM_SCOPES.filter((scope) => !isMaterializedPrepTimeDayScope(String(scope)));
157
159
  /* ------------------------------------------------------------------------ */
158
160
  /* Period sibling-day enumeration */
159
161
  /* ------------------------------------------------------------------------ */
160
162
  const pad2 = (value) => String(value).padStart(2, '0');
161
163
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
162
164
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
163
- const addMonthDays = (year, month, days) => {
165
+ const addMonthDays = (year, month, count, days) => {
164
166
  if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
165
167
  return false;
166
- const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
167
- for (let day = 1; day <= last; day += 1) {
168
- days.add(`${year}-${pad2(month)}-${pad2(day)}`);
168
+ for (let offset = 0; offset < count; offset += 1) {
169
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
170
+ const monthYear = date.getUTCFullYear();
171
+ const monthNumber = date.getUTCMonth() + 1;
172
+ const last = new Date(Date.UTC(monthYear, monthNumber, 0)).getUTCDate();
173
+ for (let day = 1; day <= last; day += 1) {
174
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
175
+ }
169
176
  }
170
177
  return true;
171
178
  };
172
- /**
173
- * Every `localDate` label whose DAY entry document can contribute to a period
174
- * the closing day rolls into (week / ISO week / month).
175
- *
176
- * The worker uses this to fetch exactly the sibling day entries the period
177
- * fold needs — never a full-period entry document and never a year-wide scan.
178
- * Returns `null` (never throws) for a malformed date.
179
- */
180
- export function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
179
+ const addPeriodDays = (scope, scopeField, days) => {
180
+ switch (scope) {
181
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
182
+ const parts = parseMaterializedLocalDate(scopeField);
183
+ if (parts == null)
184
+ return false;
185
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
186
+ if (start.getUTCDay() !== 0)
187
+ return false;
188
+ for (let offset = 0; offset < 7; offset += 1)
189
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
190
+ return true;
191
+ }
192
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
193
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
194
+ if (match == null)
195
+ return false;
196
+ const weekYear = Number(match[1]);
197
+ const week = Number(match[2]);
198
+ if (!Number.isInteger(week) || week < 1 || week > 53)
199
+ return false;
200
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
201
+ const isoWeekday = jan4.getUTCDay() || 7;
202
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
203
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
204
+ for (let offset = 0; offset < 7; offset += 1)
205
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
206
+ return true;
207
+ }
208
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
209
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
210
+ if (match == null)
211
+ return false;
212
+ return addMonthDays(Number(match[1]), Number(match[2]), 1, days);
213
+ }
214
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
215
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
216
+ if (match == null)
217
+ return false;
218
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
219
+ }
220
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
221
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
222
+ if (match == null)
223
+ return false;
224
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
225
+ }
226
+ case MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
227
+ const match = /^(\d{4})$/.exec(scopeField);
228
+ if (match == null)
229
+ return false;
230
+ return addMonthDays(Number(match[1]), 1, 12, days);
231
+ }
232
+ default:
233
+ return false;
234
+ }
235
+ };
236
+ const enumeratePeriodDays = (localDate, scopes) => {
181
237
  const periodFields = getMaterializedPeriodScopeFields(localDate);
182
238
  if (periodFields == null)
183
239
  return null;
184
240
  const days = new Set([localDate]);
185
- const weekField = periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
186
- const weekParts = typeof weekField === 'string' ? parseMaterializedLocalDate(weekField) : null;
187
- if (weekParts == null)
188
- return null;
189
- const weekStart = new Date(Date.UTC(weekParts.year, weekParts.month - 1, weekParts.day));
190
- if (weekStart.getUTCDay() !== 0)
191
- return null;
192
- for (let offset = 0; offset < 7; offset += 1) {
193
- days.add(toLocalDateKey(addUtcDays(weekStart, offset)));
194
- }
195
- const isoWeekField = periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR];
196
- const isoMatch = typeof isoWeekField === 'string' ? /^(\d{4})-W(\d{2})$/.exec(isoWeekField) : null;
197
- if (isoMatch == null)
198
- return null;
199
- const weekYear = Number(isoMatch[1]);
200
- const week = Number(isoMatch[2]);
201
- if (!Number.isInteger(week) || week < 1 || week > 53)
202
- return null;
203
- const jan4 = new Date(Date.UTC(weekYear, 0, 4));
204
- const isoWeekday = jan4.getUTCDay() || 7;
205
- const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
206
- const isoStart = addUtcDays(weekOneMonday, (week - 1) * 7);
207
- for (let offset = 0; offset < 7; offset += 1) {
208
- days.add(toLocalDateKey(addUtcDays(isoStart, offset)));
241
+ for (const scope of scopes) {
242
+ const scopeField = periodFields[scope];
243
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
244
+ return null;
245
+ if (!addPeriodDays(scope, scopeField, days))
246
+ return null;
209
247
  }
210
- const monthField = periodFields[MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
211
- const monthMatch = typeof monthField === 'string' ? /^(\d{4})-(\d{2})$/.exec(monthField) : null;
212
- if (monthMatch == null)
213
- return null;
214
- if (!addMonthDays(Number(monthMatch[1]), Number(monthMatch[2]), days))
215
- return null;
216
248
  return [...days].sort();
249
+ };
250
+ /**
251
+ * Every `localDate` label whose DAY entry document can contribute to a
252
+ * month-capped period (week / ISO week / month). The worker uses this to fetch
253
+ * exactly the sibling day entries the entry fold needs — never a full-period
254
+ * entry document and never a year-wide scan.
255
+ */
256
+ export function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
257
+ return enumeratePeriodDays(localDate, MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
258
+ }
259
+ /**
260
+ * Every `localDate` label whose DAY counter document can contribute to ANY
261
+ * report period the closing day rolls into, including quarter / semester /
262
+ * year. Used by the worker's SUMMARY counter fold only; entry rows stay
263
+ * month-capped.
264
+ */
265
+ export function getMaterializedPrepTimeReportPeriodDayScopeFields(localDate) {
266
+ return enumeratePeriodDays(localDate, MATERIALIZED_PREP_TIME_PERIOD_SCOPES);
217
267
  }
218
268
  /** True when a stored prep counter document equals the incoming one (skip write). */
219
269
  export function needsMaterializedPrepTimeReportWrite(existing, incoming) {
@@ -470,7 +520,11 @@ export function buildTenantPrepTimeCloseDayPlan(input) {
470
520
  continue;
471
521
  staleEntryDocuments.push(doc);
472
522
  }
523
+ const itemPeriodScopes = new Set(MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
473
524
  for (const { scope, field } of touchedPeriods.values()) {
525
+ // ENTRY documents are month-capped; quarter/semester/year are COUNTER only.
526
+ if (!itemPeriodScopes.has(String(scope)))
527
+ continue;
474
528
  const sections = foldMaterializedPrepTimePeriodRows({
475
529
  periodScope: scope,
476
530
  periodScopeField: field,
@@ -1,5 +1,5 @@
1
1
  import mongoose from 'mongoose';
2
- import { MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, PREP_TIME_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { MATERIALIZED_PREP_TIME_ITEM_SCOPES, MATERIALIZED_PREP_TIME_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, PREP_TIME_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
3
3
  import { accumulateOrderPrepTime, freshMaterializedPrepTimeCounters, } from './materialized-prep-time-classification-helpers';
4
4
  import { getDayIndexFromLocalDate, getMaterializedPeriodScopeFields } from './scope-helpers';
5
5
  /**
@@ -86,6 +86,7 @@ export function compileTenantPrepTimeReports(input) {
86
86
  return null;
87
87
  const dayIndex = getDayIndexFromLocalDate(localDate);
88
88
  const at = computedAt ?? new Date();
89
+ const itemScopes = new Set(MATERIALIZED_PREP_TIME_ITEM_SCOPES);
89
90
  const byScope = new Map();
90
91
  const scopeContextOf = new Map();
91
92
  const bucketFor = (scope, scopeField, key) => {
@@ -138,7 +139,10 @@ export function compileTenantPrepTimeReports(input) {
138
139
  continue;
139
140
  const bucket = bucketFor(scope, scopeField, key);
140
141
  mergeMaterializedPrepTimeCounters(bucket.counters, result.counters);
141
- bucket.rows.push(...result.entries);
142
+ // ENTRY rows / flat rows are month-capped; the Summary counters go to the
143
+ // full report range. Never accumulate quarter/semester/year item rows.
144
+ if (itemScopes.has(scope))
145
+ bucket.rows.push(...result.entries);
142
146
  foldWatermark(bucket, watermark);
143
147
  }
144
148
  }
@@ -179,7 +183,7 @@ export function compileTenantPrepTimeReports(input) {
179
183
  createdAt: at,
180
184
  updatedAt: at,
181
185
  });
182
- if (Object.keys(entrySections).length > 0) {
186
+ if (itemScopes.has(scopeContext) && Object.keys(entrySections).length > 0) {
183
187
  entries.push({
184
188
  _id: new mongoose.Types.ObjectId().toHexString(),
185
189
  tenant_id: tenantId,
@@ -232,11 +232,23 @@ const addTotals = (totals, row) => {
232
232
  else
233
233
  totals.unmeasured += 1;
234
234
  };
235
- const coverageFromTotals = (totals) => ({
235
+ /**
236
+ * Coverage from COUNTS (the server-side Series aggregation groups in Mongo and
237
+ * therefore has no raw rows). Same math as `buildMaterializedPrepTimeCoverage`.
238
+ */
239
+ export function buildMaterializedPrepTimeCoverageFromCounts(input) {
240
+ const served = Math.max(0, Math.floor(Number(input.served_count) || 0));
241
+ const measured = Math.max(0, Math.floor(Number(input.measured_count) || 0));
242
+ return {
243
+ served_count: served,
244
+ measured_count: measured,
245
+ unmeasured_count: Math.max(0, served - measured),
246
+ coverage_percent: served > 0 ? round1((measured / served) * 100) : 0,
247
+ };
248
+ }
249
+ const coverageFromTotals = (totals) => buildMaterializedPrepTimeCoverageFromCounts({
236
250
  served_count: totals.served,
237
251
  measured_count: totals.measured,
238
- unmeasured_count: totals.unmeasured,
239
- coverage_percent: totals.served > 0 ? round1((totals.measured / totals.served) * 100) : 0,
240
252
  });
241
253
  /** Coverage of the supplied population (measured / served, one decimal). */
242
254
  export function buildMaterializedPrepTimeCoverage(rows) {
@@ -301,15 +313,28 @@ const addMetrics = (metrics, row) => {
301
313
  metrics.late += 1;
302
314
  }
303
315
  };
316
+ /**
317
+ * Duration statistics for a list of VALID durations (invalid values are
318
+ * filtered defensively). `null` for an empty population — never 0.
319
+ */
320
+ export function summarizeMaterializedPrepTimeDurations(durations) {
321
+ const valid = (Array.isArray(durations) ? durations : []).filter(isMaterializedPrepTimeDurationCountable);
322
+ if (valid.length === 0) {
323
+ return { avg_minutes: null, median_minutes: null, p90_minutes: null };
324
+ }
325
+ const sum = valid.reduce((total, value) => total + value, 0);
326
+ return {
327
+ avg_minutes: round1(sum / valid.length),
328
+ median_minutes: getMaterializedPrepTimeMedian(valid),
329
+ p90_minutes: getMaterializedPrepTimeP90(valid),
330
+ };
331
+ }
304
332
  const durationStats = (durations) => {
305
- const count = durations.length;
306
- if (count === 0)
307
- return { avg: null, median: null, p90: null };
308
- const sum = durations.reduce((total, value) => total + value, 0);
333
+ const summary = summarizeMaterializedPrepTimeDurations(durations);
309
334
  return {
310
- avg: round1(sum / count),
311
- median: getMaterializedPrepTimeMedian(durations),
312
- p90: getMaterializedPrepTimeP90(durations),
335
+ avg: summary.avg_minutes,
336
+ median: summary.median_minutes,
337
+ p90: summary.p90_minutes,
313
338
  };
314
339
  };
315
340
  const freshItemGroup = (itemId) => ({
@@ -25,7 +25,9 @@ const ROW_SPECS = {
25
25
  rowsKey: 'prep_time_entries',
26
26
  time: (row) => row.created_at,
27
27
  orderId: (row) => row.order_id,
28
- cursorId: (row) => row.item_id,
28
+ // ROW identity, not the catalogue item id: two lines of the same menu item
29
+ // in one order must both survive the unique flat-row identity.
30
+ cursorId: (row) => row.entry_key,
29
31
  },
30
32
  [MATERIALIZED_REPORT_TYPE_ENUM.TENANT_CASH_ENTRIES]: {
31
33
  rowsKey: 'cash_entries',
@@ -1,6 +1,6 @@
1
1
  import { Schema } from 'mongoose';
2
2
  import { ALL_DAY_INDEX } from '../../constants/ENUMS';
3
- import { ALL_MATERIALIZED_PREP_TIME_ANCHORS, ALL_MATERIALIZED_PREP_TIME_TARGETS, ALL_MATERIALIZED_REPORT_KEY_FILTERS, MATERIALIZED_PREP_TIME_REPORT_SCOPES, PREP_TIME_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { ALL_MATERIALIZED_PREP_TIME_ANCHORS, ALL_MATERIALIZED_PREP_TIME_TARGETS, ALL_MATERIALIZED_REPORT_KEY_FILTERS, MATERIALIZED_PREP_TIME_ITEM_SCOPES, PREP_TIME_KEY_FILTERS, } from '../../constants/MATERIALIZED_REPORTS';
4
4
  /**
5
5
  * Mongoose schema for `materialized_tenant_prep_time_entries` - the ITEMIZED prep
6
6
  * rows behind the prep time report's drill-down (owner decision (a2): SPLIT).
@@ -27,6 +27,7 @@ const PrepTimeEntrySchema = new Schema({
27
27
  order_id: { type: String, required: true },
28
28
  order_number: { type: Number, default: null },
29
29
  item_id: { type: String, default: null },
30
+ line_id: { type: String, default: null },
30
31
  item_name: { type: String, default: null },
31
32
  category_name: { type: String, default: null },
32
33
  // ---- measurement ----
@@ -60,7 +61,7 @@ export const MaterializedTenantPrepTimeEntriesSchema = new Schema({
60
61
  scope_context: {
61
62
  type: String,
62
63
  required: true,
63
- enum: MATERIALIZED_PREP_TIME_REPORT_SCOPES,
64
+ enum: MATERIALIZED_PREP_TIME_ITEM_SCOPES,
64
65
  },
65
66
  scope_field: { type: String, required: true },
66
67
  day_index: {
@@ -337,15 +337,27 @@ export declare const MATERIALIZED_DELIVERY_RIDER_LIMIT = 50;
337
337
  /** Cap of the per-document area leaderboard (bounded, display-only). */
338
338
  export declare const MATERIALIZED_DELIVERY_AREA_LIMIT = 50;
339
339
  /**
340
- * Scopes materialized by `materialized_tenant_prep_time_reports`.
340
+ * Scopes materialized by `materialized_tenant_prep_time_reports` — the SUMMARY
341
+ * range (and the writer's COUNTER scopes).
341
342
  *
342
343
  * NO `localHour` (decision h2): the tracked population per hour is 2-3 items in
343
- * the dev stores, so an hourly prep time would be noise. Day + periods only,
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.
344
+ * the dev stores, so an hourly prep time would be noise.
345
+ *
346
+ * The Summary is CHEAP for a year because it reads these pre-aggregated counters,
347
+ * not item rows. The itemized reads are a DIFFERENT, month-capped list
348
+ * (`MATERIALIZED_PREP_TIME_ITEM_SCOPES`); the writer therefore materializes the
349
+ * full counter range but only month-capped ENTRY rows / flat period rows.
347
350
  */
348
351
  export declare const MATERIALIZED_PREP_TIME_REPORT_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
352
+ /**
353
+ * Scopes the ITEMIZED prep reads support — Items, Categories and the Details
354
+ * drill-down. Capped at `LOCAL_MONTH` so item rows can never grow into a
355
+ * quarter/year document; the service additionally enforces a 31-effective-day
356
+ * cap (see `MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS`).
357
+ */
358
+ export declare const MATERIALIZED_PREP_TIME_ITEM_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
359
+ /** Max EFFECTIVE days (after weekday/date refinement) an item read may cover. */
360
+ export declare const MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS = 31;
349
361
  /** Ordered key filters of the prep time report (`COMPLETED:POS_WALK-IN`). */
350
362
  export declare const PREP_TIME_KEY_FILTERS: MATERIALIZED_REPORT_KEY_FILTER_ENUM[];
351
363
  /**
@@ -10,8 +10,8 @@
10
10
  * explicitly-enabled step.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = exports.MATERIALIZED_PREP_TIME_TOP_BUCKET = exports.MATERIALIZED_PREP_TIME_MAX_MINUTES = exports.ALL_MATERIALIZED_PREP_TIME_BUCKET_LABELS = exports.MATERIALIZED_PREP_TIME_BUCKETS = exports.ALL_MATERIALIZED_PREP_TIME_ANCHORS = exports.MATERIALIZED_PREP_TIME_ANCHOR_ENUM = exports.PREP_TIME_KEY_FILTERS = exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = exports.MATERIALIZED_DELIVERY_AREA_LIMIT = exports.MATERIALIZED_DELIVERY_RIDER_LIMIT = exports.MATERIALIZED_DELIVERY_DISTANCE_BUCKETS = exports.DELIVERY_KEY_FILTERS = exports.MATERIALIZED_DELIVERY_REPORT_SCOPES = exports.MATERIALIZED_CASH_SOURCE_LIMIT = exports.CASH_KEY_FILTERS = exports.MATERIALIZED_CASH_REPORT_SCOPES = exports.ALL_MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPES = exports.MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM = exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY = exports.ALL_MATERIALIZED_DISCOUNT_RATE_KINDS = exports.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SOURCE_CLASSES = exports.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM = exports.MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX = exports.MATERIALIZED_DISCOUNT_MANUAL_PREFIX = exports.MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID = exports.MATERIALIZED_DISCOUNT_SOURCE_LIMIT = exports.ALL_MATERIALIZED_DISCOUNT_LEVELS = exports.MATERIALIZED_DISCOUNT_LEVEL_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS = exports.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SUB_KINDS = exports.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SLOTS = exports.MATERIALIZED_DISCOUNT_SLOT_ENUM = exports.DISCOUNTS_KEY_FILTERS = exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = exports.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = exports.SALES_OVERVIEW_KEY_FILTERS = exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = exports.MATERIALIZED_CREDIT_BILLS_SCOPES = exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = exports.ALL_MATERIALIZED_REPORT_WINDOW_KINDS = exports.MATERIALIZED_REPORT_WINDOW_KIND_ENUM = exports.ALL_MATERIALIZED_REPORT_SCOPES = exports.MATERIALIZED_REPORT_SCOPE_ENUM = void 0;
14
- exports.ALL_PAYMENTS_COMPARISON_METRICS = exports.PAYMENTS_COMPARISON_METRIC_ENUM = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_SCHEMA_VERSION = exports.PAYMENTS_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_PAYMENTS_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_SCHEMA_VERSION = exports.HOURLY_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_HOURLY_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_SALES_COMPARISON_METRICS = exports.SALES_COMPARISON_METRIC_ENUM = exports.ALL_SALES_COMPARISON_BASELINES = exports.SALES_COMPARISON_BASELINE_ENUM = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_SCHEMA_VERSION = exports.SALES_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_SALES_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_MATERIALIZED_REPORT_TYPES = exports.MATERIALIZED_REPORT_TYPE_ENUM = exports.ALL_MATERIALIZED_PREP_TIME_TARGETS = exports.MATERIALIZED_PREP_TIME_TARGET_ENUM = void 0;
13
+ exports.MATERIALIZED_PREP_TIME_MAX_MINUTES = exports.ALL_MATERIALIZED_PREP_TIME_BUCKET_LABELS = exports.MATERIALIZED_PREP_TIME_BUCKETS = exports.ALL_MATERIALIZED_PREP_TIME_ANCHORS = exports.MATERIALIZED_PREP_TIME_ANCHOR_ENUM = exports.PREP_TIME_KEY_FILTERS = exports.MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS = exports.MATERIALIZED_PREP_TIME_ITEM_SCOPES = exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = exports.MATERIALIZED_DELIVERY_AREA_LIMIT = exports.MATERIALIZED_DELIVERY_RIDER_LIMIT = exports.MATERIALIZED_DELIVERY_DISTANCE_BUCKETS = exports.DELIVERY_KEY_FILTERS = exports.MATERIALIZED_DELIVERY_REPORT_SCOPES = exports.MATERIALIZED_CASH_SOURCE_LIMIT = exports.CASH_KEY_FILTERS = exports.MATERIALIZED_CASH_REPORT_SCOPES = exports.ALL_MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPES = exports.MATERIALIZED_REPORT_CREDIT_BILL_EVENT_TYPE_ENUM = exports.MATERIALIZED_CREDIT_SETTLEMENT_PAYMENT_TYPE = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY_PREFIX = exports.MATERIALIZED_DISCOUNT_SOURCE_KEY = exports.ALL_MATERIALIZED_DISCOUNT_RATE_KINDS = exports.MATERIALIZED_DISCOUNT_RATE_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SOURCE_CLASSES = exports.MATERIALIZED_DISCOUNT_SOURCE_CLASS_ENUM = exports.MATERIALIZED_DISCOUNT_PRICE_OVERRIDE_PREFIX = exports.MATERIALIZED_DISCOUNT_MANUAL_PREFIX = exports.MATERIALIZED_DISCOUNT_SPECIAL_DISCOUNT_ID = exports.MATERIALIZED_DISCOUNT_SOURCE_LIMIT = exports.ALL_MATERIALIZED_DISCOUNT_LEVELS = exports.MATERIALIZED_DISCOUNT_LEVEL_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_ENTRY_KINDS = exports.MATERIALIZED_DISCOUNT_ENTRY_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SUB_KINDS = exports.MATERIALIZED_DISCOUNT_SUB_KIND_ENUM = exports.ALL_MATERIALIZED_DISCOUNT_SLOTS = exports.MATERIALIZED_DISCOUNT_SLOT_ENUM = exports.DISCOUNTS_KEY_FILTERS = exports.MATERIALIZED_DISCOUNT_REPORT_SCOPES = exports.MATERIALIZED_DISCOUNT_ENTRY_PAGE_ALL = exports.SALES_OVERVIEW_KEY_FILTERS = exports.ALL_MATERIALIZED_REPORT_KEY_FILTERS = exports.MATERIALIZED_REPORT_KEY_FILTER_ENUM = exports.MATERIALIZED_CREDIT_BILLS_SCOPES = exports.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX = exports.ALL_MATERIALIZED_REPORT_WINDOW_KINDS = exports.MATERIALIZED_REPORT_WINDOW_KIND_ENUM = exports.ALL_MATERIALIZED_REPORT_SCOPES = exports.MATERIALIZED_REPORT_SCOPE_ENUM = void 0;
14
+ exports.ALL_PAYMENTS_COMPARISON_METRICS = exports.PAYMENTS_COMPARISON_METRIC_ENUM = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_SCHEMA_VERSION = exports.PAYMENTS_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_PAYMENTS_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_PAYMENTS_COMPARISON_REPORTS_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_SCHEMA_VERSION = exports.HOURLY_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_HOURLY_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_HOURLY_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_SALES_COMPARISON_METRICS = exports.SALES_COMPARISON_METRIC_ENUM = exports.ALL_SALES_COMPARISON_BASELINES = exports.SALES_COMPARISON_BASELINE_ENUM = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_SCHEMA_VERSION = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_SCHEMA_VERSION = exports.SALES_COMPARISON_KEY_FILTERS = exports.MATERIALIZED_SALES_COMPARISON_REPORT_SCOPES = exports.MATERIALIZED_TENANT_SALES_COMPARISON_ENTRIES_COLLECTION_NAME = exports.MATERIALIZED_TENANT_SALES_COMPARISON_REPORTS_COLLECTION_NAME = exports.ALL_MATERIALIZED_REPORT_TYPES = exports.MATERIALIZED_REPORT_TYPE_ENUM = exports.ALL_MATERIALIZED_PREP_TIME_TARGETS = exports.MATERIALIZED_PREP_TIME_TARGET_ENUM = exports.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = exports.MATERIALIZED_PREP_TIME_TOP_BUCKET = void 0;
15
15
  /**
16
16
  * Time-scope of a materialized report document. Every document covers exactly
17
17
  * one tenant × one scope context × one scope value (`scope_field`), and the
@@ -421,20 +421,40 @@ exports.MATERIALIZED_DELIVERY_AREA_LIMIT = 50;
421
421
  /* Prep time report (M2) */
422
422
  /* ======================================================================== */
423
423
  /**
424
- * Scopes materialized by `materialized_tenant_prep_time_reports`.
424
+ * Scopes materialized by `materialized_tenant_prep_time_reports` — the SUMMARY
425
+ * range (and the writer's COUNTER scopes).
425
426
  *
426
427
  * NO `localHour` (decision h2): the tracked population per hour is 2-3 items in
427
- * the dev stores, so an hourly prep time would be noise. Day + periods only,
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.
428
+ * the dev stores, so an hourly prep time would be noise.
429
+ *
430
+ * The Summary is CHEAP for a year because it reads these pre-aggregated counters,
431
+ * not item rows. The itemized reads are a DIFFERENT, month-capped list
432
+ * (`MATERIALIZED_PREP_TIME_ITEM_SCOPES`); the writer therefore materializes the
433
+ * full counter range but only month-capped ENTRY rows / flat period rows.
431
434
  */
432
435
  exports.MATERIALIZED_PREP_TIME_REPORT_SCOPES = [
433
436
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
434
437
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
435
438
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
436
439
  MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
440
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
441
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
442
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
443
+ ];
444
+ /**
445
+ * Scopes the ITEMIZED prep reads support — Items, Categories and the Details
446
+ * drill-down. Capped at `LOCAL_MONTH` so item rows can never grow into a
447
+ * quarter/year document; the service additionally enforces a 31-effective-day
448
+ * cap (see `MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS`).
449
+ */
450
+ exports.MATERIALIZED_PREP_TIME_ITEM_SCOPES = [
451
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
452
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
453
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
454
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
437
455
  ];
456
+ /** Max EFFECTIVE days (after weekday/date refinement) an item read may cover. */
457
+ exports.MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS = 31;
438
458
  /** Ordered key filters of the prep time report (`COMPLETED:POS_WALK-IN`). */
439
459
  exports.PREP_TIME_KEY_FILTERS = [
440
460
  MATERIALIZED_REPORT_KEY_FILTER_ENUM.ORDER_STATUS,
@@ -36,6 +36,7 @@ export interface IPrepTimeOrderSource {
36
36
  name?: string | null;
37
37
  items?: {
38
38
  _id?: string;
39
+ item_id?: string | null;
39
40
  name?: string | null;
40
41
  is_ready?: boolean;
41
42
  ready_minutes?: number | string | null;
@@ -76,8 +77,15 @@ export declare function resolveMaterializedPrepTimeTarget(order: Pick<IPrepTimeO
76
77
  target_at: Date | null;
77
78
  target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM;
78
79
  };
79
- /** Stable identity of a row inside its order - part of the page cursor. */
80
- export declare const buildMaterializedPrepTimeEntryKey: (itemId: string | null) => string;
80
+ /**
81
+ * Stable identity of ONE served item row inside its order - part of the page
82
+ * cursor and the flat projection identity.
83
+ *
84
+ * The catalogue item id is the GROUPING key; the order-line id keeps two lines
85
+ * of the same catalogue item distinct. A line is appended only when it differs
86
+ * from the catalogue id, so the common (and legacy) one-line shape is stable.
87
+ */
88
+ export declare const buildMaterializedPrepTimeEntryKey: (itemId: string | null, lineId?: string | null) => string;
81
89
  export interface IAccumulateOrderPrepTimeResult {
82
90
  counters: IMaterializedPrepTimeCounters;
83
91
  entries: IMaterializedPrepTimeEntry[];
@@ -104,8 +104,21 @@ function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes) {
104
104
  }
105
105
  return { target_at: null, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
106
106
  }
107
- /** Stable identity of a row inside its order - part of the page cursor. */
108
- const buildMaterializedPrepTimeEntryKey = (itemId) => 'item:' + String(itemId ?? 'unknown');
107
+ /**
108
+ * Stable identity of ONE served item row inside its order - part of the page
109
+ * cursor and the flat projection identity.
110
+ *
111
+ * The catalogue item id is the GROUPING key; the order-line id keeps two lines
112
+ * of the same catalogue item distinct. A line is appended only when it differs
113
+ * from the catalogue id, so the common (and legacy) one-line shape is stable.
114
+ */
115
+ const buildMaterializedPrepTimeEntryKey = (itemId, lineId) => {
116
+ const parts = [String(itemId ?? 'unknown')];
117
+ if (lineId != null && String(lineId) !== '' && String(lineId) !== String(itemId ?? '')) {
118
+ parts.push(String(lineId));
119
+ }
120
+ return 'item:' + parts.join(':');
121
+ };
109
122
  exports.buildMaterializedPrepTimeEntryKey = buildMaterializedPrepTimeEntryKey;
110
123
  /**
111
124
  * Accumulates ONE order's items into the prep counters + drill-down rows.
@@ -200,12 +213,19 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
200
213
  else {
201
214
  counters.promise.no_target_count += 1;
202
215
  }
203
- const itemId = item?._id != null ? String(item._id) : null;
216
+ // CATALOGUE item id: the grouping identity the Items tab reads. The
217
+ // order-line id is a DIFFERENT identity and is preserved as line_id, so
218
+ // two lines of one menu item remain two served events.
219
+ const lineId = item?._id != null ? String(item._id) : null;
220
+ const catalogueItemId = item?.item_id != null && String(item.item_id) !== ''
221
+ ? String(item.item_id)
222
+ : lineId;
204
223
  const row = {
205
- entry_key: (0, exports.buildMaterializedPrepTimeEntryKey)(itemId),
224
+ entry_key: (0, exports.buildMaterializedPrepTimeEntryKey)(catalogueItemId, lineId),
206
225
  order_id: orderId,
207
226
  order_number: order.order_number ?? null,
208
- item_id: itemId,
227
+ item_id: catalogueItemId,
228
+ line_id: lineId,
209
229
  item_name: item?.name != null ? String(item.name) : null,
210
230
  category_name: category?.name != null ? String(category.name) : null,
211
231
  anchor,
@@ -223,10 +243,11 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
223
243
  created_at: createdAt,
224
244
  local_hour: context.local_hour_label,
225
245
  };
226
- // Only items with a prep signal become rows: an untouched item has nothing
227
- // to inspect, and the drill-down exists to explain the numbers.
228
- if (minutes != null || prepStartedValid)
229
- entries.push(row);
246
+ // EVERY served item becomes a row - including an item with no prep
247
+ // signal. Coverage uses ALL served items as its denominator; a no-signal
248
+ // row is an UNMEASURED row with null duration and is visible in the
249
+ // Unmeasured view.
250
+ entries.push(row);
230
251
  }
231
252
  }
232
253
  if (tracked > 0)