@talkpilot/core-db 1.3.33 → 1.3.34

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 (104) hide show
  1. package/README.md +54 -0
  2. package/dist/connection.d.ts.map +1 -1
  3. package/dist/connection.js +0 -11
  4. package/dist/connection.js.map +1 -1
  5. package/dist/index.d.ts +0 -2
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -6
  8. package/dist/index.js.map +1 -1
  9. package/dist/talkpilot/clients/clients.quota.constants.d.ts +2 -0
  10. package/dist/talkpilot/clients/clients.quota.constants.d.ts.map +1 -0
  11. package/dist/talkpilot/clients/clients.quota.constants.js +5 -0
  12. package/dist/talkpilot/clients/clients.quota.constants.js.map +1 -0
  13. package/dist/talkpilot/clients/clients.quota.getters.d.ts +7 -0
  14. package/dist/talkpilot/clients/clients.quota.getters.d.ts.map +1 -0
  15. package/dist/talkpilot/clients/clients.quota.getters.js +80 -0
  16. package/dist/talkpilot/clients/clients.quota.getters.js.map +1 -0
  17. package/dist/talkpilot/clients/clients.quota.types.d.ts +24 -0
  18. package/dist/talkpilot/clients/clients.quota.types.d.ts.map +1 -0
  19. package/dist/{configuration/prompts/prompts.types.js → talkpilot/clients/clients.quota.types.js} +1 -1
  20. package/dist/talkpilot/clients/clients.quota.types.js.map +1 -0
  21. package/dist/talkpilot/clients/clients.quota.utils.d.ts +8 -0
  22. package/dist/talkpilot/clients/clients.quota.utils.d.ts.map +1 -0
  23. package/dist/talkpilot/clients/clients.quota.utils.js +45 -0
  24. package/dist/talkpilot/clients/clients.quota.utils.js.map +1 -0
  25. package/dist/talkpilot/clients/clients.types.d.ts +3 -0
  26. package/dist/talkpilot/clients/clients.types.d.ts.map +1 -1
  27. package/dist/talkpilot/clients/index.d.ts +2 -0
  28. package/dist/talkpilot/clients/index.d.ts.map +1 -1
  29. package/dist/talkpilot/clients/index.js +2 -0
  30. package/dist/talkpilot/clients/index.js.map +1 -1
  31. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts +5 -0
  32. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts.map +1 -1
  33. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js +37 -1
  34. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js.map +1 -1
  35. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts +3 -3
  36. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts.map +1 -1
  37. package/dist/talkpilot/clientsConfig/clientsConfig.types.js.map +1 -1
  38. package/dist/test-utils/db-utils.d.ts.map +1 -1
  39. package/dist/test-utils/db-utils.js +0 -2
  40. package/dist/test-utils/db-utils.js.map +1 -1
  41. package/package.json +1 -1
  42. package/src/connection.ts +0 -13
  43. package/src/index.ts +0 -7
  44. package/src/talkpilot/clients/__tests__/clients.quota.spec.ts +123 -0
  45. package/src/talkpilot/clients/clients.quota.getters.ts +119 -0
  46. package/src/talkpilot/clients/clients.quota.types.ts +27 -0
  47. package/src/talkpilot/clients/clients.types.ts +4 -0
  48. package/src/talkpilot/clients/index.ts +2 -0
  49. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.spec.ts +26 -0
  50. package/src/talkpilot/clientsConfig/clientsConfig.getters.ts +54 -0
  51. package/src/talkpilot/clientsConfig/clientsConfig.types.ts +4 -3
  52. package/src/test-utils/db-utils.ts +1 -8
  53. package/dist/configuration/index.d.ts +0 -7
  54. package/dist/configuration/index.d.ts.map +0 -1
  55. package/dist/configuration/index.js +0 -34
  56. package/dist/configuration/index.js.map +0 -1
  57. package/dist/configuration/mongodb-client.d.ts +0 -13
  58. package/dist/configuration/mongodb-client.d.ts.map +0 -1
  59. package/dist/configuration/mongodb-client.js +0 -56
  60. package/dist/configuration/mongodb-client.js.map +0 -1
  61. package/dist/configuration/prompts/index.d.ts +0 -3
  62. package/dist/configuration/prompts/index.d.ts.map +0 -1
  63. package/dist/configuration/prompts/index.js +0 -18
  64. package/dist/configuration/prompts/index.js.map +0 -1
  65. package/dist/configuration/prompts/prompts.getters.d.ts +0 -21
  66. package/dist/configuration/prompts/prompts.getters.d.ts.map +0 -1
  67. package/dist/configuration/prompts/prompts.getters.js +0 -35
  68. package/dist/configuration/prompts/prompts.getters.js.map +0 -1
  69. package/dist/configuration/prompts/prompts.types.d.ts +0 -9
  70. package/dist/configuration/prompts/prompts.types.d.ts.map +0 -1
  71. package/dist/configuration/prompts/prompts.types.js.map +0 -1
  72. package/dist/municipal/departmentsSubjects/departmentsSubjects.setters.d.ts +0 -10
  73. package/dist/municipal/departmentsSubjects/departmentsSubjects.setters.d.ts.map +0 -1
  74. package/dist/municipal/departmentsSubjects/departmentsSubjects.setters.js +0 -15
  75. package/dist/municipal/departmentsSubjects/departmentsSubjects.setters.js.map +0 -1
  76. package/dist/municipal/streets/streets.setters.d.ts +0 -10
  77. package/dist/municipal/streets/streets.setters.d.ts.map +0 -1
  78. package/dist/municipal/streets/streets.setters.js +0 -15
  79. package/dist/municipal/streets/streets.setters.js.map +0 -1
  80. package/dist/reconcile/index.d.ts +0 -5
  81. package/dist/reconcile/index.d.ts.map +0 -1
  82. package/dist/reconcile/index.js +0 -21
  83. package/dist/reconcile/index.js.map +0 -1
  84. package/dist/reconcile/reconcile.diff.d.ts +0 -4
  85. package/dist/reconcile/reconcile.diff.d.ts.map +0 -1
  86. package/dist/reconcile/reconcile.diff.js +0 -36
  87. package/dist/reconcile/reconcile.diff.js.map +0 -1
  88. package/dist/reconcile/reconcile.execute.d.ts +0 -7
  89. package/dist/reconcile/reconcile.execute.d.ts.map +0 -1
  90. package/dist/reconcile/reconcile.execute.js +0 -20
  91. package/dist/reconcile/reconcile.execute.js.map +0 -1
  92. package/dist/reconcile/reconcile.ops.d.ts +0 -12
  93. package/dist/reconcile/reconcile.ops.d.ts.map +0 -1
  94. package/dist/reconcile/reconcile.ops.js +0 -24
  95. package/dist/reconcile/reconcile.ops.js.map +0 -1
  96. package/dist/reconcile/reconcile.types.d.ts +0 -32
  97. package/dist/reconcile/reconcile.types.d.ts.map +0 -1
  98. package/dist/reconcile/reconcile.types.js +0 -3
  99. package/dist/reconcile/reconcile.types.js.map +0 -1
  100. package/src/configuration/index.ts +0 -15
  101. package/src/configuration/mongodb-client.ts +0 -61
  102. package/src/configuration/prompts/index.ts +0 -2
  103. package/src/configuration/prompts/prompts.getters.ts +0 -37
  104. package/src/configuration/prompts/prompts.types.ts +0 -10
