@wirecat/cli-core 0.662.0 → 0.663.0

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 (173) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/cli/bodies.js +2 -1
  4. package/dist/calendar/cli/index.js +13 -10
  5. package/dist/calendar/mcp/index.d.ts +3 -1
  6. package/dist/calendar/mcp/index.js +4 -4
  7. package/dist/cli/call-stats-command.d.ts +18 -0
  8. package/dist/cli/call-stats-command.js +52 -0
  9. package/dist/cli/contract-templates.js +2 -0
  10. package/dist/cli/envelope.d.ts +0 -5
  11. package/dist/cli/envelope.js +25 -0
  12. package/dist/cli/index.d.ts +2 -1
  13. package/dist/cli/index.js +2 -1
  14. package/dist/cli/meeting-batch.d.ts +2 -1
  15. package/dist/cli/meeting-batch.js +7 -5
  16. package/dist/cli/meeting-preparation-command.js +5 -5
  17. package/dist/cli/meeting-preparation-read.d.ts +5 -5
  18. package/dist/cli/meeting-preparation-read.js +13 -21
  19. package/dist/cli/meeting-series-inventory-command.js +2 -2
  20. package/dist/cli/meeting-series-inventory-read.d.ts +2 -2
  21. package/dist/cli/meeting-series-inventory-read.js +7 -15
  22. package/dist/cli/messenger/admin-statistics-command.js +2 -2
  23. package/dist/cli/messenger/counters-command.js +2 -2
  24. package/dist/cli/messenger/media-archive-command.js +5 -4
  25. package/dist/cli/messenger/media-archive-move-command.js +1 -1
  26. package/dist/cli/messenger/media-archive-timer-command.js +5 -4
  27. package/dist/cli/messenger/metadata-command.js +3 -3
  28. package/dist/cli/messenger/rankings-command.js +3 -3
  29. package/dist/cli/messenger/tags-command.js +7 -2
  30. package/dist/cli/messenger/tasks-command.js +2 -2
  31. package/dist/cli/paging.d.ts +10 -0
  32. package/dist/cli/paging.js +29 -0
  33. package/dist/cli/runs/command.js +6 -4
  34. package/dist/cli/runs/search-command.js +9 -5
  35. package/dist/cli/schedule/schedule-command.js +1 -5
  36. package/dist/domain/moment.d.ts +29 -0
  37. package/dist/domain/moment.js +58 -0
  38. package/dist/domain/providers.d.ts +6 -4
  39. package/dist/domain/providers.js +10 -5
  40. package/dist/domain/send-time.d.ts +3 -4
  41. package/dist/domain/send-time.js +10 -24
  42. package/dist/entities/fields.d.ts +2 -2
  43. package/dist/entities/fields.js +2 -2
  44. package/dist/entities/index.d.ts +92 -1
  45. package/dist/entities/index.js +3 -2
  46. package/dist/entities/meeting.d.ts +1 -1
  47. package/dist/entities/meeting.js +1 -1
  48. package/dist/errors/reasons.js +0 -1
  49. package/dist/mail/cli/index.js +4 -2
  50. package/dist/mail/facts.d.ts +5 -2
  51. package/dist/mail/facts.js +6 -3
  52. package/dist/mail/index.d.ts +1 -1
  53. package/dist/mail/meeting-notes.js +1 -1
  54. package/dist/mail/probe.d.ts +5 -2
  55. package/dist/mail/probe.js +9 -5
  56. package/dist/mail/server-search.js +1 -1
  57. package/dist/mail/sync.js +1 -1
  58. package/dist/mcp/meeting-preparation.js +1 -1
  59. package/dist/mcp/meeting-series-inventory.js +1 -1
  60. package/dist/mcp/prompts.js +6 -9
  61. package/dist/meetings/call-answers.d.ts +106 -0
  62. package/dist/meetings/call-answers.js +171 -0
  63. package/dist/meetings/call-stats.d.ts +121 -0
  64. package/dist/meetings/call-stats.js +211 -0
  65. package/dist/meetings/calls.d.ts +76 -0
  66. package/dist/meetings/calls.js +78 -0
  67. package/dist/meetings/cli/index.d.ts +8 -0
  68. package/dist/meetings/cli/index.js +10 -22
  69. package/dist/meetings/cli/search.d.ts +9 -2
  70. package/dist/meetings/cli/search.js +16 -26
  71. package/dist/meetings/index.d.ts +3 -0
  72. package/dist/meetings/index.js +3 -0
  73. package/dist/meetings/mcp/index.d.ts +6 -3
  74. package/dist/meetings/mcp/index.js +2 -4
  75. package/dist/meetings/mcp/search.d.ts +6 -1
  76. package/dist/meetings/mcp/search.js +3 -3
  77. package/dist/meetings/read-through.d.ts +2 -1
  78. package/dist/meetings/read-through.js +10 -1
  79. package/dist/meetings/stats.d.ts +3 -0
  80. package/dist/meetings/stats.js +3 -3
  81. package/dist/meetings/testing/index.d.ts +1 -0
  82. package/dist/meetings/testing/index.js +1 -0
  83. package/dist/meetings/testing/paging.d.ts +6 -0
  84. package/dist/meetings/testing/paging.js +5 -0
  85. package/dist/moderation/rules.d.ts +2 -0
  86. package/dist/moderation/rules.js +16 -2
  87. package/dist/search/fusion.d.ts +17 -0
  88. package/dist/search/fusion.js +17 -0
  89. package/dist/search/lucene/resolved.d.ts +2 -0
  90. package/dist/search/question-plan.d.ts +2 -0
  91. package/dist/search/question-plan.js +5 -0
  92. package/dist/search/service-query.d.ts +6 -1
  93. package/dist/search/service-query.js +9 -1
  94. package/dist/services/agenda-mail.js +2 -1
  95. package/dist/services/agenda.js +5 -3
  96. package/dist/services/attachments.js +4 -2
  97. package/dist/services/call-stats.d.ts +17 -0
  98. package/dist/services/call-stats.js +41 -0
  99. package/dist/services/chats.js +4 -2
  100. package/dist/services/conversations.js +4 -2
  101. package/dist/services/deps.d.ts +1 -1
  102. package/dist/services/document-source.d.ts +1 -1
  103. package/dist/services/document-source.js +4 -3
  104. package/dist/services/documents/ingestion.js +11 -40
  105. package/dist/services/documents/plan.d.ts +1 -1
  106. package/dist/services/documents/plan.js +30 -17
  107. package/dist/services/documents/ports.d.ts +5 -0
  108. package/dist/services/documents/sync.js +1 -1
  109. package/dist/services/embeddings-search.js +20 -4
  110. package/dist/services/events-search.js +2 -1
  111. package/dist/services/index.d.ts +1 -0
  112. package/dist/services/index.js +1 -0
  113. package/dist/services/mail-search.d.ts +1 -1
  114. package/dist/services/mail-search.js +10 -11
  115. package/dist/services/media-archive-move.js +2 -4
  116. package/dist/services/media-archive.d.ts +0 -1
  117. package/dist/services/media-archive.js +2 -12
  118. package/dist/services/meeting-combined.js +1 -1
  119. package/dist/services/messages-combined.js +15 -4
  120. package/dist/services/moderation.js +10 -2
  121. package/dist/services/moment.d.ts +4 -10
  122. package/dist/services/moment.js +16 -44
  123. package/dist/services/notes-search.d.ts +0 -2
  124. package/dist/services/notes-search.js +1 -2
  125. package/dist/services/search-all.js +2 -1
  126. package/dist/services/tags.js +4 -2
  127. package/dist/services/task-stats.js +2 -2
  128. package/dist/services/tasks.js +2 -2
  129. package/dist/store/accounts.js +2 -1
  130. package/dist/store/sqlite/account-purge.d.ts +3 -0
  131. package/dist/store/sqlite/account-purge.js +143 -0
  132. package/dist/store/sqlite/accounts.d.ts +0 -2
  133. package/dist/store/sqlite/accounts.js +2 -134
  134. package/dist/store/sqlite/calendar.d.ts +1 -0
  135. package/dist/store/sqlite/calendar.js +5 -5
  136. package/dist/store/sqlite/catalog.js +2 -16
  137. package/dist/store/sqlite/chats.js +2 -1
  138. package/dist/store/sqlite/context-document-source.d.ts +3 -3
  139. package/dist/store/sqlite/context-document-source.js +9 -7
  140. package/dist/store/sqlite/context-evidence.js +9 -3
  141. package/dist/store/sqlite/document-listing.js +2 -1
  142. package/dist/store/sqlite/events.js +2 -1
  143. package/dist/store/sqlite/file-note.d.ts +6 -0
  144. package/dist/store/sqlite/file-note.js +15 -0
  145. package/dist/store/sqlite/files.d.ts +3 -2
  146. package/dist/store/sqlite/files.js +5 -3
  147. package/dist/store/sqlite/identities.js +2 -1
  148. package/dist/store/sqlite/imported-documents.js +2 -2
  149. package/dist/store/sqlite/knowledge.js +19 -19
  150. package/dist/store/sqlite/lucene-fields.js +8 -12
  151. package/dist/store/sqlite/mail-rules.js +2 -1
  152. package/dist/store/sqlite/meeting-calls.d.ts +4 -0
  153. package/dist/store/sqlite/meeting-calls.js +66 -0
  154. package/dist/store/sqlite/meetings.d.ts +2 -2
  155. package/dist/store/sqlite/meetings.js +4 -1
  156. package/dist/store/sqlite/mention-sources.js +2 -1
  157. package/dist/store/sqlite/mentions.js +2 -2
  158. package/dist/store/sqlite/messages.js +6 -1
  159. package/dist/store/sqlite/note-search.js +8 -11
  160. package/dist/store/sqlite/notes.d.ts +2 -0
  161. package/dist/store/sqlite/notes.js +24 -13
  162. package/dist/store/sqlite/organizations.js +2 -2
  163. package/dist/store/sqlite/people-list.js +3 -3
  164. package/dist/store/sqlite/query-filter.d.ts +3 -3
  165. package/dist/store/sqlite/query-filter.js +3 -3
  166. package/dist/store/sqlite/reads.d.ts +4 -4
  167. package/dist/store/sqlite/reads.js +4 -4
  168. package/dist/store/sqlite/search.js +11 -7
  169. package/dist/store/sqlite/test-accounts.js +1 -1
  170. package/dist/store/sqlite/trigram-match.d.ts +9 -0
  171. package/dist/store/sqlite/trigram-match.js +28 -0
  172. package/dist/store/sqlite/work-tasks.js +1 -1
  173. package/package.json +3 -3
