@bikdotai/bik-shared-backend 20.4.1-beta.0 → 20.4.1

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 (81) hide show
  1. package/lib/alertsV2/alertInstances.repo.js +2 -26
  2. package/lib/alertsV2/alertsV2.helper.d.ts +4 -3
  3. package/lib/alertsV2/alertsV2.helper.js +3 -49
  4. package/lib/alertsV2/alertsV2.service.js +5 -14
  5. package/lib/auth/authMiddlewares.js +3 -68
  6. package/lib/auth/firebase-auth.service.js +3 -3
  7. package/lib/auth/implementations/bik-admin-auth-service.d.ts +1 -1
  8. package/lib/auth/implementations/bik-admin-auth-service.js +1 -2
  9. package/lib/auth/index.d.ts +0 -3
  10. package/lib/auth/index.js +0 -3
  11. package/lib/auth/secret-manager/env-variables/variables.list.d.ts +0 -3
  12. package/lib/auth/secret-manager/env-variables/variables.list.js +0 -3
  13. package/lib/chat-handover-protocol/chat-handover-protocol.js +41 -26
  14. package/lib/core/setup.d.ts +0 -3
  15. package/lib/core/setup.js +2 -24
  16. package/lib/elastic/counter/ingestion.js +0 -1
  17. package/lib/elastic/queries/campaign/getBroadcastDetailedStats.d.ts +0 -117
  18. package/lib/elastic/queries/campaign/getBroadcastDetailedStats.js +1 -94
  19. package/lib/elastic/queries/campaign/getUniqueCustomerCnt.d.ts +0 -1
  20. package/lib/elastic/queries/campaign/getUniqueCustomerCnt.js +0 -1
  21. package/lib/elastic/queries/chatbot/getAiOperations.d.ts +5 -5
  22. package/lib/elastic/queries/chatbot/getAiOperations.js +3 -3
  23. package/lib/elastic/queries/chatbot/index.d.ts +0 -1
  24. package/lib/elastic/queries/chatbot/index.js +0 -1
  25. package/lib/elastic/queries/crm/getActivityTimelineByAgent.js +1 -1
  26. package/lib/elastic/queries/crm/getBreachedSLACount.d.ts +0 -1
  27. package/lib/elastic/queries/crm/getBreachedSLACount.js +5 -8
  28. package/lib/elastic/queries/crm/getFirstResponseTime.d.ts +0 -1
  29. package/lib/elastic/queries/crm/getFirstResponseTime.js +5 -8
  30. package/lib/elastic/queries/integrations/index.d.ts +0 -1
  31. package/lib/elastic/queries/integrations/index.js +0 -1
  32. package/lib/elastic/queries/openAi/addToCartSession.d.ts +0 -1
  33. package/lib/elastic/queries/openAi/addToCartSession.js +3 -11
  34. package/lib/elastic/queries/openAi/checkoutCompletedSession.d.ts +0 -1
  35. package/lib/elastic/queries/openAi/checkoutCompletedSession.js +3 -11
  36. package/lib/elastic/reports/crm/index.d.ts +0 -1
  37. package/lib/elastic/reports/crm/index.js +0 -1
  38. package/lib/elastic/reports/reports.service.js +8 -17
  39. package/lib/events/events.d.ts +0 -8
  40. package/lib/events/events.js +1 -25
  41. package/lib/events/schema/events.helper.d.ts +0 -1
  42. package/lib/events/schema/events.helper.js +6 -12
  43. package/lib/index.d.ts +0 -1
  44. package/lib/index.js +0 -1
  45. package/lib/merchant-events/elastic.search.d.ts +0 -5
  46. package/lib/merchant-events/elastic.search.js +2 -23
  47. package/lib/merchant-events/merchant.service.d.ts +1 -1
  48. package/lib/merchant-events/merchant.service.js +11 -12
  49. package/lib/recordAnalytics/recordAnalytics.service.js +4 -5
  50. package/lib/redis/redisPubSubService.d.ts +6 -4
  51. package/lib/redis/redisPubSubService.js +123 -211
  52. package/lib/redis/redisService.js +8 -14
  53. package/lib/swagger/SwaggerSchemaHelper.js +17 -21
  54. package/lib/user-properties/userProperties.service.js +0 -1
  55. package/package.json +2 -2
  56. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncDelay.d.ts +0 -1
  57. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncDelay.js +0 -4
  58. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncFailed.d.ts +0 -1
  59. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncFailed.js +0 -4
  60. package/lib/alerts/templates/campaign/campaignScheduledTimeExceededDueToSyncDelay.d.ts +0 -1
  61. package/lib/alerts/templates/campaign/campaignScheduledTimeExceededDueToSyncDelay.js +0 -4
  62. package/lib/auth/secret-manager/configManager.firestore.d.ts +0 -22
  63. package/lib/auth/secret-manager/configManager.firestore.js +0 -166
  64. package/lib/auth/secret-manager/configManager.helper.d.ts +0 -13
  65. package/lib/auth/secret-manager/configManager.helper.js +0 -32
  66. package/lib/auth/secret-manager/configManager.model.d.ts +0 -38
  67. package/lib/auth/secret-manager/configManager.model.js +0 -2
  68. package/lib/auth/secret-manager/configManager.service.d.ts +0 -17
  69. package/lib/auth/secret-manager/configManager.service.js +0 -138
  70. package/lib/core/local_runner.d.ts +0 -1
  71. package/lib/core/local_runner.js +0 -60
  72. package/lib/database/database.model.d.ts +0 -95
  73. package/lib/database/database.model.js +0 -5
  74. package/lib/database/database.service.d.ts +0 -90
  75. package/lib/database/database.service.js +0 -382
  76. package/lib/database/index.d.ts +0 -7
  77. package/lib/database/index.js +0 -23
  78. package/lib/elastic/queries/chatbot/getAgentCostForBroadcast.d.ts +0 -117
  79. package/lib/elastic/queries/chatbot/getAgentCostForBroadcast.js +0 -98
  80. package/lib/elastic/queries/integrations/getOrdersShadowServices.d.ts +0 -76
  81. package/lib/elastic/queries/integrations/getOrdersShadowServices.js +0 -61