@@ -16,11 +16,9 @@ async function initTestDb() {
16
16
  const talkpilotDb = client.db();
17
17
  const municipalDb = client.db("municipal-data");
18
18
  const websitalkDb = client.db("website-talk");
19
- const configurationDb = client.db("configuration");
20
19
  (0, index_1.setDb)(talkpilotDb);
21
20
  (0, index_1.setMunicipalDataDb)(municipalDb);
22
21
  (0, index_1.setWebsitalkDb)(websitalkDb);
23
- (0, index_1.setConfigurationDb)(configurationDb);
24
22
  return talkpilotDb;
25
23
  }
26
24
  async function closeTestDb() {
@@ -1 +1 @@
1
- {"version":3,"file":"db-utils.js","sourceRoot":"","sources":["../../src/test-utils/db-utils.ts"],"names":[],"mappings":";;AAYA,gCAeC;AAED,kCAGC;AAhCD,iEAA0D;AAC1D,qCAA0C;AAC1C,oCAKkB;AAElB,IAAI,WAA8B,CAAC;AACnC,IAAI,MAAmB,CAAC;AAEjB,KAAK,UAAU,UAAU;IAC9B,WAAW,GAAG,MAAM,yCAAiB,CAAC,MAAM,CAAC;QAC3C,QAAQ,EAAE,EAAE,EAAE,EAAE,WAAW,EAAE;KAC9B,CAAC,CAAC;IACH,MAAM,GAAG,IAAI,qBAAW,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/C,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACvB,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,EAAE,CAAC;IAChC,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAChD,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC;IAC9C,MAAM,eAAe,GAAG,MAAM,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC;IACnD,IAAA,aAAK,EAAC,WAAW,CAAC,CAAC;IACnB,IAAA,0BAAkB,EAAC,WAAW,CAAC,CAAC;IAChC,IAAA,sBAAc,EAAC,WAAW,CAAC,CAAC;IAC5B,IAAA,0BAAkB,EAAC,eAAe,CAAC,CAAC;IACpC,OAAO,WAAW,CAAC;AACrB,CAAC;AAEM,KAAK,UAAU,WAAW;IAC/B,IAAI,MAAM;QAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACjC,IAAI,WAAW;QAAE,MAAM,WAAW,CAAC,IAAI,EAAE,CAAC;AAC5C,CAAC"}
1
+ {"version":3,"file":"db-utils.js","sourceRoot":"","sources":["../../src/test-utils/db-utils.ts"],"names":[],"mappings":";;AAOA,gCAaC;AAED,kCAGC;AAzBD,iEAA0D;AAC1D,qCAA0C;AAC1C,oCAAqE;AAErE,IAAI,WAA8B,CAAC;AACnC,IAAI,MAAmB,CAAC;AAEjB,KAAK,UAAU,UAAU;IAC9B,WAAW,GAAG,MAAM,yCAAiB,CAAC,MAAM,CAAC;QAC3C,QAAQ,EAAE,EAAE,EAAE,EAAE,WAAW,EAAE;KAC9B,CAAC,CAAC;IACH,MAAM,GAAG,IAAI,qBAAW,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;IAC/C,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACvB,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,EAAE,CAAC;IAChC,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,CAAC,gBAAgB,CAAC,CAAC;IAChD,MAAM,WAAW,GAAG,MAAM,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC;IAC9C,IAAA,aAAK,EAAC,WAAW,CAAC,CAAC;IACnB,IAAA,0BAAkB,EAAC,WAAW,CAAC,CAAC;IAChC,IAAA,sBAAc,EAAC,WAAW,CAAC,CAAC;IAC5B,OAAO,WAAW,CAAC;AACrB,CAAC;AAEM,KAAK,UAAU,WAAW;IAC/B,IAAI,MAAM;QAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACjC,IAAI,WAAW;QAAE,MAAM,WAAW,CAAC,IAAI,EAAE,CAAC;AAC5C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talkpilot/core-db",
3
- "version": "1.3.33",
3
+ "version": "1.3.34",
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",
package/src/connection.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { mongodbClient } from "./talkpilot";
2
2
  import { municipalDataMongodbClient } from "./municipal";
3
3
  import { websitalkMongodbClient } from "./websitalk";
4
- import { configurationMongodbClient } from "./configuration";
5
4
 
6
5
  let isConnected = false;
7
6
 
@@ -18,7 +17,6 @@ export async function ensureDbConnected() {
18
17
  const talkpilotUri = mongoUri;
19
18
  const municipalUri = mongoUri;
20
19
  const websiteTalkUri = mongoUri;
21
- const configurationUri = mongoUri;
22
20
 
23
21
  if (!talkpilotUri) {
24
22
  console.warn("[core-db] MONGO_URI is not set");
@@ -52,16 +50,6 @@ export async function ensureDbConnected() {
52
50
  );
53
51
  }
54
52
 
55
- if (!configurationUri) {
56
- console.warn("[core-db] MONGO_URI is not set");
57
- } else {
58
- const dbName = process.env.CONFIGURATION_DB_NAME;
59
- await configurationMongodbClient.connect(configurationUri, dbName);
60
- console.info(
61
- `[core-db] Connected to Configuration MongoDB: ${dbName || "configuration (default)"}`,
62
- );
63
- }
64
-
65
53
  isConnected = true;
66
54
  }
67
55
 
@@ -74,7 +62,6 @@ export async function disconnectDb(): Promise<void> {
74
62
  mongodbClient.disconnect(),
75
63
  municipalDataMongodbClient.disconnect(),
76
64
  websitalkMongodbClient.disconnect(),
77
- configurationMongodbClient.disconnect(),
78
65
  ]);
79
66
  isConnected = false;
80
67
  }
