@talkpilot/core-db 1.3.70 → 1.3.71

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 CHANGED
@@ -182,6 +182,7 @@ Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and fact
182
182
  | 1.3.61 | Optional `activeFlowId` on `WebsiteTalkProduct` (CP-1849). WebsiteTalk updates this flow instead of the flow on a phone number. |
183
183
  | 1.3.62 | Pause/Resume support for WebsiteTalk scans (CP-1752): `PAUSED` and `CANCELED` added to `SCAN_STATUSES` (`PAUSED` deliberately excluded from `FINISHED_SCAN_STATUSES` — pausing isn't done, `CANCELED` is). Added `Scan.pausedAt`, tracked across pause/resume so elapsed-time display can freeze correctly instead of counting the paused duration. |
184
184
  | 1.3.64 | New `callTokenUsage` collection with `incrementCallTokenUsage` (CP-1810): per-call realtime token usage, one document per `callSid`. |
185
+ | 1.3.71 | Who ended a call (CP-1873): optional `Call.endedBy` (`system` / `agent` / `user`), `CallEndedByValues`, and `setCallEndedBy` (first write wins). **Breaking** vs 1.3.69–1.3.70: the value `resident` was replaced by `user`. |
185
186
 
186
187
  ### 1.1.9
187
188
 
@@ -804,6 +805,24 @@ Optional `activeFlowId` on `WebsiteTalkProduct`. WTIS reads this field when it u
804
805
 
805
806
  No — the field is optional. **WTIS** should upgrade to **1.3.61** so the call-script update can use it.
806
807
 
808
+ ### 1.3.71 — Who ended the call (CP-1873)
809
+
810
+ Records who ended a connected call. Unset for calls that never connected (busy, no-answer) and for calls moved to a conference.
811
+
812
+ **Added**
813
+
814
+ | Item | Purpose |
815
+ | --- | --- |
816
+ | `Call.endedBy` | `system` (our platform, e.g. silence timeout), `agent` (the bot ended the flow) or `user` (the caller hung up). |
817
+ | `CallEndedByValues` / `CallEndedBy` | Const object and the type derived from it, same pattern as `CallStatusValues`. |
818
+ | `setCallEndedBy(callSid, endedBy)` | Writes only if `endedBy` is not set yet; returns `true` when this call wrote it. |
819
+
820
+ `endedBy` is not part of `CallUpdateParams`, so `updateCallByCallSid` cannot overwrite it.
821
+
822
+ **Do I need to update my app?**
823
+
824
+ **TalkPilot Server** must upgrade to **1.3.71** to write the field. 1.3.69–1.3.70 used `resident` instead of `user` — don't use them.
825
+
807
826
  ## 🛠 CI/CD & deployment
808
827
 
809
828
  - This package is consumed by Cloud Build-based services (TalkPilot Server, MIS, CIS) as a dependency when Docker images are built. Keep `dist/` in sync with your builds because the compiled artifact is what downstream services install.
@@ -32,4 +32,10 @@ export declare const CallStatusValues: {
32
32
  readonly Canceled: "canceled";
33
33
  };
34
34
  export declare const ALL_CALL_STATUSES: ("in-progress" | "answered" | "no-answer" | "completed" | "busy" | "failed" | "canceled" | "initiated" | "ringing")[];
35
+ /** Who ended a connected call: our platform, the bot (end flow), or the caller. */
36
+ export declare const CallEndedByValues: {
37
+ readonly System: "system";
38
+ readonly Agent: "agent";
39
+ readonly User: "user";
40
+ };
35
41
  //# sourceMappingURL=calls.constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"calls.constants.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/calls/calls.constants.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,eAAO,MAAM,wBAAwB,EAAG,UAAmB,CAAC;AAE5D,gDAAgD;AAChD,eAAO,MAAM,0BAA0B,EAAG,YAAqB,CAAC;AAEhE,wEAAwE;AACxE,eAAO,MAAM,gBAAgB,sCAAuC,CAAC;AAErE,4EAA4E;AAC5E,eAAO,MAAM,cAAc,mEAMjB,CAAC;AAEX,6BAA6B;AAC7B,eAAO,MAAM,aAAa,KAAK,CAAC;AAEhC,iEAAiE;AACjE,eAAO,MAAM,iBAAiB,QAAS,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAC/C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD,eAAO,MAAM,gBAAgB;;;;;;;;;;CAUnB,CAAC;AAEX,eAAO,MAAM,iBAAiB,uHAAkC,CAAC"}
1
+ {"version":3,"file":"calls.constants.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/calls/calls.constants.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,eAAO,MAAM,wBAAwB,EAAG,UAAmB,CAAC;AAE5D,gDAAgD;AAChD,eAAO,MAAM,0BAA0B,EAAG,YAAqB,CAAC;AAEhE,wEAAwE;AACxE,eAAO,MAAM,gBAAgB,sCAAuC,CAAC;AAErE,4EAA4E;AAC5E,eAAO,MAAM,cAAc,mEAMjB,CAAC;AAEX,6BAA6B;AAC7B,eAAO,MAAM,aAAa,KAAK,CAAC;AAEhC,iEAAiE;AACjE,eAAO,MAAM,iBAAiB,QAAS,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,IAAI,CAAC;AAC/C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD,eAAO,MAAM,gBAAgB;;;;;;;;;;CAUnB,CAAC;AAEX,eAAO,MAAM,iBAAiB,uHAAkC,CAAC;AAEjE,mFAAmF;AACnF,eAAO,MAAM,iBAAiB;;;;CAIpB,CAAC"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ALL_CALL_STATUSES = exports.CallStatusValues = exports.TOOL_EXECUTIONS_DEFAULT_LIMIT = exports.TOOL_EXECUTIONS_DEFAULT_SKIP = exports.TREND_WEEK_BUCKET_MIN_MONTHS = exports.TREND_MONTH_BUCKET_MIN_MONTHS = exports.STATS_MAX_TIME_MS = exports.HOURS_PER_DAY = exports.FINAL_STATUSES = exports.IN_CALL_STATUSES = exports.CONFERENCE_ROLE_SUPERVISOR = exports.CONFERENCE_ROLE_CUSTOMER = void 0;
3
+ exports.CallEndedByValues = exports.ALL_CALL_STATUSES = exports.CallStatusValues = exports.TOOL_EXECUTIONS_DEFAULT_LIMIT = exports.TOOL_EXECUTIONS_DEFAULT_SKIP = exports.TREND_WEEK_BUCKET_MIN_MONTHS = exports.TREND_MONTH_BUCKET_MIN_MONTHS = exports.STATS_MAX_TIME_MS = exports.HOURS_PER_DAY = exports.FINAL_STATUSES = exports.IN_CALL_STATUSES = exports.CONFERENCE_ROLE_SUPERVISOR = exports.CONFERENCE_ROLE_CUSTOMER = void 0;
4
4
  /** Customer role within a conference call. */
5
5
  exports.CONFERENCE_ROLE_CUSTOMER = "customer";
6
6
  /** Supervisor role within a conference call. */
@@ -41,4 +41,10 @@ exports.CallStatusValues = {
41
41
  Canceled: "canceled",
42
42
  };
43
43
  exports.ALL_CALL_STATUSES = Object.values(exports.CallStatusValues);
44
+ /** Who ended a connected call: our platform, the bot (end flow), or the caller. */
45
+ exports.CallEndedByValues = {
46
+ System: "system",
47
+ Agent: "agent",
48
+ User: "user",
49
+ };
44
50
  //# sourceMappingURL=calls.constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"calls.constants.js","sourceRoot":"","sources":["../../../src/talkpilot/calls/calls.constants.ts"],"names":[],"mappings":";;;AAAA,8CAA8C;AACjC,QAAA,wBAAwB,GAAG,UAAmB,CAAC;AAE5D,gDAAgD;AACnC,QAAA,0BAA0B,GAAG,YAAqB,CAAC;AAEhE,wEAAwE;AAC3D,QAAA,gBAAgB,GAAG,CAAC,aAAa,EAAE,UAAU,CAAU,CAAC;AAErE,4EAA4E;AAC/D,QAAA,cAAc,GAAG;IAC5B,WAAW;IACX,WAAW;IACX,MAAM;IACN,QAAQ;IACR,UAAU;CACF,CAAC;AAEX,6BAA6B;AAChB,QAAA,aAAa,GAAG,EAAE,CAAC;AAEhC,iEAAiE;AACpD,QAAA,iBAAiB,GAAG,MAAM,CAAC;AAExC;;;;;GAKG;AACU,QAAA,6BAA6B,GAAG,CAAC,CAAC;AAClC,QAA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B,SAAS,EAAE,WAAW;IACtB,IAAI,EAAE,MAAM;IACZ,QAAQ,EAAE,WAAW;IACrB,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;CACZ,CAAC;AAEE,QAAA,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC,wBAAgB,CAAC,CAAC;AAEjE,mFAAmF;AACtE,QAAA,iBAAiB,GAAG;IAC/B,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;IACd,IAAI,EAAE,MAAM;CACJ,CAAC"}
@@ -1,10 +1,10 @@
1
1
  import { ObjectId, Sort, WithId } from "mongodb";
2
2
  import { TranscriptionSegment } from "../results";
3
3
  import { LeadProperty } from "../leads";
4
- import { CallStatusValues, CONFERENCE_ROLE_CUSTOMER, CONFERENCE_ROLE_SUPERVISOR } from "./calls.constants";
4
+ import { CallEndedByValues, CallStatusValues, CONFERENCE_ROLE_CUSTOMER, CONFERENCE_ROLE_SUPERVISOR } from "./calls.constants";
5
5
  export type ConferenceRole = typeof CONFERENCE_ROLE_CUSTOMER | typeof CONFERENCE_ROLE_SUPERVISOR | null;
6
6
  export type CallStatus = (typeof CallStatusValues)[keyof typeof CallStatusValues];
7
- export type CallEndedBy = "system" | "resident";
7
+ export type CallEndedBy = (typeof CallEndedByValues)[keyof typeof CallEndedByValues];
8
8
  export type Call = {
9
9
  callSid: string;
10
10
  flowId: ObjectId;
@@ -1 +1 @@
1
- {"version":3,"file":"calls.types.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/calls/calls.types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC,OAAO,EACL,gBAAgB,EAChB,wBAAwB,EACxB,0BAA0B,EAC3B,MAAM,mBAAmB,CAAC;AAE3B,MAA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B,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,KAAK,CAAC,EAAE,IAAI,CAAC;CACd,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talkpilot/core-db",
3
- "version": "1.3.70",
3
+ "version": "1.3.71",
4
4
  "description": "Core database package for centralized connections and ORM integration.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,519 +1,519 @@
1
- import {
2
- createCallDoc,
3
- getCallsByFlow,
4
- getCallsByClient,
5
- getCallsByPhoneNumber,
6
- getCallByCallSid,
7
- findCallsByQuery,
8
- countCalls,
9
- getCallsByClientAndDateRange,
10
- getCallsCollection,
11
- pushToolExecution,
12
- getToolExecutionsByCallSid,
13
- updateCallStatusByCallSid,
14
- setCallEndedBy,
15
- } from "../calls.getters";
16
- import type { ToolExecution, ToolExecutionStep } from "../calls.types";
17
- import { ObjectId } from "mongodb";
18
- import { createOutGoingCallDoc } from "../../../test-utils/factories";
19
-
20
- describe("db.calls", () => {
21
- it("should return calls by flow", async () => {
22
- const flowId = new ObjectId();
23
- const call1 = createOutGoingCallDoc({ flowId });
24
- const call2 = createOutGoingCallDoc({ flowId });
25
-
26
- await createCallDoc(call1);
27
- await createCallDoc(call2);
28
-
29
- const result = await getCallsByFlow(flowId);
30
-
31
- expect(result.length).toBe(2);
32
- expect(result).toMatchObject([
33
- { callSid: call1.callSid },
34
- { callSid: call2.callSid },
35
- ]);
36
- });
37
-
38
- it("should get call by callSid", async () => {
39
- const call = createOutGoingCallDoc();
40
- await createCallDoc(call);
41
-
42
- const result = await getCallByCallSid(call.callSid);
43
-
44
- expect(result).toBeDefined();
45
- expect(result?.callSid).toBe(call.callSid);
46
- });
47
-
48
- it("should get calls by client", async () => {
49
- const call = createOutGoingCallDoc();
50
- await createCallDoc(call);
51
-
52
- const result = await getCallsByClient(call.clientId);
53
-
54
- expect(result.some((c) => c.callSid === call.callSid)).toBe(true);
55
- });
56
-
57
- it("should get calls by phone number", async () => {
58
- const call = createOutGoingCallDoc();
59
- await createCallDoc(call);
60
-
61
- const result = await getCallsByPhoneNumber(call.customerPhoneNumber);
62
-
63
- expect(result.some((c) => c.callSid === call.callSid)).toBe(true);
64
- });
65
-
66
- it("should set current status only via updateCallStatusByCallSid", async () => {
67
- const call = createOutGoingCallDoc({ status: "ringing" });
68
- await createCallDoc(call);
69
-
70
- const updated = await updateCallStatusByCallSid(call.callSid, "in-progress");
71
-
72
- expect(updated?.status).toBe("in-progress");
73
- expect(await getCallByCallSid(call.callSid)).toMatchObject({
74
- status: "in-progress",
75
- });
76
- });
77
-
78
- describe("setCallEndedBy()", () => {
79
- it("should set endedBy when it is not set yet", async () => {
80
- const call = createOutGoingCallDoc();
81
- await createCallDoc(call);
82
-
83
- const written = await setCallEndedBy(call.callSid, "resident");
84
-
85
- expect(written).toBe(true);
86
- expect(await getCallByCallSid(call.callSid)).toMatchObject({
87
- endedBy: "resident",
88
- });
89
- });
90
-
91
- it("should keep the first value when called again", async () => {
92
- const call = createOutGoingCallDoc();
93
- await createCallDoc(call);
94
-
95
- await setCallEndedBy(call.callSid, "resident");
96
- const written = await setCallEndedBy(call.callSid, "system");
97
-
98
- expect(written).toBe(false);
99
- expect(await getCallByCallSid(call.callSid)).toMatchObject({
100
- endedBy: "resident",
101
- });
102
- });
103
-
104
- it("should let only one of two concurrent writers win", async () => {
105
- const call = createOutGoingCallDoc();
106
- await createCallDoc(call);
107
-
108
- const results = await Promise.all([
109
- setCallEndedBy(call.callSid, "resident"),
110
- setCallEndedBy(call.callSid, "system"),
111
- ]);
112
-
113
- expect(results.filter(Boolean)).toHaveLength(1);
114
- const stored = await getCallByCallSid(call.callSid);
115
- expect(stored?.endedBy).toBe(results[0] ? "resident" : "system");
116
- });
117
-
118
- it("should return false when the call does not exist", async () => {
119
- await expect(setCallEndedBy("nonexistent-sid", "system")).resolves.toBe(
120
- false,
121
- );
122
- });
123
- });
124
-
125
- describe("findCallsByQuery()", () => {
126
- it("should find calls by status with limit and sort", async () => {
127
- const clientId = "client123";
128
- const call1 = createOutGoingCallDoc({ clientId, status: "completed" });
129
- const call2 = createOutGoingCallDoc({ clientId, status: "completed" });
130
- const call3 = createOutGoingCallDoc({ clientId, status: "busy" });
131
-
132
- // We need to control createdAt to test sort. We'll insert directly.
133
- await getCallsCollection().insertOne({
134
- ...call1,
135
- createdAt: new Date("2023-01-01"),
136
- updatedAt: new Date(),
137
- env: "test",
138
- });
139
- await getCallsCollection().insertOne({
140
- ...call2,
141
- createdAt: new Date("2023-01-02"),
142
- updatedAt: new Date(),
143
- env: "test",
144
- });
145
- await getCallsCollection().insertOne({
146
- ...call3,
147
- createdAt: new Date(),
148
- updatedAt: new Date(),
149
- env: "test",
150
- });
151
-
152
- const result = await findCallsByQuery(
153
- { clientId, status: "completed" },
154
- { sort: { createdAt: -1 }, limit: 1 },
155
- );
156
-
157
- expect(result.length).toBe(1);
158
- expect(result[0].callSid).toBe(call2.callSid);
159
- });
160
- });
161
-
162
- describe("countCalls()", () => {
163
- it("should count calls matching query", async () => {
164
- const clientId = "countClient";
165
- await createCallDoc(
166
- createOutGoingCallDoc({ clientId, status: "completed" }),
167
- );
168
- await createCallDoc(
169
- createOutGoingCallDoc({ clientId, status: "completed" }),
170
- );
171
- await createCallDoc(
172
- createOutGoingCallDoc({ clientId, status: "failed" }),
173
- );
174
-
175
- const count = await countCalls({ clientId, status: "completed" });
176
- expect(count).toBe(2);
177
- });
178
- });
179
-
180
- describe("pushToolExecution()", () => {
181
- let callSid: string;
182
-
183
- beforeEach(async () => {
184
- const call = createOutGoingCallDoc();
185
- await createCallDoc(call);
186
- callSid = call.callSid;
187
- });
188
-
189
- const makeHttpExecution = (
190
- overrides?: Partial<ToolExecution>,
191
- ): ToolExecution => ({
192
- toolName: "sendSms",
193
- executedAt: new Date(),
194
- durationMs: 120,
195
- args: { to: "+1234567890", message: "hello" },
196
- meta: {
197
- kind: "http",
198
- url: "https://api.example.com/sms",
199
- method: "POST",
200
- },
201
- status: "success",
202
- httpStatus: 200,
203
- ...overrides,
204
- });
205
-
206
- it("should append an execution to a call with none", async () => {
207
- const execution = makeHttpExecution();
208
- await pushToolExecution(callSid, execution);
209
-
210
- const result = await getCallByCallSid(callSid);
211
- expect(result?.toolExecutions).toHaveLength(1);
212
- expect(result?.toolExecutions?.[0]).toMatchObject({
213
- toolName: "sendSms",
214
- status: "success",
215
- httpStatus: 200,
216
- });
217
- });
218
-
219
- it("should maintain insertion order across multiple pushes", async () => {
220
- const first = makeHttpExecution({ toolName: "first" });
221
- const second = makeHttpExecution({ toolName: "second" });
222
- const third = makeHttpExecution({ toolName: "third" });
223
-
224
- await pushToolExecution(callSid, first);
225
- await pushToolExecution(callSid, second);
226
- await pushToolExecution(callSid, third);
227
-
228
- const result = await getCallByCallSid(callSid);
229
- expect(result?.toolExecutions?.map((e) => e.toolName)).toEqual([
230
- "first",
231
- "second",
232
- "third",
233
- ]);
234
- });
235
-
236
- it("should store an internal tool execution", async () => {
237
- const execution: ToolExecution = {
238
- toolName: "endFlow",
239
- executedAt: new Date(),
240
- durationMs: 5,
241
- args: {},
242
- meta: { kind: "internal" },
243
- status: "success",
244
- };
245
-
246
- await pushToolExecution(callSid, execution);
247
-
248
- const result = await getCallByCallSid(callSid);
249
- expect(result?.toolExecutions?.[0]).toMatchObject({
250
- toolName: "endFlow",
251
- meta: { kind: "internal" },
252
- });
253
- });
254
-
255
- it("should store redacted args for sensitive tools", async () => {
256
- const execution = makeHttpExecution({ args: { _redacted: true } });
257
- await pushToolExecution(callSid, execution);
258
-
259
- const result = await getCallByCallSid(callSid);
260
- expect(result?.toolExecutions?.[0].args).toEqual({ _redacted: true });
261
- });
262
-
263
- it("should store an error execution", async () => {
264
- const execution = makeHttpExecution({ status: "error", httpStatus: 500 });
265
- await pushToolExecution(callSid, execution);
266
-
267
- const result = await getCallByCallSid(callSid);
268
- expect(result?.toolExecutions?.[0]).toMatchObject({
269
- status: "error",
270
- httpStatus: 500,
271
- });
272
- });
273
-
274
- it("should be a no-op for an unknown callSid", async () => {
275
- await expect(
276
- pushToolExecution("nonexistent-sid", makeHttpExecution()),
277
- ).resolves.not.toThrow();
278
- });
279
-
280
- it("should store the response body", async () => {
281
- const execution = makeHttpExecution({
282
- response: { userId: "123", status: "sent" },
283
- });
284
- await pushToolExecution(callSid, execution);
285
-
286
- const result = await getCallByCallSid(callSid);
287
- expect(result?.toolExecutions?.[0].response).toEqual({
288
- userId: "123",
289
- status: "sent",
290
- });
291
- });
292
- });
293
-
294
- describe("getToolExecutionsByCallSid()", () => {
295
- const makeExecution = (
296
- overrides?: Partial<ToolExecution>,
297
- ): ToolExecution => ({
298
- toolName: "testTool",
299
- executedAt: new Date(),
300
- durationMs: 100,
301
- args: { query: "test" },
302
- meta: { kind: "http", url: "https://example.com", method: "POST" },
303
- status: "success",
304
- httpStatus: 200,
305
- ...overrides,
306
- });
307
-
308
- it("returns all executions for a call", async () => {
309
- const call = createOutGoingCallDoc();
310
- await createCallDoc(call);
311
- await pushToolExecution(call.callSid, makeExecution({ toolName: "first" }));
312
- await pushToolExecution(call.callSid, makeExecution({ toolName: "second" }));
313
-
314
- const result = await getToolExecutionsByCallSid(call.callSid);
315
-
316
- expect(result).toHaveLength(2);
317
- expect(result.map((e) => e.toolName)).toEqual(["first", "second"]);
318
- });
319
-
320
- it("returns an empty array when the call has no executions", async () => {
321
- const call = createOutGoingCallDoc();
322
- await createCallDoc(call);
323
-
324
- const result = await getToolExecutionsByCallSid(call.callSid);
325
-
326
- expect(result).toEqual([]);
327
- });
328
-
329
- it("returns an empty array for an unknown callSid", async () => {
330
- const result = await getToolExecutionsByCallSid("nonexistent-sid");
331
-
332
- expect(result).toEqual([]);
333
- });
334
-
335
- it("respects skip and limit for pagination", async () => {
336
- const call = createOutGoingCallDoc();
337
- await createCallDoc(call);
338
- for (const name of ["a", "b", "c", "d", "e"]) {
339
- await pushToolExecution(call.callSid, makeExecution({ toolName: name }));
340
- }
341
-
342
- const page1 = await getToolExecutionsByCallSid(call.callSid, { skip: 0, limit: 2 });
343
- const page2 = await getToolExecutionsByCallSid(call.callSid, { skip: 2, limit: 2 });
344
- const page3 = await getToolExecutionsByCallSid(call.callSid, { skip: 4, limit: 2 });
345
-
346
- expect(page1.map((e) => e.toolName)).toEqual(["a", "b"]);
347
- expect(page2.map((e) => e.toolName)).toEqual(["c", "d"]);
348
- expect(page3.map((e) => e.toolName)).toEqual(["e"]);
349
- });
350
-
351
- it("includes steps when present", async () => {
352
- const call = createOutGoingCallDoc();
353
- await createCallDoc(call);
354
- const steps: ToolExecutionStep[] = [
355
- { timestamp: new Date("2024-01-01T10:00:00Z"), label: "audio_enrichment", level: "info", data: { audioUsed: true } },
356
- { timestamp: new Date("2024-01-01T10:00:01Z"), label: "subject_classification", level: "warn" },
357
- ];
358
- await pushToolExecution(call.callSid, makeExecution({ steps }));
359
-
360
- const result = await getToolExecutionsByCallSid(call.callSid);
361
-
362
- expect(result[0].steps).toHaveLength(2);
363
- const s0 = result[0].steps![0];
364
- expect(s0.label).toBe("audio_enrichment");
365
- expect(s0.level).toBe("info");
366
- expect(new Date(s0.timestamp).toISOString()).toBe("2024-01-01T10:00:00.000Z");
367
- expect(s0.data).toEqual({ audioUsed: true });
368
- const s1 = result[0].steps![1];
369
- expect(s1.label).toBe("subject_classification");
370
- expect(s1.level).toBe("warn");
371
- expect(s1.data).toBeUndefined();
372
- });
373
-
374
- it("includes step payload when present", async () => {
375
- const call = createOutGoingCallDoc();
376
- await createCallDoc(call);
377
- const steps: ToolExecutionStep[] = [
378
- {
379
- timestamp: new Date("2024-01-01T10:00:00Z"),
380
- label: "subject_classification",
381
- level: "info",
382
- data: "Classified as: ניקיון / אשפה",
383
- payload: { subject: "ניקיון", subSubject: "אשפה", ids: { subject: "abc", subSubject: "def" } },
384
- },
385
- ];
386
- await pushToolExecution(call.callSid, makeExecution({ steps }));
387
-
388
- const result = await getToolExecutionsByCallSid(call.callSid);
389
-
390
- const s0 = result[0].steps![0];
391
- expect(s0.data).toBe("Classified as: ניקיון / אשפה");
392
- expect(s0.payload).toEqual({ subject: "ניקיון", subSubject: "אשפה", ids: { subject: "abc", subSubject: "def" } });
393
- });
394
-
395
- it("does not require step payload to be present", async () => {
396
- const call = createOutGoingCallDoc();
397
- await createCallDoc(call);
398
- const steps: ToolExecutionStep[] = [
399
- { timestamp: new Date(), label: "user_query", level: "info", data: "Query: הרצל" },
400
- ];
401
- await pushToolExecution(call.callSid, makeExecution({ steps }));
402
-
403
- const result = await getToolExecutionsByCallSid(call.callSid);
404
-
405
- expect(result[0].steps![0].payload).toBeUndefined();
406
- });
407
-
408
- it("does not require steps to be present", async () => {
409
- const call = createOutGoingCallDoc();
410
- await createCallDoc(call);
411
- await pushToolExecution(call.callSid, makeExecution());
412
-
413
- const result = await getToolExecutionsByCallSid(call.callSid);
414
-
415
- expect(result[0].steps).toBeUndefined();
416
- });
417
-
418
- it("returns at most 50 executions by default", async () => {
419
- const call = createOutGoingCallDoc();
420
- await getCallsCollection().insertOne({
421
- ...call,
422
- createdAt: new Date(),
423
- updatedAt: new Date(),
424
- env: "test",
425
- toolExecutions: Array.from({ length: 51 }, (_, i) =>
426
- makeExecution({ toolName: `tool${i}` }),
427
- ),
428
- });
429
-
430
- const result = await getToolExecutionsByCallSid(call.callSid);
431
-
432
- expect(result).toHaveLength(50);
433
- expect(result[0].toolName).toBe("tool0");
434
- expect(result[49].toolName).toBe("tool49");
435
- });
436
-
437
- it("clamps negative skip to 0", async () => {
438
- const call = createOutGoingCallDoc();
439
- await createCallDoc(call);
440
- await pushToolExecution(call.callSid, makeExecution({ toolName: "only" }));
441
-
442
- const result = await getToolExecutionsByCallSid(call.callSid, { skip: -5 });
443
-
444
- expect(result).toHaveLength(1);
445
- expect(result[0].toolName).toBe("only");
446
- });
447
-
448
- it("clamps negative limit to 1", async () => {
449
- const call = createOutGoingCallDoc();
450
- await createCallDoc(call);
451
- await pushToolExecution(call.callSid, makeExecution({ toolName: "first" }));
452
- await pushToolExecution(call.callSid, makeExecution({ toolName: "second" }));
453
-
454
- const result = await getToolExecutionsByCallSid(call.callSid, { limit: -1 });
455
-
456
- expect(result).toHaveLength(1);
457
- });
458
-
459
- it("returns executions when clientId matches the call's client", async () => {
460
- const call = createOutGoingCallDoc({ clientId: "clientA" });
461
- await createCallDoc(call);
462
- await pushToolExecution(call.callSid, makeExecution({ toolName: "secret" }));
463
-
464
- const result = await getToolExecutionsByCallSid(call.callSid, { clientId: "clientA" });
465
-
466
- expect(result).toHaveLength(1);
467
- expect(result[0].toolName).toBe("secret");
468
- });
469
-
470
- it("returns empty when clientId does not match the call's client", async () => {
471
- const call = createOutGoingCallDoc({ clientId: "clientA" });
472
- await createCallDoc(call);
473
- await pushToolExecution(call.callSid, makeExecution({ toolName: "secret" }));
474
-
475
- const result = await getToolExecutionsByCallSid(call.callSid, { clientId: "clientB" });
476
-
477
- expect(result).toEqual([]);
478
- });
479
- });
480
-
481
- describe("getCallsByClientAndDateRange()", () => {
482
- it("should return calls within date range", async () => {
483
- const clientId = "dateRangeClient";
484
- const startDate = new Date("2023-05-01");
485
- const endDate = new Date("2023-05-31");
486
-
487
- const callInside = createOutGoingCallDoc({ clientId });
488
- const callBefore = createOutGoingCallDoc({ clientId });
489
- const callAfter = createOutGoingCallDoc({ clientId });
490
-
491
- await getCallsCollection().insertOne({
492
- ...callInside,
493
- createdAt: new Date("2023-05-15"),
494
- updatedAt: new Date(),
495
- env: "test",
496
- });
497
- await getCallsCollection().insertOne({
498
- ...callBefore,
499
- createdAt: new Date("2023-04-30"),
500
- updatedAt: new Date(),
501
- env: "test",
502
- });
503
- await getCallsCollection().insertOne({
504
- ...callAfter,
505
- createdAt: new Date("2023-06-01"),
506
- updatedAt: new Date(),
507
- env: "test",
508
- });
509
-
510
- const result = await getCallsByClientAndDateRange(
511
- clientId,
512
- startDate,
513
- endDate,
514
- );
515
- expect(result.length).toBe(1);
516
- expect(result[0].callSid).toBe(callInside.callSid);
517
- });
518
- });
519
- });
1
+ import {
2
+ createCallDoc,
3
+ getCallsByFlow,
4
+ getCallsByClient,
5
+ getCallsByPhoneNumber,
6
+ getCallByCallSid,
7
+ findCallsByQuery,
8
+ countCalls,
9
+ getCallsByClientAndDateRange,
10
+ getCallsCollection,
11
+ pushToolExecution,
12
+ getToolExecutionsByCallSid,
13
+ updateCallStatusByCallSid,
14
+ setCallEndedBy,
15
+ } from "../calls.getters";
16
+ import type { ToolExecution, ToolExecutionStep } from "../calls.types";
17
+ import { ObjectId } from "mongodb";
18
+ import { createOutGoingCallDoc } from "../../../test-utils/factories";
19
+
20
+ describe("db.calls", () => {
21
+ it("should return calls by flow", async () => {
22
+ const flowId = new ObjectId();
23
+ const call1 = createOutGoingCallDoc({ flowId });
24
+ const call2 = createOutGoingCallDoc({ flowId });
25
+
26
+ await createCallDoc(call1);
27
+ await createCallDoc(call2);
28
+
29
+ const result = await getCallsByFlow(flowId);
30
+
31
+ expect(result.length).toBe(2);
32
+ expect(result).toMatchObject([
33
+ { callSid: call1.callSid },
34
+ { callSid: call2.callSid },
35
+ ]);
36
+ });
37
+
38
+ it("should get call by callSid", async () => {
39
+ const call = createOutGoingCallDoc();
40
+ await createCallDoc(call);
41
+
42
+ const result = await getCallByCallSid(call.callSid);
43
+
44
+ expect(result).toBeDefined();
45
+ expect(result?.callSid).toBe(call.callSid);
46
+ });
47
+
48
+ it("should get calls by client", async () => {
49
+ const call = createOutGoingCallDoc();
50
+ await createCallDoc(call);
51
+
52
+ const result = await getCallsByClient(call.clientId);
53
+
54
+ expect(result.some((c) => c.callSid === call.callSid)).toBe(true);
55
+ });
56
+
57
+ it("should get calls by phone number", async () => {
58
+ const call = createOutGoingCallDoc();
59
+ await createCallDoc(call);
60
+
61
+ const result = await getCallsByPhoneNumber(call.customerPhoneNumber);
62
+
63
+ expect(result.some((c) => c.callSid === call.callSid)).toBe(true);
64
+ });
65
+
66
+ it("should set current status only via updateCallStatusByCallSid", async () => {
67
+ const call = createOutGoingCallDoc({ status: "ringing" });
68
+ await createCallDoc(call);
69
+
70
+ const updated = await updateCallStatusByCallSid(call.callSid, "in-progress");
71
+
72
+ expect(updated?.status).toBe("in-progress");
73
+ expect(await getCallByCallSid(call.callSid)).toMatchObject({
74
+ status: "in-progress",
75
+ });
76
+ });
77
+
78
+ describe("setCallEndedBy()", () => {
79
+ it("should set endedBy when it is not set yet", async () => {
80
+ const call = createOutGoingCallDoc();
81
+ await createCallDoc(call);
82
+
83
+ const written = await setCallEndedBy(call.callSid, "user");
84
+
85
+ expect(written).toBe(true);
86
+ expect(await getCallByCallSid(call.callSid)).toMatchObject({
87
+ endedBy: "user",
88
+ });
89
+ });
90
+
91
+ it("should keep the first value when called again", async () => {
92
+ const call = createOutGoingCallDoc();
93
+ await createCallDoc(call);
94
+
95
+ await setCallEndedBy(call.callSid, "user");
96
+ const written = await setCallEndedBy(call.callSid, "agent");
97
+
98
+ expect(written).toBe(false);
99
+ expect(await getCallByCallSid(call.callSid)).toMatchObject({
100
+ endedBy: "user",
101
+ });
102
+ });
103
+
104
+ it("should let only one of two concurrent writers win", async () => {
105
+ const call = createOutGoingCallDoc();
106
+ await createCallDoc(call);
107
+
108
+ const results = await Promise.all([
109
+ setCallEndedBy(call.callSid, "user"),
110
+ setCallEndedBy(call.callSid, "system"),
111
+ ]);
112
+
113
+ expect(results.filter(Boolean)).toHaveLength(1);
114
+ const stored = await getCallByCallSid(call.callSid);
115
+ expect(stored?.endedBy).toBe(results[0] ? "user" : "system");
116
+ });
117
+
118
+ it("should return false when the call does not exist", async () => {
119
+ await expect(setCallEndedBy("nonexistent-sid", "system")).resolves.toBe(
120
+ false,
121
+ );
122
+ });
123
+ });
124
+
125
+ describe("findCallsByQuery()", () => {
126
+ it("should find calls by status with limit and sort", async () => {
127
+ const clientId = "client123";
128
+ const call1 = createOutGoingCallDoc({ clientId, status: "completed" });
129
+ const call2 = createOutGoingCallDoc({ clientId, status: "completed" });
130
+ const call3 = createOutGoingCallDoc({ clientId, status: "busy" });
131
+
132
+ // We need to control createdAt to test sort. We'll insert directly.
133
+ await getCallsCollection().insertOne({
134
+ ...call1,
135
+ createdAt: new Date("2023-01-01"),
136
+ updatedAt: new Date(),
137
+ env: "test",
138
+ });
139
+ await getCallsCollection().insertOne({
140
+ ...call2,
141
+ createdAt: new Date("2023-01-02"),
142
+ updatedAt: new Date(),
143
+ env: "test",
144
+ });
145
+ await getCallsCollection().insertOne({
146
+ ...call3,
147
+ createdAt: new Date(),
148
+ updatedAt: new Date(),
149
+ env: "test",
150
+ });
151
+
152
+ const result = await findCallsByQuery(
153
+ { clientId, status: "completed" },
154
+ { sort: { createdAt: -1 }, limit: 1 },
155
+ );
156
+
157
+ expect(result.length).toBe(1);
158
+ expect(result[0].callSid).toBe(call2.callSid);
159
+ });
160
+ });
161
+
162
+ describe("countCalls()", () => {
163
+ it("should count calls matching query", async () => {
164
+ const clientId = "countClient";
165
+ await createCallDoc(
166
+ createOutGoingCallDoc({ clientId, status: "completed" }),
167
+ );
168
+ await createCallDoc(
169
+ createOutGoingCallDoc({ clientId, status: "completed" }),
170
+ );
171
+ await createCallDoc(
172
+ createOutGoingCallDoc({ clientId, status: "failed" }),
173
+ );
174
+
175
+ const count = await countCalls({ clientId, status: "completed" });
176
+ expect(count).toBe(2);
177
+ });
178
+ });
179
+
180
+ describe("pushToolExecution()", () => {
181
+ let callSid: string;
182
+
183
+ beforeEach(async () => {
184
+ const call = createOutGoingCallDoc();
185
+ await createCallDoc(call);
186
+ callSid = call.callSid;
187
+ });
188
+
189
+ const makeHttpExecution = (
190
+ overrides?: Partial<ToolExecution>,
191
+ ): ToolExecution => ({
192
+ toolName: "sendSms",
193
+ executedAt: new Date(),
194
+ durationMs: 120,
195
+ args: { to: "+1234567890", message: "hello" },
196
+ meta: {
197
+ kind: "http",
198
+ url: "https://api.example.com/sms",
199
+ method: "POST",
200
+ },
201
+ status: "success",
202
+ httpStatus: 200,
203
+ ...overrides,
204
+ });
205
+
206
+ it("should append an execution to a call with none", async () => {
207
+ const execution = makeHttpExecution();
208
+ await pushToolExecution(callSid, execution);
209
+
210
+ const result = await getCallByCallSid(callSid);
211
+ expect(result?.toolExecutions).toHaveLength(1);
212
+ expect(result?.toolExecutions?.[0]).toMatchObject({
213
+ toolName: "sendSms",
214
+ status: "success",
215
+ httpStatus: 200,
216
+ });
217
+ });
218
+
219
+ it("should maintain insertion order across multiple pushes", async () => {
220
+ const first = makeHttpExecution({ toolName: "first" });
221
+ const second = makeHttpExecution({ toolName: "second" });
222
+ const third = makeHttpExecution({ toolName: "third" });
223
+
224
+ await pushToolExecution(callSid, first);
225
+ await pushToolExecution(callSid, second);
226
+ await pushToolExecution(callSid, third);
227
+
228
+ const result = await getCallByCallSid(callSid);
229
+ expect(result?.toolExecutions?.map((e) => e.toolName)).toEqual([
230
+ "first",
231
+ "second",
232
+ "third",
233
+ ]);
234
+ });
235
+
236
+ it("should store an internal tool execution", async () => {
237
+ const execution: ToolExecution = {
238
+ toolName: "endFlow",
239
+ executedAt: new Date(),
240
+ durationMs: 5,
241
+ args: {},
242
+ meta: { kind: "internal" },
243
+ status: "success",
244
+ };
245
+
246
+ await pushToolExecution(callSid, execution);
247
+
248
+ const result = await getCallByCallSid(callSid);
249
+ expect(result?.toolExecutions?.[0]).toMatchObject({
250
+ toolName: "endFlow",
251
+ meta: { kind: "internal" },
252
+ });
253
+ });
254
+
255
+ it("should store redacted args for sensitive tools", async () => {
256
+ const execution = makeHttpExecution({ args: { _redacted: true } });
257
+ await pushToolExecution(callSid, execution);
258
+
259
+ const result = await getCallByCallSid(callSid);
260
+ expect(result?.toolExecutions?.[0].args).toEqual({ _redacted: true });
261
+ });
262
+
263
+ it("should store an error execution", async () => {
264
+ const execution = makeHttpExecution({ status: "error", httpStatus: 500 });
265
+ await pushToolExecution(callSid, execution);
266
+
267
+ const result = await getCallByCallSid(callSid);
268
+ expect(result?.toolExecutions?.[0]).toMatchObject({
269
+ status: "error",
270
+ httpStatus: 500,
271
+ });
272
+ });
273
+
274
+ it("should be a no-op for an unknown callSid", async () => {
275
+ await expect(
276
+ pushToolExecution("nonexistent-sid", makeHttpExecution()),
277
+ ).resolves.not.toThrow();
278
+ });
279
+
280
+ it("should store the response body", async () => {
281
+ const execution = makeHttpExecution({
282
+ response: { userId: "123", status: "sent" },
283
+ });
284
+ await pushToolExecution(callSid, execution);
285
+
286
+ const result = await getCallByCallSid(callSid);
287
+ expect(result?.toolExecutions?.[0].response).toEqual({
288
+ userId: "123",
289
+ status: "sent",
290
+ });
291
+ });
292
+ });
293
+
294
+ describe("getToolExecutionsByCallSid()", () => {
295
+ const makeExecution = (
296
+ overrides?: Partial<ToolExecution>,
297
+ ): ToolExecution => ({
298
+ toolName: "testTool",
299
+ executedAt: new Date(),
300
+ durationMs: 100,
301
+ args: { query: "test" },
302
+ meta: { kind: "http", url: "https://example.com", method: "POST" },
303
+ status: "success",
304
+ httpStatus: 200,
305
+ ...overrides,
306
+ });
307
+
308
+ it("returns all executions for a call", async () => {
309
+ const call = createOutGoingCallDoc();
310
+ await createCallDoc(call);
311
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "first" }));
312
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "second" }));
313
+
314
+ const result = await getToolExecutionsByCallSid(call.callSid);
315
+
316
+ expect(result).toHaveLength(2);
317
+ expect(result.map((e) => e.toolName)).toEqual(["first", "second"]);
318
+ });
319
+
320
+ it("returns an empty array when the call has no executions", async () => {
321
+ const call = createOutGoingCallDoc();
322
+ await createCallDoc(call);
323
+
324
+ const result = await getToolExecutionsByCallSid(call.callSid);
325
+
326
+ expect(result).toEqual([]);
327
+ });
328
+
329
+ it("returns an empty array for an unknown callSid", async () => {
330
+ const result = await getToolExecutionsByCallSid("nonexistent-sid");
331
+
332
+ expect(result).toEqual([]);
333
+ });
334
+
335
+ it("respects skip and limit for pagination", async () => {
336
+ const call = createOutGoingCallDoc();
337
+ await createCallDoc(call);
338
+ for (const name of ["a", "b", "c", "d", "e"]) {
339
+ await pushToolExecution(call.callSid, makeExecution({ toolName: name }));
340
+ }
341
+
342
+ const page1 = await getToolExecutionsByCallSid(call.callSid, { skip: 0, limit: 2 });
343
+ const page2 = await getToolExecutionsByCallSid(call.callSid, { skip: 2, limit: 2 });
344
+ const page3 = await getToolExecutionsByCallSid(call.callSid, { skip: 4, limit: 2 });
345
+
346
+ expect(page1.map((e) => e.toolName)).toEqual(["a", "b"]);
347
+ expect(page2.map((e) => e.toolName)).toEqual(["c", "d"]);
348
+ expect(page3.map((e) => e.toolName)).toEqual(["e"]);
349
+ });
350
+
351
+ it("includes steps when present", async () => {
352
+ const call = createOutGoingCallDoc();
353
+ await createCallDoc(call);
354
+ const steps: ToolExecutionStep[] = [
355
+ { timestamp: new Date("2024-01-01T10:00:00Z"), label: "audio_enrichment", level: "info", data: { audioUsed: true } },
356
+ { timestamp: new Date("2024-01-01T10:00:01Z"), label: "subject_classification", level: "warn" },
357
+ ];
358
+ await pushToolExecution(call.callSid, makeExecution({ steps }));
359
+
360
+ const result = await getToolExecutionsByCallSid(call.callSid);
361
+
362
+ expect(result[0].steps).toHaveLength(2);
363
+ const s0 = result[0].steps![0];
364
+ expect(s0.label).toBe("audio_enrichment");
365
+ expect(s0.level).toBe("info");
366
+ expect(new Date(s0.timestamp).toISOString()).toBe("2024-01-01T10:00:00.000Z");
367
+ expect(s0.data).toEqual({ audioUsed: true });
368
+ const s1 = result[0].steps![1];
369
+ expect(s1.label).toBe("subject_classification");
370
+ expect(s1.level).toBe("warn");
371
+ expect(s1.data).toBeUndefined();
372
+ });
373
+
374
+ it("includes step payload when present", async () => {
375
+ const call = createOutGoingCallDoc();
376
+ await createCallDoc(call);
377
+ const steps: ToolExecutionStep[] = [
378
+ {
379
+ timestamp: new Date("2024-01-01T10:00:00Z"),
380
+ label: "subject_classification",
381
+ level: "info",
382
+ data: "Classified as: ניקיון / אשפה",
383
+ payload: { subject: "ניקיון", subSubject: "אשפה", ids: { subject: "abc", subSubject: "def" } },
384
+ },
385
+ ];
386
+ await pushToolExecution(call.callSid, makeExecution({ steps }));
387
+
388
+ const result = await getToolExecutionsByCallSid(call.callSid);
389
+
390
+ const s0 = result[0].steps![0];
391
+ expect(s0.data).toBe("Classified as: ניקיון / אשפה");
392
+ expect(s0.payload).toEqual({ subject: "ניקיון", subSubject: "אשפה", ids: { subject: "abc", subSubject: "def" } });
393
+ });
394
+
395
+ it("does not require step payload to be present", async () => {
396
+ const call = createOutGoingCallDoc();
397
+ await createCallDoc(call);
398
+ const steps: ToolExecutionStep[] = [
399
+ { timestamp: new Date(), label: "user_query", level: "info", data: "Query: הרצל" },
400
+ ];
401
+ await pushToolExecution(call.callSid, makeExecution({ steps }));
402
+
403
+ const result = await getToolExecutionsByCallSid(call.callSid);
404
+
405
+ expect(result[0].steps![0].payload).toBeUndefined();
406
+ });
407
+
408
+ it("does not require steps to be present", async () => {
409
+ const call = createOutGoingCallDoc();
410
+ await createCallDoc(call);
411
+ await pushToolExecution(call.callSid, makeExecution());
412
+
413
+ const result = await getToolExecutionsByCallSid(call.callSid);
414
+
415
+ expect(result[0].steps).toBeUndefined();
416
+ });
417
+
418
+ it("returns at most 50 executions by default", async () => {
419
+ const call = createOutGoingCallDoc();
420
+ await getCallsCollection().insertOne({
421
+ ...call,
422
+ createdAt: new Date(),
423
+ updatedAt: new Date(),
424
+ env: "test",
425
+ toolExecutions: Array.from({ length: 51 }, (_, i) =>
426
+ makeExecution({ toolName: `tool${i}` }),
427
+ ),
428
+ });
429
+
430
+ const result = await getToolExecutionsByCallSid(call.callSid);
431
+
432
+ expect(result).toHaveLength(50);
433
+ expect(result[0].toolName).toBe("tool0");
434
+ expect(result[49].toolName).toBe("tool49");
435
+ });
436
+
437
+ it("clamps negative skip to 0", async () => {
438
+ const call = createOutGoingCallDoc();
439
+ await createCallDoc(call);
440
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "only" }));
441
+
442
+ const result = await getToolExecutionsByCallSid(call.callSid, { skip: -5 });
443
+
444
+ expect(result).toHaveLength(1);
445
+ expect(result[0].toolName).toBe("only");
446
+ });
447
+
448
+ it("clamps negative limit to 1", async () => {
449
+ const call = createOutGoingCallDoc();
450
+ await createCallDoc(call);
451
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "first" }));
452
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "second" }));
453
+
454
+ const result = await getToolExecutionsByCallSid(call.callSid, { limit: -1 });
455
+
456
+ expect(result).toHaveLength(1);
457
+ });
458
+
459
+ it("returns executions when clientId matches the call's client", async () => {
460
+ const call = createOutGoingCallDoc({ clientId: "clientA" });
461
+ await createCallDoc(call);
462
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "secret" }));
463
+
464
+ const result = await getToolExecutionsByCallSid(call.callSid, { clientId: "clientA" });
465
+
466
+ expect(result).toHaveLength(1);
467
+ expect(result[0].toolName).toBe("secret");
468
+ });
469
+
470
+ it("returns empty when clientId does not match the call's client", async () => {
471
+ const call = createOutGoingCallDoc({ clientId: "clientA" });
472
+ await createCallDoc(call);
473
+ await pushToolExecution(call.callSid, makeExecution({ toolName: "secret" }));
474
+
475
+ const result = await getToolExecutionsByCallSid(call.callSid, { clientId: "clientB" });
476
+
477
+ expect(result).toEqual([]);
478
+ });
479
+ });
480
+
481
+ describe("getCallsByClientAndDateRange()", () => {
482
+ it("should return calls within date range", async () => {
483
+ const clientId = "dateRangeClient";
484
+ const startDate = new Date("2023-05-01");
485
+ const endDate = new Date("2023-05-31");
486
+
487
+ const callInside = createOutGoingCallDoc({ clientId });
488
+ const callBefore = createOutGoingCallDoc({ clientId });
489
+ const callAfter = createOutGoingCallDoc({ clientId });
490
+
491
+ await getCallsCollection().insertOne({
492
+ ...callInside,
493
+ createdAt: new Date("2023-05-15"),
494
+ updatedAt: new Date(),
495
+ env: "test",
496
+ });
497
+ await getCallsCollection().insertOne({
498
+ ...callBefore,
499
+ createdAt: new Date("2023-04-30"),
500
+ updatedAt: new Date(),
501
+ env: "test",
502
+ });
503
+ await getCallsCollection().insertOne({
504
+ ...callAfter,
505
+ createdAt: new Date("2023-06-01"),
506
+ updatedAt: new Date(),
507
+ env: "test",
508
+ });
509
+
510
+ const result = await getCallsByClientAndDateRange(
511
+ clientId,
512
+ startDate,
513
+ endDate,
514
+ );
515
+ expect(result.length).toBe(1);
516
+ expect(result[0].callSid).toBe(callInside.callSid);
517
+ });
518
+ });
519
+ });
@@ -47,3 +47,10 @@ export const CallStatusValues = {
47
47
  } as const;
48
48
 
49
49
  export const ALL_CALL_STATUSES = Object.values(CallStatusValues);
50
+
51
+ /** Who ended a connected call: our platform, the bot (end flow), or the caller. */
52
+ export const CallEndedByValues = {
53
+ System: "system",
54
+ Agent: "agent",
55
+ User: "user",
56
+ } as const;
@@ -3,6 +3,7 @@ import { TranscriptionSegment } from "../results";
3
3
  import { LeadProperty } from "../leads";
4
4
 
5
5
  import {
6
+ CallEndedByValues,
6
7
  CallStatusValues,
7
8
  CONFERENCE_ROLE_CUSTOMER,
8
9
  CONFERENCE_ROLE_SUPERVISOR,
@@ -15,7 +16,7 @@ export type ConferenceRole =
15
16
 
16
17
  export type CallStatus = (typeof CallStatusValues)[keyof typeof CallStatusValues];
17
18
 
18
- export type CallEndedBy = "system" | "resident";
19
+ export type CallEndedBy = (typeof CallEndedByValues)[keyof typeof CallEndedByValues];
19
20
 
20
21
  export type Call = {
21
22
  callSid: string;