@talkpilot/core-db 1.3.17 → 1.3.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +199 -58
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/municipal/index.d.ts +1 -1
  7. package/dist/municipal/index.d.ts.map +1 -1
  8. package/dist/municipal/tickets/tickets.statistics.getters.d.ts.map +1 -1
  9. package/dist/municipal/tickets/tickets.statistics.getters.js +6 -2
  10. package/dist/municipal/tickets/tickets.statistics.getters.js.map +1 -1
  11. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts +3 -0
  12. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts.map +1 -1
  13. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js +17 -1
  14. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js.map +1 -1
  15. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts +2 -2
  16. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts.map +1 -1
  17. package/dist/talkpilot/flows/flows.schema.d.ts +3 -0
  18. package/dist/talkpilot/flows/flows.schema.d.ts.map +1 -1
  19. package/dist/talkpilot/flows/flows.schema.js +1 -0
  20. package/dist/talkpilot/flows/flows.schema.js.map +1 -1
  21. package/dist/talkpilot/flows/flows.setter.d.ts +13 -0
  22. package/dist/talkpilot/flows/flows.setter.d.ts.map +1 -0
  23. package/dist/talkpilot/flows/flows.setter.js +90 -0
  24. package/dist/talkpilot/flows/flows.setter.js.map +1 -0
  25. package/dist/talkpilot/flows/flows.types.d.ts +2 -0
  26. package/dist/talkpilot/flows/flows.types.d.ts.map +1 -1
  27. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts +1 -0
  28. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts.map +1 -1
  29. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js +8 -1
  30. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js.map +1 -1
  31. package/dist/test-utils/factories/index.d.ts +1 -0
  32. package/dist/test-utils/factories/index.d.ts.map +1 -1
  33. package/dist/test-utils/factories/index.js +1 -0
  34. package/dist/test-utils/factories/index.js.map +1 -1
  35. package/dist/test-utils/factories/websitalk/scans.d.ts.map +1 -1
  36. package/dist/test-utils/factories/websitalk/scans.js +2 -1
  37. package/dist/test-utils/factories/websitalk/scans.js.map +1 -1
  38. package/dist/websitalk/index.d.ts +1 -0
  39. package/dist/websitalk/index.d.ts.map +1 -1
  40. package/dist/websitalk/index.js +1 -0
  41. package/dist/websitalk/index.js.map +1 -1
  42. package/dist/websitalk/scans/index.d.ts +2 -0
  43. package/dist/websitalk/scans/index.d.ts.map +1 -1
  44. package/dist/websitalk/scans/index.js +2 -0
  45. package/dist/websitalk/scans/index.js.map +1 -1
  46. package/dist/websitalk/scans/scans.getters.d.ts +10 -3
  47. package/dist/websitalk/scans/scans.getters.d.ts.map +1 -1
  48. package/dist/websitalk/scans/scans.getters.js +49 -9
  49. package/dist/websitalk/scans/scans.getters.js.map +1 -1
  50. package/dist/websitalk/scans/scans.types.d.ts +3 -8
  51. package/dist/websitalk/scans/scans.types.d.ts.map +1 -1
  52. package/package.json +1 -1
  53. package/src/index.ts +1 -0
  54. package/src/municipal/index.ts +1 -1
  55. package/src/municipal/tickets/tickets.statistics.getters.ts +16 -3
  56. package/src/talkpilot/calls/__tests__/calls.statistics.spec.ts +6 -4
  57. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.getters.spec.ts +57 -5
  58. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.spec.ts +0 -4
  59. package/src/talkpilot/clientsConfig/clientsConfig.getters.ts +24 -0
  60. package/src/talkpilot/clientsConfig/clientsConfig.types.ts +2 -2
  61. package/src/talkpilot/flows/__tests__/flows.schema.spec.ts +3 -0
  62. package/src/talkpilot/flows/flows.schema.ts +1 -0
  63. package/src/talkpilot/flows/flows.types.ts +2 -0
  64. package/src/talkpilot/phone_numbers/phone_numbers.getter.ts +13 -0
  65. package/src/test-utils/factories/index.ts +1 -0
  66. package/src/test-utils/factories/websitalk/scans.ts +2 -1
  67. package/src/test-utils/factories/websitalk/websiteUrls.ts +17 -0
  68. package/src/websitalk/index.ts +1 -0
  69. package/src/websitalk/scans/__tests__/scans.spec.ts +121 -26
  70. package/src/websitalk/scans/index.ts +2 -0
  71. package/src/websitalk/scans/scans.constants.ts +15 -0
  72. package/src/websitalk/scans/scans.getters.ts +64 -17
  73. package/src/websitalk/scans/scans.types.ts +3 -11
  74. package/src/websitalk/scans/scans.utils.ts +5 -0
  75. package/src/websitalk/websiteUrls/__tests__/websiteUrls.spec.ts +77 -0
  76. package/src/websitalk/websiteUrls/index.ts +2 -0
  77. package/src/websitalk/websiteUrls/websiteUrls.getters.ts +65 -0
  78. package/src/websitalk/websiteUrls/websiteUrls.types.ts +13 -0
  79. package/tsconfig.json +4 -4
  80. package/README_OLD.md +0 -160