package/src/index.ts CHANGED
@@ -27,13 +27,6 @@ export * from "./websitalk/scans/scans.getters";
27
27
  export type * from "./websitalk/scans/scans.types";
28
28
  export * from "./websitalk/websiteUrls";
29
29
 
30
- export {
31
- configurationMongodbClient,
32
- getDb as getConfigurationDb,
33
- setDb as setConfigurationDb,
34
- } from "./configuration";
35
- export * from "./configuration/prompts";
36
-
37
30
  export { ObjectId } from "mongodb";
38
31
  export type { Filter } from "mongodb";
39
32
  export type { AnyBulkWriteOperation as BulkWriteOp } from "mongodb";
@@ -0,0 +1,123 @@
1
+ import {
2
+ getClientsConfigCollection,
3
+ incrementClientQuotaUsage,
4
+ listClientIdsWithConfiguredQuota,
5
+ resetClientQuotaUsage,
6
+ } from "../../clientsConfig/clientsConfig.getters";
7
+ import { getClientsCollection } from "../clients.getters";
8
+ import {
9
+ markQuotaAlertSent,
10
+ markQuotaExpiredSent,
11
+ updateQuotaAlertsConfig,
12
+ } from "../clients.quota.getters";
13
+
14
+ describe("quota getters", () => {
15
+ beforeEach(async () => {
16
+ await getClientsConfigCollection().deleteMany({});
17
+ await getClientsCollection().deleteMany({});
18
+ });
19
+
20
+ const seed = async (clientId: string, configQuota: object, clientQuota?: object) => {
21
+ await getClientsConfigCollection().insertOne({
22
+ clientId,
23
+ products: {},
24
+ quota: configQuota,
25
+ } as any);
26
+ if (clientQuota !== undefined) {
27
+ await getClientsCollection().insertOne({
28
+ clientId,
29
+ createdAt: new Date(),
30
+ updatedAt: new Date(),
31
+ credits: 0,
32
+ quota: clientQuota,
33
+ } as any);
34
+ }
35
+ };
36
+
37
+ it("updateQuotaAlertsConfig stores alerts on clients", async () => {
38
+ const clientId = "quota-alerts";
39
+ await seed(clientId, { totalQuota: 100, usedQuota: 5 });
40
+
41
+ await updateQuotaAlertsConfig(clientId, [
42
+ { thresholdPct: 50, recipientEmails: ["a@example.com"] },
43
+ { thresholdPct: 80, recipientEmails: ["b@example.com", "c@example.com"] },
44
+ ]);
45
+
46
+ const client = await getClientsCollection().findOne({ clientId });
47
+ expect(client?.quota?.alerts).toEqual([
48
+ { thresholdPct: 50, recipientEmails: ["a@example.com"] },
49
+ { thresholdPct: 80, recipientEmails: ["b@example.com", "c@example.com"] },
50
+ ]);
51
+
52
+ const config = await getClientsConfigCollection().findOne({ clientId });
53
+ expect(config?.quota).toEqual({ totalQuota: 100, usedQuota: 5 });
54
+ });
55
+
56
+ it("markQuotaAlertSent returns true only on first transition", async () => {
57
+ const clientId = "quota-alert-sent";
58
+ await seed(
59
+ clientId,
60
+ { totalQuota: 100, usedQuota: 0 },
61
+ { alerts: [{ thresholdPct: 50, recipientEmails: ["a@b.com"] }] },
62
+ );
63
+
64
+ expect(await markQuotaAlertSent(clientId, 0)).toBe(true);
65
+ expect(await markQuotaAlertSent(clientId, 0)).toBe(false);
66
+
67
+ const client = await getClientsCollection().findOne({ clientId });
68
+ expect(client?.quota?.alerts?.[0]?.thresholdSent).toBe(true);
69
+ });
70
+
71
+ it("markQuotaExpiredSent returns true only on first transition", async () => {
72
+ const clientId = "quota-notify";
73
+ await seed(clientId, { totalQuota: 10, usedQuota: 10 });
74
+
75
+ expect(await markQuotaExpiredSent(clientId)).toBe(true);
76
+ expect(await markQuotaExpiredSent(clientId)).toBe(false);
77
+
78
+ const client = await getClientsCollection().findOne({ clientId });
79
+ expect(client?.quota?.expiredSent).toBe(true);
80
+ });
81
+
82
+ it("listClientIdsWithConfiguredQuota returns clientIds with totalQuota set", async () => {
83
+ await seed("quota-a", { totalQuota: 100, usedQuota: 0 });
84
+ await seed("quota-b", { totalQuota: 50, usedQuota: 10 });
85
+ await getClientsConfigCollection().insertOne({
86
+ clientId: "no-quota",
87
+ products: {},
88
+ } as any);
89
+
90
+ const ids = await listClientIdsWithConfiguredQuota();
91
+ expect(ids.sort()).toEqual(["quota-a", "quota-b"]);
92
+ });
93
+
94
+ it("incrementClientQuotaUsage increments usedQuota on clientsConfig", async () => {
95
+ const clientId = "quota-inc";
96
+ await seed(clientId, { totalQuota: 100, usedQuota: 3 });
97
+
98
+ await incrementClientQuotaUsage(clientId, 2);
99
+ const config = await getClientsConfigCollection().findOne({ clientId });
100
+ expect(config?.quota?.usedQuota).toBe(5);
101
+ });
102
+
103
+ it("resetClientQuotaUsage zeros usedQuota and clears client quota flags", async () => {
104
+ const clientId = "quota-reset";
105
+ await seed(
106
+ clientId,
107
+ { totalQuota: 100, usedQuota: 50 },
108
+ {
109
+ expiredSent: true,
110
+ alerts: [{ thresholdPct: 50, recipientEmails: ["a@b.com"], thresholdSent: true }],
111
+ },
112
+ );
113
+
114
+ await resetClientQuotaUsage(clientId);
115
+
116
+ const config = await getClientsConfigCollection().findOne({ clientId });
117
+ expect(config?.quota?.usedQuota).toBe(0);
118
+
119
+ const client = await getClientsCollection().findOne({ clientId });
120
+ expect(client?.quota?.expiredSent).toBeUndefined();
121
+ expect(client?.quota?.alerts?.[0]?.thresholdSent).toBeUndefined();
122
+ });
123
+ });
@@ -0,0 +1,119 @@
1
+ import { getClientConfig } from "../clientsConfig/clientsConfig.getters";
2
+ import { getClientsCollection } from "./clients.getters";
3
+ import type {
4
+ ClientQuotaState,
5
+ QuotaAlertInput,
6
+ } from "./clients.quota.types";
7
+
8
+ export async function getClientQuotaState(
9
+ clientId: string,
10
+ ): Promise<ClientQuotaState | null> {
11
+ const [config, client] = await Promise.all([
12
+ getClientConfig(clientId),
13
+ getClientsCollection().findOne({ clientId }),
14
+ ]);
15
+
16
+ const usage = config?.quota;
17
+ if (usage?.totalQuota === undefined || usage?.totalQuota === null) return null;
18
+
19
+ const settings = client?.quota;
20
+
21
+ return {
22
+ totalQuota: usage.totalQuota,
23
+ usedQuota: usage.usedQuota ?? 0,
24
+ expiresAt: usage.expiresAt,
25
+ alerts: settings?.alerts,
26
+ expiredSent: settings?.expiredSent,
27
+ };
28
+ }
29
+
30
+ const ensureClientDoc = async (clientId: string): Promise<void> => {
31
+ const now = new Date();
32
+ await getClientsCollection().updateOne(
33
+ { clientId },
34
+ { $setOnInsert: { clientId, createdAt: now, updatedAt: now, credits: 0 } },
35
+ { upsert: true },
36
+ );
37
+ await getClientsCollection().updateOne({ clientId }, { $set: { updatedAt: now } });
38
+ };
39
+
40
+ export async function updateQuotaAlertsConfig(
41
+ clientId: string,
42
+ alerts: QuotaAlertInput[],
43
+ ): Promise<void> {
44
+ const config = await getClientConfig(clientId);
45
+ if (!config) {
46
+ throw new Error(`No client config found for clientId: ${clientId}`);
47
+ }
48
+
49
+ await ensureClientDoc(clientId);
50
+ const state = await getClientQuotaState(clientId);
51
+ const existing = state?.alerts ?? [];
52
+ const sentByThreshold = new Map(
53
+ existing.filter((a) => a.thresholdSent).map((a) => [a.thresholdPct, true]),
54
+ );
55
+ const merged = alerts.map((alert) => ({
56
+ thresholdPct: alert.thresholdPct,
57
+ recipientEmails: alert.recipientEmails,
58
+ ...(sentByThreshold.get(alert.thresholdPct) ? { thresholdSent: true as const } : {}),
59
+ }));
60
+
61
+ const result = await getClientsCollection().updateOne(
62
+ { clientId },
63
+ { $set: { "quota.alerts": merged, updatedAt: new Date() } },
64
+ );
65
+
66
+ if (result.matchedCount === 0) {
67
+ throw new Error(`No client found for clientId: ${clientId}`);
68
+ }
69
+ }
70
+
71
+ export async function markQuotaAlertSent(
72
+ clientId: string,
73
+ alertIndex: number,
74
+ ): Promise<boolean> {
75
+ await ensureClientDoc(clientId);
76
+ const result = await getClientsCollection().findOneAndUpdate(
77
+ {
78
+ clientId,
79
+ [`quota.alerts.${alertIndex}.thresholdSent`]: { $ne: true },
80
+ },
81
+ { $set: { [`quota.alerts.${alertIndex}.thresholdSent`]: true, updatedAt: new Date() } },
82
+ { returnDocument: "after" },
83
+ );
84
+
85
+ return result !== null;
86
+ }
87
+
88
+ export async function markQuotaExpiredSent(clientId: string): Promise<boolean> {
89
+ await ensureClientDoc(clientId);
90
+ const result = await getClientsCollection().findOneAndUpdate(
91
+ {
92
+ clientId,
93
+ "quota.expiredSent": { $ne: true },
94
+ },
95
+ { $set: { "quota.expiredSent": true, updatedAt: new Date() } },
96
+ { returnDocument: "after" },
97
+ );
98
+
99
+ return result !== null;
100
+ }
101
+
102
+ export async function resetClientQuotaSettings(clientId: string): Promise<void> {
103
+ const client = await getClientsCollection().findOne({ clientId });
104
+ const alerts =
105
+ client?.quota?.alerts?.map(({ thresholdSent: _s, ...alert }) => alert) ?? [];
106
+
107
+ if (client) {
108
+ await getClientsCollection().updateOne(
109
+ { clientId },
110
+ {
111
+ $set: {
112
+ ...(alerts.length ? { "quota.alerts": alerts } : {}),
113
+ updatedAt: new Date(),
114
+ },
115
+ $unset: { "quota.expiredSent": "" },
116
+ },
117
+ );
118
+ }
119
+ }
@@ -0,0 +1,27 @@
1
+ export type QuotaThresholdAlert = {
2
+ thresholdPct: number;
3
+ recipientEmails: string[];
4
+ thresholdSent?: boolean;
5
+ };
6
+
7
+ export type ClientQuotaSettings = {
8
+ /** Up to 3 threshold alerts, each with up to 3 recipient emails. */
9
+ alerts?: QuotaThresholdAlert[];
10
+ /** Set after expired-quota email is sent successfully. */
11
+ expiredSent?: boolean;
12
+ };
13
+
14
+ export type QuotaAlertInput = {
15
+ thresholdPct: number;
16
+ recipientEmails: string[];
17
+ };
18
+
19
+ export type ClientQuotaUsage = {
20
+ totalQuota: number;
21
+ usedQuota: number;
22
+ expiresAt?: Date;
23
+ /** Human-readable account label for quota alert emails. */
24
+ clientDisplayName?: string;
25
+ };
26
+
27
+ export type ClientQuotaState = ClientQuotaUsage & ClientQuotaSettings;
@@ -1,4 +1,7 @@
1
1
  import { ObjectId } from "mongodb";