@@ -1,166 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.FirestoreConfigManager = void 0;
13
- const config_1 = require("../config");
14
- class FirestoreConfigManager {
15
- constructor() {
16
- this.secretsCollection = 'secrets';
17
- this.envDocPrefix = 'bik-platform-secrets-';
18
- this.globalSecretsDocId = 'bik-platform-secrets-globalsecrets';
19
- const app = (0, config_1.getSecondaryApp)();
20
- this.db = app.firestore();
21
- }
22
- static getInstance() {
23
- if (!FirestoreConfigManager.instance) {
24
- FirestoreConfigManager.instance = new FirestoreConfigManager();
25
- }
26
- return FirestoreConfigManager.instance;
27
- }
28
- getDocId(section, podName) {
29
- if (section === 'secrets') {
30
- return this.globalSecretsDocId;
31
- }
32
- return `${this.envDocPrefix}${podName}`;
33
- }
34
- isDocFromSection(section, docId) {
35
- if (section === 'secrets') {
36
- return docId === this.globalSecretsDocId;
37
- }
38
- return docId.startsWith(this.envDocPrefix) && docId !== this.globalSecretsDocId;
39
- }
40
- getPodNameFromDocId(section, docId) {
41
- if (!this.isDocFromSection(section, docId)) {
42
- return undefined;
43
- }
44
- if (section === 'secrets') {
45
- return 'global';
46
- }
47
- const podName = docId.replace(this.envDocPrefix, '');
48
- if (!podName) {
49
- return undefined;
50
- }
51
- return podName;
52
- }
53
- toEmptySchema(schema) {
54
- if (!schema || typeof schema !== 'object') {
55
- return { generic: {} };
56
- }
57
- const normalized = { generic: {} };
58
- Object.keys(schema).forEach((serviceName) => {
59
- const category = schema[serviceName];
60
- normalized[serviceName] = category && typeof category === 'object' ? Object.assign({}, category) : {};
61
- });
62
- if (!normalized.generic) {
63
- normalized.generic = {};
64
- }
65
- return normalized;
66
- }
67
- getConfig(section, podName) {
68
- return __awaiter(this, void 0, void 0, function* () {
69
- try {
70
- const id = this.getDocId(section, podName);
71
- const docRef = this.db.collection(this.secretsCollection).doc(id);
72
- const docSnap = yield docRef.get();
73
- const docData = docSnap.data();
74
- return {
75
- id,
76
- section,
77
- podName,
78
- schema: this.toEmptySchema(docData === null || docData === void 0 ? void 0 : docData.schema),
79
- updatedAtMills: (docData === null || docData === void 0 ? void 0 : docData.updatedAtMills) || Date.now(),
80
- updatedBy: (docData === null || docData === void 0 ? void 0 : docData.updatedBy) || 'NA',
81
- };
82
- }
83
- catch (error) {
84
- throw new Error(`Failed to retrieve config: ${error}`);
85
- }
86
- });
87
- }
88
- storeConfig(section, podName, schema, updatedBy = 'NA') {
89
- return __awaiter(this, void 0, void 0, function* () {
90
- try {
91
- const id = this.getDocId(section, podName);
92
- const configDoc = {
93
- id,
94
- section,
95
- podName,
96
- schema: this.toEmptySchema(schema),
97
- updatedAtMills: Date.now(),
98
- updatedBy,
99
- };
100
- const docRef = this.db.collection(this.secretsCollection).doc(id);
101
- yield docRef.set(configDoc);
102
- }
103
- catch (error) {
104
- throw new Error(`Failed to store config: ${error}`);
105
- }
106
- });
107
- }
108
- getAll(section) {
109
- return __awaiter(this, void 0, void 0, function* () {
110
- try {
111
- const snapshot = yield this.db.collection(this.secretsCollection).get();
112
- const configs = {};
113
- snapshot.forEach((doc) => {
114
- if (!this.isDocFromSection(section, doc.id)) {
115
- return;
116
- }
117
- const docData = doc.data();
118
- const podName = docData.podName || this.getPodNameFromDocId(section, doc.id);
119
- if (!podName) {
120
- return;
121
- }
122
- if (section === 'secrets' && podName !== 'global') {
123
- return;
124
- }
125
- configs[podName] = this.toEmptySchema(docData.schema);
126
- });
127
- return configs;
128
- }
129
- catch (error) {
130
- throw new Error(`Failed to retrieve all configs for section ${section}: ${error}`);
131
- }
132
- });
133
- }
134
- getAllConfigs() {
135
- return __awaiter(this, void 0, void 0, function* () {
136
- try {
137
- const snapshot = yield this.db.collection(this.secretsCollection).get();
138
- const envVariables = {};
139
- const secrets = {};
140
- snapshot.forEach((doc) => {
141
- if (doc.id.startsWith(this.envDocPrefix) && doc.id !== this.globalSecretsDocId) {
142
- const docData = doc.data();
143
- const podName = docData.podName || this.getPodNameFromDocId('envVariables', doc.id);
144
- if (!podName) {
145
- return;
146
- }
147
- envVariables[podName] = this.toEmptySchema(docData.schema);
148
- return;
149
- }
150
- if (doc.id === this.globalSecretsDocId) {
151
- const docData = doc.data();
152
- secrets.global = this.toEmptySchema(docData.schema);
153
- }
154
- });
155
- return {
156
- envVariables,
157
- secrets,
158
- };
159
- }
160
- catch (error) {
161
- throw new Error(`Failed to retrieve all configs: ${error}`);
162
- }
163
- });
164
- }
165
- }
166
- exports.FirestoreConfigManager = FirestoreConfigManager;
@@ -1,13 +0,0 @@
1
- import { ResolvedFunctionResponse } from '../../apis';
2
- import { ConfigManagerService } from './configManager.service';
3
- import { CheckConflictsResponse, GetConfigRequest, PodConfigData, StoreConfigRequest, UnifiedConfigsData } from './configManager.model';
4
- export declare class ConfigManagerHelper {
5
- private service;
6
- constructor(service?: ConfigManagerService);
7
- getAllConfigs(): ResolvedFunctionResponse<UnifiedConfigsData>;
8
- getConfig(request: GetConfigRequest): ResolvedFunctionResponse<PodConfigData>;
9
- storeConfig(request: StoreConfigRequest): ResolvedFunctionResponse<{
10
- success: boolean;
11
- }>;
12
- checkConflicts(request: StoreConfigRequest): ResolvedFunctionResponse<CheckConflictsResponse>;
13
- }
@@ -1,32 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ConfigManagerHelper = void 0;
4
- const apis_1 = require("../../apis");
5
- const configManager_service_1 = require("./configManager.service");
6
- class ConfigManagerHelper {
7
- constructor(service = new configManager_service_1.ConfigManagerService()) {
8
- this.service = service;
9
- }
10
- getAllConfigs() {
11
- return this.service.getAllConfigs();
12
- }
13
- getConfig(request) {
14
- if (!(request === null || request === void 0 ? void 0 : request.podName)) {
15
- return Promise.resolve(apis_1.FunctionResponseHelper.failed(apis_1.ErrorCodes.VALIDATION_FAILED, 'podName is required', 'podName is required'));
16
- }
17
- return this.service.getConfig(request);
18
- }
19
- storeConfig(request) {
20
- if (!(request === null || request === void 0 ? void 0 : request.section) || !(request === null || request === void 0 ? void 0 : request.podName) || !(request === null || request === void 0 ? void 0 : request.schema)) {
21
- return Promise.resolve(apis_1.FunctionResponseHelper.failed(apis_1.ErrorCodes.VALIDATION_FAILED, 'section, podName and schema are required', 'section, podName and schema are required'));
22
- }
23
- return this.service.storeConfig(request);
24
- }
25
- checkConflicts(request) {
26
- if (!(request === null || request === void 0 ? void 0 : request.section) || !(request === null || request === void 0 ? void 0 : request.podName) || !(request === null || request === void 0 ? void 0 : request.schema)) {
27
- return Promise.resolve(apis_1.FunctionResponseHelper.failed(apis_1.ErrorCodes.VALIDATION_FAILED, 'section, podName and schema are required', 'section, podName and schema are required'));
28
- }
29
- return this.service.checkConflicts(request);
30
- }
31
- }
32
- exports.ConfigManagerHelper = ConfigManagerHelper;
@@ -1,38 +0,0 @@
1
- import { PodNameOrGlobal, SecretSchema } from './secretManager.model';
2
- export type ConfigSection = 'envVariables' | 'secrets';
3
- export interface StoreConfigRequest {
4
- section: ConfigSection;
5
- podName: PodNameOrGlobal;
6
- schema: SecretSchema;
7
- }
8
- export interface GetConfigRequest {
9
- podName: PodNameOrGlobal;
10
- }
11
- export interface UnifiedConfigsData {
12
- envVariables: Record<string, SecretSchema>;
13
- secrets: Record<string, SecretSchema>;
14
- }
15
- export interface PodConfigData {
16
- podName: PodNameOrGlobal;
17
- envVariables: SecretSchema;
18
- secrets: Record<'global', SecretSchema>;
19
- }
20
- export interface ConflictItem {
21
- serviceName: string;
22
- keyName: string;
23
- existingPods: string[];
24
- currentValue: string;
25
- existingValues: Record<string, string>;
26
- }
27
- export interface CheckConflictsResponse {
28
- hasConflicts: boolean;
29
- conflicts: ConflictItem[];
30
- }
31
- export interface ConfigDocument {
32
- id: string;
33
- section: ConfigSection;
34
- podName: PodNameOrGlobal;
35
- schema: SecretSchema;
36
- updatedAtMills: number;
37
- updatedBy: string;
38
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,17 +0,0 @@
1
- import { ResolvedFunctionResponse } from '../../apis';
2
- import { FirestoreConfigManager } from './configManager.firestore';
3
- import { CheckConflictsResponse, GetConfigRequest, StoreConfigRequest, UnifiedConfigsData, PodConfigData } from './configManager.model';
4
- export declare class ConfigManagerService {
5
- private configStore;
6
- constructor(configStore?: FirestoreConfigManager);
7
- private normalizeSchema;
8
- private validateSectionAndPod;
9
- getAllConfigs(): ResolvedFunctionResponse<UnifiedConfigsData>;
10
- getConfig({ podName }: GetConfigRequest): ResolvedFunctionResponse<PodConfigData>;
11
- storeConfig(request: StoreConfigRequest): ResolvedFunctionResponse<{
12
- success: boolean;
13
- }>;
14
- private getExistingPodsAndValues;
15
- checkConflicts(request: StoreConfigRequest): ResolvedFunctionResponse<CheckConflictsResponse>;
16
- static getInvalidSecretsPodMessage(): string;
17
- }
@@ -1,138 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.ConfigManagerService = void 0;
13
- const apis_1 = require("../../apis");
14
- const configManager_firestore_1 = require("./configManager.firestore");
15
- const INVALID_SECRETS_POD_ERROR = 'Secrets are supported only for podName=global';
16
- class ConfigManagerService {
17
- constructor(configStore = configManager_firestore_1.FirestoreConfigManager.getInstance()) {
18
- this.configStore = configStore;
19
- }
20
- normalizeSchema(schema) {
21
- if (!schema || typeof schema !== 'object') {
22
- return { generic: {} };
23
- }
24
- const normalized = { generic: {} };
25
- Object.keys(schema).forEach((serviceName) => {
26
- const category = schema[serviceName];
27
- normalized[serviceName] = category && typeof category === 'object' ? Object.assign({}, category) : {};
28
- });
29
- if (!normalized.generic) {
30
- normalized.generic = {};
31
- }
32
- return normalized;
33
- }
34
- validateSectionAndPod(section, podName) {
35
- if (section === 'secrets' && podName !== 'global') {
36
- return INVALID_SECRETS_POD_ERROR;
37
- }
38
- return null;
39
- }
40
- getAllConfigs() {
41
- var _a;
42
- return __awaiter(this, void 0, void 0, function* () {
43
- const allConfigs = yield this.configStore.getAllConfigs();
44
- const envVariables = {};
45
- Object.keys(allConfigs.envVariables || {}).forEach((podName) => {
46
- envVariables[podName] = this.normalizeSchema(allConfigs.envVariables[podName]);
47
- });
48
- const secrets = {};
49
- if ((_a = allConfigs.secrets) === null || _a === void 0 ? void 0 : _a.global) {
50
- secrets.global = this.normalizeSchema(allConfigs.secrets.global);
51
- }
52
- return apis_1.FunctionResponseHelper.success({
53
- envVariables,
54
- secrets,
55
- });
56
- });
57
- }
58
- getConfig({ podName }) {
59
- return __awaiter(this, void 0, void 0, function* () {
60
- const [envConfig, globalSecretConfig] = yield Promise.all([
61
- this.configStore.getConfig('envVariables', podName),
62
- this.configStore.getConfig('secrets', 'global'),
63
- ]);
64
- return apis_1.FunctionResponseHelper.success({
65
- podName,
66
- envVariables: this.normalizeSchema(envConfig.schema),
67
- secrets: {
68
- global: this.normalizeSchema(globalSecretConfig.schema),
69
- },
70
- });
71
- });
72
- }
73
- storeConfig(request) {
74
- return __awaiter(this, void 0, void 0, function* () {
75
- const validationError = this.validateSectionAndPod(request.section, request.podName);
76
- if (validationError) {
77
- return apis_1.FunctionResponseHelper.failed(apis_1.ErrorCodes.VALIDATION_FAILED, validationError, validationError);
78
- }
79
- yield this.configStore.storeConfig(request.section, request.podName, this.normalizeSchema(request.schema));
80
- return apis_1.FunctionResponseHelper.success({ success: true });
81
- });
82
- }
83
- getExistingPodsAndValues(section, podName, allConfigs, serviceName, keyName) {
84
- const existingValues = {};
85
- Object.keys(allConfigs).forEach((existingPodName) => {
86
- var _a, _b;
87
- if (section === 'envVariables' && existingPodName === podName) {
88
- return;
89
- }
90
- const existingValue = (_b = (_a = allConfigs[existingPodName]) === null || _a === void 0 ? void 0 : _a[serviceName]) === null || _b === void 0 ? void 0 : _b[keyName];
91
- if (typeof existingValue === 'string') {
92
- existingValues[existingPodName] = existingValue;
93
- }
94
- });
95
- return existingValues;
96
- }
97
- checkConflicts(request) {
98
- return __awaiter(this, void 0, void 0, function* () {
99
- const validationError = this.validateSectionAndPod(request.section, request.podName);
100
- if (validationError) {
101
- return apis_1.FunctionResponseHelper.failed(apis_1.ErrorCodes.VALIDATION_FAILED, validationError, validationError);
102
- }
103
- const normalizedSchema = this.normalizeSchema(request.schema);
104
- const allConfigs = yield this.configStore.getAll(request.section);
105
- const conflicts = [];
106
- Object.keys(normalizedSchema).forEach((serviceName) => {
107
- const keys = normalizedSchema[serviceName] || {};
108
- Object.keys(keys).forEach((keyName) => {
109
- const currentValue = keys[keyName] || '';
110
- const existingValues = this.getExistingPodsAndValues(request.section, request.podName, allConfigs, serviceName, keyName);
111
- const existingPods = Object.keys(existingValues);
112
- if (existingPods.length === 0) {
113
- return;
114
- }
115
- const hasDifferentValue = existingPods.some((pod) => existingValues[pod] !== currentValue);
116
- if (!hasDifferentValue) {
117
- return;
118
- }
119
- conflicts.push({
120
- serviceName,
121
- keyName,
122
- existingPods,
123
- currentValue,
124
- existingValues,
125
- });
126
- });
127
- });
128
- return apis_1.FunctionResponseHelper.success({
129
- hasConflicts: conflicts.length > 0,
130
- conflicts,
131
- });
132
- });
133
- }
134
- static getInvalidSecretsPodMessage() {
135
- return INVALID_SECRETS_POD_ERROR;
136
- }
137
- }
138
- exports.ConfigManagerService = ConfigManagerService;
@@ -1 +0,0 @@
1
- export {};
@@ -1,60 +0,0 @@
1
- "use strict";
2
- // Boilerplate code to easily run bik-shared-backend locally
3
- // To run this in local please do npx tsc && npx ts-node src/core/local_runner.ts
4
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6
- return new (P || (P = Promise))(function (resolve, reject) {
7
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
9
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
10
- step((generator = generator.apply(thisArg, _arguments || [])).next());
11
- });
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- const setup_1 = __importDefault(require("../logger/setup"));
18
- const setup_2 = require("./setup");
19
- const alertsV2_service_1 = require("../alertsV2/alertsV2.service");
20
- const constants_1 = require("@bikdotai/bik-models/core/constants");
21
- setup_2.BikBackendSetup.setUpV2({
22
- slackConfiguration: {
23
- slackChannelId: 'C04LEGSM0Q2',
24
- },
25
- useSharedFirebase: true,
26
- }).then(() => {
27
- setup_1.default.setUp([console, console]);
28
- console.log('BikBackendSetup done');
29
- // Uncomment to run the simulation when you start this file.
30
- for (let i = 0; i < 1; i++) {
31
- simulateSendAlert().then().catch(console.error);
32
- }
33
- });
34
- /**
35
- * Function to simulate concurrent Redis requests
36
- */
37
- // async function test() {}
38
- // test().then().catch();
39
- /**
40
- * Minimal local simulation for Alerts V2 `sendAlert`.
41
- *
42
- * Notes:
43
- * - This hits repo lookups + channel senders.
44
- * - If `alertConfigId` doesn't exist (or is inactive), you'd see `RESOURCE_NOT_FOUND` or a success no-op.
45
- * - Keep `types` undefined to use whatever channels are configured on the alert config.
46
- */
47
- function simulateSendAlert() {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- const alertsV2Service = new alertsV2_service_1.AlertsV2Service();
50
- // TODO: Replace these with real IDs from your env.
51
- const res = yield alertsV2Service.sendAlert({
52
- alertConfigId: 'PE294r6xtYgMzCVMgiEK',
53
- storeId: 'p60HYv5wjgQaOrPdqT5NjbpkroD2',
54
- sentBy: constants_1.POD_NAME.CAMPAIGN,
55
- agentId: ['amankun77@gmail.com'],
56
- variables: ['Hi', 'Sir', 'Aman', 'You have been conned', "https://google.co.in", "go to google.com"],
57
- });
58
- console.log('sendAlert response:', JSON.stringify(res, null, 2));
59
- });
60
- }
@@ -1,95 +0,0 @@
1
- /**
2
- * Types and Interfaces for Database Service
3
- */
4
- import { Sequelize } from 'sequelize';
5
- import { Pool } from 'pg';
6
- /**
7
- * PostgreSQL configuration interface
8
- */
9
- export interface PgConfig {
10
- username: string;
11
- password: string;
12
- host: string;
13
- read?: Array<{
14
- host: string;
15
- }>;
16
- database: string;
17
- dialect: string;
18
- schema: string;
19
- port: number;
20
- }
21
- /**
22
- * Options for creating a Sequelize connection
23
- */
24
- export interface SequelizeConnectionOptions {
25
- /** Maximum number of connections in the pool (default: 15) */
26
- maxConnections?: number;
27
- /** Minimum number of connections in the pool (default: 1) */
28
- minConnections?: number;
29
- /** Maximum time in milliseconds to acquire a connection (default: 60000) */
30
- acquireTimeout?: number;
31
- /** Maximum time in milliseconds for a connection to be idle before being released (default: 1000) */
32
- idleTimeout?: number;
33
- /** Maximum number of retry attempts for failed connections (default: 20) */
34
- maxRetries?: number;
35
- /** Initial backoff duration in milliseconds for retries (default: 500) */
36
- backoffBase?: number;
37
- /** Exponent to increase backoff duration on each retry (default: 1.2) */
38
- backoffExponent?: number;
39
- /** Enable SQL query logging (default: false) */
40
- enableLogging?: boolean;
41
- /** Override database schema from secret */
42
- customSchema?: string;
43
- /**
44
- * Enable API metadata in SQL queries for tracking (default: true)
45
- *
46
- * When enabled, automatically sets PostgreSQL application_name to 'bik:{apiName}'
47
- * for every query, making it visible in:
48
- * - Aurora Performance Insights (group by application_name dimension)
49
- * - pg_stat_activity (real-time query monitoring)
50
- * - CloudWatch Logs (historical analysis)
51
- *
52
- * API name is extracted from LogExecutionContextHelper.getContext()?.apiName
53
- * Format: 'bik:{apiName}' for write pools, 'bik:{apiName}:read' for reader pools
54
- */
55
- enableQueryMetadata?: boolean;
56
- }
57
- /**
58
- * Options for creating a PostgreSQL Pool connection
59
- */
60
- export interface PoolConnectionOptions {
61
- /** Maximum number of connections in the pool (default: 15) */
62
- maxConnections?: number;
63
- /** Minimum number of connections in the pool (default: 0) */
64
- minConnections?: number;
65
- /** Connection idle timeout in milliseconds (default: 1000) */
66
- idleTimeout?: number;
67
- }
68
- /**
69
- * Result of creating all database connections
70
- */
71
- export interface DatabaseConnections {
72
- /** Sequelize ORM instance for complex queries and models */
73
- sequelize: Sequelize;
74
- /** PostgreSQL Pool for write operations */
75
- pool: Pool;
76
- /** PostgreSQL Pool for read operations (uses read replicas) */
77
- readerPool: Pool;
78
- }
79
- /**
80
- * Connections object for cleanup
81
- */
82
- export interface ConnectionsToClose {
83
- sequelize?: Sequelize;
84
- pool?: Pool;
85
- readerPool?: Pool;
86
- }
87
- /**
88
- * Options passed to Sequelize beforeQuery hook
89
- */
90
- export interface BeforeQueryOptions {
91
- sql?: string;
92
- bind?: any;
93
- type?: string;
94
- [key: string]: any;
95
- }
@@ -1,5 +0,0 @@
1
- "use strict";
2
- /**
3
- * Types and Interfaces for Database Service
4
- */
5
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,90 +0,0 @@
1
- /**
2
- * Database Service
3
- *
4
- * Provides generic database connection management for PostgreSQL using Sequelize and node-postgres.
5
- * Supports connection pooling, read replicas, auto-retry logic, and Secret Manager integration.
6
- */
7
- import { Sequelize } from 'sequelize';
8
- import { Pool } from 'pg';
9
- import { SequelizeConnectionOptions, PoolConnectionOptions, DatabaseConnections, ConnectionsToClose } from './database.model';
10
- export declare const databaseSchema: string;
11
- export declare const ENABLE_SEQUELIZE_LOGGING: boolean;
12
- /**
13
- * Service class for managing database connections
14
- * Provides generic functions to create Sequelize and pg Pool connections
15
- */
16
- export declare class DatabaseService {
17
- private static pgConfigCache;
18
- /**
19
- * Get PostgreSQL configuration from secrets
20
- * @param secretKeyName - Optional custom secret key name (defaults to 'aurora-common')
21
- * @returns Promise<PgConfig>
22
- */
23
- private static getPgConfig;
24
- /**
25
- * Reset the cached config (useful for testing or when secrets change)
26
- */
27
- static resetConfigCache(): void;
28
- /**
29
- * Create a Sequelize instance with optimal configuration
30
- * @param options - Optional configuration for connection pooling and retry logic
31
- * @param secretKeyName - Optional custom secret key name
32
- * @returns Promise<Sequelize>
33
- */
34
- static createSequelizeConnection(options?: SequelizeConnectionOptions, secretKeyName?: string): Promise<Sequelize>;
35
- /**
36
- * Create a PostgreSQL Pool for raw queries (write operations)
37
- * @param options - Optional configuration for connection pooling
38
- * @param secretKeyName - Optional custom secret key name
39
- * @returns Promise<Pool>
40
- */
41
- static createPool(options?: PoolConnectionOptions, secretKeyName?: string): Promise<Pool>;
42
- /**
43
- * Create a PostgreSQL Pool for read operations (using read replicas)
44
- * @param options - Optional configuration for connection pooling
45
- * @param secretKeyName - Optional custom secret key name
46
- * @returns Promise<Pool>
47
- */
48
- static createReaderPool(options?: PoolConnectionOptions, secretKeyName?: string): Promise<Pool>;
49
- /**
50
- * Create all database connections at once
51
- * Useful for initializing all required connections at application startup
52
- * @param options - Optional configuration for connection pooling
53
- * @param secretKeyName - Optional custom secret key name
54
- * @returns Promise with all connection types
55
- */
56
- static createAllConnections(options?: SequelizeConnectionOptions & PoolConnectionOptions, secretKeyName?: string): Promise<DatabaseConnections>;
57
- /**
58
- * Test database connection
59
- * @param sequelize - Sequelize instance to test
60
- * @returns Promise<boolean>
61
- */
62
- static testConnection(sequelize: Sequelize): Promise<boolean>;
63
- /**
64
- * Gracefully close all connections
65
- * @param connections - Object containing all connection instances
66
- */
67
- static closeConnections(connections: ConnectionsToClose): Promise<void>;
68
- }
69
- /**
70
- * Get or create the default Sequelize instance (Singleton)
71
- * @returns Promise<Sequelize>
72
- */
73
- export declare const getDefaultSequelize: () => Promise<Sequelize>;
74
- /**
75
- * Get or create the default Pool instance (Singleton)
76
- * @returns Promise<Pool>
77
- */
78
- export declare const getDefaultPool: () => Promise<Pool>;
79
- /**
80
- * Get or create the default Reader Pool instance (Singleton)
81
- * @returns Promise<Pool>
82
- */
83
- export declare const getDefaultReaderPool: () => Promise<Pool>;
84
- /**
85
- * Reset all singleton instances (useful for testing)
86
- */
87
- export declare const resetDefaultConnections: () => void;
88
- export declare const BikSequelize: Promise<Sequelize>;
89
- export declare const pool: Promise<Pool>;
90
- export declare const readerPool: Promise<Pool>;