@@ -1,6 +1,9 @@
1
1
  import { describe, it, expect, beforeEach, afterEach } from "@jest/globals";
2
2
  import {
3
3
  getClientsConfigCollection,
4
+ getActiveScanId,
5
+ updateActiveScanId,
6
+ clearActiveScanId,
4
7
  updateProductConfig,
5
8
  } from "../clientsConfig.getters";
6
9
 
@@ -23,8 +26,6 @@ describe("updateProductConfig", () => {
23
26
  websiteTalk: {
24
27
  language: "English",
25
28
  companyName: "OldCorp",
26
- defaultBaseUrl: "https://old-url.com",
27
- logoUrl: "",
28
29
  timezone: "UTC",
29
30
  },
30
31
  },
@@ -38,9 +39,7 @@ describe("updateProductConfig", () => {
38
39
  expect(updatedDoc).toBeDefined();
39
40
  expect(updatedDoc?.products.websiteTalk?.language).toBe("Hebrew");
40
41
  expect(updatedDoc?.products.websiteTalk?.companyName).toBe("TestCorp");
41
- expect(updatedDoc?.products.websiteTalk?.defaultBaseUrl).toBe(
42
- "https://old-url.com",
43
- );
42
+ expect(updatedDoc?.products.websiteTalk?.timezone).toBe("UTC");
44
43
  });
45
44
 
46
45
  it("should throw an error if no client config is found", async () => {
@@ -51,3 +50,56 @@ describe("updateProductConfig", () => {
51
50
  ).rejects.toThrow("No client config found for clientId: invalid-client");
52
51
  });
53
52
  });
53
+
54
+ describe("activeScanId", () => {
55
+ beforeEach(async () => {
56
+ await getClientsConfigCollection().deleteMany({});
57
+ });
58
+
59
+ afterEach(async () => {
60
+ await getClientsConfigCollection().deleteMany({});
61
+ });
62
+
63
+ it("should return undefined when activeScanId is not set", async () => {
64
+ const clientId = "client-active";
65
+ await getClientsConfigCollection().insertOne({
66
+ clientId,
67
+ products: {
68
+ websiteTalk: { companyName: "X", timezone: "UTC", language: "he" },
69
+ },
70
+ } as any);
71
+
72
+ expect(await getActiveScanId(clientId)).toBeUndefined();
73
+ });
74
+
75
+ it("should persist activeScanId and return it from getActiveScanId", async () => {
76
+ const clientId = "client-active-2";
77
+ await getClientsConfigCollection().insertOne({
78
+ clientId,
79
+ products: {
80
+ websiteTalk: { companyName: "X", timezone: "UTC", language: "he" },
81
+ },
82
+ } as any);
83
+
84
+ await updateActiveScanId(clientId, "scan-abc");
85
+ expect(await getActiveScanId(clientId)).toBe("scan-abc");
86
+ });
87
+
88
+ it("should clear activeScanId and return undefined from getActiveScanId", async () => {
89
+ const clientId = "client-active-3";
90
+ await getClientsConfigCollection().insertOne({
91
+ clientId,
92
+ products: {
93
+ websiteTalk: {
94
+ companyName: "X",
95
+ timezone: "UTC",
96
+ language: "he",
97
+ activeScanId: "scan-old",
98
+ },
99
+ },
100
+ } as any);
101
+
102
+ await clearActiveScanId(clientId);
103
+ expect(await getActiveScanId(clientId)).toBeUndefined();
104
+ });
105
+ });
@@ -31,11 +31,9 @@ describe("db.clientsConfig", () => {
31
31
  clientId,
32
32
  products: {
33
33
  websiteTalk: {
34
- logoUrl: "https://cdn.example.com/branding/acme/logo.png",
35
34
  companyName: "Acme Ltd",
36
35
  timezone: "Asia/Jerusalem",
37
36
  language: "he",
38
- defaultBaseUrl: "https://acme.example",
39
37
  },
40
38
  },
41
39
  });
