@managesome/eposmatic-toolkit 0.4.44 → 0.4.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +19 -9
  2. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +122 -31
  3. package/esm/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +9 -7
  4. package/esm/helpers/materialized-reports/tenant-prep-time-formatter.js +5 -7
  5. package/esm/schemas/models/materialized_tenant_prep_time_entries.js +1 -1
  6. package/lib/constants/MATERIALIZED_REPORTS.d.ts +19 -9
  7. package/lib/constants/MATERIALIZED_REPORTS.js +19 -9
  8. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.d.ts +36 -3
  9. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +122 -31
  10. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.d.ts +9 -3
  11. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +9 -7
  12. package/lib/helpers/materialized-reports/tenant-prep-time-formatter.d.ts +1 -1
  13. package/lib/helpers/materialized-reports/tenant-prep-time-formatter.js +5 -7
  14. package/lib/schemas/models/materialized_tenant_prep_time_entries.js +1 -1
  15. package/lib/schemas/types/materialized_tenant_prep_time_entries.d.ts +4 -1
  16. package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +9 -7
  17. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +178 -23
  18. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +1 -2
  19. package/lib/tests/materialized-reports/materialized-prep-time-compile.test.js +35 -5
  20. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +2 -1
  21. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +1 -2
  22. package/lib/tests/materialized-reports/tenant-prep-time-formatter.test.js +2 -5
  23. package/package.json +1 -1
@@ -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.
@@ -69,8 +129,7 @@ function freshMaterializedPrepTimeCounters() {
69
129
  order_count: 0,
70
130
  },
71
131
  duration: { min: 0, max: 0, sum: 0, count: 0, instant_count: 0, buckets },
72
- promise: {
73
- promise_set_count: 0,
132
+ target: {
74
133
  default_baseline_count: 0,
75
134
  on_time_count: 0,
76
135
  late_count: 0,
@@ -80,28 +139,62 @@ function freshMaterializedPrepTimeCounters() {
80
139
  late_items: { count: 0, worst_delta: 0 },
81
140
  };
82
141
  }
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 };
142
+ /**
143
+ * The on-time target of one order, and where it came from (decision e2).
144
+ *
145
+ * The target is used ONLY for grading:
146
+ * ready_at = prep_started_at + ready_minutes
147
+ * delta = ready_at - target_at
148
+ *
149
+ * The anchor is the PUNCH instant (order.createdAt), never start_time. Explicit
150
+ * estimated_takeaway_time / estimated_delivery_time are deliberately NOT part of
151
+ * this hierarchy.
152
+ *
153
+ * DINE-IN:
154
+ * 1. dinein_details.prep_minutes (MINUTES; 0 = explicit immediate target)
155
+ * 2. tenant.default_prep_minutes (MINUTES; > 0)
156
+ * 3. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
157
+ * 4. NONE
158
+ *
159
+ * NON-DINE-IN:
160
+ * 1. tenant.default_prep_minutes (MINUTES; > 0)
161
+ * 2. tenant.takeaway_time (MILLISECONDS -> whole minutes; > 0 after rounding)
162
+ * 3. NONE
163
+ *
164
+ * Every invalid / non-finite / negative value is absent and falls through.
165
+ */
166
+ function resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs) {
167
+ const createdMs = order?.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
168
+ if (Number.isNaN(createdMs)) {
169
+ return { target_at: null, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
170
+ }
171
+ if (isDineInOrder(order)) {
172
+ // prep_minutes is already MINUTES. 0 is a VALID immediate target when the
173
+ // field is present, so only a negative / invalid value falls through.
174
+ const prepMinutes = toTargetMinutes(order.dinein_details?.prep_minutes, true);
175
+ if (prepMinutes != null) {
176
+ return {
177
+ target_at: new Date(createdMs + prepMinutes * 60000),
178
+ target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP,
179
+ };
91
180
  }
92
181
  }
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)) {
182
+ // default_prep_minutes is MINUTES; 0 means "not configured" for targets.
183
+ const defaultMinutes = toTargetMinutes(tenantDefaultMinutes, false);
184
+ if (defaultMinutes != null) {
100
185
  return {
101
- target_at: new Date(createdMs + fallbackMinutes * 60000),
186
+ target_at: new Date(createdMs + defaultMinutes * 60000),
102
187
  target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TENANT_DEFAULT,
103
188
  };
104
189
  }
190
+ // takeaway_time is MILLISECONDS and MUST be converted to whole minutes first.
191
+ const takeawayMinutes = toTakeawayMinutes(tenantTakeawayTimeMs);
192
+ if (takeawayMinutes != null) {
193
+ return {
194
+ target_at: new Date(createdMs + takeawayMinutes * 60000),
195
+ target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME,
196
+ };
197
+ }
105
198
  return { target_at: null, target_source: MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE };
106
199
  }
