@managesome/eposmatic-toolkit 0.4.61 → 0.4.63

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 (122) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +77 -0
  2. package/esm/constants/MATERIALIZED_SCHEMA_VERSIONS.js +17 -0
  3. package/esm/constants/TENANT_ENUMS.js +15 -0
  4. package/esm/constants/WORKER_ENDPOINTS.js +14 -2
  5. package/esm/helpers/materialized-reports/index.js +4 -0
  6. package/esm/helpers/materialized-reports/materialized-credit-bills-helpers.js +3 -3
  7. package/esm/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +5 -5
  8. package/esm/helpers/materialized-reports/materialized-delivery-compile-helpers.js +2 -2
  9. package/esm/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +5 -5
  10. package/esm/helpers/materialized-reports/materialized-dialer-compile-helpers.js +2 -2
  11. package/esm/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +5 -5
  12. package/esm/helpers/materialized-reports/materialized-dinein-compile-helpers.js +2 -2
  13. package/esm/helpers/materialized-reports/materialized-discount-compile-helpers.js +3 -3
  14. package/esm/helpers/materialized-reports/materialized-document-size.js +2 -2
  15. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +3 -1
  16. package/esm/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -3
  17. package/esm/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +3 -3
  18. package/esm/helpers/materialized-reports/materialized-report-runs.js +143 -0
  19. package/esm/helpers/materialized-reports/report-compile.js +38 -0
  20. package/esm/helpers/materialized-reports/tenant-sales-overview-bson.js +27 -0
  21. package/esm/helpers/materialized-reports/tenant-sales-overview-helpers.js +3 -22
  22. package/esm/schemas/models/index.js +1 -0
  23. package/esm/schemas/models/materialized_credit_bills.js +2 -1
  24. package/esm/schemas/models/materialized_tenant_delivery_entries.js +2 -1
  25. package/esm/schemas/models/materialized_tenant_delivery_reports.js +2 -1
  26. package/esm/schemas/models/materialized_tenant_dialer_entries.js +2 -1
  27. package/esm/schemas/models/materialized_tenant_dialer_reports.js +2 -1
  28. package/esm/schemas/models/materialized_tenant_dinein_entries.js +2 -1
  29. package/esm/schemas/models/materialized_tenant_dinein_reports.js +2 -1
  30. package/esm/schemas/models/materialized_tenant_report_runs.js +105 -0
  31. package/esm/schemas/models/materialized_tenant_sales_overview_reports.js +2 -1
  32. package/esm/schemas/models/tenant_active_jobs.js +19 -1
  33. package/esm/schemas/types/index.js +1 -0
  34. package/lib/constants/MATERIALIZED_REPORTS.d.ts +69 -0
  35. package/lib/constants/MATERIALIZED_REPORTS.js +78 -1
  36. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.d.ts +17 -0
  37. package/lib/constants/MATERIALIZED_SCHEMA_VERSIONS.js +20 -0
  38. package/lib/constants/TENANT_ENUMS.d.ts +14 -0
  39. package/lib/constants/TENANT_ENUMS.js +16 -1
  40. package/lib/constants/WORKER_ENDPOINTS.d.ts +12 -2
  41. package/lib/constants/WORKER_ENDPOINTS.js +14 -2
  42. package/lib/helpers/materialized-reports/index.d.ts +3 -0
  43. package/lib/helpers/materialized-reports/index.js +27 -0
  44. package/lib/helpers/materialized-reports/materialized-credit-bills-helpers.js +4 -4
  45. package/lib/helpers/materialized-reports/materialized-delivery-close-day-helpers.js +6 -6
  46. package/lib/helpers/materialized-reports/materialized-delivery-compile-helpers.js +4 -4
  47. package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +6 -6
  48. package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.js +6 -6
  49. package/lib/helpers/materialized-reports/materialized-dinein-close-day-helpers.js +6 -6
  50. package/lib/helpers/materialized-reports/materialized-dinein-compile-helpers.js +6 -6
  51. package/lib/helpers/materialized-reports/materialized-discount-compile-helpers.js +3 -3
  52. package/lib/helpers/materialized-reports/materialized-document-size.js +2 -5
  53. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +2 -0
  54. package/lib/helpers/materialized-reports/materialized-prep-time-close-day-helpers.js +3 -3
  55. package/lib/helpers/materialized-reports/materialized-prep-time-compile-helpers.js +3 -3
  56. package/lib/helpers/materialized-reports/materialized-report-runs.d.ts +105 -0
  57. package/lib/helpers/materialized-reports/materialized-report-runs.js +156 -0
  58. package/lib/helpers/materialized-reports/report-compile.d.ts +38 -0
  59. package/lib/helpers/materialized-reports/report-compile.js +87 -0
  60. package/lib/helpers/materialized-reports/tenant-sales-overview-bson.d.ts +12 -0
  61. package/lib/helpers/materialized-reports/tenant-sales-overview-bson.js +33 -0
  62. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.d.ts +1 -12
  63. package/lib/helpers/materialized-reports/tenant-sales-overview-helpers.js +4 -24
  64. package/lib/helpers/types/workers.d.ts +65 -0
  65. package/lib/schemas/models/index.d.ts +1 -0
  66. package/lib/schemas/models/index.js +1 -0
  67. package/lib/schemas/models/materialized_credit_bills.d.ts +29 -46
  68. package/lib/schemas/models/materialized_credit_bills.js +3 -2
  69. package/lib/schemas/models/materialized_tenant_cash_entries.d.ts +9 -9
  70. package/lib/schemas/models/materialized_tenant_cash_reports.d.ts +9 -9
  71. package/lib/schemas/models/materialized_tenant_delivery_entries.d.ts +11 -10
  72. package/lib/schemas/models/materialized_tenant_delivery_entries.js +3 -2
  73. package/lib/schemas/models/materialized_tenant_delivery_geo_cells.d.ts +9 -9
  74. package/lib/schemas/models/materialized_tenant_delivery_geo_scopes.d.ts +6 -6
  75. package/lib/schemas/models/materialized_tenant_delivery_reports.d.ts +11 -10
  76. package/lib/schemas/models/materialized_tenant_delivery_reports.js +3 -2
  77. package/lib/schemas/models/materialized_tenant_dialer_entries.d.ts +8 -7
  78. package/lib/schemas/models/materialized_tenant_dialer_entries.js +3 -2
  79. package/lib/schemas/models/materialized_tenant_dialer_reports.d.ts +11 -10
  80. package/lib/schemas/models/materialized_tenant_dialer_reports.js +3 -2
  81. package/lib/schemas/models/materialized_tenant_dinein_entries.d.ts +8 -7
  82. package/lib/schemas/models/materialized_tenant_dinein_entries.js +3 -2
  83. package/lib/schemas/models/materialized_tenant_dinein_reports.d.ts +11 -10
  84. package/lib/schemas/models/materialized_tenant_dinein_reports.js +3 -2
  85. package/lib/schemas/models/materialized_tenant_discount_entries.d.ts +9 -9
  86. package/lib/schemas/models/materialized_tenant_discount_reports.d.ts +9 -9
  87. package/lib/schemas/models/materialized_tenant_discount_sources.d.ts +9 -9
  88. package/lib/schemas/models/materialized_tenant_hourly_comparison_entries.d.ts +9 -9
  89. package/lib/schemas/models/materialized_tenant_hourly_comparison_reports.d.ts +9 -9
  90. package/lib/schemas/models/materialized_tenant_payments_comparison_entries.d.ts +9 -9
  91. package/lib/schemas/models/materialized_tenant_payments_comparison_reports.d.ts +9 -9
  92. package/lib/schemas/models/materialized_tenant_prep_time_entries.d.ts +9 -9
  93. package/lib/schemas/models/materialized_tenant_prep_time_reports.d.ts +9 -9
  94. package/lib/schemas/models/materialized_tenant_report_runs.d.ts +97 -0
  95. package/lib/schemas/models/materialized_tenant_report_runs.js +108 -0
  96. package/lib/schemas/models/materialized_tenant_sales_comparison_entries.d.ts +9 -9
  97. package/lib/schemas/models/materialized_tenant_sales_comparison_reports.d.ts +9 -9
  98. package/lib/schemas/models/materialized_tenant_sales_overview_reports.d.ts +11 -35
  99. package/lib/schemas/models/materialized_tenant_sales_overview_reports.js +3 -2
  100. package/lib/schemas/models/tenant_active_jobs.d.ts +12 -3
  101. package/lib/schemas/models/tenant_active_jobs.js +18 -0
  102. package/lib/schemas/types/index.d.ts +1 -0
  103. package/lib/schemas/types/index.js +1 -0
  104. package/lib/schemas/types/materialized_tenant_report_runs.d.ts +55 -0
  105. package/lib/schemas/types/tenant_active_jobs.d.ts +15 -1
  106. package/lib/tests/materialized-reports/materialized-report-runs.test.js +116 -0
  107. package/lib/tests/materialized-reports/tenant-dinein-formatter.test.js +159 -0
  108. package/lib/tests/materialized-reports/tenant-sales-overview-close-day-helpers.test.js +2 -1
  109. package/lib/tests/materialized-reports/tenant-sales-overview-helpers.test.js +5 -4
  110. package/lib/tests/reporting-contract/no-live-transport.test.js +106 -0
  111. package/package.json +2 -1
  112. package/lib/helpers/order/payment-collection.d.ts +0 -25
  113. package/lib/helpers/order/payment-collection.js +0 -51
  114. package/lib/schemas/models/applied_order_discounts.d.ts +0 -80
  115. package/lib/schemas/models/applied_order_discounts.js +0 -106
  116. package/lib/schemas/types/applied_order_discounts.d.ts +0 -22
  117. package/lib/tests/payment-collection-timestamps.test.d.ts +0 -1
  118. package/lib/tests/payment-collection-timestamps.test.js +0 -71
  119. /package/{lib/tests/materialized-reports/analytics-growth-helpers.test.d.ts → esm/schemas/types/materialized_tenant_report_runs.js} +0 -0
  120. /package/lib/schemas/types/{applied_order_discounts.js → materialized_tenant_report_runs.js} +0 -0
  121. /package/lib/tests/materialized-reports/{analytics-overview-helpers.test.d.ts → materialized-report-runs.test.d.ts} +0 -0
  122. /package/lib/tests/{materialized-reports/analytics-performance-helpers.test.d.ts → reporting-contract/no-live-transport.test.d.ts} +0 -0
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_report_runs_1 = require("../../helpers/materialized-reports/materialized-report-runs");
5
+ const materialized_tenant_report_runs_1 = require("../../schemas/models/materialized_tenant_report_runs");
6
+ const report_contract_1 = require("../../helpers/reporting-contract/report-contract");
7
+ /**
8
+ * Report run ledger contract (Phase 1 of END_TENANT_DAY).
9
+ *
10
+ * The ledger is the OPERATIONAL record of one report execution and is separate
11
+ * from readiness: FAILED never appears in readiness.
12
+ */
13
+ describe('materialized report run ledger contract', () => {
14
+ const identity = {
15
+ tenantId: 'tenant-a',
16
+ localDate: '2026-09-14',
17
+ reportKey: report_contract_1.REPORT_KEY_ENUM.OVERVIEW,
18
+ };
19
+ it('pins the operational collection + schema version', () => {
20
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUNS_COLLECTION_NAME).toBe('materialized_tenant_report_runs');
21
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUNS_SCHEMA_VERSION).toBe(1);
22
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_MAX_ATTEMPTS).toBe(2);
23
+ });
24
+ it('has exactly the five operational statuses and no FAILED readiness leak', () => {
25
+ expect(Object.values(MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STATUS_ENUM).sort()).toEqual(['COMMITTED', 'FAILED', 'PENDING', 'RETRYING', 'RUNNING'].sort());
26
+ // Readiness never gains FAILED: it is the read gate, not the ledger.
27
+ expect(Object.values(MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_READINESS_STATUS_ENUM)).not.toContain('FAILED');
28
+ });
29
+ it('builds ONE stable identity key/filter per report', () => {
30
+ expect((0, materialized_report_runs_1.materializedReportRunKey)(identity)).toBe('tenant-a|2026-09-14|OVERVIEW|1');
31
+ expect((0, materialized_report_runs_1.buildMaterializedReportRunFilter)(identity)).toEqual({
32
+ tenant_id: 'tenant-a',
33
+ localDate: '2026-09-14',
34
+ report_key: 'OVERVIEW',
35
+ schema_version: 1,
36
+ });
37
+ });
38
+ it('allows retry only for FAILED or a MISSING run', () => {
39
+ expect((0, materialized_report_runs_1.canRetryMaterializedReportRun)(null)).toBe(true);
40
+ expect((0, materialized_report_runs_1.canRetryMaterializedReportRun)(undefined)).toBe(true);
41
+ expect((0, materialized_report_runs_1.canRetryMaterializedReportRun)('FAILED')).toBe(true);
42
+ for (const blocked of ['PENDING', 'RUNNING', 'RETRYING', 'COMMITTED']) {
43
+ expect((0, materialized_report_runs_1.canRetryMaterializedReportRun)(blocked)).toBe(false);
44
+ expect((0, materialized_report_runs_1.isMaterializedReportRunInFlight)(blocked)).toBe(blocked !== 'COMMITTED');
45
+ }
46
+ });
47
+ it('detects terminal states and only ages IN-FLIGHT runs as stale', () => {
48
+ expect((0, materialized_report_runs_1.isMaterializedReportRunTerminal)('COMMITTED')).toBe(true);
49
+ expect((0, materialized_report_runs_1.isMaterializedReportRunTerminal)('FAILED')).toBe(true);
50
+ for (const live of ['PENDING', 'RUNNING', 'RETRYING']) {
51
+ expect((0, materialized_report_runs_1.isMaterializedReportRunTerminal)(live)).toBe(false);
52
+ }
53
+ const now = new Date('2026-09-15T12:00:00.000Z');
54
+ const startedAt = new Date(now.getTime() - MATERIALIZED_REPORTS_1.MATERIALIZED_TENANT_REPORT_RUN_STALE_MS);
55
+ expect((0, materialized_report_runs_1.isMaterializedReportRunStale)({ run: { status: 'RUNNING', started_at: startedAt }, now })).toBe(true);
56
+ expect((0, materialized_report_runs_1.isMaterializedReportRunStale)({
57
+ run: { status: 'RUNNING', started_at: new Date(now.getTime() - 1000) },
58
+ now,
59
+ })).toBe(false);
60
+ // Terminal rows are never "stale": they are final.
61
+ expect((0, materialized_report_runs_1.isMaterializedReportRunStale)({ run: { status: 'COMMITTED', started_at: startedAt }, now })).toBe(false);
62
+ // A legacy row without started_at falls back to updatedAt.
63
+ expect((0, materialized_report_runs_1.isMaterializedReportRunStale)({
64
+ run: { status: 'RETRYING', updatedAt: startedAt },
65
+ now,
66
+ })).toBe(true);
67
+ });
68
+ it('proves readiness ownership by RUN id, never by status alone', () => {
69
+ // Same run -> the readiness row is proof.
70
+ expect((0, materialized_report_runs_1.isMaterializedReadinessOwnedByRun)({
71
+ readiness: { run_id: 'lease-B' },
72
+ run: { run_id: 'lease-B' },
73
+ })).toBe(true);
74
+ // An OLDER close's row proves nothing about the current run.
75
+ expect((0, materialized_report_runs_1.isMaterializedReadinessOwnedByRun)({
76
+ readiness: { run_id: 'lease-A' },
77
+ run: { run_id: 'lease-B' },
78
+ })).toBe(false);
79
+ expect((0, materialized_report_runs_1.isMaterializedReadinessOwnedByRun)({
80
+ readiness: null,
81
+ run: { run_id: 'lease-B' },
82
+ })).toBe(false);
83
+ // A run without an identity can never be proven by readiness.
84
+ expect((0, materialized_report_runs_1.isMaterializedReadinessOwnedByRun)({
85
+ readiness: { run_id: 'lease-B' },
86
+ run: { run_id: null },
87
+ })).toBe(false);
88
+ });
89
+ it('detects the UNKNOWN-COMMIT marker', () => {
90
+ expect((0, materialized_report_runs_1.isMaterializedReportRunCommitOutcomeUnknown)({
91
+ last_error: 'COMMIT_OUTCOME_UNKNOWN',
92
+ })).toBe(true);
93
+ expect((0, materialized_report_runs_1.isMaterializedReportRunCommitOutcomeUnknown)({
94
+ last_error: 'INTERRUPTED_RUN',
95
+ })).toBe(false);
96
+ expect((0, materialized_report_runs_1.isMaterializedReportRunCommitOutcomeUnknown)(null)).toBe(false);
97
+ });
98
+ it('declares (never applies) the unique per-report identity index', () => {
99
+ const unique = materialized_tenant_report_runs_1.MATERIALIZED_TENANT_REPORT_RUNS_INDEX_OPTIONS.filter((index) => index.unique === true);
100
+ expect(unique).toHaveLength(1);
101
+ expect(unique[0].key).toEqual({
102
+ tenant_id: 1,
103
+ localDate: 1,
104
+ report_key: 1,
105
+ schema_version: 1,
106
+ });
107
+ });
108
+ it('sanitizes durable errors: no PII, single line, bounded', () => {
109
+ const sanitized = (0, materialized_report_runs_1.sanitizeMaterializedReportRunError)(new Error('dialer failed for jane.doe@example.com phone +92 300 1234567\nsecond line ' + 'x'.repeat(2000)));
110
+ expect(sanitized).not.toContain('jane.doe@example.com');
111
+ expect(sanitized).not.toContain('1234567');
112
+ expect(sanitized).toContain('[redacted-email]');
113
+ expect(sanitized).not.toContain('\n');
114
+ expect(sanitized.length).toBeLessThanOrEqual(500);
115
+ });
116
+ });
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
4
  const materialized_dinein_close_day_helpers_1 = require("../../helpers/materialized-reports/materialized-dinein-close-day-helpers");