@@ -0,0 +1,171 @@
1
+ import { isoTime, reference } from "@wirecat/cli-base/standards";
2
+ import * as v from "valibot";
3
+ import { CALL_DIRECTIONS, CALL_OUTCOMES } from "./calls.js";
4
+ import { formatMeetingReference } from "./reference.js";
5
+ const count = v.pipe(v.number(), v.integer(), v.minValue(0));
6
+ const ms = count;
7
+ const id = v.pipe(v.number(), v.integer(), v.minValue(1));
8
+ const counts = (keys) => v.strictObject(Object.fromEntries([...keys, "unknown"].map((key) => [key, count])));
9
+ const maybe = v.exactOptional;
10
+ const employee = v.strictObject({
11
+ /** `extension:<number>`, or `identity:<id>` where the provider names no extension. */
12
+ key: v.string(),
13
+ name: v.nullable(v.string()),
14
+ identity_id: v.nullable(id),
15
+ extension: v.nullable(v.string()),
16
+ calls: count,
17
+ incoming: count,
18
+ outgoing: count,
19
+ internal: count,
20
+ placed: maybe(count),
21
+ answered: maybe(count),
22
+ rang_not_answered: maybe(count),
23
+ talk_ms: maybe(ms),
24
+ mean_talk_ms: maybe(v.nullable(ms)),
25
+ mean_wait_ms: maybe(v.nullable(ms)),
26
+ max_wait_ms: maybe(v.nullable(ms)),
27
+ });
28
+ const periodFields = {
29
+ calls: count,
30
+ incoming: count,
31
+ outgoing: count,
32
+ internal: count,
33
+ answered: maybe(count),
34
+ missed: maybe(count),
35
+ talk_ms: maybe(ms),
36
+ };
37
+ const callRef = v.strictObject({ ref: reference, meeting_id: id, started_at: v.nullable(isoTime) });
38
+ /**
39
+ * `stats calls show`: layer-1 numbers over stored phone calls. Counts are over the calls that give the field, and
40
+ * `known` says how many do; a key no call gives is absent, never zero.
41
+ */
42
+ const callStatsSchema = v.strictObject({
43
+ time_zone: v.string(),
44
+ callback_within_ms: ms,
45
+ short_call_under_ms: ms,
46
+ calls: count,
47
+ /** Selected meetings that are not calls. */
48
+ not_calls: count,
49
+ /** How many calls give each field; `roles` says who placed, answered and rang. */
50
+ known: v.strictObject({
51
+ direction: count,
52
+ outcome: count,
53
+ wait_ms: count,
54
+ talk_ms: count,
55
+ duration_ms: count,
56
+ roles: count,
57
+ }),
58
+ by_direction: maybe(counts(CALL_DIRECTIONS)),
59
+ by_outcome: maybe(counts(CALL_OUTCOMES)),
60
+ talk_ms: maybe(ms),
61
+ mean_talk_ms: maybe(ms),
62
+ duration_ms: maybe(ms),
63
+ mean_wait_ms: maybe(v.nullable(ms)),
64
+ max_wait_ms: maybe(v.nullable(ms)),
65
+ short_calls: maybe(count),
66
+ employees: v.array(employee),
67
+ /** Hours 0–23 in `time_zone`. */
68
+ hours: v.array(v.strictObject({ hour: v.pipe(count, v.maxValue(23)), ...periodFields })),
69
+ /** `YYYY-MM-DD` in `time_zone`, the days with a call. */
70
+ days: v.array(v.strictObject({ date: v.string(), ...periodFields })),
71
+ missed: maybe(v.strictObject({
72
+ calls: count,
73
+ called_back: count,
74
+ not_called_back: count,
75
+ unknown_callback: count,
76
+ unknown_outcome: count,
77
+ /** Newest first. */
78
+ items: v.array(v.strictObject({
79
+ ...callRef.entries,
80
+ outcome: v.picklist(["voicemail", "busy", "no_answer"]),
81
+ client: v.nullable(v.strictObject({ key: v.string(), name: v.nullable(v.string()) })),
82
+ rang: v.array(v.string()),
83
+ called_back: maybe(v.boolean()),
84
+ callback: maybe(v.nullable(v.strictObject({ ...callRef.entries, after_ms: ms, direction: v.picklist(["outgoing", "incoming"]) }))),
85
+ })),
86
+ has_more: v.boolean(),
87
+ })),
88
+ });
89
+ export const callStats = callStatsSchema;
90
+ const iso = (at) => (at === null ? null : new Date(at).toISOString());
91
+ const has = (key, value) => (value === undefined ? {} : { [key]: value });
92
+ const periodItem = (row) => ({
93
+ calls: row.calls,
94
+ incoming: row.incoming,
95
+ outgoing: row.outgoing,
96
+ internal: row.internal,
97
+ ...has("answered", row.answered),
98
+ ...has("missed", row.missed),
99
+ ...has("talk_ms", row.talkMs),
100
+ });
101
+ export const callStatsItem = (found) => {
102
+ const refOf = (meetingId, startedAt) => ({
103
+ ref: formatMeetingReference({ type: "meeting", accountId: found.accountId, meetingId }),
104
+ meeting_id: meetingId,
105
+ started_at: iso(startedAt),
106
+ });
107
+ return {
108
+ time_zone: found.timeZone,
109
+ callback_within_ms: found.callbackWithinMs,
110
+ short_call_under_ms: found.shortCallUnderMs,
111
+ calls: found.calls,
112
+ not_calls: found.notCalls,
113
+ known: {
114
+ direction: found.known.direction,
115
+ outcome: found.known.outcome,
116
+ wait_ms: found.known.waitMs,
117
+ talk_ms: found.known.talkMs,
118
+ duration_ms: found.known.durationMs,
119
+ roles: found.known.roles,
120
+ },
121
+ ...has("by_direction", found.byDirection),
122
+ ...has("by_outcome", found.byOutcome),
123
+ ...has("talk_ms", found.talkMs),
124
+ ...has("mean_talk_ms", found.meanTalkMs),
125
+ ...has("duration_ms", found.durationMs),
126
+ ...has("mean_wait_ms", found.meanWaitMs),
127
+ ...has("max_wait_ms", found.maxWaitMs),
128
+ ...has("short_calls", found.shortCalls),
129
+ employees: found.employees.map((one) => ({
130
+ key: one.key,
131
+ name: one.name,
132
+ identity_id: one.identityId,
133
+ extension: one.extension,
134
+ calls: one.calls,
135
+ incoming: one.incoming,
136
+ outgoing: one.outgoing,
137
+ internal: one.internal,
138
+ ...has("placed", one.placed),
139
+ ...has("answered", one.answered),
140
+ ...has("rang_not_answered", one.rangNotAnswered),
141
+ ...has("talk_ms", one.talkMs),
142
+ ...has("mean_talk_ms", one.meanTalkMs),
143
+ ...has("mean_wait_ms", one.meanWaitMs),
144
+ ...has("max_wait_ms", one.maxWaitMs),
145
+ })),
146
+ hours: found.hours.map((row) => ({ hour: row.hour, ...periodItem(row) })),
147
+ days: found.days.map((row) => ({ date: row.date, ...periodItem(row) })),
148
+ ...has("missed", found.missed && {
149
+ calls: found.missed.calls,
150
+ called_back: found.missed.calledBack,
151
+ not_called_back: found.missed.notCalledBack,
152
+ unknown_callback: found.missed.unknownCallback,
153
+ unknown_outcome: found.missed.unknownOutcome,
154
+ items: found.missed.items.map((one) => ({
155
+ ...refOf(one.meetingId, one.startedAt),
156
+ outcome: one.outcome,
157
+ client: one.client,
158
+ rang: one.rang,
159
+ ...has("called_back", one.calledBack),
160
+ ...has("callback", one.callback === undefined
161
+ ? undefined
162
+ : one.callback && {
163
+ ...refOf(one.callback.meetingId, one.callback.startedAt),
164
+ after_ms: one.callback.afterMs,
165
+ direction: one.callback.direction,
166
+ }),
167
+ })),
168
+ has_more: found.missed.hasMore,
169
+ }),
170
+ };
171
+ };
@@ -0,0 +1,121 @@
1
+ import { type Call, type CallDirection, type CallEmployee, type CallOutcome } from "./calls.js";
2
+ export declare const CALLBACK_WITHIN_MS: number;
3
+ /** call-qa's layer-1 filter grades only calls of 30 seconds or more; shorter ones are reported as short. */
4
+ export declare const SHORT_CALL_UNDER_MS = 30000;
5
+ export interface CallStatsOptions {
6
+ timeZone?: string;
7
+ /** How long after a missed call a callback counts. */
8
+ callbackWithinMs?: number;
9
+ shortCallUnderMs?: number;
10
+ /** Most missed calls listed one by one; all are counted. */
11
+ missedLimit?: number;
12
+ /** Other calls of the account, read only to find callbacks: after the selection, or by employees it leaves out. */
13
+ later?: readonly Call[];
14
+ }
15
+ type Counts<K extends string> = Record<K | "unknown", number>;
16
+ /**
17
+ * A key no call of the selection can give is absent: `placed`, `answered` and `rangNotAnswered` when the provider
18
+ * never says who took a call, talk and wait when it records neither.
19
+ */
20
+ export interface CallEmployeeStats extends CallEmployee {
21
+ calls: number;
22
+ incoming: number;
23
+ outgoing: number;
24
+ internal: number;
25
+ placed?: number;
26
+ answered?: number;
27
+ rangNotAnswered?: number;
28
+ /** Over the calls this employee placed or answered. */
29
+ talkMs?: number;
30
+ /** `null` when this employee talked on no call. */
31
+ meanTalkMs?: number | null;
32
+ /** Over the incoming calls this employee answered first; `null` when none. */
33
+ meanWaitMs?: number | null;
34
+ maxWaitMs?: number | null;
35
+ }
36
+ export interface CallPeriodStats {
37
+ calls: number;
38
+ incoming: number;
39
+ outgoing: number;
40
+ internal: number;
41
+ answered?: number;
42
+ missed?: number;
43
+ talkMs?: number;
44
+ }
45
+ export interface CallCallback {
46
+ meetingId: number;
47
+ startedAt: number;
48
+ afterMs: number;
49
+ direction: "outgoing" | "incoming";
50
+ }
51
+ export interface MissedCall {
52
+ meetingId: number;
53
+ startedAt: number | null;
54
+ outcome: CallOutcome;
55
+ client: {
56
+ key: string;
57
+ name: string | null;
58
+ } | null;
59
+ rang: string[];
60
+ /** Absent when the client is unknown or the call has no start, so nobody can tell. */
61
+ calledBack?: boolean;
62
+ /** `null` when it was not called back within the window. */
63
+ callback?: CallCallback | null;
64
+ }
65
+ /**
66
+ * Counts are over the calls that give the field, and `known` says how many do. A key no call gives is absent, never
67
+ * zero; `null` means known to have no value, such as the mean wait when no incoming call was answered.
68
+ */
69
+ export interface CallStats {
70
+ timeZone: string;
71
+ callbackWithinMs: number;
72
+ shortCallUnderMs: number;
73
+ calls: number;
74
+ known: {
75
+ direction: number;
76
+ outcome: number;
77
+ waitMs: number;
78
+ talkMs: number;
79
+ durationMs: number;
80
+ roles: number;
81
+ };
82
+ byDirection?: Counts<CallDirection>;
83
+ byOutcome?: Counts<CallOutcome>;
84
+ talkMs?: number;
85
+ meanTalkMs?: number;
86
+ durationMs?: number;
87
+ /** Over the answered incoming calls. */
88
+ meanWaitMs?: number | null;
89
+ maxWaitMs?: number | null;
90
+ /** Answered calls with known talk shorter than `shortCallUnderMs`. */
91
+ shortCalls?: number;
92
+ employees: CallEmployeeStats[];
93
+ /** All 24 hours of the day in the zone. */
94
+ hours: (CallPeriodStats & {
95
+ hour: number;
96
+ })[];
97
+ /** The days with a call, in the zone, oldest first. */
98
+ days: (CallPeriodStats & {
99
+ date: string;
100
+ })[];
101
+ /** Absent when no call gives its outcome. */
102
+ missed?: {
103
+ /** Incoming calls that went to voicemail, were busy or not answered. */
104
+ calls: number;
105
+ calledBack: number;
106
+ notCalledBack: number;
107
+ /** Missed calls with no known client or no start. */
108
+ unknownCallback: number;
109
+ /** Incoming calls whose outcome is unknown, so whether they were missed is too. */
110
+ unknownOutcome: number;
111
+ items: MissedCall[];
112
+ hasMore: boolean;
113
+ };
114
+ }
115
+ /**
116
+ * Layer-1 call numbers over calls a phone system recorded: totals by direction and outcome, per employee, by hour and
117
+ * day in a zone, missed incoming calls and their callbacks, and short calls. A transferred call's talk counts for each
118
+ * employee who answered it.
119
+ */
120
+ export declare const aggregateCallStats: (calls: readonly Call[], options?: CallStatsOptions) => CallStats;
121
+ export {};
@@ -0,0 +1,211 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { CALL_DIRECTIONS, CALL_OUTCOMES, MISSED_OUTCOMES, } from "./calls.js";
3
+ import { dayKey, zoneFormat, zoneOf } from "./stats.js";
4
+ export const CALLBACK_WITHIN_MS = 24 * 60 * 60 * 1000;
5
+ /** call-qa's layer-1 filter grades only calls of 30 seconds or more; shorter ones are reported as short. */
6
+ export const SHORT_CALL_UNDER_MS = 30_000;
7
+ const MOST_MISSED = 100;
8
+ const countsOf = (keys) => Object.fromEntries([...keys, "unknown"].map((key) => [key, 0]));
9
+ const isMissed = (call) => call.direction === "incoming" && call.outcome !== null && MISSED_OUTCOMES.includes(call.outcome);
10
+ const mean = (sum, count) => (count === 0 ? null : Math.round(sum / count));
11
+ const positiveMs = (value, fallback, name) => {
12
+ const ms = value ?? fallback;
13
+ if (!Number.isSafeInteger(ms) || ms < 1)
14
+ throw new CliError("validation_error", `${name} is a positive duration`);
15
+ return ms;
16
+ };
17
+ const hourFormat = (zone) => new Intl.DateTimeFormat("en-US", { timeZone: zone, hour: "2-digit", hourCycle: "h23" });
18
+ /** A later call that answers a missed one: the business called the client, or the client got through. */
19
+ const answersMissed = (missed, later, within) => missed.startedAt !== null &&
20
+ later.startedAt !== null &&
21
+ later.startedAt > missed.startedAt &&
22
+ later.startedAt - missed.startedAt <= within &&
23
+ (later.direction === "outgoing" || (later.direction === "incoming" && later.outcome === "answered"));
24
+ const when = (present, value) => (present ? value : {});
25
+ const period = () => ({ calls: 0, incoming: 0, outgoing: 0, internal: 0, answered: 0, missed: 0, talkMs: 0 });
26
+ /**
27
+ * Layer-1 call numbers over calls a phone system recorded: totals by direction and outcome, per employee, by hour and
28
+ * day in a zone, missed incoming calls and their callbacks, and short calls. A transferred call's talk counts for each
29
+ * employee who answered it.
30
+ */
31
+ export const aggregateCallStats = (calls, options = {}) => {
32
+ const zone = zoneOf(options.timeZone);
33
+ const within = positiveMs(options.callbackWithinMs, CALLBACK_WITHIN_MS, "--within");
34
+ const short = positiveMs(options.shortCallUnderMs, SHORT_CALL_UNDER_MS, "the short-call threshold");
35
+ const limit = options.missedLimit ?? MOST_MISSED;
36
+ if (!Number.isSafeInteger(limit) || limit < 0)
37
+ throw new CliError("validation_error", "--limit is a positive number");
38
+ const known = {
39
+ direction: calls.filter((call) => call.direction !== null).length,
40
+ outcome: calls.filter((call) => call.outcome !== null).length,
41
+ waitMs: calls.filter((call) => call.waitMs !== null).length,
42
+ talkMs: calls.filter((call) => call.talkMs !== null).length,
43
+ durationMs: calls.filter((call) => call.durationMs !== null).length,
44
+ roles: calls.filter((call) => call.roles).length,
45
+ };
46
+ const has = { outcome: known.outcome > 0, talk: known.talkMs > 0, wait: known.waitMs > 0, roles: known.roles > 0 };
47
+ const days = zoneFormat(zone);
48
+ const hourOf = hourFormat(zone);
49
+ const byDirection = countsOf(CALL_DIRECTIONS);
50
+ const byOutcome = countsOf(CALL_OUTCOMES);
51
+ let talk = 0;
52
+ let duration = 0;
53
+ let wait = { sum: 0, count: 0, max: null };
54
+ let shortCalls = 0;
55
+ const employees = new Map();
56
+ const hours = Array.from({ length: 24 }, period);
57
+ const dayRows = new Map();
58
+ const employee = (one) => {
59
+ const held = employees.get(one.key) ?? {
60
+ ...one,
61
+ ...period(),
62
+ placed: 0,
63
+ rangNotAnswered: 0,
64
+ talks: 0,
65
+ waits: 0,
66
+ waitSum: 0,
67
+ maxWaitMs: null,
68
+ };
69
+ held.name ??= one.name;
70
+ held.identityId ??= one.identityId;
71
+ employees.set(one.key, held);
72
+ return held;
73
+ };
74
+ const addTo = (row, call) => {
75
+ row.calls += 1;
76
+ if (call.direction)
77
+ row[call.direction] += 1;
78
+ if (call.outcome === "answered")
79
+ row.answered += 1;
80
+ if (isMissed(call))
81
+ row.missed += 1;
82
+ row.talkMs += call.talkMs ?? 0;
83
+ };
84
+ for (const call of calls) {
85
+ byDirection[call.direction ?? "unknown"] += 1;
86
+ byOutcome[call.outcome ?? "unknown"] += 1;
87
+ talk += call.talkMs ?? 0;
88
+ duration += call.durationMs ?? 0;
89
+ if (call.outcome === "answered" && call.talkMs !== null && call.talkMs < short)
90
+ shortCalls += 1;
91
+ if (call.direction === "incoming" && call.outcome === "answered" && call.waitMs !== null)
92
+ wait = { sum: wait.sum + call.waitMs, count: wait.count + 1, max: Math.max(wait.max ?? 0, call.waitMs) };
93
+ const talkers = new Set([
94
+ ...call.answeredBy.map(({ key }) => key),
95
+ ...(call.placedBy && call.outcome === "answered" ? [call.placedBy.key] : []),
96
+ ]);
97
+ for (const one of call.employees) {
98
+ const held = employee(one);
99
+ held.calls += 1;
100
+ if (call.direction)
101
+ held[call.direction] += 1;
102
+ if (call.placedBy?.key === one.key)
103
+ held.placed += 1;
104
+ if (call.answeredBy.some(({ key }) => key === one.key))
105
+ held.answered += 1;
106
+ if (call.rang.some(({ key }) => key === one.key))
107
+ held.rangNotAnswered += 1;
108
+ if (talkers.has(one.key) && call.talkMs !== null) {
109
+ held.talkMs += call.talkMs;
110
+ held.talks += 1;
111
+ }
112
+ if (call.direction === "incoming" && call.answeredBy[0]?.key === one.key && call.waitMs !== null) {
113
+ held.waits += 1;
114
+ held.waitSum += call.waitMs;
115
+ held.maxWaitMs = Math.max(held.maxWaitMs ?? 0, call.waitMs);
116
+ }
117
+ }
118
+ if (call.startedAt !== null) {
119
+ const hour = hours[Number(hourOf.format(new Date(call.startedAt))) % 24];
120
+ if (hour)
121
+ addTo(hour, call);
122
+ const date = dayKey(call.startedAt, days);
123
+ const row = dayRows.get(date) ?? period();
124
+ addTo(row, call);
125
+ dayRows.set(date, row);
126
+ }
127
+ }
128
+ const periodOf = ({ answered, missed, talkMs, ...row }) => ({
129
+ ...row,
130
+ ...when(has.outcome, { answered, missed }),
131
+ ...when(has.talk, { talkMs }),
132
+ });
133
+ const byClient = new Map();
134
+ for (const call of [...calls, ...(options.later ?? [])]) {
135
+ if (!call.client)
136
+ continue;
137
+ const list = byClient.get(call.client.key) ?? [];
138
+ list.push(call);
139
+ byClient.set(call.client.key, list);
140
+ }
141
+ for (const list of byClient.values())
142
+ list.sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0));
143
+ const missedCalls = calls
144
+ .filter(isMissed)
145
+ .sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
146
+ .map((call) => {
147
+ const { client, startedAt } = call;
148
+ const found = client ? byClient.get(client.key)?.find((one) => answersMissed(call, one, within)) : undefined;
149
+ return {
150
+ meetingId: call.meetingId,
151
+ startedAt,
152
+ outcome: call.outcome,
153
+ client: client ? { key: client.key, name: client.name } : null,
154
+ rang: call.rang.map(({ key }) => key),
155
+ ...when(client !== null && startedAt !== null, {
156
+ calledBack: found !== undefined,
157
+ callback: found && found.startedAt !== null && startedAt !== null
158
+ ? {
159
+ meetingId: found.meetingId,
160
+ startedAt: found.startedAt,
161
+ afterMs: found.startedAt - startedAt,
162
+ direction: found.direction,
163
+ }
164
+ : null,
165
+ }),
166
+ };
167
+ });
168
+ return {
169
+ timeZone: zone,
170
+ callbackWithinMs: within,
171
+ shortCallUnderMs: short,
172
+ calls: calls.length,
173
+ known,
174
+ ...when(known.direction > 0, { byDirection }),
175
+ ...when(has.outcome, { byOutcome }),
176
+ ...when(has.talk, { talkMs: talk, meanTalkMs: Math.round(talk / known.talkMs) }),
177
+ ...when(known.durationMs > 0, { durationMs: duration }),
178
+ ...when(has.wait, { meanWaitMs: mean(wait.sum, wait.count), maxWaitMs: wait.max }),
179
+ ...when(has.outcome && has.talk, { shortCalls }),
180
+ employees: [...employees.values()]
181
+ .map(({ talks, waits, waitSum, placed, answered, rangNotAnswered, talkMs, maxWaitMs, missed: _, ...one }) => ({
182
+ key: one.key,
183
+ name: one.name,
184
+ identityId: one.identityId,
185
+ extension: one.extension,
186
+ calls: one.calls,
187
+ incoming: one.incoming,
188
+ outgoing: one.outgoing,
189
+ internal: one.internal,
190
+ ...when(has.roles, { placed, answered, rangNotAnswered }),
191
+ ...when(has.roles && has.talk, { talkMs, meanTalkMs: mean(talkMs, talks) }),
192
+ ...when(has.roles && has.wait, { meanWaitMs: mean(waitSum, waits), maxWaitMs }),
193
+ }))
194
+ .sort((a, b) => b.calls - a.calls || a.key.localeCompare(b.key)),
195
+ hours: hours.map((row, hour) => ({ hour, ...periodOf(row) })),
196
+ days: [...dayRows.entries()]
197
+ .sort(([a], [b]) => a.localeCompare(b))
198
+ .map(([date, row]) => ({ date, ...periodOf(row) })),
199
+ ...when(has.outcome, {
200
+ missed: {
201
+ calls: missedCalls.length,
202
+ calledBack: missedCalls.filter((one) => one.calledBack === true).length,
203
+ notCalledBack: missedCalls.filter((one) => one.calledBack === false).length,
204
+ unknownCallback: missedCalls.filter((one) => one.calledBack === undefined).length,
205
+ unknownOutcome: calls.filter((call) => call.direction === "incoming" && call.outcome === null).length,
206
+ items: missedCalls.slice(0, limit),
207
+ hasMore: missedCalls.length > limit,
208
+ },
209
+ }),
210
+ };
211
+ };
@@ -0,0 +1,76 @@
1
+ import type { MeetingStatsSelection } from "./stats.js";
2
+ export declare const CALL_DIRECTIONS: readonly ["incoming", "outgoing", "internal"];
3
+ export type CallDirection = (typeof CALL_DIRECTIONS)[number];
4
+ export declare const CALL_OUTCOMES: readonly ["answered", "voicemail", "busy", "no_answer", "failed"];
5
+ export type CallOutcome = (typeof CALL_OUTCOMES)[number];
6
+ /** The outcomes of an incoming call nobody took: what a business calls back. */
7
+ export declare const MISSED_OUTCOMES: readonly CallOutcome[];
8
+ /** One participant of a stored call, as the store keeps it. */
9
+ export interface StoredCallParticipant {
10
+ identityId: number;
11
+ /** The identity's external id: `phone:+34…`, `number:…`, `extension:<profile>/101`, `abonent:…`. */
12
+ identityKey: string;
13
+ role: string | null;
14
+ name: string | null;
15
+ /** The provider's own id for the participant; a PBX gives the extension number. */
16
+ externalId: string | null;
17
+ }
18
+ /** One stored meeting as the call reader needs it: its metadata unparsed, its people. */
19
+ export interface StoredCall {
20
+ meetingId: number;
21
+ startedAt: number | null;
22
+ /** The meeting's own duration column. */
23
+ durationMs: number | null;
24
+ metadata: unknown;
25
+ participants: readonly StoredCallParticipant[];
26
+ }
27
+ /** An employee on a call: by extension where the provider names one, else by the stored identity. */
28
+ export interface CallEmployee {
29
+ /** `extension:<number>` or `identity:<id>`. */
30
+ key: string;
31
+ name: string | null;
32
+ identityId: number | null;
33
+ extension: string | null;
34
+ }
35
+ export interface CallClient {
36
+ /** The identity's external id, `phone:+E164` or `number:<raw>`: the same client on every call. */
37
+ key: string;
38
+ name: string | null;
39
+ identityId: number;
40
+ }
41
+ /** A meeting read as a phone call. A field the provider does not give is `null`, never a guess. */
42
+ export interface Call {
43
+ meetingId: number;
44
+ startedAt: number | null;
45
+ direction: CallDirection | null;
46
+ outcome: CallOutcome | null;
47
+ /** From the first ring to the first answer. */
48
+ waitMs: number | null;
49
+ /** From the first answer to the end. */
50
+ talkMs: number | null;
51
+ durationMs: number | null;
52
+ client: CallClient | null;
53
+ placedBy: CallEmployee | null;
54
+ /** Whether the provider says who placed, answered and rang; when not, those three are empty and unknown. */
55
+ roles: boolean;
56
+ /** In the order they answered. */
57
+ answeredBy: CallEmployee[];
58
+ /** Rang and did not answer. */
59
+ rang: CallEmployee[];
60
+ /** Everyone of the business on the call: who placed it, answered, rang, or the provider lists as its manager. */
61
+ employees: CallEmployee[];
62
+ }
63
+ /**
64
+ * A stored meeting as a call, or `null` when it is not one: a call has a direction or an outcome a phone system
65
+ * writes, or a participant whose role is `client`. Keys may be missing or of the wrong type; each such field is
66
+ * `null`. Wait and talk come only from the provider's own `waitMs` and `talkMs`: a recording's length is not talk.
67
+ */
68
+ export declare const callOf: (stored: StoredCall) => Call | null;
69
+ export interface MeetingCallsInput extends MeetingStatsSelection {
70
+ /** Most meetings to read (default 200000); more is an error, never a silent cut. */
71
+ maxRows?: number;
72
+ }
73
+ export interface MeetingCallsStore {
74
+ /** The selected meetings with their metadata and people, oldest first; the caller reads which are calls. */
75
+ meetingCalls(input: MeetingCallsInput): Promise<StoredCall[]>;
76
+ }
@@ -0,0 +1,78 @@
1
+ export const CALL_DIRECTIONS = ["incoming", "outgoing", "internal"];
2
+ export const CALL_OUTCOMES = ["answered", "voicemail", "busy", "no_answer", "failed"];
3
+ /** The outcomes of an incoming call nobody took: what a business calls back. */
4
+ export const MISSED_OUTCOMES = ["voicemail", "busy", "no_answer"];
5
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ const milliseconds = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.round(value) : null;
7
+ const word = (value) => (typeof value === "string" && value.trim() ? value.trim() : null);
8
+ // Beeline writes INBOUND and OUTBOUND.
9
+ const DIRECTION_WORDS = {
10
+ incoming: "incoming",
11
+ inbound: "incoming",
12
+ outgoing: "outgoing",
13
+ outbound: "outgoing",
14
+ internal: "internal",
15
+ };
16
+ const directionOf = (value) => {
17
+ const found = word(value)?.toLowerCase();
18
+ return found === undefined ? null : (DIRECTION_WORDS[found] ?? null);
19
+ };
20
+ const outcomeOf = (value) => {
21
+ const found = word(value);
22
+ return found && CALL_OUTCOMES.includes(found) ? found : null;
23
+ };
24
+ const numbers = (value) => Array.isArray(value) ? value.map(word).filter((one) => one !== null) : [];
25
+ /**
26
+ * A stored meeting as a call, or `null` when it is not one: a call has a direction or an outcome a phone system
27
+ * writes, or a participant whose role is `client`. Keys may be missing or of the wrong type; each such field is
28
+ * `null`. Wait and talk come only from the provider's own `waitMs` and `talkMs`: a recording's length is not talk.
29
+ */
30
+ export const callOf = (stored) => {
31
+ const metadata = isRecord(stored.metadata) ? stored.metadata : {};
32
+ const direction = directionOf(metadata.direction);
33
+ const outcome = outcomeOf(metadata.outcome);
34
+ const clientParticipant = stored.participants.find((one) => one.role === "client");
35
+ if (direction === null && outcome === null && !clientParticipant)
36
+ return null;
37
+ const managers = stored.participants.filter((one) => one.role === "manager");
38
+ const byExtension = (number) => {
39
+ const found = managers.find((one) => one.externalId === number);
40
+ return {
41
+ key: `extension:${number}`,
42
+ name: found?.name ?? null,
43
+ identityId: found?.identityId ?? null,
44
+ extension: number,
45
+ };
46
+ };
47
+ const placed = word(metadata.placedBy);
48
+ const answeredBy = numbers(metadata.answeredBy).map(byExtension);
49
+ const rang = numbers(metadata.rang).map(byExtension);
50
+ const placedBy = placed === null ? null : byExtension(placed);
51
+ const named = [placedBy, ...answeredBy, ...rang].filter((one) => one !== null);
52
+ const listed = managers
53
+ .filter((one) => !named.some((employee) => employee.identityId === one.identityId))
54
+ .map((one) => ({
55
+ key: `identity:${one.identityId}`,
56
+ name: one.name,
57
+ identityId: one.identityId,
58
+ extension: one.externalId,
59
+ }));
60
+ const employees = [...new Map([...named, ...listed].map((one) => [one.key, one])).values()];
61
+ return {
62
+ meetingId: stored.meetingId,
63
+ startedAt: stored.startedAt,
64
+ direction,
65
+ outcome,
66
+ waitMs: milliseconds(metadata.waitMs),
67
+ talkMs: milliseconds(metadata.talkMs),
68
+ durationMs: milliseconds(metadata.durationMs) ?? milliseconds(stored.durationMs),
69
+ client: clientParticipant
70
+ ? { key: clientParticipant.identityKey, name: clientParticipant.name, identityId: clientParticipant.identityId }
71
+ : null,
72
+ placedBy,
73
+ roles: ["placedBy", "answeredBy", "rang"].some((key) => key in metadata),
74
+ answeredBy,
75
+ rang,
76
+ employees,
77
+ };
78
+ };
@@ -31,6 +31,14 @@ export interface MeetingCommandDeps {
31
31
  * keeps the one-shot deadline.
32
32
  */
33
33
  budgetOf?: (command: Command) => MeetingBudget;
34
+ /**
35
+ * `meetings list`'s page from its flags and the profile's `defaults.limit`: `pagingOf` from `@wirecat/cli-core/cli`.
36
+ * Required, since this module cannot reach the profile's settings itself.
37
+ */
38
+ pagingOf: (command: Command) => {
39
+ limit: number;
40
+ page: number;
41
+ };
34
42
  now?: () => number;
35
43
  /** The owner's zone, in which `meetings list` reads a query's dates on both sides; the computer's without it. */
36
44
  timezone?: string;