@talkpilot/core-db 1.3.11 → 1.3.13

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 (50) hide show
  1. package/README.md +64 -44
  2. package/dist/municipal/tickets/index.d.ts +1 -1
  3. package/dist/municipal/tickets/index.d.ts.map +1 -1
  4. package/dist/municipal/tickets/tickets.statistics.getters.d.ts.map +1 -1
  5. package/dist/municipal/tickets/tickets.statistics.getters.js +19 -6
  6. package/dist/municipal/tickets/tickets.statistics.getters.js.map +1 -1
  7. package/dist/talkpilot/calls/calls.statistics.getters.d.ts.map +1 -1
  8. package/dist/talkpilot/calls/calls.statistics.getters.js +39 -10
  9. package/dist/talkpilot/calls/calls.statistics.getters.js.map +1 -1
  10. package/dist/talkpilot/calls/calls.statistics.types.d.ts +1 -0
  11. package/dist/talkpilot/calls/calls.statistics.types.d.ts.map +1 -1
  12. package/dist/talkpilot/contextNotes/contextNotes.getters.d.ts.map +1 -1
  13. package/dist/talkpilot/contextNotes/contextNotes.getters.js +1 -3
  14. package/dist/talkpilot/contextNotes/contextNotes.getters.js.map +1 -1
  15. package/dist/talkpilot/flows/flows.schema.d.ts +3 -0
  16. package/dist/talkpilot/flows/flows.schema.d.ts.map +1 -1
  17. package/dist/talkpilot/flows/flows.schema.js +1 -0
  18. package/dist/talkpilot/flows/flows.schema.js.map +1 -1
  19. package/dist/talkpilot/flows/flows.types.d.ts +2 -0
  20. package/dist/talkpilot/flows/flows.types.d.ts.map +1 -1
  21. package/dist/talkpilot/subscriptions/subscriptions.utils.d.ts +4 -0
  22. package/dist/talkpilot/subscriptions/subscriptions.utils.d.ts.map +1 -0
  23. package/dist/talkpilot/subscriptions/subscriptions.utils.js +20 -0
  24. package/dist/talkpilot/subscriptions/subscriptions.utils.js.map +1 -0
  25. package/dist/test-utils/factories/talkpilot/contextNotes.d.ts.map +1 -1
  26. package/dist/test-utils/factories/talkpilot/contextNotes.js +4 -1
  27. package/dist/test-utils/factories/talkpilot/contextNotes.js.map +1 -1
  28. package/dist/test-utils/factories/talkpilot/flows.d.ts.map +1 -1
  29. package/dist/test-utils/factories/talkpilot/flows.js +1 -0
  30. package/dist/test-utils/factories/talkpilot/flows.js.map +1 -1
  31. package/dist/utils/date.utils.d.ts.map +1 -1
  32. package/dist/utils/date.utils.js +7 -2
  33. package/dist/utils/date.utils.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/municipal/muniIssues/__tests__/muniIssues.setters.spec.ts +3 -1
  36. package/src/municipal/tickets/__tests__/tickets.statistics.spec.ts +9 -4
  37. package/src/municipal/tickets/index.ts +7 -1
  38. package/src/municipal/tickets/tickets.statistics.getters.ts +48 -12
  39. package/src/talkpilot/calls/__tests__/calls.statistics.spec.ts +144 -36
  40. package/src/talkpilot/calls/calls.statistics.getters.ts +122 -44
  41. package/src/talkpilot/calls/calls.statistics.types.ts +1 -0
  42. package/src/talkpilot/contextNotes/__tests__/contextNotes.getters.spec.ts +61 -20
  43. package/src/talkpilot/contextNotes/contextNotes.getters.ts +3 -4
  44. package/src/talkpilot/flows/flows.schema.ts +1 -0
  45. package/src/talkpilot/flows/flows.types.ts +2 -0
  46. package/src/talkpilot/products/__tests__/products.getters.spec.ts +0 -1
  47. package/src/test-utils/factories/talkpilot/contextNotes.ts +10 -3
  48. package/src/test-utils/factories/talkpilot/flows.ts +1 -0
  49. package/src/utils/date.utils.ts +17 -7
  50. package/README_OLD.md +0 -160
