@talkpilot/core-db 1.3.12 → 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 (45) hide show
  1. package/.cursor/rules/development.mdc +65 -65
  2. package/DEVELOPMENT.md +141 -141
  3. package/README.md +307 -297
  4. package/dist/municipal/tickets/tickets.statistics.getters.d.ts.map +1 -1
  5. package/dist/municipal/tickets/tickets.statistics.getters.js +6 -2
  6. package/dist/municipal/tickets/tickets.statistics.getters.js.map +1 -1
  7. package/dist/talkpilot/flows/flows.schema.d.ts +3 -0
  8. package/dist/talkpilot/flows/flows.schema.d.ts.map +1 -1
  9. package/dist/talkpilot/flows/flows.schema.js +1 -0
  10. package/dist/talkpilot/flows/flows.schema.js.map +1 -1
  11. package/dist/talkpilot/flows/flows.types.d.ts +2 -0
  12. package/dist/talkpilot/flows/flows.types.d.ts.map +1 -1
  13. package/dist/talkpilot/subscriptions/subscriptions.utils.d.ts +4 -0
  14. package/dist/talkpilot/subscriptions/subscriptions.utils.d.ts.map +1 -0
  15. package/dist/talkpilot/subscriptions/subscriptions.utils.js +20 -0
  16. package/dist/talkpilot/subscriptions/subscriptions.utils.js.map +1 -0
  17. package/dist/test-utils/factories/talkpilot/flows.d.ts.map +1 -1
  18. package/dist/test-utils/factories/talkpilot/flows.js +1 -0
  19. package/dist/test-utils/factories/talkpilot/flows.js.map +1 -1
  20. package/jest.config.js +20 -20
  21. package/package.json +46 -46
  22. package/src/municipal/muniIssues/__tests__/muniIssues.setters.spec.ts +94 -94
  23. package/src/municipal/tickets/__tests__/tickets.statistics.spec.ts +99 -99
  24. package/src/municipal/tickets/index.ts +9 -9
  25. package/src/municipal/tickets/tickets.statistics.aggregation.ts +110 -110
  26. package/src/municipal/tickets/tickets.statistics.getters.ts +145 -132
  27. package/src/municipal/tickets/tickets.types.ts +54 -54
  28. package/src/talkpilot/calls/__tests__/calls.statistics.spec.ts +483 -481
  29. package/src/talkpilot/calls/calls.statistics.getters.ts +668 -668
  30. package/src/talkpilot/calls/calls.statistics.types.ts +48 -48
  31. package/src/talkpilot/clientsConfig/clientsConfig.types.ts +127 -127
  32. package/src/talkpilot/contextNotes/__tests__/contextNotes.getters.spec.ts +217 -217
  33. package/src/talkpilot/contextNotes/contextNotes.getters.ts +85 -85
  34. package/src/talkpilot/flows/flows.schema.ts +1 -0
  35. package/src/talkpilot/flows/flows.types.ts +2 -0
  36. package/src/talkpilot/products/__tests__/products.getters.spec.ts +44 -44
  37. package/src/test-utils/factories/talkpilot/contextNotes.ts +40 -40
  38. package/src/test-utils/factories/talkpilot/flows.ts +1 -0
  39. package/src/utils/date.utils.ts +126 -126
  40. package/tsconfig.json +23 -23
  41. package/README_OLD.md +0 -160
  42. package/dist/talkpilot/calls/calls.dashboard.d.ts +0 -3
  43. package/dist/talkpilot/calls/calls.dashboard.d.ts.map +0 -1
  44. package/dist/talkpilot/calls/calls.dashboard.js +0 -191
  45. package/dist/talkpilot/calls/calls.dashboard.js.map +0 -1
