@managesome/eposmatic-toolkit 0.4.4 → 0.4.7

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 (60) hide show
  1. package/esm/constants/REPORT_CALENDAR.js +47 -0
  2. package/esm/constants/index.js +1 -0
  3. package/esm/helpers/materialized-reports/index.js +2 -0
  4. package/esm/helpers/materialized-reports/materialized-reports-read-helpers.js +20 -21
  5. package/esm/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +281 -0
  6. package/esm/helpers/materialized-reports/materialized-reports-selection-helpers.js +473 -0
  7. package/esm/helpers/materialized-reports/tenant-sales-overview-formatter.js +126 -7
  8. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  9. package/esm/helpers/order/generate-order.js +11 -0
  10. package/esm/helpers/store/common-order-actions.js +7 -3
  11. package/esm/helpers/types/index.js +1 -0
  12. package/esm/helpers/types/materialized-reports-apis.js +1 -1
  13. package/esm/helpers/types/report-calendar.js +1 -0
  14. package/lib/constants/REPORT_CALENDAR.d.ts +31 -0
  15. package/lib/constants/REPORT_CALENDAR.js +50 -0
  16. package/lib/constants/index.d.ts +1 -0
  17. package/lib/constants/index.js +1 -0
  18. package/lib/helpers/materialized-reports/index.d.ts +2 -0
  19. package/lib/helpers/materialized-reports/index.js +2 -0
  20. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.d.ts +20 -21
  21. package/lib/helpers/materialized-reports/materialized-reports-read-helpers.js +20 -21
  22. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.d.ts +58 -0
  23. package/lib/helpers/materialized-reports/materialized-reports-scope-group-helpers.js +286 -0
  24. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.d.ts +25 -0
  25. package/lib/helpers/materialized-reports/materialized-reports-selection-helpers.js +479 -0
  26. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.d.ts +24 -0
  27. package/lib/helpers/materialized-reports/tenant-sales-overview-formatter.js +127 -7
  28. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +47 -1
  29. package/lib/helpers/order/generate-order.d.ts +2 -0
  30. package/lib/helpers/order/generate-order.js +13 -0
  31. package/lib/helpers/store/common-order-actions.js +7 -3
  32. package/lib/helpers/types/index.d.ts +1 -0
  33. package/lib/helpers/types/index.js +1 -0
  34. package/lib/helpers/types/materialized-reports-apis.d.ts +117 -25
  35. package/lib/helpers/types/materialized-reports-apis.js +1 -0
  36. package/lib/helpers/types/report-calendar.d.ts +20 -0
  37. package/lib/helpers/types/report-calendar.js +2 -0
  38. package/lib/schemas/models/internal_invoices.d.ts +3 -3
  39. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +6 -6
  40. package/lib/schemas/models/orders.d.ts +692 -692
  41. package/lib/schemas/models/tenant_purchase_orders.d.ts +90 -90
  42. package/lib/schemas/models/tenants.d.ts +9 -9
  43. package/lib/schemas/models/warehouse_communications.d.ts +3 -3
  44. package/lib/schemas/models/warehouse_internal_movements.d.ts +48 -48
  45. package/lib/schemas/models/warehouse_purchase_order_rfqs.d.ts +63 -63
  46. package/lib/schemas/models/warehouse_purchase_orders.d.ts +96 -96
  47. package/lib/schemas/models/warehouse_sale_invoices.d.ts +3 -3
  48. package/lib/schemas/models/warehouse_sale_order_rfqs.d.ts +69 -69
  49. package/lib/schemas/models/warehouse_sale_orders.d.ts +45 -45
  50. package/lib/schemas/models/warehouses.d.ts +6 -6
  51. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.d.ts +1 -0
  52. package/lib/tests/materialized-reports/materialized-reports-scope-group-helpers.test.js +275 -0
  53. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.d.ts +1 -0
  54. package/lib/tests/materialized-reports/materialized-reports-selection-helpers.test.js +166 -0
  55. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.d.ts +1 -0
  56. package/lib/tests/materialized-reports/tenant-sales-overview-formatter-aggregated.test.js +143 -0
  57. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +22 -0
  58. package/lib/tests/num-of-guests-limit.test.d.ts +1 -0
  59. package/lib/tests/num-of-guests-limit.test.js +76 -0
  60. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getFormattedTenantSalesOverviewReporting = getFormattedTenantSalesOverviewReporting;
4
+ exports.getFormattedTenantSalesOverviewAggregatedReporting = getFormattedTenantSalesOverviewAggregatedReporting;
4
5
  const constants_1 = require("../../constants");
5
6
  const ENUMS_1 = require("../../constants/ENUMS");
6
7
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
@@ -77,11 +78,10 @@ const matchesFilters = (components, keyFilters, filters) => {
77
78
  }
78
79
  return true;
