@talkpilot/core-db 1.3.64 → 1.3.66

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 (132) hide show
  1. package/README.md +863 -816
  2. package/dist/talkpilot/auditLogs/auditLogs.getters.d.ts +8 -0
  3. package/dist/talkpilot/auditLogs/auditLogs.getters.d.ts.map +1 -0
  4. package/dist/talkpilot/auditLogs/auditLogs.getters.js +26 -0
  5. package/dist/talkpilot/auditLogs/auditLogs.getters.js.map +1 -0
  6. package/dist/talkpilot/auditLogs/auditLogs.setters.d.ts +3 -0
  7. package/dist/talkpilot/auditLogs/auditLogs.setters.d.ts.map +1 -0
  8. package/dist/talkpilot/auditLogs/auditLogs.setters.js +9 -0
  9. package/dist/talkpilot/auditLogs/auditLogs.setters.js.map +1 -0
  10. package/dist/talkpilot/auditLogs/auditLogs.types.d.ts +11 -0
  11. package/dist/talkpilot/auditLogs/auditLogs.types.d.ts.map +1 -0
  12. package/dist/talkpilot/{callTokenUsage/callTokenUsage.types.js → auditLogs/auditLogs.types.js} +1 -1
  13. package/dist/talkpilot/auditLogs/auditLogs.types.js.map +1 -0
  14. package/dist/talkpilot/auditLogs/index.d.ts +3 -0
  15. package/dist/talkpilot/auditLogs/index.d.ts.map +1 -0
  16. package/dist/talkpilot/{callTokenUsage → auditLogs}/index.js +2 -1
  17. package/dist/talkpilot/auditLogs/index.js.map +1 -0
  18. package/dist/talkpilot/calls/calls.constants.d.ts +9 -1
  19. package/dist/talkpilot/calls/calls.constants.d.ts.map +1 -1
  20. package/dist/talkpilot/calls/calls.constants.js +9 -1
  21. package/dist/talkpilot/calls/calls.constants.js.map +1 -1
  22. package/dist/talkpilot/calls/calls.getters.d.ts +7 -1
  23. package/dist/talkpilot/calls/calls.getters.d.ts.map +1 -1
  24. package/dist/talkpilot/calls/calls.getters.js +181 -1
  25. package/dist/talkpilot/calls/calls.getters.js.map +1 -1
  26. package/dist/talkpilot/calls/calls.types.d.ts +35 -0
  27. package/dist/talkpilot/calls/calls.types.d.ts.map +1 -1
  28. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.d.ts +4 -0
  29. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.d.ts.map +1 -0
  30. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.js +9 -0
  31. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.js.map +1 -0
  32. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.d.ts +3 -0
  33. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.d.ts.map +1 -0
  34. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.js +9 -0
  35. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.js.map +1 -0
  36. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.d.ts +10 -0
  37. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.d.ts.map +1 -0
  38. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.js +3 -0
  39. package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.js.map +1 -0
  40. package/dist/talkpilot/clientDeletionLogs/index.d.ts +4 -0
  41. package/dist/talkpilot/clientDeletionLogs/index.d.ts.map +1 -0
  42. package/dist/talkpilot/clientDeletionLogs/index.js +20 -0
  43. package/dist/talkpilot/clientDeletionLogs/index.js.map +1 -0
  44. package/dist/talkpilot/clients/clients.constants.d.ts +3 -0
  45. package/dist/talkpilot/clients/clients.constants.d.ts.map +1 -0
  46. package/dist/talkpilot/clients/clients.constants.js +6 -0
  47. package/dist/talkpilot/clients/clients.constants.js.map +1 -0
  48. package/dist/talkpilot/clients/clients.getters.d.ts +2 -0
  49. package/dist/talkpilot/clients/clients.getters.d.ts.map +1 -1
  50. package/dist/talkpilot/clients/clients.getters.js +15 -1
  51. package/dist/talkpilot/clients/clients.getters.js.map +1 -1
  52. package/dist/talkpilot/clients/clients.lifecycle.d.ts +10 -0
  53. package/dist/talkpilot/clients/clients.lifecycle.d.ts.map +1 -0
  54. package/dist/talkpilot/clients/clients.lifecycle.js +95 -0
  55. package/dist/talkpilot/clients/clients.lifecycle.js.map +1 -0
  56. package/dist/talkpilot/clients/clients.types.d.ts +21 -0
  57. package/dist/talkpilot/clients/clients.types.d.ts.map +1 -1
  58. package/dist/talkpilot/clients/index.d.ts +2 -0
  59. package/dist/talkpilot/clients/index.d.ts.map +1 -1
  60. package/dist/talkpilot/clients/index.js +2 -0
  61. package/dist/talkpilot/clients/index.js.map +1 -1
  62. package/dist/talkpilot/index.d.ts +1 -1
  63. package/dist/talkpilot/index.d.ts.map +1 -1
  64. package/dist/talkpilot/index.js +1 -1
  65. package/dist/talkpilot/index.js.map +1 -1
  66. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts +9 -1
  67. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts.map +1 -1
  68. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js +66 -1
  69. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js.map +1 -1
  70. package/dist/talkpilot/phone_numbers/phone_numbers.types.d.ts +5 -0
  71. package/dist/talkpilot/phone_numbers/phone_numbers.types.d.ts.map +1 -1
  72. package/dist/talkpilot/results/results.constants.d.ts +4 -0
  73. package/dist/talkpilot/results/results.constants.d.ts.map +1 -0
  74. package/dist/talkpilot/results/results.constants.js +10 -0
  75. package/dist/talkpilot/results/results.constants.js.map +1 -0
  76. package/dist/talkpilot/results/results.statistics.getters.d.ts +12 -0
  77. package/dist/talkpilot/results/results.statistics.getters.d.ts.map +1 -0
  78. package/dist/talkpilot/results/results.statistics.getters.js +258 -0
  79. package/dist/talkpilot/results/results.statistics.getters.js.map +1 -0
  80. package/dist/talkpilot/results/results.statistics.types.d.ts +22 -0
  81. package/dist/talkpilot/results/results.statistics.types.d.ts.map +1 -0
  82. package/dist/talkpilot/results/results.statistics.types.js +3 -0
  83. package/dist/talkpilot/results/results.statistics.types.js.map +1 -0
  84. package/dist/test-utils/factories/index.d.ts +2 -0
  85. package/dist/test-utils/factories/index.d.ts.map +1 -1
  86. package/dist/test-utils/factories/index.js +2 -0
  87. package/dist/test-utils/factories/index.js.map +1 -1
  88. package/dist/test-utils/factories/talkpilot/clients.d.ts +14 -0
  89. package/dist/test-utils/factories/talkpilot/clients.d.ts.map +1 -0
  90. package/dist/test-utils/factories/talkpilot/clients.js +19 -0
  91. package/dist/test-utils/factories/talkpilot/clients.js.map +1 -0
  92. package/dist/test-utils/factories/talkpilot/results.d.ts +16 -0
  93. package/dist/test-utils/factories/talkpilot/results.d.ts.map +1 -0
  94. package/dist/test-utils/factories/talkpilot/results.js +40 -0
  95. package/dist/test-utils/factories/talkpilot/results.js.map +1 -0
  96. package/package.json +1 -1
  97. package/src/talkpilot/auditLogs/__tests__/auditLogs.spec.ts +91 -0
  98. package/src/talkpilot/auditLogs/auditLogs.getters.ts +26 -0
  99. package/src/talkpilot/auditLogs/auditLogs.types.ts +12 -0
  100. package/src/talkpilot/auditLogs/index.ts +2 -0
  101. package/src/talkpilot/calls/__tests__/calls.statistics.getters.spec.ts +374 -0
  102. package/src/talkpilot/calls/calls.constants.ts +12 -0
  103. package/src/talkpilot/calls/calls.getters.ts +546 -277
  104. package/src/talkpilot/calls/calls.types.ts +189 -149
  105. package/src/talkpilot/clients/__tests__/clients.getters.spec.ts +51 -0
  106. package/src/talkpilot/clients/__tests__/clients.lifecycle.spec.ts +166 -0
  107. package/src/talkpilot/clients/clients.constants.ts +2 -0
  108. package/src/talkpilot/clients/clients.getters.ts +13 -0
  109. package/src/talkpilot/clients/clients.lifecycle.ts +116 -0
  110. package/src/talkpilot/clients/clients.types.ts +19 -0
  111. package/src/talkpilot/clients/index.ts +2 -0
  112. package/src/talkpilot/index.ts +1 -1
  113. package/src/talkpilot/phone_numbers/__tests__/phone_numbers.spec.ts +257 -13
  114. package/src/talkpilot/phone_numbers/phone_numbers.getter.ts +85 -1
  115. package/src/talkpilot/phone_numbers/phone_numbers.types.ts +6 -0
  116. package/src/test-utils/factories/index.ts +2 -0
  117. package/src/test-utils/factories/talkpilot/clients.ts +21 -0
  118. package/src/test-utils/factories/talkpilot/results.ts +43 -0
  119. package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.d.ts +0 -4
  120. package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.d.ts.map +0 -1
  121. package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.js +0 -30
  122. package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.js.map +0 -1
  123. package/dist/talkpilot/callTokenUsage/callTokenUsage.types.d.ts +0 -28
  124. package/dist/talkpilot/callTokenUsage/callTokenUsage.types.d.ts.map +0 -1
  125. package/dist/talkpilot/callTokenUsage/callTokenUsage.types.js.map +0 -1
  126. package/dist/talkpilot/callTokenUsage/index.d.ts +0 -3
  127. package/dist/talkpilot/callTokenUsage/index.d.ts.map +0 -1
  128. package/dist/talkpilot/callTokenUsage/index.js.map +0 -1
  129. package/src/talkpilot/callTokenUsage/__tests__/callTokenUsage.getters.spec.ts +0 -57
  130. package/src/talkpilot/callTokenUsage/callTokenUsage.getters.ts +0 -42
  131. package/src/talkpilot/callTokenUsage/callTokenUsage.types.ts +0 -28
  132. package/src/talkpilot/callTokenUsage/index.ts +0 -2
