@managesome/eposmatic-toolkit 0.4.43 → 0.4.45

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.
@@ -518,19 +518,32 @@ export const MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = 0;
518
518
  /**
519
519
  * WHERE an item's on-time target came from (decision e2).
520
520
  *
521
- * Promise-only grading would leave 63-97% of items ungraded (measured: only
522
- * 2.7% / 36.2% of orders carry an explicit estimate), so an item with no promise
523
- * is graded against the TENANT DEFAULT - the documented
524
- * `getDeliveryExpectedTime` fallback chain. The baseline is labelled per row so
525
- * a reader can always tell the two apart.
521
+ * The M2 target hierarchy is anchored to the PUNCH instant (`order.createdAt`):
522
+ *
523
+ * DINE-IN: dinein_details.prep_minutes (MINUTES; 0 = immediate)
524
+ * -> tenant.default_prep_minutes (MINUTES; > 0)
525
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
526
+ * -> NONE
527
+ * OTHER: tenant.default_prep_minutes (MINUTES; > 0)
528
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
529
+ * -> NONE
530
+ *
531
+ * Explicit `estimated_takeaway_time` / `estimated_delivery_time` are NOT part
532
+ * of this hierarchy. PROMISE is retained only so historical documents remain
533
+ * readable; the current writer never produces it. The baseline is labelled per
534
+ * row so a reader can always tell which rule produced the target.
526
535
  */
527
536
  export var MATERIALIZED_PREP_TIME_TARGET_ENUM;
528
537
  (function (MATERIALIZED_PREP_TIME_TARGET_ENUM) {
529
- /** The order carried an explicit estimate. */
538
+ /** Legacy-only: an explicit estimate written by an older implementation. */
530
539
  MATERIALIZED_PREP_TIME_TARGET_ENUM["PROMISE"] = "PROMISE";
531
- /** The order was ASAP and is graded against the tenant default. */
540
+ /** Dine-in target from `dinein_details.prep_minutes` (MINUTES). */
541
+ MATERIALIZED_PREP_TIME_TARGET_ENUM["DINE_IN_PREP"] = "DINE_IN_PREP";
542
+ /** Tenant `default_prep_minutes` (MINUTES), anchored to the punch instant. */
532
543
  MATERIALIZED_PREP_TIME_TARGET_ENUM["TENANT_DEFAULT"] = "TENANT_DEFAULT";
533
- /** Neither exists - the row cannot be graded. */
544
+ /** Tenant `takeaway_time` (MILLISECONDS -> whole minutes), from the punch instant. */
545
+ MATERIALIZED_PREP_TIME_TARGET_ENUM["TAKEAWAY_TIME"] = "TAKEAWAY_TIME";
546
+ /** No source in the hierarchy - the row cannot be graded. */
534
547
  MATERIALIZED_PREP_TIME_TARGET_ENUM["NONE"] = "NONE";
535
548
  })(MATERIALIZED_PREP_TIME_TARGET_ENUM || (MATERIALIZED_PREP_TIME_TARGET_ENUM = {}));
536
549
  export const ALL_MATERIALIZED_PREP_TIME_TARGETS = Object.values(MATERIALIZED_PREP_TIME_TARGET_ENUM);
@@ -18,6 +18,66 @@ const toMinutes = (value) => {
18
18
  }
19
19
  return null;
20
20
  };