79
80
  };
80
- /** Drops non-matching keys from a document's metric map (bills included). */
81
- const pruneReportForFilters = (doc, filters) => {
82
- const keyFilters = doc.sale_type_key_filters ?? [];
81
+ /** Drops non-matching keys from a key map (raw documents and aggregated records share this). */
82
+ const pruneMetricsMap = (keyFilters, metrics, filters) => {
83
83
  const kept = {};
84
- for (const [key, metric] of Object.entries(doc.sale_type_metrics ?? {})) {
84
+ for (const [key, metric] of Object.entries(metrics ?? {})) {
85
85
  const components = (0, key_helpers_1.parseMaterializedReportKey)(key);
86
86
  // Unparseable key — cannot be matched; skipping keeps the sums honest
87
87
  // (the write side rejects such keys, so this is defensive only).
@@ -91,6 +91,11 @@ const pruneReportForFilters = (doc, filters) => {
91
91
  continue;
92
92
  kept[key] = metric;
93
93
  }
94
+ return kept;
95
+ };
96
+ /** Drops non-matching keys from a document's metric map (bills included). */
97
+ const pruneReportForFilters = (doc, filters) => {
98
+ const kept = pruneMetricsMap(doc.sale_type_key_filters ?? [], doc.sale_type_metrics, filters);
94
99
  return { ...doc, sale_type_metrics: kept };
95
100
  };
96
101
  /* ------------------------------------------------------------------------ */
@@ -248,6 +253,17 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
248
253
  const merged = (0, tenant_sales_overview_helpers_1.sumMaterializedTenantSalesOverviewReports)(pruned, { allowTenantMismatch: true });
249
254
  if (merged == null)
250
255
  return null;
256
+ const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
257
+ return buildPageDataFromMetrics(merged, tenantIds, supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null, scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null);
258
+ };
259
+ /**
260
+ * Shared page assembly — identical for the raw read (one merged document) and
261
+ * the AGGREGATED read (one pipeline record): every section derives from the
262
+ * pruned key map. The slice-derived sections are inputs: the raw read passes
263
+ * the weekday / hourly grouping of its documents; the aggregated read passes
264
+ * `null` (its response carries no per-scope slices).
265
+ */
266
+ const buildPageDataFromMetrics = (merged, tenantIds, weekday, hourly) => {
251
267
  const keyFilters = merged.sale_type_key_filters ?? [];
252
268
  const summaryRaw = createRawOrderMetric();
253
269
  const collectedRaw = createRawOrderMetric();
@@ -307,7 +323,6 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
307
323
  gross_amount: toDecimal(channel.gross_amount),
308
324
  }))
309
325
  .sort((a, b) => b.count - a.count || a.platform.localeCompare(b.platform));
310
- const supportsDayIndex = scopeContext != null && MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPES_WITH_DAY_INDEX.includes(scopeContext);
311
326
  return {
312
327
  tenant_ids: tenantIds,
313
328
  summary: formatRawOrderMetric(summaryRaw),
@@ -325,8 +340,8 @@ const buildPageDataForDocs = (docs, scopeContext, filters) => {
325
340
  received: { count: receivedRaw.count, amount: toDecimal(receivedRaw.amount) },
326
341
  outstanding_amount: toDecimal(issuedRaw.amount - issuedRaw.settled_amount),
327
342
  },
328
- weekday: supportsDayIndex ? buildWeekdaySection(scopedDocs, filters) : null,
329
- hourly: scopeContext === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_HOUR ? buildHourlySection(scopedDocs, filters) : null,
343
+ weekday,
344
+ hourly,
330
345
  };
331
346
  };
332
347
  /* ------------------------------------------------------------------------ */
@@ -380,3 +395,108 @@ function getFormattedTenantSalesOverviewReporting(docs, filters = null, separate
380
395
  }
381
396
  return [results, null];
382
397
  }
