@bikdotai/bik-shared-backend 20.3.1 → 20.3.2-beta.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 (80) hide show
  1. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncDelay.d.ts +1 -0
  2. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncDelay.js +4 -0
  3. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncFailed.d.ts +1 -0
  4. package/lib/alerts/templates/campaign/campaignMovedToDraftSegmentSyncFailed.js +4 -0
  5. package/lib/alerts/templates/campaign/campaignScheduledTimeExceededDueToSyncDelay.d.ts +1 -0
  6. package/lib/alerts/templates/campaign/campaignScheduledTimeExceededDueToSyncDelay.js +4 -0
  7. package/lib/alertsV2/alertInstances.repo.js +26 -2
  8. package/lib/alertsV2/alertsV2.helper.d.ts +3 -4
  9. package/lib/alertsV2/alertsV2.helper.js +49 -3
  10. package/lib/alertsV2/alertsV2.service.js +14 -5
  11. package/lib/auth/authMiddlewares.js +68 -3
  12. package/lib/auth/firebase-auth.service.js +3 -3
  13. package/lib/auth/implementations/bik-admin-auth-service.d.ts +1 -1
  14. package/lib/auth/implementations/bik-admin-auth-service.js +2 -1
  15. package/lib/auth/index.d.ts +3 -0
  16. package/lib/auth/index.js +3 -0
  17. package/lib/auth/secret-manager/configManager.firestore.d.ts +22 -0
  18. package/lib/auth/secret-manager/configManager.firestore.js +166 -0
  19. package/lib/auth/secret-manager/configManager.helper.d.ts +13 -0
  20. package/lib/auth/secret-manager/configManager.helper.js +32 -0
  21. package/lib/auth/secret-manager/configManager.model.d.ts +38 -0
  22. package/lib/auth/secret-manager/configManager.model.js +2 -0
  23. package/lib/auth/secret-manager/configManager.service.d.ts +17 -0
  24. package/lib/auth/secret-manager/configManager.service.js +138 -0
  25. package/lib/auth/secret-manager/env-variables/variables.list.d.ts +3 -0
  26. package/lib/auth/secret-manager/env-variables/variables.list.js +3 -0
  27. package/lib/chat-handover-protocol/chat-handover-protocol.js +26 -41
  28. package/lib/core/local_runner.js +28 -11
  29. package/lib/core/setup.d.ts +3 -0
  30. package/lib/core/setup.js +24 -2
  31. package/lib/database/database.model.d.ts +95 -0
  32. package/lib/database/database.model.js +5 -0
  33. package/lib/database/database.service.d.ts +90 -0
  34. package/lib/database/database.service.js +382 -0
  35. package/lib/database/index.d.ts +7 -0
  36. package/lib/database/index.js +23 -0
  37. package/lib/elastic/counter/ingestion.js +1 -0
  38. package/lib/elastic/queries/campaign/getBroadcastDetailedStats.d.ts +117 -0
  39. package/lib/elastic/queries/campaign/getBroadcastDetailedStats.js +94 -1
  40. package/lib/elastic/queries/campaign/getUniqueCustomerCnt.d.ts +1 -0
  41. package/lib/elastic/queries/campaign/getUniqueCustomerCnt.js +1 -0
  42. package/lib/elastic/queries/chatbot/getAgentCostForBroadcast.d.ts +117 -0
  43. package/lib/elastic/queries/chatbot/getAgentCostForBroadcast.js +98 -0
  44. package/lib/elastic/queries/chatbot/getAiOperations.d.ts +5 -5
  45. package/lib/elastic/queries/chatbot/getAiOperations.js +3 -3
  46. package/lib/elastic/queries/chatbot/index.d.ts +1 -0
  47. package/lib/elastic/queries/chatbot/index.js +1 -0
  48. package/lib/elastic/queries/crm/getActivityTimelineByAgent.js +1 -1
  49. package/lib/elastic/queries/crm/getBreachedSLACount.d.ts +1 -0
  50. package/lib/elastic/queries/crm/getBreachedSLACount.js +8 -5
  51. package/lib/elastic/queries/crm/getFirstResponseTime.d.ts +1 -0
  52. package/lib/elastic/queries/crm/getFirstResponseTime.js +8 -5
  53. package/lib/elastic/queries/integrations/getOrdersShadowServices.d.ts +76 -0
  54. package/lib/elastic/queries/integrations/getOrdersShadowServices.js +61 -0
  55. package/lib/elastic/queries/integrations/index.d.ts +1 -0
  56. package/lib/elastic/queries/integrations/index.js +1 -0
  57. package/lib/elastic/queries/openAi/addToCartSession.d.ts +1 -0
  58. package/lib/elastic/queries/openAi/addToCartSession.js +11 -3
  59. package/lib/elastic/queries/openAi/checkoutCompletedSession.d.ts +1 -0
  60. package/lib/elastic/queries/openAi/checkoutCompletedSession.js +11 -3
  61. package/lib/elastic/reports/crm/index.d.ts +1 -0
  62. package/lib/elastic/reports/crm/index.js +1 -0
  63. package/lib/elastic/reports/reports.service.js +17 -8
  64. package/lib/events/events.d.ts +8 -0
  65. package/lib/events/events.js +25 -1
  66. package/lib/events/schema/events.helper.d.ts +1 -0
  67. package/lib/events/schema/events.helper.js +12 -6
  68. package/lib/index.d.ts +1 -0
  69. package/lib/index.js +1 -0
  70. package/lib/merchant-events/elastic.search.d.ts +5 -0
  71. package/lib/merchant-events/elastic.search.js +23 -2
  72. package/lib/merchant-events/merchant.service.d.ts +1 -1
  73. package/lib/merchant-events/merchant.service.js +12 -11
  74. package/lib/recordAnalytics/recordAnalytics.service.js +5 -4
  75. package/lib/redis/redisPubSubService.d.ts +4 -6
  76. package/lib/redis/redisPubSubService.js +211 -123
  77. package/lib/redis/redisService.js +14 -8
  78. package/lib/swagger/SwaggerSchemaHelper.js +21 -17
  79. package/lib/user-properties/userProperties.service.js +1 -0
  80. package/package.json +2 -2
