@managesome/eposmatic-toolkit 0.4.31 → 0.4.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +3 -5
  2. package/esm/constants/enums/offers.js +0 -6
  3. package/esm/helpers/materialized-reports/index.js +1 -0
  4. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  5. package/esm/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
  6. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -9
  7. package/esm/helpers/materialized-reports/materialized-prep-time-read-helpers.js +613 -0
  8. package/esm/helpers/store/cart-actions.js +3 -12
  9. package/esm/helpers/types/materialized-reports-apis.js +10 -0
  10. package/esm/helpers/utils/offer-apply-helpers.js +2 -10
  11. package/esm/helpers/utils/offers-helpers.js +117 -2
  12. package/esm/schemas/models/index.js +0 -1
  13. package/esm/schemas/types/index.js +0 -1
  14. package/lib/constants/MATERIALIZED_REPORTS.d.ts +3 -2
  15. package/lib/constants/MATERIALIZED_REPORTS.js +3 -5
  16. package/lib/constants/enums/offers.d.ts +0 -5
  17. package/lib/constants/enums/offers.js +1 -7
  18. package/lib/helpers/materialized-reports/index.d.ts +1 -0
  19. package/lib/helpers/materialized-reports/index.js +1 -0
  20. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  21. package/lib/helpers/materialized-reports/materialized-prep-time-classification-helpers.js +12 -8
  22. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.d.ts +15 -0
  23. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +86 -8
  24. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.d.ts +179 -0
  25. package/lib/helpers/materialized-reports/materialized-prep-time-read-helpers.js +639 -0
  26. package/lib/helpers/store/cart-actions.js +1 -10
  27. package/lib/helpers/types/materialized-reports-apis.d.ts +145 -1
  28. package/lib/helpers/types/materialized-reports-apis.js +11 -0
  29. package/lib/helpers/utils/offer-apply-helpers.js +2 -10
  30. package/lib/helpers/utils/offers-helpers.d.ts +50 -0
  31. package/lib/helpers/utils/offers-helpers.js +120 -2
  32. package/lib/schemas/models/index.d.ts +0 -1
  33. package/lib/schemas/models/index.js +0 -1
  34. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +6 -6
  35. package/lib/schemas/types/index.d.ts +0 -1
  36. package/lib/schemas/types/index.js +0 -1
  37. package/lib/schemas/types/materialized_tenant_prep_time_reports.d.ts +7 -5
  38. package/lib/tests/materialized-reports/materialized-prep-time-classification.test.js +28 -5
  39. package/lib/tests/materialized-reports/materialized-prep-time-close-day.test.js +17 -4
  40. package/lib/tests/materialized-reports/materialized-prep-time-constants.test.js +6 -4
  41. package/lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.js +135 -0
  42. package/lib/tests/materialized-reports/materialized-prep-time-plan.test.js +71 -3
  43. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.d.ts +1 -0
  44. package/lib/tests/materialized-reports/materialized-prep-time-read-helpers.test.js +620 -0
  45. package/lib/tests/offers-helpers-points-evidence.test.d.ts +1 -0
  46. package/lib/tests/offers-helpers-points-evidence.test.js +338 -0
  47. package/lib/tests/offers-matrix.test.d.ts +1 -0
  48. package/lib/tests/offers-matrix.test.js +401 -0
  49. package/package.json +1 -1
  50. package/esm/schemas/models/rewards_usage.js +0 -61
  51. package/lib/schemas/models/rewards_usage.d.ts +0 -53
  52. package/lib/schemas/models/rewards_usage.js +0 -64
  53. package/lib/schemas/types/rewards_usage.d.ts +0 -13
  54. package/lib/schemas/types/rewards_usage.js +0 -2
  55. /package/{esm/schemas/types/rewards_usage.js → lib/tests/materialized-reports/materialized-prep-time-duration-consistency.test.d.ts} +0 -0