5
+ const materialized_integer_contract_1 = require("../../helpers/materialized-reports/materialized-integer-contract");
5
6
  const tenant_dinein_formatter_1 = require("../../helpers/materialized-reports/tenant-dinein-formatter");
6
7
  const dinein_fixtures_1 = require("./dinein-fixtures");
7
8
  /**
@@ -296,4 +297,162 @@ describe('dinein formatter', () => {
296
297
  // the day documents are formatted at their own scope level
297
298
  expect(formatted.scopes).toEqual([{ scope_context: 'localDate', scope_field: dinein_fixtures_1.DINEIN_DAY }]);
298
299
  });
300
+ /**
301
+ * The formatter's documented unit is 0–100 PERCENT for every derived rate /
302
+ * share. The admin adapter converts ONCE to a 0–1 ratio at its boundary; a
303
+ * test that pins the unit here prevents the two sides drifting again.
304
+ */
305
+ it('publishes derived rates in the documented 0–100 percent unit', () => {
306
+ const documents = documentsFor([
307
+ {
308
+ _id: 'percent-check',
309
+ amount_earned: 21400,
310
+ service_fee_amount: 1000,
311
+ is_service_fee_percentage: true,
312
+ is_service_fee_taxable: true,
313
+ categories: [{ items: [{ _id: 'line-a', quantity: 2 }] }],
314
+ iterations: [{ categories: [{ items: [{ _id: 'line-a', quantity: 1 }] }], platform: 'POS_DINE-IN' }],
315
+ dinein_details: {
316
+ table_id: 'table-t04',
317
+ table_name: 'T-04',
318
+ floor_id: 'floor-main',
319
+ start_time: '2026-10-01T13:00:00.000Z',
320
+ courses: [{ course_id: 'c-mains', name: 'Mains', item_ids: ['line-a'], called: true }],
321
+ },
322
+ payments: [
323
+ { payment_type: 'CARD', amount_paid: 20000, amount_refunded: 500 },
324
+ { payment_type: 'CASH', amount_paid: 1400, amount_refunded: 0 },
325
+ ],
326
+ },
327
+ ], { guests: { 'percent-check': 4 } });
328
+ const { summary, by_course } = (0, tenant_dinein_formatter_1.formatMaterializedDineinReport)(documents);
329
+ // 1000 / 21400 = 4.67% — a 0–100 percent value, not a ratio.
330
+ expect(summary.service_charge_share).toBe(4.67);
331
+ // 1 edited check out of 1 = 100%.
332
+ expect(summary.edit_rate).toBe(100);
333
+ // 1 called course out of 1 = 100%.
334
+ expect(summary.course_call_rate).toBe(100);
335
+ // 19500 net card of 20900 collected = 93.3%.
336
+ expect(summary.card_share).toBe(93.3);
337
+ // A 0–100 percent value is > 1 whenever the share is above 1%.
338
+ expect(summary.service_charge_share).toBeGreaterThan(1);
339
+ expect(by_course[0].call_rate).toBe(100);
340
+ // No derived rate/share/average leaf lives in the STORED documents.
341
+ const derivedNames = new Set([
342
+ 'average_ticket',
343
+ 'average_covers_per_check',
344
+ 'cancelled_rate',
345
+ 'service_charge_share',
346
+ 'split_sales_share',
347
+ 'offline_sales_share',
348
+ 'edit_rate',
349
+ 'average_edits_per_check',
350
+ 'course_call_rate',
351
+ 'card_share',
352
+ 'cash_share',
353
+ 'other_share',
354
+ 'average_rating',
355
+ 'average_occupancy_minutes',
356
+ 'call_rate',
357
+ 'share',
358
+ 'rate',
359
+ 'average',
360
+ ]);
361
+ const numericPaths = [];
362
+ const walk = (node, path) => {
363
+ if (typeof node === 'number')
364
+ numericPaths.push(path);
365
+ if (Array.isArray(node))
366
+ node.forEach((item, index) => walk(item, `${path}[${index}]`));
367
+ else if (node != null && typeof node === 'object') {
368
+ for (const [key, value] of Object.entries(node)) {
369
+ walk(value, path === '' ? key : `${path}.${key}`);
370
+ }
371
+ }
372
+ };
373
+ for (const document of documents)
374
+ walk(document, '');
375
+ for (const path of numericPaths) {
376
+ const leaf = path.slice(path.lastIndexOf('.') + 1);
377
+ // `service_charge_rate_counts` is a COUNT map keyed by a string rate; its
378
+ // leaves are counts, not rates.
379
+ if (path.includes('service_charge_rate_counts'))
380
+ continue;
381
+ expect(derivedNames.has(leaf)).toBe(false);
382
+ }
383
+ for (const document of documents) {
384
+ expect((0, materialized_integer_contract_1.findNonIntegerNumericLeaves)(document)).toEqual([]);
385
+ }
386
+ });
387
+ /**
388
+ * The writer materializes a reservations-only day as a document with an EMPTY
389
+ * counter map. Formatting it must still publish the reservation block, the
390
+ * by-hour chart and the bounded snapshot — a zero-check day is not a zero
391
+ * reservation day.
392
+ */
393
+ it('formats a reservations-only document with an empty counter map', () => {
394
+ const compile = (0, dinein_fixtures_1.compileDay)({
395
+ orders: [],
396
+ reservations: [(0, dinein_fixtures_1.dineinReservation)({ num_of_guests: 4 })],
397
+ });
398
+ expect(compile).not.toBeNull();
399
+ const plan = (0, materialized_dinein_close_day_helpers_1.buildTenantDineinCloseDayPlan)({
400
+ tenantId: dinein_fixtures_1.DINEIN_TENANT,
401
+ localDate: dinein_fixtures_1.DINEIN_DAY,
402
+ reports: compile.reports,
403
+ entries: compile.entries,
404
+ reason: 'NEW_DAY',
405
+ });
406
+ const documents = plan.writes
407
+ .filter((write) => String(write.report.scope_context) === 'localDate')
408
+ .map((write) => write.report);
409
+ expect(documents).toHaveLength(1);
410
+ expect(documents[0].dinein_counters).toEqual({});
411
+ expect(documents[0].reservation_counters.reservations).toBe(1);
412
+ const formatted = (0, tenant_dinein_formatter_1.formatMaterializedDineinReport)(documents);
413
+ expect(formatted.summary.orders).toBe(0);
414
+ expect(formatted.summary.sales).toBe(0);
415
+ expect(formatted.summary.tables_served_distinct).toBe(0);
416
+ expect(formatted.reservations.reservations).toBe(1);
417
+ expect(formatted.reservations.reservation_covers).toBe(4);
418
+ expect(formatted.reservations.average_party_size).toBe(4);
419
+ expect(formatted.reservation_by_hour[18]).toEqual({
420
+ hour: 18,
421
+ label: '18',
422
+ reservations: 1,
423
+ reservation_covers: 4,
424
+ });
425
+ expect(formatted.upcoming_reservations).toHaveLength(1);
426
+ // No counter key was invented for a day with no check.
427
+ expect(formatted.by_status).toEqual([]);
428
+ expect(formatted.by_platform).toEqual([]);
429
+ });
430
+ it('keeps every compiled document and entry page integer-only', () => {
431
+ const documents = documentsFor([
432
+ {
433
+ _id: 'integer-check',
434
+ amount_earned: 21400,
435
+ service_fee_amount: 1000,
436
+ is_service_fee_percentage: true,
437
+ categories: [{ items: [{ _id: 'line-a', quantity: 2 }] }],
438
+ payments: [
439
+ { payment_type: 'CARD', amount_paid: 20000, amount_refunded: 500 },
440
+ { payment_type: 'CASH', amount_paid: 1400, amount_refunded: 0 },
441
+ ],
442
+ },
443
+ ], { guests: { 'integer-check': 4 }, reservations: [{ num_of_guests: 3 }] });
444
+ expect(documents.length).toBeGreaterThan(0);
445
+ for (const document of documents) {
446
+ expect((0, materialized_integer_contract_1.findNonIntegerNumericLeaves)(document)).toEqual([]);
447
+ }
448
+ const compile = (0, dinein_fixtures_1.compileDay)({
449
+ orders: [(0, dinein_fixtures_1.dineinOrder)({ _id: 'page-check' })],
450
+ fingerprints: [(0, dinein_fixtures_1.dineinFingerprint)('page-check', { num_of_guests: 2 })],
451
+ });
452
+ for (const page of compile.entries) {
453
+ expect((0, materialized_integer_contract_1.findNonIntegerNumericLeaves)(page)).toEqual([]);
454
+ }
455
+ // Every entry scope is page-partitioned by the source day and integer-only.
456
+ expect(compile.entries.map((page) => String(page.scope_context)).sort()).toEqual([...MATERIALIZED_REPORTS_1.MATERIALIZED_DINEIN_ENTRY_SCOPES].sort());
457
+ });
299
458
  });
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const constants_1 = require("../../constants");
4
4
  const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