@@ -48,11 +46,9 @@ describe("db.clientsConfig", () => {
48
46
  clientId,
49
47
  products: {
50
48
  websiteTalk: {
51
- logoUrl: "https://cdn.example.com/branding/acme/logo.png",
52
49
  companyName: "Acme Ltd",
53
50
  timezone: "Asia/Jerusalem",
54
51
  language: "he",
55
- defaultBaseUrl: "https://acme.example",
56
52
  },
57
53
  },
58
54
  });
@@ -53,3 +53,27 @@ export async function updateProductConfig<K extends KnownProductKey>(
53
53
  throw new Error(`No client config found for clientId: ${clientId}`);
54
54
  }
55
55
  }
56
+
57
+ export const getActiveScanId = async (
58
+ clientId: string,
59
+ ): Promise<string | undefined> => {
60
+ const cfg = await getClientConfig(clientId);
61
+ return cfg?.products?.websiteTalk?.activeScanId;
62
+ };
63
+
64
+ export const updateActiveScanId = async (
65
+ clientId: string,
66
+ scanId: string,
67
+ ): Promise<void> => {
68
+ await updateProductConfig(clientId, "websiteTalk", { activeScanId: scanId });
69
+ };
70
+
71
+ export const clearActiveScanId = async (clientId: string): Promise<void> => {
72
+ const result = await getClientsConfigCollection().updateOne(
73
+ { clientId },
74
+ { $unset: { "products.websiteTalk.activeScanId": "" } },
75
+ );
76
+ if (result.matchedCount === 0) {
77
+ throw new Error(`No client config found for clientId: ${clientId}`);
78
+ }
79
+ };
@@ -58,11 +58,11 @@ export type WebsiteTalkScheduler = {
58
58
 
59
59
  /** Product config for the websiteTalk */
60
60
  export type WebsiteTalkProduct = {
61
- logoUrl: string;
62
61
  companyName: string;
63
62
  timezone: string;
64
63
  language: string;
65
- defaultBaseUrl: string;
64
+ activeScanId?: string;
65
+ flowId?: string;
66
66
  };
67
67
 
68
68
  // ---------------------------------------------------------------------------
@@ -79,6 +79,9 @@ describe("flowMongoSchema", () => {
79
79
  expect(toolItem.properties).toHaveProperty("runInBackground");
80
80
  expect(toolItem.properties.runInBackground.bsonType).toBe("bool");
81
81
 
82
+ expect(toolItem.properties).toHaveProperty("useRedisTranscription");
83
+ expect(toolItem.properties.useRedisTranscription.bsonType).toBe("bool");
84
+
82
85
  expect(toolItem.properties).toHaveProperty("backgroundToolType");
83
86
  expect(toolItem.properties.backgroundToolType.bsonType).toBe("string");
84
87
  expect(toolItem.properties.backgroundToolType.enum).toEqual([
@@ -138,6 +138,7 @@ export const flowMongoSchema = {
138
138
  parameters: { bsonType: "object" },
139
139
  bodyFormat: { bsonType: "string", enum: ["json", "form-data"] },
140
140
  preventAudioDuringTool: { bsonType: "bool" },
141
+ useRedisTranscription: { bsonType: "bool" },
141
142
  sendUserAuthToken: { bsonType: "bool" },
142
143
  runInBackground: { bsonType: "bool" },
143
144
  backgroundToolType: {
@@ -71,6 +71,8 @@ export type FlowTool = {
71
71
  parameters: Record<string, unknown>;
72
72
  bodyFormat?: "json" | "form-data";
73
73
  preventAudioDuringTool?: boolean;
74
+ /** When true, prefer cached transcription from Redis (default: false). */
75
+ useRedisTranscription?: boolean;
74
76
  sendUserAuthToken?: boolean;
75
77
  runInBackground?: boolean;
76
78
  backgroundToolType?: "backgroundToolAlways" | "backgroundToolOnce";
@@ -156,3 +156,16 @@ export const findClientByPhoneNumber = async (
156
156
  if (!client) throw new Error("Failed to get client");
157
157
  return client;
158
158
  };
159
+
160
+ export const bindClientPhoneToFlow = async (
161
+ clientId: string,
162
+ flowId: string,
163
+ ): Promise<void> => {
164
+ const result = await getPhoneNumbersCollection().updateOne(
165
+ { client_id: clientId, is_primary: true },
166
+ { $set: { flow_id: new ObjectId(flowId), updatedAt: new Date() } },
167
+ );
168
+ if (result.matchedCount === 0) {
169
+ throw new Error(`No primary phone number found for client: ${clientId}`);
170
+ }
171
+ };
@@ -13,3 +13,4 @@ export * from "./municipal/muniIssues";
13
13
  export * from "./municipal/streets";
14
14
  export * from "./municipal/tickets";
15
15
  export * from "./websitalk/scans";
16
+ export * from "./websitalk/websiteUrls";
@@ -1,10 +1,11 @@
1
1
  import { Factory } from "fishery";
2
2
  import { faker } from "@faker-js/faker";
3
+ import { ObjectId } from "mongodb";
3
4
  import type { Scan } from "../../../websitalk";
4
5
 
5
6
  export const scanFactory = Factory.define<Scan>(() => ({
6
7
  clientId: faker.string.uuid(),
7
- baseUrl: faker.internet.url(),
8
+ websiteUrlId: new ObjectId().toString(),
8
9
  status: "CHECKING",
9
10
  activeTasksCount: 0,
10
11
  pagesScanned: 0,
@@ -0,0 +1,17 @@
1
+ import { Factory } from "fishery";
2
+ import { faker } from "@faker-js/faker";
3
+ import type { WebsiteUrl } from "../../../websitalk/websiteUrls";
4
+
5
+ export const websiteUrlFactory = Factory.define<WebsiteUrl>(() => ({
6
+ clientId: faker.string.uuid(),
7
+ name: faker.company.name(),
8
+ baseUrl: faker.internet.url(),
9
+ createdAt: new Date(),
10
+ updatedAt: new Date(),
11
+ }));
12
+
13
+ export function createWebsiteUrlFixture(
14
+ overrides?: Partial<WebsiteUrl>,
15
+ ): WebsiteUrl {
16
+ return websiteUrlFactory.build(overrides);
17
+ }
@@ -1,6 +1,7 @@
1
1
  import { Db, ObjectId as MongoObjectId } from "mongodb";
2
2
 
3
3
  export * from "./scans";
4
+ export * from "./websiteUrls";
4
5
  export { websitalkMongodbClient } from "./mongodb-client";
5
6
 
6
7
  let db: Db;
@@ -6,7 +6,12 @@ import {
6
6
  countScans,
7
7
  createScanDoc,
8
8
  updateScanDoc,
9
- getActiveScanStatus,
9
+ findInProgressScansByClient,
10
+ getScansByWebsiteUrl,
11
+ getLatestScanByWebsiteUrl,
12
+ getInProgressScanByWebsiteUrl,
13
+ getLatestCompletedScanByWebsiteUrl,
14
+ deleteScansByWebsiteUrl,
10
15
  } from "../scans.getters";
11
16
  import { createScanFixture } from "../../../test-utils/factories";
12
17
  import { ObjectId } from "mongodb";
@@ -37,7 +42,7 @@ describe("db.websitalk.scans", () => {
37
42
  expect(result.length).toBe(1);
38
43
  expect(result[0]).toMatchObject({
39
44
  clientId,
40
- baseUrl: scanInside.baseUrl,
45
+ websiteUrlId: scanInside.websiteUrlId,
41
46
  status: "COMPLETED",
42
47
  });
43
48
  expect(result[0]).toHaveProperty("siteChrome");
@@ -83,12 +88,12 @@ describe("db.websitalk.scans", () => {
83
88
  clientId,
84
89
  new Date("2023-05-01"),
85
90
  new Date("2023-05-31"),
86
- ["clientId", "baseUrl", "status"],
91
+ ["clientId", "websiteUrlId", "status"],
87
92
  );
88
93
 
89
94
  expect(result).toMatchObject({
90
95
  clientId,
91
- baseUrl: scan.baseUrl,
96
+ websiteUrlId: scan.websiteUrlId,
92
97
  status: "COMPLETED",
93
98
  });
94
99
  expect(result).toHaveProperty("_id");
@@ -110,7 +115,7 @@ describe("db.websitalk.scans", () => {
110
115
  const count = await countScans({ clientId });
111
116
 
112
117
  expect(result.length).toBe(1);
113
- expect(result[0].baseUrl).toBe(completed.baseUrl);
118
+ expect(result[0].websiteUrlId).toBe(completed.websiteUrlId);
114
119
  expect(count).toBe(2);
115
120
  });
116
121
  });
@@ -118,15 +123,15 @@ describe("db.websitalk.scans", () => {
118
123
  describe("createScanDoc()", () => {
119
124
  it("should insert a scan with default values for the rest of the fields", async () => {
120
125
  const clientId = "createClient";
121
- const baseUrl = "https://example.com";
126
+ const websiteUrlId = new ObjectId().toString();
122
127
 
123
- const { insertedId } = await createScanDoc({ clientId, baseUrl });
128
+ const { insertedId } = await createScanDoc({ clientId, websiteUrlId });
124
129
 
125
130
  const result = await getScansCollection().findOne({ _id: insertedId });
126
131
 
127
132
  expect(result).toMatchObject({
128
133
  clientId,
129
- baseUrl,
134
+ websiteUrlId,
130
135
  status: "CHECKING",
131
136
  activeTasksCount: 0,
132
137
  pagesScanned: 0,
@@ -166,53 +171,143 @@ describe("db.websitalk.scans", () => {
166
171
  });
167
172
  });
168
173
 
169
- describe("getActiveScanStatus()", () => {
170
- it("should return isActive: true with the status when the latest scan is still in progress", async () => {
171
- const clientId = "activeClient";
174
+ describe("in-progress scan helpers", () => {
175
+ const websiteUrlId = "website-123";
172
176
 
177
+ it("should return website scan history newest first", async () => {
173
178
  await getScansCollection().insertMany([
174
179
  createScanFixture({
175
- clientId,
180
+ websiteUrlId,
176
181
  status: "COMPLETED",
177
182
  createdAt: new Date("2023-05-01"),
178
183
  }),
179
184
  createScanFixture({
180
- clientId,
181
- status: "SCANNING",
185
+ websiteUrlId,
186
+ status: "COMPLETED",
182
187
  createdAt: new Date("2023-05-15"),
183
188
  }),
184
189
  ]);
185
190
 
186
- const result = await getActiveScanStatus(clientId);
191
+ const scans = await getScansByWebsiteUrl(websiteUrlId);
192
+ expect(scans).toHaveLength(2);
193
+ expect(scans[0].createdAt.getTime()).toBeGreaterThan(
194
+ scans[1].createdAt.getTime(),
195
+ );
196
+ });
197
+
198
+ it("should return the newest scan for a website", async () => {
199
+ await getScansCollection().insertMany([
200
+ createScanFixture({
201
+ websiteUrlId,
202
+ status: "COMPLETED",
203
+ createdAt: new Date("2023-05-01"),
204
+ }),
205
+ createScanFixture({
206
+ websiteUrlId,
207
+ status: "FAILED",
208
+ createdAt: new Date("2023-05-15"),
209
+ }),
210
+ ]);
187
211
 
188
- expect(result).toEqual({ isActive: true, status: "SCANNING" });
212
+ const latest = await getLatestScanByWebsiteUrl(websiteUrlId);
213
+ expect(latest?.status).toBe("FAILED");
189
214
  });
190
215
 
191
- it("should return isActive: false when the latest scan finished (COMPLETED / FAILED)", async () => {
192
- const clientId = "finishedClient";
216
+ it("should return in-progress scan and return null when only completed exists", async () => {
217
+ await getScansCollection().insertMany([
218
+ createScanFixture({
219
+ websiteUrlId,
220
+ status: "COMPLETED",
221
+ createdAt: new Date("2023-05-01"),
222
+ }),
223
+ createScanFixture({
224
+ websiteUrlId,
225
+ status: "SCANNING",
226
+ createdAt: new Date("2023-05-15"),
227
+ }),
228
+ ]);
193
229
 
230
+ const inProgressScan = await getInProgressScanByWebsiteUrl(websiteUrlId);
231
+ expect(inProgressScan?.status).toBe("SCANNING");
232
+
233
+ await getScansCollection().deleteMany({ websiteUrlId });
234
+ await getScansCollection().insertOne(
235
+ createScanFixture({
236
+ websiteUrlId,
237
+ status: "COMPLETED",
238
+ createdAt: new Date("2023-05-20"),
239
+ }),
240
+ );
241
+
242
+ expect(await getInProgressScanByWebsiteUrl(websiteUrlId)).toBeNull();
243
+ });
244
+
245
+ it("should return all in-progress scans across websites for a client", async () => {
246
+ const clientId = "multiScanClient";
194
247
  await getScansCollection().insertMany([
195
248
  createScanFixture({
196
249
  clientId,
250
+ websiteUrlId: "website-a",
197
251
  status: "SCANNING",
198
- createdAt: new Date("2023-05-01"),
199
252
  }),
200
253
  createScanFixture({
201
254
  clientId,
202
- status: "FAILED",
203
- createdAt: new Date("2023-05-15"),
255
+ websiteUrlId: "website-b",
256
+ status: "PROCESSING",
257
+ }),
258
+ createScanFixture({
259
+ clientId,
260
+ websiteUrlId: "website-c",
261
+ status: "COMPLETED",
204
262
  }),
205
263
  ]);
206
264
 
207
- const result = await getActiveScanStatus(clientId);
265
+ const scans = await findInProgressScansByClient(clientId);
266
+ expect(scans).toHaveLength(2);
267
+ expect(scans.map((s) => s.websiteUrlId).sort()).toEqual([
268
+ "website-a",
269
+ "website-b",
270
+ ]);
271
+ });
272
+ });
208
273
 
209
- expect(result).toEqual({ isActive: false });
274
+ describe("website delete helpers", () => {
275
+ it("should return the newest completed scan only", async () => {
276
+ const websiteUrlId = new ObjectId().toString();
277
+ await getScansCollection().insertMany([
278
+ createScanFixture({
279
+ websiteUrlId,
280
+ status: "FAILED",
281
+ createdAt: new Date("2023-05-25"),
282
+ }),
283
+ createScanFixture({
284
+ websiteUrlId,
285
+ status: "COMPLETED",
286
+ createdAt: new Date("2023-05-20"),
287
+ }),
288
+ createScanFixture({
289
+ websiteUrlId,
290
+ status: "COMPLETED",
291
+ createdAt: new Date("2023-05-22"),
292
+ }),
293
+ ]);
294
+
295
+ const latest = await getLatestCompletedScanByWebsiteUrl(websiteUrlId);
296
+ expect(latest?.status).toBe("COMPLETED");
297
+ expect(latest?.createdAt).toEqual(new Date("2023-05-22"));
210
298
  });
211
299
 
212
- it("should return isActive: false when the client has no scans", async () => {
213
- const result = await getActiveScanStatus("noScansClient");
300
+ it("should delete all scans for the website and return count", async () => {
301
+ const websiteUrlId = new ObjectId().toString();
302
+ await getScansCollection().insertMany([
303
+ createScanFixture({ websiteUrlId }),
304
+ createScanFixture({ websiteUrlId }),
305
+ createScanFixture({ websiteUrlId: new ObjectId().toString() }),
306
+ ]);
214
307
 
215
- expect(result).toEqual({ isActive: false });
308
+ const deleted = await deleteScansByWebsiteUrl(websiteUrlId);
309
+ expect(deleted).toBe(2);
310
+ expect(await countScans({ websiteUrlId })).toBe(0);
216
311
  });
217
312
  });
218
313
  });
@@ -1,2 +1,4 @@
1
+ export * from "./scans.constants";
1
2
  export * from "./scans.getters";
2
3
  export * from "./scans.types";
4
+ export * from "./scans.utils";
@@ -0,0 +1,15 @@
1
+ export const SCAN_STATUSES = {
2
+ CHECKING: "CHECKING",
3
+ PREPARING: "PREPARING",
4
+ SCANNING: "SCANNING",
5
+ PROCESSING: "PROCESSING",
6
+ COMPLETED: "COMPLETED",
7
+ FAILED: "FAILED",
8
+ OVERWRITTEN: "OVERWRITTEN",
9
+ } as const;
10
+
11
+ export const FINISHED_SCAN_STATUSES = [
12
+ SCAN_STATUSES.COMPLETED,
13
+ SCAN_STATUSES.FAILED,
14
+ SCAN_STATUSES.OVERWRITTEN,
15
+ ] as const;
@@ -4,12 +4,9 @@ import {
4
4
  applyQueryOptions,
5
5
  QueryOptions,
6
6
  } from "../../talkpilot/utils/query.utils";
7
- import type {
8
- ActiveScanStatus,
9
- Scan,
10
- ScanDoc,
11
- ScanStatus,
12
- } from "./scans.types";
7
+ import type { Scan, ScanDoc } from "./scans.types";
8
+ import { FINISHED_SCAN_STATUSES, SCAN_STATUSES } from "./scans.constants";
9
+ import { isInProgressScan } from "./scans.utils";
13
10
 
14
11
  export const getScansCollection = (): Collection<Scan> => {
15
12
  return getDb().collection<Scan>("scans");
@@ -57,11 +54,12 @@ export const getScanFieldsByClientAndDateRange = <K extends keyof Scan>(
57
54
  };
58
55
 
59
56
  export const createScanDoc = (
60
- scan: Pick<Scan, "clientId" | "baseUrl" | "notifyPhoneNumber">,
57
+ scan: Pick<Scan, "clientId" | "websiteUrlId"> &
58
+ Partial<Pick<Scan, "notifyPhoneNumber">>,
61
59
  ) => {
62
60
  return getScansCollection().insertOne({
63
61
  ...scan,
64
- status: "CHECKING",
62
+ status: SCAN_STATUSES.CHECKING,
65
63
  activeTasksCount: 0,
66
64
  pagesScanned: 0,
67
65
  pagesSkipped: 0,
@@ -72,21 +70,48 @@ export const createScanDoc = (
72
70
  });
73
71
  };
74
72
 
75
- const FINISHED_SCAN_STATUSES: ScanStatus[] = ["COMPLETED", "FAILED"];
73
+ export const getScanById = async (id: string): Promise<ScanDoc | null> => {
74
+ return getScansCollection().findOne({ _id: new ObjectId(id) });
75
+ };
76
76
 
77
- export const getActiveScanStatus = async (
78
- clientId: string,
79
- ): Promise<ActiveScanStatus> => {
80
- const latestScan = await getScansCollection().findOne(
81
- { clientId },
77
+ export const getScansByWebsiteUrl = async (
78
+ websiteUrlId: string,
79
+ ): Promise<ScanDoc[]> => {
80
+ return getScansCollection()
81
+ .find({ websiteUrlId })
82
+ .sort({ createdAt: -1 })
83
+ .toArray();
84
+ };
85
+
86
+ export const getLatestScanByWebsiteUrl = async (
87
+ websiteUrlId: string,
88
+ ): Promise<ScanDoc | null> => {
89
+ return getScansCollection().findOne(
90
+ { websiteUrlId },
82
91
  { sort: { createdAt: -1 } },
83
92
  );
93
+ };
84
94
 
85
- if (!latestScan || FINISHED_SCAN_STATUSES.includes(latestScan.status)) {
86
- return { isActive: false };
95
+ export const getInProgressScanByWebsiteUrl = async (
96
+ websiteUrlId: string,
97
+ ): Promise<ScanDoc | null> => {
98
+ const latestScan = await getLatestScanByWebsiteUrl(websiteUrlId);
99
+ if (!latestScan || !isInProgressScan(latestScan)) {
100
+ return null;
87
101
  }
102
+ return latestScan;
103
+ };
88
104
 
89
- return { isActive: true, status: latestScan.status };
105
+ export const findInProgressScansByClient = async (
106
+ clientId: string,
107
+ ): Promise<ScanDoc[]> => {
108
+ return getScansCollection()
109
+ .find({
110
+ clientId,
111
+ status: { $nin: FINISHED_SCAN_STATUSES },
112
+ })
113
+ .sort({ createdAt: -1 })
114
+ .toArray();
90
115
  };
91
116
 
92
117
  export const updateScanDoc = async (
@@ -111,3 +136,25 @@ export const findScansByQuery = async (
111
136
  export const countScans = async (query: Filter<Scan>): Promise<number> => {
112
137
  return getScansCollection().countDocuments(query);
113
138
  };
139
+
140
+ export const hasScansForWebsiteUrl = async (
141
+ websiteUrlId: string,
142
+ ): Promise<boolean> => {
143
+ return (await countScans({ websiteUrlId })) > 0;
144
+ };
145
+
146
+ export const getLatestCompletedScanByWebsiteUrl = async (
147
+ websiteUrlId: string,
148
+ ): Promise<ScanDoc | null> => {
149
+ return getScansCollection().findOne(
150
+ { websiteUrlId, status: SCAN_STATUSES.COMPLETED },
151
+ { sort: { createdAt: -1 } },
152
+ );
153
+ };
154
+
155
+ export const deleteScansByWebsiteUrl = async (
156
+ websiteUrlId: string,
157
+ ): Promise<number> => {
158
+ const result = await getScansCollection().deleteMany({ websiteUrlId });
159
+ return result.deletedCount;
160
+ };
@@ -1,16 +1,8 @@
1
1
  import { WithId } from "mongodb";
2
2
 
3
- export type ScanStatus =
4
- | "CHECKING"
5
- | "PREPARING"
6
- | "SCANNING"
7
- | "PROCESSING"
8
- | "COMPLETED"
9
- | "FAILED";
3
+ import type { SCAN_STATUSES } from "./scans.constants";
10
4
 
11
- export type ActiveScanStatus =
12
- | { isActive: true; status: ScanStatus }
13
- | { isActive: false };
5
+ export type ScanStatus = (typeof SCAN_STATUSES)[keyof typeof SCAN_STATUSES];
14
6
 
15
7
  export type SiteChromeEntry = {
16
8
  url: string;
@@ -38,7 +30,7 @@ export type SkippedEntry = {
38
30
 
39
31
  export type Scan = {
40
32
  clientId: string;
41
- baseUrl: string;
33
+ websiteUrlId: string;
42
34
  notifyPhoneNumber?: string | null;
43
35
  status: ScanStatus;
44
36
  activeTasksCount: number;
@@ -0,0 +1,5 @@
1
+ import type { Scan, ScanStatus } from "./scans.types";
2
+ import { FINISHED_SCAN_STATUSES } from "./scans.constants";
3
+
4
+ export const isInProgressScan = (scan: Scan): boolean =>
5
+ !(FINISHED_SCAN_STATUSES as readonly ScanStatus[]).includes(scan.status);