@managesome/eposmatic-toolkit 0.4.34 → 0.4.35

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.
@@ -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,
@@ -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) => ({
@@ -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).
@@ -60,7 +60,7 @@ export const MaterializedTenantPrepTimeEntriesSchema = new Schema({
60
60
  scope_context: {
61
61
  type: String,
62
62
  required: true,
63
- enum: MATERIALIZED_PREP_TIME_REPORT_SCOPES,
63
+ enum: MATERIALIZED_PREP_TIME_ITEM_SCOPES,
64
64
  },
65
65
  scope_field: { type: String, required: true },
66
66
  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,
@@ -70,15 +70,22 @@ export declare function foldMaterializedPrepTimePeriodRows({ periodScopeField, p
70
70
  }>;
71
71
  /** The period scope contexts (everything except the day scope). */
72
72
  export declare const MATERIALIZED_PREP_TIME_PERIOD_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
73
+ /** Period scopes that carry ENTRY rows / flat rows (month-capped). */
74
+ export declare const MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
73
75
  /**
74
- * Every `localDate` label whose DAY entry document can contribute to a period
75
- * the closing day rolls into (week / ISO week / month).
76
- *
77
- * The worker uses this to fetch exactly the sibling day entries the period
78
- * fold needs — never a full-period entry document and never a year-wide scan.
79
- * Returns `null` (never throws) for a malformed date.
76
+ * Every `localDate` label whose DAY entry document can contribute to a
77
+ * month-capped period (week / ISO week / month). The worker uses this to fetch
78
+ * exactly the sibling day entries the entry fold needs — never a full-period
79
+ * entry document and never a year-wide scan.
80
80
  */
81
81
  export declare function getMaterializedPrepTimePeriodDayScopeFields(localDate: string): string[] | null;
82
+ /**
83
+ * Every `localDate` label whose DAY counter document can contribute to ANY
84
+ * report period the closing day rolls into, including quarter / semester /
85
+ * year. Used by the worker's SUMMARY counter fold only; entry rows stay
86
+ * month-capped.
87
+ */
88
+ export declare function getMaterializedPrepTimeReportPeriodDayScopeFields(localDate: string): string[] | null;
82
89
  /** True when a stored prep counter document equals the incoming one (skip write). */
83
90
  export declare function needsMaterializedPrepTimeReportWrite(existing: IMaterializedTenantPrepTimeReport | null | undefined, incoming: IMaterializedTenantPrepTimeReport | null | undefined): boolean;
84
91
  /** One planned write: the document plus its shared-history iteration row. */
@@ -3,12 +3,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES = exports.isMaterializedPrepTimeDayScope = exports.mergeMaterializedPrepTimeEntrySections = void 0;
6
+ exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES = exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES = exports.isMaterializedPrepTimeDayScope = exports.mergeMaterializedPrepTimeEntrySections = void 0;
7
7
  exports.updateMaterializedPrepTimeEntries = updateMaterializedPrepTimeEntries;
8
8
  exports.needsMaterializedPrepTimeEntriesWrite = needsMaterializedPrepTimeEntriesWrite;
9
9
  exports.foldMaterializedPrepTimePeriodCounters = foldMaterializedPrepTimePeriodCounters;
10
10
  exports.foldMaterializedPrepTimePeriodRows = foldMaterializedPrepTimePeriodRows;
11
11
  exports.getMaterializedPrepTimePeriodDayScopeFields = getMaterializedPrepTimePeriodDayScopeFields;
12
+ exports.getMaterializedPrepTimeReportPeriodDayScopeFields = getMaterializedPrepTimeReportPeriodDayScopeFields;
12
13
  exports.needsMaterializedPrepTimeReportWrite = needsMaterializedPrepTimeReportWrite;
13
14
  exports.buildTenantPrepTimeCloseDayPlan = buildTenantPrepTimeCloseDayPlan;
14
15
  const mongoose_1 = __importDefault(require("mongoose"));
@@ -169,66 +170,116 @@ function foldMaterializedPrepTimePeriodRows({ periodScopeField, periodScope, day
169
170
  }
170
171
  /** The period scope contexts (everything except the day scope). */
171
172
  exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES.filter((scope) => !(0, exports.isMaterializedPrepTimeDayScope)(String(scope)));
173
+ /** Period scopes that carry ENTRY rows / flat rows (month-capped). */
174
+ exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES = MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES.filter((scope) => !(0, exports.isMaterializedPrepTimeDayScope)(String(scope)));
172
175
  /* ------------------------------------------------------------------------ */
173
176
  /* Period sibling-day enumeration */
174
177
  /* ------------------------------------------------------------------------ */
175
178
  const pad2 = (value) => String(value).padStart(2, '0');
176
179
  const toLocalDateKey = (date) => `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
177
180
  const addUtcDays = (date, amount) => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + amount));
178
- const addMonthDays = (year, month, days) => {
181
+ const addMonthDays = (year, month, count, days) => {
179
182
  if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12)
180
183
  return false;
181
- const last = new Date(Date.UTC(year, month, 0)).getUTCDate();
182
- for (let day = 1; day <= last; day += 1) {
183
- days.add(`${year}-${pad2(month)}-${pad2(day)}`);
184
+ for (let offset = 0; offset < count; offset += 1) {
185
+ const date = new Date(Date.UTC(year, month - 1 + offset, 1));
186
+ const monthYear = date.getUTCFullYear();
187
+ const monthNumber = date.getUTCMonth() + 1;
188
+ const last = new Date(Date.UTC(monthYear, monthNumber, 0)).getUTCDate();
189
+ for (let day = 1; day <= last; day += 1) {
190
+ days.add(`${monthYear}-${pad2(monthNumber)}-${pad2(day)}`);
191
+ }
184
192
  }
185
193
  return true;
186
194
  };
187
- /**
188
- * Every `localDate` label whose DAY entry document can contribute to a period
189
- * the closing day rolls into (week / ISO week / month).
190
- *
191
- * The worker uses this to fetch exactly the sibling day entries the period
192
- * fold needs — never a full-period entry document and never a year-wide scan.
193
- * Returns `null` (never throws) for a malformed date.
194
- */
195
- function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
195
+ const addPeriodDays = (scope, scopeField, days) => {
196
+ switch (scope) {
197
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK: {
198
+ const parts = (0, scope_helpers_1.parseMaterializedLocalDate)(scopeField);
199
+ if (parts == null)
200
+ return false;
201
+ const start = new Date(Date.UTC(parts.year, parts.month - 1, parts.day));
202
+ if (start.getUTCDay() !== 0)
203
+ return false;
204
+ for (let offset = 0; offset < 7; offset += 1)
205
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
206
+ return true;
207
+ }
208
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR: {
209
+ const match = /^(\d{4})-W(\d{2})$/.exec(scopeField);
210
+ if (match == null)
211
+ return false;
212
+ const weekYear = Number(match[1]);
213
+ const week = Number(match[2]);
214
+ if (!Number.isInteger(week) || week < 1 || week > 53)
215
+ return false;
216
+ const jan4 = new Date(Date.UTC(weekYear, 0, 4));
217
+ const isoWeekday = jan4.getUTCDay() || 7;
218
+ const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
219
+ const start = addUtcDays(weekOneMonday, (week - 1) * 7);
220
+ for (let offset = 0; offset < 7; offset += 1)
221
+ days.add(toLocalDateKey(addUtcDays(start, offset)));
222
+ return true;
223
+ }
224
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH: {
225
+ const match = /^(\d{4})-(\d{2})$/.exec(scopeField);
226
+ if (match == null)
227
+ return false;
228
+ return addMonthDays(Number(match[1]), Number(match[2]), 1, days);
229
+ }
230
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER: {
231
+ const match = /^(\d{4})-Q([1-4])$/.exec(scopeField);
232
+ if (match == null)
233
+ return false;
234
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 3 + 1, 3, days);
235
+ }
236
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER: {
237
+ const match = /^(\d{4})-S([12])$/.exec(scopeField);
238
+ if (match == null)
239
+ return false;
240
+ return addMonthDays(Number(match[1]), (Number(match[2]) - 1) * 6 + 1, 6, days);
241
+ }
242
+ case MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR: {
243
+ const match = /^(\d{4})$/.exec(scopeField);
244
+ if (match == null)
245
+ return false;
246
+ return addMonthDays(Number(match[1]), 1, 12, days);
247
+ }
248
+ default:
249
+ return false;
250
+ }
251
+ };
252
+ const enumeratePeriodDays = (localDate, scopes) => {
196
253
  const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
197
254
  if (periodFields == null)
198
255
  return null;
199
256
  const days = new Set([localDate]);
200
- const weekField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK];
201
- const weekParts = typeof weekField === 'string' ? (0, scope_helpers_1.parseMaterializedLocalDate)(weekField) : null;
202
- if (weekParts == null)
203
- return null;
204
- const weekStart = new Date(Date.UTC(weekParts.year, weekParts.month - 1, weekParts.day));
205
- if (weekStart.getUTCDay() !== 0)
206
- return null;
207
- for (let offset = 0; offset < 7; offset += 1) {
208
- days.add(toLocalDateKey(addUtcDays(weekStart, offset)));
209
- }
210
- const isoWeekField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR];
211
- const isoMatch = typeof isoWeekField === 'string' ? /^(\d{4})-W(\d{2})$/.exec(isoWeekField) : null;
212
- if (isoMatch == null)
213
- return null;
214
- const weekYear = Number(isoMatch[1]);
215
- const week = Number(isoMatch[2]);
216
- if (!Number.isInteger(week) || week < 1 || week > 53)
217
- return null;
218
- const jan4 = new Date(Date.UTC(weekYear, 0, 4));
219
- const isoWeekday = jan4.getUTCDay() || 7;
220
- const weekOneMonday = addUtcDays(jan4, 1 - isoWeekday);
221
- const isoStart = addUtcDays(weekOneMonday, (week - 1) * 7);
222
- for (let offset = 0; offset < 7; offset += 1) {
223
- days.add(toLocalDateKey(addUtcDays(isoStart, offset)));
257
+ for (const scope of scopes) {
258
+ const scopeField = periodFields[scope];
259
+ if (typeof scopeField !== 'string' || scopeField.length === 0)
260
+ return null;
261
+ if (!addPeriodDays(scope, scopeField, days))
262
+ return null;
224
263
  }
225
- const monthField = periodFields[MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH];
226
- const monthMatch = typeof monthField === 'string' ? /^(\d{4})-(\d{2})$/.exec(monthField) : null;
227
- if (monthMatch == null)
228
- return null;
229
- if (!addMonthDays(Number(monthMatch[1]), Number(monthMatch[2]), days))
230
- return null;
231
264
  return [...days].sort();
265
+ };
266
+ /**
267
+ * Every `localDate` label whose DAY entry document can contribute to a
268
+ * month-capped period (week / ISO week / month). The worker uses this to fetch
269
+ * exactly the sibling day entries the entry fold needs — never a full-period
270
+ * entry document and never a year-wide scan.
271
+ */
272
+ function getMaterializedPrepTimePeriodDayScopeFields(localDate) {
273
+ return enumeratePeriodDays(localDate, exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
274
+ }
275
+ /**
276
+ * Every `localDate` label whose DAY counter document can contribute to ANY
277
+ * report period the closing day rolls into, including quarter / semester /
278
+ * year. Used by the worker's SUMMARY counter fold only; entry rows stay
279
+ * month-capped.
280
+ */
281
+ function getMaterializedPrepTimeReportPeriodDayScopeFields(localDate) {
282
+ return enumeratePeriodDays(localDate, exports.MATERIALIZED_PREP_TIME_PERIOD_SCOPES);
232
283
  }
233
284
  /** True when a stored prep counter document equals the incoming one (skip write). */
234
285
  function needsMaterializedPrepTimeReportWrite(existing, incoming) {
@@ -485,7 +536,11 @@ function buildTenantPrepTimeCloseDayPlan(input) {
485
536
  continue;
486
537
  staleEntryDocuments.push(doc);
487
538
  }
539
+ const itemPeriodScopes = new Set(exports.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES);
488
540
  for (const { scope, field } of touchedPeriods.values()) {
541
+ // ENTRY documents are month-capped; quarter/semester/year are COUNTER only.
542
+ if (!itemPeriodScopes.has(String(scope)))
543
+ continue;
489
544
  const sections = foldMaterializedPrepTimePeriodRows({
490
545
  periodScope: scope,
491
546
  periodScopeField: field,
@@ -93,6 +93,7 @@ function compileTenantPrepTimeReports(input) {
93
93
  return null;
94
94
  const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(localDate);
95
95
  const at = computedAt ?? new Date();
96
+ const itemScopes = new Set(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES);
96
97
  const byScope = new Map();
97
98
  const scopeContextOf = new Map();
98
99
  const bucketFor = (scope, scopeField, key) => {
@@ -145,7 +146,10 @@ function compileTenantPrepTimeReports(input) {
145
146
  continue;
146
147
  const bucket = bucketFor(scope, scopeField, key);
147
148
  mergeMaterializedPrepTimeCounters(bucket.counters, result.counters);
148
- bucket.rows.push(...result.entries);
149
+ // ENTRY rows / flat rows are month-capped; the Summary counters go to the
150
+ // full report range. Never accumulate quarter/semester/year item rows.
151
+ if (itemScopes.has(scope))
152
+ bucket.rows.push(...result.entries);
149
153
  foldWatermark(bucket, watermark);
150
154
  }
151
155
  }
@@ -186,7 +190,7 @@ function compileTenantPrepTimeReports(input) {
186
190
  createdAt: at,
187
191
  updatedAt: at,
188
192
  });
189
- if (Object.keys(entrySections).length > 0) {
193
+ if (itemScopes.has(scopeContext) && Object.keys(entrySections).length > 0) {
190
194
  entries.push({
191
195
  _id: new mongoose_1.default.Types.ObjectId().toHexString(),
192
196
  tenant_id: tenantId,
@@ -97,6 +97,14 @@ export declare function applyMaterializedPrepTimeReadFilters(rows: IPrepTimeRead
97
97
  * can still state "1,192 of 1,552 served items have their own prep clock".
98
98
  */
99
99
  export declare const withoutMaterializedPrepTimeAnchorFilter: (filters?: IPrepTimeReadFilters | null) => IPrepTimeReadFilters;
100
+ /**
101
+ * Coverage from COUNTS (the server-side Series aggregation groups in Mongo and
102
+ * therefore has no raw rows). Same math as `buildMaterializedPrepTimeCoverage`.
103
+ */
104
+ export declare function buildMaterializedPrepTimeCoverageFromCounts(input: {
105
+ served_count: number;
106
+ measured_count: number;
107
+ }): IPrepTimeCoverage;
100
108
  /** Coverage of the supplied population (measured / served, one decimal). */
101
109
  export declare function buildMaterializedPrepTimeCoverage(rows: IPrepTimeReadRow[] | null | undefined): IPrepTimeCoverage;
102
110
  /**
@@ -111,6 +119,17 @@ export declare function getMaterializedPrepTimePercentile(values: number[] | nul
111
119
  export declare function getMaterializedPrepTimeMedian(values: number[] | null | undefined): number | null;
112
120
  /** EXACT p90 (interpolated). */
113
121
  export declare function getMaterializedPrepTimeP90(values: number[] | null | undefined): number | null;
122
+ /** The three duration statistics for ONE population (avg / exact median / exact p90). */
123
+ export interface IPrepTimeDurationSummary {
124
+ avg_minutes: number | null;
125
+ median_minutes: number | null;
126
+ p90_minutes: number | null;
127
+ }
128
+ /**
129
+ * Duration statistics for a list of VALID durations (invalid values are
130
+ * filtered defensively). `null` for an empty population — never 0.
131
+ */
132
+ export declare function summarizeMaterializedPrepTimeDurations(durations: number[] | null | undefined): IPrepTimeDurationSummary;
114
133
  /**
115
134
  * Groups filtered rows by `item_id` (never by name). Counts are per ROW, so an
116
135
  * item sold on many orders is never collapsed into one sale.
@@ -8,10 +8,12 @@ exports.isMaterializedPrepTimeDurationCountable = isMaterializedPrepTimeDuration
8
8
  exports.filterMaterializedPrepTimeRowsByAnchor = filterMaterializedPrepTimeRowsByAnchor;
9
9
  exports.matchesMaterializedPrepTimeReadFilters = matchesMaterializedPrepTimeReadFilters;
10
10
  exports.applyMaterializedPrepTimeReadFilters = applyMaterializedPrepTimeReadFilters;
11
+ exports.buildMaterializedPrepTimeCoverageFromCounts = buildMaterializedPrepTimeCoverageFromCounts;
11
12
  exports.buildMaterializedPrepTimeCoverage = buildMaterializedPrepTimeCoverage;
12
13
  exports.getMaterializedPrepTimePercentile = getMaterializedPrepTimePercentile;
13
14
  exports.getMaterializedPrepTimeMedian = getMaterializedPrepTimeMedian;
14
15
  exports.getMaterializedPrepTimeP90 = getMaterializedPrepTimeP90;
16
+ exports.summarizeMaterializedPrepTimeDurations = summarizeMaterializedPrepTimeDurations;
15
17
  exports.groupMaterializedPrepTimeItemRows = groupMaterializedPrepTimeItemRows;
16
18
  exports.isMaterializedPrepTimeItemSort = isMaterializedPrepTimeItemSort;
17
19
  exports.getMaterializedPrepTimeItemSortValue = getMaterializedPrepTimeItemSortValue;
@@ -258,11 +260,23 @@ const addTotals = (totals, row) => {
258
260
  else
259
261
  totals.unmeasured += 1;
260
262
  };
261
- const coverageFromTotals = (totals) => ({
263
+ /**
264
+ * Coverage from COUNTS (the server-side Series aggregation groups in Mongo and
265
+ * therefore has no raw rows). Same math as `buildMaterializedPrepTimeCoverage`.
266
+ */
267
+ function buildMaterializedPrepTimeCoverageFromCounts(input) {
268
+ const served = Math.max(0, Math.floor(Number(input.served_count) || 0));
269
+ const measured = Math.max(0, Math.floor(Number(input.measured_count) || 0));
270
+ return {
271
+ served_count: served,
272
+ measured_count: measured,
273
+ unmeasured_count: Math.max(0, served - measured),
274
+ coverage_percent: served > 0 ? round1((measured / served) * 100) : 0,
275
+ };
276
+ }
277
+ const coverageFromTotals = (totals) => buildMaterializedPrepTimeCoverageFromCounts({
262
278
  served_count: totals.served,
263
279
  measured_count: totals.measured,
264
- unmeasured_count: totals.unmeasured,
265
- coverage_percent: totals.served > 0 ? round1((totals.measured / totals.served) * 100) : 0,
266
280
  });
267
281
  /** Coverage of the supplied population (measured / served, one decimal). */
268
282
  function buildMaterializedPrepTimeCoverage(rows) {
@@ -327,15 +341,28 @@ const addMetrics = (metrics, row) => {
327
341
  metrics.late += 1;
328
342
  }
329
343
  };
344
+ /**
345
+ * Duration statistics for a list of VALID durations (invalid values are
346
+ * filtered defensively). `null` for an empty population — never 0.
347
+ */
348
+ function summarizeMaterializedPrepTimeDurations(durations) {
349
+ const valid = (Array.isArray(durations) ? durations : []).filter(isMaterializedPrepTimeDurationCountable);
350
+ if (valid.length === 0) {
351
+ return { avg_minutes: null, median_minutes: null, p90_minutes: null };
352
+ }
353
+ const sum = valid.reduce((total, value) => total + value, 0);
354
+ return {
355
+ avg_minutes: round1(sum / valid.length),
356
+ median_minutes: getMaterializedPrepTimeMedian(valid),
357
+ p90_minutes: getMaterializedPrepTimeP90(valid),
358
+ };
359
+ }
330
360
  const durationStats = (durations) => {
331
- const count = durations.length;
332
- if (count === 0)
333
- return { avg: null, median: null, p90: null };
334
- const sum = durations.reduce((total, value) => total + value, 0);
361
+ const summary = summarizeMaterializedPrepTimeDurations(durations);
335
362
  return {
336
- avg: round1(sum / count),
337
- median: getMaterializedPrepTimeMedian(durations),
338
- p90: getMaterializedPrepTimeP90(durations),
363
+ avg: summary.avg_minutes,
364
+ median: summary.median_minutes,
365
+ p90: summary.p90_minutes,
339
366
  };
340
367
  };
341
368
  const freshItemGroup = (itemId) => ({
@@ -63,7 +63,7 @@ exports.MaterializedTenantPrepTimeEntriesSchema = new mongoose_1.Schema({
63
63
  scope_context: {
64
64
  type: String,
65
65
  required: true,
66
- enum: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES,
66
+ enum: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES,
67
67
  },
68
68
  scope_field: { type: String, required: true },
69
69
  day_index: {
@@ -65,12 +65,31 @@ 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 month-capped accumulating period scopes', () => {
68
+ it('exposes the full report periods and the month-capped item periods', () => {
69
69
  expect(materialized_prep_time_close_day_helpers_1.MATERIALIZED_PREP_TIME_PERIOD_SCOPES.sort()).toEqual([
70
70
  'localMonth',
71
+ 'localQuarter',
72
+ 'localSemester',
71
73
  'localWeek',
72
74
  'localWeekOfYear',
75
+ 'localYear',
73
76
  ]);
77
+ expect(materialized_prep_time_close_day_helpers_1.MATERIALIZED_PREP_TIME_ITEM_PERIOD_SCOPES.sort()).toEqual([
78
+ 'localMonth',
79
+ 'localWeek',
80
+ 'localWeekOfYear',
81
+ ]);
82
+ });
83
+ it('enumerates the FULL report sibling days (through year) separately from the item days', () => {
84
+ // Item period days stay month-bounded (Sep 1..30 for this Monday).
85
+ const itemDays = (0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimePeriodDayScopeFields)('2026-09-14');
86
+ expect(itemDays).toHaveLength(30);
87
+ // Report period days include the whole year (the Summary year counter fold).
88
+ const reportDays = (0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimeReportPeriodDayScopeFields)('2026-09-14');
89
+ expect(reportDays).toHaveLength(365);
90
+ expect(reportDays[0]).toBe('2026-01-01');
91
+ expect(reportDays[reportDays.length - 1]).toBe('2026-12-31');
92
+ expect(reportDays).toEqual(expect.arrayContaining(itemDays));
74
93
  });
75
94
  it('enumerates the EXACT week / ISO-week / month sibling days', () => {
76
95
  const days = (0, materialized_prep_time_close_day_helpers_1.getMaterializedPrepTimePeriodDayScopeFields)('2026-09-14');
@@ -110,11 +110,20 @@ describe('mergeMaterializedPrepTimeCounters', () => {
110
110
  });
111
111
  });
112
112
  describe('compileTenantPrepTimeReports', () => {
113
- it('emits the approved scope set with NO hour scope', () => {
113
+ it('emits the FULL report scope set with NO hour scope', () => {
114
114
  const result = compile([order()]);
115
115
  const scopes = result.reports.map((doc) => doc.scope_context);
116
116
  expect(scopes.sort()).toEqual([...MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_REPORT_SCOPES].sort());
117
117
  expect(scopes).not.toContain('localHour');
118
+ expect(scopes).toEqual(expect.arrayContaining(['localQuarter', 'localSemester', 'localYear']));
119
+ });
120
+ it('emits ENTRY documents only for the month-capped item scopes', () => {
121
+ const result = compile([order()]);
122
+ const entryScopes = [...new Set(result.entries.map((doc) => doc.scope_context))].sort();
123
+ expect(entryScopes).toEqual([...MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES].sort());
124
+ expect(entryScopes).not.toContain('localQuarter');
125
+ expect(entryScopes).not.toContain('localSemester');
126
+ expect(entryScopes).not.toContain('localYear');
118
127
  });
119
128
  it('sets day_index ONLY on the date document', () => {
120
129
  const result = compile([order()]);
@@ -10,19 +10,30 @@ 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 month-capped day + periods with NO hour scope (decision h2)', () => {
13
+ it('report scopes are the FULL Summary range 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,
19
22
  ]);
20
23
  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
+ });
25
+ it('item scopes are the month-capped read range', () => {
26
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES).toEqual([
27
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
28
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
29
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
30
+ MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
31
+ ]);
32
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER);
33
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER);
34
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR);
35
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_SCOPES).not.toContain(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR);
36
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ITEM_MAX_READ_DAYS).toBe(31);
26
37
  });
27
38
  it('buckets TILE the range with no gap and no overlap', () => {
28
39
  // Contiguous: each bucket starts exactly one minute after the previous ends.
@@ -76,13 +76,30 @@ 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',
79
81
  'localWeek',
80
82
  'localWeekOfYear',
83
+ 'localYear',
81
84
  ]);
82
85
  for (const write of periodWrites) {
83
86
  expect(write.report.prep_time_counters[KEY].coverage.item_count).toBe(3);
84
87
  }
85
88
  });
89
+ it('FOLDS ENTRY rows only for the month-capped item periods', () => {
90
+ const plan = build({
91
+ reports: [report('localDate', '2026-09-14', { coverage: { item_count: 1 } })],
92
+ entries: [entry('localDate', '2026-09-14', { prep_time_entries: { [KEY]: { rows: [entryRowFixture()] } } })],
93
+ });
94
+ const periodEntryScopes = plan.entryWrites
95
+ .filter((write) => write.report.scope_context !== 'localDate')
96
+ .map((write) => write.report.scope_context)
97
+ .sort();
98
+ expect(periodEntryScopes).toEqual(['localMonth', 'localWeek', 'localWeekOfYear']);
99
+ expect(periodEntryScopes).not.toContain('localQuarter');
100
+ expect(periodEntryScopes).not.toContain('localSemester');
101
+ expect(periodEntryScopes).not.toContain('localYear');
102
+ });
86
103
  it('ACCUMULATES two closed days into the same month', () => {
87
104
  // Day 13 is already stored; day 14 is being closed now.
88
105
  const storedDay13 = report('localDate', '2026-09-13', { coverage: { item_count: 2 } });
@@ -172,6 +189,27 @@ describe('buildTenantPrepTimeCloseDayPlan', () => {
172
189
  });
173
190
  });
174
191
  /** A day/period entry document (rows are irrelevant to the iteration contract). */
192
+ const entryRowFixture = () => ({
193
+ entry_key: 'item:1',
194
+ order_id: 'order-1',
195
+ item_id: '1',
196
+ item_name: 'Burger',
197
+ category_name: 'Mains',
198
+ anchor: 'MEASURED',
199
+ duration_minutes: 9,
200
+ prep_started_at: new Date('2026-09-14T10:00:00.000Z'),
201
+ ready_at: new Date('2026-09-14T10:09:00.000Z'),
202
+ is_ready: true,
203
+ target_at: null,
204
+ target_source: null,
205
+ delta_minutes: null,
206
+ staff_id: null,
207
+ staff_name: null,
208
+ order_status: 'COMPLETED',
209
+ platform: 'POS_WALK-IN',
210
+ created_at: new Date('2026-09-14T09:55:00.000Z'),
211
+ local_hour: '2026-09-14 10',
212
+ });
175
213
  const entry = (scope, field, over = {}) => ({
176
214
  _id: scope + '|' + field,
177
215
  tenant_id: 'tenant-a',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.34",
3
+ "version": "0.4.35",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",