@managesome/eposmatic-toolkit 0.4.60 → 0.4.62

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 (96) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +254 -4
  2. package/esm/constants/TENANT_ENUMS.js +15 -0
  3. package/esm/constants/WORKER_ENDPOINTS.js +12 -0
  4. package/esm/helpers/materialized-reports/index.js +8 -0
  5. package/esm/helpers/materialized-reports/materialized-day-readiness.js +2 -2
  6. package/esm/helpers/materialized-reports/materialized-dinein-accumulator-helpers.js +557 -0
  7. package/esm/helpers/materialized-reports/materialized-dinein-classification-helpers.js +447 -0
  8. package/esm/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +372 -0
  9. package/esm/helpers/materialized-reports/materialized-dinein-compile-helpers.js +500 -0
  10. package/esm/helpers/materialized-reports/materialized-dinein-entry-pages.js +218 -0
  11. package/esm/helpers/materialized-reports/materialized-dinein-key-helpers.js +87 -0
  12. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +7 -1
  13. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +8 -0
  14. package/esm/helpers/materialized-reports/materialized-report-runs.js +143 -0
  15. package/esm/helpers/materialized-reports/report-platform/definition.js +93 -1
  16. package/esm/helpers/materialized-reports/tenant-dinein-formatter.js +240 -0
  17. package/esm/helpers/reporting-contract/report-contract.js +3 -0
  18. package/esm/schemas/models/index.js +3 -0
  19. package/esm/schemas/models/materialized_tenant_dinein_entries.js +57 -0
  20. package/esm/schemas/models/materialized_tenant_dinein_reports.js +73 -0
  21. package/esm/schemas/models/materialized_tenant_report_runs.js +105 -0
  22. package/esm/schemas/models/tenant_active_jobs.js +19 -1
  23. package/esm/schemas/types/index.js +3 -0
  24. package/esm/schemas/types/materialized_report_drilldown_rows.js +1 -0
  25. package/esm/schemas/types/materialized_tenant_dinein_entries.js +1 -0
  26. package/esm/schemas/types/materialized_tenant_dinein_reports.js +6 -0
  27. package/esm/schemas/types/materialized_tenant_report_runs.js +1 -0
  28. package/lib/constants/MATERIALIZED_REPORTS.d.ts +229 -4
  29. package/lib/constants/MATERIALIZED_REPORTS.js +255 -5
  30. package/lib/constants/TENANT_ENUMS.d.ts +14 -0
  31. package/lib/constants/TENANT_ENUMS.js +16 -1
  32. package/lib/constants/WORKER_ENDPOINTS.d.ts +12 -0
  33. package/lib/constants/WORKER_ENDPOINTS.js +12 -0
  34. package/lib/helpers/materialized-reports/index.d.ts +8 -0
  35. package/lib/helpers/materialized-reports/index.js +8 -0
  36. package/lib/helpers/materialized-reports/materialized-day-readiness.d.ts +1 -1
  37. package/lib/helpers/materialized-reports/materialized-day-readiness.js +2 -2
  38. package/lib/helpers/materialized-reports/materialized-dinein-accumulator-helpers.d.ts +67 -0
  39. package/lib/helpers/materialized-reports/materialized-dinein-accumulator-helpers.js +582 -0
  40. package/lib/helpers/materialized-reports/materialized-dinein-classification-helpers.d.ts +245 -0
  41. package/lib/helpers/materialized-reports/materialized-dinein-classification-helpers.js +469 -0
  42. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.d.ts +110 -0
  43. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +384 -0
  44. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.d.ts +73 -0
  45. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.js +504 -0
  46. package/lib/helpers/materialized-reports/materialized-dinein-entry-pages.d.ts +69 -0
  47. package/lib/helpers/materialized-reports/materialized-dinein-entry-pages.js +231 -0
  48. package/lib/helpers/materialized-reports/materialized-dinein-key-helpers.d.ts +44 -0
  49. package/lib/helpers/materialized-reports/materialized-dinein-key-helpers.js +96 -0
  50. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +6 -0
  51. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +8 -0
  52. package/lib/helpers/materialized-reports/materialized-report-runs.d.ts +105 -0
  53. package/lib/helpers/materialized-reports/materialized-report-runs.js +156 -0
  54. package/lib/helpers/materialized-reports/report-platform/definition.js +92 -0
  55. package/lib/helpers/materialized-reports/tenant-dinein-formatter.d.ts +225 -0
  56. package/lib/helpers/materialized-reports/tenant-dinein-formatter.js +243 -0
  57. package/lib/helpers/reporting-contract/report-contract.d.ts +1 -0
  58. package/lib/helpers/reporting-contract/report-contract.js +3 -0
  59. package/lib/helpers/types/workers.d.ts +65 -0
  60. package/lib/schemas/models/index.d.ts +3 -0
  61. package/lib/schemas/models/index.js +3 -0
  62. package/lib/schemas/models/materialized_tenant_day_readiness.d.ts +3 -3
  63. package/lib/schemas/models/materialized_tenant_dinein_entries.d.ts +100 -0
  64. package/lib/schemas/models/materialized_tenant_dinein_entries.js +60 -0
  65. package/lib/schemas/models/materialized_tenant_dinein_reports.d.ts +111 -0
  66. package/lib/schemas/models/materialized_tenant_dinein_reports.js +76 -0
  67. package/lib/schemas/models/materialized_tenant_report_runs.d.ts +97 -0
  68. package/lib/schemas/models/materialized_tenant_report_runs.js +108 -0
  69. package/lib/schemas/models/tenant_active_jobs.d.ts +12 -3
  70. package/lib/schemas/models/tenant_active_jobs.js +18 -0
  71. package/lib/schemas/types/index.d.ts +3 -0
  72. package/lib/schemas/types/index.js +3 -0
  73. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +1 -1
  74. package/lib/schemas/types/materialized_report_drilldown_rows.js +1 -0
  75. package/lib/schemas/types/materialized_tenant_dinein_entries.d.ts +127 -0
  76. package/lib/schemas/types/materialized_tenant_dinein_entries.js +2 -0
  77. package/lib/schemas/types/materialized_tenant_dinein_reports.d.ts +326 -0
  78. package/lib/schemas/types/materialized_tenant_dinein_reports.js +9 -0
  79. package/lib/schemas/types/materialized_tenant_report_runs.d.ts +55 -0
  80. package/lib/schemas/types/materialized_tenant_report_runs.js +2 -0
  81. package/lib/schemas/types/tenant_active_jobs.d.ts +15 -1
  82. package/lib/tests/materialized-reports/dinein-fixtures.d.ts +29 -0
  83. package/lib/tests/materialized-reports/dinein-fixtures.js +130 -0
  84. package/lib/tests/materialized-reports/materialized-day-readiness.test.js +3 -2
  85. package/lib/tests/materialized-reports/materialized-dinein-compile.test.d.ts +1 -0
  86. package/lib/tests/materialized-reports/materialized-dinein-compile.test.js +807 -0
  87. package/lib/tests/materialized-reports/materialized-dinein-plan.test.d.ts +1 -0
  88. package/lib/tests/materialized-reports/materialized-dinein-plan.test.js +419 -0
  89. package/lib/tests/materialized-reports/materialized-report-runs.test.d.ts +1 -0
  90. package/lib/tests/materialized-reports/materialized-report-runs.test.js +116 -0
  91. package/lib/tests/materialized-reports/materialized-tenant-dinein-schema.test.d.ts +1 -0
  92. package/lib/tests/materialized-reports/materialized-tenant-dinein-schema.test.js +185 -0
  93. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +15 -2
  94. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.d.ts +1 -0
  95. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.js +458 -0
  96. package/package.json +1 -1
