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