@talkpilot/core-db 1.3.62 → 1.3.64

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
@@ -181,6 +181,7 @@ Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and fact
181
181
  | 1.3.57 | Phone-number bind getters: list by client, exclusive flow assign, unbind, and `flow_id` match for ObjectId or leftover string. `getClientByClientId`. |
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
+ | 1.3.64 | New `callTokenUsage` collection with `incrementCallTokenUsage` (CP-1810): per-call realtime token usage, one document per `callSid`. |
184
185
 
185
186
  ### 1.1.9
186
187
 
@@ -0,0 +1,4 @@
1
+ import { CallTokenUsage, CallTokenUsageDoc } from "./callTokenUsage.types";
2
+ export declare const getCallTokenUsageCollection: () => import("mongodb").Collection<CallTokenUsageDoc>;
3
+ export declare const incrementCallTokenUsage: (callSid: string, { provider, model, ...counters }: CallTokenUsage) => Promise<void>;
4
+ //# sourceMappingURL=callTokenUsage.getters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callTokenUsage.getters.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/callTokenUsage.getters.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE3E,eAAO,MAAM,2BAA2B,uDAEvC,CAAC;AAkBF,eAAO,MAAM,uBAAuB,GAClC,SAAS,MAAM,EACf,kCAAkC,cAAc,KAC/C,OAAO,CAAC,IAAI,CAcd,CAAC"}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.incrementCallTokenUsage = exports.getCallTokenUsageCollection = void 0;
4
+ const index_1 = require("../index");
5
+ const getCallTokenUsageCollection = () => {
6
+ return (0, index_1.getDb)().collection("callTokenUsage");
7
+ };
8
+ exports.getCallTokenUsageCollection = getCallTokenUsageCollection;
9
+ // Unique callSid, so concurrent first reports of a call upsert one document, not several.
10
+ const callSidIndexByDb = new WeakMap();
11
+ const ensureCallSidIndex = () => {
12
+ const db = (0, index_1.getDb)();
13
+ let index = callSidIndexByDb.get(db);
14
+ if (!index) {
15
+ index = (0, exports.getCallTokenUsageCollection)().createIndex({ callSid: 1 }, { unique: true });
16
+ callSidIndexByDb.set(db, index);
17
+ }
18
+ return index;
19
+ };
20
+ const incrementCallTokenUsage = async (callSid, { provider, model, ...counters }) => {
21
+ await ensureCallSidIndex();
22
+ const now = new Date();
23
+ await (0, exports.getCallTokenUsageCollection)().updateOne({ callSid }, {
24
+ $inc: Object.fromEntries(Object.entries(counters).filter(([, value]) => (value ?? 0) > 0)),
25
+ $set: { provider, ...(model && { model }), updatedAt: now },
26
+ $setOnInsert: { createdAt: now },
27
+ }, { upsert: true });
28
+ };
29
+ exports.incrementCallTokenUsage = incrementCallTokenUsage;
30
+ //# sourceMappingURL=callTokenUsage.getters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callTokenUsage.getters.js","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/callTokenUsage.getters.ts"],"names":[],"mappings":";;;AACA,oCAAiC;AAG1B,MAAM,2BAA2B,GAAG,GAAG,EAAE;IAC9C,OAAO,IAAA,aAAK,GAAE,CAAC,UAAU,CAAoB,gBAAgB,CAAC,CAAC;AACjE,CAAC,CAAC;AAFW,QAAA,2BAA2B,+BAEtC;AAEF,0FAA0F;AAC1F,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAuB,CAAC;AAE5D,MAAM,kBAAkB,GAAG,GAAoB,EAAE;IAC/C,MAAM,EAAE,GAAG,IAAA,aAAK,GAAE,CAAC;IACnB,IAAI,KAAK,GAAG,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACrC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG,IAAA,mCAA2B,GAAE,CAAC,WAAW,CAC/C,EAAE,OAAO,EAAE,CAAC,EAAE,EACd,EAAE,MAAM,EAAE,IAAI,EAAE,CACjB,CAAC;QACF,gBAAgB,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEK,MAAM,uBAAuB,GAAG,KAAK,EAC1C,OAAe,EACf,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAkB,EACjC,EAAE;IACjB,MAAM,kBAAkB,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,IAAA,mCAA2B,GAAE,CAAC,SAAS,CAC3C,EAAE,OAAO,EAAE,EACX;QACE,IAAI,EAAE,MAAM,CAAC,WAAW,CACtB,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CACjE;QACD,IAAI,EAAE,EAAE,QAAQ,EAAE,GAAG,CAAC,KAAK,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;QAC3D,YAAY,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE;KACE,EACpC,EAAE,MAAM,EAAE,IAAI,EAAE,CACjB,CAAC;AACJ,CAAC,CAAC;AAjBW,QAAA,uBAAuB,2BAiBlC"}
@@ -0,0 +1,28 @@
1
+ export type CallTokenUsage = {
2
+ provider: string;
3
+ model?: string;
4
+ responsesCount?: number;
5
+ inputTokens?: number;
6
+ outputTokens?: number;
7
+ totalTokens?: number;
8
+ inputTextTokens?: number;
9
+ inputAudioTokens?: number;
10
+ inputImageTokens?: number;
11
+ cachedInputTokens?: number;
12
+ cachedInputTextTokens?: number;
13
+ cachedInputAudioTokens?: number;
14
+ cachedInputImageTokens?: number;
15
+ outputTextTokens?: number;
16
+ outputAudioTokens?: number;
17
+ thoughtsTokens?: number;
18
+ toolUseTokens?: number;
19
+ billableAudioSeconds?: number;
20
+ sessionSeconds?: number;
21
+ textInputsCount?: number;
22
+ };
23
+ export type CallTokenUsageDoc = CallTokenUsage & {
24
+ callSid: string;
25
+ createdAt: Date;
26
+ updatedAt: Date;
27
+ };
28
+ //# sourceMappingURL=callTokenUsage.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callTokenUsage.types.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/callTokenUsage.types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,cAAc,GAAG;IAC/C,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,EAAE,IAAI,CAAC;CACjB,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=callTokenUsage.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callTokenUsage.types.js","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/callTokenUsage.types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ export * from "./callTokenUsage.getters";
2
+ export type * from "./callTokenUsage.types";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/index.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,mBAAmB,wBAAwB,CAAC"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./callTokenUsage.getters"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/talkpilot/callTokenUsage/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2DAAyC"}
@@ -12,6 +12,7 @@ export * from "./plans";
12
12
  export * from "./subscriptions";
