@managesome/eposmatic-toolkit 0.4.55 → 0.4.56

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 (70) hide show
  1. package/esm/constants/MATERIALIZED_REPORTS.js +91 -0
  2. package/esm/helpers/materialized-reports/index.js +7 -0
  3. package/esm/helpers/materialized-reports/materialized-dialer-accumulator-helpers.js +100 -0
  4. package/esm/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +328 -0
  5. package/esm/helpers/materialized-reports/materialized-dialer-compile-helpers.js +180 -0
  6. package/esm/helpers/materialized-reports/materialized-dialer-entry-pages.js +222 -0
  7. package/esm/helpers/materialized-reports/materialized-dialer-key-helpers.js +82 -0
  8. package/esm/helpers/materialized-reports/materialized-dialer-masking.js +54 -0
  9. package/esm/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  10. package/esm/helpers/materialized-reports/materialized-report-drilldown-rows.js +13 -1
  11. package/esm/helpers/materialized-reports/report-platform/definition.js +85 -1
  12. package/esm/helpers/materialized-reports/tenant-dialer-formatter.js +95 -0
  13. package/esm/helpers/reporting-contract/report-contract.js +3 -0
  14. package/esm/schemas/models/index.js +2 -0
  15. package/esm/schemas/models/materialized_report_drilldown_rows.js +1 -0
  16. package/esm/schemas/models/materialized_tenant_dialer_entries.js +65 -0
  17. package/esm/schemas/models/materialized_tenant_dialer_reports.js +66 -0
  18. package/esm/schemas/types/index.js +2 -0
  19. package/esm/schemas/types/materialized_report_drilldown_rows.js +1 -0
  20. package/esm/schemas/types/materialized_tenant_dialer_entries.js +1 -0
  21. package/esm/schemas/types/materialized_tenant_dialer_reports.js +7 -0
  22. package/lib/constants/MATERIALIZED_REPORTS.d.ts +72 -2
  23. package/lib/constants/MATERIALIZED_REPORTS.js +93 -1
  24. package/lib/helpers/materialized-reports/index.d.ts +7 -0
  25. package/lib/helpers/materialized-reports/index.js +7 -0
  26. package/lib/helpers/materialized-reports/materialized-dialer-accumulator-helpers.d.ts +39 -0
  27. package/lib/helpers/materialized-reports/materialized-dialer-accumulator-helpers.js +110 -0
  28. package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.d.ts +90 -0
  29. package/lib/helpers/materialized-reports/materialized-dialer-close-day-helpers.js +340 -0
  30. package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.d.ts +67 -0
  31. package/lib/helpers/materialized-reports/materialized-dialer-compile-helpers.js +183 -0
  32. package/lib/helpers/materialized-reports/materialized-dialer-entry-pages.d.ts +97 -0
  33. package/lib/helpers/materialized-reports/materialized-dialer-entry-pages.js +235 -0
  34. package/lib/helpers/materialized-reports/materialized-dialer-key-helpers.d.ts +51 -0
  35. package/lib/helpers/materialized-reports/materialized-dialer-key-helpers.js +90 -0
  36. package/lib/helpers/materialized-reports/materialized-dialer-masking.d.ts +35 -0
  37. package/lib/helpers/materialized-reports/materialized-dialer-masking.js +57 -0
  38. package/lib/helpers/materialized-reports/materialized-index-bootstrap.js +4 -0
  39. package/lib/helpers/materialized-reports/materialized-report-drilldown-rows.js +13 -1
  40. package/lib/helpers/materialized-reports/report-platform/definition.js +84 -0
  41. package/lib/helpers/materialized-reports/tenant-dialer-formatter.d.ts +91 -0
  42. package/lib/helpers/materialized-reports/tenant-dialer-formatter.js +98 -0
  43. package/lib/helpers/reporting-contract/report-contract.d.ts +1 -0
  44. package/lib/helpers/reporting-contract/report-contract.js +3 -0
  45. package/lib/schemas/models/index.d.ts +2 -0
  46. package/lib/schemas/models/index.js +2 -0
  47. package/lib/schemas/models/materialized_report_drilldown_rows.js +1 -0
  48. package/lib/schemas/models/materialized_tenant_dialer_entries.d.ts +107 -0
  49. package/lib/schemas/models/materialized_tenant_dialer_entries.js +68 -0
  50. package/lib/schemas/models/materialized_tenant_dialer_reports.d.ts +100 -0
  51. package/lib/schemas/models/materialized_tenant_dialer_reports.js +69 -0
  52. package/lib/schemas/models/tenant_dialer_events.d.ts +3 -3
  53. package/lib/schemas/types/index.d.ts +2 -0
  54. package/lib/schemas/types/index.js +2 -0
  55. package/lib/schemas/types/materialized_report_drilldown_rows.d.ts +1 -1
  56. package/lib/schemas/types/materialized_report_drilldown_rows.js +1 -0
  57. package/lib/schemas/types/materialized_tenant_dialer_entries.d.ts +83 -0
  58. package/lib/schemas/types/materialized_tenant_dialer_entries.js +2 -0
  59. package/lib/schemas/types/materialized_tenant_dialer_reports.d.ts +77 -0
  60. package/lib/schemas/types/materialized_tenant_dialer_reports.js +10 -0
  61. package/lib/tests/materialized-reports/materialized-dialer-compile.test.d.ts +1 -0
  62. package/lib/tests/materialized-reports/materialized-dialer-compile.test.js +213 -0
  63. package/lib/tests/materialized-reports/materialized-dialer-formatter.test.d.ts +1 -0
  64. package/lib/tests/materialized-reports/materialized-dialer-formatter.test.js +159 -0
  65. package/lib/tests/materialized-reports/materialized-dialer-plan.test.d.ts +1 -0
  66. package/lib/tests/materialized-reports/materialized-dialer-plan.test.js +223 -0
  67. package/lib/tests/materialized-reports/materialized-tenant-dialer-schema.test.d.ts +1 -0
  68. package/lib/tests/materialized-reports/materialized-tenant-dialer-schema.test.js +183 -0
  69. package/lib/tests/materialized-reports/report-platform/registry-conformance.test.js +16 -3
  70. package/package.json +1 -1