107
200
  /**
@@ -127,7 +220,7 @@ exports.buildMaterializedPrepTimeEntryKey = buildMaterializedPrepTimeEntryKey;
127
220
  * item counts toward coverage; only MEASURED items reach the duration statistics,
128
221
  * and only MEASURED items with a target are graded on time.
129
222
  */
130
- function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, }) {
223
+ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null, tenantTakeawayTimeMs = null, }) {
131
224
  const counters = freshMaterializedPrepTimeCounters();
132
225
  const entries = [];
133
226
  if (order == null)
@@ -141,7 +234,7 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
141
234
  const staffName = order.staff_details?.name != null ? String(order.staff_details.name) : null;
142
235
  const createdMs = order.createdAt != null ? new Date(order.createdAt).getTime() : NaN;
143
236
  const createdAt = Number.isNaN(createdMs) ? new Date(0) : new Date(createdMs);
144
- const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes);
237
+ const { target_at, target_source } = resolveMaterializedPrepTimeTarget(order, tenantDefaultMinutes, tenantTakeawayTimeMs);
145
238
  let tracked = 0;
146
239
  for (const category of order.categories ?? []) {
147
240
  for (const item of category?.items ?? []) {
@@ -185,12 +278,12 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
185
278
  }
186
279
  if (target_at != null) {
187
280
  deltaMinutes = Math.round((readyAt.getTime() - target_at.getTime()) / 60000);
188
- counters.promise.delta_sum += deltaMinutes;
281
+ counters.target.delta_sum += deltaMinutes;
189
282
  if (deltaMinutes <= MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA) {
190
- counters.promise.on_time_count += 1;
283
+ counters.target.on_time_count += 1;
191
284
  }
192
285
  else {
193
- counters.promise.late_count += 1;
286
+ counters.target.late_count += 1;
194
287
  counters.late_items.count += 1;
195
288
  if (deltaMinutes > counters.late_items.worst_delta) {
196
289
  counters.late_items.worst_delta = deltaMinutes;
@@ -202,16 +295,13 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
202
295
  counters.coverage.fallback_anchor_count += 1;
203
296
  }
204
297
  }
298
+ // Every target is DINE_IN_PREP / TENANT_DEFAULT / TAKEAWAY_TIME; a row
299
+ // with no target is NONE.
205
300
  if (target_at != null) {
206
- if (target_source === MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.PROMISE) {
207
- counters.promise.promise_set_count += 1;
208
- }
209
- else {
210
- counters.promise.default_baseline_count += 1;
211
- }
301
+ counters.target.default_baseline_count += 1;
212
302
  }
213
303
  else {
214
- counters.promise.no_target_count += 1;
304
+ counters.target.no_target_count += 1;
215
305
  }
216
306
  // CATALOGUE item id: the grouping identity the Items tab reads. The
217
307
  // order-line id is a DIFFERENT identity and is preserved as line_id, so
@@ -232,7 +322,8 @@ function accumulateOrderPrepTime({ order, context, tenantDefaultMinutes = null,
232
322
  ready_at: readyAt,
233
323
  is_ready: isReady,
234
324
  target_at,
235
- target_source: target_at != null ? target_source : null,
325
+ // NONE is the explicit "no target" source; never null on a new row.
326
+ target_source,
236
327
  delta_minutes: deltaMinutes,
237
328
  staff_id: staffId,
238
329
  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,13 +41,14 @@ 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) ----
45
- target.promise.promise_set_count += source.promise.promise_set_count;
46
- target.promise.default_baseline_count += source.promise.default_baseline_count;
47
- target.promise.on_time_count += source.promise.on_time_count;
48
- target.promise.late_count += source.promise.late_count;
49
- target.promise.delta_sum += source.promise.delta_sum;
50
- target.promise.no_target_count += source.promise.no_target_count;
44
+ // ---- target / on-time (all additive; delta_sum is SIGNED) ----
45
+ // Target-grading counters; every target is DINE_IN_PREP /
46
+ // TENANT_DEFAULT / TAKEAWAY_TIME.
47
+ target.target.default_baseline_count += source.target.default_baseline_count;
48
+ target.target.on_time_count += source.target.on_time_count;
49
+ target.target.late_count += source.target.late_count;
50
+ target.target.delta_sum += source.target.delta_sum;
51
+ target.target.no_target_count += source.target.no_target_count;
51
52
  // ---- late items ----
52
53
  target.late_items.count += source.late_items.count;
53
54
  target.late_items.worst_delta = Math.max(target.late_items.worst_delta, source.late_items.worst_delta);
@@ -126,6 +127,7 @@ function compileTenantPrepTimeReports(input) {
126
127
  order,
127
128
  context,
128
129
  tenantDefaultMinutes: input.tenantDefaultMinutes ?? null,
130
+ tenantTakeawayTimeMs: input.tenantTakeawayTimeMs ?? null,
129
131
  });
130
132
  // COVERAGE IS THE HEADLINE, so an order that served items but was never
131
133
  // observed MUST still contribute its denominator. Skipping it would let the
@@ -48,7 +48,7 @@ export interface IFormattedPrepTimeSummary {
48
48
  instant_percent: number | null;
49
49
  on_time_count: number;
50
50
  late_count: number;
51
- promise_baseline_count: number;
51
+ /** DINE_IN_PREP / TENANT_DEFAULT / TAKEAWAY_TIME targets. */
52
52
  default_baseline_count: number;
53
53
  unmeasurable_count: number;
54
54
  }
@@ -58,7 +58,6 @@ const emptySummary = () => ({
58
58
  instant_percent: null,
59
59
  on_time_count: 0,
60
60
  late_count: 0,
61
- promise_baseline_count: 0,
62
61
  default_baseline_count: 0,
63
62
  unmeasurable_count: 0,
64
63
  });
@@ -72,7 +71,7 @@ const buildBuckets = (counters) => {
72
71
  const buildSummary = (counters) => {
73
72
  const coverage = counters.coverage;
74
73
  const duration = counters.duration;
75
- const promise = counters.promise;
74
+ const target = counters.target;
76
75
  const buckets = buildBuckets(counters);
77
76
  return {
78
77
  items: coverage.item_count,
@@ -86,11 +85,10 @@ const buildSummary = (counters) => {
86
85
  median_bucket: percentileBucket(buckets, 0.5),
87
86
  p90_bucket: percentileBucket(buckets, 0.9),
88
87
  instant_percent: duration.count > 0 ? toPercent(duration.instant_count, duration.count) : null,
89
- on_time_count: promise.on_time_count,
90
- late_count: promise.late_count,
91
- promise_baseline_count: promise.promise_set_count,
92
- default_baseline_count: promise.default_baseline_count,
93
- unmeasurable_count: promise.no_target_count,
88
+ on_time_count: target.on_time_count,
89
+ late_count: target.late_count,
90
+ default_baseline_count: target.default_baseline_count,
91
+ unmeasurable_count: target.no_target_count,
94
92
  };
95
93
  };
96
94
  const emptyPage = (tenantIds) => {
@@ -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,24 @@ 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
+ * Every target comes from the current hierarchy (dine-in prep / tenant default /
64
+ * converted takeaway time); there is no legacy baseline.
61
65
  */
62
- export interface IMaterializedPrepTimePromise {
63
- /** Orders carrying an explicit estimate. */
64
- promise_set_count: number;
65
- /** Orders graded against the tenant default (ASAP). */
66
+ export interface IMaterializedPrepTimeTargetGrading {
67
+ /** Items graded against a baseline (DINE_IN_PREP / TENANT_DEFAULT / TAKEAWAY_TIME). */
66
68
  default_baseline_count: number;
67
69
  on_time_count: number;
68
70
  late_count: number;
69
71
  /** Sum of the SIGNED deltas - the signed detail survives for a grace window. */
70
72
  delta_sum: number;
71
- /** No promise AND no tenant default - cannot be graded. */
73
+ /** No target in the hierarchy - cannot be graded. */
72
74
  no_target_count: number;
73
75
  }
74
76
  /** The per-key counter block. */
@@ -76,7 +78,7 @@ export interface IMaterializedPrepTimeCounters {
76
78
  coverage: IMaterializedPrepTimeCoverage;
77
79
  /** MEASURED items only. */
78
80
  duration: IMaterializedPrepTimeDuration;
79
- promise: IMaterializedPrepTimePromise;
81
+ target: IMaterializedPrepTimeTargetGrading;
80
82
  /** Late rows (measured, delta > tolerance). Details live in the entries collection. */
81
83
  late_items: {
82
84
  count: number;
@@ -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);
79
+ expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
80
+ });
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);
62
84
  expect(resolved.target_at?.toISOString()).toBe('2026-09-13T10:10:00.000Z');
63
85
  });
64
- it('falls back to the TENANT DEFAULT measured from the punch instant', () => {
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 target.
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,33 +304,33 @@ 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
- expect(result.counters.promise.on_time_count).toBe(1);
225
- expect(result.counters.promise.late_count).toBe(0);
226
- expect(result.counters.promise.delta_sum).toBe(-5);
227
- expect(result.counters.promise.promise_set_count).toBe(1);
317
+ expect(result.counters.target.on_time_count).toBe(1);
318
+ expect(result.counters.target.late_count).toBe(0);
319
+ expect(result.counters.target.delta_sum).toBe(-5);
320
+ expect(result.counters.target.default_baseline_count).toBe(1);
228
321
  });
229
322
  it('grades LATE with a SIGNED delta and tracks worst_delta', () => {
230
323
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
231
324
  // ready 10:00 + 20 = 10:20; target 10:10 -> +10 late.
232
325
  order: order({
233
326
  categories: [{ name: 'Mains', items: [item({ ready_minutes: 20 })] }],
234
- takeaway_details: { estimated_takeaway_time: '2026-09-13T10:10:00.000Z' },
235
327
  }),
236
328
  context,
329
+ tenantDefaultMinutes: 15,
237
330
  });
238
- expect(result.counters.promise.late_count).toBe(1);
239
- expect(result.counters.promise.on_time_count).toBe(0);
240
- expect(result.counters.promise.delta_sum).toBe(10);
331
+ expect(result.counters.target.late_count).toBe(1);
332
+ expect(result.counters.target.on_time_count).toBe(0);
333
+ expect(result.counters.target.delta_sum).toBe(10);
241
334
  expect(result.counters.late_items.count).toBe(1);
242
335
  expect(result.counters.late_items.worst_delta).toBe(10);
243
336
  });