package/README.md CHANGED
@@ -1,297 +1,307 @@
1
- L1:# @talkpilot/core-db
2
-
3
- `@talkpilot/core-db` is the shared TypeScript database package that wires TalkPilot APIs, municipal CRM integrations, and internal tools to a single, type-safe MongoDB surface. Every repo (MIS, CIS, TalkPilot Server, etc.) imports this package to avoid re-implementing connections, collections, or validation helpers.
4
-
5
- ## Purpose
6
-
7
- - Provide a reliable, multi-domain MongoDB layer for TalkPilot and municipal data.
8
- - Export typed getters, vector search helpers, and document factories so services can focus on behavior instead of schema wiring.
9
- - Manage connection lifecycles, environment configuration, and test helpers from one place so every repo reuses the same plumbing.
10
-
11
- ## Main Concepts
12
-
13
- - **Multi-domain clients** – `src/connection.ts` exposes `mongodbClient` (TalkPilot) and `municipalDataMongodbClient`, each of which resolves `MONGO_URI`, DB overrides, and default names.
14
- - **Domain-specific getters** – `src/talkpilot/` and `src/municipal/` host typed getters (agents, calls, streets, tickets, etc.), vector-search helpers, and service-friendly adapters that keep caller code DRY.
15
- - **Product-specific clients (future)** – While the package currently exposes the shared TalkPilot + municipal clients, we expect each product (CIS, MIS, TalkPilot Server) to eventually get its own domain-specific client helpers or wrappers so the shared core can remain stable while new consumers add targeted extensions.
16
- - **Test helpers** – `src/test-utils/` plus `src/__tests__/` reuse `MongoMemoryServer` and shared factories so tests start with clean data regardless of the consuming repo.
17
- - **Utility layers** – `src/utils/` contains shared validation, pagination, and environment helpers that complement the getters.
18
- - **Environment awareness** – Defaults, fallbacks, and `process.env` lookups ensure local, CI, and Cloud Run clients all connect using the right URI/DB names.
19
-
20
- ## Key Components
21
-
22
- - `src/connection.ts` – Central connection logic that resolves URIs/DB names from env vars (`MONGO_URI`, `MONGODB_URI`, `TALKPILOT_DB_NAME`, `MUNICIPAL_DB_NAME`) and reuses a single `MongoClient`.
23
- - `src/talkpilot/`Call history, agents, flows, sessions, leads, subscriptions, and support helpers exposed as getters plus helper enums/types for each collection.
24
- - `src/municipal/` – Municipal-specific collections (`cities`, `streets`, `departmentsSubjects`, `tickets`, etc.) plus vector search helpers and Ash Bina helpers used by MIS.
25
- - `src/utils/` – Shared helpers such as `resolveConnection`, pagination utilities, and schema validation helper functions.
26
- - `src/test-utils/` and `src/__tests__/` Utilities that bootstrap `MongoMemoryServer`, expose factories, and make sure Jest environments can stub database calls predictably.
27
- - `dist/` – Compiled output consumed by downstream repos (CJS + ESM + type defs).
28
-
29
- ## Domain APIs
30
-
31
- - **TalkPilot domain** – Imports like `findAgents`, `getFlows`, `findCalls`, and `vectorSearchCalls` live in `src/talkpilot`. These functions are the canonical access pattern for call history, session metadata, and provider configs.
32
- - **Municipal domain** – Helpers such as `findStreets`, `getMunicipalCities`, `findDepartmentSubjects`, and `createTicket` live under `src/municipal` and feed MIS workflows (street hints, subject matching, Ash Bina tickets).
33
-
34
- ## Environment variables
35
-
36
- | Variable | Purpose | Required |
37
- |---------------------------|--------------------------------------------------------------------------------------|----------|
38
- | `MONGO_URI` | Primary MongoDB connection string for every domain (overridden by `MONGODB_URI`). | ✅ |
39
- | `MONGODB_URI` | Alternate connection string used when Mongo needs a second URI parameter. | ✅ |
40
- | `TALKPILOT_DB_NAME` | Optional override for the TalkPilot database name (defaults from URI path). | |
41
- | `MUNICIPAL_DB_NAME` | Optional override for the municipal database name (defaults to `municipal-data`). | ❌ |
42
- | `ENV` | Free-form label used in logs/validators (defaults to `unknown`). | ❌ |
43
-
44
- If you pass a `uri` directly to `mongodbClient.connect()` or `municipalDataMongodbClient.connect()`, the client will prefer that value over the env vars.
45
-
46
- ## Getting Started
47
-
48
- ### Prerequisites
49
-
50
- - Node.js 22.x+ (aligns with downstream services).
51
- - npm 11+ or Yarn.
52
- - MongoDB accessible from your environment or a `MongoMemoryServer` for tests.
53
-
54
- ### Setup
55
-
56
- 1. Clone the repo and install dependencies:
57
-
58
- ```bash
59
- git clone https://github.com/talkpilot/core-db.git
60
- cd core-db
61
- npm install
62
- ```
63
-
64
- 2. Build the package before using it locally:
65
-
66
- ```bash
67
- npm run build
68
- ```
69
-
70
- 3. Import `@talkpilot/core-db` from another project by pointing `package.json` at the local path during development or installing the published release.
71
-
72
- ## Sample `.env`
73
-
74
- ```
75
- MONGO_URI=mongodb://localhost:27017
76
- TALKPILOT_DB_NAME=talkpilot-dev
77
- MUNICIPAL_DB_NAME=municipal-dev
78
- ENV=development
79
- ```
80
-
81
- Adjust `MONGO_URI` to match the running Mongo instance and configure `talkpilot`/`municipal` DB names if you want to keep them separate.
82
-
83
- ## Local development
84
-
85
- 1. Run `npm install`.
86
- 2. Build the compiled output: `npm run build`.
87
- 3. Execute tests: `npm run test`.
88
- 4. Use `npm link` or `npm pack` to consume the freshly built package from other repos (`CIS`, `MIS`, `TalkPilot Server`).
89
-
90
- ## Development guide
91
-
92
- `DEVELOPMENT.md` contains the tactical steps for contributors. At a glance:
93
-
94
- - Node 18+/TypeScript is required (aligns with downstream services).
95
- - Run `npm install` `npm run build` after cloning.
96
- - Use `npm link`/`npm link @talkpilot/core-db` to test the package locally before publishing.
97
- - When adding getters, define types, implement the function, export it through the domain `index.ts`, and add a corresponding test under the domain’s `__tests__` folder.
98
- - Always rely on the provided test factories (`src/test-utils/factories`) to seed data so tests remain consistent.
99
- - Jest with `mongodb-memory-server` is the only execution path we have to verify this core utility—unit tests are the safety net for every change.
100
-
101
- Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and factory samples.
102
-
103
- ## 🧪 Testing
104
-
105
- - `npm run test` – Jest suite (factories, utils, integration mocks) powered by `mongodb-memory-server`.
106
- - Tests rely on `src/__tests__/setup.ts` to bootstrap the in-memory Mongo instances and wire shared factories/helpers before each run.
107
- - When adding getters, helpers, or domain logic, create focused coverage inside the consuming domain’s `__tests__/` folder and use the provided factories to keep fixtures consistent.
108
-
109
- `@talkpilot/core-db` does not run in a product UI or feature branch—unit tests are the *only* reliable execution path to ensure your changes work. Every change must ship with a unit test so downstream repos can upgrade without surprises; treat the test suite as the canonical safety net for this core utility package.
110
-
111
- ## 🧹 Lint & build verification
112
-
113
- - `npm run lint` – Run ESLint over `src/**/*.{ts,tsx}`.
114
- - `npm run format` – Format the source files with Prettier.
115
- - `npm run build` – Compile TypeScript and emit `dist/` (used by downstream consumers).
116
-
117
- ## ✅ Pre-push checklist
118
-
119
- 1. `npm run build`.
120
- 2. `npm run test`.
121
- 3. `npm run format`.
122
-
123
- ## Publishing & release notes
124
-
125
- - Releases are handled by `npm version <patch|minor|major>` followed by `npm publish`. The package is a **private `@talkpilot` dependency**, so every contributor must install the shared npm automation token into their global `~/.npmrc` before running publish or `npm install`.
126
- - The shared token is rotated periodically—if you see authentication failures, request the refreshed token, update your `~/.npmrc`, and retry. Never commit credentials to source control.
127
- - After publishing, downstream repos (`CIS`, `MIS`, `TalkPilot Server`, etc.) should run `npm update @talkpilot/core-db` so they receive the latest helpers/bug fixes.
128
- - Cloud Build & Cloud Run jobs that depend on this package pick up the new version the next time they rebuild their container; the services pull the compiled `dist/` output and type definitions when installing the dependency.
129
-
130
- - Release process, when to publish, branch hygiene, and the function-signature versioning policy: see [`DEVELOPMENT.md`](./DEVELOPMENT.md).
131
-
132
- ### Version history
133
-
134
- | Version | Note |
135
- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
- | 1.1.9 | Maintenance release (build, test, format). |
137
- | 1.3.4 | Added new statistics getters for call & ticket dashboards (CP-149): summary, trend, hourly, and routing for calls, plus open/draft/subject ticket stats. **Removed** the legacy getters `getTicketsCountByCityAndDateRange` and `getTicketsSubjectStats`. |
138
- | 1.3.5 | Added the `muniIssues` collection & module (CP-1115): the `MuniIssue` document type, `createMuniIssue` (accepts a caller-supplied `_id` for a two-way Jira link), `generateMuniIssueId`, `getMuniIssueById` / `getMuniIssueByJiraKey`, a `$jsonSchema` validator with indexes (unique `jira.key`), and `ensureMuniIssuesCollection` to provision it at boot. |
139
- | 1.3.6 | Added `contextNotes` and `products` modules under `src/talkpilot/`. |
140
- | 1.3.7 | Added `disableGenericPrompt` optional boolean field to the `Flow` type and schema (CP-704). |
141
- | 1.3.8 | Ticket-count Map getters (CP-1200): deprecated `string[]` ticket getters and `CallsStatsFilter` fields, added `Map<string, number>` replacements; fixed ticket counting in `aggregateCallsSummary`. |
142
- | 1.3.9 | Fixed wrap-around hour filter boundary guards (CP-1166): excluded first-day morning calls and last-day evening calls from wrap-around windows. |
143
- | 1.3.10 | Added optional `isDraft` flag to `Ticket` (CP-1390): explicit draft marking with legacy fallback for existing tickets. |
144
- | 1.3.11 | Fixed pre-existing broken type declaration import in `clientsConfig.types.d.ts` that caused consumer `tsc` builds to fail. |
145
-
146
- | 1.3.12 | Added `callsWithTickets` to `CallsSummaryAggregation` (CP-1200): distinct call count with at least one open ticket, enabling accurate `ticketOpenRate` and `not_opened` calculations in consumers. |
147
- ### 1.1.9
148
-
149
- 1. `npm run build`.
150
- 2. `npm run test`.
151
- 3. `npm run format`.
152
-
153
- ### 1.3.4 Call & ticket statistics (CP-149)
154
-
155
- New call statistics getters for dashboards (summary, trend, hourly, routing) and ticket statistics scoped to the same date range (open tickets, draft tickets, subject breakdowns).
156
-
157
- **Removed**
158
-
159
- | Removed | Replacement |
160
- | --- | --- |
161
- | `getTicketsCountByCityAndDateRange` | `aggregateCallsSummary` + `findCallSidTicketCountsByCity` — note: returns `Map<string, number>`, not `string[]` |
162
- | `getTicketsSubjectStats` | `findSubjectsByCityAndDateRange` |
163
- | `SubjectStatsItem` | `SubjectItem` |
164
-
165
- **Do I need to update my app?**
166
-
167
- Yes if you used any of the removed functions above.
168
-
169
- ### 1.3.5 Muni issues (CP-1115)
170
-
171
- New `muniIssues` module under `src/municipal/` for issues reported from the call-log screen. The document is written to the municipal DB after its Jira ticket is created.
172
-
173
- **Added**
174
-
175
- | Export | Purpose |
176
- | --- | --- |
177
- | `MuniIssue` / `CreateMuniIssueInput` | Document type and insert-input type (`issueContent` + `jira` domains). |
178
- | `createMuniIssue(input, id)` | Insert an issue; requires a caller-supplied `_id` from MIS (via `generateMuniIssueId`) so it matches the id embedded in the Jira ticket (two-way link). |
179
- | `generateMuniIssueId()` | Pre-generate the `_id` to pass to `createMuniIssue`. |
180
- | `getMuniIssueById` / `getMuniIssueByJiraKey` | Lookups by our id or by the Jira key. |
181
- | `ensureMuniIssuesCollection()` | Provision the `$jsonSchema` validator and indexes (unique `jira.key`); run once at MIS boot. |
182
-
183
- **Do I need to update my app?**
184
-
185
- No purely additive. New consumers (MIS) import these from `@talkpilot/core-db`.
186
-
187
- ### 1.3.6 Context Notes & Products
188
-
189
- **Context Notes** — new `contextNotes` collection under `src/talkpilot/` for per-client, per-product notes injected into AI calls at runtime. Each document holds a `systemPrompt` and a list of time-bounded entries (`activeFrom`, `expiresAt`). Two setters with split ownership: `setContextNoteEntries` for the notes list and `setContextNoteConfig` for `systemPrompt` and `product`.
190
-
191
- **Products** — new `products` collection under `src/talkpilot/` cataloguing TalkPilot products. Each document has a stable `name` and an optional `displayName` locale map (`Record<string, string>`) for UI display.
192
-
193
- **Added**
194
-
195
- | Export | Purpose |
196
- | --- | --- |
197
- | `getContextNotes(clientId, product)` | Fetch context note documents for a client/product pair. |
198
- | `createContextNote(input)` | Insert a new context note document. |
199
- | `setContextNoteEntries(id, clientId, notes)` | Replace the notes list on an existing document. |
200
- | `setContextNoteConfig(id, clientId, config)` | Update `systemPrompt` and/or `product` on an existing document. |
201
- | `getAllProducts()` | Fetch the full product catalogue. |
202
-
203
- **Do I need to update my app?**
204
-
205
- No purely additive.
206
-
207
- ### 1.3.7 Generic prompt control (CP-704)
208
-
209
- Added an optional boolean field to the `Flow` type and MongoDB schema.
210
-
211
- **Added**
212
-
213
- | Export | Purpose |
214
- | --- | --- |
215
- | `Flow.disableGenericPrompt` | Optional `boolean`. When `true`, disables the generic prompt for the flow. Existing flows without this field continue to work unchanged. |
216
-
217
- **Do I need to update my app?**
218
-
219
- No the field is optional and fully backwards-compatible.
220
-
221
- ### 1.3.8 Ticket-count Map getters (CP-1200)
222
-
223
- Adds `Map<string, number>` ticket getters that return per-call ticket counts. The old `string[]` getters and filter fields are kept and marked `@deprecated`.
224
-
225
- **Deprecated Replacement**
226
-
227
- | Deprecated | Replacement |
228
- | --- | --- |
229
- | `findCallSidsWithTicketsByCity` | `findCallSidTicketCountsByCity` → `Map<string, number>` |
230
- | `findCallSidsWithDraftTicketsByCity` | `findCallSidDraftTicketCountsByCity` → `Map<string, number>` |
231
- | `CallsStatsFilter.callSidsWithTickets` | `CallsStatsFilter.callSidTicketCounts` |
232
- | `CallsStatsFilter.callSidsWithDraftTickets` | `CallsStatsFilter.callSidDraftTicketCounts` |
233
-
234
- **Do I need to update my app?**
235
-
236
- No the old fields still compile. Migrate when convenient.
237
-
238
- ### 1.3.9 Wrap-around hour filter boundary guards (CP-1166)
239
-
240
- When `hourFrom` > `hourTo` (e.g. 23:00–13:00), two silent miscounting bugs existed:
241
-
242
- - **First-day morning**: calls before `hourTo` on the first day (e.g. 08:00 on Jun 8) were counted even though the window starts at `hourFrom` that day. Fixed by adding `dateLocal > startStr` to the after-midnight leg.
243
- - **Last-day evening**: calls at or after `hourFrom` on the last day (e.g. 23:30 on Jun 9) were counted even though the window ends at `hourTo` that day. Fixed by adding `dateLocal < endStr` to the before-midnight leg.
244
-
245
- **Affects:** `aggregateCallsTrend`, `aggregateCallsSummary`, `aggregateCallsHourlyByRange`, `aggregateCallsRouting`, `findFilteredCallSids`, `findSubjectsByCityAndDateRange`.
246
-
247
- **Do I need to update my app?**
248
-
249
- No API changes both fixes correct silent miscounting. Upgrading is recommended if you use a wrap-around hour window.
250
-
251
- ### 1.3.10Ticket draft flag (CP-1390)
252
-
253
- Added an optional `isDraft` boolean field to the `Ticket` type.
254
-
255
- **Added**
256
-
257
- | Export | Purpose |
258
- | --- | --- |
259
- | `Ticket.isDraft` | Optional `boolean`. When `true`, the ticket is a draft. When `false`, it is not. When absent (legacy tickets), draft detection falls back to the previous `event_subject_id` heuristic. |
260
-
261
- **Affects:** `findCallSidDraftTicketCountsByCity`, `findCallSidsWithDraftTicketsByCity` (draft filtering in ticket statistics).
262
-
263
- **Do I need to update my app?**
264
-
265
- No purely additive. Existing tickets without `isDraft` continue to work unchanged. New consumers (MIS) can pass `isDraft: true` when creating a draft ticket.
266
-
267
- ### 1.3.11 Fix clientsConfig type declaration import
268
-
269
- Fixed a pre-existing broken import path in the published `clientsConfig.types.d.ts` (introduced in an earlier release, unrelated to 1.3.10). Consumer TypeScript builds could fail with:
270
-
271
- `Cannot find module 'src/utils/shared.types' or its corresponding type declarations.`
272
-
273
- The import now uses a relative path (`../../utils/shared.types`) so `tsc` resolves it correctly from `node_modules/@talkpilot/core-db/dist/`.
274
-
275
- **Do I need to update my app?**
276
-
277
- Yes upgrade to 1.3.11 if your build failed with the error above (affects any version that shipped the broken declaration). No API or behavior changes otherwise.
278
-
279
- ### 1.3.12 Calls-with-tickets count (CP-1200)
280
-
281
- Added `callsWithTickets` to `CallsSummaryAggregation` the number of distinct calls that opened at least one ticket. Use this field (instead of `openTickets`) to compute call-level rates and "calls without a ticket" counts.
282
-
283
- **Do I need to update my app?**
284
-
285
- Yes replace `openTickets` with `callsWithTickets` wherever you compute `ticketOpenRate` or `not_opened`.
286
-
287
-
288
- ## 🛠 CI/CD & deployment
289
-
290
- - 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.
291
- - Releases require the shared npm token documented in `DEVELOPMENT.md`; consult that guide for contribution, linking, and token rotation procedures.
292
-
293
- ## Resources
294
-
295
- - [DEVELOPMENT.md](./DEVELOPMENT.md) (setup, tooling, publishing, token management)
296
- - [src/test-utils](src/test-utils) and the `__tests__` folder for examples of `MongoMemoryServer` wiring.
297
-
1
+ L1:# @talkpilot/core-db
2
+
3
+ [NPM Version](https://www.npmjs.com/package/@talkpilot/core-db)
4
+ `@talkpilot/core-db` is the shared TypeScript database package that wires TalkPilot APIs, municipal CRM integrations, and internal tools to a single, type-safe MongoDB surface. Every repo (MIS, CIS, TalkPilot Server, etc.) imports this package to avoid re-implementing connections, collections, or validation helpers.
5
+
6
+ ## Purpose
7
+
8
+ - Provide a reliable, multi-domain MongoDB layer for TalkPilot and municipal data.
9
+ - Export typed getters, vector search helpers, and document factories so services can focus on behavior instead of schema wiring.
10
+ - Manage connection lifecycles, environment configuration, and test helpers from one place so every repo reuses the same plumbing.
11
+
12
+ ## Main Concepts
13
+
14
+ - **Multi-domain clients** – `src/connection.ts` exposes `mongodbClient` (TalkPilot) and `municipalDataMongodbClient`, each of which resolves `MONGO_URI`, DB overrides, and default names.
15
+ - **Domain-specific getters** – `src/talkpilot/` and `src/municipal/` host typed getters (agents, calls, streets, tickets, etc.), vector-search helpers, and service-friendly adapters that keep caller code DRY.
16
+ - **Product-specific clients (future)** – While the package currently exposes the shared TalkPilot + municipal clients, we expect each product (CIS, MIS, TalkPilot Server) to eventually get its own domain-specific client helpers or wrappers so the shared core can remain stable while new consumers add targeted extensions.
17
+ - **Test helpers** – `src/test-utils/` plus `src/__tests__/` reuse `MongoMemoryServer` and shared factories so tests start with clean data regardless of the consuming repo.
18
+ - **Utility layers** – `src/utils/` contains shared validation, pagination, and environment helpers that complement the getters.
19
+ - **Environment awareness** – Defaults, fallbacks, and `process.env` lookups ensure local, CI, and Cloud Run clients all connect using the right URI/DB names.
20
+
21
+ ## Key Components
22
+
23
+ - `src/connection.ts`Central connection logic that resolves URIs/DB names from env vars (`MONGO_URI`, `MONGODB_URI`, `TALKPILOT_DB_NAME`, `MUNICIPAL_DB_NAME`) and reuses a single `MongoClient`.
24
+ - `src/talkpilot/` – Call history, agents, flows, sessions, leads, subscriptions, and support helpers exposed as getters plus helper enums/types for each collection.
25
+ - `src/municipal/` – Municipal-specific collections (`cities`, `streets`, `departmentsSubjects`, `tickets`, etc.) plus vector search helpers and Ash Bina helpers used by MIS.
26
+ - `src/utils/` Shared helpers such as `resolveConnection`, pagination utilities, and schema validation helper functions.
27
+ - `src/test-utils/` and `src/__tests__/` Utilities that bootstrap `MongoMemoryServer`, expose factories, and make sure Jest environments can stub database calls predictably.
28
+ - `dist/` – Compiled output consumed by downstream repos (CJS + ESM + type defs).
29
+
30
+ ## Domain APIs
31
+
32
+ - **TalkPilot domain** – Imports like `findAgents`, `getFlows`, `findCalls`, and `vectorSearchCalls` live in `src/talkpilot`. These functions are the canonical access pattern for call history, session metadata, and provider configs.
33
+ - **Municipal domain** – Helpers such as `findStreets`, `getMunicipalCities`, `findDepartmentSubjects`, and `createTicket` live under `src/municipal` and feed MIS workflows (street hints, subject matching, Ash Bina tickets).
34
+
35
+ ## Environment variables
36
+
37
+ | Variable | Purpose | Required |
38
+ |---------------------|-----------------------------------------------------------------------------------|----------|
39
+ | `MONGO_URI` | Primary MongoDB connection string for every domain (overridden by `MONGODB_URI`). | ✅ |
40
+ | `MONGODB_URI` | Alternate connection string used when Mongo needs a second URI parameter. | |
41
+ | `TALKPILOT_DB_NAME` | Optional override for the TalkPilot database name (defaults from URI path). | ❌ |
42
+ | `MUNICIPAL_DB_NAME` | Optional override for the municipal database name (defaults to `municipal-data`). | ❌ |
43
+ | `ENV` | Free-form label used in logs/validators (defaults to `unknown`). | ❌ |
44
+
45
+ If you pass a `uri` directly to `mongodbClient.connect()` or `municipalDataMongodbClient.connect()`, the client will prefer that value over the env vars.
46
+
47
+ ## Getting Started
48
+
49
+ ### Prerequisites
50
+
51
+ - Node.js 22.x+ (aligns with downstream services).
52
+ - npm 11+ or Yarn.
53
+ - MongoDB accessible from your environment or a `MongoMemoryServer` for tests.
54
+
55
+ ### Setup
56
+
57
+ 1. Clone the repo and install dependencies:
58
+
59
+ ```bash
60
+ git clone https://github.com/talkpilot/core-db.git
61
+ cd core-db
62
+ npm install
63
+ ```
64
+
65
+ 2. Build the package before using it locally:
66
+
67
+ ```bash
68
+ npm run build
69
+ ```
70
+
71
+ 3. Import `@talkpilot/core-db` from another project by pointing `package.json` at the local path during development or installing the published release.
72
+
73
+ ## Sample `.env`
74
+
75
+ ```
76
+ MONGO_URI=mongodb://localhost:27017
77
+ TALKPILOT_DB_NAME=talkpilot-dev
78
+ MUNICIPAL_DB_NAME=municipal-dev
79
+ ENV=development
80
+ ```
81
+
82
+ Adjust `MONGO_URI` to match the running Mongo instance and configure `talkpilot`/`municipal` DB names if you want to keep them separate.
83
+
84
+ ## Local development
85
+
86
+ 1. Run `npm install`.
87
+ 2. Build the compiled output: `npm run build`.
88
+ 3. Execute tests: `npm run test`.
89
+ 4. Use `npm link` or `npm pack` to consume the freshly built package from other repos (`CIS`, `MIS`, `TalkPilot Server`).
90
+
91
+ ## Development guide
92
+
93
+ `DEVELOPMENT.md` contains the tactical steps for contributors. At a glance:
94
+
95
+ - Node 18+/TypeScript is required (aligns with downstream services).
96
+ - Run `npm install` `npm run build` after cloning.
97
+ - Use `npm link`/`npm link @talkpilot/core-db` to test the package locally before publishing.
98
+ - When adding getters, define types, implement the function, export it through the domain `index.ts`, and add a corresponding test under the domain’s `__tests__` folder.
99
+ - Always rely on the provided test factories (`src/test-utils/factories`) to seed data so tests remain consistent.
100
+ - Jest with `mongodb-memory-server` is the only execution path we have to verify this core utility—unit tests are the safety net for every change.
101
+
102
+ Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and factory samples.
103
+
104
+ ## 🧪 Testing
105
+
106
+ - `npm run test` Jest suite (factories, utils, integration mocks) powered by `mongodb-memory-server`.
107
+ - Tests rely on `src/__tests__/setup.ts` to bootstrap the in-memory Mongo instances and wire shared factories/helpers before each run.
108
+ - When adding getters, helpers, or domain logic, create focused coverage inside the consuming domain’s `__tests__/` folder and use the provided factories to keep fixtures consistent.
109
+
110
+ `@talkpilot/core-db` does not run in a product UI or feature branch—unit tests are the *only* reliable execution path to ensure your changes work. Every change must ship with a unit test so downstream repos can upgrade without surprises; treat the test suite as the canonical safety net for this core utility package.
111
+
112
+ ## 🧹 Lint & build verification
113
+
114
+ - `npm run lint` – Run ESLint over `src/**/*.{ts,tsx}`.
115
+ - `npm run format` – Format the source files with Prettier.
116
+ - `npm run build` – Compile TypeScript and emit `dist/` (used by downstream consumers).
117
+
118
+ ## ✅ Pre-push checklist
119
+
120
+ 1. `npm run build`.
121
+ 2. `npm run test`.
122
+ 3. `npm run format`.
123
+
124
+ ## Publishing & release notes
125
+
126
+ - Releases are handled by `npm version <patch|minor|major>` followed by `npm publish`. The package is a **private `@talkpilot` dependency**, so every contributor must install the shared npm automation token into their global `~/.npmrc` before running publish or `npm install`.
127
+ - The shared token is rotated periodically—if you see authentication failures, request the refreshed token, update your `~/.npmrc`, and retry. Never commit credentials to source control.
128
+ - After publishing, downstream repos (`CIS`, `MIS`, `TalkPilot Server`, etc.) should run `npm update @talkpilot/core-db` so they receive the latest helpers/bug fixes.
129
+ - Cloud Build & Cloud Run jobs that depend on this package pick up the new version the next time they rebuild their container; the services pull the compiled `dist/` output and type definitions when installing the dependency.
130
+
131
+ - Release process, when to publish, branch hygiene, and the function-signature versioning policy: see [`DEVELOPMENT.md`](./DEVELOPMENT.md).
132
+
133
+ ### Version history
134
+
135
+ | Version | Note |
136
+ |---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
137
+ | 1.1.9 | Maintenance release (build, test, format). |
138
+ | 1.3.4 | Added new statistics getters for call & ticket dashboards (CP-149): summary, trend, hourly, and routing for calls, plus open/draft/subject ticket stats. **Removed** the legacy getters `getTicketsCountByCityAndDateRange` and `getTicketsSubjectStats`. |
139
+ | 1.3.5 | Added the `muniIssues` collection & module (CP-1115): the `MuniIssue` document type, `createMuniIssue` (accepts a caller-supplied `_id` for a two-way Jira link), `generateMuniIssueId`, `getMuniIssueById` / `getMuniIssueByJiraKey`, a `$jsonSchema` validator with indexes (unique `jira.key`), and `ensureMuniIssuesCollection` to provision it at boot. |
140
+ | 1.3.6 | Added `contextNotes` and `products` modules under `src/talkpilot/`. |
141
+ | 1.3.7 | Added `disableGenericPrompt` optional boolean field to the `Flow` type and schema (CP-704). |
142
+ | 1.3.8 | Ticket-count Map getters (CP-1200): deprecated `string[]` ticket getters and `CallsStatsFilter` fields, added `Map<string, number>` replacements; fixed ticket counting in `aggregateCallsSummary`. |
143
+ | 1.3.9 | Fixed wrap-around hour filter boundary guards (CP-1166): excluded first-day morning calls and last-day evening calls from wrap-around windows. |
144
+ | 1.3.10 | Added optional `isDraft` flag to `Ticket` (CP-1390): explicit draft marking with legacy fallback for existing tickets. |
145
+ | 1.3.11 | Fixed pre-existing broken type declaration import in `clientsConfig.types.d.ts` that caused consumer `tsc` builds to fail. |
146
+ | 1.3.12 | Added `callsWithTickets` to `CallsSummaryAggregation` (CP-1200): distinct call count with at least one open ticket, enabling accurate `ticketOpenRate` and `not_opened` calculations in consumers. |
147
+ | 1.3.13 | Added `Flow.useRedisTranscription` optional flag to control whether cached Redis transcriptions are used (defaults to `false`). |
148
+
149
+ ### 1.1.9
150
+
151
+ 1. `npm run build`.
152
+ 2. `npm run test`.
153
+ 3. `npm run format`.
154
+
155
+ ### 1.3.4 Call & ticket statistics (CP-149)
156
+
157
+ New call statistics getters for dashboards (summary, trend, hourly, routing) and ticket statistics scoped to the same date range (open tickets, draft tickets, subject breakdowns).
158
+
159
+ **Removed**
160
+
161
+ | Removed | Replacement |
162
+ |-------------------------------------|-----------------------------------------------------------------------------------------------------------------|
163
+ | `getTicketsCountByCityAndDateRange` | `aggregateCallsSummary` + `findCallSidTicketCountsByCity` — note: returns `Map<string, number>`, not `string[]` |
164
+ | `getTicketsSubjectStats` | `findSubjectsByCityAndDateRange` |
165
+ | `SubjectStatsItem` | `SubjectItem` |
166
+
167
+ **Do I need to update my app?**
168
+
169
+ Yesif you used any of the removed functions above.
170
+
171
+ ### 1.3.5 Muni issues (CP-1115)
172
+
173
+ New `muniIssues` module under `src/municipal/` for issues reported from the call-log screen. The document is written to the municipal DB after its Jira ticket is created.
174
+
175
+ **Added**
176
+
177
+ | Export | Purpose |
178
+ |----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
179
+ | `MuniIssue` / `CreateMuniIssueInput` | Document type and insert-input type (`issueContent` + `jira` domains). |
180
+ | `createMuniIssue(input, id)` | Insert an issue; requires a caller-supplied `_id` from MIS (via `generateMuniIssueId`) so it matches the id embedded in the Jira ticket (two-way link). |
181
+ | `generateMuniIssueId()` | Pre-generate the `_id` to pass to `createMuniIssue`. |
182
+ | `getMuniIssueById` / `getMuniIssueByJiraKey` | Lookups by our id or by the Jira key. |
183
+ | `ensureMuniIssuesCollection()` | Provision the `$jsonSchema` validator and indexes (unique `jira.key`); run once at MIS boot. |
184
+
185
+ **Do I need to update my app?**
186
+
187
+ No — purely additive. New consumers (MIS) import these from `@talkpilot/core-db`.
188
+
189
+ ### 1.3.6 Context Notes & Products
190
+
191
+ **Context Notes** — new `contextNotes` collection under `src/talkpilot/` for per-client, per-product notes injected into AI calls at runtime. Each document holds a `systemPrompt` and a list of time-bounded entries (`activeFrom`, `expiresAt`). Two setters with split ownership: `setContextNoteEntries` for the notes list and `setContextNoteConfig` for `systemPrompt` and `product`.
192
+
193
+ **Products** — new `products` collection under `src/talkpilot/` cataloguing TalkPilot products. Each document has a stable `name` and an optional `displayName` locale map (`Record<string, string>`) for UI display.
194
+
195
+ **Added**
196
+
197
+ | Export | Purpose |
198
+ |----------------------------------------------|-----------------------------------------------------------------|
199
+ | `getContextNotes(clientId, product)` | Fetch context note documents for a client/product pair. |
200
+ | `createContextNote(input)` | Insert a new context note document. |
201
+ | `setContextNoteEntries(id, clientId, notes)` | Replace the notes list on an existing document. |
202
+ | `setContextNoteConfig(id, clientId, config)` | Update `systemPrompt` and/or `product` on an existing document. |
203
+ | `getAllProducts()` | Fetch the full product catalogue. |
204
+
205
+ **Do I need to update my app?**
206
+
207
+ Nopurely additive.
208
+
209
+ ### 1.3.7 Generic prompt control (CP-704)
210
+
211
+ Added an optional boolean field to the `Flow` type and MongoDB schema.
212
+
213
+ **Added**
214
+
215
+ | Export | Purpose |
216
+ |-----------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
217
+ | `Flow.disableGenericPrompt` | Optional `boolean`. When `true`, disables the generic prompt for the flow. Existing flows without this field continue to work unchanged. |
218
+
219
+ **Do I need to update my app?**
220
+
221
+ Nothe field is optional and fully backwards-compatible.
222
+
223
+ ### 1.3.8 Ticket-count Map getters (CP-1200)
224
+
225
+ Adds `Map<string, number>` ticket getters that return per-call ticket counts. The old `string[]` getters and filter fields are kept and marked `@deprecated`.
226
+
227
+ **Deprecated Replacement**
228
+
229
+ | Deprecated | Replacement |
230
+ |---------------------------------------------|--------------------------------------------------------------|
231
+ | `findCallSidsWithTicketsByCity` | `findCallSidTicketCountsByCity` → `Map<string, number>` |
232
+ | `findCallSidsWithDraftTicketsByCity` | `findCallSidDraftTicketCountsByCity` → `Map<string, number>` |
233
+ | `CallsStatsFilter.callSidsWithTickets` | `CallsStatsFilter.callSidTicketCounts` |
234
+ | `CallsStatsFilter.callSidsWithDraftTickets` | `CallsStatsFilter.callSidDraftTicketCounts` |
235
+
236
+ **Do I need to update my app?**
237
+
238
+ Nothe old fields still compile. Migrate when convenient.
239
+
240
+ ### 1.3.9 Wrap-around hour filter boundary guards (CP-1166)
241
+
242
+ When `hourFrom` > `hourTo` (e.g. 23:00–13:00), two silent miscounting bugs existed:
243
+
244
+ - **First-day morning**: calls before `hourTo` on the first day (e.g. 08:00 on Jun 8) were counted even though the window starts at `hourFrom` that day. Fixed by adding `dateLocal > startStr` to the after-midnight leg.
245
+ - **Last-day evening**: calls at or after `hourFrom` on the last day (e.g. 23:30 on Jun 9) were counted even though the window ends at `hourTo` that day. Fixed by adding `dateLocal < endStr` to the before-midnight leg.
246
+
247
+ **Affects:** `aggregateCallsTrend`, `aggregateCallsSummary`, `aggregateCallsHourlyByRange`, `aggregateCallsRouting`, `findFilteredCallSids`, `findSubjectsByCityAndDateRange`.
248
+
249
+ **Do I need to update my app?**
250
+
251
+ No API changes both fixes correct silent miscounting. Upgrading is recommended if you use a wrap-around hour window.
252
+
253
+ ### 1.3.10 Ticket draft flag (CP-1390)
254
+
255
+ Added an optional `isDraft` boolean field to the `Ticket` type.
256
+
257
+ **Added**
258
+
259
+ | Export | Purpose |
260
+ |------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
261
+ | `Ticket.isDraft` | Optional `boolean`. When `true`, the ticket is a draft. When `false`, it is not. When absent (legacy tickets), draft detection falls back to the previous `event_subject_id` heuristic. |
262
+
263
+ **Affects:** `findCallSidDraftTicketCountsByCity`, `findCallSidsWithDraftTicketsByCity` (draft filtering in ticket statistics).
264
+
265
+ **Do I need to update my app?**
266
+
267
+ No — purely additive. Existing tickets without `isDraft` continue to work unchanged. New consumers (MIS) can pass `isDraft: true` when creating a draft ticket.
268
+
269
+ ### 1.3.11 Fix clientsConfig type declaration import
270
+
271
+ Fixed a pre-existing broken import path in the published `clientsConfig.types.d.ts` (introduced in an earlier release, unrelated to 1.3.10). Consumer TypeScript builds could fail with:
272
+
273
+ `Cannot find module 'src/utils/shared.types' or its corresponding type declarations.`
274
+
275
+ The import now uses a relative path (`../../utils/shared.types`) so `tsc` resolves it correctly from `node_modules/@talkpilot/core-db/dist/`.
276
+
277
+ **Do I need to update my app?**
278
+
279
+ Yes — upgrade to 1.3.11 if your build failed with the error above (affects any version that shipped the broken declaration). No API or behavior changes otherwise.
280
+
281
+ ### 1.3.12Calls-with-tickets count (CP-1200)
282
+
283
+ Added `callsWithTickets` to `CallsSummaryAggregation` — the number of distinct calls that opened at least one ticket. Use this field (instead of `openTickets`) to compute call-level rates and "calls without a ticket" counts.
284
+
285
+ **Do I need to update my app?**
286
+
287
+ Yes — replace `openTickets` with `callsWithTickets` wherever you compute `ticketOpenRate` or `not_opened`.
288
+
289
+ ### 1.3.13 — Redis transcription flag
290
+
291
+ Added an optional `Flow.useRedisTranscription` boolean that tells consumers whether to read transcriptions from Redis. Defaults to `false` when omitted.
292
+
293
+ **Do I need to update my app?**
294
+
295
+ No — this flag is optional. Only update if you want to opt into the Redis transcription path.
296
+
297
+
298
+ ## 🛠 CI/CD & deployment
299
+
300
+ - 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.
301
+ - Releases require the shared npm token documented in `DEVELOPMENT.md`; consult that guide for contribution, linking, and token rotation procedures.
302
+
303
+ ## Resources
304
+
305
+ - [DEVELOPMENT.md](./DEVELOPMENT.md) (setup, tooling, publishing, token management)
306
+ - [src/test-utils](src/test-utils) and the `__tests__` folder for examples of `MongoMemoryServer` wiring.
307
+