398
+ /* ------------------------------------------------------------------------ */
399
+ /* Aggregated read (pipeline records) */
400
+ /* ------------------------------------------------------------------------ */
401
+ /** Folds a group of aggregated records into ONE combined key-map slice. */
402
+ const mergeAggregatedKeyMetrics = (reports) => {
403
+ const merged = {};
404
+ const TOTAL_SALES = constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES;
405
+ const AMOUNT_COLLECTED = constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED;
406
+ const CREDIT_BILLS = constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS;
407
+ for (const report of reports) {
408
+ for (const [key, metrics] of Object.entries(report.sale_type_metrics ?? {})) {
409
+ const entry = merged[key] ??
410
+ (merged[key] = {
411
+ [TOTAL_SALES]: { orders: createRawOrderMetric(), payments: [] },
412
+ [AMOUNT_COLLECTED]: { orders: createRawOrderMetric() },
413
+ [CREDIT_BILLS]: {
414
+ issued: { count: 0, amount: 0, settled_count: 0, settled_amount: 0 },
415
+ received: { count: 0, amount: 0 },
416
+ },
417
+ });
418
+ addRawOrderMetric(entry[TOTAL_SALES].orders, metrics[TOTAL_SALES]?.orders);
419
+ addRawOrderMetric(entry[AMOUNT_COLLECTED].orders, metrics[AMOUNT_COLLECTED]?.orders);
420
+ for (const payment of metrics[TOTAL_SALES]?.payments ?? []) {
421
+ entry[TOTAL_SALES].payments.push(payment);
422
+ }
423
+ entry[CREDIT_BILLS].issued.count += metrics[CREDIT_BILLS]?.issued?.count ?? 0;
424
+ entry[CREDIT_BILLS].issued.amount += metrics[CREDIT_BILLS]?.issued?.amount ?? 0;
425
+ entry[CREDIT_BILLS].issued.settled_count += metrics[CREDIT_BILLS]?.issued?.settled_count ?? 0;
426
+ entry[CREDIT_BILLS].issued.settled_amount += metrics[CREDIT_BILLS]?.issued?.settled_amount ?? 0;
427
+ entry[CREDIT_BILLS].received.count += metrics[CREDIT_BILLS]?.received?.count ?? 0;
428
+ entry[CREDIT_BILLS].received.amount += metrics[CREDIT_BILLS]?.received?.amount ?? 0;
429
+ }
430
+ }
431
+ return {
432
+ sale_type_key_filters: reports[0]?.sale_type_key_filters ?? [],
433
+ sale_type_metrics: merged,
434
+ };
435
+ };
436
+ /**
437
+ * Frontend formatter for the overview response —
438
+ * `IMaterializedTenantSalesOverviewAggregatedReport[]` (one pipeline-computed
439
+ * record per tenant — the shape of every read).
440
+ *
441
+ * Same page-ready output as `getFormattedTenantSalesOverviewReporting`, with
442
+ * the platform / order-status filters applied client-side on the records'
443
+ * preserved key maps (zero refetches). Differences, by construction:
444
+ * - the slice-derived sections are ALWAYS `null`: `weekday` and `hourly`
445
+ * need per-scope documents — the aggregated record has none (most recent
446
+ * period reads must use the raw response if those sections are ever
447
+ * rendered);
448
+ * - an explicit `day_indexes` filter is REJECTED (`null`): the weekday
449
+ * refinement must narrow the request scope (the calendar selection),
450
+ * never the response;
451
+ * - the combined view (default) folds the tenants' records together; with
452
+ * `separate_view_per_tenant: true` each tenant keeps its own entry.
453
+ *
454
+ * Returns `null` (never throws) when the records cannot be formatted
455
+ * together (mixed key grammars, mismatched brands in the combined view,
456
+ * unsupported filter).
457
+ */
458
+ function getFormattedTenantSalesOverviewAggregatedReporting(reports, filters = null, separate_view_per_tenant = false) {
459
+ if (!Array.isArray(reports) || reports.some((report) => report == null)) {
460
+ return null;
461
+ }
462
+ if (filters != null && Array.isArray(filters.day_indexes) && filters.day_indexes.length > 0) {
463
+ return null;
464
+ }
465
+ if (reports.length > 0) {
466
+ const keyFilterSignature = (reports[0].sale_type_key_filters ?? []).join(':');
467
+ for (const report of reports) {
468
+ // The combined view folds the tenants' records together — same guard as
469
+ // the raw merge (`canMergeMaterializedReportsIgnoringTenant`): one brand.
470
+ // Per-tenant views (`separate_view_per_tenant`) never cross brands.
471
+ if (!separate_view_per_tenant && report.brand_id !== reports[0].brand_id)
472
+ return null;
473
+ if ((report.sale_type_key_filters ?? []).join(':') !== keyFilterSignature)
474
+ return null;
475
+ }
476
+ }
477
+ if (reports.length === 0) {
478
+ return [[buildEmptyPageData(null, [])], null];
479
+ }
480
+ const groups = [];
481
+ if (separate_view_per_tenant) {
482
+ const byTenant = new Map();
483
+ for (const report of reports) {
484
+ const group = byTenant.get(report.tenant_id) ?? [];
485
+ group.push(report);
486
+ byTenant.set(report.tenant_id, group);
487
+ }
488
+ for (const tenantId of [...byTenant.keys()].sort()) {
489
+ groups.push(byTenant.get(tenantId));
490
+ }
491
+ }
492
+ else {
493
+ groups.push(reports);
494
+ }
495
+ const results = [];
496
+ for (const group of groups) {
497
+ const merged = mergeAggregatedKeyMetrics(group);
498
+ const pruned = pruneMetricsMap(merged.sale_type_key_filters, merged.sale_type_metrics, filters);
499
+ results.push(buildPageDataFromMetrics({ sale_type_key_filters: merged.sale_type_key_filters, sale_type_metrics: pruned }, uniqueTenantIds(group), null, null));
500
+ }
501
+ return [results, null];
502
+ }
@@ -256,6 +256,50 @@ function finalizeMetrics(metrics) {
256
256
  }
