@managesome/eposmatic-toolkit 0.4.60 → 0.4.61

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 (74) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +177 -4
  2. package/esm/helpers/materialized-reports/index.js +7 -0
  3. package/esm/helpers/materialized-reports/materialized-day-readiness.js +2 -2
  4. package/esm/helpers/materialized-reports/materialized-dinein-accumulator-helpers.js +557 -0
  5. package/esm/helpers/materialized-reports/materialized-dinein-classification-helpers.js +447 -0
  6. package/esm/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +372 -0
  7. package/esm/helpers/materialized-reports/materialized-dinein-compile-helpers.js +500 -0
  8. package/esm/helpers/materialized-reports/materialized-dinein-entry-pages.js +218 -0
  9. package/esm/helpers/materialized-reports/materialized-dinein-key-helpers.js +87 -0
  10. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  11. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +8 -0
  12. package/esm/helpers/materialized-reports/report-platform/definition.js +93 -1
  13. package/esm/helpers/materialized-reports/tenant-dinein-formatter.js +240 -0
  14. package/esm/helpers/reporting-contract/report-contract.js +3 -0
  15. package/esm/schemas/models/index.js +2 -0
  16. package/esm/schemas/models/materialized_tenant_dinein_entries.js +57 -0
  17. package/esm/schemas/models/materialized_tenant_dinein_reports.js +73 -0
  18. package/esm/schemas/types/index.js +2 -0
  19. package/esm/schemas/types/materialized_report_drilldown_rows.js +1 -0
  20. package/esm/schemas/types/materialized_tenant_dinein_entries.js +1 -0
  21. package/esm/schemas/types/materialized_tenant_dinein_reports.js +6 -0
  22. package/lib/constants/MATERIALIZED_REPORTS.d.ts +160 -4
  23. package/lib/constants/MATERIALIZED_REPORTS.js +178 -5
  24. package/lib/helpers/materialized-reports/index.d.ts +7 -0
  25. package/lib/helpers/materialized-reports/index.js +7 -0
  26. package/lib/helpers/materialized-reports/materialized-day-readiness.d.ts +1 -1
  27. package/lib/helpers/materialized-reports/materialized-day-readiness.js +2 -2
  28. package/lib/helpers/materialized-reports/materialized-dinein-accumulator-helpers.d.ts +67 -0
  29. package/lib/helpers/materialized-reports/materialized-dinein-accumulator-helpers.js +582 -0
  30. package/lib/helpers/materialized-reports/materialized-dinein-classification-helpers.d.ts +245 -0
  31. package/lib/helpers/materialized-reports/materialized-dinein-classification-helpers.js +469 -0
  32. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.d.ts +110 -0
  33. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +384 -0
  34. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.d.ts +73 -0
  35. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.js +504 -0
  36. package/lib/helpers/materialized-reports/materialized-dinein-entry-pages.d.ts +69 -0
  37. package/lib/helpers/materialized-reports/materialized-dinein-entry-pages.js +231 -0
  38. package/lib/helpers/materialized-reports/materialized-dinein-key-helpers.d.ts +44 -0
  39. package/lib/helpers/materialized-reports/materialized-dinein-key-helpers.js +96 -0
  40. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  41. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +8 -0
  42. package/lib/helpers/materialized-reports/report-platform/definition.js +92 -0
  43. package/lib/helpers/materialized-reports/tenant-dinein-formatter.d.ts +225 -0
  44. package/lib/helpers/materialized-reports/tenant-dinein-formatter.js +243 -0
  45. package/lib/helpers/reporting-contract/report-contract.d.ts +1 -0
  46. package/lib/helpers/reporting-contract/report-contract.js +3 -0
  47. package/lib/schemas/models/index.d.ts +2 -0
  48. package/lib/schemas/models/index.js +2 -0
  49. package/lib/schemas/models/materialized_tenant_day_readiness.d.ts +3 -3
  50. package/lib/schemas/models/materialized_tenant_dinein_entries.d.ts +100 -0
  51. package/lib/schemas/models/materialized_tenant_dinein_entries.js +60 -0
  52. package/lib/schemas/models/materialized_tenant_dinein_reports.d.ts +111 -0
  53. package/lib/schemas/models/materialized_tenant_dinein_reports.js +76 -0
  54. package/lib/schemas/types/index.d.ts +2 -0
  55. package/lib/schemas/types/index.js +2 -0
  56. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +1 -1
  57. package/lib/schemas/types/materialized_report_drilldown_rows.js +1 -0
  58. package/lib/schemas/types/materialized_tenant_dinein_entries.d.ts +127 -0
  59. package/lib/schemas/types/materialized_tenant_dinein_entries.js +2 -0
  60. package/lib/schemas/types/materialized_tenant_dinein_reports.d.ts +326 -0
  61. package/lib/schemas/types/materialized_tenant_dinein_reports.js +9 -0
  62. package/lib/tests/materialized-reports/dinein-fixtures.d.ts +29 -0
  63. package/lib/tests/materialized-reports/dinein-fixtures.js +130 -0
  64. package/lib/tests/materialized-reports/materialized-day-readiness.test.js +3 -2
  65. package/lib/tests/materialized-reports/materialized-dinein-compile.test.d.ts +1 -0
  66. package/lib/tests/materialized-reports/materialized-dinein-compile.test.js +807 -0
  67. package/lib/tests/materialized-reports/materialized-dinein-plan.test.d.ts +1 -0
  68. package/lib/tests/materialized-reports/materialized-dinein-plan.test.js +419 -0
  69. package/lib/tests/materialized-reports/materialized-tenant-dinein-schema.test.d.ts +1 -0
  70. package/lib/tests/materialized-reports/materialized-tenant-dinein-schema.test.js +185 -0
  71. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +15 -2
  72. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.d.ts +1 -0
  73. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.js +299 -0
  74. package/package.json +1 -1
