@optimiser/common 1.0.365 → 1.0.367

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 (69) hide show
  1. package/dist/aws/awsservices.d.ts +39 -39
  2. package/dist/aws/awsservices.js +398 -398
  3. package/dist/constants.d.ts +35 -35
  4. package/dist/constants.js +36 -36
  5. package/dist/enums/databasetype.enum.d.ts +7 -7
  6. package/dist/enums/databasetype.enum.js +11 -11
  7. package/dist/enums/log.enum.d.ts +22 -22
  8. package/dist/enums/log.enum.js +26 -26
  9. package/dist/index.d.ts +25 -25
  10. package/dist/index.js +69 -61
  11. package/dist/lib/activity.d.ts +1 -1
  12. package/dist/lib/activity.js +44 -44
  13. package/dist/lib/calculatedbsize.d.ts +15 -15
  14. package/dist/lib/calculatedbsize.js +75 -75
  15. package/dist/lib/connection.d.ts +116 -116
  16. package/dist/lib/connection.js +595 -595
  17. package/dist/lib/convertfilesize.d.ts +2 -2
  18. package/dist/lib/convertfilesize.js +15 -15
  19. package/dist/lib/countrycode.d.ts +2 -2
  20. package/dist/lib/countrycode.js +255 -255
  21. package/dist/lib/event.d.ts +26 -26
  22. package/dist/lib/event.js +252 -248
  23. package/dist/lib/helper.d.ts +94 -93
  24. package/dist/lib/helper.js +1016 -1009
  25. package/dist/lib/memoryserverclient.d.ts +40 -40
  26. package/dist/lib/memoryserverclient.js +256 -252
  27. package/dist/lib/operautilitycommon.d.ts +65 -65
  28. package/dist/lib/operautilitycommon.js +620 -620
  29. package/dist/lib/redis.d.ts +21 -21
  30. package/dist/lib/redis.js +46 -46
  31. package/dist/lib/socketidfromredis.d.ts +3 -3
  32. package/dist/lib/socketidfromredis.js +5 -5
  33. package/dist/lib/taskutils.d.ts +40 -40
  34. package/dist/lib/taskutils.js +656 -656
  35. package/dist/lib/utility.d.ts +300 -298
  36. package/dist/lib/utility.js +5626 -5621
  37. package/dist/lib/validateRequest.d.ts +3 -3
  38. package/dist/lib/validateRequest.js +13 -13
  39. package/dist/logs/auditlog.d.ts +25 -25
  40. package/dist/logs/auditlog.js +1033 -1029
  41. package/dist/logs/checklogtable.d.ts +3 -3
  42. package/dist/logs/checklogtable.js +67 -67
  43. package/dist/logs/log.table.d.ts +7 -7
  44. package/dist/logs/log.table.js +127 -127
  45. package/dist/modals/connection.modal.d.ts +32 -32
  46. package/dist/modals/connection.modal.js +2 -2
  47. package/dist/modals/globalNotification.modal.d.ts +8 -8
  48. package/dist/modals/globalNotification.modal.js +2 -2
  49. package/dist/modals/log.modal.d.ts +64 -64
  50. package/dist/modals/log.modal.js +2 -2
  51. package/dist/modals/mail.modal.d.ts +6 -6
  52. package/dist/modals/mail.modal.js +2 -2
  53. package/dist/modals/notificationData.modal.d.ts +29 -29
  54. package/dist/modals/notificationData.modal.js +2 -2
  55. package/dist/modals/redisconfig.modal.d.ts +6 -6
  56. package/dist/modals/redisconfig.modal.js +2 -2
  57. package/dist/modals/sqsconfig.modal.d.ts +8 -8
  58. package/dist/modals/sqsconfig.modal.js +2 -2
  59. package/dist/modals/utility.modal.d.ts +17 -17
  60. package/dist/modals/utility.modal.js +2 -2
  61. package/dist/utility/crypto.d.ts +4 -4
  62. package/dist/utility/crypto.js +43 -43
  63. package/dist/utility/errorHandler.d.ts +30 -30
  64. package/dist/utility/errorHandler.js +24 -24
  65. package/dist/utility/errorHandlerForServices.d.ts +22 -22
  66. package/dist/utility/errorHandlerForServices.js +19 -19
  67. package/dist/utility/mail.d.ts +21 -21
  68. package/dist/utility/mail.js +91 -87
  69. package/package.json +3 -3