13
13
  export * from "./groups";
14
14
  export * from "./calls";
15
+ export * from "./callTokenUsage";
15
16
  export * from "./clientAudioBuffers";
16
17
  export * from "./clientsConfig";
17
18
  export * from "./backgroundToolResults";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/talkpilot/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AAExD,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AACxC,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGjD,eAAO,MAAM,KAAK,GAAI,GAAG,EAAE,SAE1B,CAAC;AACF,eAAO,MAAM,KAAK,QAAO,EAGxB,CAAC;AAEF,eAAO,MAAM,QAAQ,sBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/talkpilot/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AAExD,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AACxC,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGjD,eAAO,MAAM,KAAK,GAAI,GAAG,EAAE,SAE1B,CAAC;AACF,eAAO,MAAM,KAAK,QAAO,EAGxB,CAAC;AAEF,eAAO,MAAM,QAAQ,sBAAgB,CAAC"}
@@ -29,6 +29,7 @@ __exportStar(require("./plans"), exports);
29
29
  __exportStar(require("./subscriptions"), exports);
30
30
  __exportStar(require("./groups"), exports);
31
31
  __exportStar(require("./calls"), exports);
32
+ __exportStar(require("./callTokenUsage"), exports);
32
33
  __exportStar(require("./clientAudioBuffers"), exports);
33
34
  __exportStar(require("./clientsConfig"), exports);
34
35
  __exportStar(require("./backgroundToolResults"), exports);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/talkpilot/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qCAAwD;AAExD,0CAAwB;AACxB,iDAA+B;AAC/B,6CAA2B;AAC3B,4CAA0B;AAC1B,6CAA2B;AAC3B,kDAAgC;AAChC,0CAAwB;AACxB,4CAA0B;AAC1B,2CAAyB;AACzB,0CAAwB;AACxB,kDAAgC;AAChC,2CAAyB;AACzB,0CAAwB;AACxB,uDAAqC;AACrC,kDAAgC;AAChC,0DAAwC;AACxC,kDAAgC;AAChC,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AAEtB,IAAI,EAAM,CAAC;AACJ,MAAM,KAAK,GAAG,CAAC,CAAK,EAAE,EAAE;IAC7B,EAAE,GAAG,CAAC,CAAC;AACT,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB;AACK,MAAM,KAAK,GAAG,GAAO,EAAE;IAC5B,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;IAC/C,OAAO,EAAE,CAAC;AACZ,CAAC,CAAC;AAHW,QAAA,KAAK,SAGhB;AAEW,QAAA,QAAQ,GAAG,kBAAa,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/talkpilot/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qCAAwD;AAExD,0CAAwB;AACxB,iDAA+B;AAC/B,6CAA2B;AAC3B,4CAA0B;AAC1B,6CAA2B;AAC3B,kDAAgC;AAChC,0CAAwB;AACxB,4CAA0B;AAC1B,2CAAyB;AACzB,0CAAwB;AACxB,kDAAgC;AAChC,2CAAyB;AACzB,0CAAwB;AACxB,mDAAiC;AACjC,uDAAqC;AACrC,kDAAgC;AAChC,0DAAwC;AACxC,kDAAgC;AAChC,mDAAiD;AAAxC,+GAAA,aAAa,OAAA;AAEtB,IAAI,EAAM,CAAC;AACJ,MAAM,KAAK,GAAG,CAAC,CAAK,EAAE,EAAE;IAC7B,EAAE,GAAG,CAAC,CAAC;AACT,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB;AACK,MAAM,KAAK,GAAG,GAAO,EAAE;IAC5B,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;IAC/C,OAAO,EAAE,CAAC;AACZ,CAAC,CAAC;AAHW,QAAA,KAAK,SAGhB;AAEW,QAAA,QAAQ,GAAG,kBAAa,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talkpilot/core-db",