257
257
  return finalized;
258
258
  }
259
+ /** True for a number that is zero (or broken beyond being distinguishable). */
260
+ const isZeroNumber = (value) => !value;
261
+ const isZeroPaymentMetric = (payment) => isZeroNumber(payment.count) &&
262
+ isZeroNumber(payment.gross_amount) &&
263
+ isZeroNumber(payment.amount_due) &&
264
+ isZeroNumber(payment.amount_paid) &&
265
+ isZeroNumber(payment.amount_refunded) &&
266
+ isZeroNumber(payment.card_charges);
267
+ const isZeroOrderReportMetric = (orders) => isZeroNumber(orders.count) &&
268
+ isZeroNumber(orders.gross_amount) &&
269
+ isZeroNumber(orders.discount_amount) &&
270
+ isZeroNumber(orders.discount_by_type.special_discount) &&
271
+ isZeroNumber(orders.discount_by_type.loyalty_discount) &&
272
+ isZeroNumber(orders.discount_by_type.voucher_discount) &&
273
+ isZeroNumber(orders.gst_amount) &&
274
+ isZeroNumber(orders.tax_amount) &&
275
+ isZeroNumber(orders.tip_amount) &&
276
+ isZeroNumber(orders.tax_invoice_provider_charges) &&
277
+ isZeroNumber(orders.delivery_charges);
278
+ /**
279
+ * Reconcile-time cleanup: subtracting a day can zero a key out while leaving
280
+ * it behind — a "zombie" key that would make accumulated period documents
281
+ * diverge from day / hour reads (which simply lose the key). Compile output
282
+ * never carries all-zero keys, so pruning only removes reconcile artifacts.
283
+ * A key whose payments are all zero-valued counts as empty (subtraction can
284
+ * leave zero-count payment entries behind).
285
+ */
286
+ const pruneZeroReportKeys = (metrics) => {
287
+ const pruned = {};
288
+ for (const [key, metric] of Object.entries(metrics)) {
289
+ const totalSales = metric[constants_1.REPORT_SALE_TYPE_ENUM.TOTAL_SALES];
290
+ const amountCollected = metric[constants_1.REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED];
291
+ const creditBills = metric[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS];
292
+ const isZero = isZeroOrderReportMetric(totalSales.orders) &&
293
+ totalSales.payments.every(isZeroPaymentMetric) &&
294
+ isZeroOrderReportMetric(amountCollected.orders) &&
295
+ (amountCollected.payments ?? []).every(isZeroPaymentMetric) &&
296
+ creditBills.issued.bills.length === 0 &&
297
+ creditBills.received.bills.length === 0;
298
+ if (!isZero)
299
+ pruned[key] = metric;
300
+ }
301
+ return pruned;
302
+ };
259
303
  /**
260
304
  * Deep plain-value conversion for mongoose-hydrated values: subdocuments
261
305
  * (`toObject()`), nested `Map`s and document arrays. Plain JSON values are
@@ -877,7 +921,9 @@ function updateMaterializedTenantSalesOverviewReport(existing, updates, options
877
921
  }
878
922
  return {
879
923
  ...existing,
880
- sale_type_metrics: finalizeMetrics(metrics),
924
+ // Reconcile artifacts: a fully-subtracted key is pruned so accumulated
925
+ // period documents keep the same key set as day / hour reads.
926
+ sale_type_metrics: pruneZeroReportKeys(finalizeMetrics(metrics)),
881
927
  // Version metric writes AND ledger-changing received-payment patches (both
882
928
  // append a history row via the caller). No-op patches bump nothing, so
883
929
  // replays stay churn-free.
@@ -1,5 +1,7 @@
1
1
  import Mongoose from 'mongoose';
2
2
  import { IOrder } from '../../schemas';
3
+ export declare const MAX_NUM_OF_GUESTS = 1000;
4
+ export declare function getValidNumOfGuests(num_of_guests?: number | null): number;
3
5
  export declare function generateOrderDineinDetails(dinein_details?: IOrder['dinein_details']): IOrder['dinein_details'];
4
6
  export declare function generateOrderCategories(categories?: IOrder['categories']): IOrder['categories'];
5
7
  export declare function generateOrderOnCreate<T extends IOrder | Partial<IOrder>>(order: T, withIterations?: boolean): T;
@@ -3,12 +3,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MAX_NUM_OF_GUESTS = void 0;
7
+ exports.getValidNumOfGuests = getValidNumOfGuests;
6
8
  exports.generateOrderDineinDetails = generateOrderDineinDetails;
7
9
  exports.generateOrderCategories = generateOrderCategories;
8
10
  exports.generateOrderOnCreate = generateOrderOnCreate;
9
11
  exports.generateOrderOnUpdate = generateOrderOnUpdate;
10
12
  const mongoose_1 = __importDefault(require("mongoose"));
11
13
  const constants_1 = require("../../constants");
14
+ // num_of_guests is persisted as a BSON int32 (orders collection validator: bsonType 'int', minimum 1).
15
+ // Corrupt client values (e.g. 3257330333) serialize as a double and make the whole order write fail
16
+ // document validation — clamp to a sane range on every normalization pass.
17
+ exports.MAX_NUM_OF_GUESTS = 1000;
18
+ function getValidNumOfGuests(num_of_guests) {
19
+ const numOfGuests = Number(num_of_guests);
20
+ if (!Number.isFinite(numOfGuests) || numOfGuests < 1)
21
+ return 1;
22
+ return Math.min(Math.floor(numOfGuests), exports.MAX_NUM_OF_GUESTS);
23
+ }
12
24
  function generateOrderDineinDetails(dinein_details) {
13
25
  if (!dinein_details)
14
26
  return null;
@@ -16,6 +28,7 @@ function generateOrderDineinDetails(dinein_details) {
16
28
  ...dinein_details,
17
29
  floor_id: new mongoose_1.default.Types.ObjectId(dinein_details.floor_id),
18
30
  table_id: new mongoose_1.default.Types.ObjectId(dinein_details.table_id),
31
+ num_of_guests: getValidNumOfGuests(dinein_details.num_of_guests),
19
32
  reservation_time: new Date(dinein_details.reservation_time),
20
33
  start_time: new Date(dinein_details.start_time),
21
34
  };
@@ -24,6 +24,7 @@ exports.getVoidItemsWithReason = getVoidItemsWithReason;
24
24
  exports.getSplitOrdersFromOrder = getSplitOrdersFromOrder;
25
25
  const bson_objectid_1 = __importDefault(require("bson-objectid"));
26
26
  const constants_1 = require("../../constants");
27
+ const generate_order_1 = require("../order/generate-order");
27
28
  const utils_1 = require("../utils");
28
29
  const cart_actions_1 = require("./cart-actions");
29
30
  /* ======================>Order Object<====================== */