@@ -1,277 +1,546 @@
1
- import {
2
- Call,
3
- CallDoc,
4
- CallQueryOptions,
5
- CallUpdateParams,
6
- getDb,
7
- } from "../index";
8
- import type { CountOpts, DateRange, ToolExecution, CallStatus } from "./calls.types";
9
- import {
10
- TOOL_EXECUTIONS_DEFAULT_LIMIT,
11
- TOOL_EXECUTIONS_DEFAULT_SKIP,
12
- } from "./calls.constants";
13
- import { Filter, ObjectId } from "mongodb";
14
- import * as process from "node:process";
15
- import { applyQueryOptions } from "../utils/query.utils";
16
- import { DashboardHeatmapMetric } from "./dashboard/calls.dashboard.types";
17
-
18
- export const getCallsCollection = () => {
19
- return getDb().collection<Call>("calls");
20
- };
21
-
22
- export const getCallByCallSid = (callSid: string) => {
23
- return getCallsCollection().findOne({ callSid });
24
- };
25
-
26
- export const getCallsByPhoneNumber = (phoneNumber: string) => {
27
- return getCallsCollection()
28
- .find({ customerPhoneNumber: phoneNumber })
29
- .toArray();
30
- };
31
-
32
- export const getCallsByClient = (clientId: string) => {
33
- return getCallsCollection().find({ clientId }).toArray();
34
- };
35
-
36
- export const getCallsByFlow = (flowId: ObjectId) => {
37
- return getCallsCollection().find({ flowId }).toArray();
38
- };
39
-
40
- export const createCallDoc = (
41
- call: Omit<Call, "createdAt" | "updatedAt" | "env">,
42
- ) => {
43
- return getCallsCollection().insertOne({
44
- ...call,
45
- createdAt: new Date(),
46
- updatedAt: new Date(),
47
- env: process.env.ENV ?? "unknown",
48
- });
49
- };
50
-
51
- export const updateCallByCallSid = async (
52
- callSid: string,
53
- updates: CallUpdateParams,
54
- ): Promise<CallDoc | null> => {
55
- return await getCallsCollection().findOneAndUpdate(
56
- { callSid: callSid },
57
- {
58
- $set: {
59
- ...updates,
60
- updatedAt: new Date(),
61
- },
62
- },
63
- { returnDocument: "after" },
64
- );
65
- };
66
-
67
- export const getToolExecutionsByCallSid = async (
68
- callSid: string,
69
- opts?: Pick<CallQueryOptions, "skip" | "limit"> & { clientId?: string },
70
- ): Promise<ToolExecution[]> => {
71
- const skip = Math.max(0, opts?.skip ?? TOOL_EXECUTIONS_DEFAULT_SKIP);
72
- const limit = Math.max(1, opts?.limit ?? TOOL_EXECUTIONS_DEFAULT_LIMIT);
73
- const filter: Filter<Call> = { callSid };
74
- if (opts?.clientId != null) filter.clientId = opts.clientId;
75
- const call = await getCallsCollection().findOne(
76
- filter,
77
- { projection: { toolExecutions: { $slice: [skip, limit] } } },
78
- );
79
- return call?.toolExecutions ?? [];
80
- };
81
-
82
- export const updateCallStatusByCallSid = async (
83
- callSid: string,
84
- status: CallStatus,
85
- ): Promise<CallDoc | null> =>
86
- getCallsCollection().findOneAndUpdate(
87
- { callSid },
88
- { $set: { status, updatedAt: new Date() } },
89
- { returnDocument: "after" },
90
- );
91
-
92
- export const pushToolExecution = async (
93
- callSid: string,
94
- execution: ToolExecution,
95
- ): Promise<void> => {
96
- await getCallsCollection().updateOne(
97
- { callSid },
98
- { $push: { toolExecutions: execution } },
99
- );
100
- };
101
-
102
- // get calls by client and date range
103
- //client here is the user id
104
- export const getCallsByClientAndDateRange = (
105
- clientId: string,
106
- startDate: Date,
107
- endDate: Date,
108
- ) => {
109
- return getCallsCollection()
110
- .find({
111
- clientId,
112
- createdAt: {
113
- $gte: startDate,
114
- $lte: endDate,
115
- },
116
- })
117
- .toArray();
118
- };
119
-
120
- export const findCallsByQuery = async (
121
- query: Filter<Call>,
122
- options?: CallQueryOptions,
123
- ): Promise<CallDoc[]> => {
124
- const cursor = getCallsCollection().find(query);
125
- return await applyQueryOptions(cursor, options).toArray();
126
- };
127
-
128
- export const countCalls = async (query: Filter<Call>): Promise<number> => {
129
- return getCallsCollection().countDocuments(query);
130
- };
131
-
132
- export async function countCallsByPhoneInRange(
133
- customerPhoneNumber: string,
134
- opts: CountOpts = {},
135
- range: DateRange = {},
136
- ): Promise<number> {
137
- const filter: Partial<Call> & { customerPhoneNumber: string } = {
138
- customerPhoneNumber,
139
- };
140
-
141
- if (opts.isOutgoingCall !== undefined) {
142
- filter.isOutgoingCall = opts.isOutgoingCall;
143
- }
144
- if (opts.isIncomingCall !== undefined) {
145
- filter.isIncomingCall = opts.isIncomingCall;
146
- }
147
-
148
- if (range.since || range.until) {
149
- (filter as Filter<Call>).createdAt = {
150
- ...(range.since ? { $gte: range.since } : {}),
151
- ...(range.until ? { $lt: range.until } : {}),
152
- };
153
- }
154
-
155
- return getCallsCollection().countDocuments(filter as Filter<Call>);
156
- }
157
-
158
- export const range = {
159
- between: (since: Date, until: Date): DateRange => ({ since, until }),
160
- todayToNow: (): DateRange => ({ since: startOfDay(), until: new Date() }),
161
- yesterday: (): DateRange => {
162
- const s = startOfDay(addDays(new Date(), -1));
163
- const e = addDays(s, 1);
164
- return { since: s, until: e };
165
- },
166
- todayFull: (): DateRange => {
167
- const s = startOfDay();
168
- const e = addDays(s, 1);
169
- return { since: s, until: e };
170
- },
171
- startOfDayToNow: (d: Date): DateRange => ({
172
- since: startOfDay(d),
173
- until: new Date(),
174
- }),
175
- };
176
-
177
- export function startOfDay(d: Date = new Date()): Date {
178
- const x = new Date(d);
179
- x.setUTCHours(0, 0, 0, 0);
180
- return x;
181
- }
182
-
183
- export function addDays(d: Date, days: number): Date {
184
- const x = new Date(d);
185
- x.setDate(x.getDate() + days);
186
- return x;
187
- }
188
-
189
- /**
190
- * Aggregate calls stats for a date range (createdAt in [startStr, endStr] in timezone).
191
- * completed = agentHungUp=true or status='completed'.
192
- */
193
- export async function getCallsStatsForDateRange(
194
- clientId: string,
195
- startStr: string,
196
- endStr: string,
197
- timezone: string,
198
- ): Promise<{ count: number; totalLen: number; completed: number }> {
199
- const coll = getCallsCollection();
200
- const out = await coll
201
- .aggregate<{
202
- _id: null;
203
- count: number;
204
- totalLen: number;
205
- completed: number;
206
- }>([
207
- // 1. Restrict to the given client
208
- { $match: { clientId } },
209
- // 2. Derive dateLocal (createdAt as YYYY-MM-DD in timezone) and isCompleted (agentHungUp or status='completed')
210
- {
211
- $addFields: {
212
- dateLocal: {
213
- $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone },
214
- },
215
- isCompleted: {
216
- $or: [
217
- { $eq: ["$agentHungUp", true] },
218
- { $eq: ["$status", "completed"] },
219
- ],
220
- },
221
- },
222
- },
223
- // 3. Keep only documents with dateLocal in [startStr, endStr] (inclusive)
224
- { $match: { dateLocal: { $gte: startStr, $lte: endStr } } },
225
- // 4. Single group: count, totalLen, completed
226
- {
227
- $group: {
228
- _id: null,
229
- count: { $sum: 1 },
230
- totalLen: { $sum: "$callLength" },
231
- completed: { $sum: { $cond: ["$isCompleted", 1, 0] } },
232
- },
233
- },
234
- ])
235
- .next();
236
- return {
237
- count: out?.count ?? 0,
238
- totalLen: out?.totalLen ?? 0,
239
- completed: out?.completed ?? 0,
240
- };
241
- }
242
-
243
- /**
244
- * Aggregate calls by hour for a given date (createdAt converted to given timezone). Hour format "HH:mm".
245
- */
246
- export async function getCallsHourlyAggregation(
247
- clientId: string,
248
- dateStr: string,
249
- timezone: string,
250
- ): Promise<DashboardHeatmapMetric[]> {
251
- const coll = getCallsCollection();
252
- const rows = await coll
253
- .aggregate<{ _id: number; calls: number }>([
254
- // 1. Restrict to the given client
255
- { $match: { clientId } },
256
- {
257
- $addFields: {
258
- dateLocal: {
259
- $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone },
260
- },
261
- hour: { $hour: { date: "$createdAt", timezone } },
262
- },
263
- },
264
- // 3. Keep only the requested date
265
- { $match: { dateLocal: dateStr } },
266
- // 4. Group by hour, sum calls per hour
267
- { $group: { _id: "$hour", calls: { $sum: 1 } } },
268
- // 5. Order by hour ascending (0..23)
269
- { $sort: { _id: 1 } },
270
- ])
271
- .toArray();
272
-
273
- return rows.map((r: any) => ({
274
- hour: r._id,
275
- calls: r.calls,
276
- }));
277
- }
1
+ import {
2
+ Call,
3
+ CallDoc,
4
+ CallQueryOptions,
5
+ CallUpdateParams,
6
+ getDb,
7
+ } from "../index";
8
+ import type {
9
+ CountOpts,
10
+ DateRange,
11
+ ToolExecution,
12
+ CallStatus,
13
+ ActiveCallsSummary,
14
+ TodayCallsSummary,
15
+ ClientCallStats,
16
+ SessionCallStats,
17
+ StatsDateRangeParams,
18
+ } from "./calls.types";
19
+ import {
20
+ TOOL_EXECUTIONS_DEFAULT_LIMIT,
21
+ TOOL_EXECUTIONS_DEFAULT_SKIP,
22
+ ACTIVE_STATUSES,
23
+ ACTIVE_CALLS_WINDOW_MS,
24
+ INCOMING_SESSION_ID,
25
+ ALL_STATUSES_FOR_BREAKDOWN,
26
+ } from "./calls.constants";
27
+ import { Filter, ObjectId } from "mongodb";
28
+ import * as process from "node:process";
29
+ import { applyQueryOptions } from "../utils/query.utils";
30
+ import { DashboardHeatmapMetric } from "./dashboard/calls.dashboard.types";
31
+ import {
32
+ formatYmdInTz,
33
+ startOfCalendarDayInTz,
34
+ endOfCalendarDayInTz,
35
+ } from "../../utils/date.utils";
36
+
37
+ export const getCallsCollection = () => {
38
+ return getDb().collection<Call>("calls");
39
+ };
40
+
41
+ export const getCallByCallSid = (callSid: string) => {
42
+ return getCallsCollection().findOne({ callSid });
43
+ };
44
+
45
+ export const getCallsByPhoneNumber = (phoneNumber: string) => {
46
+ return getCallsCollection()
47
+ .find({ customerPhoneNumber: phoneNumber })
48
+ .toArray();
49
+ };
50
+
51
+ export const getCallsByClient = (clientId: string) => {
52
+ return getCallsCollection().find({ clientId }).toArray();
53
+ };
54
+
55
+ export const getCallsByFlow = (flowId: ObjectId) => {
56
+ return getCallsCollection().find({ flowId }).toArray();
57
+ };
58
+
59
+ export const createCallDoc = (
60
+ call: Omit<Call, "createdAt" | "updatedAt" | "env">,
61
+ ) => {
62
+ return getCallsCollection().insertOne({
63
+ ...call,
64
+ createdAt: new Date(),
65
+ updatedAt: new Date(),
66
+ env: process.env.ENV ?? "unknown",
67
+ });
68
+ };
69
+
70
+ export const updateCallByCallSid = async (
71
+ callSid: string,
72
+ updates: CallUpdateParams,
73
+ ): Promise<CallDoc | null> => {
74
+ return await getCallsCollection().findOneAndUpdate(
75
+ { callSid: callSid },
76
+ {
77
+ $set: {
78
+ ...updates,
79
+ updatedAt: new Date(),
80
+ },
81
+ },
82
+ { returnDocument: "after" },
83
+ );
84
+ };
85
+
86
+ export const getToolExecutionsByCallSid = async (
87
+ callSid: string,
88
+ opts?: Pick<CallQueryOptions, "skip" | "limit"> & { clientId?: string },
89
+ ): Promise<ToolExecution[]> => {
90
+ const skip = Math.max(0, opts?.skip ?? TOOL_EXECUTIONS_DEFAULT_SKIP);
91
+ const limit = Math.max(1, opts?.limit ?? TOOL_EXECUTIONS_DEFAULT_LIMIT);
92
+ const filter: Filter<Call> = { callSid };
93
+ if (opts?.clientId != null) filter.clientId = opts.clientId;
94
+ const call = await getCallsCollection().findOne(
95
+ filter,
96
+ { projection: { toolExecutions: { $slice: [skip, limit] } } },
97
+ );
98
+ return call?.toolExecutions ?? [];
99
+ };
100
+
101
+ export const updateCallStatusByCallSid = async (
102
+ callSid: string,
103
+ status: CallStatus,
104
+ ): Promise<CallDoc | null> =>
105
+ getCallsCollection().findOneAndUpdate(
106
+ { callSid },
107
+ { $set: { status, updatedAt: new Date() } },
108
+ { returnDocument: "after" },
109
+ );
110
+
111
+ export const pushToolExecution = async (
112
+ callSid: string,
113
+ execution: ToolExecution,
114
+ ): Promise<void> => {
115
+ await getCallsCollection().updateOne(
116
+ { callSid },
117
+ { $push: { toolExecutions: execution } },
118
+ );
119
+ };
120
+
121
+ // get calls by client and date range
122
+ //client here is the user id
123
+ export const getCallsByClientAndDateRange = (
124
+ clientId: string,
125
+ startDate: Date,
126
+ endDate: Date,
127
+ ) => {
128
+ return getCallsCollection()
129
+ .find({
130
+ clientId,
131
+ createdAt: {
132
+ $gte: startDate,
133
+ $lte: endDate,
134
+ },
135
+ })
136
+ .toArray();
137
+ };
138
+
139
+ export const findCallsByQuery = async (
140
+ query: Filter<Call>,
141
+ options?: CallQueryOptions,
142
+ ): Promise<CallDoc[]> => {
143
+ const cursor = getCallsCollection().find(query);
144
+ return await applyQueryOptions(cursor, options).toArray();
145
+ };
146
+
147
+ export const countCalls = async (query: Filter<Call>): Promise<number> => {
148
+ return getCallsCollection().countDocuments(query);
149
+ };
150
+
151
+ export async function countCallsByPhoneInRange(
152
+ customerPhoneNumber: string,
153
+ opts: CountOpts = {},
154
+ range: DateRange = {},
155
+ ): Promise<number> {
156
+ const filter: Partial<Call> & { customerPhoneNumber: string } = {
157
+ customerPhoneNumber,
158
+ };
159
+
160
+ if (opts.isOutgoingCall !== undefined) {
161
+ filter.isOutgoingCall = opts.isOutgoingCall;
162
+ }
163
+ if (opts.isIncomingCall !== undefined) {
164
+ filter.isIncomingCall = opts.isIncomingCall;
165
+ }
166
+
167
+ if (range.since || range.until) {
168
+ (filter as Filter<Call>).createdAt = {
169
+ ...(range.since ? { $gte: range.since } : {}),
170
+ ...(range.until ? { $lt: range.until } : {}),
171
+ };
172
+ }
173
+
174
+ return getCallsCollection().countDocuments(filter as Filter<Call>);
175
+ }
176
+
177
+ export const range = {
178
+ between: (since: Date, until: Date): DateRange => ({ since, until }),
179
+ todayToNow: (): DateRange => ({ since: startOfDay(), until: new Date() }),
180
+ yesterday: (): DateRange => {
181
+ const s = startOfDay(addDays(new Date(), -1));
182
+ const e = addDays(s, 1);
183
+ return { since: s, until: e };
184
+ },
185
+ todayFull: (): DateRange => {
186
+ const s = startOfDay();
187
+ const e = addDays(s, 1);
188
+ return { since: s, until: e };
189
+ },
190
+ startOfDayToNow: (d: Date): DateRange => ({
191
+ since: startOfDay(d),
192
+ until: new Date(),
193
+ }),
194
+ };
195
+
196
+ export function startOfDay(d: Date = new Date()): Date {
197
+ const x = new Date(d);
198
+ x.setUTCHours(0, 0, 0, 0);
199
+ return x;
200
+ }
201
+
202
+ export function addDays(d: Date, days: number): Date {
203
+ const x = new Date(d);
204
+ x.setDate(x.getDate() + days);
205
+ return x;
206
+ }
207
+
208
+ /**
209
+ * Aggregate calls stats for a date range (createdAt in [startStr, endStr] in timezone).
210
+ * completed = agentHungUp=true or status='completed'.
211
+ */
212
+ export async function getCallsStatsForDateRange(
213
+ clientId: string,
214
+ startStr: string,
215
+ endStr: string,
216
+ timezone: string,
217
+ ): Promise<{ count: number; totalLen: number; completed: number }> {
218
+ const coll = getCallsCollection();
219
+ const out = await coll
220
+ .aggregate<{
221
+ _id: null;
222
+ count: number;
223
+ totalLen: number;
224
+ completed: number;
225
+ }>([
226
+ // 1. Restrict to the given client
227
+ { $match: { clientId } },
228
+ // 2. Derive dateLocal (createdAt as YYYY-MM-DD in timezone) and isCompleted (agentHungUp or status='completed')
229
+ {
230
+ $addFields: {
231
+ dateLocal: {
232
+ $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone },
233
+ },
234
+ isCompleted: {
235
+ $or: [
236
+ { $eq: ["$agentHungUp", true] },
237
+ { $eq: ["$status", "completed"] },
238
+ ],
239
+ },
240
+ },
241
+ },
242
+ // 3. Keep only documents with dateLocal in [startStr, endStr] (inclusive)
243
+ { $match: { dateLocal: { $gte: startStr, $lte: endStr } } },
244
+ // 4. Single group: count, totalLen, completed
245
+ {
246
+ $group: {
247
+ _id: null,
248
+ count: { $sum: 1 },
249
+ totalLen: { $sum: "$callLength" },
250
+ completed: { $sum: { $cond: ["$isCompleted", 1, 0] } },
251
+ },
252
+ },
253
+ ])
254
+ .next();
255
+ return {
256
+ count: out?.count ?? 0,
257
+ totalLen: out?.totalLen ?? 0,
258
+ completed: out?.completed ?? 0,
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Aggregate calls by hour for a given date (createdAt converted to given timezone). Hour format "HH:mm".
264
+ */
265
+ export async function getCallsHourlyAggregation(
266
+ clientId: string,
267
+ dateStr: string,
268
+ timezone: string,
269
+ ): Promise<DashboardHeatmapMetric[]> {
270
+ const coll = getCallsCollection();
271
+ const rows = await coll
272
+ .aggregate<{ _id: number; calls: number }>([
273
+ // 1. Restrict to the given client
274
+ { $match: { clientId } },
275
+ {
276
+ $addFields: {
277
+ dateLocal: {
278
+ $dateToString: { format: "%Y-%m-%d", date: "$createdAt", timezone },
279
+ },
280
+ hour: { $hour: { date: "$createdAt", timezone } },
281
+ },
282
+ },
283
+ // 3. Keep only the requested date
284
+ { $match: { dateLocal: dateStr } },
285
+ // 4. Group by hour, sum calls per hour
286
+ { $group: { _id: "$hour", calls: { $sum: 1 } } },
287
+ // 5. Order by hour ascending (0..23)
288
+ { $sort: { _id: 1 } },
289
+ ])
290
+ .toArray();
291
+
292
+ return rows.map((r: any) => ({
293
+ hour: r._id,
294
+ calls: r.calls,
295
+ }));
296
+ }
297
+
298
+ type StatusCountFields = { [K in (typeof ALL_STATUSES_FOR_BREAKDOWN)[number]]: number };
299
+
300
+ // One $sum/$cond accumulator per status in ALL_STATUSES_FOR_BREAKDOWN.
301
+ const buildStatusCountFields = (field: string) =>
302
+ Object.fromEntries(
303
+ ALL_STATUSES_FOR_BREAKDOWN.map((status) => [
304
+ status,
305
+ { $sum: { $cond: [{ $eq: [field, status] }, 1, 0] } },
306
+ ]),
307
+ );
308
+
309
+ const extractStatusCounts = (row: StatusCountFields): Record<string, number> =>
310
+ Object.fromEntries(ALL_STATUSES_FOR_BREAKDOWN.map((status) => [status, row[status] ?? 0]));
311
+
312
+ const dateRangeFilter = (
313
+ dateFrom: string | undefined,
314
+ dateTo: string | undefined,
315
+ timezone: string,
316
+ ): { start: Date; end: Date } => {
317
+ const today = formatYmdInTz(new Date(), timezone);
318
+ return {
319
+ start: startOfCalendarDayInTz(dateFrom ?? today, timezone),
320
+ end: endOfCalendarDayInTz(dateTo ?? today, timezone),
321
+ };
322
+ };
323
+
324
+ const buildCallsStatsMatch = ({ dateFrom, dateTo, clientId, timezone = "UTC" }: StatsDateRangeParams) => {
325
+ const range = dateFrom || dateTo ? dateRangeFilter(dateFrom, dateTo, timezone) : null;
326
+ return {
327
+ ...(range ? { createdAt: { $gte: range.start, $lte: range.end } } : {}),
328
+ ...(clientId ? { clientId } : {}),
329
+ };
330
+ };
331
+
332
+ export const aggregateActiveCallsSummary = async (
333
+ clientId?: string,
334
+ ): Promise<ActiveCallsSummary> => {
335
+ const coll = getCallsCollection();
336
+ const twoHoursAgo = new Date(Date.now() - ACTIVE_CALLS_WINDOW_MS);
337
+
338
+ const match = {
339
+ status: { $in: ACTIVE_STATUSES },
340
+ updatedAt: { $gte: twoHoursAgo },
341
+ ...(clientId ? { clientId } : {}),
342
+ };
343
+
344
+ const facetResult = await coll
345
+ .aggregate<{
346
+ counts: { total: number; incoming: number; outgoing: number }[];
347
+ activeClients: { _id: string }[];
348
+ }>([
349
+ { $match: match },
350
+ {
351
+ $facet: {
352
+ counts: [
353
+ {
354
+ $group: {
355
+ _id: null,
356
+ total: { $sum: 1 },
357
+ incoming: { $sum: { $cond: ["$isIncomingCall", 1, 0] } },
358
+ outgoing: { $sum: { $cond: ["$isOutgoingCall", 1, 0] } },
359
+ },
360
+ },
361
+ ],
362
+ activeClients: [{ $group: { _id: "$clientId" } }],
363
+ },
364
+ },
365
+ ])
366
+ .next();
367
+
368
+ const counts = facetResult?.counts?.[0];
369
+
370
+ return {
371
+ total: counts?.total ?? 0,
372
+ incoming: counts?.incoming ?? 0,
373
+ outgoing: counts?.outgoing ?? 0,
374
+ activeClientIds: (facetResult?.activeClients ?? []).map((d) => d._id || "Unknown"),
375
+ };
376
+ };
377
+
378
+ export const aggregateTodayCallsSummary = async ({
379
+ dateFrom,
380
+ dateTo,
381
+ clientId,
382
+ timezone = "UTC",
383
+ }: StatsDateRangeParams): Promise<TodayCallsSummary> => {
384
+ const coll = getCallsCollection();
385
+ const match = buildCallsStatsMatch({ dateFrom, dateTo, clientId, timezone });
386
+
387
+ const facetResult = await coll
388
+ .aggregate<{
389
+ byStatus: { _id: string; count: number }[];
390
+ byType: { _id: string; count: number }[];
391
+ total: { count: number }[];
392
+ totalSeconds: { seconds: number }[];
393
+ }>([
394
+ { $match: match },
395
+ {
396
+ $facet: {
397
+ byStatus: [{ $group: { _id: "$status", count: { $sum: 1 } } }],
398
+ byType: [
399
+ {
400
+ $group: {
401
+ _id: { $cond: ["$isIncomingCall", "incoming", "outgoing"] },
402
+ count: { $sum: 1 },
403
+ },
404
+ },
405
+ ],
406
+ total: [{ $group: { _id: null, count: { $sum: 1 } } }],
407
+ totalSeconds: [{ $group: { _id: null, seconds: { $sum: "$callLength" } } }],
408
+ },
409
+ },
410
+ ])
411
+ .next();
412
+
413
+ const byStatus: Record<string, number> = {};
414
+ (facetResult?.byStatus ?? []).forEach((s) => {
415
+ byStatus[s._id] = s.count;
416
+ });
417
+ const byType: Record<string, number> = {};
418
+ (facetResult?.byType ?? []).forEach((t) => {
419
+ byType[t._id] = t.count;
420
+ });
421
+
422
+ const totalSeconds = facetResult?.totalSeconds?.[0]?.seconds ?? 0;
423
+
424
+ return {
425
+ total: facetResult?.total?.[0]?.count ?? 0,
426
+ incoming: byType.incoming ?? 0,
427
+ outgoing: byType.outgoing ?? 0,
428
+ completed: byStatus.completed ?? 0,
429
+ failed: byStatus.failed ?? 0,
430
+ busy: byStatus.busy ?? 0,
431
+ noAnswer: byStatus["no-answer"] ?? 0,
432
+ totalMinutes: Math.ceil(totalSeconds / 60),
433
+ };
434
+ };
435
+
436
+ export const aggregateClientCallStats = async ({
437
+ dateFrom,
438
+ dateTo,
439
+ clientId,
440
+ timezone = "UTC",
441
+ }: StatsDateRangeParams): Promise<ClientCallStats[]> => {
442
+ const coll = getCallsCollection();
443
+ const match = buildCallsStatsMatch({ dateFrom, dateTo, clientId, timezone });
444
+
445
+ const rows = await coll
446
+ .aggregate<
447
+ {
448
+ _id: string;
449
+ totalCalls: number;
450
+ totalSeconds: number;
451
+ lastCallDate: Date;
452
+ } & StatusCountFields
453
+ >([
454
+ { $match: match },
455
+ {
456
+ $group: {
457
+ _id: "$clientId",
458
+ totalCalls: { $sum: 1 },
459
+ ...buildStatusCountFields("$status"),
460
+ totalSeconds: { $sum: "$callLength" },
461
+ lastCallDate: { $max: "$createdAt" },
462
+ },
463
+ },
464
+ { $sort: { totalCalls: -1 } },
465
+ ])
466
+ .toArray();
467
+
468
+ return rows.map((r) => ({
469
+ clientId: r._id || "Unknown",
470
+ totalCalls: r.totalCalls,
471
+ statusCounts: extractStatusCounts(r),
472
+ totalMinutes: Math.ceil((r.totalSeconds || 0) / 60),
473
+ lastCallDate: r.lastCallDate,
474
+ }));
475
+ };
476
+
477
+ export const aggregateSessionCallStats = async ({
478
+ dateFrom,
479
+ dateTo,
480
+ clientId,
481
+ timezone = "UTC",
482
+ }: StatsDateRangeParams): Promise<SessionCallStats[]> => {
483
+ const coll = getCallsCollection();
484
+ const match = buildCallsStatsMatch({ dateFrom, dateTo, clientId, timezone });
485
+
486
+ const rows = await coll
487
+ .aggregate<
488
+ {
489
+ _id: ObjectId | null;
490
+ sessionDoc: { session_name: string }[];
491
+ totalCalls: number;
492
+ } & StatusCountFields
493
+ >([
494
+ { $match: match },
495
+ {
496
+ $group: {
497
+ _id: "$sessionId",
498
+ totalCalls: { $sum: 1 },
499
+ ...buildStatusCountFields("$status"),
500
+ },
501
+ },
502
+ {
503
+ $lookup: {
504
+ from: "sessions",
505
+ localField: "_id",
506
+ foreignField: "_id",
507
+ as: "sessionDoc",
508
+ },
509
+ },
510
+ { $sort: { totalCalls: -1 } },
511
+ ])
512
+ .toArray();
513
+
514
+ return rows.map((r) => ({
515
+ // A null sessionId is an incoming call (expected), not a broken/orphaned one.
516
+ sessionId: r._id ? r._id.toString() : INCOMING_SESSION_ID,
517
+ sessionName: r._id ? r.sessionDoc[0]?.session_name || "Unknown" : "Incoming Call",
518
+ totalCalls: r.totalCalls,
519
+ statusCounts: extractStatusCounts(r),
520
+ }));
521
+ };
522
+
523
+ export const getAllClientsLastCallDate = async (): Promise<Map<string, Date>> => {
524
+ const rows = await getCallsCollection()
525
+ .aggregate<{ _id: string; lastCallDate: Date }>([
526
+ { $group: { _id: "$clientId", lastCallDate: { $max: "$createdAt" } } },
527
+ ])
528
+ .toArray();
529
+
530
+ return new Map(rows.map((r) => [r._id, r.lastCallDate]));
531
+ };
532
+
533
+ export const findClientIdsByCallSids = async (
534
+ callSids: string[],
535
+ ): Promise<Map<string, string>> => {
536
+ if (callSids.length === 0) return new Map();
537
+
538
+ const docs = await getCallsCollection()
539
+ .find(
540
+ { callSid: { $in: callSids } },
541
+ { projection: { _id: 0, clientId: 1, callSid: 1 } },
542
+ )
543
+ .toArray();
544
+
545
+ return new Map(docs.map((d) => [d.callSid, d.clientId]));
546
+ };