@@ -1,620 +1,620 @@
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
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.EmailPrioritySearch = exports.AddToQueueForOpera = exports.UpdateInitialSyncData = exports.GetProfileDetailByDynamicFields = exports.OperaErrorHandler = exports.SyncContactWithOperaOnEmailUnsubscribe = exports.GetIntegrationSettings = void 0;
43
- var mongodb_1 = require("mongodb");
44
- var __1 = require("..");
45
- var constants_1 = __importDefault(require("../constants"));
46
- var GetIntegrationSettings = function (db, hotelCode) {
47
- return new Promise(function (resolve, reject) {
48
- var hotelMatch = { "IsActive": true, "PropertyStatus": constants_1.default.OperaPropertyStatus.Active };
49
- if (hotelCode != "all") {
50
- hotelMatch.PropertyCode = new RegExp(hotelCode, "i");
51
- }
52
- db.collection("IntegrationSettings").aggregate([
53
- { $match: { "IntegrationParty": "Oracle", "IntegrationPartyCode": "Opera", "IsActive": true } },
54
- { $project: { Status: 1, ForceDisable: 1, InterfaceId: 1, InitialSyncStatus: 1, PropertySharedDB: 1 } },
55
- {
56
- $lookup: {
57
- from: "OperaProperty", pipeline: [{ $match: hotelMatch }, {
58
- $project: {
59
- "_id": 1,
60
- "PropertyName": 1,
61
- "PropertyCode": 1,
62
- "ChainCode": 1,
63
- "Currency": 1,
64
- "LeadProperty": 1,
65
- "ReservationEmail": 1,
66
- "SubscribeID": 1,
67
- "InitialSyncStatus": 1,
68
- "PropertyStatus": 1,
69
- "IsActive": 1,
70
- "Modules": 1,
71
- "ProfileInitialSyncDataProcessStartTime": 1,
72
- "ProfileInitialSyncDataProcessEndTime": 1,
73
- "InitialSyncCompleteDate": 1,
74
- "LastInventorySyncDate": 1,
75
- "LastInventorySyncStatus": 1,
76
- "ProfileInitialSyncDataProcessErrorTime": 1,
77
- "ProfileInitialSyncDataProcessReStartCounter": 1,
78
- "DefaultRoomTypesAdded": 1
79
- }
80
- }], as: "HotelList"
81
- }
82
- },
83
- { $lookup: { from: "OperaOptimiserMapping", pipeline: [{ $project: { "_id": 1, "Name": 1, "Data": 1 } }], as: "OperaOptimiserMapping" } }
84
- ]).toArray(function (error, result) {
85
- if (error) {
86
- error.name += " - Fetch Opera Integration Settings";
87
- OperaErrorHandler(db, error);
88
- reject(error);
89
- }
90
- else if (result && result.length > 0) {
91
- resolve(result[0]);
92
- }
93
- else {
94
- resolve(null);
95
- }
96
- });
97
- });
98
- };
99
- exports.GetIntegrationSettings = GetIntegrationSettings;
100
- var SyncContactWithOperaOnEmailUnsubscribe = function (db, email) {
101
- if (db && email) {
102
- db.collection("Company").findOne({}, { projection: { "Setting.AppsSubscribed": 1 } }, function (err, result) {
103
- if (err) {
104
- if (err.name)
105
- err.name += " - while checking AppsSubscribe in Company";
106
- OperaErrorHandler(db, err);
107
- }
108
- else if (result && result.Setting && result.Setting.AppsSubscribed && result.Setting.AppsSubscribed.indexOf(constants_1.default.STORE_APP_NAMES.OPERA_PMS) >= 0) {
109
- db.collection("Contact").findOne({ Email: new RegExp("^" + email + "$", "i"), "IsActive": true }, { projection: { "_id": 1, "OperaProfileId": 1 } }, function (errContact, resultContact) {
110
- if (errContact) {
111
- if (errContact.name)
112
- errContact.name += " - while fetching contact to update contact opera sync flag";
113
- OperaErrorHandler(db, errContact);
114
- }
115
- else if (resultContact && resultContact._id && resultContact.OperaProfileId) {
116
- GetIntegrationSettings(db, "all").then(function (oiSettings) {
117
- if (oiSettings && oiSettings.Status == constants_1.default.CompanyAppStatus.ENABLE && oiSettings.HotelList && oiSettings.HotelList.length > 0) {
118
- if (oiSettings.HotelList.filter(function (x) { return x.Modules && x.Modules.length > 0 && x.Modules.find(function (y) { return y.ModuleName && y.ModuleName == "contact"; }); }).length > 0)
119
- // db.collection("Contact").updateOne({ "_id": resultContact._id, "IsActive": true }, { $set: { "OperaStatus": constants.OperaSyncStatus.READY } });
120
- db.collection("Contact").updateOne({ "_id": resultContact._id, "IsActive": true }, { $set: { "EmailSubscriptionFromOptimiserToOpera": (new Date()).getMilliseconds() } });
121
- }
122
- }, function (erroOiSettings) {
123
- if (erroOiSettings.name)
124
- erroOiSettings.name += " - while fetching integration settings to update contact opera sync flag";
125
- OperaErrorHandler(db, erroOiSettings);
126
- });
127
- }
128
- });
129
- }
130
- });
131
- }
132
- };
133
- exports.SyncContactWithOperaOnEmailUnsubscribe = SyncContactWithOperaOnEmailUnsubscribe;
134
- var OperaErrorHandler = function (db, ex) {
135
- var errObj = {
136
- 'error-name': ex.name,
137
- 'error-message': ex.message,
138
- 'error-info': ex.stack,
139
- 'time': new Date()
140
- };
141
- db.collection("Error").insertOne(errObj, function (err, res) {
142
- if (err) {
143
- console.log(err);
144
- }
145
- });
146
- };
147
- exports.OperaErrorHandler = OperaErrorHandler;
148
- /**
149
- * This function is used to search profiles by dynamics fields in both Memory server and db.
150
- * If data found in memory server then it search data by _id in db the return data.
151
- *
152
- * @param params.ModuleName Name of Module either Account | Contact.
153
- * @param params.MappingFields fields which is used for searching
154
- * @param params.ModuleData Data of fields
155
- * @param params.db database objects
156
- * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
157
- * @param params.SelectedFields to get only selected fields
158
- * @param params.AllowInactive to search data without IsActive field.
159
- * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
160
- * @param params.MemoryServerClient memory server client object to get data from memory server
161
- * @param params.CompanyId to indicate searcing is to do from memory server
162
- * @param params.DataSet to indicate searcing is to do from memory server
163
- *
164
- * @returns [error,ResultData]
165
- */
166
- var GetProfileDetailByDynamicFields = function (params) {
167
- return __awaiter(this, void 0, void 0, function () {
168
- var mongodbTransactionQueryopts, searchObj, searchItems, len, i, field, appendSearch, _a, memoryServerSearchError, dataResult, projection, i, resultData, ex_1, searchObj, projection, len, i, field, i, resultData, ex_2;
169
- return __generator(this, function (_b) {
170
- switch (_b.label) {
171
- case 0:
172
- mongodbTransactionQueryopts = {};
173
- //if query options passed then setting them to pass into query.
174
- if (params.MongodbTransactionQueryOptions) {
175
- mongodbTransactionQueryopts = params.MongodbTransactionQueryOptions;
176
- }
177
- if (!params.SearchFromMemoryServer) return [3 /*break*/, 10];
178
- searchObj = "x=>";
179
- searchItems = new Array();
180
- /*Preparing searching object for memory server*/
181
- for (len = params.MappingFields.length, i = 0; i < len; i++) {
182
- field = params.MappingFields[i];
183
- appendSearch = "";
184
- switch (field.UIDataType) {
185
- case 'email':
186
- case 'text':
187
- //left hand part
188
- appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
189
- //right hand part
190
- appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
191
- break;
192
- // case 'multilookup':
193
- // break;
194
- // case 'multiselect':
195
- // break;
196
- case 'lookup':
197
- case 'objectid':
198
- //left hand part
199
- appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
200
- //right hand part
201
- appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
202
- break;
203
- case 'phone':
204
- //left hand part
205
- appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
206
- //right hand part
207
- appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
208
- break;
209
- case 'dropdown':
210
- appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
211
- //right hand part
212
- appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
213
- break;
214
- default:
215
- appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
216
- //right hand part
217
- appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
218
- break;
219
- }
220
- if (appendSearch && appendSearch.length > 0) {
221
- searchItems.push(appendSearch);
222
- }
223
- }
224
- if (!(searchItems.length > 0)) return [3 /*break*/, 8];
225
- searchObj += searchItems.join(' && ');
226
- //if search required on InActive data
227
- // if (params.AllowInactive != true) {
228
- // searchObj += " && x.IsActive== true";
229
- // }
230
- console.log("Search query===>", searchObj);
231
- return [4 /*yield*/, params.MemoryServerClient.Fetch('search', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'findQuery': searchObj })];
232
- case 1:
233
- _a = _b.sent(), memoryServerSearchError = _a[0], dataResult = _a[1];
234
- if (!(dataResult && dataResult.response && dataResult.response._id)) return [3 /*break*/, 6];
235
- projection = {};
236
- //to get only required field otherwise get all data of object by id
237
- if (params.SelectedFields && params.SelectedFields.length > 0) {
238
- for (i = 0; i < params.SelectedFields.length; i++) {
239
- projection[params.SelectedFields[i]] = 1;
240
- }
241
- }
242
- else {
243
- projection = {};
244
- }
245
- resultData = null;
246
- _b.label = 2;
247
- case 2:
248
- _b.trys.push([2, 4, , 5]);
249
- return [4 /*yield*/, params.db.collection(params.ModuleName).findOne({ _id: new mongodb_1.ObjectId(dataResult.response._id) }, projection, mongodbTransactionQueryopts)];
250
- case 3:
251
- resultData = _b.sent();
252
- return [2 /*return*/, [null, resultData]];
253
- case 4:
254
- ex_1 = _b.sent();
255
- return [2 /*return*/, [ex_1, null]];
256
- case 5: return [3 /*break*/, 7];
257
- case 6:
258
- if (memoryServerSearchError) {
259
- console.log("Error while searching in memory server", memoryServerSearchError);
260
- return [2 /*return*/, [memoryServerSearchError, null]];
261
- }
262
- else {
263
- console.log("data not found in memory server");
264
- return [2 /*return*/, [null, null]];
265
- }
266
- _b.label = 7;
267
- case 7: return [3 /*break*/, 9];
268
- case 8:
269
- console.log("Search object not prepared");
270
- return [2 /*return*/, [null, null]];
271
- case 9: return [3 /*break*/, 14];
272
- case 10:
273
- searchObj = {};
274
- projection = {};
275
- /*Preparing searching object*/
276
- for (len = params.MappingFields.length, i = 0; i < len; i++) {
277
- field = params.MappingFields[i];
278
- switch (field.UIDataType) {
279
- case 'email':
280
- case 'text':
281
- searchObj[field.Name] = new RegExp('^' + params.ModuleData[field.Name] + '$', 'i');
282
- break;
283
- // case 'multilookup':
284
- // break;
285
- // case 'multiselect':
286
- // break;
287
- case 'lookup':
288
- case 'objectid':
289
- searchObj[field.Name] = params.ModuleData[field.Name];
290
- break;
291
- case 'phone':
292
- case 'dropdown':
293
- searchObj[field.Name] = params.ModuleData[field.Name];
294
- break;
295
- default:
296
- searchObj[field.Name] = params.ModuleData[field.Name];
297
- break;
298
- }
299
- }
300
- //If serch object build adding IsActive flag
301
- if (!__1._utility.isEmptyObj(searchObj)) {
302
- //if search required on InActive data
303
- if (params.AllowInactive != true) {
304
- searchObj["IsActive"] = true;
305
- //to show data is InActive so adding IsActive field in SelectedFields array if not available.
306
- if (params.SelectedFields && params.SelectedFields.length > 0 && !params.SelectedFields.find(function (x) { return x.Name == "IsActive"; })) {
307
- params.SelectedFields.push("IsActive");
308
- }
309
- }
310
- }
311
- else {
312
- console.log("Search object not prepared");
313
- return [2 /*return*/, [null, null]];
314
- }
315
- //to get only required field otherwise get all data of object by id
316
- if (params.SelectedFields && params.SelectedFields.length > 0) {
317
- for (i = 0; i < params.SelectedFields.length; i++) {
318
- projection[params.SelectedFields[i]] = 1;
319
- }
320
- }
321
- else {
322
- projection = {};
323
- }
324
- resultData = null;
325
- _b.label = 11;
326
- case 11:
327
- _b.trys.push([11, 13, , 14]);
328
- return [4 /*yield*/, params.db.collection(params.ModuleName).findOne(searchObj, projection, mongodbTransactionQueryopts)];
329
- case 12:
330
- resultData = _b.sent();
331
- return [2 /*return*/, [null, resultData]];
332
- case 13:
333
- ex_2 = _b.sent();
334
- return [2 /*return*/, [ex_2, null]];
335
- case 14: return [2 /*return*/];
336
- }
337
- });
338
- });
339
- };
340
- exports.GetProfileDetailByDynamicFields = GetProfileDetailByDynamicFields;
341
- /**
342
- * This function is used to update data.
343
- * @param params.ModuleName Name of Module either Account | Contact.
344
- * @param params.Collection Name of Collection
345
- * @param params.Id which doucment has to update
346
- * @param params.db database objects
347
- * @param params.MongodbTransactionQueryOptions Mongodb query option object , it may have transaction as well.
348
- * @param params.UpdateObj to update data in collection.
349
-
350
- * @returns
351
- */
352
- var UpdateInitialSyncData = function (params) { return __awaiter(void 0, void 0, void 0, function () {
353
- var mongodbQueryOpts;
354
- return __generator(this, function (_a) {
355
- mongodbQueryOpts = {};
356
- if (params.MongodbQueryOpts) {
357
- mongodbQueryOpts = params.MongodbQueryOpts;
358
- }
359
- return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
360
- var updatedData, error_1;
361
- return __generator(this, function (_a) {
362
- switch (_a.label) {
363
- case 0:
364
- _a.trys.push([0, 3, , 4]);
365
- if (!params) return [3 /*break*/, 2];
366
- updatedData = null;
367
- return [4 /*yield*/, params.db.collection(params.Collection).updateOne({ '_id': params.Id }, { $set: params.UpdateObj }, mongodbQueryOpts)];
368
- case 1:
369
- updatedData = _a.sent();
370
- if (updatedData) {
371
- resolve([null, true]);
372
- }
373
- _a.label = 2;
374
- case 2: return [3 /*break*/, 4];
375
- case 3:
376
- error_1 = _a.sent();
377
- resolve([error_1, null]);
378
- return [3 /*break*/, 4];
379
- case 4: return [2 /*return*/];
380
- }
381
- });
382
- }); })];
383
- });
384
- }); };
385
- exports.UpdateInitialSyncData = UpdateInitialSyncData;
386
- /**
387
- * This function is used to stop unnecessary databse hits for checking any data available send to opera.
388
- * this flag will be in reddis
389
- * @param params.RedisClient reddis client
390
- * @param params.CompanyId to create/check opera key with company id
391
- * @param params.Mode GET/SET operation to perform on reddis
392
- * @param params.db database objects
393
- * @param params.isAvailable value to set in reddis
394
-
395
- * @returns
396
- */
397
- var AddToQueueForOpera = function (params) { return __awaiter(void 0, void 0, void 0, function () {
398
- var key, redisDataOnKey, setDataOnKey, setDataOnKey, status_1, setDataOnKey, error_2;
399
- return __generator(this, function (_a) {
400
- switch (_a.label) {
401
- case 0:
402
- _a.trys.push([0, 14, , 15]);
403
- key = 'opera-queue:' + params.CompanyId.toString();
404
- if (!(params.Mode === 'GET')) return [3 /*break*/, 5];
405
- return [4 /*yield*/, params.RedisClient.hget(key, 'DataAvailable')];
406
- case 1:
407
- redisDataOnKey = _a.sent();
408
- if (!(redisDataOnKey === null || redisDataOnKey === undefined)) return [3 /*break*/, 3];
409
- return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
410
- case 2:
411
- setDataOnKey = _a.sent();
412
- // reddis returns 1 when data inserted
413
- if (setDataOnKey === 1) {
414
- return [2 /*return*/, [null, 'true']];
415
- }
416
- return [3 /*break*/, 4];
417
- case 3: return [2 /*return*/, [null, redisDataOnKey]];
418
- case 4: return [3 /*break*/, 13];
419
- case 5:
420
- if (!(params.Mode === 'SET')) return [3 /*break*/, 13];
421
- //
422
- console.log("Request receive to set in Opera Queue : ", params.isAvailable);
423
- if (!(params.isAvailable === true)) return [3 /*break*/, 7];
424
- return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
425
- case 6:
426
- setDataOnKey = _a.sent();
427
- // reddis returns 1 when data inserted and 0 when data already exists
428
- if (setDataOnKey === 1 || setDataOnKey === 0) {
429
- return [2 /*return*/, [null, 'true']];
430
- }
431
- return [3 /*break*/, 13];
432
- case 7:
433
- if (!(params.isAvailable === false)) return [3 /*break*/, 13];
434
- console.log("Checking data available or not in OperaApiLogs");
435
- return [4 /*yield*/, params.db.collection("OperaApiLogs").findOne({ 'Status': { $in: ["-1", "2", "3"] } })];
436
- case 8:
437
- status_1 = _a.sent();
438
- if (!!status_1) return [3 /*break*/, 10];
439
- console.log("Checking data available or not in OperaDataSyncRequest");
440
- return [4 /*yield*/, params.db.collection("OperaDataSyncRequest").findOne({ 'Status': '1', 'IsActive': true })];
441
- case 9:
442
- status_1 = _a.sent();
443
- _a.label = 10;
444
- case 10:
445
- if (!(status_1 === null || status_1 === undefined)) return [3 /*break*/, 12];
446
- console.log("Setting Opera Queue as data not available");
447
- return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
448
- case 11:
449
- setDataOnKey = _a.sent();
450
- if (setDataOnKey === 1 || setDataOnKey === 0) {
451
- return [2 /*return*/, [null, 'success']];
452
- }
453
- return [3 /*break*/, 13];
454
- case 12:
455
- console.log("Data available in queue");
456
- _a.label = 13;
457
- case 13: return [3 /*break*/, 15];
458
- case 14:
459
- error_2 = _a.sent();
460
- console.error(error_2);
461
- return [2 /*return*/, [error_2, null]];
462
- case 15: return [2 /*return*/];
463
- }
464
- });
465
- }); };
466
- exports.AddToQueueForOpera = AddToQueueForOpera;
467
- // email prioritysearch
468
- /**
469
- * This function is used to search data in case of contact from memory server using email
470
- * @param params.db database objects
471
- * @param params.ProfileType profile type account/contact
472
- * @param params.PrimaryEmail primary email
473
- * @param params.SecondaryEmail secondary email
474
- * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
475
- * @param params.SelectedFields to get only selected fields
476
- * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
477
- * @param params.MemoryServerClient memory server client object to get data from memory server
478
- * @param params.CompanyId to indicate searcing is to do from memory server
479
- * @param params.DataSet to indicate searcing is to do from memory server
480
- *
481
- * @returns
482
- */
483
- var EmailPrioritySearch = function (params) { return __awaiter(void 0, void 0, void 0, function () {
484
- return __generator(this, function (_a) {
485
- return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
486
- var $project, i, script, primaryEmail, secondaryEmail, primaryEmail_1, mongodbTransactionQueryopts, _a, memoryServerSearchError, memoryServerSearchData, id, convertedToObjectID, result, mongodbTransactionQueryopts, allContactData, objectID, type, result, primaryEmail_2, secondaryEmail_1, primaryEmailrResult, secondaryEmailResult, result_1, ex_3;
487
- var _b;
488
- return __generator(this, function (_c) {
489
- switch (_c.label) {
490
- case 0:
491
- _c.trys.push([0, 11, , 12]);
492
- $project = {};
493
- if (params.SelectedFields && params.SelectedFields.length > 0) {
494
- for (i = 0; i < params.SelectedFields.length; i++) {
495
- $project[params.SelectedFields[i]] = 1;
496
- }
497
- }
498
- else {
499
- //setting dummy field in projection for fast query processing
500
- $project = {};
501
- }
502
- if (!(params && params.SearchFromMemoryServer === true)) return [3 /*break*/, 6];
503
- script = "";
504
- primaryEmail = null;
505
- secondaryEmail = null;
506
- if (params.PrimaryEmail && params.SecondaryEmail) {
507
- primaryEmail = params.PrimaryEmail.toString().toLowerCase().trim();
508
- secondaryEmail = params.SecondaryEmail.toString().toLowerCase().trim();
509
- script += "let result:any = null ;\n let type:any = null;\n result = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"" + primaryEmail + "\"); \n if(result){\n // req.response = {...result}\n type = 'primary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"" + primaryEmail + "\"); \n if(result){\n // req.response = {...result}\n type= 'primary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"" + secondaryEmail + "\"); \n if(result){\n // req.response = {...result}\n type= 'secondary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"" + secondaryEmail + "\"); \n if(result){\n // req.response = {...result}\n type = 'secondary_email'\n // socket.write(JSON.stringify(req))\n }\n\n }\n }\n }\n if(result===null || result===undefined){\n socket.write(JSON.stringify(req))\n }else{\n req.response = {...result}\n req.response.type = type;\n socket.write(JSON.stringify(req))\n }";
510
- }
511
- else if (params.PrimaryEmail) {
512
- primaryEmail_1 = params.PrimaryEmail.toString().toLowerCase().trim();
513
- script += "let result = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"" + primaryEmail_1 + "\"); \n if(result){\n req.response = {...result}\n req.response.type = 'primary_email'\n socket.write(JSON.stringify(req))\n }else{\n let result:any = db[\"" + params.DataSet + "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"" + primaryEmail_1 + "\"); \n if(result){\n req.response = {...result}\n req.response.type = 'primary_email'\n socket.write(JSON.stringify(req))\n }\n }";
514
- }
515
- mongodbTransactionQueryopts = {};
516
- return [4 /*yield*/, params.MemoryServerClient.Fetch('execute', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'Script': script })];
517
- case 1:
518
- _a = _c.sent(), memoryServerSearchError = _a[0], memoryServerSearchData = _a[1];
519
- if (!(memoryServerSearchData && Object.keys(memoryServerSearchData.response).length !== 0)) return [3 /*break*/, 4];
520
- id = (_b = memoryServerSearchData === null || memoryServerSearchData === void 0 ? void 0 : memoryServerSearchData.response) === null || _b === void 0 ? void 0 : _b._id;
521
- if (!(id && id !== '')) return [3 /*break*/, 3];
522
- convertedToObjectID = new mongodb_1.ObjectId(id);
523
- return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': convertedToObjectID }, mongodbTransactionQueryopts)];
524
- case 2:
525
- result = _c.sent();
526
- if (result) {
527
- result.Type = memoryServerSearchData.response.type;
528
- resolve([null, result]);
529
- }
530
- else {
531
- resolve([null, 'result not found']);
532
- }
533
- _c.label = 3;
534
- case 3: return [3 /*break*/, 5];
535
- case 4:
536
- resolve([null, 'memory server search data not found']);
537
- _c.label = 5;
538
- case 5: return [3 /*break*/, 10];
539
- case 6:
540
- mongodbTransactionQueryopts = {};
541
- return [4 /*yield*/, params.db.collection(params.ProfileType).find({}, { projection: { Email: 1, SecondaryEmail: 1, _id: 1 } }, mongodbTransactionQueryopts).toArray()];
542
- case 7:
543
- allContactData = _c.sent();
544
- console.log(allContactData);
545
- if (!(allContactData && allContactData.length > 0)) return [3 /*break*/, 10];
546
- objectID = null;
547
- type = "";
548
- result = null;
549
- if (params.PrimaryEmail && params.SecondaryEmail) {
550
- primaryEmail_2 = params.PrimaryEmail.toString().toLowerCase().trim();
551
- secondaryEmail_1 = params.SecondaryEmail.toString().toLowerCase().trim();
552
- result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
553
- if (result) {
554
- objectID = result._id;
555
- type = 'primary_email';
556
- }
557
- else {
558
- result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
559
- if (result) {
560
- objectID = result._id;
561
- type = 'primary_email';
562
- }
563
- else {
564
- result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
565
- if (result) {
566
- objectID = result._id;
567
- type = 'secondary_email';
568
- }
569
- else {
570
- result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
571
- if (result) {
572
- objectID = result._id;
573
- type = 'secondary_email';
574
- }
575
- }
576
- }
577
- }
578
- }
579
- else if (params.PrimaryEmail) {
580
- primaryEmailrResult = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
581
- if (primaryEmailrResult) {
582
- objectID = primaryEmailrResult._id;
583
- type = 'primary_email';
584
- }
585
- else {
586
- secondaryEmailResult = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
587
- if (secondaryEmailResult) {
588
- type = 'primary_email';
589
- objectID = primaryEmailrResult._id;
590
- }
591
- }
592
- }
593
- if (!(objectID === null)) return [3 /*break*/, 8];
594
- resolve(null);
595
- return [3 /*break*/, 10];
596
- case 8:
597
- if (!objectID) return [3 /*break*/, 10];
598
- return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': objectID }, { projection: $project }, mongodbTransactionQueryopts)];
599
- case 9:
600
- result_1 = _c.sent();
601
- if (result_1) {
602
- result_1.Type = type;
603
- resolve([null, result_1]);
604
- }
605
- else {
606
- resolve([null, 'result not found']);
607
- }
608
- _c.label = 10;
609
- case 10: return [3 /*break*/, 12];
610
- case 11:
611
- ex_3 = _c.sent();
612
- resolve([ex_3, null]);
613
- return [3 /*break*/, 12];
614
- case 12: return [2 /*return*/];
615
- }
616
- });
617
- }); })];
618
- });
619
- }); };
620
- exports.EmailPrioritySearch = EmailPrioritySearch;
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
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.EmailPrioritySearch = exports.AddToQueueForOpera = exports.UpdateInitialSyncData = exports.GetProfileDetailByDynamicFields = exports.OperaErrorHandler = exports.SyncContactWithOperaOnEmailUnsubscribe = exports.GetIntegrationSettings = void 0;
43
+ var mongodb_1 = require("mongodb");
44
+ var __1 = require("..");
45
+ var constants_1 = __importDefault(require("../constants"));
46
+ var GetIntegrationSettings = function (db, hotelCode) {
47
+ return new Promise(function (resolve, reject) {
48
+ var hotelMatch = { "IsActive": true, "PropertyStatus": constants_1.default.OperaPropertyStatus.Active };
49
+ if (hotelCode != "all") {
50
+ hotelMatch.PropertyCode = new RegExp(hotelCode, "i");
51
+ }
52
+ db.collection("IntegrationSettings").aggregate([
53
+ { $match: { "IntegrationParty": "Oracle", "IntegrationPartyCode": "Opera", "IsActive": true } },
54
+ { $project: { Status: 1, ForceDisable: 1, InterfaceId: 1, InitialSyncStatus: 1, PropertySharedDB: 1 } },
55
+ {
56
+ $lookup: {
57
+ from: "OperaProperty", pipeline: [{ $match: hotelMatch }, {
58
+ $project: {
59
+ "_id": 1,
60
+ "PropertyName": 1,
61
+ "PropertyCode": 1,
62
+ "ChainCode": 1,
63
+ "Currency": 1,
64
+ "LeadProperty": 1,
65
+ "ReservationEmail": 1,
66
+ "SubscribeID": 1,
67
+ "InitialSyncStatus": 1,
68
+ "PropertyStatus": 1,
69
+ "IsActive": 1,
70
+ "Modules": 1,
71
+ "ProfileInitialSyncDataProcessStartTime": 1,
72
+ "ProfileInitialSyncDataProcessEndTime": 1,
73
+ "InitialSyncCompleteDate": 1,
74
+ "LastInventorySyncDate": 1,
75
+ "LastInventorySyncStatus": 1,
76
+ "ProfileInitialSyncDataProcessErrorTime": 1,
77
+ "ProfileInitialSyncDataProcessReStartCounter": 1,
78
+ "DefaultRoomTypesAdded": 1
79
+ }
80
+ }], as: "HotelList"
81
+ }
82
+ },
83
+ { $lookup: { from: "OperaOptimiserMapping", pipeline: [{ $project: { "_id": 1, "Name": 1, "Data": 1 } }], as: "OperaOptimiserMapping" } }
84
+ ]).toArray(function (error, result) {
85
+ if (error) {
86
+ error.name += " - Fetch Opera Integration Settings";
87
+ OperaErrorHandler(db, error);
88
+ reject(error);
89
+ }
90
+ else if (result && result.length > 0) {
91
+ resolve(result[0]);
92
+ }
93
+ else {
94
+ resolve(null);
95
+ }
96
+ });
97
+ });
98
+ };
99
+ exports.GetIntegrationSettings = GetIntegrationSettings;
100
+ var SyncContactWithOperaOnEmailUnsubscribe = function (db, email) {
101
+ if (db && email) {
102
+ db.collection("Company").findOne({}, { projection: { "Setting.AppsSubscribed": 1 } }, function (err, result) {
103
+ if (err) {
104
+ if (err.name)
105
+ err.name += " - while checking AppsSubscribe in Company";
106
+ OperaErrorHandler(db, err);
107
+ }
108
+ else if (result && result.Setting && result.Setting.AppsSubscribed && result.Setting.AppsSubscribed.indexOf(constants_1.default.STORE_APP_NAMES.OPERA_PMS) >= 0) {
109
+ db.collection("Contact").findOne({ Email: new RegExp("^" + email + "$", "i"), "IsActive": true }, { projection: { "_id": 1, "OperaProfileId": 1 } }, function (errContact, resultContact) {
110
+ if (errContact) {
111
+ if (errContact.name)
112
+ errContact.name += " - while fetching contact to update contact opera sync flag";
113
+ OperaErrorHandler(db, errContact);
114
+ }
115
+ else if (resultContact && resultContact._id && resultContact.OperaProfileId) {
116
+ GetIntegrationSettings(db, "all").then(function (oiSettings) {
117
+ if (oiSettings && oiSettings.Status == constants_1.default.CompanyAppStatus.ENABLE && oiSettings.HotelList && oiSettings.HotelList.length > 0) {
118
+ if (oiSettings.HotelList.filter(function (x) { return x.Modules && x.Modules.length > 0 && x.Modules.find(function (y) { return y.ModuleName && y.ModuleName == "contact"; }); }).length > 0)
119
+ // db.collection("Contact").updateOne({ "_id": resultContact._id, "IsActive": true }, { $set: { "OperaStatus": constants.OperaSyncStatus.READY } });
120
+ db.collection("Contact").updateOne({ "_id": resultContact._id, "IsActive": true }, { $set: { "EmailSubscriptionFromOptimiserToOpera": (new Date()).getMilliseconds() } });
121
+ }
122
+ }, function (erroOiSettings) {
123
+ if (erroOiSettings.name)
124
+ erroOiSettings.name += " - while fetching integration settings to update contact opera sync flag";
125
+ OperaErrorHandler(db, erroOiSettings);
126
+ });
127
+ }
128
+ });
129
+ }
130
+ });
131
+ }
132
+ };
133
+ exports.SyncContactWithOperaOnEmailUnsubscribe = SyncContactWithOperaOnEmailUnsubscribe;
134
+ var OperaErrorHandler = function (db, ex) {
135
+ var errObj = {
136
+ 'error-name': ex.name,
137
+ 'error-message': ex.message,
138
+ 'error-info': ex.stack,
139
+ 'time': new Date()
140
+ };
141
+ db.collection("Error").insertOne(errObj, function (err, res) {
142
+ if (err) {
143
+ console.log(err);
144
+ }
145
+ });
146
+ };
147
+ exports.OperaErrorHandler = OperaErrorHandler;
148
+ /**
149
+ * This function is used to search profiles by dynamics fields in both Memory server and db.
150
+ * If data found in memory server then it search data by _id in db the return data.
151
+ *
152
+ * @param params.ModuleName Name of Module either Account | Contact.
153
+ * @param params.MappingFields fields which is used for searching
154
+ * @param params.ModuleData Data of fields
155
+ * @param params.db database objects
156
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
157
+ * @param params.SelectedFields to get only selected fields
158
+ * @param params.AllowInactive to search data without IsActive field.
159
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
160
+ * @param params.MemoryServerClient memory server client object to get data from memory server
161
+ * @param params.CompanyId to indicate searcing is to do from memory server
162
+ * @param params.DataSet to indicate searcing is to do from memory server
163
+ *
164
+ * @returns [error,ResultData]
165
+ */
166
+ var GetProfileDetailByDynamicFields = function (params) {
167
+ return __awaiter(this, void 0, void 0, function () {
168
+ var mongodbTransactionQueryopts, searchObj, searchItems, len, i, field, appendSearch, _a, memoryServerSearchError, dataResult, projection, i, resultData, ex_1, searchObj, projection, len, i, field, i, resultData, ex_2;
169
+ return __generator(this, function (_b) {
170
+ switch (_b.label) {
171
+ case 0:
172
+ mongodbTransactionQueryopts = {};
173
+ //if query options passed then setting them to pass into query.
174
+ if (params.MongodbTransactionQueryOptions) {
175
+ mongodbTransactionQueryopts = params.MongodbTransactionQueryOptions;
176
+ }
177
+ if (!params.SearchFromMemoryServer) return [3 /*break*/, 10];
178
+ searchObj = "x=>";
179
+ searchItems = new Array();
180
+ /*Preparing searching object for memory server*/
181
+ for (len = params.MappingFields.length, i = 0; i < len; i++) {
182
+ field = params.MappingFields[i];
183
+ appendSearch = "";
184
+ switch (field.UIDataType) {
185
+ case 'email':
186
+ case 'text':
187
+ //left hand part
188
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
189
+ //right hand part
190
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
191
+ break;
192
+ // case 'multilookup':
193
+ // break;
194
+ // case 'multiselect':
195
+ // break;
196
+ case 'lookup':
197
+ case 'objectid':
198
+ //left hand part
199
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
200
+ //right hand part
201
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
202
+ break;
203
+ case 'phone':
204
+ //left hand part
205
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
206
+ //right hand part
207
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
208
+ break;
209
+ case 'dropdown':
210
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
211
+ //right hand part
212
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
213
+ break;
214
+ default:
215
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
216
+ //right hand part
217
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
218
+ break;
219
+ }
220
+ if (appendSearch && appendSearch.length > 0) {
221
+ searchItems.push(appendSearch);
222
+ }
223
+ }
224
+ if (!(searchItems.length > 0)) return [3 /*break*/, 8];
225
+ searchObj += searchItems.join(' && ');
226
+ //if search required on InActive data
227
+ // if (params.AllowInactive != true) {
228
+ // searchObj += " && x.IsActive== true";
229
+ // }
230
+ console.log("Search query===>", searchObj);
231
+ return [4 /*yield*/, params.MemoryServerClient.Fetch('search', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'findQuery': searchObj })];
232
+ case 1:
233
+ _a = _b.sent(), memoryServerSearchError = _a[0], dataResult = _a[1];
234
+ if (!(dataResult && dataResult.response && dataResult.response._id)) return [3 /*break*/, 6];
235
+ projection = {};
236
+ //to get only required field otherwise get all data of object by id
237
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
238
+ for (i = 0; i < params.SelectedFields.length; i++) {
239
+ projection[params.SelectedFields[i]] = 1;
240
+ }
241
+ }
242
+ else {
243
+ projection = {};
244
+ }
245
+ resultData = null;
246
+ _b.label = 2;
247
+ case 2:
248
+ _b.trys.push([2, 4, , 5]);
249
+ return [4 /*yield*/, params.db.collection(params.ModuleName).findOne({ _id: new mongodb_1.ObjectId(dataResult.response._id) }, projection, mongodbTransactionQueryopts)];
250
+ case 3:
251
+ resultData = _b.sent();
252
+ return [2 /*return*/, [null, resultData]];
253
+ case 4:
254
+ ex_1 = _b.sent();
255
+ return [2 /*return*/, [ex_1, null]];
256
+ case 5: return [3 /*break*/, 7];
257
+ case 6:
258
+ if (memoryServerSearchError) {
259
+ console.log("Error while searching in memory server", memoryServerSearchError);
260
+ return [2 /*return*/, [memoryServerSearchError, null]];
261
+ }
262
+ else {
263
+ console.log("data not found in memory server");
264
+ return [2 /*return*/, [null, null]];
265
+ }
266
+ _b.label = 7;
267
+ case 7: return [3 /*break*/, 9];
268
+ case 8:
269
+ console.log("Search object not prepared");
270
+ return [2 /*return*/, [null, null]];
271
+ case 9: return [3 /*break*/, 14];
272
+ case 10:
273
+ searchObj = {};
274
+ projection = {};
275
+ /*Preparing searching object*/
276
+ for (len = params.MappingFields.length, i = 0; i < len; i++) {
277
+ field = params.MappingFields[i];
278
+ switch (field.UIDataType) {
279
+ case 'email':
280
+ case 'text':
281
+ searchObj[field.Name] = new RegExp('^' + params.ModuleData[field.Name] + '$', 'i');
282
+ break;
283
+ // case 'multilookup':
284
+ // break;
285
+ // case 'multiselect':
286
+ // break;
287
+ case 'lookup':
288
+ case 'objectid':
289
+ searchObj[field.Name] = params.ModuleData[field.Name];
290
+ break;
291
+ case 'phone':
292
+ case 'dropdown':
293
+ searchObj[field.Name] = params.ModuleData[field.Name];
294
+ break;
295
+ default:
296
+ searchObj[field.Name] = params.ModuleData[field.Name];
297
+ break;
298
+ }
299
+ }
300
+ //If serch object build adding IsActive flag
301
+ if (!__1._utility.isEmptyObj(searchObj)) {
302
+ //if search required on InActive data
303
+ if (params.AllowInactive != true) {
304
+ searchObj["IsActive"] = true;
305
+ //to show data is InActive so adding IsActive field in SelectedFields array if not available.
306
+ if (params.SelectedFields && params.SelectedFields.length > 0 && !params.SelectedFields.find(function (x) { return x.Name == "IsActive"; })) {
307
+ params.SelectedFields.push("IsActive");
308
+ }
309
+ }
310
+ }
311
+ else {
312
+ console.log("Search object not prepared");
313
+ return [2 /*return*/, [null, null]];
314
+ }
315
+ //to get only required field otherwise get all data of object by id
316
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
317
+ for (i = 0; i < params.SelectedFields.length; i++) {
318
+ projection[params.SelectedFields[i]] = 1;
319
+ }
320
+ }
321
+ else {
322
+ projection = {};
323
+ }
324
+ resultData = null;
325
+ _b.label = 11;
326
+ case 11:
327
+ _b.trys.push([11, 13, , 14]);
328
+ return [4 /*yield*/, params.db.collection(params.ModuleName).findOne(searchObj, projection, mongodbTransactionQueryopts)];
329
+ case 12:
330
+ resultData = _b.sent();
331
+ return [2 /*return*/, [null, resultData]];
332
+ case 13:
333
+ ex_2 = _b.sent();
334
+ return [2 /*return*/, [ex_2, null]];
335
+ case 14: return [2 /*return*/];
336
+ }
337
+ });
338
+ });
339
+ };
340
+ exports.GetProfileDetailByDynamicFields = GetProfileDetailByDynamicFields;
341
+ /**
342
+ * This function is used to update data.
343
+ * @param params.ModuleName Name of Module either Account | Contact.
344
+ * @param params.Collection Name of Collection
345
+ * @param params.Id which doucment has to update
346
+ * @param params.db database objects
347
+ * @param params.MongodbTransactionQueryOptions Mongodb query option object , it may have transaction as well.
348
+ * @param params.UpdateObj to update data in collection.
349
+
350
+ * @returns
351
+ */
352
+ var UpdateInitialSyncData = function (params) { return __awaiter(void 0, void 0, void 0, function () {
353
+ var mongodbQueryOpts;
354
+ return __generator(this, function (_a) {
355
+ mongodbQueryOpts = {};
356
+ if (params.MongodbQueryOpts) {
357
+ mongodbQueryOpts = params.MongodbQueryOpts;
358
+ }
359
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
360
+ var updatedData, error_1;
361
+ return __generator(this, function (_a) {
362
+ switch (_a.label) {
363
+ case 0:
364
+ _a.trys.push([0, 3, , 4]);
365
+ if (!params) return [3 /*break*/, 2];
366
+ updatedData = null;
367
+ return [4 /*yield*/, params.db.collection(params.Collection).updateOne({ '_id': params.Id }, { $set: params.UpdateObj }, mongodbQueryOpts)];
368
+ case 1:
369
+ updatedData = _a.sent();
370
+ if (updatedData) {
371
+ resolve([null, true]);
372
+ }
373
+ _a.label = 2;
374
+ case 2: return [3 /*break*/, 4];
375
+ case 3:
376
+ error_1 = _a.sent();
377
+ resolve([error_1, null]);
378
+ return [3 /*break*/, 4];
379
+ case 4: return [2 /*return*/];
380
+ }
381
+ });
382
+ }); })];
383
+ });
384
+ }); };
385
+ exports.UpdateInitialSyncData = UpdateInitialSyncData;
386
+ /**
387
+ * This function is used to stop unnecessary databse hits for checking any data available send to opera.
388
+ * this flag will be in reddis
389
+ * @param params.RedisClient reddis client
390
+ * @param params.CompanyId to create/check opera key with company id
391
+ * @param params.Mode GET/SET operation to perform on reddis
392
+ * @param params.db database objects
393
+ * @param params.isAvailable value to set in reddis
394
+
395
+ * @returns
396
+ */
397
+ var AddToQueueForOpera = function (params) { return __awaiter(void 0, void 0, void 0, function () {
398
+ var key, redisDataOnKey, setDataOnKey, setDataOnKey, status_1, setDataOnKey, error_2;
399
+ return __generator(this, function (_a) {
400
+ switch (_a.label) {
401
+ case 0:
402
+ _a.trys.push([0, 14, , 15]);
403
+ key = 'opera-queue:' + params.CompanyId.toString();
404
+ if (!(params.Mode === 'GET')) return [3 /*break*/, 5];
405
+ return [4 /*yield*/, params.RedisClient.hget(key, 'DataAvailable')];
406
+ case 1:
407
+ redisDataOnKey = _a.sent();
408
+ if (!(redisDataOnKey === null || redisDataOnKey === undefined)) return [3 /*break*/, 3];
409
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
410
+ case 2:
411
+ setDataOnKey = _a.sent();
412
+ // reddis returns 1 when data inserted
413
+ if (setDataOnKey === 1) {
414
+ return [2 /*return*/, [null, 'true']];
415
+ }
416
+ return [3 /*break*/, 4];
417
+ case 3: return [2 /*return*/, [null, redisDataOnKey]];
418
+ case 4: return [3 /*break*/, 13];
419
+ case 5:
420
+ if (!(params.Mode === 'SET')) return [3 /*break*/, 13];
421
+ //
422
+ console.log("Request receive to set in Opera Queue : ", params.isAvailable);
423
+ if (!(params.isAvailable === true)) return [3 /*break*/, 7];
424
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
425
+ case 6:
426
+ setDataOnKey = _a.sent();
427
+ // reddis returns 1 when data inserted and 0 when data already exists
428
+ if (setDataOnKey === 1 || setDataOnKey === 0) {
429
+ return [2 /*return*/, [null, 'true']];
430
+ }
431
+ return [3 /*break*/, 13];
432
+ case 7:
433
+ if (!(params.isAvailable === false)) return [3 /*break*/, 13];
434
+ console.log("Checking data available or not in OperaApiLogs");
435
+ return [4 /*yield*/, params.db.collection("OperaApiLogs").findOne({ 'Status': { $in: ["-1", "2", "3"] } })];
436
+ case 8:
437
+ status_1 = _a.sent();
438
+ if (!!status_1) return [3 /*break*/, 10];
439
+ console.log("Checking data available or not in OperaDataSyncRequest");
440
+ return [4 /*yield*/, params.db.collection("OperaDataSyncRequest").findOne({ 'Status': '1', 'IsActive': true })];
441
+ case 9:
442
+ status_1 = _a.sent();
443
+ _a.label = 10;
444
+ case 10:
445
+ if (!(status_1 === null || status_1 === undefined)) return [3 /*break*/, 12];
446
+ console.log("Setting Opera Queue as data not available");
447
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
448
+ case 11:
449
+ setDataOnKey = _a.sent();
450
+ if (setDataOnKey === 1 || setDataOnKey === 0) {
451
+ return [2 /*return*/, [null, 'success']];
452
+ }
453
+ return [3 /*break*/, 13];
454
+ case 12:
455
+ console.log("Data available in queue");
456
+ _a.label = 13;
457
+ case 13: return [3 /*break*/, 15];
458
+ case 14:
459
+ error_2 = _a.sent();
460
+ console.error(error_2);
461
+ return [2 /*return*/, [error_2, null]];
462
+ case 15: return [2 /*return*/];
463
+ }
464
+ });
465
+ }); };
466
+ exports.AddToQueueForOpera = AddToQueueForOpera;
467
+ // email prioritysearch
468
+ /**
469
+ * This function is used to search data in case of contact from memory server using email
470
+ * @param params.db database objects
471
+ * @param params.ProfileType profile type account/contact
472
+ * @param params.PrimaryEmail primary email
473
+ * @param params.SecondaryEmail secondary email
474
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
475
+ * @param params.SelectedFields to get only selected fields
476
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
477
+ * @param params.MemoryServerClient memory server client object to get data from memory server
478
+ * @param params.CompanyId to indicate searcing is to do from memory server
479
+ * @param params.DataSet to indicate searcing is to do from memory server
480
+ *
481
+ * @returns
482
+ */
483
+ var EmailPrioritySearch = function (params) { return __awaiter(void 0, void 0, void 0, function () {
484
+ return __generator(this, function (_a) {
485
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
486
+ var $project, i, script, primaryEmail, secondaryEmail, primaryEmail_1, mongodbTransactionQueryopts, _a, memoryServerSearchError, memoryServerSearchData, id, convertedToObjectID, result, mongodbTransactionQueryopts, allContactData, objectID, type, result, primaryEmail_2, secondaryEmail_1, primaryEmailrResult, secondaryEmailResult, result_1, ex_3;
487
+ var _b;
488
+ return __generator(this, function (_c) {
489
+ switch (_c.label) {
490
+ case 0:
491
+ _c.trys.push([0, 11, , 12]);
492
+ $project = {};
493
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
494
+ for (i = 0; i < params.SelectedFields.length; i++) {
495
+ $project[params.SelectedFields[i]] = 1;
496
+ }
497
+ }
498
+ else {
499
+ //setting dummy field in projection for fast query processing
500
+ $project = {};
501
+ }
502
+ if (!(params && params.SearchFromMemoryServer === true)) return [3 /*break*/, 6];
503
+ script = "";
504
+ primaryEmail = null;
505
+ secondaryEmail = null;
506
+ if (params.PrimaryEmail && params.SecondaryEmail) {
507
+ primaryEmail = params.PrimaryEmail.toString().toLowerCase().trim();
508
+ secondaryEmail = params.SecondaryEmail.toString().toLowerCase().trim();
509
+ script += "let result:any = null ;\n let type:any = null;\n result = db[\"".concat(params.DataSet, "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"").concat(primaryEmail, "\"); \n if(result){\n // req.response = {...result}\n type = 'primary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"").concat(params.DataSet, "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"").concat(primaryEmail, "\"); \n if(result){\n // req.response = {...result}\n type= 'primary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"").concat(params.DataSet, "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"").concat(secondaryEmail, "\"); \n if(result){\n // req.response = {...result}\n type= 'secondary_email'\n // socket.write(JSON.stringify(req))\n }else{\n result = db[\"").concat(params.DataSet, "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"").concat(secondaryEmail, "\"); \n if(result){\n // req.response = {...result}\n type = 'secondary_email'\n // socket.write(JSON.stringify(req))\n }\n\n }\n }\n }\n if(result===null || result===undefined){\n socket.write(JSON.stringify(req))\n }else{\n req.response = {...result}\n req.response.type = type;\n socket.write(JSON.stringify(req))\n }");
510
+ }
511
+ else if (params.PrimaryEmail) {
512
+ primaryEmail_1 = params.PrimaryEmail.toString().toLowerCase().trim();
513
+ script += "let result = db[\"".concat(params.DataSet, "\"].Records.find((x: any)=>x.Email?.toString().toLowerCase().trim()===\"").concat(primaryEmail_1, "\"); \n if(result){\n req.response = {...result}\n req.response.type = 'primary_email'\n socket.write(JSON.stringify(req))\n }else{\n let result:any = db[\"").concat(params.DataSet, "\"].Records.find((x: any)=>x.SecondaryEmail?.toString().toLowerCase().trim()===\"").concat(primaryEmail_1, "\"); \n if(result){\n req.response = {...result}\n req.response.type = 'primary_email'\n socket.write(JSON.stringify(req))\n }\n }");
514
+ }
515
+ mongodbTransactionQueryopts = {};
516
+ return [4 /*yield*/, params.MemoryServerClient.Fetch('execute', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'Script': script })];
517
+ case 1:
518
+ _a = _c.sent(), memoryServerSearchError = _a[0], memoryServerSearchData = _a[1];
519
+ if (!(memoryServerSearchData && Object.keys(memoryServerSearchData.response).length !== 0)) return [3 /*break*/, 4];
520
+ id = (_b = memoryServerSearchData === null || memoryServerSearchData === void 0 ? void 0 : memoryServerSearchData.response) === null || _b === void 0 ? void 0 : _b._id;
521
+ if (!(id && id !== '')) return [3 /*break*/, 3];
522
+ convertedToObjectID = new mongodb_1.ObjectId(id);
523
+ return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': convertedToObjectID }, mongodbTransactionQueryopts)];
524
+ case 2:
525
+ result = _c.sent();
526
+ if (result) {
527
+ result.Type = memoryServerSearchData.response.type;
528
+ resolve([null, result]);
529
+ }
530
+ else {
531
+ resolve([null, 'result not found']);
532
+ }
533
+ _c.label = 3;
534
+ case 3: return [3 /*break*/, 5];
535
+ case 4:
536
+ resolve([null, 'memory server search data not found']);
537
+ _c.label = 5;
538
+ case 5: return [3 /*break*/, 10];
539
+ case 6:
540
+ mongodbTransactionQueryopts = {};
541
+ return [4 /*yield*/, params.db.collection(params.ProfileType).find({}, { projection: { Email: 1, SecondaryEmail: 1, _id: 1 } }, mongodbTransactionQueryopts).toArray()];
542
+ case 7:
543
+ allContactData = _c.sent();
544
+ console.log(allContactData);
545
+ if (!(allContactData && allContactData.length > 0)) return [3 /*break*/, 10];
546
+ objectID = null;
547
+ type = "";
548
+ result = null;
549
+ if (params.PrimaryEmail && params.SecondaryEmail) {
550
+ primaryEmail_2 = params.PrimaryEmail.toString().toLowerCase().trim();
551
+ secondaryEmail_1 = params.SecondaryEmail.toString().toLowerCase().trim();
552
+ result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
553
+ if (result) {
554
+ objectID = result._id;
555
+ type = 'primary_email';
556
+ }
557
+ else {
558
+ result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
559
+ if (result) {
560
+ objectID = result._id;
561
+ type = 'primary_email';
562
+ }
563
+ else {
564
+ result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
565
+ if (result) {
566
+ objectID = result._id;
567
+ type = 'secondary_email';
568
+ }
569
+ else {
570
+ result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
571
+ if (result) {
572
+ objectID = result._id;
573
+ type = 'secondary_email';
574
+ }
575
+ }
576
+ }
577
+ }
578
+ }
579
+ else if (params.PrimaryEmail) {
580
+ primaryEmailrResult = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
581
+ if (primaryEmailrResult) {
582
+ objectID = primaryEmailrResult._id;
583
+ type = 'primary_email';
584
+ }
585
+ else {
586
+ secondaryEmailResult = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
587
+ if (secondaryEmailResult) {
588
+ type = 'primary_email';
589
+ objectID = primaryEmailrResult._id;
590
+ }
591
+ }
592
+ }
593
+ if (!(objectID === null)) return [3 /*break*/, 8];
594
+ resolve(null);
595
+ return [3 /*break*/, 10];
596
+ case 8:
597
+ if (!objectID) return [3 /*break*/, 10];
598
+ return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': objectID }, { projection: $project }, mongodbTransactionQueryopts)];
599
+ case 9:
600
+ result_1 = _c.sent();
601
+ if (result_1) {
602
+ result_1.Type = type;
603
+ resolve([null, result_1]);
604
+ }
605
+ else {
606
+ resolve([null, 'result not found']);
607
+ }
608
+ _c.label = 10;
609
+ case 10: return [3 /*break*/, 12];
610
+ case 11:
611
+ ex_3 = _c.sent();
612
+ resolve([ex_3, null]);
613
+ return [3 /*break*/, 12];
614
+ case 12: return [2 /*return*/];
615
+ }
616
+ });
617
+ }); })];
618
+ });
619
+ }); };
620
+ exports.EmailPrioritySearch = EmailPrioritySearch;