2
+ import { ClientQuotaSettings } from "./clients.quota.types";
3
+
4
+ export type { QuotaThresholdAlert, ClientQuotaSettings, QuotaAlertInput, ClientQuotaUsage, ClientQuotaState } from "./clients.quota.types";
2
5
 
3
6
  export type Client = {
4
7
  _id?: ObjectId;
@@ -9,6 +12,7 @@ export type Client = {
9
12
  apiKey?: string | null;
10
13
  credits: number;
11
14
  managedBy?: string;
15
+ quota?: ClientQuotaSettings;
12
16
  };
13
17
 
14
18
  export type ClientDoc = Client & { _id: ObjectId };
@@ -1,2 +1,4 @@
1
1
  export * from "./clients.getters";
2
2
  export * from "./clients.types";
3
+ export * from "./clients.quota.getters";
4
+ export * from "./clients.quota.types";
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  createClientConfigDoc,
3
3
  getClientConfig,
4
+ getClientDisplayName,
4
5
  } from "../clientsConfig.getters";
5
6
  import { createClientConfig } from "../../../test-utils/factories";
6
7
 
@@ -59,6 +60,31 @@ describe("db.clientsConfig", () => {
59
60
  expect(result).toBeNull();
60
61
  });
61
62
 
63
+ it("should return quota.clientDisplayName when set on client config", async () => {
64
+ const clientId = "display-name-client";
65
+ await createClientConfigDoc(
66
+ createClientConfig({
67
+ clientId,
68
+ quota: { totalQuota: 100, usedQuota: 0, clientDisplayName: "Acme Corp" },
69
+ }),
70
+ );
71
+
72
+ expect(await getClientDisplayName(clientId)).toBe("Acme Corp");
73
+ });
74
+
75
+ it("should return '-' when quota.clientDisplayName is missing", async () => {
76
+ const clientId = "no-display-name-client";
77
+ await createClientConfigDoc(
78
+ createClientConfig({ clientId, quota: { totalQuota: 100, usedQuota: 0 } }),
79
+ );
80
+
81
+ expect(await getClientDisplayName(clientId)).toBe("-");
82
+ });
83
+
84
+ it("should return '-' when client config is missing", async () => {
85
+ expect(await getClientDisplayName("missing-client")).toBe("-");
86
+ });
87
+
62
88
  it("given moked_106 with both toolsPrompts when saved and retrieved then both prompts are persisted", async () => {
63
89
  // Given
64
90
  const clientId = "tools-prompts-both";
@@ -7,6 +7,7 @@ import {
7
7
  KnownProductKey,
8
8
  } from "../index";
9
9
  import { Collection } from "mongodb";
10
+ import { resetClientQuotaSettings } from "../clients/clients.quota.getters";
10
11
 
11
12
  export const getClientsConfigCollection = (): Collection<ClientConfigDoc> => {
12
13
  return getDb().collection<ClientConfigDoc>("clientsConfig");
@@ -16,6 +17,15 @@ export const getClientConfig = (clientId: string) => {
16
17
  return getClientsConfigCollection().findOne({ clientId });
17
18
  };
18
19
 
20
+ export const getClientDisplayName = async (clientId: string): Promise<string> => {
21
+ const doc = await getClientsConfigCollection().findOne(
22
+ { clientId },
23
+ { projection: { "quota.clientDisplayName": 1, _id: 0 } },
24
+ );
25
+ const name = doc?.quota?.clientDisplayName?.trim();
26
+ return name || "-";
27
+ };
28
+
19
29
  export const getClientConfigByPhone = async (phone: string) => {
20
30
  const client = await findClientByPhoneNumber(phone);
21
31
  if (!client) return null;
@@ -77,3 +87,47 @@ export const clearActiveScanId = async (clientId: string): Promise<void> => {
77
87
  throw new Error(`No client config found for clientId: ${clientId}`);
78
88
  }
79
89
  };
90
+
91
+ export async function listClientIdsWithConfiguredQuota(): Promise<string[]> {
92
+ const docs = await getClientsConfigCollection()
93
+ .find({ "quota.totalQuota": { $exists: true, $ne: null } })
94
+ .project({ clientId: 1, _id: 0 })
95
+ .toArray();
96
+
97
+ return docs.map(({ clientId }) => clientId);
98
+ }
99
+
100
+ export async function incrementClientQuotaUsage(
101
+ clientId: string,
102
+ amount: number = 1,
103
+ ): Promise<void> {
104
+ const result = await getClientsConfigCollection().updateOne(
105
+ { clientId, "quota.totalQuota": { $exists: true } },
106
+ { $inc: { "quota.usedQuota": amount } },
107
+ );
108
+
109
+ if (result.matchedCount === 0) {
110
+ return;
111
+ }
112
+ }
113
+
114
+ export async function resetClientQuotaUsage(clientId: string): Promise<void> {
115
+ const result = await getClientsConfigCollection().updateOne(
116
+ { clientId },
117
+ { $set: { "quota.usedQuota": 0 } },
118
+ );
119
+
120
+ if (result.matchedCount === 0) {
121
+ throw new Error(`No client config found for clientId: ${clientId}`);
122
+ }
123
+
124
+ await resetClientQuotaSettings(clientId);
125
+ }
126
+
127
+ export {
128
+ getClientQuotaState,
129
+ updateQuotaAlertsConfig,
130
+ markQuotaAlertSent,
131
+ markQuotaExpiredSent,
132
+ resetClientQuotaSettings,
133
+ } from "../clients/clients.quota.getters";
@@ -12,12 +12,10 @@ export type InitiateCallForShortSlaConfig = {
12
12
  flow_id?: string | string[];
13
13
  };
14
14
 
15
- /** Per-tool LLM system prompt overrides. Falls back to configuration-db defaults when absent. */
15
+ /** Per-tool LLM system prompt overrides. Falls back to hardcoded defaults when absent. */
16
16
  export type Moked106ToolPrompts = {
17
17
  findSubjectsSystemPrompt?: string;
18
18
  findStreetsSystemPrompt?: string;
19
- transcriptionStreetSystemPrompt?: string;
20
- transcriptionSubjectSystemPrompt?: string;
21
19
  };
22
20
 
23
21
  /** Feature flags and behavior config for the moked_106 municipal call-center product. */
@@ -113,6 +111,8 @@ export type CommunicationsConfig = {
113
111
  whatsapp?: WhatsappConfig;
114
112
  };
115
113
 
114
+ import type { ClientQuotaUsage } from "../clients/clients.quota.types";
115
+
116
116
  export type ClientConfig<P extends Products = Products> = {
117
117
  clientId: string;
118
118
  phoneNumber?: string;
@@ -121,6 +121,7 @@ export type ClientConfig<P extends Products = Products> = {
121
121
  timezone?: string;
122
122
  communications?: CommunicationsConfig;
123
123
  callLengthThresholds?: CallLengthThresholds;
124
+ quota?: ClientQuotaUsage;
124
125
  };
125
126
 
126
127
  export type ClientConfigDoc<P extends Products = Products> = WithId<
@@ -1,11 +1,6 @@
1
1
  import { MongoMemoryServer } from "mongodb-memory-server";
2
2
  import { MongoClient, Db } from "mongodb";
3
- import {
4
- setDb,
5
- setMunicipalDataDb,
6
- setWebsitalkDb,
7
- setConfigurationDb,
8
- } from "../index";
3
+ import { setDb, setMunicipalDataDb, setWebsitalkDb } from "../index";
9
4
 
10
5
  let mongoServer: MongoMemoryServer;
11
6
  let client: MongoClient;
@@ -19,11 +14,9 @@ export async function initTestDb(): Promise<Db> {
19
14
  const talkpilotDb = client.db();
20
15
  const municipalDb = client.db("municipal-data");
21
16
  const websitalkDb = client.db("website-talk");
22
- const configurationDb = client.db("configuration");
23
17
  setDb(talkpilotDb);
24
18
  setMunicipalDataDb(municipalDb);
25
19
  setWebsitalkDb(websitalkDb);
26
- setConfigurationDb(configurationDb);
27
20
  return talkpilotDb;
28
21
  }
29
22
 
@@ -1,7 +0,0 @@
1
- import { Db, ObjectId as MongoObjectId } from "mongodb";
2
- export * from "./prompts";
3
- export { configurationMongodbClient } from "./mongodb-client";
4
- export declare const setDb: (d: Db) => void;
5
- export declare const getDb: () => Db;
6
- export declare const ObjectId: typeof MongoObjectId;
7
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/configuration/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,SAAS,CAAC;AAExD,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAG9D,eAAO,MAAM,KAAK,GAAI,GAAG,EAAE,SAE1B,CAAC;AAEF,eAAO,MAAM,KAAK,QAAO,EAGxB,CAAC;AACF,eAAO,MAAM,QAAQ,sBAAgB,CAAC"}
@@ -1,34 +0,0 @@
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
- exports.ObjectId = exports.getDb = exports.setDb = exports.configurationMongodbClient = void 0;
18
- const mongodb_1 = require("mongodb");
19
- __exportStar(require("./prompts"), exports);
20
- var mongodb_client_1 = require("./mongodb-client");
21
- Object.defineProperty(exports, "configurationMongodbClient", { enumerable: true, get: function () { return mongodb_client_1.configurationMongodbClient; } });
22
- let db;
23
- const setDb = (d) => {
24
- db = d;
25
- };
26
- exports.setDb = setDb;
27
- const getDb = () => {
28
- if (!db)
29
- throw new Error("Configuration DB not initialised");
30
- return db;
31
- };
32
- exports.getDb = getDb;
33
- exports.ObjectId = mongodb_1.ObjectId;
34
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/configuration/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qCAAwD;AAExD,4CAA0B;AAC1B,mDAA8D;AAArD,4HAAA,0BAA0B,OAAA;AAEnC,IAAI,EAAM,CAAC;AACJ,MAAM,KAAK,GAAG,CAAC,CAAK,EAAE,EAAE;IAC7B,EAAE,GAAG,CAAC,CAAC;AACT,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB;AAEK,MAAM,KAAK,GAAG,GAAO,EAAE;IAC5B,IAAI,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IAC7D,OAAO,EAAE,CAAC;AACZ,CAAC,CAAC;AAHW,QAAA,KAAK,SAGhB;AACW,QAAA,QAAQ,GAAG,kBAAa,CAAC"}
@@ -1,13 +0,0 @@
1
- import { Db } from "mongodb";
2
- declare class ConfigurationMongoDBClient {
3
- private client;
4
- private db;
5
- private readonly defaultDbName;
6
- connect(uri?: string, dbName?: string): Promise<void>;
7
- disconnect(): Promise<void>;
8
- getDb(): Db;
9
- isConnected(): boolean;
10
- }
11
- export declare const configurationMongodbClient: ConfigurationMongoDBClient;
12
- export {};
13
- //# sourceMappingURL=mongodb-client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongodb-client.d.ts","sourceRoot":"","sources":["../../src/configuration/mongodb-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,EAAE,EAAE,MAAM,SAAS,CAAC;AAI1C,cAAM,0BAA0B;IAC9B,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,EAAE,CAAmB;IAC7B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAmB;IAE3C,OAAO,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAuBrD,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAcjC,KAAK,IAAI,EAAE;IASX,WAAW,IAAI,OAAO;CAGvB;AAED,eAAO,MAAM,0BAA0B,4BAAmC,CAAC"}
@@ -1,56 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.configurationMongodbClient = void 0;
4
- const mongodb_1 = require("mongodb");
5
- const index_1 = require("./index");
6
- const validation_1 = require("../utils/validation");
7
- class ConfigurationMongoDBClient {
8
- client = null;
9
- db = null;
10
- defaultDbName = "configuration";
11
- async connect(uri, dbName) {
12
- if (this.client) {
13
- return;
14
- }
15
- const mongodbUri = uri || process.env.MONGO_URI || process.env.MONGODB_URI;
16
- (0, validation_1.validateConfig)("MONGO_URI", mongodbUri);
17
- (0, validation_1.validateMongoUri)(mongodbUri);
18
- try {
19
- this.client = new mongodb_1.MongoClient(mongodbUri);
20
- await this.client.connect();
21
- const targetDbName = dbName || process.env.CONFIGURATION_DB_NAME || this.defaultDbName;
22
- this.db = this.client.db(targetDbName);
23
- (0, index_1.setDb)(this.db);
24
- console.info(`[core-db] Configuration MongoDB connected: ${targetDbName}`);
25
- }
26
- catch (error) {
27
- console.error("[core-db] Configuration connection failed", error);
28
- throw error;
29
- }
30
- }
31
- async disconnect() {
32
- if (this.client) {
33
- try {
34
- await this.client.close();
35
- this.client = null;
36
- this.db = null;
37
- console.info("Configuration MongoDB disconnected successfully");
38
- }
39
- catch (error) {
40
- console.error("[core-db] Configuration disconnection failed", error);
41
- throw error;
42
- }
43
- }
44
- }
45
- getDb() {
46
- if (!this.db) {
47
- throw new Error("Configuration database not initialized. Call connect() first.");
48
- }
49
- return this.db;
50
- }
51
- isConnected() {
52
- return this.client !== null && this.client !== undefined;
53
- }
54
- }
55
- exports.configurationMongodbClient = new ConfigurationMongoDBClient();
56
- //# sourceMappingURL=mongodb-client.js.map