5
  const tenant_sales_overview_close_day_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-close-day-helpers");
6
+ const tenant_sales_overview_bson_1 = require("../../helpers/materialized-reports/tenant-sales-overview-bson");
6
7
  const tenant_sales_overview_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-helpers");
7
8
  const materialized_credit_bills_helpers_1 = require("../../helpers/materialized-reports/materialized-credit-bills-helpers");
8
9
  /** Narrows helper results that are `null` on invalid data (tests expect valid data). */
@@ -453,7 +454,7 @@ describe('tenant sales overview close-day plan', () => {
453
454
  // Real hydration shape: `Model.find()` docs carry the `sale_type_metrics` Map
454
455
  // with mongoose subdocument values (NOT plain objects).
455
456
  const hydratedStored = world1.docs.map((doc) => doc.scope_context === LOCAL_DATE && doc.scope_field === D1
456
- ? (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(doc).toObject()
457
+ ? (0, tenant_sales_overview_bson_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(doc).toObject()
457
458
  : doc);
458
459
  const plan = closeDay(D2, [cashD2, collectedCredit], { docs: hydratedStored, credit: world1.credit }, CT2);
459
460
  expect(plan.receivedPatches).toHaveLength(8); // the hydrated D1 date doc is still detected + patched
@@ -6,6 +6,7 @@ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
6
6
  const key_helpers_1 = require("../../helpers/materialized-reports/key-helpers");
7
7
  const materialized_tenant_reports_iterations_helpers_1 = require("../../helpers/materialized-reports/materialized-tenant-reports-iterations-helpers");
8
8
  const scope_helpers_1 = require("../../helpers/materialized-reports/scope-helpers");
9
+ const tenant_sales_overview_bson_1 = require("../../helpers/materialized-reports/tenant-sales-overview-bson");
9
10
  const tenant_sales_overview_helpers_1 = require("../../helpers/materialized-reports/tenant-sales-overview-helpers");
10
11
  const time_helpers_1 = require("../../helpers/utils/time-helpers");
11
12
  const fixtures_1 = require("./fixtures");
@@ -521,14 +522,14 @@ describe('credit-bill lifecycle (synthetic PAY_LATER orders)', () => {
521
522
  expect(bareCompile.credit_bill_issues[0]?.issued_at).toEqual(computedAt);
522
523
  });
523
524
  it('converts the JSON document to a mongoose (BSON) document', () => {
524
- const hydrated = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(issueDateDoc);
525
+ const hydrated = (0, tenant_sales_overview_bson_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(issueDateDoc);
525
526
  expect(hydrated.get('scope_context')).toBe('localDate');
526
527
  expect(hydrated.get('sale_type_metrics')).toBeInstanceOf(Map);
527
528
  const metrics = hydrated.get('sale_type_metrics');
528
529
  const issued = metrics.get('COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].issued;
529
530
  expect(issued?.count).toBe(1);
530
531
  expect(issued?.amount).toBe(1200);
531
- const hydratedCollect = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(collectDateDoc);
532
+ const hydratedCollect = (0, tenant_sales_overview_bson_1.convertMaterializedTenantSalesOverviewReportJsonToBson)(collectDateDoc);
532
533
  const collectedMetrics = hydratedCollect.get('sale_type_metrics');
533
534
  const received = collectedMetrics.get('COMPLETED:POS_WALK-IN')?.[constants_1.REPORT_SALE_TYPE_ENUM.CREDIT_BILLS].received;
534
535
  expect(received?.count).toBe(1);
@@ -901,11 +902,11 @@ describe('subtract + versioned reconcile (iteration bump)', () => {
901
902
  });
902
903
  // Real hydration shapes: `Model.find()` / json→BSON cast docs carry the Map
903
904
  // with mongoose subdocument values; `.toObject()` output keeps them too.
904
- const hydrated = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
905
+ const hydrated = (0, tenant_sales_overview_bson_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
905
906
  ...stored,
906
907
  _id: '68dd3f9c9f1b2c3d4e5f6a7b',
907
908
  }).toObject();
908
- const hydratedFlattened = (0, tenant_sales_overview_helpers_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
909
+ const hydratedFlattened = (0, tenant_sales_overview_bson_1.convertMaterializedTenantSalesOverviewReportJsonToBson)({
909
910
  ...stored,
910
911
  _id: '68dd3f9c9f1b2c3d4e5f6a7b',
911
912
  }).toObject({ flattenMaps: true });
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const node_fs_1 = __importDefault(require("node:fs"));
40
+ const node_path_1 = __importDefault(require("node:path"));
41
+ const WORKER_ENDPOINTS_1 = require("../../constants/WORKER_ENDPOINTS");
42
+ const reportCompile = __importStar(require("../../helpers/materialized-reports/report-compile"));
43
+ /**
44
+ * SHARED CONTRACT SURFACE — after the live-proxy revert and the direct-API move.
45
+ *
46
+ * - no internal live summary/details transport types;
47
+ * - no WORKER_ENDPOINTS entry for the removed live proxy or the catalog reads
48
+ * that items-service owns now;
49
+ * - the pure `report-compile` subpath still exposes the close compilers.
50
+ *
51
+ * The `report-compile` import graph must stay mongoose-free: it is the worker
52
+ * boundary for BOTH services' Piscina compile threads.
53
+ */
54
+ const root = process.cwd();
55
+ const readSource = (relative) => node_fs_1.default.readFileSync(node_path_1.default.join(root, relative), 'utf8');
56
+ test('the internal live transport module is removed', () => {
57
+ expect(node_fs_1.default.existsSync(node_path_1.default.join(root, 'src/helpers/reporting-contract/live-reports.ts'))).toBe(false);
58
+ const barrel = readSource('src/helpers/reporting-contract/index.ts');
59
+ expect(barrel).not.toContain('live-reports');
60
+ });
61
+ test('no WORKER_ENDPOINTS entry is a live-proxy or moved catalog path', () => {
62
+ const values = Object.values(WORKER_ENDPOINTS_1.WORKER_ENDPOINTS);
63
+ expect(values.some((value) => value.includes('/live'))).toBe(false);
64
+ expect('ITEMS_USING_MODIFIER' in WORKER_ENDPOINTS_1.WORKER_ENDPOINTS).toBe(false);
65
+ expect('AUDIT_ITEM_MODIFIERS' in WORKER_ENDPOINTS_1.WORKER_ENDPOINTS).toBe(false);
66
+ // The endpoints that MUST stay.
67
+ expect(WORKER_ENDPOINTS_1.WORKER_ENDPOINTS.END_TENANT_DAY).toBe('/end-tenant-day');
68
+ expect(WORKER_ENDPOINTS_1.WORKER_ENDPOINTS.RETRY_MATERIALIZED_REPORT).toBe('/internal/materialization/reports/retry');
69
+ expect(WORKER_ENDPOINTS_1.WORKER_ENDPOINTS.RECONCILE_MATERIALIZED_REPORT_RUNS).toBe('/internal/materialization/reports/reconcile');
70
+ });
71
+ test('the pure report-compile subpath still exports the close compilers', () => {
72
+ expect(typeof reportCompile.compileTenantDineinReports).toBe('function');
73
+ expect(typeof reportCompile.compileTenantDiscountReports).toBe('function');
74
+ expect(typeof reportCompile.compileTenantPrepTimeReports).toBe('function');
75
+ expect(typeof reportCompile.compileTenantDialerReports).toBe('function');
76
+ expect(typeof reportCompile.compileTenantDeliveryReports).toBe('function');
77
+ expect(typeof reportCompile.convertOrdersToMaterializedTenantSalesOverviewReports).toBe('function');
78
+ });
79
+ test('the report-compile import graph contains no mongoose or schema model', () => {
80
+ const entry = 'src/helpers/materialized-reports/report-compile.ts';
81
+ const visited = new Set();
82
+ const queue = [entry];
83
+ while (queue.length > 0) {
84
+ const current = queue.shift();
85
+ if (visited.has(current))
86
+ continue;
87
+ visited.add(current);
88
+ const source = readSource(current);
89
+ // Type-only imports are erased by tsc and never load a module.
90
+ const runtimeSource = source
91
+ .replace(/import\s+type\s+[^;]+?from\s*['"][^'"]+['"];?/gs, '')
92
+ .replace(/export\s+type\s+\{[^}]*\}\s*from\s*['"][^'"]+['"];?/gs, '');
93
+ expect(runtimeSource).not.toContain("from 'mongoose'");
94
+ expect(runtimeSource).not.toContain('from "mongoose"');
95
+ for (const match of runtimeSource.matchAll(/(?:from|import)\s*\(?\s*['"](\.[^'"]+)['"]/g)) {
96
+ const candidate = node_path_1.default.posix.normalize(node_path_1.default.posix.join(node_path_1.default.posix.dirname(current), match[1]));
97
+ // Toolkit sources use extensionless specifiers; services use `.js`.
98
+ const asTs = candidate.endsWith('.js') ? candidate.replace(/\.js$/, '.ts') : `${candidate}.ts`;
99
+ if (node_fs_1.default.existsSync(node_path_1.default.join(root, asTs)))
100
+ queue.push(asTs);
101
+ }
102
+ }
103
+ // The graph is real (not an empty walk) and includes the service-facing API.
104
+ expect(visited.size).toBeGreaterThan(5);
105
+ expect([...visited].some((file) => file.includes('materialized-dinein-'))).toBe(true);
106
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@managesome/eposmatic-toolkit",
3
- "version": "0.4.61",
3
+ "version": "0.4.63",
4
4
  "description": "A Toolkit Library for Eposmatic",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",
@@ -32,6 +32,7 @@
32
32
  "test:characterization": "jest --config jestconfig.json src/tests/materialized-reports/characterization --runInBand"
33
33
  },
34
34
  "dependencies": {
35
+ "bson": "^6.10.3",
35
36
  "bson-objectid": "^2.0.4",
36
37
  "crypto-js": "^4.2.0",
37
38
  "emoji-strip": "^1.0.1",
@@ -1,25 +0,0 @@
1
- import { IOrderPayment } from '../../schemas/types/orders';
2
- /**
3
- * Server-owned `collected_at` stamping for order payments.
4
- *
5
- * A payment line is the unit a credit bill lives on: the sale is issued on the
6
- * punch day, and money may arrive later (full or partial). `order_settled_at`
7
- * only moves on FULL settlement, so it cannot anchor a partial collection.
8
- * This helper records the LAST collection moment on the payment itself,
9
- * derived by comparing `amount_paid` with the stored previous version.
10
- *
11
- * Rules:
12
- * - never trust the incoming `collected_at` (clients may send anything);
13
- * - a NEW payment line with money in (`amount_paid > 0`) gets `now`;
14
- * - an EXISTING line whose `amount_paid` increased gets `now`;
15
- * - unchanged / decreased / zero-amount lines keep the stored timestamp
16
- * (`null` when unknown — legacy rows are not backfilled here).
17
- *
18
- * Pure and never throws. `previousPayments` must be the SERVER copy of the
19
- * order's payments before the write (pass none on create).
20
- */
21
- export interface IStampPaymentCollectionTimestampsOptions {
22
- /** Override for the collection instant (tests / offline replays). */
23
- now?: Date | string | null;
24
- }
25
- export declare function stampPaymentCollectionTimestamps(payments: IOrderPayment[] | null | undefined, previousPayments?: IOrderPayment[] | null | undefined, options?: IStampPaymentCollectionTimestampsOptions): IOrderPayment[];
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stampPaymentCollectionTimestamps = stampPaymentCollectionTimestamps;
4
- const constants_1 = require("../../constants");
5
- const toValidDate = (value) => {
6
- if (value == null)
7
- return null;
8
- const date = value instanceof Date ? value : new Date(value);
9
- return Number.isNaN(date.getTime()) ? null : date;
10
- };
11
- /** Stable identity across a merge: subdoc `_id` first, then `payment_id`. */
12
- const identityOf = (payment) => {
13
- if (payment._id != null && String(payment._id).trim() !== '') {
14
- return `id:${String(payment._id)}`;
15
- }
16
- if (typeof payment.payment_id === 'string' && payment.payment_id.trim() !== '') {
17
- return `payment:${payment.payment_id}`;
18
- }
19
- return null;
20
- };
21
- function stampPaymentCollectionTimestamps(payments, previousPayments = null, options = {}) {
22
- if (!Array.isArray(payments))
23
- return [];
24
- const now = toValidDate(options.now) ?? new Date();
25
- const previousByIdentity = new Map();
26
- for (const previous of Array.isArray(previousPayments) ? previousPayments : []) {
27
- if (previous == null)
28
- continue;
29
- const identity = identityOf(previous);
30
- if (identity != null)
31
- previousByIdentity.set(identity, previous);
32
- }
33
- return payments.map((payment) => {
34
- if (payment == null)
35
- return payment;
36
- const identity = identityOf(payment);
37
- const previous = identity != null ? previousByIdentity.get(identity) : undefined;
38
- const previousCollectedAt = toValidDate(previous?.collected_at);
39
- const amountPaid = Number(payment.amount_paid ?? 0);
40
- const previousAmountPaid = Number(previous?.amount_paid ?? 0);
41
- const isFailed = payment.payment_status === constants_1.PAYMENT_STATUS_ENUM.FAILED;
42
- const isNewCollection = !isFailed &&
43
- Number.isFinite(amountPaid) &&
44
- amountPaid > 0 &&
45
- (previous == null || amountPaid > previousAmountPaid);
46
- return {
47
- ...payment,
48
- collected_at: isNewCollection ? now : previousCollectedAt,
49
- };
50
- });
51
- }
@@ -1,80 +0,0 @@
1
- import { Schema } from 'mongoose';
2
- export declare const AppliedOrderDiscountsSchema: Schema<any, import("mongoose").Model<any, any, any, any, any, any>, {}, {}, {}, {}, {
3
- timestamps: true;
4
- versionKey: false;
5
- minimize: false;
6
- }, {
7
- createdAt: NativeDate;
8
- updatedAt: NativeDate;
9
- } & {
10
- _id: import("mongoose").Types.ObjectId;
11
- type: import("../../constants").DISCOUNT_TYPE_ENUM;
12
- name: string;
13
- tenant_id: string;
14
- order_id: import("mongoose").Types.ObjectId;
15
- discount_id: string;
16
- applicability: import("../../constants").DISCOUNT_APPLICABILITY_ENUM;
17
- platform: import("../../constants").PLATFORMS_ENUM;
18
- order_amount: number;
19
- discount_amount: number;
20
- reason: string;
21
- staff_id: string;
22
- staff_phone: string;
23
- staff_name: string;
24
- createdAt_mins: number;
25
- createdAt: NativeDate;
26
- updatedAt: NativeDate;
27
- discount_rate?: number | null | undefined;
28
- reference_number?: string | null | undefined;
29
- }, import("mongoose").Document<unknown, {}, import("mongoose").FlatRecord<{
30
- createdAt: NativeDate;
31
- updatedAt: NativeDate;
32
- } & {
33
- _id: import("mongoose").Types.ObjectId;
34
- type: import("../../constants").DISCOUNT_TYPE_ENUM;
35
- name: string;
36
- tenant_id: string;
37
- order_id: import("mongoose").Types.ObjectId;
38
- discount_id: string;
39
- applicability: import("../../constants").DISCOUNT_APPLICABILITY_ENUM;
40
- platform: import("../../constants").PLATFORMS_ENUM;
41
- order_amount: number;
42
- discount_amount: number;
43
- reason: string;
44
- staff_id: string;
45
- staff_phone: string;
46
- staff_name: string;
47
- createdAt_mins: number;
48
- createdAt: NativeDate;
49
- updatedAt: NativeDate;
50
- discount_rate?: number | null | undefined;
51
- reference_number?: string | null | undefined;
52
- }>> & import("mongoose").FlatRecord<{
53
- createdAt: NativeDate;
54
- updatedAt: NativeDate;
55
- } & {
56
- _id: import("mongoose").Types.ObjectId;
57
- type: import("../../constants").DISCOUNT_TYPE_ENUM;
58
- name: string;
59
- tenant_id: string;
60
- order_id: import("mongoose").Types.ObjectId;
61
- discount_id: string;
62
- applicability: import("../../constants").DISCOUNT_APPLICABILITY_ENUM;
63
- platform: import("../../constants").PLATFORMS_ENUM;
64
- order_amount: number;
65
- discount_amount: number;
66
- reason: string;
67
- staff_id: string;
68
- staff_phone: string;
69
- staff_name: string;
70
- createdAt_mins: number;
71
- createdAt: NativeDate;
72
- updatedAt: NativeDate;
73
- discount_rate?: number | null | undefined;
74
- reference_number?: string | null | undefined;
75
- }> & Required<{
76
- _id: import("mongoose").Types.ObjectId;
77
- }> & {
78
- __v: number;
79
- }>;
80
- export declare const APPLIED_ORDER_DISCOUNTS_COLLECTION_NAME = "applied_order_discounts";