21
+ /**
22
+ * Finite numeric value or null. Used by the TARGET resolver, where a source
23
+ * value is a setting/field value (not a stored duration), so it must not be
24
+ * rounded before the arithmetic.
25
+ */
26
+ const toFiniteNumber = (value) => {
27
+ if (typeof value === 'number')
28
+ return Number.isFinite(value) ? value : null;
29
+ if (typeof value === 'string' && value.trim() !== '') {
30
+ const parsed = Number(value);
31
+ return Number.isFinite(parsed) ? parsed : null;
32
+ }
33
+ return null;
34
+ };
35
+ /**
36
+ * A TARGET duration in MINUTES, or null when the value is absent / invalid.
37
+ *
38
+ * prep_minutes and default_prep_minutes are ALREADY minutes, so they are used
39
+ * as-is. A negative / non-finite value is absent and falls through the
40
+ * hierarchy. prep_minutes === 0 is an explicit immediate target (0 minutes),
41
+ * while a tenant default of 0 means "not configured".
42
+ */
43
+ const toTargetMinutes = (value, allowZero) => {
44
+ const minutes = toFiniteNumber(value);
45
+ if (minutes == null || minutes < 0)
46
+ return null;
47
+ if (!allowZero && minutes <= 0)
48
+ return null;
49
+ return minutes;
50
+ };
51
+ /**
52
+ * Tenant takeaway_time is MILLISECONDS. Convert it to WHOLE minutes
53
+ * (Math.round), then use those minutes as the target duration. A value that
54
+ * rounds to 0 is treated as NO target.
55
+ *
56
+ * This conversion is load-bearing: adding the raw milliseconds to createdAt
57
+ * would make a 30-minute setting a 30-SECOND target.
58
+ */
59
+ const toTakeawayMinutes = (value) => {
60
+ const milliseconds = toFiniteNumber(value);
61
+ if (milliseconds == null || milliseconds <= 0)
62
+ return null;
63
+ const minutes = Math.round(milliseconds / 60000);
64
+ return minutes > 0 ? minutes : null;
65
+ };
66
+ /**
67
+ * Dine-in is identified by the order's PLATFORM / ORDER SOURCE, never by the
68
+ * mere presence of dinein_details (a non-dine-in order may still carry the
69
+ * detail block, and a dine-in order may omit prep_minutes). Real values are
70
+ * POS_DINE-IN / WEB_DINE-IN / APP_DINE-IN; the check is deliberately
71
+ * case-insensitive and substring-based so a new source prefix cannot silently
72
+ * lose the dine-in target.
73
+ */
74
+ const isDineInOrder = (order) => {
75
+ for (const source of [order?.platform, order?.order_from]) {
76
+ if (typeof source === 'string' && source.toUpperCase().includes('DINE'))
77
+ return true;
78
+ }
79
+ return false;
80
+ };
21
81
  /**
22
82
  * Histogram bucket label of a duration. Total by construction: the top bucket is
23
83
  * open-ended, so every finite duration lands in exactly one bucket.
@@ -72,28 +132,62 @@ export function freshMaterializedPrepTimeCounters() {
72
132
  late_items: { count: 0, worst_delta: 0 },
73
133
  };
74
134
  }
75
- /** The on-time target of one order, and where it came from (decision e2). */
76
- export function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes) {
77
- // An explicit estimate is an ABSOLUTE timestamp on the order's detail block.
78
- const promised = order?.takeaway_details?.estimated_takeaway_time ?? order?.delivery_details?.estimated_delivery_time ?? null;
79
- if (typeof promised === 'string' && promised.trim() !== '') {
80
- const at = new Date(promised);
81
- if (!Number.isNaN(at.getTime())) {
82
- return { target_at: at, target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE };
135
+ /**
136
+ * The on-time target of one order, and where it came from (decision e2).
137
+ *
138
+ * The target is used ONLY for grading:
139
+ * ready_at = prep_started_at + ready_minutes
140
+ * delta = ready_at - target_at
141
+ *
142
+ * The anchor is the PUNCH instant (order.createdAt), never start_time. Explicit
143
+ * estimated_takeaway_time / estimated_delivery_time are deliberately NOT part of
144
+ * this hierarchy.
145
+ *
146
+ * DINE-IN:
147
+ * 1. dinein_details.prep_minutes (MINUTES; 0 = explicit immediate target)
148
+ * 2. tenant.default_prep_minutes (MINUTES; > 0)
149
+ * 3. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
150
+ * 4. NONE
151
+ *
152
+ * NON-DINE-IN:
153
+ * 1. tenant.default_prep_minutes (MINUTES; > 0)
154
+ * 2. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
155
+ * 3. NONE
156
+ *
157
+ * Every invalid / non-finite / negative value is absent and falls through.
158
+ */
159
+ export function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs) {
160
+ const createdMs = order?.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
161
+ if (Number.isNaN(createdMs)) {
162
+ return { target_at: null, target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
163
+ }
164
+ if (isDineInOrder(order)) {
165
+ // prep_minutes is already MINUTES. 0 is a VALID immediate target when the
166
+ // field is present, so only a negative / invalid value falls through.
167
+ const prepMinutes = toTargetMinutes(order.dinein_details?.prep_minutes, true);
168
+ if (prepMinutes != null) {
169
+ return {
170
+ target_at: new Date(createdMs + prepMinutes * 60000),
171
+ target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP,
172
+ };
83
173
  }
84
174
  }
85
- // Otherwise the tenant default, measured from the punch instant. Absent in the
86
- // dev fixtures (0 orders carry one), so it arrives from tenant config and is
87
- // usually null - those items are honestly counted as NONE, never graded against
88
- // an invented baseline.
89
- const fallbackMinutes = toMinutes(tenantDefaultMinutes);
90
- const createdMs = order?.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
91
- if (fallbackMinutes != null && fallbackMinutes > 0 && !Number.isNaN(createdMs)) {
175
+ // default_prep_minutes is MINUTES; 0 means "not configured" for targets.
176
+ const defaultMinutes = toTargetMinutes(tenantDefaultMinutes, false);
177
+ if (defaultMinutes != null) {
92
178
  return {
93
- target_at: new Date(createdMs + fallbackMinutes * 60000),
179
+ target_at: new Date(createdMs + defaultMinutes * 60000),
94
180
  target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT,
95
181
  };
96
182
  }
183
+ // takeaway_time is MILLISECONDS and MUST be converted to whole minutes first.
184
+ const takeawayMinutes = toTakeawayMinutes(tenantTakeawayTimeMs);
185
+ if (takeawayMinutes != null) {
186
+ return {
187
+ target_at: new Date(createdMs + takeawayMinutes * 60000),
188
+ target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME,
189
+ };
190
+ }
97
191
  return { target_at: null, target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
98
192
  }
99
193
  /**
@@ -118,7 +212,7 @@ export const buildMaterializedPrepTimeEntryKey = (itemId, lineId) => {
118
212
  * item counts toward coverage; only MEASURED items reach the duration statistics,
119
213
  * and only MEASURED items with a target are graded on time.
120
214
  */
121
- export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, }) {
215
+ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, tenantTakeawayTimeMs = null, }) {
122
216
  const counters = freshMaterializedPrepTimeCounters();
123
217
  const entries = [];
124
218
  if (order == null)
@@ -132,7 +226,7 @@ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes =
132
226
  const staffName = order.staff_details?.name != null ? String(order.staff_details.name) : null;
133
227
  const createdMs = order.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
134
228
  const createdAt = Number.isNaN(createdMs) ? new Date(0) : new Date(createdMs);
135
- const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes);
229
+ const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs);
136
230
  let tracked = 0;
137
231
  for (const category of order.categories ?? []) {
138
232
  for (const item of category?.items ?? []) {
@@ -193,6 +287,10 @@ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes =
193
287
  counters.coverage.fallback_anchor_count += 1;
194
288
  }
195
289
  }
290
+ // Counter semantics of the NEW hierarchy: PROMISE is legacy-only and is
291
+ // never produced by resolveMaterializedPrepTimeTarget, so every target it
292
+ // DOES produce is a default-baseline target (DINE_IN_PREP /
293
+ // TENANT_DEFAULT / TAKEAWAY_TIME). A row with no target is NONE.
196
294
  if (target_at != null) {
197
295
  if (target_source === MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE) {
198
296
  counters.promise.promise_set_count += 1;
@@ -223,7 +321,8 @@ export function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes =
223
321
  ready_at: readyAt,
224
322
  is_ready: isReady,
225
323
  target_at,
226
- target_source: target_at != null ? target_source : null,
324
+ // NONE is the explicit "no target" source; never null on a new row.
325
+ target_source,
227
326
  delta_minutes: deltaMinutes,
228
327
  staff_id: staffId,
229
328
  staff_name: staffName,
@@ -34,7 +34,10 @@ export function mergeMaterializedPrepTimeCounters(target, source) {
34
34
  : Math.min(target.duration.min, source.duration.min);
35
35
  target.duration.max = Math.max(target.duration.max, source.duration.max);
36
36
  }
37
- // ---- promise (all additive; delta_sum is SIGNED) ----
37
+ // ---- target / on-time (all additive; delta_sum is SIGNED) ----
38
+ // The counter block keeps its historical `promise` name for API compatibility.
39
+ // PROMISE is legacy-only; the new hierarchy contributes to
40
+ // default_baseline_count / no_target_count instead.
38
41
  target.promise.promise_set_count += source.promise.promise_set_count;
39
42
  target.promise.default_baseline_count += source.promise.default_baseline_count;
40
43
  target.promise.on_time_count += source.promise.on_time_count;
@@ -119,6 +122,7 @@ export function compileTenantPrepTimeReports(input) {
119
122
  order,
120
123
  context,
121
124
  tenantDefaultMinutes: input.tenantDefaultMinutes ?? null,
125
+ tenantTakeawayTimeMs: input.tenantTakeawayTimeMs ?? null,
122
126
  });
123
127
  // COVERAGE IS THE HEADLINE, so an order that served items but was never
124
128
  // observed MUST still contribute its denominator. Skipping it would let the
@@ -37,7 +37,7 @@ const PrepTimeEntrySchema = new Schema({
37
37
  // Reconstructed (= prep_started_at + ready_minutes), MEASURED rows only.
38
38
  ready_at: { type: Schema.Types.Date, default: null },
39
39
  is_ready: { type: Boolean, required: true, default: false },
40
- // ---- promise ----
40
+ // ---- target / on-time grading ----
41
41
  target_at: { type: Schema.Types.Date, default: null },
42
42
  target_source: {
43
43
  type: String,
@@ -417,18 +417,31 @@ export declare const MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = 0;
417
417
  /**
418
418
  * WHERE an item's on-time target came from (decision e2).
419
419
  *
420
- * Promise-only grading would leave 63-97% of items ungraded (measured: only
421
- * 2.7% / 36.2% of orders carry an explicit estimate), so an item with no promise
422
- * is graded against the TENANT DEFAULT - the documented
423
- * `getDeliveryExpectedTime` fallback chain. The baseline is labelled per row so
424
- * a reader can always tell the two apart.
420
+ * The M2 target hierarchy is anchored to the PUNCH instant (`order.createdAt`):
421
+ *
422
+ * DINE-IN: dinein_details.prep_minutes (MINUTES; 0 = immediate)
423
+ * -> tenant.default_prep_minutes (MINUTES; > 0)
424
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
425
+ * -> NONE
426
+ * OTHER: tenant.default_prep_minutes (MINUTES; > 0)
427
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
428
+ * -> NONE
429
+ *
430
+ * Explicit `estimated_takeaway_time` / `estimated_delivery_time` are NOT part
431
+ * of this hierarchy. PROMISE is retained only so historical documents remain
432
+ * readable; the current writer never produces it. The baseline is labelled per
433
+ * row so a reader can always tell which rule produced the target.
425
434
  */
426
435
  export declare enum MATERIALIZED_PREP_TIME_TARGET_ENUM {
427
- /** The order carried an explicit estimate. */
436
+ /** Legacy-only: an explicit estimate written by an older implementation. */
428
437
  PROMISE = "PROMISE",
429
- /** The order was ASAP and is graded against the tenant default. */
438
+ /** Dine-in target from `dinein_details.prep_minutes` (MINUTES). */
439
+ DINE_IN_PREP = "DINE_IN_PREP",
440
+ /** Tenant `default_prep_minutes` (MINUTES), anchored to the punch instant. */
430
441
  TENANT_DEFAULT = "TENANT_DEFAULT",
431
- /** Neither exists - the row cannot be graded. */
442
+ /** Tenant `takeaway_time` (MILLISECONDS -> whole minutes), from the punch instant. */
443
+ TAKEAWAY_TIME = "TAKEAWAY_TIME",
444
+ /** No source in the hierarchy - the row cannot be graded. */
432
445
  NONE = "NONE"
433
446
  }
434
447
  export declare const ALL_MATERIALIZED_PREP_TIME_TARGETS: MATERIALIZED_PREP_TIME_TARGET_ENUM[];
@@ -522,19 +522,32 @@ exports.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA = 0;
522
522
  /**
523
523
  * WHERE an item's on-time target came from (decision e2).
524
524
  *
525
- * Promise-only grading would leave 63-97% of items ungraded (measured: only
526
- * 2.7% / 36.2% of orders carry an explicit estimate), so an item with no promise
527
- * is graded against the TENANT DEFAULT - the documented
528
- * `getDeliveryExpectedTime` fallback chain. The baseline is labelled per row so
529
- * a reader can always tell the two apart.
525
+ * The M2 target hierarchy is anchored to the PUNCH instant (`order.createdAt`):
526
+ *
527
+ * DINE-IN: dinein_details.prep_minutes (MINUTES; 0 = immediate)
528
+ * -> tenant.default_prep_minutes (MINUTES; > 0)
529
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
530
+ * -> NONE
531
+ * OTHER: tenant.default_prep_minutes (MINUTES; > 0)
532
+ * -> tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0)
533
+ * -> NONE
534
+ *
535
+ * Explicit `estimated_takeaway_time` / `estimated_delivery_time` are NOT part
536
+ * of this hierarchy. PROMISE is retained only so historical documents remain
537
+ * readable; the current writer never produces it. The baseline is labelled per
538
+ * row so a reader can always tell which rule produced the target.
530
539
  */
531
540
  var MATERIALIZED_PREP_TIME_TARGET_ENUM;
532
541
  (function (MATERIALIZED_PREP_TIME_TARGET_ENUM) {
533
- /** The order carried an explicit estimate. */
542
+ /** Legacy-only: an explicit estimate written by an older implementation. */
534
543
  MATERIALIZED_PREP_TIME_TARGET_ENUM["PROMISE"] = "PROMISE";
535
- /** The order was ASAP and is graded against the tenant default. */
544
+ /** Dine-in target from `dinein_details.prep_minutes` (MINUTES). */
545
+ MATERIALIZED_PREP_TIME_TARGET_ENUM["DINE_IN_PREP"] = "DINE_IN_PREP";
546
+ /** Tenant `default_prep_minutes` (MINUTES), anchored to the punch instant. */
536
547
  MATERIALIZED_PREP_TIME_TARGET_ENUM["TENANT_DEFAULT"] = "TENANT_DEFAULT";
537
- /** Neither exists - the row cannot be graded. */
548
+ /** Tenant `takeaway_time` (MILLISECONDS -> whole minutes), from the punch instant. */
549
+ MATERIALIZED_PREP_TIME_TARGET_ENUM["TAKEAWAY_TIME"] = "TAKEAWAY_TIME";
550
+ /** No source in the hierarchy - the row cannot be graded. */
538
551
  MATERIALIZED_PREP_TIME_TARGET_ENUM["NONE"] = "NONE";
539
552
  })(MATERIALIZED_PREP_TIME_TARGET_ENUM || (exports.MATERIALIZED_PREP_TIME_TARGET_ENUM = MATERIALIZED_PREP_TIME_TARGET_ENUM = {}));
540
553
  exports.ALL_MATERIALIZED_PREP_TIME_TARGETS = Object.values(MATERIALIZED_PREP_TIME_TARGET_ENUM);
@@ -43,12 +43,21 @@ export interface IPrepTimeOrderSource {
43
43
  prep_started_at?: Date | string | null;
44
44
  }[];
45
45
  }[];
46
+ /**
47
+ * Explicit estimates are present on the SOURCE order but are deliberately NOT
48
+ * part of the M2 target hierarchy (they are a promise, not the prep-time
49
+ * baseline). Kept in the shape so callers can pass a full order object.
50
+ */
46
51
  delivery_details?: {
47
52
  estimated_delivery_time?: Date | string | null;
48
53
  } | null;
49
54
  takeaway_details?: {
50
55
  estimated_takeaway_time?: Date | string | null;
51
56
  } | null;
57
+ /** Dine-in prep target in MINUTES. */
58
+ dinein_details?: {
59
+ prep_minutes?: number | string | null;
60
+ } | null;
52
61
  }
53
62
  export interface IPrepTimeOrderContext {
54
63
  local_date: string;
@@ -72,8 +81,31 @@ export declare function classifyMaterializedPrepTimeAnchor(item: {
72
81
  }): MATERIALIZED_PREP_TIME_ANCHOR_ENUM;
73
82
  /** A zeroed counter block. */
74
83
  export declare function freshMaterializedPrepTimeCounters(): IMaterializedPrepTimeCounters;
75
- /** The on-time target of one order, and where it came from (decision e2). */
76
- export declare function resolveMaterializedPrepTimeTarget(order: Pick<IPrepTimeOrderSource, 'createdAt' | 'delivery_details' | 'takeaway_details'>, tenantDefaultMinutes?: number | null): {
84
+ /**
85
+ * The on-time target of one order, and where it came from (decision e2).
86
+ *
87
+ * The target is used ONLY for grading:
88
+ * ready_at = prep_started_at + ready_minutes
89
+ * delta = ready_at - target_at
90
+ *
91
+ * The anchor is the PUNCH instant (order.createdAt), never start_time. Explicit
92
+ * estimated_takeaway_time / estimated_delivery_time are deliberately NOT part of
93
+ * this hierarchy.
94
+ *
95
+ * DINE-IN:
96
+ * 1. dinein_details.prep_minutes (MINUTES; 0 = explicit immediate target)
97
+ * 2. tenant.default_prep_minutes (MINUTES; > 0)
98
+ * 3. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
99
+ * 4. NONE
100
+ *
101
+ * NON-DINE-IN:
102
+ * 1. tenant.default_prep_minutes (MINUTES; > 0)
103
+ * 2. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
104
+ * 3. NONE
105
+ *
106
+ * Every invalid / non-finite / negative value is absent and falls through.
107
+ */
108
+ export declare function resolveMaterializedPrepTimeTarget(order: Pick<IPrepTimeOrderSource, 'createdAt' | 'platform' | 'order_from' | 'dinein_details'>, tenantDefaultMinutes?: number | null, tenantTakeawayTimeMs?: number | null): {
77
109
  target_at: Date | null;
78
110
  target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM;
79
111
  };
@@ -99,8 +131,9 @@ export interface IAccumulateOrderPrepTimeResult {
99
131
  * item counts toward coverage; only MEASURED items reach the duration statistics,
100
132
  * and only MEASURED items with a target are graded on time.
101
133
  */
102
- export declare function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes, }: {
134
+ export declare function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes, tenantTakeawayTimeMs, }: {
103
135
  order: IPrepTimeOrderSource;
104
136
  context: IPrepTimeOrderContext;
105
137
  tenantDefaultMinutes?: number | null;
138
+ tenantTakeawayTimeMs?: number | null;
106
139
  }): IAccumulateOrderPrepTimeResult;
@@ -26,6 +26,66 @@ const toMinutes = (value) => {
26
26
  }
27
27
  return null;
28
28
  };
29
+ /**
30
+ * Finite numeric value or null. Used by the TARGET resolver, where a source
31
+ * value is a setting/field value (not a stored duration), so it must not be
32
+ * rounded before the arithmetic.
33
+ */
34
+ const toFiniteNumber = (value) => {
35
+ if (typeof value === 'number')
36
+ return Number.isFinite(value) ? value : null;
37
+ if (typeof value === 'string' && value.trim() !== '') {
38
+ const parsed = Number(value);
39
+ return Number.isFinite(parsed) ? parsed : null;
40
+ }
41
+ return null;
42
+ };
43
+ /**
44
+ * A TARGET duration in MINUTES, or null when the value is absent / invalid.
45
+ *
46
+ * prep_minutes and default_prep_minutes are ALREADY minutes, so they are used
47
+ * as-is. A negative / non-finite value is absent and falls through the
48
+ * hierarchy. prep_minutes === 0 is an explicit immediate target (0 minutes),
49
+ * while a tenant default of 0 means "not configured".
50
+ */
51
+ const toTargetMinutes = (value, allowZero) => {
52
+ const minutes = toFiniteNumber(value);
53
+ if (minutes == null || minutes < 0)
54
+ return null;
55
+ if (!allowZero && minutes <= 0)
56
+ return null;
57
+ return minutes;
58
+ };
59
+ /**
60
+ * Tenant takeaway_time is MILLISECONDS. Convert it to WHOLE minutes
61
+ * (Math.round), then use those minutes as the target duration. A value that
62
+ * rounds to 0 is treated as NO target.
63
+ *
64
+ * This conversion is load-bearing: adding the raw milliseconds to createdAt
65
+ * would make a 30-minute setting a 30-SECOND target.
66
+ */
67
+ const toTakeawayMinutes = (value) => {
68
+ const milliseconds = toFiniteNumber(value);
69
+ if (milliseconds == null || milliseconds <= 0)
70
+ return null;
71
+ const minutes = Math.round(milliseconds / 60000);
72
+ return minutes > 0 ? minutes : null;
73
+ };
74
+ /**
75
+ * Dine-in is identified by the order's PLATFORM / ORDER SOURCE, never by the
76
+ * mere presence of dinein_details (a non-dine-in order may still carry the
77
+ * detail block, and a dine-in order may omit prep_minutes). Real values are
78
+ * POS_DINE-IN / WEB_DINE-IN / APP_DINE-IN; the check is deliberately
79
+ * case-insensitive and substring-based so a new source prefix cannot silently
80
+ * lose the dine-in target.
81
+ */
82
+ const isDineInOrder = (order) => {
83
+ for (const source of [order?.platform, order?.order_from]) {
84
+ if (typeof source === 'string' && source.toUpperCase().includes('DINE'))
85
+ return true;
86
+ }
87
+ return false;
88
+ };
29
89
  /**
30
90
  * Histogram bucket label of a duration. Total by construction: the top bucket is
31
91
  * open-ended, so every finite duration lands in exactly one bucket.
@@ -80,28 +140,62 @@ function freshMaterializedPrepTimeCounters() {
80
140
  late_items: { count: 0, worst_delta: 0 },
81
141
  };
82
142
  }
83
- /** The on-time target of one order, and where it came from (decision e2). */
84
- function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes) {
85
- // An explicit estimate is an ABSOLUTE timestamp on the order's detail block.
86
- const promised = order?.takeaway_details?.estimated_takeaway_time ?? order?.delivery_details?.estimated_delivery_time ?? null;
87
- if (typeof promised === 'string' && promised.trim() !== '') {
88
- const at = new Date(promised);
89
- if (!Number.isNaN(at.getTime())) {
90
- return { target_at: at, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE };
143
+ /**
144
+ * The on-time target of one order, and where it came from (decision e2).
145
+ *
146
+ * The target is used ONLY for grading:
147
+ * ready_at = prep_started_at + ready_minutes
148
+ * delta = ready_at - target_at
149
+ *
150
+ * The anchor is the PUNCH instant (order.createdAt), never start_time. Explicit
151
+ * estimated_takeaway_time / estimated_delivery_time are deliberately NOT part of
152
+ * this hierarchy.
153
+ *
154
+ * DINE-IN:
155
+ * 1. dinein_details.prep_minutes (MINUTES; 0 = explicit immediate target)
156
+ * 2. tenant.default_prep_minutes (MINUTES; > 0)
157
+ * 3. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
158
+ * 4. NONE
159
+ *
160
+ * NON-DINE-IN:
161
+ * 1. tenant.default_prep_minutes (MINUTES; > 0)
162
+ * 2. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
163
+ * 3. NONE
164
+ *
165
+ * Every invalid / non-finite / negative value is absent and falls through.
166
+ */
167
+ function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs) {
168
+ const createdMs = order?.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
169
+ if (Number.isNaN(createdMs)) {
170
+ return { target_at: null, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
171
+ }
172
+ if (isDineInOrder(order)) {
173
+ // prep_minutes is already MINUTES. 0 is a VALID immediate target when the
174
+ // field is present, so only a negative / invalid value falls through.
175
+ const prepMinutes = toTargetMinutes(order.dinein_details?.prep_minutes, true);
176
+ if (prepMinutes != null) {
177
+ return {
178
+ target_at: new Date(createdMs + prepMinutes * 60000),
179
+ target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP,
180
+ };
91
181
  }
92
182
  }
93
- // Otherwise the tenant default, measured from the punch instant. Absent in the
94
- // dev fixtures (0 orders carry one), so it arrives from tenant config and is
95
- // usually null - those items are honestly counted as NONE, never graded against
96
- // an invented baseline.
97
- const fallbackMinutes = toMinutes(tenantDefaultMinutes);
98
- const createdMs = order?.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
99
- if (fallbackMinutes != null && fallbackMinutes > 0 && !Number.isNaN(createdMs)) {
183
+ // default_prep_minutes is MINUTES; 0 means "not configured" for targets.
184
+ const defaultMinutes = toTargetMinutes(tenantDefaultMinutes, false);
185
+ if (defaultMinutes != null) {
100
186
  return {
101
- target_at: new Date(createdMs + fallbackMinutes * 60000),
187
+ target_at: new Date(createdMs + defaultMinutes * 60000),
102
188
  target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT,
103
189
  };
104
190
  }
191
+ // takeaway_time is MILLISECONDS and MUST be converted to whole minutes first.
192
+ const takeawayMinutes = toTakeawayMinutes(tenantTakeawayTimeMs);
193
+ if (takeawayMinutes != null) {
194
+ return {
195
+ target_at: new Date(createdMs + takeawayMinutes * 60000),
196
+ target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME,
197
+ };
198
+ }
105
199
  return { target_at: null, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
106
200
  }
107
201
  /**
@@ -127,7 +221,7 @@ exports.buildMaterializedPrepTimeEntryKey = buildMaterializedPrepTimeEntryKey;
127
221
  * item counts toward coverage; only MEASURED items reach the duration statistics,
128
222
  * and only MEASURED items with a target are graded on time.
129
223
  */
130
- function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, }) {
224
+ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, tenantTakeawayTimeMs = null, }) {
131
225
  const counters = freshMaterializedPrepTimeCounters();
132
226
  const entries = [];
133
227
  if (order == null)
@@ -141,7 +235,7 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
141
235
  const staffName = order.staff_details?.name != null ? String(order.staff_details.name) : null;
142
236
  const createdMs = order.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
143
237
  const createdAt = Number.isNaN(createdMs) ? new Date(0) : new Date(createdMs);
144
- const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes);
238
+ const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs);
145
239
  let tracked = 0;
146
240
  for (const category of order.categories ?? []) {
147
241
  for (const item of category?.items ?? []) {
@@ -202,6 +296,10 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
202
296
  counters.coverage.fallback_anchor_count += 1;
203
297
  }
204
298
  }
299
+ // Counter semantics of the NEW hierarchy: PROMISE is legacy-only and is
300
+ // never produced by resolveMaterializedPrepTimeTarget, so every target it
301
+ // DOES produce is a default-baseline target (DINE_IN_PREP /
302
+ // TENANT_DEFAULT / TAKEAWAY_TIME). A row with no target is NONE.
205
303
  if (target_at != null) {
206
304
  if (target_source === MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE) {
207
305
  counters.promise.promise_set_count += 1;
@@ -232,7 +330,8 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
232
330
  ready_at: readyAt,
233
331
  is_ready: isReady,
234
332
  target_at,
235
- target_source: target_at != null ? target_source : null,
333
+ // NONE is the explicit "no target" source; never null on a new row.
334
+ target_source,
236
335
  delta_minutes: deltaMinutes,
237
336
  staff_id: staffId,
238
337
  staff_name: staffName,
@@ -17,11 +17,17 @@ export interface ICompileTenantPrepTimeReportsInput {
17
17
  localDate: string;
18
18
  orders: IPrepTimeOrderSource[];
19
19
  /**
20
- * Tenant default prep target in MINUTES, when the tenant has one. Absent in the
21
- * dev fixtures, so it is an explicit input rather than something the compile
22
- * invents; items with neither a promise nor a default are counted as NONE.
20
+ * Tenant `default_prep_minutes` target in MINUTES, when the tenant has one.
21
+ * 0 / absent means "not configured" for targets. It is an explicit input so
22
+ * the compile never invents a tenant setting.
23
23
  */
24
24
  tenantDefaultMinutes?: number | null;
25
+ /**
26
+ * Tenant `takeaway_time` in MILLISECONDS. Final fallback of the hierarchy; the
27
+ * compile converts it to whole MINUTES before anchoring it to `createdAt`.
28
+ * Ignored while the default is present and > 0.
29
+ */
30
+ tenantTakeawayTimeMs?: number | null;
25
31
  computedAt?: Date;
26
32
  }
27
33
  export interface ICompileTenantPrepTimeReportsResult {
@@ -41,7 +41,10 @@ function mergeMaterializedPrepTimeCounters(target, source) {
41
41
  : Math.min(target.duration.min, source.duration.min);
42
42
  target.duration.max = Math.max(target.duration.max, source.duration.max);
43
43
  }
44
- // ---- promise (all additive; delta_sum is SIGNED) ----
44
+ // ---- target / on-time (all additive; delta_sum is SIGNED) ----
45
+ // The counter block keeps its historical `promise` name for API compatibility.
46
+ // PROMISE is legacy-only; the new hierarchy contributes to
47
+ // default_baseline_count / no_target_count instead.
45
48
  target.promise.promise_set_count += source.promise.promise_set_count;
46
49
  target.promise.default_baseline_count += source.promise.default_baseline_count;
47
50
  target.promise.on_time_count += source.promise.on_time_count;
@@ -126,6 +129,7 @@ function compileTenantPrepTimeReports(input) {
126
129
  order,
127
130
  context,
128
131
  tenantDefaultMinutes: input.tenantDefaultMinutes ?? null,
132
+ tenantTakeawayTimeMs: input.tenantTakeawayTimeMs ?? null,
129
133
  });
130
134
  // COVERAGE IS THE HEADLINE, so an order that served items but was never
131
135
  // observed MUST still contribute its denominator. Skipping it would let the
@@ -48,7 +48,9 @@ export interface IFormattedPrepTimeSummary {
48
48
  instant_percent: number | null;
49
49
  on_time_count: number;
50
50
  late_count: number;
51
+ /** LEGACY-only; the current target hierarchy never produces PROMISE. */
51
52
  promise_baseline_count: number;
53
+ /** DINE_IN_PREP / TENANT_DEFAULT / TAKEAWAY_TIME targets. */
52
54
  default_baseline_count: number;
53
55
  unmeasurable_count: number;
54
56
  }
@@ -40,7 +40,7 @@ const PrepTimeEntrySchema = new mongoose_1.Schema({
40
40
  // Reconstructed (= prep_started_at + ready_minutes), MEASURED rows only.
41
41
  ready_at: { type: mongoose_1.Schema.Types.Date, default: null },
42
42
  is_ready: { type: Boolean, required: true, default: false },
43
- // ---- promise ----
43
+ // ---- target / on-time grading ----
44
44
  target_at: { type: mongoose_1.Schema.Types.Date, default: null },
45
45
  target_source: {
46
46
  type: String,
@@ -45,7 +45,10 @@ export interface IMaterializedPrepTimeEntry {
45
45
  */
46
46
  ready_at: Date | null;
47
47
  is_ready: boolean;
48
- /** The on-time target, and where it came from (decision e2). */
48
+ /**
49
+ * The on-time target, and where it came from. `NONE` is the explicit
50
+ * no-target source on new rows; `null` is accepted only for legacy rows.
51
+ */
49
52
  target_at: Date | null;
50
53
  target_source: MATERIALIZED_PREP_TIME_TARGET_ENUM | null;
51
54
  /** SIGNED minutes (ready_at - target_at); positive means late. MEASURED + target only. */
@@ -53,22 +53,28 @@ export interface IMaterializedPrepTimeDuration {
53
53
  buckets: Record<string, number>;
54
54
  }
55
55
  /**
56
- * Promise grading - measured items ONLY (the ready instant exists only there).
56
+ * Target / on-time grading - measured items ONLY (the ready instant exists only
57
+ * there).
57
58
  *
58
59
  * `delta` is SIGNED minutes: positive means late, negative means early. The
59
60
  * tolerance is `MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA` (0 for v1), kept as a
60
61
  * constant so a grace window can be applied to the SAME materialized data later.
62
+ *
63
+ * The `promise` block keeps its historical name for API compatibility. The
64
+ * current target hierarchy (dine-in prep / tenant default / converted takeaway
65
+ * time) NEVER produces `PROMISE`; every target it produces is a default
66
+ * baseline.
61
67
  */
62
68
  export interface IMaterializedPrepTimePromise {
63
- /** Orders carrying an explicit estimate. */
69
+ /** LEGACY-only: orders carrying an explicit estimate. Always 0 for new data. */
64
70
  promise_set_count: number;
65
- /** Orders graded against the tenant default (ASAP). */
71
+ /** Items graded against the tenant baseline (DINE_IN_PREP / TENANT_DEFAULT / TAKEAWAY_TIME). */
66
72
  default_baseline_count: number;
67
73
  on_time_count: number;
68
74
  late_count: number;
69
75
  /** Sum of the SIGNED deltas - the signed detail survives for a grace window. */
70
76
  delta_sum: number;
71
- /** No promise AND no tenant default - cannot be graded. */
77
+ /** No target in the hierarchy - cannot be graded. */
72
78
  no_target_count: number;
73
79
  }
74
80
  /** The per-key counter block. */
@@ -55,20 +55,113 @@ describe('resolveMaterializedPrepTimeBucket', () => {
55
55
  expect((0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeBucket)(9999)).toBe('60+');
56
56
  });
57
57
  });
58
- describe('resolveMaterializedPrepTimeTarget (decision e2)', () => {
59
- it('uses an explicit estimate as the PROMISE baseline', () => {
60
- const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ takeaway_details: { estimated_takeaway_time: '2026-09-13T10:10:00.000Z' } }));
61
- expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE);
58
+ describe('resolveMaterializedPrepTimeTarget (target hierarchy)', () => {
59
+ it('DINE-IN: uses dinein_details.prep_minutes in MINUTES, anchored to createdAt (not start_time)', () => {
60
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({
61
+ platform: 'POS_DINE-IN',
62
+ dinein_details: { prep_minutes: 20, start_time: '2026-09-13T09:00:00.000Z' },
63
+ }), 15, 1800000);
64
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP);
65
+ // createdAt 09:55 + 20 min - NOT start_time 09:00.
66
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:15:00.000Z');
67
+ });
68
+ it('DINE-IN: detects the order source when platform is absent', () => {
69
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ platform: null, order_from: 'WEB_DINE-IN', dinein_details: { prep_minutes: 10 } }), 15);
70
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP);
71
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:05:00.000Z');
72
+ });
73
+ it('does NOT infer dine-in from dinein_details alone', () => {
74
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({
75
+ platform: 'POS_TAKE-AWAY',
76
+ dinein_details: { prep_minutes: 30 },
77
+ }), 15, 1800000);
78
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT);
62
79
  expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
63
80
  });
64
- it('falls back to the TENANT DEFAULT measured from the punch instant', () => {
81
+ it('DINE-IN: falls back to tenant.default_prep_minutes when prep_minutes is absent', () => {
82
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ platform: 'POS_DINE-IN', dinein_details: {} }), 15, 1800000);
83
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT);
84
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
85
+ });
86
+ it('DINE-IN: falls back to takeaway_time when prep_minutes and default are absent', () => {
87
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ platform: 'APP_DINE-IN', dinein_details: {} }), null, 1800000);
88
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
89
+ // 1_800_000 ms = 30 MINUTES -> 09:55 + 30 = 10:25.
90
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:25:00.000Z');
91
+ });
92
+ it('NON-DINE-IN: uses tenant.default_prep_minutes in MINUTES', () => {
65
93
  const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), 15);