@@ -0,0 +1,469 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toDineinInt = exports.toDineinDate = void 0;
4
+ exports.isDineinOrder = isDineinOrder;
5
+ exports.isDeletedSplitParent = isDeletedSplitParent;
6
+ exports.isSplitChild = isSplitChild;
7
+ exports.firstVersionOf = firstVersionOf;
8
+ exports.classifyMaterializedDineinOrigin = classifyMaterializedDineinOrigin;
9
+ exports.splitRoleOf = splitRoleOf;
10
+ exports.itemQuantityOf = itemQuantityOf;
11
+ exports.itemLineQuantities = itemLineQuantities;
12
+ exports.itemLineDelta = itemLineDelta;
13
+ exports.validRatingOf = validRatingOf;
14
+ exports.paymentClassOf = paymentClassOf;
15
+ exports.collectedAmountOf = collectedAmountOf;
16
+ exports.refundsOf = refundsOf;
17
+ exports.serviceChargeRateKeyOf = serviceChargeRateKeyOf;
18
+ exports.courseKeyOf = courseKeyOf;
19
+ exports.addDineinOrderToCounters = addDineinOrderToCounters;
20
+ exports.freshDineinKeyCounters = freshDineinKeyCounters;
21
+ exports.freshDineinCoverage = freshDineinCoverage;
22
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
23
+ const platform_1 = require("../../constants/enums/platform");
24
+ const materialized_dinein_accumulator_helpers_1 = require("./materialized-dinein-accumulator-helpers");
25
+ const num = (value) => {
26
+ const number = typeof value === 'number' ? value : Number(value);
27
+ return Number.isFinite(number) ? Math.round(number) : 0;
28
+ };
29
+ exports.toDineinInt = num;
30
+ const toDate = (value) => {
31
+ if (value == null)
32
+ return null;
33
+ const date = value instanceof Date ? value : new Date(value);
34
+ return Number.isNaN(date.getTime()) ? null : date;
35
+ };
36
+ exports.toDineinDate = toDate;
37
+ const text = (value) => (value == null ? '' : String(value).trim());
38
+ /** A check belongs to the dine-in population when it carries `dinein_details`. */
39
+ function isDineinOrder(order) {
40
+ return order != null && order.dinein_details != null;
41
+ }
42
+ /** An auto-deleted split PARENT: never a collectable check. */
43
+ function isDeletedSplitParent(order) {
44
+ if (order == null)
45
+ return false;
46
+ if (order.is_deleted !== true)
47
+ return false;
48
+ if (text(order.delete_reason) !== MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_SPLIT_PARENT_DELETE_REASON)
49
+ return false;
50
+ return Array.isArray(order.split_child_ids) ? order.split_child_ids.length > 0 : true;
51
+ }
52
+ /** A split CHILD: a collectable check that belongs to a split group. */
53
+ function isSplitChild(order) {
54
+ return order != null && text(order.split_parent_id) !== '';
55
+ }
56
+ /**
57
+ * The FIRST version of a check.
58
+ *
59
+ * `iterations[0]` is the MOST RECENT previous version and `iterations[last]` is
60
+ * the original one, so the first version is the LAST element — or the current
61
+ * order when there are no iterations. Using `iterations[0]` would read an edit
62
+ * as the first version.
63
+ */
64
+ function firstVersionOf(order) {
65
+ const iterations = Array.isArray(order?.iterations) ? order.iterations : [];
66
+ if (iterations.length === 0)
67
+ return order;
68
+ return iterations[iterations.length - 1] ?? order;
69
+ }
70
+ /**
71
+ * The frozen origin classification.
72
+ *
73
+ * | first version | staff | consumer phone | origin |
74
+ * | --- | --- | --- | --- |
75
+ * | `POS_DINE-IN` | any | any | `POS_DIRECT` |
76
+ * | `APP_DINE-IN` / `WEB_DINE-IN` | yes | any | `STAFF_TABLET` |
77
+ * | `APP_DINE-IN` / `WEB_DINE-IN` | no | yes | `QR_SELF_ORDER` |
78
+ * | anything else | any | any | `UNKNOWN_ORIGIN` |
79
+ *
80
+ * The phone is read as a boolean only — it is NEVER stored.
81
+ */
82
+ function classifyMaterializedDineinOrigin(order) {
83
+ if (order == null)
84
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ORIGIN_ENUM.UNKNOWN_ORIGIN;
85
+ const first = firstVersionOf(order);
86
+ const platform = text(first.platform ?? order.platform);
87
+ const hasStaff = first.staff_details != null ||
88
+ first.order_taker_details != null;
89
+ const phone = text((first.consumer ?? order.consumer)?.phone);
90
+ const hasConsumerPhone = phone !== '';
91
+ if (platform === platform_1.PLATFORMS_ENUM.POS_DINE_IN)
92
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ORIGIN_ENUM.POS_DIRECT;
93
+ if (platform === platform_1.PLATFORMS_ENUM.APP_DINE_IN || platform === platform_1.PLATFORMS_ENUM.WEB_DINE_IN) {
94
+ if (hasStaff)
95
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ORIGIN_ENUM.STAFF_TABLET;
96
+ if (hasConsumerPhone)
97
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ORIGIN_ENUM.QR_SELF_ORDER;
98
+ }
99
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ORIGIN_ENUM.UNKNOWN_ORIGIN;
100
+ }
101
+ /** The role of a counted check in a split bill (a parent is never counted). */
102
+ function splitRoleOf(order) {
103
+ return isSplitChild(order) ? MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_SPLIT_ROLE_ENUM.CHILD : MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_SPLIT_ROLE_ENUM.NONE;
104
+ }
105
+ /** Total item quantity of one check version. */
106
+ function itemQuantityOf(order) {
107
+ let total = 0;
108
+ for (const category of order?.categories ?? []) {
109
+ for (const item of category?.items ?? [])
110
+ total += Math.max(0, num(item?.quantity));
111
+ }
112
+ return total;
113
+ }
114
+ /**
115
+ * Item quantity by LINE identity (`_id`, falling back to `item_id`).
116
+ *
117
+ * Two lines of the same menu item are two identities, so an edit that moves one
118
+ * of them is counted on its own line instead of netting against its twin.
119
+ */
120
+ function itemLineQuantities(order) {
121
+ const quantities = new Map();
122
+ for (const category of order?.categories ?? []) {
123
+ for (const item of category?.items ?? []) {
124
+ const identity = text(item?._id) || text(item?.item_id);
125
+ if (identity === '')
126
+ continue;
127
+ quantities.set(identity, (quantities.get(identity) ?? 0) + Math.max(0, num(item?.quantity)));
128
+ }
129
+ }
130
+ return quantities;
131
+ }
132
+ /**
133
+ * The line delta between two versions of one check.
134
+ *
135
+ * Identity is the item LINE (`_id`, else `item_id`), so moving one of two lines
136
+ * of the same menu item is measured on its own line. A version without
137
+ * categories cannot be compared and contributes nothing.
138
+ */
139
+ function itemLineDelta(previous, next) {
140
+ if (previous?.categories == null || next?.categories == null) {
141
+ return { additions: 0, removals: 0, net: 0 };
142
+ }
143
+ const before = itemLineQuantities(previous);
144
+ const after = itemLineQuantities(next);
145
+ let additions = 0;
146
+ let removals = 0;
147
+ let net = 0;
148
+ for (const identity of new Set([...before.keys(), ...after.keys()])) {
149
+ const delta = (after.get(identity) ?? 0) - (before.get(identity) ?? 0);
150
+ if (delta > 0)
151
+ additions += delta;
152
+ else if (delta < 0)
153
+ removals += -delta;
154
+ net += delta;
155
+ }
156
+ return { additions, removals, net };
157
+ }
158
+ /** A validated rating (1..5) or null. A 0 / 6 / non-numeric value is NOT a rating. */
159
+ function validRatingOf(value) {
160
+ const rating = Number(value);
161
+ if (!Number.isInteger(rating) || rating < 1 || rating > 5)
162
+ return null;
163
+ return rating;
164
+ }
165
+ /** A payment's class: `CASH`, `CARD` (`CARD` + `TERMINAL`), everything else `OTHER`. */
166
+ function paymentClassOf(paymentType) {
167
+ const type = text(paymentType).toUpperCase();
168
+ if (type === 'CASH')
169
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CASH;
170
+ if (type === 'CARD' || type === 'TERMINAL')
171
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CARD;
172
+ return MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.OTHER;
173
+ }
174
+ /**
175
+ * The collected amount of one payment, NET OF REFUNDS.
176
+ *
177
+ * `amount_paid - amount_refunded`, in integer cents. The report uses the
178
+ * COLLECTED amount (not the order count) for card vs cash, so an order that was
179
+ * partially refunded contributes what was actually kept.
180
+ */
181
+ function collectedAmountOf(payment) {
182
+ return num(payment?.amount_paid) - num(payment?.amount_refunded);
183
+ }
184
+ /** The refunded amount of one check, summed over its payment rows. */
185
+ function refundsOf(order) {
186
+ let total = 0;
187
+ for (const payment of order?.payments ?? [])
188
+ total += Math.max(0, num(payment?.amount_refunded));
189
+ return total;
190
+ }
191
+ /** The service-charge rate key: `<PCT|FIXED>:<rate>` (bounded by the document cap). */
192
+ function serviceChargeRateKeyOf(order) {
193
+ const amount = num(order?.service_fee_amount);
194
+ const isPercentage = order?.is_service_fee_percentage === true;
195
+ if (isPercentage) {
196
+ const value = Number(order?.service_fee);
197
+ const normalized = Number.isFinite(value) ? String(Math.round(value * 100) / 100) : '0';
198
+ return 'PCT:' + normalized;
199
+ }
200
+ return 'FIXED:' + String(amount);
201
+ }
202
+ /** The bounded course key of one course row (`course_id`, falling back to the name). */
203
+ function courseKeyOf(course) {
204
+ const id = text(course?.course_id);
205
+ if (id !== '')
206
+ return id;
207
+ const name = text(course?.name);
208
+ return name !== '' ? name : MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
209
+ }
210
+ /**
211
+ * Accumulates ONE collectable check into `counters`.
212
+ *
213
+ * `covers` is passed in (already resolved from the fingerprint) because covers
214
+ * are never derived from the order. `tableSessions` are this check's own
215
+ * sessions; the caller already filtered them to joined, deduped fingerprints.
216
+ */
217
+ function addDineinOrderToCounters(input) {
218
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
219
+ const { counters, order, covers, sessions, rating, splitType } = input;
220
+ const keyStatus = text(order?.order_status) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
221
+ const keyPlatform = text(order?.platform) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
222
+ const sales = num(order?.amount_earned);
223
+ const serviceCharge = num(order?.service_fee_amount);
224
+ const items = itemQuantityOf(order);
225
+ const isChild = isSplitChild(order);
226
+ counters.orders += 1;
227
+ if (keyStatus === 'COMPLETED')
228
+ counters.completed_orders += 1;
229
+ if (keyStatus === 'CANCELLED')
230
+ counters.cancelled_orders += 1;
231
+ counters.covers += Math.max(0, num(covers));
232
+ counters.items += items;
233
+ counters.sales += sales;
234
+ counters.discounts += num(order?.total_discount_applied ?? order?.order_discount_details?.total_discount);
235
+ counters.tax += num(order?.tax_amount);
236
+ counters.tips += num(order?.tip_amount);
237
+ counters.service_charge_amount += serviceCharge;
238
+ counters.service_charge_taxable_amount += order?.is_service_fee_taxable === true ? serviceCharge : 0;
239
+ counters.surcharge_amount += num(order?.surcharge_amount);
240
+ counters.refunds += refundsOf(order);
241
+ // ---- split bills ----
242
+ if (isChild) {
243
+ counters.split_children += 1;
244
+ counters.split_sales += sales;
245
+ const type = splitType ?? MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
246
+ counters.split_type_counts[type] = num(counters.split_type_counts[type]) + 1;
247
+ }
248
+ // ---- offline ----
249
+ if (order?.synced_offline === true) {
250
+ counters.offline_orders += 1;
251
+ counters.offline_sales += sales;
252
+ }
253
+ // ---- origin ----
254
+ const origin = classifyMaterializedDineinOrigin(order);
255
+ (_a = counters.by_origin)[origin] ?? (_a[origin] = { orders: 0, sales: 0, covers: 0 });
256
+ counters.by_origin[origin].orders += 1;
257
+ counters.by_origin[origin].sales += sales;
258
+ counters.by_origin[origin].covers += Math.max(0, num(covers));
259
+ counters.origin_orders += 1;
260
+ counters.origin_sales += sales;
261
+ counters.origin_covers += Math.max(0, num(covers));
262
+ // ---- service charge composition ----
263
+ if (serviceCharge !== 0) {
264
+ counters.service_charge_orders += 1;
265
+ if (order?.is_service_fee_percentage === true)
266
+ counters.service_charge_percentage_orders += 1;
267
+ else
268
+ counters.service_charge_fixed_orders += 1;
269
+ if (order?.apply_service_fee_on_original_price === true) {
270
+ counters.service_charge_original_price_orders += 1;
271
+ }
272
+ const rateKey = serviceChargeRateKeyOf(order);
273
+ counters.service_charge_rate_counts[rateKey] = num(counters.service_charge_rate_counts[rateKey]) + 1;
274
+ }
275
+ // ---- edits: consecutive versions oldest -> current, current is NOT an edit ----
276
+ const versions = [
277
+ ...(Array.isArray(order?.iterations) ? [...order.iterations].reverse() : []),
278
+ order,
279
+ ];
280
+ const edits = Math.max(0, Array.isArray(order?.iterations) ? order.iterations.length : 0);
281
+ if (edits > 0)
282
+ counters.edited_orders += 1;
283
+ counters.total_edits += edits;
284
+ let additions = 0;
285
+ let removals = 0;
286
+ let net = 0;
287
+ for (let index = 1; index < versions.length; index += 1) {
288
+ // A version without categories cannot be compared; the edit count still
289
+ // counts the version (it IS a recorded edit), the quantity delta does not.
290
+ const delta = itemLineDelta(versions[index - 1], versions[index]);
291
+ additions += delta.additions;
292
+ removals += delta.removals;
293
+ net += delta.net;
294
+ }
295
+ counters.item_additions += additions;
296
+ counters.item_removals += removals;
297
+ counters.net_item_change += net;
298
+ // ---- courses (CURRENT state only: no call history on the order) ----
299
+ for (const course of order?.dinein_details?.courses ?? []) {
300
+ const courseKey = courseKeyOf(course);
301
+ const row = ((_b = counters.by_course)[courseKey] ?? (_b[courseKey] = {
302
+ course_id: courseKey,
303
+ name: text(course?.name) || courseKey,
304
+ assigned: 0,
305
+ called: 0,
306
+ on_hold: 0,
307
+ items: 0,
308
+ }));
309
+ row.assigned += 1;
310
+ if (course?.called === true)
311
+ row.called += 1;
312
+ else
313
+ row.on_hold += 1;
314
+ const courseItems = Array.isArray(course?.item_ids) ? course.item_ids.length : 0;
315
+ row.items += courseItems;
316
+ counters.courses_assigned += 1;
317
+ if (course?.called === true)
318
+ counters.courses_called += 1;
319
+ else
320
+ counters.courses_on_hold += 1;
321
+ counters.course_items += courseItems;
322
+ }
323
+ // ---- card vs cash (collected, net of refunds) ----
324
+ // The AMOUNT is per payment row; the ORDER count is per distinct payment type
325
+ // on the check, so two card rows on one bill count as ONE card order.
326
+ const classes = new Set();
327
+ const amountByType = new Map();
328
+ for (const payment of order?.payments ?? []) {
329
+ const paymentType = text(payment?.payment_type) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
330
+ const amount = collectedAmountOf(payment);
331
+ const paymentClass = paymentClassOf(paymentType);
332
+ classes.add(paymentClass);
333
+ if (paymentClass === MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CASH)
334
+ counters.cash_amount += amount;
335
+ else if (paymentClass === MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CARD)
336
+ counters.card_amount += amount;
337
+ else
338
+ counters.other_amount += amount;
339
+ amountByType.set(paymentType, (amountByType.get(paymentType) ?? 0) + amount);
340
+ }
341
+ if (classes.has(MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CASH))
342
+ counters.cash_orders += 1;
343
+ if (classes.has(MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_PAYMENT_CLASS_ENUM.CARD))
344
+ counters.card_orders += 1;
345
+ if (classes.size > 1)
346
+ counters.split_tender_orders += 1;
347
+ for (const [paymentType, amount] of amountByType) {
348
+ const target = ((_c = counters.by_payment_type)[paymentType] ?? (_c[paymentType] = (0, materialized_dinein_accumulator_helpers_1.emptyMaterializedDineinPaymentRow)()));
349
+ target.amount += amount;
350
+ target.orders += 1;
351
+ }
352
+ // ---- ratings ----
353
+ if (rating != null) {
354
+ counters.rated_orders += 1;
355
+ counters.rating_sum += rating;
356
+ const bucket = ('rating_' + String(rating));
357
+ counters[bucket] += 1;
358
+ }
359
+ if (text(order?.review) !== '')
360
+ counters.review_count += 1;
361
+ // ---- dimensions ----
362
+ // `Number(null)` is 0, so an ABSENT hour must be rejected explicitly — an
363
+ // unbucketed check is never moved to midnight.
364
+ const rawHour = order?.localHour;
365
+ const hour = rawHour == null || rawHour === '' ? NaN : Number(rawHour);
366
+ if (Number.isInteger(hour) && hour >= 0 && hour <= 23) {
367
+ const hourKey = String(hour);
368
+ const hourRow = ((_d = counters.by_hour)[hourKey] ?? (_d[hourKey] = { orders: 0, sales: 0, covers: 0 }));
369
+ hourRow.orders += 1;
370
+ hourRow.sales += sales;
371
+ hourRow.covers += Math.max(0, num(covers));
372
+ }
373
+ // RICH breakdown rows: the page renders checks + covers + sales side by side.
374
+ const statusRow = ((_e = counters.by_status)[keyStatus] ?? (_e[keyStatus] = { orders: 0, covers: 0, sales: 0 }));
375
+ statusRow.orders += 1;
376
+ statusRow.covers += Math.max(0, num(covers));
377
+ statusRow.sales += sales;
378
+ const platformRow = ((_f = counters.by_platform)[keyPlatform] ?? (_f[keyPlatform] = { orders: 0, covers: 0, sales: 0 }));
379
+ platformRow.orders += 1;
380
+ platformRow.covers += Math.max(0, num(covers));
381
+ platformRow.sales += sales;
382
+ const tableId = text(order?.dinein_details?.table_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
383
+ const floorId = text(order?.dinein_details?.floor_id) || MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_UNKNOWN_TOKEN;
384
+ const tableRow = ((_g = counters.by_table)[tableId] ?? (_g[tableId] = {
385
+ table_id: tableId,
386
+ table_name: text(order?.dinein_details?.table_name),
387
+ floor_id: floorId,
388
+ orders: 0,
389
+ sessions: 0,
390
+ covers: 0,
391
+ occupancy_minutes: 0,
392
+ sales: 0,
393
+ }));
394
+ tableRow.orders += 1;
395
+ tableRow.covers += Math.max(0, num(covers));
396
+ tableRow.sales += sales;
397
+ const floorRow = ((_h = counters.by_floor)[floorId] ?? (_h[floorId] = {
398
+ floor_id: floorId,
399
+ orders: 0,
400
+ sessions: 0,
401
+ covers: 0,
402
+ occupancy_minutes: 0,
403
+ sales: 0,
404
+ }));
405
+ floorRow.orders += 1;
406
+ floorRow.covers += Math.max(0, num(covers));
407
+ floorRow.sales += sales;
408
+ // ---- table sessions / seated occupancy (fingerprint truth) ----
409
+ const tables = new Set();
410
+ for (const session of sessions) {
411
+ tables.add(session.table_id);
412
+ counters.table_sessions += 1;
413
+ counters.occupancy_minutes_sum += session.duration_minutes;
414
+ if (session.fallback_start)
415
+ counters.fallback_occupancy_sessions += 1;
416
+ else
417
+ counters.occupancy_sessions += 1;
418
+ const sessionTable = ((_j = counters.by_table)[_k = session.table_id] ?? (_j[_k] = {
419
+ table_id: session.table_id,
420
+ table_name: session.table_name,
421
+ floor_id: session.floor_id,
422
+ orders: 0,
423
+ sessions: 0,
424
+ covers: 0,
425
+ occupancy_minutes: 0,
426
+ sales: 0,
427
+ }));
428
+ sessionTable.sessions += 1;
429
+ sessionTable.occupancy_minutes += session.duration_minutes;
430
+ const sessionFloor = ((_l = counters.by_floor)[_m = session.floor_id] ?? (_l[_m] = {
431
+ floor_id: session.floor_id,
432
+ orders: 0,
433
+ sessions: 0,
434
+ covers: 0,
435
+ occupancy_minutes: 0,
436
+ sales: 0,
437
+ }));
438
+ sessionFloor.sessions += 1;
439
+ sessionFloor.occupancy_minutes += session.duration_minutes;
440
+ }
441
+ // The check's own table is "served" even when its fingerprint is missing.
442
+ tables.add(tableId);
443
+ counters.tables_served += tables.size;
444
+ }
445
+ /** A fresh accumulator entry for one key. */
446
+ function freshDineinKeyCounters() {
447
+ return (0, materialized_dinein_accumulator_helpers_1.freshMaterializedDineinCounters)();
448
+ }
449
+ /** The coverage counters of a compiled day, initialized to zero. */
450
+ function freshDineinCoverage() {
451
+ return {
452
+ orders_counted: 0,
453
+ orders_out_of_day: 0,
454
+ deleted_split_parents_excluded: 0,
455
+ ratings_from_deleted_parents: 0,
456
+ orders_without_fingerprint: 0,
457
+ fingerprints_total: 0,
458
+ fingerprints_joined: 0,
459
+ fingerprints_duplicate: 0,
460
+ fingerprints_unattached: 0,
461
+ fingerprints_missing_start: 0,
462
+ fingerprints_missing_end: 0,
463
+ fingerprints_negative_duration: 0,
464
+ fingerprints_fallback_start: 0,
465
+ reservations_counted: 0,
466
+ reservations_out_of_day: 0,
467
+ reservations_missing_time: 0,
468
+ };
469
+ }
@@ -0,0 +1,110 @@
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM } from '../../constants/MATERIALIZED_REPORTS';
2
+ import { IMaterializedTenantDineinEntry } from '../../schemas/types/materialized_tenant_dinein_entries';
3
+ import { IMaterializedDineinCounters, IMaterializedTenantDineinReport } from '../../schemas/types/materialized_tenant_dinein_reports';
4
+ import { freshMaterializedDineinReservationCounters } from './materialized-dinein-accumulator-helpers';
5
+ /**
6
+ * Dinein close-day helpers.
7
+ *
8
+ * ## Period counters are RE-FOLDED, never patched
9
+ *
10
+ * Every touched period (week / ISO week / month / quarter / semester / year) is
11
+ * rebuilt from its whole set of DAY documents. Removing a day by decrementing
12
+ * its contribution is not usable here because the document also carries
13
+ * document-level BOUNDED maps (top tables / floors / courses / rates), which are
14
+ * re-ranked after the merge.
15
+ *
16
+ * ## The watermark comes from the FOLDED DAYS
17
+ *
18
+ * A folded document that inherited the STORED watermark would look unchanged to
19
+ * the write guard and be skipped forever. The watermark is the max over the DAY
20
+ * documents that belong to the period — never an unrelated day's.
21
+ *
22
+ * ## ENTRY pages are NOT folded
23
+ *
24
+ * `materialized_tenant_dinein_entries` is page-partitioned by source day. The
25
+ * plan never reads, merges or folds another day's page: the caller fetches
26
+ * exactly the closing day's pages, each is replaced by its page identity, and a
27
+ * fetched page the day no longer owns is deleted.
28
+ */
29
+ /** Period COUNTER scopes this report materializes (everything but the day scope). */
30
+ export declare const MATERIALIZED_DINEIN_PERIOD_SCOPES: MATERIALIZED_REPORT_SCOPE_ENUM[];
31
+ /**
32
+ * Every `localDate` label whose DAY counter document can contribute to a REPORT
33
+ * period the closing day rolls into - week through YEAR. The worker uses it to
34
+ * fetch exactly the sibling DAY counters the period re-fold needs.
35
+ */
36
+ export declare function getMaterializedDineinReportPeriodDayScopeFields(localDate: string): string[] | null;
37
+ /** True when the scope is the plain day scope. */
38
+ export declare const isMaterializedDineinDayScope: (scopeContext: unknown) => boolean;
39
+ /** True when the stored report document does not already carry this content. */
40
+ export declare function needsMaterializedDineinReportWrite(existing: IMaterializedTenantDineinReport | null | undefined, next: IMaterializedTenantDineinReport): boolean;
41
+ /** True when the stored entry page does not already carry these rows. */
42
+ export declare function needsMaterializedDineinEntriesWrite(existing: IMaterializedTenantDineinEntry | null | undefined, next: IMaterializedTenantDineinEntry): boolean;
43
+ /**
44
+ * Folds every DAY document belonging to one period scope.
45
+ *
46
+ * Both the keyed counters and the document-level reservation block are additive;
47
+ * the bounded maps are re-bounded by the caller (`pruneDocumentDineinMaps`).
48
+ */
49
+ export declare function foldMaterializedDineinPeriodCounters(input: {
50
+ periodScope: string;
51
+ periodScopeField: string;
52
+ dayDocuments: IMaterializedTenantDineinReport[];
53
+ }): {
54
+ counters: Record<string, IMaterializedDineinCounters>;
55
+ reservations: ReturnType<typeof freshMaterializedDineinReservationCounters>;
56
+ /** Re-ranked union of the day snapshots (bounded by the caller). */
57
+ upcomingReservations: IMaterializedTenantDineinReport['upcoming_reservations'];
58
+ topEditedChecks: IMaterializedTenantDineinReport['top_edited_checks'];
59
+ };
60
+ /** One plan write: the document plus its iteration history row. */
61
+ export interface IMaterializedDineinCloseDayWrite<T> {
62
+ report: T;
63
+ iteration: {
64
+ report_type: string;
65
+ report_id: string;
66
+ iteration: number;
67
+ schema_version: number;
68
+ reason: string;
69
+ snapshot: unknown;
70
+ createdAt: Date;
71
+ updatedAt: Date;
72
+ };
73
+ }
74
+ export interface ITenantDineinCloseDayPlan {
75
+ writes: IMaterializedDineinCloseDayWrite<IMaterializedTenantDineinReport>[];
76
+ entryWrites: IMaterializedDineinCloseDayWrite<IMaterializedTenantDineinEntry>[];
77
+ staleDocuments: IMaterializedTenantDineinReport[];
78
+ staleEntryDocuments: IMaterializedTenantDineinEntry[];
79
+ skippedDocuments: IMaterializedTenantDineinReport[];
80
+ skippedEntryDocuments: IMaterializedTenantDineinEntry[];
81
+ }
82
+ export interface IBuildTenantDineinCloseDayPlanInput {
83
+ tenantId: string;
84
+ reports: IMaterializedTenantDineinReport[];
85
+ entries: IMaterializedTenantDineinEntry[];
86
+ localDate?: string | null;
87
+ existing?: IMaterializedTenantDineinReport[];
88
+ existingEntries?: IMaterializedTenantDineinEntry[];
89
+ reason: string;
90
+ computedAt?: Date;
91
+ /**
92
+ * Rewrite every touched document even when the watermark says nothing changed.
93
+ *
94
+ * Dinein counters are not purely append-only: an order's status/rating, a
95
+ * course's `called` flag and a fingerprint's covers all change in place
96
+ * WITHOUT advancing the max watermark, and a removed order changes the day
97
+ * without changing the watermark either. A value-idempotent forced rewrite is
98
+ * therefore the safe default.
99
+ */
100
+ force?: boolean;
101
+ }
102
+ /**
103
+ * Builds the close-day plan for ONE tenant-day.
104
+ *
105
+ * The DAY scope comes from the compile. Every PERIOD scope the day touches is
106
+ * RE-FOLDED from its whole day set, and the touched set is the union of the
107
+ * closed day's periods AND every removed day's periods - emptying a day must
108
+ * clear it from the periods it used to belong to.
109
+ */
110
+ export declare function buildTenantDineinCloseDayPlan(input: IBuildTenantDineinCloseDayPlanInput | null | undefined): ITenantDineinCloseDayPlan | null;