3
- "version": "1.3.62",
3
+ "version": "1.3.64",
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",
@@ -0,0 +1,57 @@
1
+ import {
2
+ getCallTokenUsageCollection,
3
+ incrementCallTokenUsage,
4
+ } from "../callTokenUsage.getters";
5
+
6
+ describe("callTokenUsage getters", () => {
7
+ it("should add each report to the call totals and keep provider and model", async () => {
8
+ await incrementCallTokenUsage("CA-usage-1", {
9
+ provider: "openai",
10
+ model: "gpt-realtime",
11
+ inputTokens: 10,
12
+ });
13
+ await incrementCallTokenUsage("CA-usage-1", {
14
+ provider: "openai",
15
+ inputTokens: 5,
16
+ });
17
+
18
+ const usage = await getCallTokenUsageCollection().findOne({
19
+ callSid: "CA-usage-1",
20
+ });
21
+ expect(usage).toMatchObject({
22
+ provider: "openai",
23
+ model: "gpt-realtime",
24
+ inputTokens: 15,
25
+ });
26
+ });
27
+
28
+ it("should create a single document when first reports arrive together", async () => {
29
+ await Promise.all(
30
+ Array.from({ length: 10 }, () =>
31
+ incrementCallTokenUsage("CA-usage-2", {
32
+ provider: "xai",
33
+ textInputsCount: 1,
34
+ }),
35
+ ),
36
+ );
37
+
38
+ const docs = await getCallTokenUsageCollection()
39
+ .find({ callSid: "CA-usage-2" })
40
+ .toArray();
41
+ expect(docs).toHaveLength(1);
42
+ expect(docs[0].textInputsCount).toBe(10);
43
+ });
44
+
45
+ it("should not write zero counters", async () => {
46
+ await incrementCallTokenUsage("CA-usage-3", {
47
+ provider: "gemini",
48
+ inputTokens: 3,
49
+ outputTokens: 0,
50
+ });
51
+
52
+ const usage = await getCallTokenUsageCollection().findOne({
53
+ callSid: "CA-usage-3",
54
+ });
55
+ expect(usage).not.toHaveProperty("outputTokens");
56
+ });
57
+ });
@@ -0,0 +1,42 @@
1
+ import { Db, UpdateFilter } from "mongodb";
2
+ import { getDb } from "../index";
3
+ import { CallTokenUsage, CallTokenUsageDoc } from "./callTokenUsage.types";
4
+
5
+ export const getCallTokenUsageCollection = () => {
6
+ return getDb().collection<CallTokenUsageDoc>("callTokenUsage");
7
+ };
8
+
9
+ // Unique callSid, so concurrent first reports of a call upsert one document, not several.
10
+ const callSidIndexByDb = new WeakMap<Db, Promise<string>>();
11
+
12
+ const ensureCallSidIndex = (): Promise<string> => {
13
+ const db = getDb();
14
+ let index = callSidIndexByDb.get(db);
15
+ if (!index) {
16
+ index = getCallTokenUsageCollection().createIndex(
17
+ { callSid: 1 },
18
+ { unique: true },
19
+ );
20
+ callSidIndexByDb.set(db, index);
21
+ }
22
+ return index;
23
+ };
24
+
25
+ export const incrementCallTokenUsage = async (
26
+ callSid: string,
27
+ { provider, model, ...counters }: CallTokenUsage,
28
+ ): Promise<void> => {
29
+ await ensureCallSidIndex();
30
+ const now = new Date();
31
+ await getCallTokenUsageCollection().updateOne(
32
+ { callSid },
33
+ {
34
+ $inc: Object.fromEntries(
35
+ Object.entries(counters).filter(([, value]) => (value ?? 0) > 0),
36
+ ),
37
+ $set: { provider, ...(model && { model }), updatedAt: now },
38
+ $setOnInsert: { createdAt: now },
39
+ } as UpdateFilter<CallTokenUsageDoc>,
40
+ { upsert: true },
41
+ );
42
+ };
@@ -0,0 +1,28 @@
1
+ export type CallTokenUsage = {
2
+ provider: string;
3
+ model?: string;
4
+ responsesCount?: number;
5
+ inputTokens?: number;
6
+ outputTokens?: number;
7
+ totalTokens?: number;
8
+ inputTextTokens?: number;
9
+ inputAudioTokens?: number;
10
+ inputImageTokens?: number;
11
+ cachedInputTokens?: number;
12
+ cachedInputTextTokens?: number;
13
+ cachedInputAudioTokens?: number;
14
+ cachedInputImageTokens?: number;
15
+ outputTextTokens?: number;
16
+ outputAudioTokens?: number;
17
+ thoughtsTokens?: number;
18
+ toolUseTokens?: number;
19
+ billableAudioSeconds?: number;
20
+ sessionSeconds?: number;
21
+ textInputsCount?: number;
22
+ };
23
+
24
+ export type CallTokenUsageDoc = CallTokenUsage & {
25
+ callSid: string;
26
+ createdAt: Date;
27
+ updatedAt: Date;
28
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./callTokenUsage.getters";
2
+ export type * from "./callTokenUsage.types";
@@ -13,6 +13,7 @@ export * from "./plans";
13
13
  export * from "./subscriptions";
14
14
  export * from "./groups";
15
15
  export * from "./calls";
16
+ export * from "./callTokenUsage";
16
17
  export * from "./clientAudioBuffers";
17
18
  export * from "./clientsConfig";
18
19
  export * from "./backgroundToolResults";
@@ -1,362 +1,362 @@
1
- import {
2
- getScansCollection,
3
- getScansByClientAndDateRange,
4
- getScanFieldsByClientAndDateRange,
5
- findScansByQuery,
6
- countScans,
7
- createScanDoc,
8
- updateScanDoc,
9
- findInProgressScansByClient,
10
- getScansByWebsiteUrl,
11
- getLatestScanByWebsiteUrl,
12
- getInProgressScanByWebsiteUrl,
13
- getLatestCompletedScanByWebsiteUrl,
14
- deleteScansByWebsiteUrl,
15
- deleteScanById,
16
- } from "../scans.getters";
17
- import { FINISHED_SCAN_STATUSES, SCAN_STATUSES } from "../scans.constants";
18
- import { createScanFixture } from "../../../test-utils/factories";
19
- import { ObjectId } from "mongodb";
20
-
21
- describe("db.websitalk.scans", () => {
22
- describe("getScansByClientAndDateRange()", () => {
23
- it("should return full scan documents within the date range", async () => {
24
- const clientId = "dateRangeClient";
25
- const startDate = new Date("2023-05-01");
26
- const endDate = new Date("2023-05-31");
27
-
28
- const scanInside = createScanFixture({ clientId, status: "COMPLETED" });
29
- const scanBefore = createScanFixture({ clientId });
30
- const scanAfter = createScanFixture({ clientId });
31
-
32
- await getScansCollection().insertMany([
33
- { ...scanInside, createdAt: new Date("2023-05-15") },
34
- { ...scanBefore, createdAt: new Date("2023-04-30") },
35
- { ...scanAfter, createdAt: new Date("2023-06-01") },
36
- ]);
37
-
38
- const result = await getScansByClientAndDateRange(
39
- clientId,
40
- startDate,
41
- endDate,
42
- );
43
-
44
- expect(result.length).toBe(1);
45
- expect(result[0]).toMatchObject({
46
- clientId,
47
- websiteUrlId: scanInside.websiteUrlId,
48
- status: "COMPLETED",
49
- });
50
- expect(result[0]).toHaveProperty("siteChrome");
51
- expect(result[0]).toHaveProperty("skipped");
52
- });
53
-
54
- it("should respect the date range boundaries (inclusive)", async () => {
55
- const clientId = "boundaryClient";
56
- const onStart = createScanFixture({ clientId });
57
- const onEnd = createScanFixture({ clientId });
58
-
59
- await getScansCollection().insertMany([
60
- { ...onStart, createdAt: new Date("2023-05-01") },
61
- { ...onEnd, createdAt: new Date("2023-05-31") },
62
- ]);
63
-
64
- const result = await getScansByClientAndDateRange(
65
- clientId,
66
- new Date("2023-05-01"),
67
- new Date("2023-05-31"),
68
- );
69
-
70
- expect(result.length).toBe(2);
71
- });
72
- });
73
-
74
- describe("getScanFieldsByClientAndDateRange()", () => {
75
- it("should return only the requested fields (plus _id)", async () => {
76
- const clientId = "projectionClient";
77
- const scan = createScanFixture({
78
- clientId,
79
- status: "COMPLETED",
80
- siteChrome: { url: "https://example.com", sourceType: "site_chrome" },
81
- skipped: [{ path: "/broken", reason: "HTTP 500" }],
82
- });
83
-
84
- await getScansCollection().insertOne({
85
- ...scan,
86
- createdAt: new Date("2023-05-15"),
87
- });
88
-
89
- const [result] = await getScanFieldsByClientAndDateRange(
90
- clientId,
91
- new Date("2023-05-01"),
92
- new Date("2023-05-31"),
93
- ["clientId", "websiteUrlId", "status"],
94
- );
95
-
96
- expect(result).toMatchObject({
97
- clientId,
98
- websiteUrlId: scan.websiteUrlId,
99
- status: "COMPLETED",
100
- });
101
- expect(result).toHaveProperty("_id");
102
- expect(result).not.toHaveProperty("siteChrome");
103
- expect(result).not.toHaveProperty("skipped");
104
- expect(result).not.toHaveProperty("createdAt");
105
- });
106
- });
107
-
108
- describe("findScansByQuery() / countScans()", () => {
109
- it("should find scans matching a raw filter and count them", async () => {
110
- const clientId = "queryClient";
111
- const completed = createScanFixture({ clientId, status: "COMPLETED" });
112
- const scanning = createScanFixture({ clientId, status: "SCANNING" });
113
-
114
- await getScansCollection().insertMany([completed, scanning]);
115
-
116
- const result = await findScansByQuery({ clientId, status: "COMPLETED" });
117
- const count = await countScans({ clientId });
118
-
119
- expect(result.length).toBe(1);
120
- expect(result[0].websiteUrlId).toBe(completed.websiteUrlId);
121
- expect(count).toBe(2);
122
- });
123
- });
124
-
125
- describe("createScanDoc()", () => {
126
- it("should insert a scan with default values for the rest of the fields", async () => {
127
- const clientId = "createClient";
128
- const websiteUrlId = new ObjectId().toString();
129
-
130
- const { insertedId } = await createScanDoc({ clientId, websiteUrlId });
131
-
132
- const result = await getScansCollection().findOne({ _id: insertedId });
133
-
134
- expect(result).toMatchObject({
135
- clientId,
136
- websiteUrlId,
137
- status: "CHECKING",
138
- activeTasksCount: 0,
139
- pagesScanned: 0,
140
- pagesSkipped: 0,
141
- skipped: [],
142
- siteChrome: {},
143
- pausedAt: null,
144
- });
145
- expect(result?.createdAt).toBeInstanceOf(Date);
146
- expect(result?.updatedAt).toBeInstanceOf(Date);
147
- });
148
- });
149
-
150
- describe("pausedAt", () => {
151
- it("is set on pause and cleared back to null on resume, via updateScanDoc", async () => {
152
- const scan = createScanFixture({ status: "SCANNING", pausedAt: null });
153
- const { insertedId } = await getScansCollection().insertOne(scan);
154
-
155
- const pausedAt = new Date();
156
- const paused = await updateScanDoc(insertedId, {
157
- status: "PAUSED",
158
- pausedAt,
159
- });
160
- expect(paused?.pausedAt).toEqual(pausedAt);
161
-
162
- const resumed = await updateScanDoc(insertedId, {
163
- status: "SCANNING",
164
- pausedAt: null,
165
- });
166
- expect(resumed?.pausedAt).toBeNull();
167
- });
168
- });
169
-
170
- describe("updateScanDoc()", () => {
171
- it("should update the given fields and bump updatedAt", async () => {
172
- const scan = createScanFixture({ status: "SCANNING", pagesScanned: 0 });
173
- const { insertedId } = await getScansCollection().insertOne(scan);
174
-
175
- const result = await updateScanDoc(insertedId, {
176
- status: "COMPLETED",
177
- pagesScanned: 10,
178
- });
179
-
180
- expect(result).toMatchObject({
181
- _id: insertedId,
182
- status: "COMPLETED",
183
- pagesScanned: 10,
184
- });
185
- expect(result?.updatedAt.getTime()).toBeGreaterThan(
186
- scan.updatedAt.getTime(),
187
- );
188
- });
189
-
190
- it("should return null when the scan does not exist", async () => {
191
- const result = await updateScanDoc(new ObjectId(), { status: "FAILED" });
192
-
193
- expect(result).toBeNull();
194
- });
195
- });
196
-
197
- describe("in-progress scan helpers", () => {
198
- const websiteUrlId = "website-123";
199
-
200
- it("should return website scan history newest first", async () => {
201
- await getScansCollection().insertMany([
202
- createScanFixture({
203
- websiteUrlId,
204
- status: "COMPLETED",
205
- createdAt: new Date("2023-05-01"),
206
- }),
207
- createScanFixture({
208
- websiteUrlId,
209
- status: "COMPLETED",
210
- createdAt: new Date("2023-05-15"),
211
- }),
212
- ]);
213
-
214
- const scans = await getScansByWebsiteUrl(websiteUrlId);
215
- expect(scans).toHaveLength(2);
216
- expect(scans[0].createdAt.getTime()).toBeGreaterThan(
217
- scans[1].createdAt.getTime(),
218
- );
219
- });
220
-
221
- it("should return the newest scan for a website", async () => {
222
- await getScansCollection().insertMany([
223
- createScanFixture({
224
- websiteUrlId,
225
- status: "COMPLETED",
226
- createdAt: new Date("2023-05-01"),
227
- }),
228
- createScanFixture({
229
- websiteUrlId,
230
- status: "FAILED",
231
- createdAt: new Date("2023-05-15"),
232
- }),
233
- ]);
234
-
235
- const latest = await getLatestScanByWebsiteUrl(websiteUrlId);
236
- expect(latest?.status).toBe("FAILED");
237
- });
238
-
239
- it("should return in-progress scan and return null when only completed exists", async () => {
240
- await getScansCollection().insertMany([
241
- createScanFixture({
242
- websiteUrlId,
243
- status: "COMPLETED",
244
- createdAt: new Date("2023-05-01"),
245
- }),
246
- createScanFixture({
247
- websiteUrlId,
248
- status: "SCANNING",
249
- createdAt: new Date("2023-05-15"),
250
- }),
251
- ]);
252
-
253
- const inProgressScan = await getInProgressScanByWebsiteUrl(websiteUrlId);
254
- expect(inProgressScan?.status).toBe("SCANNING");
255
-
256
- await getScansCollection().deleteMany({ websiteUrlId });
257
- await getScansCollection().insertOne(
258
- createScanFixture({
259
- websiteUrlId,
260
- status: "COMPLETED",
261
- createdAt: new Date("2023-05-20"),
262
- }),
263
- );
264
-
265
- expect(await getInProgressScanByWebsiteUrl(websiteUrlId)).toBeNull();
266
- });
267
-
268
- it("should return all in-progress scans across websites for a client", async () => {
269
- const clientId = "multiScanClient";
270
- await getScansCollection().insertMany([
271
- createScanFixture({
272
- clientId,
273
- websiteUrlId: "website-a",
274
- status: "SCANNING",
275
- }),
276
- createScanFixture({
277
- clientId,
278
- websiteUrlId: "website-b",
279
- status: "PROCESSING",
280
- }),
281
- createScanFixture({
282
- clientId,
283
- websiteUrlId: "website-c",
284
- status: "COMPLETED",
285
- }),
286
- ]);
287
-
288
- const scans = await findInProgressScansByClient(clientId);
289
- expect(scans).toHaveLength(2);
290
- expect(scans.map((s) => s.websiteUrlId).sort()).toEqual([
291
- "website-a",
292
- "website-b",
293
- ]);
294
- });
295
- });
296
-
297
- describe("website delete helpers", () => {
298
- it("should return the newest completed scan only", async () => {
299
- const websiteUrlId = new ObjectId().toString();
300
- await getScansCollection().insertMany([
301
- createScanFixture({
302
- websiteUrlId,
303
- status: "FAILED",
304
- createdAt: new Date("2023-05-25"),
305
- }),
306
- createScanFixture({
307
- websiteUrlId,
308
- status: "COMPLETED",
309
- createdAt: new Date("2023-05-20"),
310
- }),
311
- createScanFixture({
312
- websiteUrlId,
313
- status: "COMPLETED",
314
- createdAt: new Date("2023-05-22"),
315
- }),
316
- ]);
317
-
318
- const latest = await getLatestCompletedScanByWebsiteUrl(websiteUrlId);
319
- expect(latest?.status).toBe("COMPLETED");
320
- expect(latest?.createdAt).toEqual(new Date("2023-05-22"));
321
- });
322
-
323
- it("should delete all scans for the website and return count", async () => {
324
- const websiteUrlId = new ObjectId().toString();
325
- await getScansCollection().insertMany([
326
- createScanFixture({ websiteUrlId }),
327
- createScanFixture({ websiteUrlId }),
328
- createScanFixture({ websiteUrlId: new ObjectId().toString() }),
329
- ]);
330
-
331
- const deleted = await deleteScansByWebsiteUrl(websiteUrlId);
332
- expect(deleted).toBe(2);
333
- expect(await countScans({ websiteUrlId })).toBe(0);
334
- });
335
- });
336
-
337
- describe("deleteScanById()", () => {
338
- it("should delete the scan and return true", async () => {
339
- const { insertedId } =
340
- await getScansCollection().insertOne(createScanFixture());
341
-
342
- expect(await deleteScanById(insertedId)).toBe(true);
343
- expect(
344
- await getScansCollection().findOne({ _id: insertedId }),
345
- ).toBeNull();
346
- });
347
-
348
- it("should return false when the scan does not exist", async () => {
349
- expect(await deleteScanById(new ObjectId())).toBe(false);
350
- });
351
- });
352
-
353
- describe("FINISHED_SCAN_STATUSES", () => {
354
- it("should include CANCELED — canceling is final, not resumable", () => {
355
- expect(FINISHED_SCAN_STATUSES).toContain(SCAN_STATUSES.CANCELED);
356
- });
357
-
358
- it("should NOT include PAUSED — pausing is reversible", () => {
359
- expect(FINISHED_SCAN_STATUSES).not.toContain(SCAN_STATUSES.PAUSED);
360
- });
361
- });
362
- });
1
+ import {
2
+ getScansCollection,
3
+ getScansByClientAndDateRange,
4
+ getScanFieldsByClientAndDateRange,
5
+ findScansByQuery,
6
+ countScans,
7
+ createScanDoc,
8
+ updateScanDoc,
9
+ findInProgressScansByClient,
10
+ getScansByWebsiteUrl,
11
+ getLatestScanByWebsiteUrl,
12
+ getInProgressScanByWebsiteUrl,
13
+ getLatestCompletedScanByWebsiteUrl,
14
+ deleteScansByWebsiteUrl,
15
+ deleteScanById,
16
+ } from "../scans.getters";
17
+ import { FINISHED_SCAN_STATUSES, SCAN_STATUSES } from "../scans.constants";
18
+ import { createScanFixture } from "../../../test-utils/factories";
19
+ import { ObjectId } from "mongodb";
20
+
21
+ describe("db.websitalk.scans", () => {
22
+ describe("getScansByClientAndDateRange()", () => {
23
+ it("should return full scan documents within the date range", async () => {
24
+ const clientId = "dateRangeClient";
25
+ const startDate = new Date("2023-05-01");
26
+ const endDate = new Date("2023-05-31");
27
+
28
+ const scanInside = createScanFixture({ clientId, status: "COMPLETED" });
29
+ const scanBefore = createScanFixture({ clientId });
30
+ const scanAfter = createScanFixture({ clientId });
31
+
32
+ await getScansCollection().insertMany([
33
+ { ...scanInside, createdAt: new Date("2023-05-15") },
34
+ { ...scanBefore, createdAt: new Date("2023-04-30") },
35
+ { ...scanAfter, createdAt: new Date("2023-06-01") },
36
+ ]);
37
+
38
+ const result = await getScansByClientAndDateRange(
39
+ clientId,
40
+ startDate,
41
+ endDate,
42
+ );
43
+
44
+ expect(result.length).toBe(1);
45
+ expect(result[0]).toMatchObject({
46
+ clientId,
47
+ websiteUrlId: scanInside.websiteUrlId,
48
+ status: "COMPLETED",
49
+ });
50
+ expect(result[0]).toHaveProperty("siteChrome");
51
+ expect(result[0]).toHaveProperty("skipped");
52
+ });
53
+
54
+ it("should respect the date range boundaries (inclusive)", async () => {
55
+ const clientId = "boundaryClient";
56
+ const onStart = createScanFixture({ clientId });
57
+ const onEnd = createScanFixture({ clientId });
58
+
59
+ await getScansCollection().insertMany([
60
+ { ...onStart, createdAt: new Date("2023-05-01") },
61
+ { ...onEnd, createdAt: new Date("2023-05-31") },
62
+ ]);
63
+
64
+ const result = await getScansByClientAndDateRange(
65
+ clientId,
66
+ new Date("2023-05-01"),
67
+ new Date("2023-05-31"),
68
+ );
69
+
70
+ expect(result.length).toBe(2);
71
+ });
72
+ });
73
+
74
+ describe("getScanFieldsByClientAndDateRange()", () => {
75
+ it("should return only the requested fields (plus _id)", async () => {
76
+ const clientId = "projectionClient";
77
+ const scan = createScanFixture({
78
+ clientId,
79
+ status: "COMPLETED",
80
+ siteChrome: { url: "https://example.com", sourceType: "site_chrome" },
81
+ skipped: [{ path: "/broken", reason: "HTTP 500" }],
82
+ });
83
+
84
+ await getScansCollection().insertOne({
85
+ ...scan,
86
+ createdAt: new Date("2023-05-15"),
87
+ });
88
+
89
+ const [result] = await getScanFieldsByClientAndDateRange(
90
+ clientId,
91
+ new Date("2023-05-01"),
92
+ new Date("2023-05-31"),
93
+ ["clientId", "websiteUrlId", "status"],
94
+ );
95
+
96
+ expect(result).toMatchObject({
97
+ clientId,
98
+ websiteUrlId: scan.websiteUrlId,
99
+ status: "COMPLETED",
100
+ });
101
+ expect(result).toHaveProperty("_id");
102
+ expect(result).not.toHaveProperty("siteChrome");
103
+ expect(result).not.toHaveProperty("skipped");
104
+ expect(result).not.toHaveProperty("createdAt");
105
+ });
106
+ });
107
+
108
+ describe("findScansByQuery() / countScans()", () => {
109
+ it("should find scans matching a raw filter and count them", async () => {
110
+ const clientId = "queryClient";
111
+ const completed = createScanFixture({ clientId, status: "COMPLETED" });
112
+ const scanning = createScanFixture({ clientId, status: "SCANNING" });
113
+
114
+ await getScansCollection().insertMany([completed, scanning]);
115
+
116
+ const result = await findScansByQuery({ clientId, status: "COMPLETED" });
117
+ const count = await countScans({ clientId });
118
+
119
+ expect(result.length).toBe(1);
120
+ expect(result[0].websiteUrlId).toBe(completed.websiteUrlId);
121
+ expect(count).toBe(2);
122
+ });
123
+ });
124
+
125
+ describe("createScanDoc()", () => {
126
+ it("should insert a scan with default values for the rest of the fields", async () => {
127
+ const clientId = "createClient";
128
+ const websiteUrlId = new ObjectId().toString();
129
+
130
+ const { insertedId } = await createScanDoc({ clientId, websiteUrlId });
131
+
132
+ const result = await getScansCollection().findOne({ _id: insertedId });
133
+
134
+ expect(result).toMatchObject({
135
+ clientId,
136
+ websiteUrlId,
137
+ status: "CHECKING",
138
+ activeTasksCount: 0,
139
+ pagesScanned: 0,
140
+ pagesSkipped: 0,
141
+ skipped: [],
142
+ siteChrome: {},
143
+ pausedAt: null,
144
+ });
145
+ expect(result?.createdAt).toBeInstanceOf(Date);
146
+ expect(result?.updatedAt).toBeInstanceOf(Date);
147
+ });
148
+ });
149
+
150
+ describe("pausedAt", () => {
151
+ it("is set on pause and cleared back to null on resume, via updateScanDoc", async () => {
152
+ const scan = createScanFixture({ status: "SCANNING", pausedAt: null });
153
+ const { insertedId } = await getScansCollection().insertOne(scan);
154
+
155
+ const pausedAt = new Date();
156
+ const paused = await updateScanDoc(insertedId, {
157
+ status: "PAUSED",
158
+ pausedAt,
159
+ });
160
+ expect(paused?.pausedAt).toEqual(pausedAt);
161
+
162
+ const resumed = await updateScanDoc(insertedId, {
163
+ status: "SCANNING",
164
+ pausedAt: null,
165
+ });
166
+ expect(resumed?.pausedAt).toBeNull();
167
+ });
168
+ });
169
+
170
+ describe("updateScanDoc()", () => {
171
+ it("should update the given fields and bump updatedAt", async () => {
172
+ const scan = createScanFixture({ status: "SCANNING", pagesScanned: 0 });
173
+ const { insertedId } = await getScansCollection().insertOne(scan);
174
+
175
+ const result = await updateScanDoc(insertedId, {
176
+ status: "COMPLETED",
177
+ pagesScanned: 10,
178
+ });
179
+
180
+ expect(result).toMatchObject({
181
+ _id: insertedId,
182
+ status: "COMPLETED",
183
+ pagesScanned: 10,
184
+ });
185
+ expect(result?.updatedAt.getTime()).toBeGreaterThan(
186
+ scan.updatedAt.getTime(),
187
+ );
188
+ });
189
+
190
+ it("should return null when the scan does not exist", async () => {
191
+ const result = await updateScanDoc(new ObjectId(), { status: "FAILED" });
192
+
193
+ expect(result).toBeNull();
194
+ });
195
+ });
196
+
197
+ describe("in-progress scan helpers", () => {
198
+ const websiteUrlId = "website-123";
199
+
200
+ it("should return website scan history newest first", async () => {
201
+ await getScansCollection().insertMany([
202
+ createScanFixture({
203
+ websiteUrlId,
204
+ status: "COMPLETED",
205
+ createdAt: new Date("2023-05-01"),
206
+ }),
207
+ createScanFixture({
208
+ websiteUrlId,
209
+ status: "COMPLETED",
210
+ createdAt: new Date("2023-05-15"),
211
+ }),
212
+ ]);
213
+
214
+ const scans = await getScansByWebsiteUrl(websiteUrlId);
215
+ expect(scans).toHaveLength(2);
216
+ expect(scans[0].createdAt.getTime()).toBeGreaterThan(
217
+ scans[1].createdAt.getTime(),
218
+ );
219
+ });
220
+
221
+ it("should return the newest scan for a website", async () => {
222
+ await getScansCollection().insertMany([
223
+ createScanFixture({
224
+ websiteUrlId,
225
+ status: "COMPLETED",
226
+ createdAt: new Date("2023-05-01"),
227
+ }),
228
+ createScanFixture({
229
+ websiteUrlId,
230
+ status: "FAILED",
231
+ createdAt: new Date("2023-05-15"),
232
+ }),
233
+ ]);
234
+
235
+ const latest = await getLatestScanByWebsiteUrl(websiteUrlId);
236
+ expect(latest?.status).toBe("FAILED");
237
+ });
238
+
239
+ it("should return in-progress scan and return null when only completed exists", async () => {
240
+ await getScansCollection().insertMany([
241
+ createScanFixture({
242
+ websiteUrlId,
243
+ status: "COMPLETED",
244
+ createdAt: new Date("2023-05-01"),
245
+ }),
246
+ createScanFixture({
247
+ websiteUrlId,
248
+ status: "SCANNING",
249
+ createdAt: new Date("2023-05-15"),
250
+ }),
251
+ ]);
252
+
253
+ const inProgressScan = await getInProgressScanByWebsiteUrl(websiteUrlId);
254
+ expect(inProgressScan?.status).toBe("SCANNING");
255
+
256
+ await getScansCollection().deleteMany({ websiteUrlId });
257
+ await getScansCollection().insertOne(
258
+ createScanFixture({
259
+ websiteUrlId,
260
+ status: "COMPLETED",
261
+ createdAt: new Date("2023-05-20"),
262
+ }),
263
+ );
264
+
265
+ expect(await getInProgressScanByWebsiteUrl(websiteUrlId)).toBeNull();
266
+ });
267
+
268
+ it("should return all in-progress scans across websites for a client", async () => {
269
+ const clientId = "multiScanClient";
270
+ await getScansCollection().insertMany([
271
+ createScanFixture({
272
+ clientId,
273
+ websiteUrlId: "website-a",
274
+ status: "SCANNING",
275
+ }),
276
+ createScanFixture({
277
+ clientId,
278
+ websiteUrlId: "website-b",
279
+ status: "PROCESSING",
280
+ }),
281
+ createScanFixture({
282
+ clientId,
283
+ websiteUrlId: "website-c",
284
+ status: "COMPLETED",
285
+ }),
286
+ ]);
287
+
288
+ const scans = await findInProgressScansByClient(clientId);
289
+ expect(scans).toHaveLength(2);
290
+ expect(scans.map((s) => s.websiteUrlId).sort()).toEqual([
291
+ "website-a",
292
+ "website-b",
293
+ ]);
294
+ });
295
+ });
296
+
297
+ describe("website delete helpers", () => {
298
+ it("should return the newest completed scan only", async () => {
299
+ const websiteUrlId = new ObjectId().toString();
300
+ await getScansCollection().insertMany([
301
+ createScanFixture({
302
+ websiteUrlId,
303
+ status: "FAILED",
304
+ createdAt: new Date("2023-05-25"),
305
+ }),
306
+ createScanFixture({
307
+ websiteUrlId,
308
+ status: "COMPLETED",
309
+ createdAt: new Date("2023-05-20"),
310
+ }),
311
+ createScanFixture({
312
+ websiteUrlId,
313
+ status: "COMPLETED",
314
+ createdAt: new Date("2023-05-22"),
315
+ }),
316
+ ]);
317
+
318
+ const latest = await getLatestCompletedScanByWebsiteUrl(websiteUrlId);
319
+ expect(latest?.status).toBe("COMPLETED");
320
+ expect(latest?.createdAt).toEqual(new Date("2023-05-22"));
321
+ });
322
+
323
+ it("should delete all scans for the website and return count", async () => {
324
+ const websiteUrlId = new ObjectId().toString();
325
+ await getScansCollection().insertMany([
326
+ createScanFixture({ websiteUrlId }),
327
+ createScanFixture({ websiteUrlId }),
328
+ createScanFixture({ websiteUrlId: new ObjectId().toString() }),
329
+ ]);
330
+
331
+ const deleted = await deleteScansByWebsiteUrl(websiteUrlId);
332
+ expect(deleted).toBe(2);
333
+ expect(await countScans({ websiteUrlId })).toBe(0);
334
+ });
335
+ });
336
+
337
+ describe("deleteScanById()", () => {
338
+ it("should delete the scan and return true", async () => {
339
+ const { insertedId } =
340
+ await getScansCollection().insertOne(createScanFixture());
341
+
342
+ expect(await deleteScanById(insertedId)).toBe(true);
343
+ expect(
344
+ await getScansCollection().findOne({ _id: insertedId }),
345
+ ).toBeNull();
346
+ });
347
+
348
+ it("should return false when the scan does not exist", async () => {
349
+ expect(await deleteScanById(new ObjectId())).toBe(false);
350
+ });
351
+ });
352
+
353
+ describe("FINISHED_SCAN_STATUSES", () => {
354
+ it("should include CANCELED — canceling is final, not resumable", () => {
355
+ expect(FINISHED_SCAN_STATUSES).toContain(SCAN_STATUSES.CANCELED);
356
+ });
357
+
358
+ it("should NOT include PAUSED — pausing is reversible", () => {
359
+ expect(FINISHED_SCAN_STATUSES).not.toContain(SCAN_STATUSES.PAUSED);
360
+ });
361
+ });
362
+ });