@bikdotai/bik-shared-backend 20.3.2-beta.4 → 20.4.0

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,27 +1,4 @@
1
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -33,7 +10,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
33
10
  };
34
11
  Object.defineProperty(exports, "__esModule", { value: true });
35
12
  exports.AlertInstancesRepo = void 0;
36
- const admin = __importStar(require("firebase-admin"));
37
13
  const auth_1 = require("../auth");
38
14
  const bik_models_1 = require("@bikdotai/bik-models");
39
15
  class AlertInstancesRepo {
@@ -54,7 +30,7 @@ class AlertInstancesRepo {
54
30
  return __awaiter(this, void 0, void 0, function* () {
55
31
  try {
56
32
  const docRef = id ? this.dbRef().doc(id) : this.dbRef().doc();
57
- const alertInstanceData = Object.assign(Object.assign({}, instance), { id: docRef.id, createdAt: admin.firestore.Timestamp.now().toDate().toISOString() });
33
+ const alertInstanceData = Object.assign(Object.assign({}, instance), { id: docRef.id, createdAt: new Date().toISOString() });
58
34
  yield docRef.set(alertInstanceData);
59
35
  return {
60
36
  id: docRef.id,
@@ -71,7 +47,7 @@ class AlertInstancesRepo {
71
47
  return __awaiter(this, void 0, void 0, function* () {
72
48
  try {
73
49
  const batch = this.db.batch();
74
- const createdAt = admin.firestore.Timestamp.now().toDate().toISOString();
50
+ const createdAt = new Date().toISOString();
75
51
  instances.forEach((instance) => {
76
52
  const docRef = this.dbRef().doc();
77
53
  const alertInstanceData = Object.assign(Object.assign({}, instance), { id: docRef.id, createdAt });
@@ -4,12 +4,13 @@ export declare class AlertsV2Helper {
4
4
  private static validateTemplate;
5
5
  private static validateEmailConfig;
6
6
  static getRecipients(body: AlertsV2.GetRecipientsRequest): ResolvedFunctionResponse<AlertsV2.GetUsersByRolesResponse>;
7
- static getPhoneNumberFromAgentEmail(body: AlertsV2.getPhoneNumberFromAgentEmailRequest): ResolvedFunctionResponse<AlertsV2.getPhoneNumberFromAgentEmailResponse>;
8
- static getUserByAgentId(body: AlertsV2.GetUserByAgentIdRequest): ResolvedFunctionResponse<AlertsV2.GetUserByAgentIdResponse>;
7
+ static getUserByAgentId(body: {
8
+ agentId: string;
9
+ storeId: string;
10
+ }): ResolvedFunctionResponse<AlertsV2.GetUserByAgentIdResponse>;
9
11
  static validateCreateAlertConfig(body: AlertsV2.CreateAlertConfigRequest): ResolvedFunctionResponse<void>;
10
12
  static validateSendAlert(body: AlertsV2.SendAlertRequest, hasCurrentUser: boolean): FunctionResponse<void>;
11
13
  static validateSendWhatsappAlert(body: AlertsV2.SendWhatsappAlertRequest): FunctionResponse<void>;
12
14
  static validateAndReplaceVariables(request: AlertsV2.ValidateAndReplaceVariablesRequest): FunctionResponse<AlertsV2.ValidatedComponentPayload>;
13
15
  static extractContactInfo(recipients: AlertsV2.UserContactInfo[]): AlertsV2.ExtractedContactInfo;
14
- static extractSingleContactInfo(recipients: AlertsV2.UserContactInfo): AlertsV2.ExtractedContactInfo;
15
16
  }
@@ -83,11 +83,11 @@ class AlertsV2Helper {
83
83
  return apis_1.FunctionResponseHelper.success(responseData);
84
84
  });
85
85
  }
86
- static getPhoneNumberFromAgentEmail(body) {
86
+ static getUserByAgentId(body) {
87
87
  return __awaiter(this, void 0, void 0, function* () {
88
88
  const getUsersByAgentIdRequestBody = {
89
89
  storeId: body.storeId,
90
- email: body.email
90
+ email: body.agentId
91
91
  };
92
92
  const updateDetailsRequest = {
93
93
  apiPath: `${(0, elastic_1.getApiUrl)(constants_1.POD_NAME.CRM)}/userApiFunctions-getUsers`,
@@ -106,7 +106,7 @@ class AlertsV2Helper {
106
106
  // Handle users as an array
107
107
  if (!parsedData.users || !Array.isArray(parsedData.users) || parsedData.users.length === 0) {
108
108
  console.warn('No user found with the provided agent ID');
109
- return apis_1.FunctionResponseHelper.failed(api_response_1.ErrorCodes.RESOURCE_NOT_FOUND, `User not found for email: ${body.email}`);
109
+ return apis_1.FunctionResponseHelper.failed(api_response_1.ErrorCodes.RESOURCE_NOT_FOUND, `User not found for agentId: ${body.agentId}`);
110
110
  }
111
111
  // Map array of users to extract email and phoneNumber
112
112
  const users = parsedData.users.map((user) => ({
@@ -119,38 +119,6 @@ class AlertsV2Helper {
119
119
  return apis_1.FunctionResponseHelper.success(responseData);
120
120
  });
121
121
  }
122
- static getUserByAgentId(body) {
123
- return __awaiter(this, void 0, void 0, function* () {
124
- const getUsersByAgentIdRequestBody = {
125
- storeId: body.storeId,
126
- agentId: body.agentId
127
- };
128
- const updateDetailsRequest = {
129
- apiPath: `${(0, elastic_1.getApiUrl)(constants_1.POD_NAME.CRM)}/userApiFunctions-getUserByAgentId`,
130
- apiMethod: executor_1.HTTPMethods.POST,
131
- requestHeader: {},
132
- requestBody: JSON.stringify(getUsersByAgentIdRequestBody),
133
- isInternal: true,
134
- };
135
- const response = yield executor_1.RequestExecutor.executeHttpAPIRequest(updateDetailsRequest);
136
- if (response.status !== 200) {
137
- const errorText = yield response.text();
138
- console.log('Error response: ', errorText);
139
- return apis_1.FunctionResponseHelper.failed(api_response_1.ErrorCodes.INTERNAL_SERVER_ERROR, `Failed to get recipients: ${errorText}`);
140
- }
141
- const parsedData = yield response.json();
142
- const data = parsedData.data;
143
- // Handle users as an array
144
- if (!data.users) {
145
- console.warn('No user found with the provided agent ID');
146
- return apis_1.FunctionResponseHelper.failed(api_response_1.ErrorCodes.RESOURCE_NOT_FOUND, `User not found for agentId: ${body.agentId}`);
147
- }
148
- const responseData = {
149
- users: data.users
150
- };
151
- return apis_1.FunctionResponseHelper.success(responseData);
152
- });
153
- }
154
122
  static validateCreateAlertConfig(body) {
155
123
  var _a, _b, _c;
156
124
  return __awaiter(this, void 0, void 0, function* () {
@@ -293,19 +261,5 @@ class AlertsV2Helper {
293
261
  emails,
294
262
  };
295
263
  }
296
- static extractSingleContactInfo(recipients) {
297
- const phoneNumbers = [];
298
- const emails = [];
299
- if (recipients.phoneNumber && recipients.phoneNumber.trim() !== '') {
300
- phoneNumbers.push(recipients.phoneNumber);
301
- }
302
- if (recipients.email && recipients.email.trim() !== '') {
303
- emails.push(recipients.email);
304
- }
305
- return {
306
- phoneNumbers,
307
- emails,
308
- };
309
- }
310
264
  }
311
265
  exports.AlertsV2Helper = AlertsV2Helper;
@@ -308,11 +308,8 @@ class AlertsV2Service {
308
308
  if (!validationResult.success) {
309
309
  return validationResult;
310
310
  }
311
- // Fetch recipient contacts using appropriate strategy
311
+ // Factory pattern: Fetch recipient contacts using appropriate strategy
312
312
  const { phoneNumbers, emails } = yield this.fetchRecipientContacts(body);
313
- if (phoneNumbers.length === 0 && emails.length === 0) {
314
- return apis_1.FunctionResponseHelper.failed(api_response_1.ErrorCodes.RESOURCE_NOT_FOUND, 'No valid recipients found for alert');
315
- }
316
313
  const channels = body.types;
317
314
  // Track per-recipient results separately for each channel
318
315
  const recipientChannelSuccess = new Map();
@@ -357,7 +354,7 @@ class AlertsV2Service {
357
354
  const variableConfig = yield this.alertConfigsRepo.getVariableConfigByAlertConfigId(body.alertConfigId);
358
355
  const emailRequest = {
359
356
  emailConfig,
360
- variables: body.variables || {},
357
+ variables: body.variables || [],
361
358
  variableConfig,
362
359
  emails: emails,
363
360
  storeId: body.storeId,
@@ -394,7 +391,6 @@ class AlertsV2Service {
394
391
  try {
395
392
  const pushNotificationConfig = yield this.alertConfigsRepo.getPushNotificationConfigByAlertConfigId(body.alertConfigId);
396
393
  const variableConfig = yield this.alertConfigsRepo.getVariableConfigByAlertConfigId(body.alertConfigId);
397
- console.log('Push notification config:', pushNotificationConfig);
398
394
  const pushNotificationRequest = {
399
395
  storeId: body.storeId,
400
396
  pushNotificationConfig,
@@ -444,7 +440,7 @@ class AlertsV2Service {
444
440
  configId: body.alertConfigId,
445
441
  configName: alertConfig.name,
446
442
  persistHistory: alertConfig.persistHistory,
447
- agentId: emails,
443
+ agentId: hasCurrentUser ? body.agentId : emails,
448
444
  channel: channels,
449
445
  };
450
446
  const { successfulRecipients, failedRecipients, feConfigs, errors } = yield this.sendFrontendNotification(frontendNotificationRequest);
@@ -666,9 +662,7 @@ class AlertsV2Service {
666
662
  return {
667
663
  successfulRecipients: new Map(),
668
664
  failedRecipients: new Map(),
669
- errors: [
670
- 'Missing email content configuration: provide emailType, templateId, emailBody.html, or emailBody.text',
671
- ],
665
+ errors: ['Missing email content configuration: provide emailType, templateId, emailBody.html, or emailBody.text'],
672
666
  };
673
667
  }
674
668
  const emailFrom = ((_j = body.emailConfig.emailBody) === null || _j === void 0 ? void 0 : _j.from) ||
@@ -707,7 +701,6 @@ class AlertsV2Service {
707
701
  emailBody,
708
702
  sendViaMailgun: true,
709
703
  };
710
- console.log('Sending email with request:', { emailRequest, emailEndpoint });
711
704
  const sendEmailRequest = {
712
705
  apiPath: emailEndpoint,
713
706
  apiMethod: executor_1.HTTPMethods.POST,
@@ -770,9 +763,7 @@ class AlertsV2Service {
770
763
  successfulRecipients.set(email, messageId);
771
764
  }
772
765
  else {
773
- const errorText = responseData
774
- ? JSON.stringify(responseData)
775
- : `HTTP ${sendResponse.status}`;
766
+ const errorText = yield sendResponse.text();
776
767
  console.error(`Failed to send email alert to ${email}:`, errorText);
777
768
  errors.push(`${email}: ${errorText}`);
778
769
  failedRecipients.set(email, errorText);
@@ -1,27 +1,4 @@
1
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -31,9 +8,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
9
  });
33
10
  };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
11
  Object.defineProperty(exports, "__esModule", { value: true });
38
12
  exports.AuthMiddlewareService = void 0;
39
13
  const logger_1 = require("../logger");
@@ -43,8 +17,6 @@ const firebase_auth_service_1 = require("./firebase-auth.service");
43
17
  const all_services_1 = require("./implementations/all-services");
44
18
  const swagger_1 = require("../swagger");
45
19
  const core_1 = require("../core");
46
- const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
47
- const util = __importStar(require("util"));
48
20
  class AuthMiddlewareService {
49
21
  constructor(isProd, throwError, whitelistedApis, publicApis, firebaseApp, apiSchema, debugEnabled = false) {
50
22
  this.isProd = isProd;
@@ -55,8 +27,8 @@ class AuthMiddlewareService {
55
27
  this.apiSchema = apiSchema;
56
28
  this.debugEnabled = debugEnabled;
57
29
  this.authMiddleware = (request, response) => __awaiter(this, void 0, void 0, function* () {
58
- var _a, _b;
59
- const requestUrl = (((_a = request.routeOptions) === null || _a === void 0 ? void 0 : _a.url) || request.url).substring(1);
30
+ var _a;
31
+ const requestUrl = (request.routeOptions.url || request.url).substring(1);
60
32
  if (requestUrl.startsWith('not-a-documentation')) {
61
33
  yield swagger_1.SwaggerSetupHelper.authenticateSwagger(request, response);
62
34
  return;
@@ -72,43 +44,6 @@ class AuthMiddlewareService {
72
44
  const requestBody = request.body || {};
73
45
  const referrer = request.headers['bik-referer'] || '';
74
46
  const authorization = request.headers['authorization'];
75
- if (authorization) {
76
- try {
77
- // Remove 'Bearer ' prefix if present (case-insensitive)
78
- const rawAuth = Array.isArray(authorization) ? authorization[0] : authorization;
79
- const token = rawAuth.toString().replace(/^\s*Bearer\s+/i, '').trim();
80
- // print full raw token without truncation
81
- // eslint-disable-next-line @typescript-eslint/no-var-requires
82
- let headers = request.headers || {};
83
- // normalize header values to strings/arrays of strings so nothing gets truncated/inspected oddly
84
- const normalizedHeaders = Object.fromEntries(Object.entries(headers).map(([k, v]) => [
85
- k,
86
- Array.isArray(v) ? v.map((x) => (x === undefined || x === null ? '' : String(x))) : (v === undefined || v === null ? '' : String(v))
87
- ]));
88
- // inspect options to avoid truncation
89
- const inspectOptions = { depth: null, maxArrayLength: null, maxStringLength: null, breakLength: Infinity };
90
- // print token again with full options (ensure no truncation)
91
- console.log('FULL TOKEN (no truncate):', util.inspect(token, inspectOptions));
92
- // also print a flattened, human-readable single-line representation
93
- const flatHeaders = Object.entries(normalizedHeaders || {})
94
- .map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(',') : v}`)
95
- .join(' | ');
96
- console.log('HEADERS FLAT:', flatHeaders);
97
- // Decode WITHOUT verification (for debugging only)
98
- // use require here to avoid changing top-level imports
99
- // eslint-disable-next-line @typescript-eslint/no-var-requires
100
- const decodedPayload = jsonwebtoken_1.default.decode(token);
101
- console.log('\n' +
102
- '='.repeat(50) +
103
- '\n🔑 TOKEN INFORMATION:\n' +
104
- util.inspect(decodedPayload, inspectOptions) +
105
- '\n' +
106
- '='.repeat(50));
107
- }
108
- catch (err) {
109
- console.warn('⚠️ Failed to decode token:', err);
110
- }
111
- }
112
47
  // For public APIs the body.captchaToken variable should be present and valid.
113
48
  const availableServices = all_services_1.ALL_SERVICES;
114
49
  const requestHeaders = request.headers;
@@ -143,7 +78,7 @@ class AuthMiddlewareService {
143
78
  return this.throwErrorIfRequired(requestUrl, 'email-not-allowed', referrer, requestBody, requestHeaders, userSnapshot, false, 'The email you are using is not allowed to access this API. Please contact support.');
144
79
  }
145
80
  if (authVerificationResponse.verified) {
146
- logger_1.LogExecutionContextHelper.setAuthProperties((_b = authVerificationResponse.email) !== null && _b !== void 0 ? _b : authVerificationResponse.userId, authType);
81
+ logger_1.LogExecutionContextHelper.setAuthProperties((_a = authVerificationResponse.email) !== null && _a !== void 0 ? _a : authVerificationResponse.userId, authType);
147
82
  return true;
148
83
  }
149
84
  if (canUse === auth_interface_1.AuthEnforcementType.ENFORCED) {
@@ -81,7 +81,7 @@ class FirebaseAuthService {
81
81
  return {
82
82
  verified: isVerified,
83
83
  userId: isVerified ? user.uid : undefined,
84
- email: isVerified ? completeUser.email : undefined,
84
+ email: isVerified ? completeUser.email : undefined
85
85
  };
86
86
  });
87
87
  }
@@ -90,7 +90,7 @@ class FirebaseAuthService {
90
90
  if (this.TEST_STORE_IDS.includes(storeId)) {
91
91
  return {
92
92
  verified: true,
93
- userId: storeId,
93
+ userId: storeId
94
94
  };
95
95
  }
96
96
  const user = yield this.firebaseApp.auth().getUser(storeId);
@@ -103,7 +103,7 @@ class FirebaseAuthService {
103
103
  const domain = email.split('@')[1];
104
104
  return {
105
105
  verified: domain === 'bikayi.com' || domain === 'bik.ai',
106
- email: domain === 'bikayi.com' || domain === 'bik.ai' ? email : undefined,
106
+ email: domain === 'bikayi.com' || domain === 'bik.ai' ? email : undefined
107
107
  };
108
108
  });
109
109
  }
@@ -1,6 +1,6 @@
1
1
  import { AuthEnforcementType, AuthMiddlewareParams, AuthService, AuthVerificationResponse, RequestHeaders } from './auth.interface';
2
2
  import { AuthTypes } from '../../apis';
3
- import { auth } from 'firebase-admin';
3
+ import { auth } from "firebase-admin";
4
4
  import DecodedIdToken = auth.DecodedIdToken;
5
5
  export declare class BikAdminAuthService implements AuthService {
6
6
  getAuthType(): AuthTypes;
@@ -32,8 +32,7 @@ class BikAdminAuthService {
32
32
  // Happens only for prod as custom claims logic doesn't work on staging.
33
33
  // This is to check if spoofed login from dashboard has same store id in body and token.
34
34
  let isStoreIdVerified = false;
35
- if (core_1.isProd &&
36
- ['merchant-admin-react', 'manifest-frontend-merchant'].includes(requestHeaders.callerservicename)) {
35
+ if (core_1.isProd && ['merchant-admin-react', 'manifest-frontend-merchant'].includes(requestHeaders.callerservicename)) {
37
36
  isStoreIdVerified = yield firebaseAuthService.isLikelyBikAdmin(userSnapshot, storeId);
38
37
  }
39
38
  else {
@@ -2,9 +2,6 @@ export * from './authMiddlewares';
2
2
  export * from './secret-manager/secretManager.service';
3
3
  export * from './secret-manager/secretManager.model';
4
4
  export * from './secret-manager/secretManager.helper';
5
- export * from './secret-manager/configManager.model';
6
- export * from './secret-manager/configManager.service';
7
- export * from './secret-manager/configManager.helper';
8
5
  export * from './config';
9
6
  export * from './secret-manager/env-variables/variables.list';
10
7
  export * from './secret-manager/env-variables/env-variables.helper';
package/lib/auth/index.js CHANGED
@@ -18,9 +18,6 @@ __exportStar(require("./authMiddlewares"), exports);
18
18
  __exportStar(require("./secret-manager/secretManager.service"), exports);
19
19
  __exportStar(require("./secret-manager/secretManager.model"), exports);
20
20
  __exportStar(require("./secret-manager/secretManager.helper"), exports);
21
- __exportStar(require("./secret-manager/configManager.model"), exports);
22
- __exportStar(require("./secret-manager/configManager.service"), exports);
23
- __exportStar(require("./secret-manager/configManager.helper"), exports);
24
21
  __exportStar(require("./config"), exports);
25
22
  __exportStar(require("./secret-manager/env-variables/variables.list"), exports);
26
23
  __exportStar(require("./secret-manager/env-variables/env-variables.helper"), exports);
@@ -64,7 +64,6 @@ export declare const ShopifyKeys: {
64
64
  };
65
65
  export declare const PgSQLKeys: {
66
66
  readonly SECRET_NAME: "SECRET_NAME";
67
- readonly SECRET_NAME_SMTP: "SECRET_NAME_SMTP";
68
67
  };
69
68
  export declare const ApiKeys: {
70
69
  readonly API_KEY: "API_KEY";
@@ -75,7 +74,6 @@ export declare const GenericKeys: {
75
74
  readonly NODE_ENV: "NODE_ENV";
76
75
  readonly USE_CLOUD_REDIS: "USE_CLOUD_REDIS";
77
76
  readonly ENVIRONMENT: "ENVIRONMENT";
78
- readonly ENVIRONMENT_SMTP: "ENVIRONMENT_SMTP";
79
77
  readonly USE_PRIVATE_NETWORK: "USE_PRIVATE_NETWORK";
80
78
  readonly PORT: "PORT";
81
79
  readonly SERVICE_NAME: "SERVICE_NAME";
@@ -109,7 +107,6 @@ export declare const SlackKeys: {
109
107
  readonly SLACK_ALERT_CHANNEL: "SLACK_ALERT_CHANNEL";
110
108
  readonly SLACK_LOG_LEVEL: "SLACK_LOG_LEVEL";
111
109
  readonly SLACK_TOKEN: "slack_token";
112
- readonly SLACK_SECRET: "slack_secret";
113
110
  };
114
111
  export declare const MiraimindsKeys: {
115
112
  readonly PUBLIC_KEY: "PUBLIC_KEY";
@@ -67,7 +67,6 @@ exports.ShopifyKeys = {
67
67
  };
68
68
  exports.PgSQLKeys = {
69
69
  SECRET_NAME: 'SECRET_NAME',
70
- SECRET_NAME_SMTP: 'SECRET_NAME_SMTP',
71
70
  };
72
71
  exports.ApiKeys = {
73
72
  API_KEY: 'API_KEY',
@@ -78,7 +77,6 @@ exports.GenericKeys = {
78
77
  NODE_ENV: 'NODE_ENV',
79
78
  USE_CLOUD_REDIS: 'USE_CLOUD_REDIS',
80
79
  ENVIRONMENT: 'ENVIRONMENT',
81
- ENVIRONMENT_SMTP: 'ENVIRONMENT_SMTP',
82
80
  USE_PRIVATE_NETWORK: 'USE_PRIVATE_NETWORK',
83
81
  PORT: 'PORT',
84
82
  SERVICE_NAME: 'SERVICE_NAME',
@@ -112,7 +110,6 @@ exports.SlackKeys = {
112
110
  SLACK_ALERT_CHANNEL: 'SLACK_ALERT_CHANNEL',
113
111
  SLACK_LOG_LEVEL: 'SLACK_LOG_LEVEL',
114
112
  SLACK_TOKEN: 'slack_token',
115
- SLACK_SECRET: 'slack_secret',
116
113
  };
117
114
  exports.MiraimindsKeys = {
118
115
  PUBLIC_KEY: 'PUBLIC_KEY',
@@ -61,10 +61,12 @@ class ChatHandoverProtocol {
61
61
  if (assetId) {
62
62
  whatsAppPhoneNumberId = `${whatsAppPhoneNumberId}|${assetId}`;
63
63
  }
64
+ else {
65
+ // TODO: log error here
66
+ }
64
67
  uniqueId.push(whatsAppPhoneNumberId);
65
68
  }
66
- const finalChatId = uniqueId.filter((e) => !!e).join('#');
67
- return finalChatId;
69
+ return uniqueId.filter((e) => !!e).join('#');
68
70
  });
69
71
  }
70
72
  static getAssetId(payload) {
@@ -101,7 +103,9 @@ class ChatHandoverProtocol {
101
103
  const redisService = redis_1.RedisAppService.getInstance();
102
104
  assignmentInfo = JSON.parse((yield redisService.retrieveData(chatId)) || '{}');
103
105
  }
104
- catch (err) { }
106
+ catch (err) {
107
+ console.error('REDIS CONNECTION ERROR', JSON.stringify(err));
108
+ }
105
109
  return assignmentInfo;
106
110
  });
107
111
  }
@@ -113,7 +117,9 @@ class ChatHandoverProtocol {
113
117
  const response = yield redisService.cacheData(chatId, data, TTL);
114
118
  return response === null || response === void 0 ? void 0 : response.success;
115
119
  }
116
- catch (err) { }
120
+ catch (err) {
121
+ console.error('REDIS CONNECTION ERROR', JSON.stringify(err));
122
+ }
117
123
  });
118
124
  }
119
125
  static removeRedisInfo(chatId) {
@@ -122,12 +128,14 @@ class ChatHandoverProtocol {
122
128
  const redisService = redis_1.RedisAppService.getInstance();
123
129
  yield redisService.deleteCache(chatId);
124
130
  }
125
- catch (err) { }
131
+ catch (err) {
132
+ console.error('Error in remove cache', JSON.stringify(err));
133
+ }
126
134
  });
127
135
  }
128
136
  static checkForAgentAssignment(payload, message, call, uniqueId // for forwarding email in same thread, we use this to ensure a new ticket isn't created
129
137
  ) {
130
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
138
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
131
139
  return __awaiter(this, void 0, void 0, function* () {
132
140
  const { messageObj, commentObj, callObj } = payload;
133
141
  const channelName = messageObj
@@ -138,7 +146,6 @@ class ChatHandoverProtocol {
138
146
  ? callObj === null || callObj === void 0 ? void 0 : callObj.channel_id
139
147
  : models_1.CHANNELS.WHATSAPP;
140
148
  const isCommentFlow = !!payload.commentObj;
141
- const isCallFlow = !!payload.callObj;
142
149
  const isMessengerPostback = !!((_b = (_a = payload === null || payload === void 0 ? void 0 : payload.messageObj) === null || _a === void 0 ? void 0 : _a.buttons) === null || _b === void 0 ? void 0 : _b.includes('"id"'));
143
150
  const isBotMessage = (messageObj === null || messageObj === void 0 ? void 0 : messageObj.owner) === models_1.Owner.BOT;
144
151
  const chatId = uniqueId !== null && uniqueId !== void 0 ? uniqueId : (yield ChatHandoverProtocol.getChatId(payload));
@@ -155,7 +162,7 @@ class ChatHandoverProtocol {
155
162
  (message && message.type === whatsapp_model_1.MultiMediaTypes.Order) ||
156
163
  ((_c = commentObj === null || commentObj === void 0 ? void 0 : commentObj.extras) === null || _c === void 0 ? void 0 : _c.isUnsupportedMessage);
157
164
  // call for every chatbot ticket message, except first one
158
- ChatHandoverProtocol.updateTicketForChatbotMessage({
165
+ console.debug('--chatbot ticket update payload--', {
159
166
  storeId: payload.storeId,
160
167
  uniqueId: chatId,
161
168
  senderId: ((_d = payload.messageObj) === null || _d === void 0 ? void 0 : _d.sender_id) || ((_e = payload.commentObj) === null || _e === void 0 ? void 0 : _e.senderId),
@@ -166,6 +173,18 @@ class ChatHandoverProtocol {
166
173
  contentType: payload.messageObj ? models_1.ChatContentTypeI.MESSAGE : models_1.ChatContentTypeI.COMMENT,
167
174
  commentId: (_m = payload.commentObj) === null || _m === void 0 ? void 0 : _m.commentId,
168
175
  isMediaMessage,
176
+ });
177
+ ChatHandoverProtocol.updateTicketForChatbotMessage({
178
+ storeId: payload.storeId,
179
+ uniqueId: chatId,
180
+ senderId: ((_o = payload.messageObj) === null || _o === void 0 ? void 0 : _o.sender_id) || ((_p = payload.commentObj) === null || _p === void 0 ? void 0 : _p.senderId),
181
+ conversationStartTime: (_q = payload.messageObj) === null || _q === void 0 ? void 0 : _q.sent_at,
182
+ message: ((_r = payload.messageObj) === null || _r === void 0 ? void 0 : _r.message) || ((_s = payload.commentObj) === null || _s === void 0 ? void 0 : _s.message) || '',
183
+ messageId: (_t = payload.messageObj) === null || _t === void 0 ? void 0 : _t.message_id,
184
+ messageTimeStamp: ((_u = payload.messageObj) === null || _u === void 0 ? void 0 : _u.sent_at) || ((_v = payload.commentObj) === null || _v === void 0 ? void 0 : _v.createdAt),
185
+ contentType: payload.messageObj ? models_1.ChatContentTypeI.MESSAGE : models_1.ChatContentTypeI.COMMENT,
186
+ commentId: (_w = payload.commentObj) === null || _w === void 0 ? void 0 : _w.commentId,
187
+ isMediaMessage,
169
188
  })
170
189
  .then()
171
190
  .catch((error) => {
@@ -175,35 +194,34 @@ class ChatHandoverProtocol {
175
194
  const messageOrCall = message || call;
176
195
  // ticket is with crm (agent may or may not be assigned)
177
196
  if (assignmentInfo.customerId) {
178
- const pods = messageOrCall
179
- ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, true)
180
- : [];
197
+ console.debug('Agent is assigned, forward to : ', messageOrCall ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, true) : []);
181
198
  return Promise.resolve({
182
199
  isAgentAssigned: true,
183
200
  chatId,
184
201
  assignmentInfo,
185
202
  eligibleForAgentAssignment: false,
186
203
  ticketId: assignmentInfo.sessionId,
187
- pods,
204
+ pods: messageOrCall
205
+ ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, true)
206
+ : [],
188
207
  });
189
208
  }
190
- const pods = messageOrCall
191
- ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, false)
192
- : [];
209
+ console.debug('Agent is not assigned, forward to : ', messageOrCall ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, false) : []);
193
210
  let eligibleForAgentAssignment = false;
194
211
  // fb dm
195
212
  if (!isMessengerPostback && channelName === models_1.CHANNELS.MESSENGER && !isCommentFlow) {
196
213
  eligibleForAgentAssignment = true;
197
214
  }
198
- const result = {
215
+ return {
199
216
  chatId,
200
217
  isAgentAssigned: false,
201
218
  assignmentInfo,
202
219
  eligibleForAgentAssignment,
203
220
  ticketId: assignmentInfo === null || assignmentInfo === void 0 ? void 0 : assignmentInfo.sessionId,
204
- pods,
221
+ pods: messageOrCall
222
+ ? ChatHandoverProtocol.podsToFowardWebhook(messageOrCall, payload, false)
223
+ : [],
205
224
  };
206
- return result;
207
225
  });
208
226
  }
209
227
  static podsToFowardWebhook(messageOrCall, payload, isAgentAssigned) {
@@ -216,6 +234,7 @@ class ChatHandoverProtocol {
216
234
  : commentObj === null || commentObj === void 0 ? void 0 : commentObj.channel;
217
235
  if (((messageObj === null || messageObj === void 0 ? void 0 : messageObj.owner) && [models_1.Owner.AGENT, models_1.Owner.BOT].includes(messageObj === null || messageObj === void 0 ? void 0 : messageObj.owner)) ||
218
236
  ((commentObj === null || commentObj === void 0 ? void 0 : commentObj.owner) && [models_1.Owner.AGENT, models_1.Owner.BOT].includes(commentObj === null || commentObj === void 0 ? void 0 : commentObj.owner))) {
237
+ //early return for BICs
219
238
  return [];
220
239
  }
221
240
  // if its manifest, always return CRM
@@ -309,8 +328,7 @@ class ChatHandoverProtocol {
309
328
  }
310
329
  }
311
330
  // convert pods set to an array and return
312
- const finalPods = Array.from(pods);
313
- return finalPods;
331
+ return Array.from(pods);
314
332
  }
315
333
  static getCrmDecoupledStoreConfigFromFS() {
316
334
  return __awaiter(this, void 0, void 0, function* () {
@@ -322,8 +340,7 @@ class ChatHandoverProtocol {
322
340
  isInternal: true,
323
341
  };
324
342
  const response = yield executor_1.RequestExecutor.executeHttpAPIRequest(updateDetailsRequest);
325
- const result = yield response.json();
326
- return result;
343
+ return yield response.json();
327
344
  });
328
345
  }
329
346
  static updateTicketForChatbotMessage(payload) {
@@ -382,13 +399,11 @@ class ChatHandoverProtocol {
382
399
  }
383
400
  exports.ChatHandoverProtocol = ChatHandoverProtocol;
384
401
  ChatHandoverProtocol.checkIfQRBReplyIsFromFlow = (payload) => {
385
- if (typeof payload !== 'string') {
402
+ if (typeof payload !== 'string')
386
403
  return false; // Check if it's a string
387
- }
388
404
  try {
389
405
  const parsed = JSON.parse(payload);
390
- const isFromFlow = parsed && typeof parsed === 'object' && 'f' in parsed;
391
- return isFromFlow; // Check if `f` exists
406
+ return parsed && typeof parsed === 'object' && 'f' in parsed; // Check if `f` exists
392
407
  }
393
408
  catch (e) {
394
409
  return false; // If parsing fails, it's not a stringified object
@@ -12,9 +12,6 @@ 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;
18
15
  static fetchServiceName(): string | undefined;
19
16
  static fetchPodName(): PodName | undefined;
20
17
  static setUp(options: BikBackendOptions): void;