@@ -1,4 +1,6 @@
1
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
2
4
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
5
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
6
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -13,9 +15,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
15
  };
14
16
  Object.defineProperty(exports, "__esModule", { value: true });
15
17
  const setup_1 = __importDefault(require("../logger/setup"));
16
- const merchant_events_1 = require("../merchant-events");
17
- const podName_1 = require("./podName");
18
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");
19
21
  setup_2.BikBackendSetup.setUpV2({
20
22
  slackConfiguration: {
21
23
  slackChannelId: 'C04LEGSM0Q2',
@@ -24,20 +26,35 @@ setup_2.BikBackendSetup.setUpV2({
24
26
  }).then(() => {
25
27
  setup_1.default.setUp([console, console]);
26
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
+ }
27
33
  });
28
34
  /**
29
35
  * Function to simulate concurrent Redis requests
30
36
  */
31
- function test() {
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() {
32
48
  return __awaiter(this, void 0, void 0, function* () {
33
- const es = yield merchant_events_1.ElasticSearchService.getInstance(undefined, '9kzbACQO05VTLsIGHRz2Ws9OlLt2');
34
- es.executeQuery(podName_1.PodName.Campaign, 'broadcastSentCountByBroadcastId', {
35
- broadcastIds: ['389961', '389804'],
36
- storeId: '9kzbACQO05VTLsIGHRz2Ws9OlLt2',
37
- indexName: 'events-prod-alias',
38
- }).then((res) => {
39
- console.log('ES Response:', JSON.stringify(res, null, 2));
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"],
40
57
  });
58
+ console.log('sendAlert response:', JSON.stringify(res, null, 2));
41
59
  });
42
60
  }
43
- test().then().catch();
@@ -12,6 +12,9 @@ export interface BikBackendOptions {
12
12
  export declare class BikBackendSetup {
13
13
  static options: BikBackendOptions;
14
14
  static useSharedFirebase?: boolean;
15
+ private static didLogPackageVersions;
16
+ private static readPackageVersion;
17
+ private static logPackageVersionsOnce;
15
18
  static fetchServiceName(): string | undefined;
16
19
  static fetchPodName(): PodName | undefined;
17
20
  static setUp(options: BikBackendOptions): void;
package/lib/core/setup.js CHANGED
@@ -23,7 +23,27 @@ const auth_1 = require("../auth");
23
23
  const deprecated_1 = require("./decorators/deprecated");
24
24
  const refresh_pod_service_1 = require("../refresh/refresh-pod.service");
25
25
  const setup_1 = __importDefault(require("../logger/setup"));
26
+ const local_1 = require("./local");
26
27
  class BikBackendSetup {
28
+ static readPackageVersion(requireIdOrPath) {
29
+ try {
30
+ const pkg = require(requireIdOrPath);
31
+ const version = pkg === null || pkg === void 0 ? void 0 : pkg.version;
32
+ return typeof version === 'string' ? version : undefined;
33
+ }
34
+ catch (_a) {
35
+ return undefined;
36
+ }
37
+ }
38
+ static logPackageVersionsOnce() {
39
+ var _a, _b, _c, _d;
40
+ if (BikBackendSetup.didLogPackageVersions)
41
+ return;
42
+ BikBackendSetup.didLogPackageVersions = true;
43
+ const backendVersion = (_a = BikBackendSetup.readPackageVersion('../../package.json')) !== null && _a !== void 0 ? _a : 'unknown';
44
+ const bikModelsVersion = (_d = (_c = (_b = BikBackendSetup.readPackageVersion('@bikdotai/bik-models/package.json')) !== null && _b !== void 0 ? _b : BikBackendSetup.readPackageVersion('bik-models/package.json')) !== null && _c !== void 0 ? _c : BikBackendSetup.readPackageVersion(`${__dirname}/../../../bik-models/package.json`)) !== null && _d !== void 0 ? _d : 'unknown';
45
+ console.log(`[BikBackendSetup] versions: @bikdotai/bik-shared-backend=${backendVersion}, @bikdotai/bik-models=${bikModelsVersion}`);
46
+ }
27
47
  static fetchServiceName() {
28
48
  return auth_1.EnvVariableHelper.accessRaw('service_name');
29
49
  }
@@ -48,6 +68,7 @@ class BikBackendSetup {
48
68
  if (!options.serviceName) {
49
69
  options.serviceName = this.fetchServiceName();
50
70
  }
71
+ BikBackendSetup.logPackageVersionsOnce();
51
72
  if (options.useSharedFirebase) {
52
73
  BikBackendSetup.useSharedFirebase = options.useSharedFirebase;
53
74
  (0, auth_1.initializeFirebaseConfig)(options.serviceAccountId);
@@ -64,16 +85,17 @@ class BikBackendSetup {
64
85
  // Hot-reload listener is now keyed by pod (was service). All services in
65
86
  // a pod share one `bik:refresh:{podName}` channel and one log-config secret.
66
87
  // Non-fatal if Redis is unavailable.
67
- if (options.podName) {
88
+ if (options.podName && !(0, local_1.isLocal)()) {
68
89
  refresh_pod_service_1.RefreshPodService.initialize(options.podName);
69
90
  }
70
91
  else {
71
- console.warn('[BikBackendSetup] No podName provided; hot-reload listener not started.');
92
+ console.warn('[BikBackendSetup] No podName provided or running in local environment; hot-reload listener not started.');
72
93
  }
73
94
  });
74
95
  }
75
96
  }
76
97
  BikBackendSetup.useSharedFirebase = false;
98
+ BikBackendSetup.didLogPackageVersions = false;
77
99
  __decorate([
78
100
  (0, deprecated_1.deprecated)('This method will be removed soon. Use setUpV2() instead.')
79
101
  ], BikBackendSetup, "setUp", null);
@@ -0,0 +1,95 @@
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
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Types and Interfaces for Database Service
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,90 @@
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>;