@talkpilot/core-db 1.3.35 → 1.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +117 -1
  2. package/dist/configuration/index.d.ts +2 -0
  3. package/dist/configuration/index.d.ts.map +1 -1
  4. package/dist/configuration/index.js +2 -0
  5. package/dist/configuration/index.js.map +1 -1
  6. package/dist/configuration/internalModels/index.d.ts +4 -0
  7. package/dist/configuration/internalModels/index.d.ts.map +1 -0
  8. package/dist/configuration/internalModels/index.js +21 -0
  9. package/dist/configuration/internalModels/index.js.map +1 -0
  10. package/dist/configuration/internalModels/internalModels.constants.d.ts +2 -0
  11. package/dist/configuration/internalModels/internalModels.constants.d.ts.map +1 -0
  12. package/dist/configuration/internalModels/internalModels.constants.js +5 -0
  13. package/dist/configuration/internalModels/internalModels.constants.js.map +1 -0
  14. package/dist/configuration/internalModels/internalModels.getters.d.ts +16 -0
  15. package/dist/configuration/internalModels/internalModels.getters.d.ts.map +1 -0
  16. package/dist/configuration/internalModels/internalModels.getters.js +31 -0
  17. package/dist/configuration/internalModels/internalModels.getters.js.map +1 -0
  18. package/dist/configuration/internalModels/internalModels.types.d.ts +12 -0
  19. package/dist/configuration/internalModels/internalModels.types.d.ts.map +1 -0
  20. package/dist/configuration/internalModels/internalModels.types.js +3 -0
  21. package/dist/configuration/internalModels/internalModels.types.js.map +1 -0
  22. package/dist/configuration/models/index.d.ts +4 -0
  23. package/dist/configuration/models/index.d.ts.map +1 -0
  24. package/dist/configuration/models/index.js +16 -0
  25. package/dist/configuration/models/index.js.map +1 -0
  26. package/dist/configuration/models/models.constants.d.ts +5 -0
  27. package/dist/configuration/models/models.constants.d.ts.map +1 -0
  28. package/dist/configuration/models/models.constants.js +15 -0
  29. package/dist/configuration/models/models.constants.js.map +1 -0
  30. package/dist/configuration/models/models.getters.d.ts +21 -0
  31. package/dist/configuration/models/models.getters.d.ts.map +1 -0
  32. package/dist/configuration/models/models.getters.js +44 -0
  33. package/dist/configuration/models/models.getters.js.map +1 -0
  34. package/dist/configuration/models/models.types.d.ts +68 -0
  35. package/dist/configuration/models/models.types.d.ts.map +1 -0
  36. package/dist/configuration/models/models.types.js +3 -0
  37. package/dist/configuration/models/models.types.js.map +1 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +2 -0
  41. package/dist/index.js.map +1 -1
  42. package/dist/talkpilot/clients/clients.quota.getters.d.ts +7 -0
  43. package/dist/talkpilot/clients/clients.quota.getters.d.ts.map +1 -0
  44. package/dist/talkpilot/clients/clients.quota.getters.js +80 -0
  45. package/dist/talkpilot/clients/clients.quota.getters.js.map +1 -0
  46. package/dist/talkpilot/clients/clients.quota.types.d.ts +24 -0
  47. package/dist/talkpilot/clients/clients.quota.types.d.ts.map +1 -0
  48. package/dist/talkpilot/clients/clients.quota.types.js +3 -0
  49. package/dist/talkpilot/clients/clients.quota.types.js.map +1 -0
  50. package/dist/talkpilot/clients/clients.types.d.ts +3 -0
  51. package/dist/talkpilot/clients/clients.types.d.ts.map +1 -1
  52. package/dist/talkpilot/clients/index.d.ts +2 -0
  53. package/dist/talkpilot/clients/index.d.ts.map +1 -1
  54. package/dist/talkpilot/clients/index.js +2 -0
  55. package/dist/talkpilot/clients/index.js.map +1 -1
  56. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts +5 -0
  57. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts.map +1 -1
  58. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js +37 -1
  59. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js.map +1 -1
  60. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts +2 -0
  61. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts.map +1 -1
  62. package/package.json +1 -1
  63. package/src/configuration/index.ts +2 -0
  64. package/src/configuration/internalModels/index.ts +3 -0
  65. package/src/configuration/internalModels/internalModels.constants.ts +1 -0
  66. package/src/configuration/internalModels/internalModels.getters.ts +33 -0
  67. package/src/configuration/internalModels/internalModels.types.ts +12 -0
  68. package/src/configuration/models/index.ts +25 -0
  69. package/src/configuration/models/models.constants.ts +13 -0
  70. package/src/configuration/models/models.getters.ts +53 -0
  71. package/src/configuration/models/models.types.ts +79 -0
  72. package/src/index.ts +2 -0
  73. package/src/talkpilot/clients/__tests__/clients.quota.spec.ts +123 -0
  74. package/src/talkpilot/clients/clients.quota.getters.ts +119 -0
  75. package/src/talkpilot/clients/clients.quota.types.ts +27 -0
  76. package/src/talkpilot/clients/clients.types.ts +4 -0
  77. package/src/talkpilot/clients/index.ts +2 -0
  78. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.spec.ts +26 -0
  79. package/src/talkpilot/clientsConfig/clientsConfig.getters.ts +54 -0
  80. package/src/talkpilot/clientsConfig/clientsConfig.types.ts +3 -0
@@ -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";
@@ -113,6 +113,8 @@ export type CommunicationsConfig = {
113
113
  whatsapp?: WhatsappConfig;
114
114
  };
115
115
 
116
+ import type { ClientQuotaUsage } from "../clients/clients.quota.types";
117
+
116
118
  export type ClientConfig<P extends Products = Products> = {
117
119
  clientId: string;
118
120
  phoneNumber?: string;
@@ -121,6 +123,7 @@ export type ClientConfig<P extends Products = Products> = {
121
123
  timezone?: string;
122
124
  communications?: CommunicationsConfig;
123
125
  callLengthThresholds?: CallLengthThresholds;
126
+ quota?: ClientQuotaUsage;
124
127
  };
125
128
 
126
129
  export type ClientConfigDoc<P extends Products = Products> = WithId<