66
94
  expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT);
67
- // createdAt 09:55 + 15 min
68
95
  expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
69
96
  });
97
+ it('NON-DINE-IN: default 0 falls through to takeaway_time', () => {
98
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), 0, 1800000);
99
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
100
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:25:00.000Z');
101
+ });
70
102
  it('reports NONE rather than inventing a baseline', () => {
71
- const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null);
103
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null, null);
104
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
105
+ expect(resolved.target_at).toBeNull();
106
+ });
107
+ it('default 0 alone produces NO target', () => {
108
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), 0, null);
109
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
110
+ expect(resolved.target_at).toBeNull();
111
+ });
112
+ it('converts takeaway_time milliseconds to WHOLE minutes before anchoring', () => {
113
+ const oneMinute = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null, 30000);
114
+ expect(oneMinute.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
115
+ // 30_000 ms = 1 minute -> 09:56, NOT 09:55:30 (raw milliseconds).
116
+ expect(oneMinute.target_at?.toISOString()).toBe('2026-09-13T09:56:00.000Z');
117
+ const thirtyMinutes = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null, 1800000);
118
+ expect(thirtyMinutes.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
119
+ expect(thirtyMinutes.target_at?.toISOString()).toBe('2026-09-13T10:25:00.000Z');
120
+ // Rounds DOWN to 0 minutes -> treated as no target, never a 29.999s target.
121
+ const subMinute = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null, 29000);
122
+ expect(subMinute.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
123
+ expect(subMinute.target_at).toBeNull();
124
+ });
125
+ it('pins prep_minutes = 0 as an explicit immediate DINE_IN_PREP target', () => {
126
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({
127
+ platform: 'POS_DINE-IN',
128
+ dinein_details: { prep_minutes: 0 },
129
+ }), 15, 1800000);
130
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP);
131
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T09:55:00.000Z');
132
+ });
133
+ it('lets invalid / non-finite / negative values fall through the hierarchy', () => {
134
+ // Negative / NaN prep_minutes are absent, so the tenant default wins.
135
+ for (const prepMinutes of [-5, Number.NaN, Number.POSITIVE_INFINITY, 'nope']) {
136
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ platform: 'POS_DINE-IN', dinein_details: { prep_minutes: prepMinutes } }), 15);
137
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT);
138
+ }
139
+ // Invalid default is absent, so takeaway_time wins.
140
+ for (const defaultMinutes of [-5, Number.NaN, Number.POSITIVE_INFINITY, 'nope']) {
141
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), defaultMinutes, 1800000);
142
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
143
+ }
144
+ // Invalid takeaway_time leaves NO target.
145
+ for (const takeaway of [-1, 0, Number.NaN, Number.POSITIVE_INFINITY, 'nope']) {
146
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order(), null, takeaway);
147
+ expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
148
+ }
149
+ });
150
+ it('ignores explicit estimate fields - they are NOT part of the new hierarchy', () => {
151
+ const withEstimate = order({
152
+ takeaway_details: { estimated_takeaway_time: '2026-09-13T10:40:00.000Z' },
153
+ delivery_details: { estimated_delivery_time: '2026-09-13T10:45:00.000Z' },
154
+ });
155
+ const noTenantTarget = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(withEstimate, null, null);
156
+ expect(noTenantTarget.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
157
+ expect(noTenantTarget.target_at).toBeNull();
158
+ const tenantDefault = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(withEstimate, 15, null);
159
+ expect(tenantDefault.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT);
160
+ // 09:55 + 15 = 10:10 - NOT the 10:40 promise.
161
+ expect(tenantDefault.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
162
+ });
163
+ it('reports NONE when createdAt is unusable', () => {
164
+ const resolved = (0, materialized_prep_time_classification_helpers_1.resolveMaterializedPrepTimeTarget)(order({ createdAt: 'not-a-date' }), 15, 1800000);
72
165
  expect(resolved.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
73
166
  expect(resolved.target_at).toBeNull();
74
167
  });
@@ -211,29 +304,30 @@ describe('accumulateOrderPrepTime - the EXCLUSION rule', () => {
211
304
  expect(Object.values(duration.buckets).every((count) => count === 0)).toBe(true);
212
305
  });
213
306
  });
214
- describe('accumulateOrderPrepTime - promise grading', () => {
307
+ describe('accumulateOrderPrepTime - target grading', () => {
215
308
  it('grades ON TIME when the ready instant beats the target (delta <= 0)', () => {
216
309
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
217
310
  // prep started 10:00, 5 min -> ready 10:05; target 10:10.
218
311
  order: order({
219
312
  categories: [{ name: 'Mains', items: [item({ ready_minutes: 5 })] }],
220
- takeaway_details: { estimated_takeaway_time: '2026-09-13T10:10:00.000Z' },
221
313
  }),
222
314
  context,
315
+ tenantDefaultMinutes: 15,
223
316
  });
224
317
  expect(result.counters.promise.on_time_count).toBe(1);
225
318
  expect(result.counters.promise.late_count).toBe(0);
226
319
  expect(result.counters.promise.delta_sum).toBe(-5);
227
- expect(result.counters.promise.promise_set_count).toBe(1);
320
+ expect(result.counters.promise.default_baseline_count).toBe(1);
321
+ expect(result.counters.promise.promise_set_count).toBe(0);
228
322
  });
229
323
  it('grades LATE with a SIGNED delta and tracks worst_delta', () => {
230
324
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
231
325
  // ready 10:00 + 20 = 10:20; target 10:10 -> +10 late.
232
326
  order: order({
233
327
  categories: [{ name: 'Mains', items: [item({ ready_minutes: 20 })] }],
234
- takeaway_details: { estimated_takeaway_time: '2026-09-13T10:10:00.000Z' },
235
328
  }),
236
329
  context,
330
+ tenantDefaultMinutes: 15,
237
331
  });
238
332
  expect(result.counters.promise.late_count).toBe(1);
239
333
  expect(result.counters.promise.on_time_count).toBe(0);
@@ -250,6 +344,8 @@ describe('accumulateOrderPrepTime - promise grading', () => {
250
344
  expect(result.counters.promise.on_time_count).toBe(0);
251
345
  expect(result.counters.promise.late_count).toBe(0);
252
346
  expect(result.counters.late_items.count).toBe(0);
347
+ expect(result.counters.promise.default_baseline_count).toBe(0);
348
+ expect(result.counters.promise.promise_set_count).toBe(0);
253
349
  });
254
350
  it('counts a DEFAULT baseline separately from a promise (decision e2)', () => {
255
351
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
@@ -261,6 +357,67 @@ describe('accumulateOrderPrepTime - promise grading', () => {
261
357
  expect(result.counters.promise.promise_set_count).toBe(0);
262
358
  expect(result.counters.promise.on_time_count).toBe(1);
263
359
  });
360
+ it('counts a DINE_IN_PREP target in default_baseline_count, not promise_set_count', () => {
361
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
362
+ // ready 10:09; dine-in prep 20 -> target 10:15 -> -6 on time.
363
+ order: order({
364
+ platform: 'POS_DINE-IN',
365
+ dinein_details: { prep_minutes: 20 },
366
+ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }],
367
+ }),
368
+ context,
369
+ tenantDefaultMinutes: 15,
370
+ tenantTakeawayTimeMs: 1800000,
371
+ });
372
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP);
373
+ expect(result.counters.promise.default_baseline_count).toBe(1);
374
+ expect(result.counters.promise.promise_set_count).toBe(0);
375
+ expect(result.counters.promise.on_time_count).toBe(1);
376
+ expect(result.counters.promise.delta_sum).toBe(-6);
377
+ });
378
+ it('grades against the CONVERTED takeaway_time target, never raw milliseconds', () => {
379
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
380
+ // ready 10:09. takeaway_time 30_000 ms -> 1 minute -> target 09:56.
381
+ // Raw milliseconds would target 09:55:30 and still be late, but by a
382
+ // different amount; the exact target is what this test pins.
383
+ order: order({ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }] }),
384
+ context,
385
+ tenantDefaultMinutes: 0,
386
+ tenantTakeawayTimeMs: 30000,
387
+ });
388
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
389
+ expect(result.entries[0].target_at?.toISOString()).toBe('2026-09-13T09:56:00.000Z');
390
+ expect(result.entries[0].delta_minutes).toBe(13);
391
+ expect(result.counters.promise.late_count).toBe(1);
392
+ expect(result.counters.promise.delta_sum).toBe(13);
393
+ expect(result.counters.promise.default_baseline_count).toBe(1);
394
+ expect(result.counters.promise.promise_set_count).toBe(0);
395
+ });
396
+ it('grades ON TIME against a converted 30-minute takeaway_time target', () => {
397
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
398
+ // ready 10:09; 1_800_000 ms -> 30 minutes -> target 10:25.
399
+ order: order({ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }] }),
400
+ context,
401
+ tenantTakeawayTimeMs: 1800000,
402
+ });
403
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
404
+ expect(result.counters.promise.on_time_count).toBe(1);
405
+ expect(result.counters.promise.late_count).toBe(0);
406
+ expect(result.counters.promise.delta_sum).toBe(-16);
407
+ });
408
+ it('default 0 with no takeaway counts NO TARGET (never an instant default)', () => {
409
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
410
+ order: order({ categories: [{ name: 'Mains', items: [item()] }] }),
411
+ context,
412
+ tenantDefaultMinutes: 0,
413
+ });
414
+ expect(result.counters.promise.no_target_count).toBe(1);
415
+ expect(result.entries[0].target_at).toBeNull();
416
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
417
+ expect(result.counters.promise.default_baseline_count).toBe(0);
418
+ expect(result.counters.promise.on_time_count).toBe(0);
419
+ expect(result.counters.promise.late_count).toBe(0);
420
+ });
264
421
  });