@@ -0,0 +1,639 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withoutMaterializedPrepTimeAnchorFilter = void 0;
4
+ exports.parseMaterializedPrepTimeReadFilters = parseMaterializedPrepTimeReadFilters;
5
+ exports.buildMaterializedPrepTimeFilterSignature = buildMaterializedPrepTimeFilterSignature;
6
+ exports.isMaterializedPrepTimeLateRow = isMaterializedPrepTimeLateRow;
7
+ exports.isMaterializedPrepTimeDurationCountable = isMaterializedPrepTimeDurationCountable;
8
+ exports.filterMaterializedPrepTimeRowsByAnchor = filterMaterializedPrepTimeRowsByAnchor;
9
+ exports.matchesMaterializedPrepTimeReadFilters = matchesMaterializedPrepTimeReadFilters;
10
+ exports.applyMaterializedPrepTimeReadFilters = applyMaterializedPrepTimeReadFilters;
11
+ exports.buildMaterializedPrepTimeCoverage = buildMaterializedPrepTimeCoverage;
12
+ exports.getMaterializedPrepTimePercentile = getMaterializedPrepTimePercentile;
13
+ exports.getMaterializedPrepTimeMedian = getMaterializedPrepTimeMedian;
14
+ exports.getMaterializedPrepTimeP90 = getMaterializedPrepTimeP90;
15
+ exports.groupMaterializedPrepTimeItemRows = groupMaterializedPrepTimeItemRows;
16
+ exports.isMaterializedPrepTimeItemSort = isMaterializedPrepTimeItemSort;
17
+ exports.getMaterializedPrepTimeItemSortValue = getMaterializedPrepTimeItemSortValue;
18
+ exports.compareMaterializedPrepTimeItemRows = compareMaterializedPrepTimeItemRows;
19
+ exports.sortMaterializedPrepTimeItemRows = sortMaterializedPrepTimeItemRows;
20
+ exports.getMaterializedPrepTimeItemPage = getMaterializedPrepTimeItemPage;
21
+ exports.buildMaterializedPrepTimeItemsPage = buildMaterializedPrepTimeItemsPage;
22
+ exports.groupMaterializedPrepTimeCategoryRows = groupMaterializedPrepTimeCategoryRows;
23
+ exports.buildMaterializedPrepTimeCategoriesResult = buildMaterializedPrepTimeCategoriesResult;
24
+ exports.groupMaterializedPrepTimeSeriesPoints = groupMaterializedPrepTimeSeriesPoints;
25
+ exports.buildMaterializedPrepTimeSeriesResult = buildMaterializedPrepTimeSeriesResult;
26
+ const order_1 = require("../../constants/enums/order");
27
+ const platform_1 = require("../../constants/enums/platform");
28
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
29
+ const materialized_reports_apis_1 = require("../types/materialized-reports-apis");
30
+ const MEASURED = MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ANCHOR_ENUM.MEASURED;
31
+ const UNMEASURED = MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ANCHOR_ENUM.UNMEASURED;
32
+ const round1 = (value) => Math.round(value * 10) / 10;
33
+ const toEpochMs = (value) => {
34
+ if (value == null)
35
+ return null;
36
+ if (value instanceof Date) {
37
+ const ms = value.getTime();
38
+ return Number.isNaN(ms) ? null : ms;
39
+ }
40
+ if (typeof value === 'string' || typeof value === 'number') {
41
+ const ms = new Date(value).getTime();
42
+ return Number.isNaN(ms) ? null : ms;
43
+ }
44
+ return null;
45
+ };
46
+ const asString = (value) => (typeof value === 'string' ? value : '');
47
+ const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
48
+ const isRealLocalDate = (value) => {
49
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value))
50
+ return false;
51
+ const date = new Date(value + 'T00:00:00.000Z');
52
+ return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
53
+ };
54
+ const compareStrings = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
55
+ const EMPTY_FILTERS = {
56
+ platforms: null,
57
+ order_statuses: null,
58
+ category_names: null,
59
+ search: null,
60
+ late_only: false,
61
+ anchor: null,
62
+ };
63
+ const parseEnumArray = (value, allowed) => {
64
+ if (value === undefined || value === null)
65
+ return { ok: true, value: null };
66
+ if (!Array.isArray(value))
67
+ return { ok: false };
68
+ if (value.length === 0)
69
+ return { ok: true, value: null };
70
+ const seen = new Set();
71
+ for (const entry of value) {
72
+ if (typeof entry !== 'string')
73
+ return { ok: false };
74
+ const normalized = entry.trim();
75
+ if (normalized === '' || !allowed.includes(normalized))
76
+ return { ok: false };
77
+ seen.add(normalized);
78
+ }
79
+ return { ok: true, value: [...seen].sort(compareStrings) };
80
+ };
81
+ const parseExactNames = (value) => {
82
+ if (value === undefined || value === null)
83
+ return { ok: true, value: null };
84
+ if (!Array.isArray(value))
85
+ return { ok: false };
86
+ if (value.length === 0)
87
+ return { ok: true, value: null };
88
+ const seen = new Set();
89
+ for (const entry of value) {
90
+ if (typeof entry !== 'string' || entry === '')
91
+ return { ok: false };
92
+ seen.add(entry);
93
+ }
94
+ return { ok: true, value: [...seen].sort(compareStrings) };
95
+ };
96
+ /**
97
+ * Validates and NORMALIZES the request `filters` object. Never throws.
98
+ *
99
+ * `category_names` is ignored by the categories read (the read groups BY
100
+ * category, so a category filter would only hide the other cards) — the caller
101
+ * passes `ignoreCategoryNames` there.
102
+ */
103
+ function parseMaterializedPrepTimeReadFilters(value, options = {}) {
104
+ if (value === undefined || value === null)
105
+ return { ok: true, filters: { ...EMPTY_FILTERS } };
106
+ if (typeof value !== 'object' || Array.isArray(value))
107
+ return { ok: false };
108
+ const raw = value;
109
+ const platforms = parseEnumArray(raw.platforms, platform_1.ALL_PLATFORMS);
110
+ if (!platforms.ok)
111
+ return { ok: false };
112
+ const orderStatuses = parseEnumArray(raw.order_statuses, order_1.ALL_ORDER_STATUS_NAMES);
113
+ if (!orderStatuses.ok)
114
+ return { ok: false };
115
+ const categoryNames = options.ignoreCategoryNames
116
+ ? { ok: true, value: null }
117
+ : parseExactNames(raw.category_names);
118
+ if (!categoryNames.ok)
119
+ return { ok: false };
120
+ let search = null;
121
+ if (raw.search !== undefined && raw.search !== null) {
122
+ if (typeof raw.search !== 'string')
123
+ return { ok: false };
124
+ const trimmed = raw.search.trim();
125
+ if (trimmed.length > 200)
126
+ return { ok: false };
127
+ search = trimmed === '' ? null : trimmed;
128
+ }
129
+ let lateOnly = false;
130
+ if (raw.late_only !== undefined && raw.late_only !== null) {
131
+ if (typeof raw.late_only !== 'boolean')
132
+ return { ok: false };
133
+ lateOnly = raw.late_only;
134
+ }
135
+ let anchor = null;
136
+ if (raw.anchor !== undefined && raw.anchor !== null) {
137
+ if (raw.anchor !== MEASURED && raw.anchor !== UNMEASURED)
138
+ return { ok: false };
139
+ anchor = raw.anchor;
140
+ }
141
+ return {
142
+ ok: true,
143
+ filters: {
144
+ platforms: platforms.value,
145
+ order_statuses: orderStatuses.value,
146
+ category_names: categoryNames.value,
147
+ search,
148
+ late_only: lateOnly,
149
+ anchor,
150
+ },
151
+ };
152
+ }
153
+ /** Stable representation of normalized filters (cursor signature input). */
154
+ function buildMaterializedPrepTimeFilterSignature(filters) {
155
+ const normalized = filters ?? EMPTY_FILTERS;
156
+ const sortedOrNull = (values) => values == null ? null : [...new Set(values)].sort(compareStrings);
157
+ return JSON.stringify({
158
+ platforms: sortedOrNull(normalized.platforms),
159
+ order_statuses: sortedOrNull(normalized.order_statuses),
160
+ category_names: sortedOrNull(normalized.category_names),
161
+ search: normalized.search ?? null,
162
+ late_only: normalized.late_only === true,
163
+ anchor: normalized.anchor ?? null,
164
+ });
165
+ }
166
+ /* ======================================================================== */
167
+ /* Row filtering */
168
+ /* ======================================================================== */
169
+ const rowAnchor = (row) => row.anchor === MEASURED ? MEASURED : UNMEASURED;
170
+ /** True when the row is a late, measured, graded row. */
171
+ function isMaterializedPrepTimeLateRow(row) {
172
+ if (rowAnchor(row) !== MEASURED)
173
+ return false;
174
+ const delta = row.delta_minutes;
175
+ return typeof delta === 'number' && Number.isFinite(delta) && delta > MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA;
176
+ }
177
+ /** True when the row is MEASURED and its duration may feed avg / median / p90. */
178
+ function isMaterializedPrepTimeDurationCountable(minutes) {
179
+ return (typeof minutes === 'number' &&
180
+ Number.isFinite(minutes) &&
181
+ minutes >= 0 &&
182
+ minutes <= MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_MAX_MINUTES);
183
+ }
184
+ /**
185
+ * MEASURED / UNMEASURED row split. `anchor` null (or omitted) keeps BOTH
186
+ * populations — the categories / series default.
187
+ */
188
+ function filterMaterializedPrepTimeRowsByAnchor(rows, anchor) {
189
+ const input = Array.isArray(rows) ? rows : [];
190
+ if (anchor !== MEASURED && anchor !== UNMEASURED)
191
+ return input.slice();
192
+ return input.filter((row) => rowAnchor(row) === anchor);
193
+ }
194
+ /** True when one row passes every supplied filter. */
195
+ function matchesMaterializedPrepTimeReadFilters(row, filters) {
196
+ if (row == null)
197
+ return false;
198
+ const search = filters?.search;
199
+ const platforms = filters?.platforms;
200
+ const orderStatuses = filters?.order_statuses;
201
+ const categoryNames = filters?.category_names;
202
+ const anchor = filters?.anchor;
203
+ if (platforms != null && platforms.length > 0 && !platforms.includes(asString(row.platform))) {
204
+ return false;
205
+ }
206
+ if (orderStatuses != null &&
207
+ orderStatuses.length > 0 &&
208
+ !orderStatuses.includes(asString(row.order_status))) {
209
+ return false;
210
+ }
211
+ if (categoryNames != null && categoryNames.length > 0) {
212
+ if (!isNonEmptyString(row.category_name) || !categoryNames.includes(row.category_name)) {
213
+ return false;
214
+ }
215
+ }
216
+ if (search != null && search !== '') {
217
+ const needle = search.toLowerCase();
218
+ const itemName = asString(row.item_name).toLowerCase();
219
+ const categoryName = asString(row.category_name).toLowerCase();
220
+ if (!itemName.includes(needle) && !categoryName.includes(needle))
221
+ return false;
222
+ }
223
+ if (filters?.late_only === true && !isMaterializedPrepTimeLateRow(row))
224
+ return false;
225
+ if ((anchor === MEASURED || anchor === UNMEASURED) && rowAnchor(row) !== anchor)
226
+ return false;
227
+ return true;
228
+ }
229
+ /** Returns only the rows that pass the filters (filters apply BEFORE grouping). */
230
+ function applyMaterializedPrepTimeReadFilters(rows, filters) {
231
+ const input = Array.isArray(rows) ? rows : [];
232
+ if (filters == null)
233
+ return input.slice();
234
+ return input.filter((row) => matchesMaterializedPrepTimeReadFilters(row, filters));
235
+ }
236
+ /**
237
+ * The filters minus the ANCHOR view selector.
238
+ *
239
+ * Anchoring selects which rows a view LISTS (Measured / Unmeasured). Coverage is
240
+ * the report's headline, so it is computed over the population BEFORE the anchor
241
+ * view is applied (but after every other filter) — that is how a Measured view
242
+ * can still state "1,192 of 1,552 served items have their own prep clock".
243
+ */
244
+ const withoutMaterializedPrepTimeAnchorFilter = (filters) => ({
245
+ platforms: filters?.platforms ?? null,
246
+ order_statuses: filters?.order_statuses ?? null,
247
+ category_names: filters?.category_names ?? null,
248
+ search: filters?.search ?? null,
249
+ late_only: filters?.late_only === true,
250
+ anchor: null,
251
+ });
252
+ exports.withoutMaterializedPrepTimeAnchorFilter = withoutMaterializedPrepTimeAnchorFilter;
253
+ const freshTotals = () => ({ served: 0, measured: 0, unmeasured: 0 });
254
+ const addTotals = (totals, row) => {
255
+ totals.served += 1;
256
+ if (rowAnchor(row) === MEASURED)
257
+ totals.measured += 1;
258
+ else
259
+ totals.unmeasured += 1;
260
+ };
261
+ const coverageFromTotals = (totals) => ({
262
+ served_count: totals.served,
263
+ measured_count: totals.measured,
264
+ unmeasured_count: totals.unmeasured,
265
+ coverage_percent: totals.served > 0 ? round1((totals.measured / totals.served) * 100) : 0,
266
+ });
267
+ /** Coverage of the supplied population (measured / served, one decimal). */
268
+ function buildMaterializedPrepTimeCoverage(rows) {
269
+ const totals = freshTotals();
270
+ for (const row of Array.isArray(rows) ? rows : []) {
271
+ if (row == null)
272
+ continue;
273
+ addTotals(totals, row);
274
+ }
275
+ return coverageFromTotals(totals);
276
+ }
277
+ /**
278
+ * EXACT percentile of an UNSORTED duration list, linearly interpolated between
279
+ * the two closest ranks (the standard R-7 definition; the median of an even
280
+ * population is the mean of the two middle values). Returns null for an empty
281
+ * population. The result is rounded to one decimal — the underlying stored
282
+ * durations are whole minutes.
283
+ */
284
+ function getMaterializedPrepTimePercentile(values, percentile) {
285
+ const sorted = (Array.isArray(values) ? values : [])
286
+ .filter((value) => typeof value === 'number' && Number.isFinite(value))
287
+ .sort((a, b) => a - b);
288
+ const count = sorted.length;
289
+ if (count === 0)
290
+ return null;
291
+ const p = Math.min(1, Math.max(0, Number.isFinite(percentile) ? percentile : 0));
292
+ if (count === 1)
293
+ return sorted[0];
294
+ const position = (count - 1) * p;
295
+ const lowerIndex = Math.floor(position);
296
+ const upperIndex = Math.ceil(position);
297
+ const lower = sorted[lowerIndex];
298
+ const upper = sorted[upperIndex];
299
+ return round1(lower + (upper - lower) * (position - lowerIndex));
300
+ }
301
+ /** EXACT median (p50), interpolated for even populations. */
302
+ function getMaterializedPrepTimeMedian(values) {
303
+ return getMaterializedPrepTimePercentile(values, 0.5);
304
+ }
305
+ /** EXACT p90 (interpolated). */
306
+ function getMaterializedPrepTimeP90(values) {
307
+ return getMaterializedPrepTimePercentile(values, 0.9);
308
+ }
309
+ const freshMetrics = () => ({
310
+ ...freshTotals(),
311
+ onTime: 0,
312
+ late: 0,
313
+ durations: [],
314
+ });
315
+ const addMetrics = (metrics, row) => {
316
+ addTotals(metrics, row);
317
+ if (rowAnchor(row) !== MEASURED)
318
+ return;
319
+ if (isMaterializedPrepTimeDurationCountable(row.duration_minutes)) {
320
+ metrics.durations.push(row.duration_minutes);
321
+ }
322
+ const delta = row.delta_minutes;
323
+ if (typeof delta === 'number' && Number.isFinite(delta)) {
324
+ if (delta <= MATERIALIZED_REPORTS_1.MATERIALIZED_PREP_TIME_ON_TIME_MAX_DELTA)
325
+ metrics.onTime += 1;
326
+ else
327
+ metrics.late += 1;
328
+ }
329
+ };
330
+ const durationStats = (durations) => {
331
+ const count = durations.length;
332
+ if (count === 0)
333
+ return { avg: null, median: null, p90: null };
334
+ const sum = durations.reduce((total, value) => total + value, 0);
335
+ return {
336
+ avg: round1(sum / count),
337
+ median: getMaterializedPrepTimeMedian(durations),
338
+ p90: getMaterializedPrepTimeP90(durations),
339
+ };
340
+ };
341
+ const freshItemGroup = (itemId) => ({
342
+ item_id: itemId,
343
+ metrics: freshMetrics(),
344
+ orders: new Set(),
345
+ item_name: null,
346
+ name_ms: -1,
347
+ name_order_id: '',
348
+ category_name: null,
349
+ category_ms: -1,
350
+ category_order_id: '',
351
+ last_served_ms: null,
352
+ });
353
+ /**
354
+ * Name / category are taken from the NEWEST row that actually carries one.
355
+ * Rows keep arriving out of order (flat reads have no guaranteed order), so the
356
+ * choice is a deterministic max on `(created_at, order_id)` — never "first seen".
357
+ */
358
+ const noteItemLabels = (group, row, ms) => {
359
+ const at = ms ?? -1;
360
+ const orderId = asString(row.order_id);
361
+ const isNewer = (otherMs, otherOrderId) => at > otherMs || (at === otherMs && orderId > otherOrderId);
362
+ if (isNonEmptyString(row.item_name) && isNewer(group.name_ms, group.name_order_id)) {
363
+ group.item_name = row.item_name;
364
+ group.name_ms = at;
365
+ group.name_order_id = orderId;
366
+ }
367
+ if (isNonEmptyString(row.category_name) && isNewer(group.category_ms, group.category_order_id)) {
368
+ group.category_name = row.category_name;
369
+ group.category_ms = at;
370
+ group.category_order_id = orderId;
371
+ }
372
+ };
373
+ /**
374
+ * Groups filtered rows by `item_id` (never by name). Counts are per ROW, so an
375
+ * item sold on many orders is never collapsed into one sale.
376
+ */
377
+ function groupMaterializedPrepTimeItemRows(rows, filters) {
378
+ const filtered = applyMaterializedPrepTimeReadFilters(rows, filters);
379
+ const groups = new Map();
380
+ for (const row of filtered) {
381
+ if (row == null)
382
+ continue;
383
+ const itemId = asString(row.item_id);
384
+ if (itemId === '')
385
+ continue;
386
+ let group = groups.get(itemId);
387
+ if (group == null) {
388
+ group = freshItemGroup(itemId);
389
+ groups.set(itemId, group);
390
+ }
391
+ addMetrics(group.metrics, row);
392
+ if (isNonEmptyString(row.order_id))
393
+ group.orders.add(row.order_id);
394
+ const ms = toEpochMs(row.created_at);
395
+ noteItemLabels(group, row, ms);
396
+ if (ms != null && (group.last_served_ms == null || ms > group.last_served_ms)) {
397
+ group.last_served_ms = ms;
398
+ }
399
+ }
400
+ const itemRows = [...groups.values()].map((group) => {
401
+ const stats = durationStats(group.metrics.durations);
402
+ const graded = group.metrics.onTime + group.metrics.late;
403
+ return {
404
+ item_id: group.item_id,
405
+ item_name: group.item_name ?? '',
406
+ category_name: group.category_name,
407
+ orders_count: group.orders.size,
408
+ served_count: group.metrics.served,
409
+ measured_count: group.metrics.measured,
410
+ unmeasured_count: group.metrics.unmeasured,
411
+ avg_minutes: stats.avg,
412
+ median_minutes: stats.median,
413
+ p90_minutes: stats.p90,
414
+ on_time_count: group.metrics.onTime,
415
+ late_count: group.metrics.late,
416
+ on_time_percent: graded > 0 ? round1((group.metrics.onTime / graded) * 100) : null,
417
+ last_served_at: group.last_served_ms == null ? null : new Date(group.last_served_ms).toISOString(),
418
+ };
419
+ });
420
+ return itemRows.sort((a, b) => compareStrings(a.item_id, b.item_id));
421
+ }
422
+ /** True when `value` is one of the frozen item sort modes. */
423
+ function isMaterializedPrepTimeItemSort(value) {
424
+ return (typeof value === 'string' &&
425
+ materialized_reports_apis_1.ALL_MATERIALIZED_PREP_TIME_ITEM_SORTS.includes(value));
426
+ }
427
+ /** The sort value of one item row (the cursor stores it verbatim). */
428
+ function getMaterializedPrepTimeItemSortValue(row, sort) {
429
+ switch (sort) {
430
+ case 'avg_desc':
431
+ case 'avg_asc':
432
+ return row.avg_minutes;
433
+ case 'p90_desc':
434
+ return row.p90_minutes;
435
+ case 'on_time_asc':
436
+ return row.on_time_percent;
437
+ case 'name_asc':
438
+ return row.item_name === '' ? null : row.item_name;
439
+ case 'late_desc':
440
+ default:
441
+ return row.late_count;
442
+ }
443
+ }
444
+ const compareNumericKeys = (a, b, direction) => {
445
+ // null (unknown / nothing measured) always sorts LAST, in both directions.
446
+ if (a == null && b == null)
447
+ return 0;
448
+ if (a == null)
449
+ return 1;
450
+ if (b == null)
451
+ return -1;
452
+ return direction === 'desc' ? b - a : a - b;
453
+ };
454
+ const compareNameKeys = (a, b) => {
455
+ const left = a == null || a === '' ? null : a.toLowerCase();
456
+ const right = b == null || b === '' ? null : b.toLowerCase();
457
+ if (left == null && right == null)
458
+ return 0;
459
+ if (left == null)
460
+ return 1;
461
+ if (right == null)
462
+ return -1;
463
+ return compareStrings(left, right);
464
+ };
465
+ const compareSortValues = (a, b, sort) => {
466
+ if (sort === 'name_asc') {
467
+ return compareNameKeys(typeof a === 'string' ? a : null, typeof b === 'string' ? b : null);
468
+ }
469
+ const left = typeof a === 'number' && Number.isFinite(a) ? a : null;
470
+ const right = typeof b === 'number' && Number.isFinite(b) ? b : null;
471
+ return compareNumericKeys(left, right, sort === 'avg_asc' || sort === 'on_time_asc' ? 'asc' : 'desc');
472
+ };
473
+ /** Total comparator: sort value first, `item_id` ascending as the final tie-break. */
474
+ function compareMaterializedPrepTimeItemRows(a, b, sort) {
475
+ const compared = compareSortValues(getMaterializedPrepTimeItemSortValue(a, sort), getMaterializedPrepTimeItemSortValue(b, sort), sort);
476
+ if (compared !== 0)
477
+ return compared;
478
+ return compareStrings(a.item_id, b.item_id);
479
+ }
480
+ /** Stable sort (never mutates the input array). */
481
+ function sortMaterializedPrepTimeItemRows(rows, sort) {
482
+ const mode = isMaterializedPrepTimeItemSort(sort)
483
+ ? sort
484
+ : materialized_reports_apis_1.DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT;
485
+ return (Array.isArray(rows) ? rows : []).slice().sort((a, b) => {
486
+ const compared = compareSortValues(getMaterializedPrepTimeItemSortValue(a, mode), getMaterializedPrepTimeItemSortValue(b, mode), mode);
487
+ if (compared !== 0)
488
+ return compared;
489
+ return compareStrings(a.item_id, b.item_id);
490
+ });
491
+ }
492
+ const compareItemToCursor = (row, sort, cursor) => {
493
+ const compared = compareSortValues(getMaterializedPrepTimeItemSortValue(row, sort), cursor.sort_value, sort);
494
+ if (compared !== 0)
495
+ return compared;
496
+ return compareStrings(row.item_id, cursor.item_id);
497
+ };
498
+ /**
499
+ * Cuts one page strictly AFTER the cursor. Because the comparator is total, no
500
+ * row can be duplicated or skipped between pages.
501
+ */
502
+ function getMaterializedPrepTimeItemPage(rows, sort, cursor, limit = 25) {
503
+ const mode = isMaterializedPrepTimeItemSort(sort)
504
+ ? sort
505
+ : materialized_reports_apis_1.DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT;
506
+ const size = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 0;
507
+ const all = Array.isArray(rows) ? rows : [];
508
+ const remaining = cursor == null ? all.slice() : all.filter((row) => compareItemToCursor(row, mode, cursor) > 0);
509
+ const page = remaining.slice(0, size);
510
+ const last = page[page.length - 1];
511
+ const hasMore = remaining.length > size;
512
+ return {
513
+ rows: page,
514
+ next_cursor: hasMore && last != null
515
+ ? { sort_value: getMaterializedPrepTimeItemSortValue(last, mode), item_id: last.item_id }
516
+ : null,
517
+ };
518
+ }
519
+ /**
520
+ * The complete Items read: filters -> grouping -> stable sort -> cursor page.
521
+ *
522
+ * The LISTED rows follow the anchor view; coverage spans both anchor
523
+ * populations (after every other filter) and is independent of the page window,
524
+ * so the measured view can still show the observed share of the whole period.
525
+ */
526
+ function buildMaterializedPrepTimeItemsPage(args) {
527
+ const filtered = applyMaterializedPrepTimeReadFilters(args.rows, args.filters);
528
+ const coverage = buildMaterializedPrepTimeCoverage(applyMaterializedPrepTimeReadFilters(args.rows, (0, exports.withoutMaterializedPrepTimeAnchorFilter)(args.filters)));
529
+ const sort = isMaterializedPrepTimeItemSort(args.sort)
530
+ ? args.sort
531
+ : materialized_reports_apis_1.DEFAULT_MATERIALIZED_PREP_TIME_ITEM_SORT;
532
+ const grouped = groupMaterializedPrepTimeItemRows(filtered);
533
+ const sorted = sortMaterializedPrepTimeItemRows(grouped, sort);
534
+ const page = getMaterializedPrepTimeItemPage(sorted, sort, args.cursor ?? null, args.limit ?? 25);
535
+ return { rows: page.rows, next_cursor: page.next_cursor, coverage };
536
+ }
537
+ /* ======================================================================== */
538
+ /* Category read */
539
+ /* ======================================================================== */
540
+ /**
541
+ * Groups filtered rows by EXACT `category_name`. Rows without a category are
542
+ * not attributable to a category card and are excluded from this read (and
543
+ * therefore from its coverage); the Items and Series reads still count them.
544
+ *
545
+ * Sort: `measured_count` DESC, then `category_name` ASC (stable by construction
546
+ * — category names are the group identity).
547
+ */
548
+ function groupMaterializedPrepTimeCategoryRows(rows, filters) {
549
+ const filtered = applyMaterializedPrepTimeReadFilters(rows, filters).filter((row) => row != null && isNonEmptyString(row.category_name));
550
+ const groups = new Map();
551
+ for (const row of filtered) {
552
+ const name = row.category_name;
553
+ let metrics = groups.get(name);
554
+ if (metrics == null) {
555
+ metrics = freshMetrics();
556
+ groups.set(name, metrics);
557
+ }
558
+ addMetrics(metrics, row);
559
+ }
560
+ return [...groups.entries()]
561
+ .map(([category_name, metrics]) => {
562
+ const stats = durationStats(metrics.durations);
563
+ const graded = metrics.onTime + metrics.late;
564
+ return {
565
+ category_name,
566
+ served_count: metrics.served,
567
+ measured_count: metrics.measured,
568
+ unmeasured_count: metrics.unmeasured,
569
+ avg_minutes: stats.avg,
570
+ median_minutes: stats.median,
571
+ p90_minutes: stats.p90,
572
+ on_time_count: metrics.onTime,
573
+ late_count: metrics.late,
574
+ on_time_percent: graded > 0 ? round1((metrics.onTime / graded) * 100) : null,
575
+ };
576
+ })
577
+ .sort((a, b) => b.measured_count - a.measured_count || compareStrings(a.category_name, b.category_name));
578
+ }
579
+ /** The complete Categories read (rows + coverage over the same population). */
580
+ function buildMaterializedPrepTimeCategoriesResult(args) {
581
+ const filtered = applyMaterializedPrepTimeReadFilters(args.rows, args.filters).filter((row) => row != null && isNonEmptyString(row.category_name));
582
+ const coverageRows = applyMaterializedPrepTimeReadFilters(args.rows, (0, exports.withoutMaterializedPrepTimeAnchorFilter)(args.filters)).filter((row) => row != null && isNonEmptyString(row.category_name));
583
+ return {
584
+ rows: groupMaterializedPrepTimeCategoryRows(filtered),
585
+ coverage: buildMaterializedPrepTimeCoverage(coverageRows),
586
+ };
587
+ }
588
+ /* ======================================================================== */
589
+ /* Series read */
590
+ /* ======================================================================== */
591
+ /**
592
+ * Groups filtered rows by their SOURCE local date (`YYYY-MM-DD`), ascending.
593
+ *
594
+ * Never derives a day from `created_at` (a UTC day would shift the tenant's
595
+ * evening into the next date) and never emits an empty date. Rows without a
596
+ * valid source date cannot be plotted and are excluded from this read (and its
597
+ * coverage); the day-scoped flat projection always carries one.
598
+ */
599
+ function groupMaterializedPrepTimeSeriesPoints(rows, filters) {
600
+ const filtered = applyMaterializedPrepTimeReadFilters(rows, filters).filter((row) => row != null && isRealLocalDate(row.source_local_date));
601
+ const groups = new Map();
602
+ for (const row of filtered) {
603
+ let metrics = groups.get(row.source_local_date);
604
+ if (metrics == null) {
605
+ metrics = freshMetrics();
606
+ groups.set(row.source_local_date, metrics);
607
+ }
608
+ addMetrics(metrics, row);
609
+ }
610
+ return [...groups.entries()]
611
+ .map(([local_date, metrics]) => {
612
+ const stats = durationStats(metrics.durations);
613
+ return {
614
+ local_date,
615
+ served_count: metrics.served,
616
+ measured_count: metrics.measured,
617
+ unmeasured_count: metrics.unmeasured,
618
+ avg_minutes: stats.avg,
619
+ median_minutes: stats.median,
620
+ p90_minutes: stats.p90,
621
+ on_time_count: metrics.onTime,
622
+ late_count: metrics.late,
623
+ };
624
+ })
625
+ .sort((a, b) => compareStrings(a.local_date, b.local_date));
626
+ }
627
+ /**
628
+ * The complete Series read. `target_minutes` is ALWAYS null: no tenant prep
629
+ * target exists in the read contract yet, and the report must not invent one.
630
+ */
631
+ function buildMaterializedPrepTimeSeriesResult(args) {
632
+ const filtered = applyMaterializedPrepTimeReadFilters(args.rows, args.filters).filter((row) => row != null && isRealLocalDate(row.source_local_date));
633
+ const coverageRows = applyMaterializedPrepTimeReadFilters(args.rows, (0, exports.withoutMaterializedPrepTimeAnchorFilter)(args.filters)).filter((row) => row != null && isRealLocalDate(row.source_local_date));
634
+ return {
635
+ points: groupMaterializedPrepTimeSeriesPoints(filtered),
636
+ coverage: buildMaterializedPrepTimeCoverage(coverageRows),
637
+ target_minutes: null,
638
+ };
639
+ }
@@ -844,15 +844,6 @@ function areRedeemedOffersEqualForOfferSync(currentRedeemedOffers, nextRedeemedO
844
844
  }