@@ -246,10 +339,11 @@ describe('accumulateOrderPrepTime - promise grading', () => {
246
339
  order: order({ categories: [{ name: 'Mains', items: [item()] }] }),
247
340
  context,
248
341
  });
249
- expect(result.counters.promise.no_target_count).toBe(1);
250
- expect(result.counters.promise.on_time_count).toBe(0);
251
- expect(result.counters.promise.late_count).toBe(0);
342
+ expect(result.counters.target.no_target_count).toBe(1);
343
+ expect(result.counters.target.on_time_count).toBe(0);
344
+ expect(result.counters.target.late_count).toBe(0);
252
345
  expect(result.counters.late_items.count).toBe(0);
346
+ expect(result.counters.target.default_baseline_count).toBe(0);
253
347
  });
254
348
  it('counts a DEFAULT baseline separately from a promise (decision e2)', () => {
255
349
  const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
@@ -257,9 +351,67 @@ describe('accumulateOrderPrepTime - promise grading', () => {
257
351
  context,
258
352
  tenantDefaultMinutes: 20,
259
353
  });
260
- expect(result.counters.promise.default_baseline_count).toBe(1);
261
- expect(result.counters.promise.promise_set_count).toBe(0);
262
- expect(result.counters.promise.on_time_count).toBe(1);
354
+ expect(result.counters.target.default_baseline_count).toBe(1);
355
+ expect(result.counters.target.on_time_count).toBe(1);
356
+ });
357
+ it('counts a DINE_IN_PREP target in default_baseline_count', () => {
358
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
359
+ // ready 10:09; dine-in prep 20 -> target 10:15 -> -6 on time.
360
+ order: order({
361
+ platform: 'POS_DINE-IN',
362
+ dinein_details: { prep_minutes: 20 },
363
+ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }],
364
+ }),
365
+ context,
366
+ tenantDefaultMinutes: 15,
367
+ tenantTakeawayTimeMs: 1800000,
368
+ });
369
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.DINE_IN_PREP);
370
+ expect(result.counters.target.default_baseline_count).toBe(1);
371
+ expect(result.counters.target.on_time_count).toBe(1);
372
+ expect(result.counters.target.delta_sum).toBe(-6);
373
+ });
374
+ it('grades against the CONVERTED takeaway_time target, never raw milliseconds', () => {
375
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
376
+ // ready 10:09. takeaway_time 30_000 ms -> 1 minute -> target 09:56.
377
+ // Raw milliseconds would target 09:55:30 and still be late, but by a
378
+ // different amount; the exact target is what this test pins.
379
+ order: order({ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }] }),
380
+ context,
381
+ tenantDefaultMinutes: 0,
382
+ tenantTakeawayTimeMs: 30000,
383
+ });
384
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
385
+ expect(result.entries[0].target_at?.toISOString()).toBe('2026-09-13T09:56:00.000Z');
386
+ expect(result.entries[0].delta_minutes).toBe(13);
387
+ expect(result.counters.target.late_count).toBe(1);
388
+ expect(result.counters.target.delta_sum).toBe(13);
389
+ expect(result.counters.target.default_baseline_count).toBe(1);
390
+ });
391
+ it('grades ON TIME against a converted 30-minute takeaway_time target', () => {
392
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
393
+ // ready 10:09; 1_800_000 ms -> 30 minutes -> target 10:25.
394
+ order: order({ categories: [{ name: 'Mains', items: [item({ ready_minutes: 9 })] }] }),
395
+ context,
396
+ tenantTakeawayTimeMs: 1800000,
397
+ });
398
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.TAKEAWAY_TIME);
399
+ expect(result.counters.target.on_time_count).toBe(1);
400
+ expect(result.counters.target.late_count).toBe(0);
401
+ expect(result.counters.target.delta_sum).toBe(-16);
402
+ });
403
+ it('default 0 with no takeaway counts NO TARGET (never an instant default)', () => {
404
+ const result = (0, materialized_prep_time_classification_helpers_1.accumulateOrderPrepTime)({
405
+ order: order({ categories: [{ name: 'Mains', items: [item()] }] }),
406
+ context,
407
+ tenantDefaultMinutes: 0,
408
+ });
409
+ expect(result.counters.target.no_target_count).toBe(1);
410
+ expect(result.entries[0].target_at).toBeNull();
411
+ expect(result.entries[0].target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
412
+ expect(result.counters.target.default_baseline_count).toBe(0);
413
+ expect(result.counters.target.on_time_count).toBe(0);
414
+ expect(result.counters.target.late_count).toBe(0);
263
415
  });
264
416
  });
265
417
  describe('accumulateOrderPrepTime - drill-down rows', () => {
@@ -291,6 +443,9 @@ describe('accumulateOrderPrepTime - drill-down rows', () => {
291
443
  expect(untracked.duration_minutes).toBeNull();
292
444
  expect(untracked.ready_at).toBeNull();
293
445
  expect(untracked.delta_minutes).toBeNull();
446
+ // No target at all is an explicit NONE source on the row.
447
+ expect(untracked.target_at).toBeNull();
448
+ expect(untracked.target_source).toBe(MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_TARGET_ENUM.NONE);
294
449
  // The ready instant is RECONSTRUCTED for the measured row only.
295
450
  expect(measured.ready_at?.toISOString()).toBe('2026-09-13T10:09:00.000Z');
296
451
  expect(fallback.ready_at).toBeNull();