@@ -32,7 +32,9 @@ describe("contextNotes getters", () => {
32
32
 
33
33
  it("should return documents matching clientId and product", async () => {
34
34
  const clientId = new ObjectId().toString();
35
- await createContextNote(buildContextNote({ clientId, product: "Municipal" }));
35
+ await createContextNote(
36
+ buildContextNote({ clientId, product: "Municipal" }),
37
+ );
36
38
  await createContextNote(buildContextNote({ clientId, product: "Clinics" }));
37
39
  await createContextNote(buildContextNote({ product: "Municipal" })); // different client
38
40
 
@@ -44,7 +46,9 @@ describe("contextNotes getters", () => {
44
46
 
45
47
  it("should not return documents for a different product", async () => {
46
48
  const clientId = new ObjectId().toString();
47
- await createContextNote(buildContextNote({ clientId, product: "Municipal" }));
49
+ await createContextNote(
50
+ buildContextNote({ clientId, product: "Municipal" }),
51
+ );
48
52
  await createContextNote(buildContextNote({ clientId, product: "Clinics" }));
49
53
 
50
54
  const results = await getContextNotes(clientId, "Rcure");
@@ -57,26 +61,45 @@ describe("contextNotes getters", () => {
57
61
  const past = new Date(now.getTime() - 10000);
58
62
  const future = new Date(now.getTime() + 10000);
59
63
 
60
- const activeNote = createContextNoteEntry({ activeFrom: past, expiresAt: future });
61
- const expiredNote = createContextNoteEntry({ activeFrom: past, expiresAt: past });
62
- const notYetActiveNote = createContextNoteEntry({ activeFrom: future, expiresAt: null });
63
- const noExpiryNote = createContextNoteEntry({ activeFrom: past, expiresAt: null });
64
+ const activeNote = createContextNoteEntry({
65
+ activeFrom: past,
66
+ expiresAt: future,
67
+ });
68
+ const expiredNote = createContextNoteEntry({
69
+ activeFrom: past,
70
+ expiresAt: past,
71
+ });
72
+ const notYetActiveNote = createContextNoteEntry({
73
+ activeFrom: future,
74
+ expiresAt: null,
75
+ });
76
+ const noExpiryNote = createContextNoteEntry({
77
+ activeFrom: past,
78
+ expiresAt: null,
79
+ });
64
80
 
65
- await createContextNote(buildContextNote({
66
- clientId,
67
- product: "Municipal",
68
- notes: [activeNote, expiredNote, notYetActiveNote, noExpiryNote],
69
- }));
81
+ await createContextNote(
82
+ buildContextNote({
83
+ clientId,
84
+ product: "Municipal",
85
+ notes: [activeNote, expiredNote, notYetActiveNote, noExpiryNote],
86
+ }),
87
+ );
70
88
 
71
89
  const results = await getActiveContextNotes(clientId, "Municipal");
72
90
  expect(results).toHaveLength(2);
73
91
  expect(results.map((n) => n._id.toString())).toEqual(
74
- expect.arrayContaining([activeNote._id.toString(), noExpiryNote._id.toString()]),
92
+ expect.arrayContaining([
93
+ activeNote._id.toString(),
94
+ noExpiryNote._id.toString(),
95
+ ]),
75
96
  );
76
97
  });
77
98
 
78
99
  it("should replace the notes array on a document", async () => {
79
- const doc = buildContextNote({ notes: [createContextNoteEntry(), createContextNoteEntry()] });
100
+ const doc = buildContextNote({
101
+ notes: [createContextNoteEntry(), createContextNoteEntry()],
102
+ });
80
103
  const id = await createContextNote(doc);
81
104
 
82
105
  const newNotes = [createContextNoteEntry({ title: "updated" })];
@@ -94,11 +117,15 @@ describe("contextNotes getters", () => {
94
117
  });
95
118
 
96
119
  it("should store and retrieve a systemPrompt set at creation", async () => {
97
- const doc = buildContextNote({ systemPrompt: "Treat this information as highly reliable." });
120
+ const doc = buildContextNote({
121
+ systemPrompt: "Treat this information as highly reliable.",
122
+ });
98
123
  const id = await createContextNote(doc);
99
124
 
100
125
  const saved = await getContextNotesCollection().findOne({ _id: id });
101
- expect(saved?.systemPrompt).toBe("Treat this information as highly reliable.");
126
+ expect(saved?.systemPrompt).toBe(
127
+ "Treat this information as highly reliable.",
128
+ );
102
129
  });
103
130
 
104
131
  it("should not touch systemPrompt or product when setContextNoteEntries is called", async () => {
@@ -121,7 +148,9 @@ describe("contextNotes getters", () => {
121
148
  const doc = buildContextNote({ notes: [] });
122
149
  const id = await createContextNote(doc);
123
150
 
124
- const updated = await setContextNoteConfig(id, doc.clientId, { systemPrompt: "New instructions." });
151
+ const updated = await setContextNoteConfig(id, doc.clientId, {
152
+ systemPrompt: "New instructions.",
153
+ });
125
154
  expect(updated).toBe(true);
126
155
 
127
156
  const saved = await getContextNotesCollection().findOne({ _id: id });
@@ -132,7 +161,9 @@ describe("contextNotes getters", () => {
132
161
  const doc = buildContextNote({ product: "Municipal" });
133
162
  const id = await createContextNote(doc);
134
163
 
135
- const updated = await setContextNoteConfig(id, doc.clientId, { product: "Clinics" });
164
+ const updated = await setContextNoteConfig(id, doc.clientId, {
165
+ product: "Clinics",
166
+ });
136
167
  expect(updated).toBe(true);
137
168
 
138
169
  const saved = await getContextNotesCollection().findOne({ _id: id });
@@ -148,7 +179,9 @@ describe("contextNotes getters", () => {
148
179
  });
149
180
 
150
181
  it("should return false from setContextNoteConfig for a non-existent document", async () => {
151
- const result = await setContextNoteConfig(new ObjectId(), "nobody", { systemPrompt: "x" });
182
+ const result = await setContextNoteConfig(new ObjectId(), "nobody", {
183
+ systemPrompt: "x",
184
+ });
152
185
  expect(result).toBe(false);
153
186
  });
154
187
 
@@ -158,7 +191,11 @@ describe("contextNotes getters", () => {
158
191
  const doc = buildContextNote({ notes: [noteToKeep, noteToDelete] });
159
192
  const id = await createContextNote(doc);
160
193
 
161
- const deleted = await deleteContextNoteEntry(id, doc.clientId, noteToDelete._id);
194
+ const deleted = await deleteContextNoteEntry(
195
+ id,
196
+ doc.clientId,
197
+ noteToDelete._id,
198
+ );
162
199
  expect(deleted).toBe(true);
163
200
 
164
201
  const saved = await getContextNotesCollection().findOne({ _id: id });
@@ -170,7 +207,11 @@ describe("contextNotes getters", () => {
170
207
  const doc = buildContextNote({ notes: [] });
171
208
  const id = await createContextNote(doc);
172
209
 
173
- const result = await deleteContextNoteEntry(id, doc.clientId, new ObjectId());
210
+ const result = await deleteContextNoteEntry(
211
+ id,
212
+ doc.clientId,
213
+ new ObjectId(),
214
+ );
174
215
  expect(result).toBe(false);
175
216
  });
176
217
  });
@@ -11,9 +11,7 @@ export const getContextNotes = (
11
11
  clientId: string,
12
12
  product: string,
13
13
  ): Promise<WithId<ContextNote>[]> => {
14
- return getContextNotesCollection()
15
- .find({ clientId, product })
16
- .toArray();
14
+ return getContextNotesCollection().find({ clientId, product }).toArray();
17
15
  };
18
16
 
19
17
  /** Returns all currently active note entries across matching documents */
@@ -61,7 +59,8 @@ export const setContextNoteConfig = async (
61
59
  config: { systemPrompt?: string; product?: string },
62
60
  ): Promise<boolean> => {
63
61
  const fields: Partial<ContextNote> = {};
64
- if (config.systemPrompt !== undefined) fields.systemPrompt = config.systemPrompt;
62
+ if (config.systemPrompt !== undefined)
63
+ fields.systemPrompt = config.systemPrompt;
65
64
  if (config.product !== undefined) fields.product = config.product;
66
65
  if (!Object.keys(fields).length) return false;
67
66
 
@@ -43,6 +43,7 @@ export const flowMongoSchema = {
43
43
  },
44
44
  additionalProperties: false,
45
45
  },
46
+ useRedisTranscription: { bsonType: "bool" },
46
47
  interactions: {
47
48
  bsonType: "array",
48
49
  items: {
@@ -167,6 +167,8 @@ export type Flow = {
167
167
 
168
168
  insights: string[];
169
169
  conversationSettings?: ConversationSettings;
170
+ /** When true, prefer cached transcription from Redis (default: false). */
171
+ useRedisTranscription?: boolean;
170
172
 
171
173
  interactions: Interaction[];
172
174
 
@@ -41,5 +41,4 @@ describe("products getters", () => {
41
41
  const saved = results.find((p) => p._id.equals(id));
42
42
  expect(saved?.displayName).toBeUndefined();
43
43
  });
44
-
45
44
  });
@@ -13,7 +13,9 @@ export const contextNoteEntryFactory = Factory.define<ContextNoteEntry>(() => ({
13
13
  updatedAt: new Date(),
14
14
  }));
15
15
 
16
- export const contextNoteFactory = Factory.define<ContextNote & { _id: ObjectId }>(() => ({
16
+ export const contextNoteFactory = Factory.define<
17
+ ContextNote & { _id: ObjectId }
18
+ >(() => ({
17
19
  _id: new ObjectId(),
18
20
  clientId: faker.string.uuid(),
19
21
  product: "Municipal",
@@ -23,11 +25,16 @@ export const contextNoteFactory = Factory.define<ContextNote & { _id: ObjectId }
23
25
  export function createContextNoteEntry(
24
26
  overrides?: Partial<ContextNoteEntry>,
25
27
  ): ContextNoteEntry {
26
- return { ...contextNoteEntryFactory.build(), ...overrides } as ContextNoteEntry;
28
+ return {
29
+ ...contextNoteEntryFactory.build(),
30
+ ...overrides,
31
+ } as ContextNoteEntry;
27
32
  }
28
33
 
29
34
  export function createContextNote(
30
35
  overrides?: Partial<ContextNote>,
31
36
  ): ContextNote & { _id: ObjectId } {
32
- return { ...contextNoteFactory.build(), ...overrides } as ContextNote & { _id: ObjectId };
37
+ return { ...contextNoteFactory.build(), ...overrides } as ContextNote & {
38
+ _id: ObjectId;
39
+ };
33
40
  }
@@ -13,6 +13,7 @@ export const flowFactory = Factory.define<Flow & { _id: ObjectId }>(() => {
13
13
  initialSentence: faker.lorem.sentence(),
14
14
  insights: [],
15
15
  interactions: [],
16
+ useRedisTranscription: false,
16
17
  createdAt: now,
17
18
  updatedAt: now,
18
19
  };
@@ -31,7 +31,8 @@ export const toUtcDate = (dateStr: string): Date =>
31
31
  new Date(`${dateStr}T00:00:00.000Z`);
32
32
 
33
33
  /** Formats a date as a `YYYY-MM-DD` string in UTC. */
34
- export const formatDate = (date: Date): string => date.toISOString().slice(0, 10);
34
+ export const formatDate = (date: Date): string =>
35
+ date.toISOString().slice(0, 10);
35
36
 
36
37
  /** Adds `days` to a `YYYY-MM-DD` string, returning the resulting `YYYY-MM-DD`. */
37
38
  export const addDaysToDateStr = (dateStr: string, days: number): string =>
@@ -76,9 +77,10 @@ export const getYmdInTz = (date: Date, timezone: string) => {
76
77
  /** Weekday index (Sun = 0) of a date in the given timezone. */
77
78
  export const getWeekdayInTz = (date: Date, timezone: string): number =>
78
79
  WEEKDAY[
79
- new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short" }).format(
80
- date,
81
- )
80
+ new Intl.DateTimeFormat("en-US", {
81
+ timeZone: timezone,
82
+ weekday: "short",
83
+ }).format(date)
82
84
  ] ?? 0;
83
85
 
84
86
  /**
@@ -94,7 +96,10 @@ export const dateAtNoonUtc = (dateStr: string): Date => {
94
96
  * UTC instant at the start of the given `YYYY-MM-DD` calendar day in `timezone`.
95
97
  * Binary-searches the boundary so it stays correct across DST transitions.
96
98
  */
97
- export const startOfCalendarDayInTz = (dateStr: string, timezone: string): Date => {
99
+ export const startOfCalendarDayInTz = (
100
+ dateStr: string,
101
+ timezone: string,
102
+ ): Date => {
98
103
  const anchor = dateAtNoonUtc(dateStr).getTime();
99
104
  let low = anchor - 2 * DAY_MS;
100
105
  let high = anchor + DAY_MS;
@@ -109,8 +114,13 @@ export const startOfCalendarDayInTz = (dateStr: string, timezone: string): Date
109
114
  };
110
115
 
111
116
  /** UTC instant at the last millisecond of the given calendar day in `timezone`. */
112
- export const endOfCalendarDayInTz = (dateStr: string, timezone: string): Date => {
117
+ export const endOfCalendarDayInTz = (
118
+ dateStr: string,
119
+ timezone: string,
120
+ ): Date => {
113
121
  const [y, m, d] = parseYmd(dateStr);
114
- const nextDay = new Date(Date.UTC(y, m - 1, d + 1)).toISOString().slice(0, 10);
122
+ const nextDay = new Date(Date.UTC(y, m - 1, d + 1))
123
+ .toISOString()
124
+ .slice(0, 10);
115
125
  return new Date(startOfCalendarDayInTz(nextDay, timezone).getTime() - 1);
116
126
  };
package/README_OLD.md DELETED
@@ -1,160 +0,0 @@
1
- # @talkpilot/core-db
2
-
3
- [NPM Version](https://www.npmjs.com/package/@talkpilot/core-db)
4
-
5
- A TypeScript-based core database management package designed to provide centralized database connections, ORM integrations, and client utilities for other projects. This package manages connections to both **TalkPilot** and **Municipal** MongoDB databases.
6
-
7
- ## Features
8
-
9
- - 🚀 **Multi-Domain Database Management**: Centralized handlers for both TalkPilot and Municipal Data domains.
10
- - 📦 **Reusable Getters**: Standardized functions for fetching data from various collections (calls, agents, leads, cities, etc.).
11
- - 🏗️ **Type-safe**: Built with TypeScript for full type safety across all your database interactions.
12
- - 🛠️ **Environment Aware**: Configurable via environment variables or explicit parameters.
13
-
14
- ## Installation
15
-
16
- This package is intended to be used as a dependency in other projects. If you're working locally, you can install it using a file path:
17
-
18
- ```bash
19
- # In your other project:
20
- npm install /path/to/core-db
21
- # or if published to a registry:
22
- npm install @talkpilot/core-db
23
- # or via GitHub
24
- npm install github:talkpilot/core-db
25
- ```
26
-
27
- ## Quick Start
28
-
29
- ### 1. Initialize Database Connections
30
-
31
- You must initialize the database clients before using any of the getters.
32
-
33
- ```typescript
34
- import { mongodbClient, municipalDataMongodbClient } from '@talkpilot/core-db';
35
-
36
- async function bootstrap() {
37
- // Initialize TalkPilot DB
38
- await mongodbClient.connect(process.env.TALKPILOT_MONGO_URI);
39
-
40
- // Initialize Municipal Data DB (optional)
41
- await municipalDataMongodbClient.connect(process.env.MUNICIPAL_MONGO_URI);
42
- }
43
-
44
- bootstrap().catch(console.error);
45
- ```
46
-
47
- ### 2. Using Getters
48
-
49
- Once initialized, you can import and use any of the exported database getters.
50
-
51
- ```typescript
52
- import { findAgents, findCities } from '@talkpilot/core-db';
53
-
54
- async function getSummary() {
55
- // Get all agents from TalkPilot DB
56
- const agents = await findAgents();
57
- console.log('Total Agents:', agents.length);
58
-
59
- // Get all cities from Municipal Data DB
60
- const cities = await findCities();
61
- console.log('Total Cities:', cities.length);
62
- }
63
- ```
64
-
65
- ## Available Domains
66
-
67
- The package exports two main sets of tools:
68
-
69
- ### TalkPilot Domain
70
-
71
- Includes access to:
72
-
73
- - `agents`, `calls`, `clients`, `flows`, `leads`, `phone_numbers`, `plans`, `results`, `sessions`, `subscriptions`, etc.
74
- - Exported as root level functions or via `mongodbClient`.
75
-
76
- ### Municipal Domain
77
-
78
- Includes access to:
79
-
80
- - `cities`, `streets`, `departmentsSubjects`, `tickets`.
81
- - Functions are prefixed where necessary or accessible via `getMunicipalDataDb`.
82
-
83
- ## Environment Variables
84
-
85
- The clients will automatically attempt to use the following environment variables if no URI is provided to the `connect()` method:
86
-
87
- - `MONGO_URI` or `MONGODB_URI`: Primary MongoDB connection string.
88
- - `MONGODB_DB_NAME`: Database name (defaults to 'municipal-data' for the municipal client if not specified).
89
-
90
- ## Development
91
-
92
- ### Setup
93
-
94
- 1. Clone the repository and install dependencies:
95
- ```bash
96
- git clone https://github.com/talkpilot/core-db.git
97
- cd core-db
98
- npm install
99
- ```
100
- 2. Build the project:
101
- ```bash
102
- npm run build
103
- ```
104
-
105
- This will generate the `dist/` directory with the compiled JavaScript and type definitions.
106
-
107
- ### Publishing New Versions
108
-
109
- To publish a new version of the package:
110
-
111
- 1. **Test your changes**:
112
- ```bash
113
- npm test
114
- ```
115
- 2. **Update the version**:
116
- ```bash
117
- # Bumps patch version (0.1.0 -> 0.1.1)
118
- npm version patch
119
- # Or for minor changes (0.1.0 -> 0.2.0)
120
- # npm version minor
121
- # Or for major changes (0.1.0 -> 1.0.0)
122
- # npm version major
123
- ```
124
- 3. **Publish to npm**:
125
- Ensure you have the shared team token in your `~/.npmrc` (see [Development Guide](./DEVELOPMENT.md#team-access--authentication)).
126
- 4. **Update in other repos**:
127
- ```bash
128
- npm update @talkpilot/core-db
129
- ```
130
-
131
- ## License
132
-
133
- MIT
134
-
135
- ---
136
-
137
- **Interested in contributing?** Check out our [Development Guide](./DEVELOPMENT.md) for standards and setup instructions.
138
-
139
- ## Release Notes
140
-
141
- ### 1.1.9
142
-
143
- - `getPhoneNumbersForFlows(clientId)` — lists each phone number linked to a flow for that client (newest first), with `flowId`, `phoneNumber`, and `isPrimary`.
144
- ### 1.1.5
145
-
146
- - `createPurchasedPhoneNumber` for API-bought numbers (Twilio/Telnyx metadata); optional `flowId` until linked to a flow. Types/schema updated accordingly.
147
-
148
- ### 1.0.16
149
-
150
- - Fixed critical issues present in version 1.0.15.
151
- - **Warning**: Version 1.0.15 is bugged and should not be used. Please use at least version 1.0.16.
152
-
153
- ### 1.0.20
154
-
155
- - Added to Moked106Config this param: withNeedAttentionCalls
156
- - withNeedAttentionCalls?: boolean
157
-
158
- ### 1.0.27
159
- - Added an optional `language` field to `ClientConfig` (e.g. Hebrew/English/Russian/French/Spanish) and updated tests.
160
-