@@ -110,6 +110,12 @@ export var MATERIALIZED_REPORT_KEY_FILTER_ENUM;
110
110
  // OPEN string (live stores carry values outside the enum) and is normalized only
111
111
  // for the PAY_LATER -> UNPAID remap.
112
112
  MATERIALIZED_REPORT_KEY_FILTER_ENUM["PAYMENT_METHOD"] = "PAYMENT_METHOD";
113
+ // Dialer encodes <ACTION>:<POS_ID>:<STAFF_ID>. The action is the dialer event
114
+ // action; pos/staff identify the terminal and the operator. A component the
115
+ // source does not carry is encoded as `UNKNOWN` (never dropped).
116
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM["ACTION"] = "ACTION";
117
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM["POS_ID"] = "POS_ID";
118
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM["STAFF_ID"] = "STAFF_ID";
113
119
  })(MATERIALIZED_REPORT_KEY_FILTER_ENUM || (MATERIALIZED_REPORT_KEY_FILTER_ENUM = {}));
114
120
  export const ALL_MATERIALIZED_REPORT_KEY_FILTERS = Object.values(MATERIALIZED_REPORT_KEY_FILTER_ENUM);
115
121
  /** Ordered key filters of the tenant sales overview report (`PLACED:POS_WALK-IN`). */
@@ -674,6 +680,8 @@ export var MATERIALIZED_REPORT_TYPE_ENUM;
674
680
  MATERIALIZED_REPORT_TYPE_ENUM["TENANT_HOURLY_COMPARISON_ENTRIES"] = "TENANT_HOURLY_COMPARISON_ENTRIES";
675
681
  MATERIALIZED_REPORT_TYPE_ENUM["TENANT_PAYMENTS_COMPARISON_REPORTS"] = "TENANT_PAYMENTS_COMPARISON_REPORTS";
676
682
  MATERIALIZED_REPORT_TYPE_ENUM["TENANT_PAYMENTS_COMPARISON_ENTRIES"] = "TENANT_PAYMENTS_COMPARISON_ENTRIES";
683
+ MATERIALIZED_REPORT_TYPE_ENUM["TENANT_DIALER_REPORTS"] = "TENANT_DIALER_REPORTS";
684
+ MATERIALIZED_REPORT_TYPE_ENUM["TENANT_DIALER_ENTRIES"] = "TENANT_DIALER_ENTRIES";
677
685
  })(MATERIALIZED_REPORT_TYPE_ENUM || (MATERIALIZED_REPORT_TYPE_ENUM = {}));
678
686
  export const ALL_MATERIALIZED_REPORT_TYPES = Object.values(MATERIALIZED_REPORT_TYPE_ENUM);
679
687
  /* =====================> Sales Comparison report <===================== */
@@ -807,3 +815,86 @@ export var PAYMENTS_COMPARISON_METRIC_ENUM;
807
815
  PAYMENTS_COMPARISON_METRIC_ENUM["AMOUNT_DUE"] = "AMOUNT_DUE";