@@ -201,7 +202,7 @@ function getOrderWithPrice(order, toCents) {
201
202
  ? {
202
203
  dinein_details: {
203
204
  ...order.dinein_details,
204
- num_of_guests: order.dinein_details.num_of_guests || 1,
205
+ num_of_guests: (0, generate_order_1.getValidNumOfGuests)(order.dinein_details.num_of_guests),
205
206
  },
206
207
  }
207
208
  : {}),
@@ -259,9 +260,12 @@ function getCommonOptionalBoolFields(order, partial) {
259
260
  }
260
261
  function getCommonOptionalNullFields(order, partial) {
261
262
  const defaultValue = partial ? undefined : null;
263
+ const dineinDetails = order['dinein_details'];
262
264
  return {
263
265
  delivery_details: order['delivery_details'] || defaultValue,
264
- dinein_details: order['dinein_details'] || defaultValue,
266
+ dinein_details: dineinDetails != null
267
+ ? { ...dineinDetails, num_of_guests: (0, generate_order_1.getValidNumOfGuests)(dineinDetails.num_of_guests) }
268
+ : defaultValue,
265
269
  takeaway_details: order['takeaway_details'] || defaultValue,
266
270
  staff_details: order['staff_details'] || defaultValue,
267
271
  order_taker_details: order['order_taker_details'] || defaultValue,
@@ -533,7 +537,7 @@ function syncDineinCoursesOnSplit(dinein_details, swapedItemIdsMap, totalChecks,
533
537
  }
534
538
  const result = {
535
539
  ...dinein_details,
536
- num_of_guests,
540
+ num_of_guests: (0, generate_order_1.getValidNumOfGuests)(num_of_guests),
537
541
  courses: newCourses,
538
542
  };
539
543
  return result;
@@ -18,6 +18,7 @@ export * from './marketing';
18
18
  export * from './materialized-reports-apis';
19
19
  export * from './order-engine';
20
20
  export * from './pra-generate-invoice';
21
+ export * from './report-calendar';
21
22
  export * from './report-webview';
22
23
  export * from './reports';
23
24
  export * from './smartpay-apis';
@@ -34,6 +34,7 @@ __exportStar(require("./marketing"), exports);
34
34
  __exportStar(require("./materialized-reports-apis"), exports);
35
35
  __exportStar(require("./order-engine"), exports);
36
36
  __exportStar(require("./pra-generate-invoice"), exports);
37
+ __exportStar(require("./report-calendar"), exports);
37
38
  __exportStar(require("./report-webview"), exports);
38
39
  __exportStar(require("./reports"), exports);
39
40
  __exportStar(require("./smartpay-apis"), exports);
@@ -1,4 +1,7 @@
1
- import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '../../constants';
1
+ import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, REPORT_SALE_TYPE_ENUM } from '../../constants';
2
+ import { MATERIALIZED_REPORT_KEY_FILTER_ENUM } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { IMaterializedReportOrderMetric, IMaterializedReportPaymentMetric } from '../../schemas/types/materialized_tenant_sales_overview_reports';
4
+ import { IGetMaterializedReportSelectionSpec } from './report-calendar';
2
5
  /**
3
6
  * Request body contracts for the materialized reports READ APIs
4
7
  * (operations-service, mounted at `/reports`) — shared between
@@ -7,39 +10,57 @@ import { MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM } from '.
7
10
  *
8
11
  * Every endpoint takes the tenant scope as an ARRAY (`tenants`, minimum
9
12
  * length 1) so a single call can serve one tenant or many (brand-level
10
- * reports). Responses are the persisted documents themselves (see
11
- * `IMaterializedTenantSalesOverviewReport` /
12
- * `IMaterializedTenantReportIteration`) — amounts are INTEGER CENTS.
13
+ * reports). Amounts are INTEGER CENTS. The response shape never varies:
14
+ * EVERY read is answered with ONE aggregated record per tenant
15
+ * (`IMaterializedTenantSalesOverviewAggregatedReport[]`).
13
16
  */
14
17
  /**
15
- * Body of `POST /reports/overview` — materialized sales overview
16
- * documents (`materialized_tenant_sales_overview_reports`).
18
+ * ONE scope group of a read — a single `scope_context` with its exact
19
+ * values. A smart caller can mix groups (e.g. a time SPAN read: `localHour`
20
+ * labels for the partial boundary days + `localDate` values for the full
21
+ * days between them); the backend runs one aggregation branch per group and
22
+ * folds all of them into the SAME per-tenant record.
17
23
  *
18
- * The scope query is either the exact `scope_field`, or the inclusive
19
- * lexicographic range `from`..`to` (all scope_field formats are fixed-width,
20
- * so lexicographic order equals chronological order).
24
+ * `scope_context` is optional; the backend defaults it to `LOCAL_DATE`.
25
+ * `scope_field` holds EXACT values (minimum length 1) — a single value is
26
+ * matched with direct equality, multiple values with `$in`; lexical
27
+ * `from`..`to` ranges are NOT part of the contract (removed). Groups must
28
+ * not overlap — the backend simply unions their matched documents.
21
29
  */
22
- export interface IGetMaterializedTenantSalesOverviewReportsBody {
30
+ export interface IGetMaterializedReportScopeGroup {
31
+ scope_context?: MATERIALIZED_REPORT_SCOPE_ENUM;
32
+ scope_field: string[];
33
+ }
34
+ /**
35
+ * Shared body of the materialized reports READ APIs — every report endpoint
36
+ * (`POST /reports/overview` today; X / Z / Riders / Items / … as they land)
37
+ * takes the same shape: the TENANTS plus the CALENDAR SELECTION to serve.
38
+ *
39
+ * The client ships the selection itself (`IReportCalendarSelection` — a few
40
+ * hundred bytes regardless of range); the BACKEND decodes it into the exact
41
+ * scope values (`buildMaterializedReportScopeGroupsFromSelection`) and folds
42
+ * each scope group inside MongoDB into ONE aggregated record per tenant — the
43
+ * response shape never varies. Enumerating scope values client-side is NOT
44
+ * part of the wire contract anymore.
45
+ */
46
+ export interface IGetMaterializedReportBody {
23
47
  /** One or more tenant ids to read (minimum length 1). */
24
48
  tenants: string[];
25
49
  /**
26
- * Scope granularity — one of `MATERIALIZED_REPORT_SCOPE_ENUM`. Optional;
27
- * the backend defaults to `LOCAL_DATE`.
28
- */
29
- scope_context?: MATERIALIZED_REPORT_SCOPE_ENUM;
30
- /** Exact scope value (e.g. '2026-09-30' or '2026-09-30 18'). */
31
- scope_field?: string;
32
- /**
33
- * Inclusive lower bound on `scope_field` — required together with `to` when
34
- * `scope_field` is absent.
35
- */
36
- from?: string;
37
- /**
38
- * Inclusive upper bound on `scope_field` — required together with `from`
39
- * when `scope_field` is absent.
50
+ * The committed calendar selection to serve. `spec_version` pins the
51
+ * selection model version (`MATERIALIZED_REPORT_SELECTION_SPEC_VERSION`) —
52
+ * the read API rejects unknown versions with a 400, so rolling deploys
53
+ * (old client → new backend) fail loudly instead of decoding a stale
54
+ * shape.
40
55
  */
41
- to?: string;
56
+ selection: IGetMaterializedReportSelectionSpec;
42
57
  }
58
+ /**
59
+ * Body of `POST /reports/overview` — materialized sales overview
60
+ * documents (`materialized_tenant_sales_overview_reports`). Same shape as
61
+ * every materialized reports read body.
62
+ */
63
+ export type IGetMaterializedTenantSalesOverviewReportsBody = IGetMaterializedReportBody;
43
64
  /**
44
65
  * Body of `POST /reports/iterations` — the latest stored versions
45
66
  * of ONE report document from `materialized_tenant_reports_iterations` (the
@@ -63,3 +84,74 @@ export interface IGetMaterializedReportIterationsBody {
63
84
  /** Latest N iterations, newest-first. Optional; default 5, capped at 50. */
64
85
  limit?: number;
65
86
  }
87
+ /**
88
+ * Per-key metrics of an AGGREGATED overview record — same key grammar as the
89
+ * stored documents' `sale_type_metrics`, produced by the backend's
90
+ * aggregation pipeline (operations-service — backend-only).
91
+ *
92
+ * Deliberately leaner than the stored shape (the pipeline never materializes
93
+ * what no view reads):
94
+ * - `payments` is summed ONLY under `TOTAL_SALES` (the slot the frontend
95
+ * payment breakdown reads); `AMOUNT_COLLECTED` carries orders only;
96
+ * - the credit-bill ledgers (`issued.bills[]` / `received.bills[]`) are
97
+ * dropped — only the counters the report views derive from are kept.
98
+ */
99
+ export interface IMaterializedTenantSalesOverviewAggregatedKeyMetrics {
100
+ [REPORT_SALE_TYPE_ENUM.TOTAL_SALES]: {
101
+ orders: IMaterializedReportOrderMetric;
102
+ payments: IMaterializedReportPaymentMetric[];
103
+ };
104
+ [REPORT_SALE_TYPE_ENUM.AMOUNT_COLLECTED]: {
105
+ orders: IMaterializedReportOrderMetric;
106
+ };
107
+ [REPORT_SALE_TYPE_ENUM.CREDIT_BILLS]: {
108
+ issued: {
109
+ count: number;
110
+ amount: number;
111
+ settled_count: number;
112
+ settled_amount: number;
113
+ };
114
+ received: {
115
+ count: number;
116
+ amount: number;
117
+ };
118
+ };
119
+ }
120
+ /**
121
+ * ONE aggregated record per tenant — the response of EVERY overview read
122
+ * (for a single-value read `matched_documents` is 1 and the span collapses
123
+ * to that value). The backend folds every matched scope document into this
124
+ * record inside MongoDB — nothing beyond this record crosses the
125
+ * DB → service boundary.
126
+ *
127
+ * The `sale_type_metrics` key map is fully preserved, so the frontend can
128
+ * still apply its platform / order-status filters client-side on a single
129
+ * record — via `getFormattedTenantSalesOverviewAggregatedReporting`.
130
+ *
131
+ * NOT part of the stored schema: carries no `_id`, `iteration`,
132
+ * `schema_version`, `source_watermark`, `computed_at` or timestamps — only
133
+ * the report values plus the read context (`matched_documents` and the
134
+ * `scope_field` span) useful for debugging. No `scope_context`: a span read
135
+ * mixes several.
136
+ */
137
+ export interface IMaterializedTenantSalesOverviewAggregatedReport {
138
+ tenant_id: string;
139
+ brand_id: string;
140
+ /**
141
+ * How many stored scope documents were folded into this record — an EXACT
142
+ * count, independent of the key map (documents with disjoint key sets
143
+ * and order-less documents with an empty key map still count).
144
+ */
145
+ matched_documents: number;
146
+ /**
147
+ * First / last matched scope value. Lexicographic order is chronological
148
+ * for the fixed-width period formats; for hour labels it is per-label-day
149
+ * only — never order hour series lexicographically (see
150
+ * `getMaterializedBusinessHourIndex`). For a single-value read both are
151
+ * equal.
152
+ */
153
+ first_scope_field: string;
154
+ last_scope_field: string;
155
+ sale_type_key_filters: MATERIALIZED_REPORT_KEY_FILTER_ENUM[];
156
+ sale_type_metrics: Record<string, IMaterializedTenantSalesOverviewAggregatedKeyMetrics>;
157
+ }
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("../../constants");
@@ -0,0 +1,20 @@
1
+ import { DAY_INDEX_ENUM } from '../../constants/ENUMS';
2
+ import { CALENDAR_MODE_ENUM, CALENDAR_VIEW_MODE_ENUM } from '../../constants/REPORT_CALENDAR';
3
+ export interface IReportCalendarSelection {
4
+ mode: CALENDAR_MODE_ENUM;
5
+ view: CALENDAR_VIEW_MODE_ENUM;
6
+ rangeStart: string | null;
7
+ rangeEnd: string | null;
8
+ selectedDates: string[];
9
+ timeStart: string | null;
10
+ timeEnd: string | null;
11
+ selectedPeriods: string[];
12
+ weekdays: DAY_INDEX_ENUM[];
13
+ }
14
+ /**
15
+ * A read body's `selection` — the calendar selection plus the spec version
16
+ * the request was built against (`MATERIALIZED_REPORT_SELECTION_SPEC_VERSION`).
17
+ */
18
+ export interface IGetMaterializedReportSelectionSpec extends IReportCalendarSelection {
19
+ spec_version: number;
20
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -16,9 +16,9 @@ export declare const InternalInvoiceSchema: Schema<any, import("mongoose").Model
16
16
  customer_name: string;
17
17
  status: import("../../constants").INTERNAL_INVOICE_STATUS_ENUM;
18
18
  payment_method: string;
19
- grand_total: number;
20
19
  tax_number: string;
21
20
  tax_amount: number;
21
+ grand_total: number;
22
22
  subtotal: number;
23
23
  payment_terms: string;
24
24
  notes: string;
@@ -44,9 +44,9 @@ export declare const InternalInvoiceSchema: Schema<any, import("mongoose").Model
44
44
  customer_name: string;
45
45
  status: import("../../constants").INTERNAL_INVOICE_STATUS_ENUM;
46
46
  payment_method: string;
47
- grand_total: number;
48
47
  tax_number: string;
49
48
  tax_amount: number;
49
+ grand_total: number;
50
50
  subtotal: number;
51
51
  payment_terms: string;
52
52
  notes: string;
@@ -72,9 +72,9 @@ export declare const InternalInvoiceSchema: Schema<any, import("mongoose").Model
72
72
  customer_name: string;
73
73
  status: import("../../constants").INTERNAL_INVOICE_STATUS_ENUM;
74
74
  payment_method: string;
75
- grand_total: number;
76
75
  tax_number: string;
77
76
  tax_amount: number;
77
+ grand_total: number;
78
78
  subtotal: number;
79
79
  payment_terms: string;
80
80
  notes: string;
@@ -47,9 +47,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
47
47
  count: number;
48
48
  discount_amount: number;
49
49
  delivery_charges: number;
50
- gst_amount: number;
51
50
  tip_amount: number;
52
51
  tax_amount: number;
52
+ gst_amount: number;
53
53
  tax_invoice_provider_charges: number;
54
54
  gross_amount: number;
55
55
  discount_by_type: {
@@ -89,9 +89,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
89
89
  count: number;
90
90
  discount_amount: number;
91
91
  delivery_charges: number;
92
- gst_amount: number;
93
92
  tip_amount: number;
94
93
  tax_amount: number;
94
+ gst_amount: number;
95
95
  tax_invoice_provider_charges: number;
96
96
  gross_amount: number;
97
97
  discount_by_type: {
@@ -212,9 +212,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
212
212
  count: number;
213
213
  discount_amount: number;
214
214
  delivery_charges: number;
215
- gst_amount: number;
216
215
  tip_amount: number;
217
216
  tax_amount: number;
217
+ gst_amount: number;
218
218
  tax_invoice_provider_charges: number;
219
219
  gross_amount: number;
220
220
  discount_by_type: {
@@ -254,9 +254,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
254
254
  count: number;
255
255
  discount_amount: number;
256
256
  delivery_charges: number;
257
- gst_amount: number;
258
257
  tip_amount: number;
259
258
  tax_amount: number;
259
+ gst_amount: number;
260
260
  tax_invoice_provider_charges: number;
261
261
  gross_amount: number;
262
262
  discount_by_type: {
@@ -377,9 +377,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
377
377
  count: number;
378
378
  discount_amount: number;
379
379
  delivery_charges: number;
380
- gst_amount: number;
381
380
  tip_amount: number;
382
381
  tax_amount: number;
382
+ gst_amount: number;
383
383
  tax_invoice_provider_charges: number;
384
384
  gross_amount: number;
385
385
  discount_by_type: {
@@ -419,9 +419,9 @@ export declare const MaterializedTenantSalesOverviewReportSchema: Schema<any, im
419
419
  count: number;
420
420
  discount_amount: number;
421
421
  delivery_charges: number;
422
- gst_amount: number;
423
422
  tip_amount: number;
424
423
  tax_amount: number;
424
+ gst_amount: number;
425
425
  tax_invoice_provider_charges: number;
426
426
  gross_amount: number;
427
427
  discount_by_type: {