@@ -0,0 +1,504 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.maskReservationGuestLabel = maskReservationGuestLabel;
4
+ exports.compileTenantDineinReports = compileTenantDineinReports;
5
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
6
+ const materialized_tenant_dinein_entries_1 = require("../../schemas/models/materialized_tenant_dinein_entries");
7
+ const materialized_tenant_dinein_reports_1 = require("../../schemas/models/materialized_tenant_dinein_reports");
8
+ const materialized_tenant_dinein_reports_2 = require("../../schemas/types/materialized_tenant_dinein_reports");
9
+ const materialized_dinein_accumulator_helpers_1 = require("./materialized-dinein-accumulator-helpers");
10
+ const materialized_dinein_classification_helpers_1 = require("./materialized-dinein-classification-helpers");
11
+ const materialized_dinein_entry_pages_1 = require("./materialized-dinein-entry-pages");
12
+ const materialized_dinein_key_helpers_1 = require("./materialized-dinein-key-helpers");
13
+ const materialized_document_size_1 = require("./materialized-document-size");
14
+ const scope_helpers_1 = require("./scope-helpers");
15
+ const text = (value) => (value == null ? '' : String(value).trim());
16
+ /**
17
+ * An OPTIONAL order number.
18
+ *
19
+ * `Number(null)` is 0, so a missing number must be rejected explicitly — a
20
+ * check without a number is `null` on the wire, never `#0`.
21
+ */
22
+ const optionalOrderNumber = (value) => {
23
+ if (value == null || value === '')
24
+ return null;
25
+ const numeric = Number(value);
26
+ return Number.isInteger(numeric) ? numeric : null;
27
+ };
28
+ const byIdAsc = (a, b) => {
29
+ const left = text(a?._id);
30
+ const right = text(b?._id);
31
+ return left < right ? -1 : left > right ? 1 : 0;
32
+ };
33
+ const laterOf = (current, candidate) => {
34
+ const time = candidate == null ? NaN : new Date(candidate).getTime();
35
+ if (Number.isNaN(time))
36
+ return current;
37
+ return time > current.getTime() ? new Date(time) : current;
38
+ };
39
+ /** The tenant-local hour (`0`..`23`) of an instant, or null when unusable. */
40
+ function tenantLocalHourOf(value, gmtOffset) {
41
+ const date = (0, materialized_dinein_classification_helpers_1.toDineinDate)(value);
42
+ if (date == null || !Number.isFinite(gmtOffset))
43
+ return null;
44
+ const shifted = new Date(date.getTime() + Math.round(gmtOffset * 60 * 60 * 1000));
45
+ return shifted.getUTCHours();
46
+ }
47
+ /**
48
+ * The server-side MASKED guest label for an upcoming reservation.
49
+ *
50
+ * Only initials are emitted (at most two, `A. K.`), never the full name, and
51
+ * `Guest` when the source carries nothing usable. The frontend never receives
52
+ * the name, phone or email.
53
+ */
54
+ function maskReservationGuestLabel(name) {
55
+ const words = text(name)
56
+ .split(/\s+/)
57
+ // Only NAME words contribute: a digit / symbol token is not an initial.
58
+ .filter((word) => /^[A-Za-z]/.test(word));
59
+ const initials = words
60
+ .slice(0, 2)
61
+ .map((word) => word[0].toUpperCase() + '.')
62
+ .join(' ');
63
+ return initials === '' ? 'Guest' : initials;
64
+ }
65
+ /** Compiles one business day into a counter document plus its entry pages. */
66
+ function compileTenantDineinReports(input) {
67
+ var _a;
68
+ if (input == null)
69
+ return null;
70
+ const { tenantId, brandId, localDate } = input;
71
+ if (typeof tenantId !== 'string' ||
72
+ tenantId === '' ||
73
+ typeof brandId !== 'string' ||
74
+ typeof localDate !== 'string' ||
75
+ (0, scope_helpers_1.parseMaterializedLocalDate)(localDate) == null) {
76
+ return null;
77
+ }
78
+ const computedAt = input.computedAt ?? new Date();
79
+ const gmtOffset = Number.isFinite(Number(input.gmtOffset)) ? Number(input.gmtOffset) : 0;
80
+ const coverage = (0, materialized_dinein_classification_helpers_1.freshDineinCoverage)();
81
+ let watermark = computedAt;
82
+ /* -------------------- split parents (rating discovery only) -------------------- */
83
+ const parentById = new Map();
84
+ for (const parent of input.deletedSplitParents ?? []) {
85
+ if (parent == null)
86
+ continue;
87
+ if (String(parent.tenant_id ?? tenantId) !== tenantId)
88
+ continue;
89
+ if (!(0, materialized_dinein_classification_helpers_1.isDineinOrder)(parent))
90
+ continue;
91
+ if (!(0, materialized_dinein_classification_helpers_1.isDeletedSplitParent)(parent))
92
+ continue;
93
+ const id = text(parent._id);
94
+ if (id === '')
95
+ continue;
96
+ parentById.set(id, parent);
97
+ }
98
+ coverage.deleted_split_parents_excluded = parentById.size;
99
+ for (const parent of parentById.values())
100
+ watermark = laterOf(watermark, parent.updatedAt ?? parent.createdAt);
101
+ /* -------------------- the count population -------------------- */
102
+ const counted = [];
103
+ const countedById = new Map();
104
+ for (const order of input.orders ?? []) {
105
+ if (order == null)
106
+ continue;
107
+ if (String(order.tenant_id ?? tenantId) !== tenantId)
108
+ continue;
109
+ if (!(0, materialized_dinein_classification_helpers_1.isDineinOrder)(order))
110
+ continue;
111
+ // The deleted split parent is NEVER a collectable check, even when the
112
+ // caller passes it in the regular orders array.
113
+ if (order.is_deleted === true)
114
+ continue;
115
+ const id = text(order._id);
116
+ if (id === '' || countedById.has(id))
117
+ continue;
118
+ const day = text(order.localDate);
119
+ if (day !== '' && day !== localDate) {
120
+ coverage.orders_out_of_day += 1;
121
+ continue;
122
+ }
123
+ if ((0, materialized_dinein_classification_helpers_1.toDineinDate)(order.createdAt) == null && (0, materialized_dinein_classification_helpers_1.toDineinDate)(order.updatedAt) == null)
124
+ continue;
125
+ countedById.set(id, order);
126
+ counted.push(order);
127
+ }
128
+ counted.sort(byIdAsc);
129
+ coverage.orders_counted = counted.length;
130
+ /* -------------------- fingerprints → table sessions -------------------- */
131
+ const fingerprintById = new Map();
132
+ for (const fingerprint of input.fingerprints ?? []) {
133
+ if (fingerprint == null)
134
+ continue;
135
+ if (String(fingerprint.tenant_id ?? tenantId) !== tenantId)
136
+ continue;
137
+ const id = text(fingerprint._id);
138
+ if (id === '')
139
+ continue;
140
+ if (fingerprintById.has(id)) {
141
+ coverage.fingerprints_duplicate += 1;
142
+ continue;
143
+ }
144
+ fingerprintById.set(id, fingerprint);
145
+ }
146
+ coverage.fingerprints_total = fingerprintById.size;
147
+ const fingerprintsByOrder = new Map();
148
+ for (const fingerprint of fingerprintById.values()) {
149
+ watermark = laterOf(watermark, fingerprint.updatedAt ?? fingerprint.createdAt);
150
+ const orderId = text(fingerprint.order_id);
151
+ const order = orderId === '' ? null : countedById.get(orderId);
152
+ if (order == null) {
153
+ coverage.fingerprints_unattached += 1;
154
+ continue;
155
+ }
156
+ const bucket = fingerprintsByOrder.get(orderId);
157
+ if (bucket == null)
158
+ fingerprintsByOrder.set(orderId, [fingerprint]);
159
+ else
160
+ bucket.push(fingerprint);
161
+ }
162
+ const sessionsByOrder = new Map();
163
+ const coversByOrder = new Map();
164
+ for (const order of counted) {
165
+ const orderId = text(order._id);
166
+ const key = (0, materialized_dinein_key_helpers_1.buildMaterializedDineinKey)(order.order_status, order.platform);
167
+ const fingerprints = (fingerprintsByOrder.get(orderId) ?? [])
168
+ .slice()
169
+ .sort((a, b) => ((0, materialized_dinein_classification_helpers_1.toDineinDate)(a.createdAt)?.getTime() ?? 0) - ((0, materialized_dinein_classification_helpers_1.toDineinDate)(b.createdAt)?.getTime() ?? 0) || byIdAsc(a, b));
170
+ if (fingerprints.length === 0) {
171
+ coverage.orders_without_fingerprint += 1;
172
+ sessionsByOrder.set(orderId, []);
173
+ coversByOrder.set(orderId, 0);
174
+ continue;
175
+ }
176
+ const sessions = [];
177
+ for (const fingerprint of fingerprints) {
178
+ const end = (0, materialized_dinein_classification_helpers_1.toDineinDate)(fingerprint.createdAt);
179
+ if (end == null) {
180
+ coverage.fingerprints_missing_end += 1;
181
+ continue;
182
+ }
183
+ const realStart = (0, materialized_dinein_classification_helpers_1.toDineinDate)(order.dinein_details?.start_time);
184
+ const fallbackStart = (0, materialized_dinein_classification_helpers_1.toDineinDate)(order.createdAt);
185
+ const start = realStart ?? fallbackStart;
186
+ if (start == null) {
187
+ coverage.fingerprints_missing_start += 1;
188
+ continue;
189
+ }
190
+ const durationMinutes = Math.round((end.getTime() - start.getTime()) / 60000);
191
+ if (durationMinutes < 0) {
192
+ coverage.fingerprints_negative_duration += 1;
193
+ continue;
194
+ }
195
+ const fallback = realStart == null;
196
+ if (fallback)
197
+ coverage.fingerprints_fallback_start += 1;
198
+ coverage.fingerprints_joined += 1;
199
+ const tableId = text(fingerprint.table_id) || text(order.dinein_details?.table_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
200
+ const floorId = text(fingerprint.dinein_floor_id) || text(order.dinein_details?.floor_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
201
+ sessions.push({
202
+ fingerprint_id: text(fingerprint._id),
203
+ order_id: orderId,
204
+ table_id: tableId,
205
+ table_name: text(fingerprint.name) || text(order.dinein_details?.table_name),
206
+ floor_id: floorId,
207
+ guests: Math.max(0, (0, materialized_dinein_classification_helpers_1.toDineinInt)(fingerprint.num_of_guests)),
208
+ start,
209
+ end,
210
+ duration_minutes: durationMinutes,
211
+ fallback_start: fallback,
212
+ key,
213
+ });
214
+ }
215
+ sessionsByOrder.set(orderId, sessions);
216
+ // COVERS: the check's SETTLING session (the last valid table close), so a
217
+ // party that moved tables is still counted once. Never `num_of_guests`.
218
+ const settling = sessions.length === 0 ? null : sessions[sessions.length - 1];
219
+ coversByOrder.set(orderId, settling == null ? 0 : settling.guests);
220
+ }
221
+ /* -------------------- ratings (own, or inherited from a split parent) -------------------- */
222
+ const childrenByParent = new Map();
223
+ for (const order of counted) {
224
+ const parentId = text(order.split_parent_id);
225
+ if (parentId === '')
226
+ continue;
227
+ const bucket = childrenByParent.get(parentId);
228
+ if (bucket == null)
229
+ childrenByParent.set(parentId, [order]);
230
+ else
231
+ bucket.push(order);
232
+ }
233
+ const inheritedRating = new Map();
234
+ for (const [parentId, children] of childrenByParent) {
235
+ const parentRating = (0, materialized_dinein_classification_helpers_1.validRatingOf)(parentById.get(parentId)?.rating);
236
+ if (parentRating == null)
237
+ continue;
238
+ // ONE child inherits the parent rating (the smallest order id), so a rating
239
+ // written once on the parent is never counted once per child.
240
+ const chosen = [...children].sort(byIdAsc)[0];
241
+ if (chosen == null)
242
+ continue;
243
+ if ((0, materialized_dinein_classification_helpers_1.validRatingOf)(chosen.rating) != null)
244
+ continue;
245
+ inheritedRating.set(text(chosen._id), parentRating);
246
+ coverage.ratings_from_deleted_parents += 1;
247
+ }
248
+ /* -------------------- accumulate counters + rows -------------------- */
249
+ const countersByKey = new Map();
250
+ const rowsByKey = new Map();
251
+ for (const order of counted) {
252
+ const orderId = text(order._id);
253
+ const key = (0, materialized_dinein_key_helpers_1.buildMaterializedDineinKey)(order.order_status, order.platform);
254
+ const counters = countersByKey.get(key) ?? (0, materialized_dinein_accumulator_helpers_1.freshMaterializedDineinCounters)();
255
+ countersByKey.set(key, counters);
256
+ const parentId = text(order.split_parent_id);
257
+ const parent = parentId === '' ? null : (parentById.get(parentId) ?? null);
258
+ const splitType = parentId === '' ? null : text(parent?.split_type) || text(order.split_type) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
259
+ const rating = (0, materialized_dinein_classification_helpers_1.validRatingOf)(order.rating) ?? inheritedRating.get(orderId) ?? null;
260
+ const covers = coversByOrder.get(orderId) ?? 0;
261
+ (0, materialized_dinein_classification_helpers_1.addDineinOrderToCounters)({
262
+ counters,
263
+ order,
264
+ covers,
265
+ sessions: sessionsByOrder.get(orderId) ?? [],
266
+ rating,
267
+ splitType,
268
+ });
269
+ watermark = laterOf(watermark, order.updatedAt ?? order.createdAt);
270
+ const time = (0, materialized_dinein_classification_helpers_1.toDineinDate)(order.createdAt) ?? (0, materialized_dinein_classification_helpers_1.toDineinDate)(order.updatedAt);
271
+ if (time == null)
272
+ continue;
273
+ const row = {
274
+ order_id: orderId,
275
+ order_number: optionalOrderNumber(order.order_number),
276
+ localDate: text(order.localDate) || localDate,
277
+ time: time.toISOString(),
278
+ table_id: text(order.dinein_details?.table_id) || null,
279
+ table_name: text(order.dinein_details?.table_name) || null,
280
+ floor_id: text(order.dinein_details?.floor_id) || null,
281
+ covers,
282
+ status: text(order.order_status) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN,
283
+ platform: text(order.platform) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN,
284
+ origin: (0, materialized_dinein_classification_helpers_1.classifyMaterializedDineinOrigin)(order),
285
+ split_type: splitType,
286
+ split_role: (0, materialized_dinein_classification_helpers_1.splitRoleOf)(order),
287
+ offline: order.synced_offline === true,
288
+ rating,
289
+ sales: (0, materialized_dinein_classification_helpers_1.toDineinInt)(order.amount_earned),
290
+ service_charge: (0, materialized_dinein_classification_helpers_1.toDineinInt)(order.service_fee_amount),
291
+ items: (0, materialized_dinein_classification_helpers_1.itemQuantityOf)(order),
292
+ edits: Array.isArray(order.iterations) ? order.iterations.length : 0,
293
+ };
294
+ const bucket = rowsByKey.get(key);
295
+ if (bucket == null)
296
+ rowsByKey.set(key, [row]);
297
+ else
298
+ bucket.push(row);
299
+ }
300
+ /* -------------------- most-edited checks (bounded snapshot) -------------------- */
301
+ const topEditedChecks = [];
302
+ for (const order of counted) {
303
+ const edits = Array.isArray(order.iterations) ? order.iterations.length : 0;
304
+ if (edits === 0)
305
+ continue;
306
+ // The SAME line-delta helper the counters use, so the snapshot can never
307
+ // disagree with `item_additions` / `item_removals`.
308
+ let additions = 0;
309
+ let removals = 0;
310
+ const versions = [
311
+ ...(Array.isArray(order.iterations) ? [...order.iterations].reverse() : []),
312
+ order,
313
+ ];
314
+ for (let index = 1; index < versions.length; index += 1) {
315
+ const delta = (0, materialized_dinein_classification_helpers_1.itemLineDelta)(versions[index - 1], versions[index]);
316
+ additions += delta.additions;
317
+ removals += delta.removals;
318
+ }
319
+ topEditedChecks.push({
320
+ order_id: text(order._id),
321
+ order_number: optionalOrderNumber(order.order_number),
322
+ table_id: text(order.dinein_details?.table_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN,
323
+ table_name: text(order.dinein_details?.table_name),
324
+ floor_id: text(order.dinein_details?.floor_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN,
325
+ edits,
326
+ item_additions: additions,
327
+ item_removals: removals,
328
+ covers: coversByOrder.get(text(order._id)) ?? 0,
329
+ sales: (0, materialized_dinein_classification_helpers_1.toDineinInt)(order.amount_earned),
330
+ });
331
+ }
332
+ /* -------------------- split parents per key + split_checks -------------------- */
333
+ // A parent is attributed to the key of its DETERMINISTIC FIRST counted child,
334
+ // so a group whose children land in several keys never counts its parent twice.
335
+ for (const children of childrenByParent.values()) {
336
+ const chosen = [...children].sort(byIdAsc)[0];
337
+ if (chosen == null)
338
+ continue;
339
+ const key = (0, materialized_dinein_key_helpers_1.buildMaterializedDineinKey)(chosen.order_status, chosen.platform);
340
+ const counters = countersByKey.get(key);
341
+ if (counters == null)
342
+ continue;
343
+ counters.split_parents += 1;
344
+ }
345
+ for (const counters of countersByKey.values()) {
346
+ counters.split_checks = counters.split_parents + counters.split_children;
347
+ }
348
+ /* -------------------- reservations -------------------- */
349
+ const reservationCounters = (0, materialized_dinein_accumulator_helpers_1.freshMaterializedDineinReservationCounters)();
350
+ const upcomingReservations = [];
351
+ for (const reservation of input.reservations ?? []) {
352
+ if (reservation == null)
353
+ continue;
354
+ if (String(reservation.tenant_id ?? tenantId) !== tenantId)
355
+ continue;
356
+ const sourceDay = text(reservation.source_local_date);
357
+ if (sourceDay !== '' && sourceDay !== localDate) {
358
+ coverage.reservations_out_of_day += 1;
359
+ continue;
360
+ }
361
+ const reservationTime = (0, materialized_dinein_classification_helpers_1.toDineinDate)(reservation.reservation_time);
362
+ if (reservationTime == null) {
363
+ coverage.reservations_missing_time += 1;
364
+ continue;
365
+ }
366
+ coverage.reservations_counted += 1;
367
+ watermark = laterOf(watermark, reservation.updatedAt ?? reservation.createdAt);
368
+ reservationCounters.reservations += 1;
369
+ reservationCounters.reservation_covers += Math.max(0, (0, materialized_dinein_classification_helpers_1.toDineinInt)(reservation.num_of_guests));
370
+ const status = text(reservation.reservation_status).toUpperCase();
371
+ if (status === 'CONFIRMED')
372
+ reservationCounters.reservation_confirmed += 1;
373
+ else if (status === 'PENDING')
374
+ reservationCounters.reservation_pending += 1;
375
+ else if (status === 'CANCELLED')
376
+ reservationCounters.reservation_cancelled += 1;
377
+ const createdAt = (0, materialized_dinein_classification_helpers_1.toDineinDate)(reservation.createdAt);
378
+ if (createdAt != null) {
379
+ const leadMinutes = Math.round((reservationTime.getTime() - createdAt.getTime()) / 60000);
380
+ // A booking created AFTER its slot has no lead time; it is not clamped to 0.
381
+ if (leadMinutes >= 0) {
382
+ reservationCounters.reservation_lead_minutes_sum += leadMinutes;
383
+ reservationCounters.reservation_lead_count += 1;
384
+ }
385
+ }
386
+ const duration = (0, materialized_dinein_classification_helpers_1.toDineinInt)(reservation.reservation_duration);
387
+ if (duration >= 0) {
388
+ reservationCounters.reservation_duration_minutes_sum += duration;
389
+ reservationCounters.reservation_duration_count += 1;
390
+ }
391
+ // The reservation chart is folded from THIS map, never from order hours.
392
+ const localHour = tenantLocalHourOf(reservationTime, gmtOffset);
393
+ if (localHour != null && MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_HOUR_KEYS.includes(String(localHour))) {
394
+ const hourKey = String(localHour);
395
+ const hourRow = ((_a = reservationCounters.by_hour)[hourKey] ?? (_a[hourKey] = {
396
+ reservations: 0,
397
+ reservation_covers: 0,
398
+ }));
399
+ hourRow.reservations += 1;
400
+ hourRow.reservation_covers += Math.max(0, (0, materialized_dinein_classification_helpers_1.toDineinInt)(reservation.num_of_guests));
401
+ }
402
+ // Bounded, MASKED snapshot row (no name / phone / email).
403
+ const leadMinutes = createdAt == null ? null : Math.round((reservationTime.getTime() - createdAt.getTime()) / 60000);
404
+ upcomingReservations.push({
405
+ reservation_id: text(reservation._id),
406
+ guest_label: maskReservationGuestLabel(reservation.customer_name),
407
+ reservation_time: reservationTime.toISOString(),
408
+ local_hour: localHour == null ? 0 : localHour,
409
+ party_size: Math.max(0, (0, materialized_dinein_classification_helpers_1.toDineinInt)(reservation.num_of_guests)),
410
+ status,
411
+ source: text(reservation.order_from) || 'UNKNOWN',
412
+ lead_minutes: leadMinutes != null && leadMinutes >= 0 ? leadMinutes : null,
413
+ });
414
+ }
415
+ if (counted.length === 0 && reservationCounters.reservations === 0)
416
+ return null;
417
+ /* -------------------- bound the document maps -------------------- */
418
+ (0, materialized_dinein_accumulator_helpers_1.pruneDocumentDineinMaps)(countersByKey);
419
+ const sortedKeys = [...countersByKey.keys()].sort();
420
+ const dineinCounters = {};
421
+ for (const key of sortedKeys)
422
+ dineinCounters[key] = countersByKey.get(key);
423
+ const dayIndex = (0, scope_helpers_1.getDayIndexFromLocalDate)(localDate);
424
+ const reports = [
425
+ {
426
+ _id: undefined,
427
+ tenant_id: tenantId,
428
+ brand_id: brandId,
429
+ scope_context: MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
430
+ scope_field: localDate,
431
+ day_index: dayIndex,
432
+ sale_type_key_filters: [...materialized_tenant_dinein_reports_2.MATERIALIZED_DINEIN_REPORT_KEY_FILTERS],
433
+ dinein_counters: dineinCounters,
434
+ reservation_counters: reservationCounters,
435
+ upcoming_reservations: (0, materialized_dinein_accumulator_helpers_1.mergeMaterializedDineinUpcomingReservations)([upcomingReservations], MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UPCOMING_RESERVATION_LIMIT),
436
+ top_edited_checks: (0, materialized_dinein_accumulator_helpers_1.mergeMaterializedDineinTopEditedChecks)([topEditedChecks], MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_TOP_EDITED_CHECK_LIMIT),
437
+ schema_version: materialized_tenant_dinein_reports_1.MATERIALIZED_TENANT_DINEIN_REPORTS_SCHEMA_VERSION,
438
+ source_watermark: watermark,
439
+ computed_at: computedAt,
440
+ createdAt: computedAt,
441
+ updatedAt: computedAt,
442
+ },
443
+ ];
444
+ /* -------------------- entry pages -------------------- */
445
+ const sections = {};
446
+ for (const key of [...rowsByKey.keys()].sort()) {
447
+ const rows = rowsByKey.get(key);
448
+ // NEWEST FIRST with a total tie-break: the same order the keyset reader
449
+ // uses, so the stored page and the API agree.
450
+ rows.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime() ||
451
+ (a.order_id < b.order_id ? 1 : a.order_id > b.order_id ? -1 : 0));
452
+ sections[key] = { rows };
453
+ }
454
+ const entries = [];
455
+ if (Object.keys(sections).length > 0) {
456
+ const periodFields = (0, scope_helpers_1.getMaterializedPeriodScopeFields)(localDate);
457
+ if (periodFields == null)
458
+ return null;
459
+ for (const scope of MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ENTRY_SCOPES) {
460
+ const scopeField = periodFields[scope];
461
+ const page = (0, materialized_dinein_entry_pages_1.dineinEntryPageOf)(scope, localDate);
462
+ if (typeof scopeField !== 'string' || scopeField === '' || page == null)
463
+ return null;
464
+ const pageDoc = {
465
+ _id: undefined,
466
+ tenant_id: tenantId,
467
+ brand_id: brandId,
468
+ scope_context: scope,
469
+ scope_field: scopeField,
470
+ page,
471
+ day_index: scope === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE ? dayIndex : null,
472
+ dinein_entries: sections,
473
+ schema_version: materialized_tenant_dinein_entries_1.MATERIALIZED_TENANT_DINEIN_ENTRIES_SCHEMA_VERSION,
474
+ source_watermark: watermark,
475
+ computed_at: computedAt,
476
+ createdAt: computedAt,
477
+ updatedAt: computedAt,
478
+ };
479
+ entries.push(...(0, materialized_dinein_entry_pages_1.splitMaterializedDineinEntryPage)(pageDoc));
480
+ }
481
+ }
482
+ // BSON budgets: fail at COMPILE time, naming the collection + day + scope,
483
+ // rather than at insert time inside the close transaction.
484
+ (0, materialized_document_size_1.assertMaterializedDocumentSize)(reports[0], {
485
+ label: `materialized_tenant_dinein_reports:${tenantId}:${localDate}:localDate:${localDate}`,
486
+ maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_REPORT_MAX_BSON_BYTES,
487
+ });
488
+ for (const page of entries) {
489
+ (0, materialized_document_size_1.assertMaterializedDocumentSize)(page, {
490
+ label: 'materialized_tenant_dinein_entries:' +
491
+ tenantId +
492
+ ':' +
493
+ localDate +
494
+ ':' +
495
+ String(page.scope_context) +
496
+ ':' +
497
+ page.scope_field +
498
+ ':page=' +
499
+ page.page,
500
+ maxBytes: MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ENTRY_MAX_BSON_BYTES,
501
+ });
502
+ }
503
+ return { reports, entries, coverage };
504
+ }
@@ -0,0 +1,69 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantDineinEntry } from '../../schemas/types/materialized_tenant_dinein_entries';
3
+ /** True when a scope context carries entry pages (day + the three period scopes). */
4
+ export declare function isMaterializedDineinEntryScope(scope: unknown): boolean;
5
+ /** The `page` value a compiled entry document of `scopeContext` must carry. */
6
+ export declare function dineinEntryPageOf(scopeContext: unknown, localDate: string): string | null;
7
+ /** The unsuffixed source-day page (`all` / `YYYY-MM-DD`). */
8
+ export declare function dineinEntryPageBase(page: unknown): string;
9
+ /** True when a stored page belongs to the source day (`all` / `YYYY-MM-DD` + `#N`). */
10
+ export declare function isDineinEntryPageForSourceDay(scopeContext: unknown, page: unknown, localDate: string): boolean;
11
+ /** The deterministic identity of one chunk. */
12
+ export declare function materializedDineinEntrySubPage(basePage: string, index: number): string;
13
+ /** Stable identity string of one entry page (tests / diagnostics / map keys). */
14
+ export declare function materializedDineinEntryPageKey(ref: {
15
+ scope_context: unknown;
16
+ scope_field: unknown;
17
+ page: unknown;
18
+ }): string;
19
+ /**
20
+ * Splits ONE source-day entry page when it exceeds the budget.
21
+ *
22
+ * Rows are walked in their stored (deterministic) key/row order and packed until
23
+ * the next row would cross the budget. A page that fits keeps its original
24
+ * identity. Throws when a single row cannot fit, because silently dropping a
25
+ * check would understate the statement.
26
+ */
27
+ export declare function splitMaterializedDineinEntryPage(doc: IMaterializedTenantDineinEntry, maxBytes?: number): IMaterializedTenantDineinEntry[];
28
+ /**
29
+ * Unions all pages of ONE source day (the base page or its `#N` sub-pages) into
30
+ * one logical document. Rows are disjoint by construction; the `order_id`
31
+ * dedupe makes a duplicated page harmless instead of doubling a check.
32
+ */
33
+ export declare function mergeMaterializedDineinEntryPages(pages: readonly IMaterializedTenantDineinEntry[] | null | undefined, identity?: {
34
+ scope_context: IMaterializedTenantDineinEntry['scope_context'];
35
+ scope_field: string;
36
+ page: string;
37
+ } | null): IMaterializedTenantDineinEntry | null;
38
+ /** One entry-page identity: the scope, its value, and the source-day page. */
39
+ export interface IMaterializedDineinEntryPageRef {
40
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
41
+ scope_field: string;
42
+ page: string;
43
+ }
44
+ /**
45
+ * The BASE page refs belonging to ONE source day. The close reader expands each
46
+ * ref to the base plus any deterministic `#N` sub-pages; no other day's page is
47
+ * ever fetched.
48
+ *
49
+ * Returns `null` for a malformed date.
50
+ */
51
+ export declare function buildMaterializedDineinEntryPageRefs(localDate: string): IMaterializedDineinEntryPageRef[] | null;
52
+ /** A decoded scope group, structurally identical to the read API's group shape. */
53
+ export interface IDineinScopeGroup {
54
+ scope_context: MATERIALIZED_REPORT_SCOPE_ENUM;
55
+ scope_field: string[];
56
+ }
57
+ /** The distinct `YYYY-MM` scope values of a day set, ascending. */
58
+ export declare function dineinMonthScopeFieldsOfDays(days: readonly string[]): string[];
59
+ /**
60
+ * Resolves the EXACT selected days into the scope groups a DINEIN DETAILS read
61
+ * uses:
62
+ *
63
+ * - one day → the `localDate` page (`page='all'`) — the direct path;
64
+ * - many days → the `localMonth` groups that contain them. The reader scans the
65
+ * pages of those months and filters rows to the EXACT days via
66
+ * `source_local_date`, so a quarter / semester / year / custom multi-month
67
+ * range is served, never refused.
68
+ */
69
+ export declare function buildMaterializedDineinDetailsScopeGroups(days: readonly string[]): IDineinScopeGroup[] | null;