265
422
  describe('accumulateOrderPrepTime - drill-down rows', () => {
266
423
  it('emits a row for EVERY served item, each stating its anchor', () => {
@@ -291,6 +448,9 @@ describe('accumulateOrderPrepTime - drill-down rows', () => {
291
448
  expect(untracked.duration_minutes).toBeNull();
292
449
  expect(untracked.ready_at).toBeNull();
293
450
  expect(untracked.delta_minutes).toBeNull();
451
+ // No target at all is an explicit NONE source on the row.
452
+ expect(untracked.target_at).toBeNull();
453
+ expect(untracked.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
294
454
  // The ready instant is RECONSTRUCTED for the measured row only.
295
455
  expect(measured.ready_at?.toISOString()).toBe('2026-09-13T10:09:00.000Z');
296
456
  expect(fallback.ready_at).toBeNull();
@@ -218,6 +218,38 @@ describe('compileTenantPrepTimeReports', () => {
218
218
  expect(rows).toHaveLength(1);
219
219
  expect(rows[0].anchor).toBe('MEASURED');
220
220
  });
221
+ it('threads the tenant default and takeaway_time into the compiled target', () => {
222
+ // takeaway_time arrives in MILLISECONDS; 30_000 ms = 1 minute.
223
+ const result = compile([order()], { tenantDefaultMinutes: 0, tenantTakeawayTimeMs: 30000 });
224
+ const dateEntries = result.entries.find((doc) => doc.scope_context === 'localDate');
225
+ const row = dateEntries.prep_time_entries['COMPLETED:POS_WALK-IN'].rows[0];
226
+ expect(row.target_source).toBe('TAKEAWAY_TIME');
227
+ expect(row.target_at?.toISOString()).toBe('2026-09-13T09:56:00.000Z');
228
+ expect(row.delta_minutes).toBe(13);
229
+ const dateReport = result.reports.find((doc) => doc.scope_context === 'localDate');
230
+ const counters = dateReport.prep_time_counters['COMPLETED:POS_WALK-IN'];
231
+ expect(counters.promise.default_baseline_count).toBe(1);
232
+ expect(counters.promise.promise_set_count).toBe(0);
233
+ expect(counters.promise.late_count).toBe(1);
234
+ expect(counters.promise.delta_sum).toBe(13);
235
+ });
236
+ it('threads the dine-in prep target and the tenant default into the compiled counters', () => {
237
+ const dineIn = order({
238
+ platform: 'POS_DINE-IN',
239
+ dinein_details: { prep_minutes: 20 },
240
+ });
241
+ const result = compile([dineIn], { tenantDefaultMinutes: 15, tenantTakeawayTimeMs: 1800000 });
242
+ const dateEntries = result.entries.find((doc) => doc.scope_context === 'localDate');
243
+ const row = dateEntries.prep_time_entries['COMPLETED:POS_DINE-IN'].rows[0];
244
+ expect(row.target_source).toBe('DINE_IN_PREP');
245
+ expect(row.target_at?.toISOString()).toBe('2026-09-13T10:15:00.000Z');
246
+ const dateReport = result.reports.find((doc) => doc.scope_context === 'localDate');
247
+ const counters = dateReport.prep_time_counters['COMPLETED:POS_DINE-IN'];
248
+ expect(counters.promise.default_baseline_count).toBe(1);
249
+ expect(counters.promise.promise_set_count).toBe(0);
250
+ expect(counters.promise.on_time_count).toBe(1);
251
+ expect(counters.promise.delta_sum).toBe(-6);
252
+ });
221
253
  it('rejects malformed input without throwing', () => {
222
254
  expect((0, materialized_prep_time_compile_helpers_1.compileTenantPrepTimeReports)(null)).toBeNull();
223
255
  expect((0, materialized_prep_time_compile_helpers_1.compileTenantPrepTimeReports)({
@@ -87,7 +87,9 @@ describe('prep time report constants (M2)', () => {
87
87
  it('labels every on-time baseline and allows NONE (decision e2)', () => {
88
88
  expect(MATERIALIZED_REPORTS_1.ALL_MATERIALIZED_PREP_TIME_TARGETS).toEqual([
89
89
  MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE,
90
+ MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP,
90
91
  MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT,
92
+ MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME,
91
93
  MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE,
92
94
  ]);
93
95
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.43",
3
+ "version": "0.4.45",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",