808
816
  })(PAYMENTS_COMPARISON_METRIC_ENUM || (PAYMENTS_COMPARISON_METRIC_ENUM = {}));
809
817
  export const ALL_PAYMENTS_COMPARISON_METRICS = Object.values(PAYMENTS_COMPARISON_METRIC_ENUM);
818
+ /* =====================> Dialer report <===================== */
819
+ /**
820
+ * Dialer report — the FIRST report whose source is an append-only EVENT stream
821
+ * (`tenant_dialer_events`) rather than order-shaped documents.
822
+ *
823
+ * ## No local date is ever invented
824
+ *
825
+ * A dialer event carries its tenant-local fields only when the POS dialer could
826
+ * resolve the running business day at write time. An event with no `localDate`
827
+ * is UNATTRIBUTED: it is never counted into a day (and never assigned to the
828
+ * close's day), so it cannot be double-counted by a later re-close. The
829
+ * materializer reports the day-window unattributed count instead.
830
+ *
831
+ * ## Counters only — no duration, no order attribution
832
+ *
833
+ * The source stores no duration and the report derives none: a call is a set of
834
+ * EVENTS (`CALL_ANSWERED`, `CALL_ENDED`, …), not one row with a duration. The
835
+ * page derives every rate itself from the counters
836
+ * (`outcome_denominator = answered + missed + declined`); nothing derived is
837
+ * stored.
838
+ *
839
+ * ## Key grammar
840
+ *
841
+ * `<ACTION>:<POS_ID>:<STAFF_ID>` — the three key filters. `STAFF_ID` is
842
+ * nullable in the source, so a missing component is encoded as `UNKNOWN`; the
843
+ * event is never dropped for a missing dimension.
844
+ */
845
+ /**
846
+ * Pointer scopes. Like every counters report, the period documents are FOLDED
847
+ * from the sibling DAY documents (the writer never reads another day's rows).
848
+ * No `localHour` scope: the hour dimension is a `by_hour` map INSIDE each
849
+ * counter key, which is the shape the Dialer page renders.
850
+ */
851
+ export const MATERIALIZED_DIALER_REPORT_SCOPES = [
852
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
853
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
854
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
855
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
856
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_QUARTER,
857
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_SEMESTER,
858
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_YEAR,
859
+ ];
860
+ /**
861
+ * Entry scopes: the day page plus the three PERIOD pages. Every period scope is
862
+ * PAGE-PARTITIONED by source day, so an entry document is bounded by one day's
863
+ * events. There is no quarter / semester / year entry document.
864
+ */
865
+ export const MATERIALIZED_DIALER_ENTRY_SCOPES = [
866
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE,
867
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK,
868
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_WEEK_OF_YEAR,
869
+ MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_MONTH,
870
+ ];
871
+ /**
872
+ * Page key of the DAY-scoped entry document. The day scope is already one day,
873
+ * so it needs no per-source-day partition; the three period scopes use the
874
+ * source `localDate` as their page (`page=<source localDate>`).
875
+ */
876
+ export const MATERIALIZED_DIALER_ENTRY_PAGE_ALL = 'all';
877
+ /** Ordered key filters: `<ACTION>:<POS_ID>:<STAFF_ID>`. */
878
+ export const DIALER_KEY_FILTERS = [
879
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM.ACTION,
880
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM.POS_ID,
881
+ MATERIALIZED_REPORT_KEY_FILTER_ENUM.STAFF_ID,
882
+ ];
883
+ /** Token used when a key component is missing (`UNKNOWN`). */
884
+ export const MATERIALIZED_DIALER_UNKNOWN_TOKEN = 'UNKNOWN';
885
+ /** Key component delimiter. Enum/ids cannot contain it; a raw value is sanitized. */
886
+ export const MATERIALIZED_DIALER_KEY_SEPARATOR = ':';
887
+ /**
888
+ * The 24 `by_hour` bucket labels — `"0".."23"` (NOT zero-padded; this is the
889
+ * contract the page renders and the stored documents carry). Every counters
890
+ * block initializes all 24 keys, so a missing bucket is unambiguously zero.
891
+ */
892
+ export const MATERIALIZED_DIALER_HOUR_KEYS = Array.from({ length: 24 }, (_, hour) => String(hour));
893
+ /**
894
+ * Per-collection BSON budgets. MongoDB's hard limit is 16 MiB per document;
895
+ * 15 MiB is the owner-approved practical ceiling, leaving 1 MiB of headroom.
896
+ * A document that exceeds its budget fails at COMPILE/PLAN time, naming the
897
+ * collection + source day + scope — never midway through the close transaction.
898
+ */
899
+ export const MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES = 15 * 1024 * 1024;
900
+ export const MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES = 15 * 1024 * 1024;
@@ -24,6 +24,12 @@ export * from './materialized-delivery-compile-helpers';
24
24
  export * from './materialized-delivery-classification-helpers';