845
845
  return true;
846
846
  }
847
- function getItemRewardApplicableQuantityForOfferSync(offer) {
848
- if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.ITEMS) {
849
- return toPositiveInteger(offer.reward_items?.num_of_items, 1);
850
- }
851
- if (offer.reward_type === constants_1.OFFER_REWARD_TYPE_ENUM.DISCOUNT_ITEMS) {
852
- return toPositiveInteger(offer.reward_discount_items?.num_of_items, 1);
853
- }
854
- return null;
855
- }
856
847
  function getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, offerId) {
857
848
  let totalSelectedOfferItems = 0;
858
849
  for (let i = 0; i < categories.length; i++) {
@@ -887,7 +878,7 @@ function getReconciledRedeemedOffersMapForOfferSync({ existingRedeemedOffers, ca
887
878
  const normalizedOfferId = getNormalizedOfferId(offer._id);
888
879
  if (normalizedOfferId == null)
889
880
  continue;
890
- const applicableQuantity = getItemRewardApplicableQuantityForOfferSync(offer);
881
+ const applicableQuantity = (0, offers_helpers_1.getOfferRewardApplicableQuantity)(offer);
891
882
  if (applicableQuantity != null) {
892
883
  const selectedItemsCount = getTotalSelectedOfferItemsAgainstOfferForOfferSync(categories, normalizedOfferId);
893
884
  // Any partial usage of an item reward still counts as one redeemed slot.