@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
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const DIALER_ENUMS_1 = require("../../constants/DIALER_ENUMS");
4
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
5
+ const materialized_dialer_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-compile-helpers");
6
+ const materialized_dialer_key_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-key-helpers");
7
+ const materialized_dialer_masking_1 = require("../../helpers/materialized-reports/materialized-dialer-masking");
8
+ const materialized_dialer_entry_pages_1 = require("../../helpers/materialized-reports/materialized-dialer-entry-pages");
9
+ const materialized_dialer_accumulator_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-accumulator-helpers");
10
+ /**
11
+ * Dialer day compile.
12
+ *
13
+ * The defining property of this report: the source is an APPEND-ONLY EVENT
14
+ * stream. A day is exactly the events whose own tenant-local `localDate` is the
15
+ * day, an event without local fields is never attributed to a guessed day, and
16
+ * the counters are plain event counts (no duration, no order attribution).
17
+ */
18
+ const TENANT = 'tenant-dialer';
19
+ const BRAND = 'brand-dialer';
20
+ const DAY = '2026-09-14';
21
+ const COMPUTED_AT = new Date('2026-09-15T06:00:00.000Z');
22
+ let sequence = 0;
23
+ const event = (over = {}) => {
24
+ sequence += 1;
25
+ return {
26
+ _id: `event-${String(sequence).padStart(4, '0')}`,
27
+ tenant_id: TENANT,
28
+ request_id: `call-${sequence}:${over.action ?? DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL}`,
29
+ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL,
30
+ phone_number: '+923001234567',
31
+ pos_id: 'POS-01',
32
+ staff_id: 'staff-1',
33
+ staff_phone: '+923009999999',
34
+ localDate: DAY,
35
+ localHour: 10,
36
+ localMinute: 5,
37
+ localSecond: 0,
38
+ createdAt: new Date(`${DAY}T05:05:00.000Z`),
39
+ updatedAt: new Date(`${DAY}T05:05:00.000Z`),
40
+ ...over,
41
+ };
42
+ };
43
+ const compile = (events, over = {}) => (0, materialized_dialer_compile_helpers_1.compileTenantDialerReports)({
44
+ tenantId: TENANT,
45
+ brandId: BRAND,
46
+ localDate: DAY,
47
+ events,
48
+ computedAt: COMPUTED_AT,
49
+ ...over,
50
+ });
51
+ const dayEntry = (compiled) => compiled.entries.find((entry) => String(entry.scope_context) === 'localDate');
52
+ const allRows = (compiled) => Object.values(dayEntry(compiled).dialer_entries ?? {}).flatMap((section) => section.rows);
53
+ describe('dialer day compile', () => {
54
+ it('counts every action into its counter and into `events`', () => {
55
+ const compiled = compile(Object.values(DIALER_ENUMS_1.DIALER_TYPES_ENUM).map((action) => event({ action, localHour: 9, request_id: `call:${action}` })));
56
+ const counters = (0, materialized_dialer_accumulator_helpers_1.sumDialerCounterMap)(compiled.reports[0].dialer_counters);
57
+ expect(Object.keys(compiled.reports[0].dialer_counters)).toHaveLength(7);
58
+ // The raw counter shape is fixed: counts + `by_hour`, no duration/rates.
59
+ expect(Object.keys(counters).sort()).toEqual([
60
+ 'answered',
61
+ 'by_hour',
62
+ 'declined',
63
+ 'ended',
64
+ 'events',
65
+ 'incoming_calls',
66
+ 'missed',
67
+ 'outgoing_calls',
68
+ 'pos_pings',
69
+ ]);
70
+ expect(counters.events).toBe(7);
71
+ expect(counters.incoming_calls).toBe(1);
72
+ expect(counters.outgoing_calls).toBe(1);
73
+ expect(counters.answered).toBe(1);
74
+ expect(counters.missed).toBe(1);
75
+ expect(counters.declined).toBe(1);
76
+ expect(counters.ended).toBe(1);
77
+ expect(counters.pos_pings).toBe(1);
78
+ expect(counters.by_hour['9']).toBe(7);
79
+ expect(compiled.attributed_events).toBe(7);
80
+ });
81
+ it('builds the key grammar and encodes a missing component as UNKNOWN', () => {
82
+ const compiled = compile([
83
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL, pos_id: 'POS-01', staff_id: 'staff-1' }),
84
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL, pos_id: 'POS-02', staff_id: null }),
85
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.POS_PING, pos_id: 'POS-01', staff_id: '' }),
86
+ ]);
87
+ expect(Object.keys(compiled.reports[0].dialer_counters).sort()).toEqual([
88
+ 'INCOMING_CALL:POS-01:staff-1',
89
+ 'INCOMING_CALL:POS-02:UNKNOWN',
90
+ 'POS_PING:POS-01:UNKNOWN',
91
+ ]);
92
+ expect(compiled.reports[0].sale_type_key_filters).toEqual(['ACTION', 'POS_ID', 'STAFF_ID']);
93
+ });
94
+ it('initializes all 24 by_hour keys and never invents an hour', () => {
95
+ const compiled = compile([event({ localHour: 0 }), event({ localHour: 23 })]);
96
+ const counters = Object.values(compiled.reports[0].dialer_counters)[0];
97
+ expect(Object.keys(counters.by_hour).sort()).toEqual([...MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_HOUR_KEYS].sort());
98
+ expect(counters.by_hour['0']).toBe(1);
99
+ expect(counters.by_hour['23']).toBe(1);
100
+ expect(counters.by_hour['12']).toBe(0);
101
+ expect(counters.events).toBe(2);
102
+ });
103
+ it('ignores events without a local date/hour and events of another day', () => {
104
+ const compiled = compile([
105
+ event({ localDate: DAY, localHour: 10 }),
106
+ event({ localDate: undefined, localHour: undefined }),
107
+ event({ localDate: DAY, localHour: undefined }),
108
+ event({ localDate: '2026-09-13', localHour: 23 }),
109
+ ]);
110
+ expect(compiled.attributed_events).toBe(1);
111
+ expect(compiled.unattributed_events).toBe(2);
112
+ expect(compiled.out_of_day_events).toBe(1);
113
+ expect(Object.values(compiled.reports[0].dialer_counters)[0].events).toBe(1);
114
+ expect(allRows(compiled)).toHaveLength(1);
115
+ });
116
+ it('returns null for an empty (or fully unattributed) day', () => {
117
+ expect(compile([])).toBeNull();
118
+ expect(compile([event({ localDate: undefined, localHour: undefined })])).toBeNull();
119
+ });
120
+ it('masks caller and staff phones in every materialized row', () => {
121
+ const compiled = compile([event({ phone_number: '+923001234567', staff_phone: '0300-7654321' })]);
122
+ const [row] = allRows(compiled);
123
+ expect(row.phone_number_masked).toBe('+********4567');
124
+ expect(row.staff_phone_masked).toBe('*******4321');
125
+ const serialized = JSON.stringify(compiled);
126
+ expect(serialized).not.toContain('+923001234567');
127
+ expect(serialized).not.toContain('0300-7654321');
128
+ expect(serialized).not.toContain('923001234567');
129
+ expect(serialized).not.toContain('7654321');
130
+ });
131
+ it('creates one page per source day for every entry scope', () => {
132
+ const compiled = compile([event()]);
133
+ const pages = compiled.entries.map((entry) => `${entry.scope_context}:${entry.scope_field}:${entry.page}`);
134
+ expect(pages.sort()).toEqual([
135
+ `localDate:${DAY}:all`,
136
+ 'localMonth:2026-09:2026-09-14',
137
+ 'localWeek:2026-09-13:2026-09-14',
138
+ 'localWeekOfYear:2026-W38:2026-09-14',
139
+ ].sort());
140
+ const day = dayEntry(compiled);
141
+ expect(day.day_index).not.toBeNull();
142
+ for (const target of compiled.entries.filter((entry) => entry !== day)) {
143
+ expect(target.day_index).toBeNull();
144
+ }
145
+ });
146
+ it('orders rows newest-first with a total event-id tie-break', () => {
147
+ const compiled = compile([
148
+ event({ _id: 'e-a', createdAt: new Date(`${DAY}T01:00:00.000Z`) }),
149
+ event({ _id: 'e-c', createdAt: new Date(`${DAY}T03:00:00.000Z`) }),
150
+ event({ _id: 'e-b', createdAt: new Date(`${DAY}T02:00:00.000Z`) }),
151
+ ]);
152
+ expect(allRows(compiled).map((row) => row.event_id)).toEqual(['e-c', 'e-b', 'e-a']);
153
+ expect(allRows(compiled)[0].created_at).toBe('2026-09-14T03:00:00.000Z');
154
+ });
155
+ it('uses the source watermark (max updatedAt) and the source day', () => {
156
+ const compiled = compile([
157
+ event({ updatedAt: new Date('2026-09-14T10:00:00.000Z') }),
158
+ event({ updatedAt: new Date('2026-09-14T11:00:00.000Z') }),
159
+ ]);
160
+ expect(compiled.reports[0].source_watermark.toISOString()).toBe('2026-09-14T11:00:00.000Z');
161
+ expect(compiled.reports[0].scope_context).toBe('localDate');
162
+ expect(compiled.reports[0].scope_field).toBe(DAY);
163
+ });
164
+ it('declares 15 MiB report/page budgets', () => {
165
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES).toBe(15 * 1024 * 1024);
166
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_ENTRY_MAX_BSON_BYTES).toBe(15 * 1024 * 1024);
167
+ expect(MATERIALIZED_REPORTS_1.MATERIALIZED_DIALER_REPORT_MAX_BSON_BYTES).toBeLessThan(16 * 1024 * 1024);
168
+ });
169
+ it('splits an oversized page into deterministic #N sub-pages and keeps a fitting page unsuffixed', () => {
170
+ const compiled = compile(Array.from({ length: 40 }, (_, index) => event({ _id: `split-${index}`, phone_number: `+9230000${String(index).padStart(5, '0')}` })));
171
+ const day = dayEntry(compiled);
172
+ const pages = (0, materialized_dialer_entry_pages_1.splitMaterializedDialerEntryPage)(day, 2600);
173
+ expect(pages.length).toBeGreaterThan(1);
174
+ expect(pages.map((page) => page.page)).toEqual(pages.map((_, index) => `all#${index}`));
175
+ const ids = pages.flatMap((page) => Object.values(page.dialer_entries ?? {}).flatMap((section) => section.rows.map((row) => row.event_id)));
176
+ expect(new Set(ids).size).toBe(40);
177
+ // A page that fits keeps its original identity.
178
+ expect((0, materialized_dialer_entry_pages_1.splitMaterializedDialerEntryPage)(day, 15 * 1024 * 1024)).toHaveLength(1);
179
+ expect((0, materialized_dialer_entry_pages_1.splitMaterializedDialerEntryPage)(day, 15 * 1024 * 1024)[0].page).toBe('all');
180
+ });
181
+ });
182
+ describe('dialer key grammar', () => {
183
+ it('builds, parses and sanitizes the separator', () => {
184
+ expect((0, materialized_dialer_key_helpers_1.buildMaterializedDialerKey)('INCOMING_CALL', 'POS:1', null)).toBe('INCOMING_CALL:POS-1:UNKNOWN');
185
+ expect((0, materialized_dialer_key_helpers_1.parseMaterializedDialerKey)('INCOMING_CALL:POS-01:staff-1')).toEqual({
186
+ action: 'INCOMING_CALL',
187
+ pos_id: 'POS-01',
188
+ staff_id: 'staff-1',
189
+ });
190
+ expect((0, materialized_dialer_key_helpers_1.parseMaterializedDialerKey)('broken')).toBeNull();
191
+ expect((0, materialized_dialer_key_helpers_1.parseMaterializedDialerKey)('A::B')).toBeNull();
192
+ });
193
+ it('filters whole components only and never matches a prefix', () => {
194
+ const key = 'CALL_ANSWERED:POS-01:staff-1';
195
+ expect((0, materialized_dialer_key_helpers_1.dialerKeyPassesFilters)(key, null)).toBe(true);
196
+ expect((0, materialized_dialer_key_helpers_1.dialerKeyPassesFilters)(key, { actions: ['CALL_ANSWERED'] })).toBe(true);
197
+ expect((0, materialized_dialer_key_helpers_1.dialerKeyPassesFilters)(key, { actions: ['CALL'] })).toBe(false);
198
+ expect((0, materialized_dialer_key_helpers_1.dialerKeyPassesFilters)(key, { pos_ids: ['POS-01'], staff_ids: ['staff-1'] })).toBe(true);
199
+ expect((0, materialized_dialer_key_helpers_1.dialerKeyPassesFilters)(key, { staff_ids: ['UNKNOWN'] })).toBe(false);
200
+ const regex = (0, materialized_dialer_key_helpers_1.buildDialerKeyFilterRegex)({ actions: ['INCOMING_CALL'], staff_ids: ['staff-1'] });
201
+ expect(regex.test('INCOMING_CALL:POS-01:staff-1')).toBe(true);
202
+ expect(regex.test('INCOMING_CALL:POS-01:staff-10')).toBe(false);
203
+ expect((0, materialized_dialer_key_helpers_1.buildDialerKeyFilterRegex)(null)).toBeNull();
204
+ });
205
+ it('masks with the documented rule', () => {
206
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)('+923001234567')).toBe('+********4567');
207
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)('0300-1234567')).toBe('*******4567');
208
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)('12345')).toBe('*2345');
209
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)('1234')).toBe('****');
210
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)('')).toBeNull();
211
+ expect((0, materialized_dialer_masking_1.maskDialerPhoneNumber)(null)).toBeNull();
212
+ });
213
+ });
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const materialized_dialer_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-compile-helpers");
4
+ const tenant_dialer_formatter_1 = require("../../helpers/materialized-reports/tenant-dialer-formatter");
5
+ const DIALER_ENUMS_1 = require("../../constants/DIALER_ENUMS");
6
+ /**
7
+ * Dialer formatter.
8
+ *
9
+ * The stored documents are counts only: the answer/missed rates and every
10
+ * breakdown are derived HERE, so the page never sees a stored average and the
11
+ * formatter cannot drift from the counters.
12
+ *
13
+ * APPROVED RATE CONTRACT (load-bearing):
14
+ * `outcome_denominator = answered + missed + declined`;
15
+ * `answer_rate = answered / outcome_denominator`;
16
+ * `missed_rate = missed / outcome_denominator`.
17
+ * Percentage, 2 decimals, null when the denominator is 0. `events` is NOT the
18
+ * denominator — incoming/outgoing/ended/ping events are activity, not outcomes.
19
+ */
20
+ const TENANT = 'tenant-format';
21
+ const BRAND = 'brand-format';
22
+ const DAY = '2026-09-14';
23
+ const event = (over = {}) => ({
24
+ _id: `f-${Math.random().toString(36).slice(2)}`,
25
+ tenant_id: TENANT,
26
+ request_id: `r-${Math.random().toString(36).slice(2)}`,
27
+ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL,
28
+ phone_number: '+923001234567',
29
+ pos_id: 'POS-01',
30
+ staff_id: 'staff-1',
31
+ localDate: DAY,
32
+ localHour: 10,
33
+ createdAt: new Date(`${DAY}T05:00:00.000Z`),
34
+ updatedAt: new Date(`${DAY}T05:00:00.000Z`),
35
+ ...over,
36
+ });
37
+ const compiled = (events) => (0, materialized_dialer_compile_helpers_1.compileTenantDialerReports)({
38
+ tenantId: TENANT,
39
+ brandId: BRAND,
40
+ localDate: DAY,
41
+ events,
42
+ computedAt: new Date(`${DAY}T23:00:00.000Z`),
43
+ });
44
+ const pageOf = (events, options = {}) => (0, tenant_dialer_formatter_1.formatMaterializedDialerReport)(compiled(events).reports, options);
45
+ describe('dialer formatter', () => {
46
+ it('sums counters, derives rates from the outcome denominator and exposes all 24 hours', () => {
47
+ const page = pageOf([
48
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL }),
49
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED }),
50
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.MISSED_CALL, localHour: 11 }),
51
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED, localHour: 11 }),
52
+ ]);
53
+ expect(page.summary.events).toBe(4);
54
+ expect(page.summary.answered).toBe(2);
55
+ expect(page.summary.missed).toBe(1);
56
+ expect(page.summary.declined).toBe(0);
57
+ expect(page.summary.incoming_calls).toBe(1);
58
+ // denominator = 2 answered + 1 missed + 0 declined = 3 (NOT 4 events).
59
+ expect(page.summary.answer_rate).toBe(66.67);
60
+ expect(page.summary.missed_rate).toBe(33.33);
61
+ expect(page.by_hour).toHaveLength(24);
62
+ expect(page.by_hour[10].events).toBe(2);
63
+ expect(page.by_hour[11].events).toBe(2);
64
+ expect(page.by_hour[0].events).toBe(0);
65
+ expect(page.by_hour.map((row) => row.label)).toEqual(Array.from({ length: 24 }, (_, hour) => String(hour)));
66
+ expect(page.tenant_ids).toEqual([TENANT]);
67
+ expect(page.scopes).toEqual([{ scope_context: 'localDate', scope_field: DAY }]);
68
+ });
69
+ it('ignores non-outcome events in the denominator and includes declined', () => {
70
+ const page = pageOf([
71
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL }),
72
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.OUTGOING_CALL }),
73
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ENDED }),
74
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.POS_PING }),
75
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED }),
76
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED }),
77
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.MISSED_CALL }),
78
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_DECLINED }),
79
+ ]);
80
+ expect(page.summary.events).toBe(8);
81
+ // denominator = 2 answered + 1 missed + 1 declined = 4 (not 8 events).
82
+ expect(page.summary.answer_rate).toBe(50);
83
+ expect(page.summary.missed_rate).toBe(25);
84
+ });
85
+ it('returns null rates when there is no outcome, and 0 is a real rate', () => {
86
+ const activityOnly = pageOf([
87
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL }),
88
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.POS_PING }),
89
+ ]);
90
+ expect(activityOnly.summary.events).toBe(2);
91
+ expect(activityOnly.summary.answer_rate).toBeNull();
92
+ expect(activityOnly.summary.missed_rate).toBeNull();
93
+ const declinedOnly = pageOf([event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_DECLINED })]);
94
+ expect(declinedOnly.summary.answer_rate).toBe(0);
95
+ expect(declinedOnly.summary.missed_rate).toBe(0);
96
+ });
97
+ it('rounds every rate to 2 decimals', () => {
98
+ const page = pageOf([
99
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED }),
100
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_DECLINED }),
101
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_DECLINED }),
102
+ ]);
103
+ // 1 / 3 = 33.333… %, 2 / 3 = 66.666… % (missed is 0 / 3).
104
+ expect(page.summary.answer_rate).toBe(33.33);
105
+ expect(page.summary.missed_rate).toBe(0);
106
+ });
107
+ it('groups by action, terminal and staff deterministically with the same denominator', () => {
108
+ const page = pageOf([
109
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL, pos_id: 'POS-01', staff_id: 'staff-1' }),
110
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED, pos_id: 'POS-01', staff_id: 'staff-1' }),
111
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_ANSWERED, pos_id: 'POS-01', staff_id: 'staff-1' }),
112
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.MISSED_CALL, pos_id: 'POS-01', staff_id: 'staff-1' }),
113
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.MISSED_CALL, pos_id: 'POS-02', staff_id: 'staff-2' }),
114
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.CALL_DECLINED, pos_id: 'POS-02', staff_id: 'staff-2' }),
115
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL, pos_id: 'POS-03', staff_id: null }),
116
+ ]);
117
+ expect(page.by_pos.map((row) => [row.key, row.events])).toEqual([
118
+ ['POS-01', 4],
119
+ ['POS-02', 2],
120
+ ['POS-03', 1],
121
+ ]);
122
+ expect(page.by_staff.map((row) => row.key).sort()).toEqual(['UNKNOWN', 'staff-1', 'staff-2']);
123
+ expect(page.by_action.find((row) => row.key === 'MISSED_CALL').events).toBe(2);
124
+ const pos01 = page.by_pos.find((row) => row.key === 'POS-01');
125
+ // 2 answered / (2 answered + 1 missed + 0 declined) = 66.67 %.
126
+ expect(pos01.answer_rate).toBe(66.67);
127
+ const pos02 = page.by_pos.find((row) => row.key === 'POS-02');
128
+ // 0 answered / (0 + 1 missed + 1 declined) = 0 % — a real rate, not null.
129
+ expect(pos02.answer_rate).toBe(0);
130
+ const pos03 = page.by_pos.find((row) => row.key === 'POS-03');
131
+ // No outcome at all -> null, even though the row has an event.
132
+ expect(pos03.answer_rate).toBeNull();
133
+ expect(page.by_staff.find((row) => row.key === 'staff-2').answer_rate).toBe(0);
134
+ expect(page.by_action.find((row) => row.key === 'CALL_ANSWERED').answer_rate).toBe(100);
135
+ expect(page.by_action.find((row) => row.key === 'INCOMING_CALL').answer_rate).toBeNull();
136
+ // A filter narrows the breakdown AND the totals with the same semantics.
137
+ const filtered = (0, tenant_dialer_formatter_1.formatMaterializedDialerReport)(compiled([
138
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL, pos_id: 'POS-02' }),
139
+ event({ action: DIALER_ENUMS_1.DIALER_TYPES_ENUM.MISSED_CALL, pos_id: 'POS-02' }),
140
+ ]).reports, { filters: { pos_ids: ['POS-02'] } });
141
+ expect(filtered.summary.events).toBe(2);
142
+ expect(filtered.summary.answer_rate).toBe(0);
143
+ expect(filtered.by_pos).toHaveLength(1);
144
+ });
145
+ it('returns a zeroed page for no documents (absence means zero)', () => {
146
+ const page = (0, tenant_dialer_formatter_1.formatMaterializedDialerReport)([]);
147
+ expect(page.summary.events).toBe(0);
148
+ expect(page.summary.answer_rate).toBeNull();
149
+ expect(page.summary.missed_rate).toBeNull();
150
+ expect(page.by_hour.every((row) => row.events === 0)).toBe(true);
151
+ expect(page.by_action).toEqual([]);
152
+ expect(page.by_pos).toEqual([]);
153
+ expect(page.by_staff).toEqual([]);
154
+ });
155
+ it('never exposes a phone number', () => {
156
+ const docs = compiled([event()]).reports;
157
+ expect(JSON.stringify((0, tenant_dialer_formatter_1.formatMaterializedDialerReport)(docs))).not.toContain('923001234567');
158
+ });
159
+ });
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const MATERIALIZED_REPORTS_1 = require("../../constants/MATERIALIZED_REPORTS");
4
+ const materialized_dialer_compile_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-compile-helpers");
5
+ const materialized_dialer_close_day_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-close-day-helpers");
6
+ const materialized_dialer_accumulator_helpers_1 = require("../../helpers/materialized-reports/materialized-dialer-accumulator-helpers");
7
+ const DIALER_ENUMS_1 = require("../../constants/DIALER_ENUMS");
8
+ /**
9
+ * Dialer close-day plan.
10
+ *
11
+ * The properties that make a re-close safe:
12
+ * - the DAY document is replaced from the fresh compile;
13
+ * - every touched PERIOD is re-folded from the whole day set (never incremented);
14
+ * - entry pages are replaced by page identity, and a page the day no longer owns
15
+ * is deleted;
16
+ * - a re-close with an unchanged watermark writes nothing;
17
+ * - an emptied day deletes its day document and its pages.
18
+ */
19
+ const TENANT = 'tenant-plan';
20
+ const BRAND = 'brand-plan';
21
+ const DAY = '2026-09-14';
22
+ const COMPUTED_AT = new Date('2026-09-15T06:00:00.000Z');
23
+ const event = (id, action = DIALER_ENUMS_1.DIALER_TYPES_ENUM.INCOMING_CALL) => ({
24
+ _id: id,
25
+ tenant_id: TENANT,
26
+ request_id: id,
27
+ action,
28
+ phone_number: '+923001234567',
29
+ pos_id: 'POS-01',
30
+ staff_id: 'staff-1',
31
+ localDate: DAY,
32
+ localHour: 10,
33
+ createdAt: new Date(`${DAY}T05:00:00.000Z`),
34
+ updatedAt: new Date(`${DAY}T05:00:00.000Z`),
35
+ });
36
+ const compile = (ids = ['e1', 'e2']) => (0, materialized_dialer_compile_helpers_1.compileTenantDialerReports)({
37
+ tenantId: TENANT,
38
+ brandId: BRAND,
39
+ localDate: DAY,
40
+ events: ids.map((id) => event(id)),
41
+ computedAt: COMPUTED_AT,
42
+ });
43
+ const scope = (doc) => `${doc.scope_context}|${doc.scope_field}`;
44
+ describe('dialer close-day plan', () => {
45
+ it('writes the day document, re-folded periods and one page per entry scope', () => {
46
+ const compiled = compile();
47
+ const plan = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
48
+ tenantId: TENANT,
49
+ reports: compiled.reports,
50
+ entries: compiled.entries,
51
+ localDate: DAY,
52
+ reason: 'NEW_DAY',
53
+ computedAt: COMPUTED_AT,
54
+ });
55
+ expect(plan.writes.map((write) => scope(write.report)).sort()).toEqual([
56
+ `localDate|${DAY}`,
57
+ 'localMonth|2026-09',
58
+ 'localQuarter|2026-Q3',
59
+ 'localSemester|2026-S2',
60
+ 'localWeek|2026-09-13',
61
+ 'localWeekOfYear|2026-W38',
62
+ 'localYear|2026',
63
+ ].sort());
64
+ expect(plan.entryWrites).toHaveLength(4);
65
+ expect(plan.staleDocuments).toHaveLength(0);
66
+ // Every write carries an iteration row of the right report type.
67
+ expect(plan.writes.every((write) => write.iteration.report_type === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_REPORTS)).toBe(true);
68
+ expect(plan.entryWrites.every((write) => write.iteration.report_type === MATERIALIZED_REPORTS_1.MATERIALIZED_REPORT_TYPE_ENUM.TENANT_DIALER_ENTRIES)).toBe(true);
69
+ const month = plan.writes.find((write) => write.report.scope_context === 'localMonth');
70
+ expect(Object.values(month.report.dialer_counters)[0].events).toBe(2);
71
+ expect(month.report.day_index).toBeNull();
72
+ });
73
+ it('folds sibling DAY documents into the period counters', () => {
74
+ const compiled = compile(['e1']);
75
+ const sibling = compile(['e2']);
76
+ const siblingDay = {
77
+ ...sibling.reports[0],
78
+ _id: 'sibling-id',
79
+ scope_field: '2026-09-13',
80
+ dialer_counters: {
81
+ 'INCOMING_CALL:POS-01:staff-1': {
82
+ ...(0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)(),
83
+ events: 5,
84
+ incoming_calls: 5,
85
+ by_hour: { ...(0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)().by_hour, '9': 5 },
86
+ },
87
+ },
88
+ };
89
+ const plan = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
90
+ tenantId: TENANT,
91
+ reports: compiled.reports,
92
+ entries: compiled.entries,
93
+ existing: [siblingDay],
94
+ localDate: DAY,
95
+ reason: 'RECLOSE',
96
+ computedAt: COMPUTED_AT,
97
+ });
98
+ const month = plan.writes.find((write) => write.report.scope_context === 'localMonth');
99
+ const counters = month.report.dialer_counters['INCOMING_CALL:POS-01:staff-1'];
100
+ expect(counters.events).toBe(1 + 5);
101
+ expect(counters.by_hour['9']).toBe(5);
102
+ expect(counters.by_hour['10']).toBe(1);
103
+ });
104
+ it('is idempotent on an unchanged re-close (watermark unchanged)', () => {
105
+ const compiled = compile();
106
+ const first = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
107
+ tenantId: TENANT,
108
+ reports: compiled.reports,
109
+ entries: compiled.entries,
110
+ localDate: DAY,
111
+ reason: 'NEW_DAY',
112
+ computedAt: COMPUTED_AT,
113
+ });
114
+ const existingReports = first.writes.map((write) => ({ ...write.report, _id: `id-${write.report.scope_context}` }));
115
+ const existingEntries = first.entryWrites.map((write) => ({
116
+ ...write.report,
117
+ _id: `entry-${write.report.scope_context}`,
118
+ iteration: 1,
119
+ }));
120
+ const second = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
121
+ tenantId: TENANT,
122
+ reports: compiled.reports.map((report) => ({
123
+ ...report,
124
+ source_watermark: new Date(existingReports[0].source_watermark),
125
+ })),
126
+ entries: compiled.entries.map((entry) => ({
127
+ ...entry,
128
+ source_watermark: new Date(existingReports[0].source_watermark),
129
+ })),
130
+ existing: existingReports,
131
+ existingEntries,
132
+ localDate: DAY,
133
+ reason: 'RECLOSE',
134
+ computedAt: COMPUTED_AT,
135
+ });
136
+ expect(second.writes).toHaveLength(0);
137
+ expect(second.entryWrites).toHaveLength(0);
138
+ expect(second.skippedDocuments.length).toBeGreaterThan(0);
139
+ expect(second.skippedEntryDocuments).toHaveLength(4);
140
+ });
141
+ it('deletes the day document and its pages when the day no longer has events', () => {
142
+ const compiled = compile();
143
+ const first = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
144
+ tenantId: TENANT,
145
+ reports: compiled.reports,
146
+ entries: compiled.entries,
147
+ localDate: DAY,
148
+ reason: 'NEW_DAY',
149
+ computedAt: COMPUTED_AT,
150
+ });
151
+ const existingReports = first.writes.map((write) => ({ ...write.report, _id: `id-${write.report.scope_context}` }));
152
+ const existingEntries = first.entryWrites.map((write) => ({
153
+ ...write.report,
154
+ _id: `entry-${write.report.scope_context}`,
155
+ }));
156
+ const emptied = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
157
+ tenantId: TENANT,
158
+ reports: [],
159
+ entries: [],
160
+ existing: existingReports,
161
+ existingEntries,
162
+ localDate: DAY,
163
+ reason: 'RECLOSE',
164
+ computedAt: COMPUTED_AT,
165
+ });
166
+ expect(emptied.writes).toHaveLength(0);
167
+ expect(emptied.entryWrites).toHaveLength(0);
168
+ expect(emptied.staleDocuments.map((doc) => scope(doc)).sort()).toEqual(existingReports
169
+ .filter((doc) => doc.scope_context !== 'localDate')
170
+ .map(scope)
171
+ .sort()
172
+ .concat([`localDate|${DAY}`])
173
+ .sort());
174
+ expect(emptied.staleEntryDocuments).toHaveLength(4);
175
+ });
176
+ it('does not use `_id` from the compile as a stored identity', () => {
177
+ const compiled = compile();
178
+ const plan = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
179
+ tenantId: TENANT,
180
+ reports: compiled.reports,
181
+ entries: compiled.entries,
182
+ localDate: DAY,
183
+ reason: 'NEW_DAY',
184
+ computedAt: COMPUTED_AT,
185
+ });
186
+ for (const write of [...plan.writes, ...plan.entryWrites]) {
187
+ expect(typeof write.report._id).toBe('string');
188
+ expect(String(write.report._id)).not.toBe('undefined');
189
+ expect(write.iteration.report_id).toBe(String(write.report._id));
190
+ }
191
+ });
192
+ it('folds counters with the shared merge (sums every hour)', () => {
193
+ const left = (0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)();
194
+ const right = (0, materialized_dialer_accumulator_helpers_1.freshDialerCounters)();
195
+ left.events = 1;
196
+ left.by_hour['0'] = 1;
197
+ right.events = 2;
198
+ right.by_hour['23'] = 2;
199
+ (0, materialized_dialer_accumulator_helpers_1.mergeDialerCounters)(left, right);
200
+ expect(left.events).toBe(3);
201
+ expect(left.by_hour['0']).toBe(1);
202
+ expect(left.by_hour['23']).toBe(2);
203
+ // Merge returns the same key set (24 hours) and never a partial map.
204
+ expect(Object.keys(left.by_hour)).toHaveLength(24);
205
+ });
206
+ it('produces documents whose day scope is the only one carrying day_index', () => {
207
+ const compiled = compile();
208
+ const plan = (0, materialized_dialer_close_day_helpers_1.buildTenantDialerCloseDayPlan)({
209
+ tenantId: TENANT,
210
+ reports: compiled.reports,
211
+ entries: compiled.entries,
212
+ localDate: DAY,
213
+ reason: 'NEW_DAY',
214
+ computedAt: COMPUTED_AT,
215
+ });
216
+ for (const write of plan.writes) {
217
+ if (write.report.scope_context === 'localDate')
218
+ expect(write.report.day_index).not.toBeNull();
219
+ else
220
+ expect(write.report.day_index).toBeNull();
221
+ }
222
+ });
223
+ });