25
25
  export * from './materialized-delivery-close-day-helpers';
26
26
  export * from './materialized-delivery-index-migration';
27
+ export * from './materialized-dialer-accumulator-helpers';
28
+ export * from './materialized-dialer-close-day-helpers';
29
+ export * from './materialized-dialer-compile-helpers';
30
+ export * from './materialized-dialer-entry-pages';
31
+ export * from './materialized-dialer-key-helpers';
32
+ export * from './materialized-dialer-masking';
27
33
  export * from './materialized-day-input-signature';
28
34
  export * from './materialized-cash-classification-helpers';
29
35
  export * from './materialized-cash-close-day-helpers';
@@ -50,6 +56,7 @@ export * from './tenant-discount-formatter';
50
56
  export * from './tenant-discount-source-formatter';
51
57
  export * from './tenant-cash-in-out-formatter';
52
58
  export * from './tenant-delivery-formatter';
59
+ export * from './tenant-dialer-formatter';
53
60
  export * from './tenant-prep-time-formatter';
54
61
  export * from './tenant-sales-overview-formatter';
55
62
  export * from './tenant-sales-overview-helpers';
@@ -0,0 +1,100 @@
1
+ import { DIALER_TYPES_ENUM } from '../../constants/DIALER_ENUMS';
2
+ import { MATERIALIZED_DIALER_HOUR_KEYS } from '../../constants/MATERIALIZED_REPORTS';
3
+ /**
4
+ * Dialer counter accumulation — the ONE place a source event becomes a counter.
5
+ *
6
+ * The counters are pure additive event counts (no money, no duration, no
7
+ * average), so a day compile, a live fold and a close-day period fold all use
8
+ * the same `mergeDialerCounters`. There is no order attribution and no
9
+ * duration: a call is a sequence of events, and the page derives every rate
10
+ * from these integers.
11
+ *
12
+ * `by_hour` always carries all 24 keys (`"0"`..`"23"`), so a missing bucket is
13
+ * unambiguously zero and a period fold is a plain 24-way sum.
14
+ */
15
+ /** The dialer action → counter-field mapping. One definition, no drift. */
16
+ export const MATERIALIZED_DIALER_ACTION_COUNTER = {
17
+ [DIALER_TYPES_ENUM.INCOMING_CALL]: 'incoming_calls',
18
+ [DIALER_TYPES_ENUM.OUTGOING_CALL]: 'outgoing_calls',
19
+ [DIALER_TYPES_ENUM.CALL_ANSWERED]: 'answered',
20
+ [DIALER_TYPES_ENUM.MISSED_CALL]: 'missed',
21
+ [DIALER_TYPES_ENUM.CALL_DECLINED]: 'declined',
22
+ [DIALER_TYPES_ENUM.CALL_ENDED]: 'ended',
23
+ [DIALER_TYPES_ENUM.POS_PING]: 'pos_pings',
24
+ };
25
+ /** A zeroed 24-hour map. */
26
+ export function freshDialerByHour() {
27
+ const byHour = {};
28
+ for (const hour of MATERIALIZED_DIALER_HOUR_KEYS)
29
+ byHour[hour] = 0;
30
+ return byHour;
31
+ }
32
+ /** A zeroed counter block (all 24 hour keys present). */
33
+ export function freshDialerCounters() {
34
+ return {
35
+ events: 0,
36
+ incoming_calls: 0,
37
+ outgoing_calls: 0,
38
+ answered: 0,
39
+ missed: 0,
40
+ declined: 0,
41
+ ended: 0,
42
+ pos_pings: 0,
43
+ by_hour: freshDialerByHour(),
44
+ };
45
+ }
46
+ /** The valid `by_hour` key of a tenant-local hour, or `null` when not a whole hour. */
47
+ export function dialerHourKey(hour) {
48
+ const value = Number(hour);
49
+ if (!Number.isInteger(value) || value < 0 || value > 23)
50
+ return null;
51
+ return String(value);
52
+ }
53
+ /**
54
+ * Adds ONE attributed event to a counter block.
55
+ *
56
+ * `by_hour` is incremented only for an integer hour `0..23`; the compile
57
+ * guarantees attribution already validated the hour, so a caller that passes a
58
+ * malformed hour accrues `events` without inventing a bucket.
59
+ */
60
+ export function addDialerEvent(counters, event) {
61
+ counters.events += 1;
62
+ const action = String(event?.action ?? '');
63
+ const field = MATERIALIZED_DIALER_ACTION_COUNTER[action];
64
+ if (field != null) {
65
+ counters[field] += 1;
66
+ }
67
+ const hour = dialerHourKey(event?.localHour);
68
+ if (hour != null) {
69
+ counters.by_hour[hour] = (Number(counters.by_hour[hour]) || 0) + 1;
70
+ }
71
+ }
72
+ /** Adds every counter of `source` into `target` (in place); returns `target`. */
73
+ export function mergeDialerCounters(target, source) {
74
+ if (source == null)
75
+ return target;
76
+ target.events += Number(source.events) || 0;
77
+ target.incoming_calls += Number(source.incoming_calls) || 0;
78
+ target.outgoing_calls += Number(source.outgoing_calls) || 0;
79
+ target.answered += Number(source.answered) || 0;
80
+ target.missed += Number(source.missed) || 0;
81
+ target.declined += Number(source.declined) || 0;
82
+ target.ended += Number(source.ended) || 0;
83
+ target.pos_pings += Number(source.pos_pings) || 0;
84
+ target.by_hour = target.by_hour ?? freshDialerByHour();
85
+ for (const hour of MATERIALIZED_DIALER_HOUR_KEYS) {
86
+ target.by_hour[hour] = (Number(target.by_hour[hour]) || 0) + (Number(source.by_hour?.[hour]) || 0);
87
+ }
88
+ return target;
89
+ }
90
+ /** Folds a list of counter blocks into one — the live/period read helper. */
91
+ export function sumDialerCounters(blocks) {
92
+ const total = freshDialerCounters();
93
+ for (const block of blocks ?? [])
94
+ mergeDialerCounters(total, block);
95
+ return total;
96
+ }
97
+ /** Folds a key-addressed counter map into one block. */
98
+ export function sumDialerCounterMap(counters) {
99
+ return sumDialerCounters(Object.values(counters ?? {}));
100
+ }
@@ -0,0 +1,328 @@
1
+ import mongoose from 'mongoose';
2
+ import { DIALER_KEY_FILTERS, MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES, MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES, MATERIALIZED_DIALER_REPORT_SCOPES, MATERIALIZED_REPORT_SCOPE_ENUM, MATERIALIZED_REPORT_TYPE_ENUM, } from '../../constants/MATERIALIZED_REPORTS';
3
+ import { MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION } from '../../schemas/models/materialized_tenant_dialer_reports';
4
+ import { freshDialerCounters, mergeDialerCounters } from './materialized-dialer-accumulator-helpers';
5
+ import { dialerEntryPageOf, materializedDialerEntryPageKey } from './materialized-dialer-entry-pages';
6
+ import { assertMaterializedDocumentSize } from './materialized-document-size';
7
+ import { buildMaterializedTenantReportIteration } from './materialized-tenant-reports-iterations-helpers';
8
+ import { enumerateMaterializedPeriodDays, getMaterializedPeriodScopeFields } from './scope-helpers';
9
+ /**
10
+ * Dialer close-day helpers.
11
+ *
12
+ * ## Period counters are RE-FOLDED from sibling DAY documents
13
+ *
14
+ * A period document is a plain sum of its days' event counters, so removing a
15
+ * day from a period is subtractable in principle — but re-folding is the
16
+ * platform rule and the only way an emptied/recompiled day stays exact. Every
17
+ * touched period is rebuilt from its whole day set (the closing day's fresh
18
+ * document plus the stored sibling DAY documents the caller fetched).
19
+ *
20
+ * ## ENTRY pages are NEVER folded
21
+ *
22
+ * `materialized_tenant_dialer_entries` is page-partitioned by source day: the
23
+ * caller fetches exactly the closing day's pages, each is replaced by its page
24
+ * identity, and a fetched page the day no longer owns is deleted. No other
25
+ * day's page is read, merged or rewritten.
26
+ */
27
+ /** Period COUNTER scopes this report materializes (everything but the day scope). */
28
+ export const MATERIALIZED_DIALER_PERIOD_SCOPES = MATERIALIZED_DIALER_REPORT_SCOPES.filter((scope) => String(scope) !== MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE);
29
+ /**
30
+ * Every `localDate` label whose DAY counter document can contribute to a period
31
+ * the closing day rolls into. The worker uses it to fetch exactly the sibling
32
+ * DAY counters the period re-fold needs.
33
+ */
34
+ export function getMaterializedDialerReportPeriodDayScopeFields(localDate) {
35
+ return enumerateMaterializedPeriodDays(localDate, MATERIALIZED_DIALER_PERIOD_SCOPES);
36
+ }
37
+ /** True when the scope is the plain day scope. */
38
+ export const isMaterializedDialerDayScope = (scopeContext) => String(scopeContext) === MATERIALIZED_REPORT_SCOPE_ENUM.LOCAL_DATE;
39
+ const dialerScopeKey = (doc) => String(doc.scope_context) + '|' + String(doc.scope_field);
40
+ /** True when the stored document does not already carry this exact content. */
41
+ export function needsMaterializedDialerReportWrite(existing, next) {
42
+ if (existing == null)
43
+ return true;
44
+ const stored = new Date(existing.source_watermark ?? 0).getTime();
45
+ const incoming = new Date(next.source_watermark ?? 0).getTime();
46
+ if (Number.isNaN(stored) || Number.isNaN(incoming))
47
+ return true;
48
+ return incoming > stored;
49
+ }
50
+ /** True when the stored entry page does not already carry these exact rows. */
51
+ export function needsMaterializedDialerEntriesWrite(existing, next) {
52
+ if (existing == null)
53
+ return true;
54
+ const stored = new Date(existing.source_watermark ?? 0).getTime();
55
+ const incoming = new Date(next.source_watermark ?? 0).getTime();
56
+ if (Number.isNaN(stored) || Number.isNaN(incoming))
57
+ return true;
58
+ return incoming > stored;
59
+ }
60
+ /**
61
+ * Folds the counters of every DAY document belonging to one period scope.
62
+ *
63
+ * The fold is key-addressed: two days that observed the same
64
+ * `<ACTION>:<POS_ID>:<STAFF_ID>` merge their counters; keys only one day
65
+ * observed keep their own block.
66
+ */
67
+ export function foldMaterializedDialerPeriodCounters(input) {
68
+ const { periodScope, periodScopeField, dayDocuments } = input;
69
+ const folded = {};
70
+ for (const dayDocument of dayDocuments ?? []) {
71
+ if (!isMaterializedDialerDayScope(String(dayDocument?.scope_context)))
72
+ continue;
73
+ const fields = getMaterializedPeriodScopeFields(String(dayDocument.scope_field));
74
+ if (fields == null)
75
+ continue;
76
+ if (fields[periodScope] !== periodScopeField)
77
+ continue;
78
+ for (const [key, block] of Object.entries(dayDocument.dialer_counters ?? {})) {
79
+ const target = folded[key] ?? freshDialerCounters();
80
+ mergeDialerCounters(target, block);
81
+ folded[key] = target;
82
+ }
83
+ }
84
+ return folded;
85
+ }
86
+ /**
87
+ * Builds the close-day plan for ONE tenant-day.
88
+ *
89
+ * The DAY scope comes from the compile. Every touched PERIOD scope is re-folded
90
+ * from its whole day set; the touched set is the union of the closing day's
91
+ * periods AND the periods of any day document this close removes.
92
+ */
93
+ export function buildTenantDialerCloseDayPlan(input) {
94
+ if (input == null)
95
+ return null;
96
+ const { tenantId, reports, entries, reason } = input;
97
+ if (typeof tenantId !== 'string' || tenantId.length === 0)
98
+ return null;
99
+ if (typeof reason !== 'string' || reason.length === 0)
100
+ return null;
101
+ const computedAt = input.computedAt ?? new Date();
102
+ const force = input.force === true;
103
+ const compiledReports = (reports ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
104
+ const compiledEntries = (entries ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
105
+ const storedReports = (input.existing ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
106
+ const storedEntries = (input.existingEntries ?? []).filter((doc) => String(doc?.tenant_id) === tenantId);
107
+ const compiledDateDoc = compiledReports.find((doc) => isMaterializedDialerDayScope(String(doc.scope_context)));
108
+ const localDate = input.localDate ?? (compiledDateDoc == null ? null : String(compiledDateDoc.scope_field));
109
+ if (localDate == null || localDate === '')
110
+ return null;
111
+ const writes = [];
112
+ const entryWrites = [];
113
+ const staleDocuments = [];
114
+ const staleEntryDocuments = [];
115
+ const skippedDocuments = [];
116
+ const skippedEntryDocuments = [];
117
+ const storedReportsByScope = new Map();
118
+ for (const doc of storedReports)
119
+ storedReportsByScope.set(dialerScopeKey(doc), doc);
120
+ const storedEntriesByPage = new Map();
121
+ for (const doc of storedEntries) {
122
+ // Legacy page-less entry documents are inconsistent input: the caller must
123
+ // fetch page-partitioned documents only.
124
+ if (typeof doc.page !== 'string' || doc.page === '')
125
+ return null;
126
+ storedEntriesByPage.set(materializedDialerEntryPageKey(doc), doc);
127
+ }
128
+ const addWrite = (report) => {
129
+ const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
130
+ const iteration = buildMaterializedTenantReportIteration(persisted, {
131
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_REPORTS,
132
+ reason,
133
+ computedAt,
134
+ });
135
+ if (iteration == null)
136
+ return false;
137
+ writes.push({ report: persisted, iteration: iteration });
138
+ return true;
139
+ };
140
+ const addEntryWrite = (report) => {
141
+ const persisted = report.iteration == null ? { ...report, iteration: 1 } : report;
142
+ const iteration = buildMaterializedTenantReportIteration(persisted, {
143
+ reportType: MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_ENTRIES,
144
+ reason,
145
+ computedAt,
146
+ });
147
+ if (iteration == null)
148
+ return false;
149
+ entryWrites.push({ report: persisted, iteration: iteration });
150
+ return true;
151
+ };
152
+ // ---- the DAY scope, straight from the compile ----
153
+ if (compiledDateDoc != null) {
154
+ const existing = storedReportsByScope.get(dialerScopeKey(compiledDateDoc));
155
+ const next = {
156
+ ...compiledDateDoc,
157
+ _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
158
+ iteration: Number(existing?.iteration ?? 0) + 1,
159
+ };
160
+ if (force || needsMaterializedDialerReportWrite(existing, next))
161
+ addWrite(next);
162
+ else
163
+ skippedDocuments.push(existing);
164
+ }
165
+ // ---- ENTRY PAGES: exactly the pages the closing day owns ----
166
+ const compiledEntriesByPage = new Map();
167
+ for (const doc of compiledEntries) {
168
+ const expectedPage = dialerEntryPageOf(doc.scope_context, localDate);
169
+ if (expectedPage == null || (doc.page !== expectedPage && !String(doc.page ?? '').startsWith(expectedPage + '#'))) {
170
+ return null;
171
+ }
172
+ const key = materializedDialerEntryPageKey(doc);
173
+ if (compiledEntriesByPage.has(key))
174
+ return null; // duplicate page — data issue
175
+ compiledEntriesByPage.set(key, doc);
176
+ }
177
+ // ---- DAY deletion: a stored day doc that no longer compiled ----
178
+ const compiledDateKeys = new Set(compiledReports
179
+ .filter((doc) => isMaterializedDialerDayScope(String(doc.scope_context)))
180
+ .map((doc) => dialerScopeKey(doc)));
181
+ const removedDates = [];
182
+ for (const doc of storedReports) {
183
+ if (!isMaterializedDialerDayScope(String(doc.scope_context)))
184
+ continue;
185
+ if (String(doc.scope_field) !== localDate)
186
+ continue;
187
+ if (compiledDateKeys.has(dialerScopeKey(doc)))
188
+ continue;
189
+ staleDocuments.push(doc);
190
+ removedDates.push(String(doc.scope_field));
191
+ }
192
+ // ---- PERIOD re-fold ----
193
+ const nextDayDocs = storedReports.filter((doc) => isMaterializedDialerDayScope(String(doc.scope_context)) && String(doc.scope_field) !== localDate);
194
+ if (compiledDateDoc != null) {
195
+ nextDayDocs.push(writes.find((write) => isMaterializedDialerDayScope(String(write.report.scope_context)))?.report ??
196
+ compiledDateDoc);
197
+ }
198
+ const touchedPeriods = new Map();
199
+ const noteDay = (day) => {
200
+ const fields = getMaterializedPeriodScopeFields(day);
201
+ if (fields == null)
202
+ return;
203
+ for (const scope of MATERIALIZED_DIALER_PERIOD_SCOPES) {
204
+ const field = fields[String(scope)];
205
+ if (field == null || field === '')
206
+ continue;
207
+ touchedPeriods.set(String(scope) + '|' + field, { scope: String(scope), field });
208
+ }
209
+ };
210
+ noteDay(localDate);
211
+ for (const day of removedDates)
212
+ noteDay(day);
213
+ for (const { scope, field } of touchedPeriods.values()) {
214
+ const folded = foldMaterializedDialerPeriodCounters({
215
+ periodScope: scope,
216
+ periodScopeField: field,
217
+ dayDocuments: nextDayDocs,
218
+ });
219
+ const existing = storedReportsByScope.get(scope + '|' + field);
220
+ const keys = Object.keys(folded).sort();
221
+ if (keys.length === 0) {
222
+ if (existing != null)
223
+ staleDocuments.push(existing);
224
+ continue;
225
+ }
226
+ const counters = {};
227
+ for (const key of keys)
228
+ counters[key] = folded[key];
229
+ const report = {
230
+ _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
231
+ tenant_id: tenantId,
232
+ brand_id: existing?.brand_id ?? compiledDateDoc?.brand_id ?? '',
233
+ scope_context: scope,
234
+ scope_field: field,
235
+ day_index: null,
236
+ sale_type_key_filters: [...DIALER_KEY_FILTERS],
237
+ dialer_counters: counters,
238
+ iteration: existing?.iteration,
239
+ schema_version: compiledDateDoc?.schema_version ?? MATERIALIZED_TENANT_DIALER_REPORTS_SCHEMA_VERSION,
240
+ // FROM THE DAYS THAT BELONG TO THIS PERIOD — never the stored watermark,
241
+ // and never an unrelated day from another period.
242
+ source_watermark: watermarkOfDays(nextDayDocs.filter((dayDoc) => {
243
+ const fields = getMaterializedPeriodScopeFields(String(dayDoc?.scope_field));
244
+ return fields != null && fields[scope] === field;
245
+ }), existing?.source_watermark ?? computedAt),
246
+ computed_at: computedAt,
247
+ createdAt: existing?.createdAt ?? computedAt,
248
+ updatedAt: computedAt,
249
+ };
250
+ const next = { ...report, iteration: Number(existing?.iteration ?? 0) + 1 };
251
+ if (force || needsMaterializedDialerReportWrite(existing, next))
252
+ addWrite(next);
253
+ else
254
+ skippedDocuments.push(existing);
255
+ }
256
+ // ---- entry PAGE writes (replace by page identity) ----
257
+ for (const compiled of compiledEntriesByPage.values()) {
258
+ const key = materializedDialerEntryPageKey(compiled);
259
+ const existing = storedEntriesByPage.get(key) ?? null;
260
+ const next = {
261
+ ...compiled,
262
+ _id: existing?._id ?? new mongoose.Types.ObjectId().toHexString(),
263
+ iteration: Number(existing?.iteration ?? 0) + 1,
264
+ };
265
+ if (existing == null || force || needsMaterializedDialerEntriesWrite(existing, next)) {
266
+ if (!addEntryWrite(next))
267
+ return null;
268
+ }
269
+ else {
270
+ skippedEntryDocuments.push(existing);
271
+ }
272
+ }
273
+ // Anything fetched but not recompiled is a page this day no longer owns (an
274
+ // emptied day, or a row set that disappeared): delete exactly that page.
275
+ for (const doc of storedEntriesByPage.values()) {
276
+ if (compiledEntriesByPage.has(materializedDialerEntryPageKey(doc)))
277
+ continue;
278
+ staleEntryDocuments.push(doc);
279
+ }
280
+ // BSON budgets: a counter fold or one day's page can exceed its budget even
281
+ // when the compile looked fine. Fail here, naming the collection + day + scope.
282
+ for (const write of writes) {
283
+ assertMaterializedDocumentSize(write.report, {
284
+ label: 'materialized_tenant_dialer_reports:' +
285
+ tenantId +
286
+ ':' +
287
+ localDate +
288
+ ':' +
289
+ String(write.report.scope_context) +
290
+ ':' +
291
+ write.report.scope_field,
292
+ maxBytes: MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES,
293
+ });
294
+ }
295
+ for (const write of entryWrites) {
296
+ assertMaterializedDocumentSize(write.report, {
297
+ label: 'materialized_tenant_dialer_entries:' +
298
+ tenantId +
299
+ ':' +
300
+ localDate +
301
+ ':' +
302
+ String(write.report.scope_context) +
303
+ ':' +
304
+ write.report.scope_field +
305
+ ':page=' +
306
+ write.report.page,
307
+ maxBytes: MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES,
308
+ });
309
+ }
310
+ return {
311
+ writes,
312
+ entryWrites,
313
+ staleDocuments,
314
+ staleEntryDocuments,
315
+ skippedDocuments,
316
+ skippedEntryDocuments,
317
+ };
318
+ }
319
+ /** Max watermark across the day documents that feed a fold. */
320
+ function watermarkOfDays(dayDocs, fallback) {
321
+ let latest = fallback.getTime();
322
+ for (const doc of dayDocs) {
323
+ const time = new Date(doc?.source_watermark ?? 0).getTime();
324
+ if (!Number.isNaN(time) && time > latest)
325
+ latest = time;
326
+ }
327
+ return new Date(latest);
328
+ }