@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.
- package/README.md +863 -816
- package/dist/talkpilot/auditLogs/auditLogs.getters.d.ts +8 -0
- package/dist/talkpilot/auditLogs/auditLogs.getters.d.ts.map +1 -0
- package/dist/talkpilot/auditLogs/auditLogs.getters.js +26 -0
- package/dist/talkpilot/auditLogs/auditLogs.getters.js.map +1 -0
- package/dist/talkpilot/auditLogs/auditLogs.setters.d.ts +3 -0
- package/dist/talkpilot/auditLogs/auditLogs.setters.d.ts.map +1 -0
- package/dist/talkpilot/auditLogs/auditLogs.setters.js +9 -0
- package/dist/talkpilot/auditLogs/auditLogs.setters.js.map +1 -0
- package/dist/talkpilot/auditLogs/auditLogs.types.d.ts +11 -0
- package/dist/talkpilot/auditLogs/auditLogs.types.d.ts.map +1 -0
- package/dist/talkpilot/{callTokenUsage/callTokenUsage.types.js → auditLogs/auditLogs.types.js} +1 -1
- package/dist/talkpilot/auditLogs/auditLogs.types.js.map +1 -0
- package/dist/talkpilot/auditLogs/index.d.ts +3 -0
- package/dist/talkpilot/auditLogs/index.d.ts.map +1 -0
- package/dist/talkpilot/{callTokenUsage → auditLogs}/index.js +2 -1
- package/dist/talkpilot/auditLogs/index.js.map +1 -0
- package/dist/talkpilot/calls/calls.constants.d.ts +9 -1
- package/dist/talkpilot/calls/calls.constants.d.ts.map +1 -1
- package/dist/talkpilot/calls/calls.constants.js +9 -1
- package/dist/talkpilot/calls/calls.constants.js.map +1 -1
- package/dist/talkpilot/calls/calls.getters.d.ts +7 -1
- package/dist/talkpilot/calls/calls.getters.d.ts.map +1 -1
- package/dist/talkpilot/calls/calls.getters.js +181 -1
- package/dist/talkpilot/calls/calls.getters.js.map +1 -1
- package/dist/talkpilot/calls/calls.types.d.ts +35 -0
- package/dist/talkpilot/calls/calls.types.d.ts.map +1 -1
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.d.ts +4 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.d.ts.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.js +9 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.getters.js.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.d.ts +3 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.d.ts.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.js +9 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.setters.js.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.d.ts +10 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.d.ts.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.js +3 -0
- package/dist/talkpilot/clientDeletionLogs/clientDeletionLogs.types.js.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/index.d.ts +4 -0
- package/dist/talkpilot/clientDeletionLogs/index.d.ts.map +1 -0
- package/dist/talkpilot/clientDeletionLogs/index.js +20 -0
- package/dist/talkpilot/clientDeletionLogs/index.js.map +1 -0
- package/dist/talkpilot/clients/clients.constants.d.ts +3 -0
- package/dist/talkpilot/clients/clients.constants.d.ts.map +1 -0
- package/dist/talkpilot/clients/clients.constants.js +6 -0
- package/dist/talkpilot/clients/clients.constants.js.map +1 -0
- package/dist/talkpilot/clients/clients.getters.d.ts +2 -0
- package/dist/talkpilot/clients/clients.getters.d.ts.map +1 -1
- package/dist/talkpilot/clients/clients.getters.js +15 -1
- package/dist/talkpilot/clients/clients.getters.js.map +1 -1
- package/dist/talkpilot/clients/clients.lifecycle.d.ts +10 -0
- package/dist/talkpilot/clients/clients.lifecycle.d.ts.map +1 -0
- package/dist/talkpilot/clients/clients.lifecycle.js +95 -0
- package/dist/talkpilot/clients/clients.lifecycle.js.map +1 -0
- package/dist/talkpilot/clients/clients.types.d.ts +21 -0
- package/dist/talkpilot/clients/clients.types.d.ts.map +1 -1
- package/dist/talkpilot/clients/index.d.ts +2 -0
- package/dist/talkpilot/clients/index.d.ts.map +1 -1
- package/dist/talkpilot/clients/index.js +2 -0
- package/dist/talkpilot/clients/index.js.map +1 -1
- package/dist/talkpilot/index.d.ts +1 -1
- package/dist/talkpilot/index.d.ts.map +1 -1
- package/dist/talkpilot/index.js +1 -1
- package/dist/talkpilot/index.js.map +1 -1
- package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts +9 -1
- package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts.map +1 -1
- package/dist/talkpilot/phone_numbers/phone_numbers.getter.js +66 -1
- package/dist/talkpilot/phone_numbers/phone_numbers.getter.js.map +1 -1
- package/dist/talkpilot/phone_numbers/phone_numbers.types.d.ts +5 -0
- package/dist/talkpilot/phone_numbers/phone_numbers.types.d.ts.map +1 -1
- package/dist/talkpilot/results/results.constants.d.ts +4 -0
- package/dist/talkpilot/results/results.constants.d.ts.map +1 -0
- package/dist/talkpilot/results/results.constants.js +10 -0
- package/dist/talkpilot/results/results.constants.js.map +1 -0
- package/dist/talkpilot/results/results.statistics.getters.d.ts +12 -0
- package/dist/talkpilot/results/results.statistics.getters.d.ts.map +1 -0
- package/dist/talkpilot/results/results.statistics.getters.js +258 -0
- package/dist/talkpilot/results/results.statistics.getters.js.map +1 -0
- package/dist/talkpilot/results/results.statistics.types.d.ts +22 -0
- package/dist/talkpilot/results/results.statistics.types.d.ts.map +1 -0
- package/dist/talkpilot/results/results.statistics.types.js +3 -0
- package/dist/talkpilot/results/results.statistics.types.js.map +1 -0
- package/dist/test-utils/factories/index.d.ts +2 -0
- package/dist/test-utils/factories/index.d.ts.map +1 -1
- package/dist/test-utils/factories/index.js +2 -0
- package/dist/test-utils/factories/index.js.map +1 -1
- package/dist/test-utils/factories/talkpilot/clients.d.ts +14 -0
- package/dist/test-utils/factories/talkpilot/clients.d.ts.map +1 -0
- package/dist/test-utils/factories/talkpilot/clients.js +19 -0
- package/dist/test-utils/factories/talkpilot/clients.js.map +1 -0
- package/dist/test-utils/factories/talkpilot/results.d.ts +16 -0
- package/dist/test-utils/factories/talkpilot/results.d.ts.map +1 -0
- package/dist/test-utils/factories/talkpilot/results.js +40 -0
- package/dist/test-utils/factories/talkpilot/results.js.map +1 -0
- package/package.json +1 -1
- package/src/talkpilot/auditLogs/__tests__/auditLogs.spec.ts +91 -0
- package/src/talkpilot/auditLogs/auditLogs.getters.ts +26 -0
- package/src/talkpilot/auditLogs/auditLogs.types.ts +12 -0
- package/src/talkpilot/auditLogs/index.ts +2 -0
- package/src/talkpilot/calls/__tests__/calls.statistics.getters.spec.ts +374 -0
- package/src/talkpilot/calls/calls.constants.ts +12 -0
- package/src/talkpilot/calls/calls.getters.ts +546 -277
- package/src/talkpilot/calls/calls.types.ts +189 -149
- package/src/talkpilot/clients/__tests__/clients.getters.spec.ts +51 -0
- package/src/talkpilot/clients/__tests__/clients.lifecycle.spec.ts +166 -0
- package/src/talkpilot/clients/clients.constants.ts +2 -0
- package/src/talkpilot/clients/clients.getters.ts +13 -0
- package/src/talkpilot/clients/clients.lifecycle.ts +116 -0
- package/src/talkpilot/clients/clients.types.ts +19 -0
- package/src/talkpilot/clients/index.ts +2 -0
- package/src/talkpilot/index.ts +1 -1
- package/src/talkpilot/phone_numbers/__tests__/phone_numbers.spec.ts +257 -13
- package/src/talkpilot/phone_numbers/phone_numbers.getter.ts +85 -1
- package/src/talkpilot/phone_numbers/phone_numbers.types.ts +6 -0
- package/src/test-utils/factories/index.ts +2 -0
- package/src/test-utils/factories/talkpilot/clients.ts +21 -0
- package/src/test-utils/factories/talkpilot/results.ts +43 -0
- package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.d.ts +0 -4
- package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.d.ts.map +0 -1
- package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.js +0 -30
- package/dist/talkpilot/callTokenUsage/callTokenUsage.getters.js.map +0 -1
- package/dist/talkpilot/callTokenUsage/callTokenUsage.types.d.ts +0 -28
- package/dist/talkpilot/callTokenUsage/callTokenUsage.types.d.ts.map +0 -1
- package/dist/talkpilot/callTokenUsage/callTokenUsage.types.js.map +0 -1
- package/dist/talkpilot/callTokenUsage/index.d.ts +0 -3
- package/dist/talkpilot/callTokenUsage/index.d.ts.map +0 -1
- package/dist/talkpilot/callTokenUsage/index.js.map +0 -1
- package/src/talkpilot/callTokenUsage/__tests__/callTokenUsage.getters.spec.ts +0 -57
- package/src/talkpilot/callTokenUsage/callTokenUsage.getters.ts +0 -42
- package/src/talkpilot/callTokenUsage/callTokenUsage.types.ts +0 -28
- 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 {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
export const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
);
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
export
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
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
|
+
};
|