@optimiser/common 1.0.244 → 1.0.245

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.
package/dist/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export * as helperLib from "./lib/helper";
8
8
  export * as _activity from "./lib/activity";
9
9
  export * as _operaUtilCommon from "./lib/operautilitycommon";
10
10
  export * as taskutils from "./lib/taskutils";
11
+ export { MemoryDBConnect } from "./lib/memoryserverclient";
11
12
  export * from "./modals/connection.modal";
12
13
  export * from "./modals/redisconfig.modal";
13
14
  export * from "./modals/notificationData.modal";
package/dist/index.js CHANGED
@@ -38,6 +38,8 @@ exports.helperLib = __importStar(require("./lib/helper"));
38
38
  exports._activity = __importStar(require("./lib/activity"));
39
39
  exports._operaUtilCommon = __importStar(require("./lib/operautilitycommon"));
40
40
  exports.taskutils = __importStar(require("./lib/taskutils"));
41
+ var memoryserverclient_1 = require("./lib/memoryserverclient");
42
+ Object.defineProperty(exports, "MemoryDBConnect", { enumerable: true, get: function () { return memoryserverclient_1.MemoryDBConnect; } });
41
43
  // Interface Exports
42
44
  __exportStar(require("./modals/connection.modal"), exports);
43
45
  __exportStar(require("./modals/redisconfig.modal"), exports);
@@ -1,4 +1,4 @@
1
- import { Db } from "mongodb";
1
+ import { Db, MongoClient, ClientSession } from "mongodb";
2
2
  import { NextFunction, Response } from "express";
3
3
  import IORedis from "ioredis";
4
4
  import { Sequelize } from "sequelize";
@@ -100,5 +100,17 @@ declare class Connection {
100
100
  * @description Helper function to send response
101
101
  */
102
102
  ReturnJsonResponse: (req: OPT_Request, res: Response, params: ResponseStructure) => void;
103
+ /**
104
+ * @param DBName
105
+ * @returns Promise
106
+ * @description return session from client
107
+ */
108
+ GetDBSession(dbName: string, dbAddress: string): Promise<[Error?, ClientSession?]>;
109
+ /**
110
+ * @param DBName
111
+ * @returns Promise
112
+ * @description return session from client
113
+ */
114
+ GetDBClient(dbName: string, dbAddress: string): Promise<[Error?, MongoClient?]>;
103
115
  }
104
116
  export { Connection };
@@ -458,6 +458,102 @@ var Connection = /** @class */ (function () {
458
458
  Connection.prototype.GetActiveDBConnections = function () {
459
459
  return Object.keys(this.connections);
460
460
  };
461
+ /**
462
+ * @param DBName
463
+ * @returns Promise
464
+ * @description return session from client
465
+ */
466
+ Connection.prototype.GetDBSession = function (dbName, dbAddress) {
467
+ return __awaiter(this, void 0, void 0, function () {
468
+ var _this = this;
469
+ return __generator(this, function (_a) {
470
+ return [2 /*return*/, new Promise(function (resolve, reject) {
471
+ try {
472
+ // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
473
+ //return this.FindAndReturnDBConnection(DBName, DBAddress)
474
+ // if (dbName == this.masterConfig.MASTER_DB_NAME) {
475
+ // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
476
+ // }
477
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
478
+ resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
479
+ }
480
+ else {
481
+ _this.ConnectToDb({
482
+ DBAddress: dbAddress,
483
+ DBName: dbName
484
+ }).then(function (success) {
485
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
486
+ resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')].startSession()]);
487
+ }
488
+ else {
489
+ resolve([undefined, undefined]);
490
+ }
491
+ });
492
+ }
493
+ // } else {
494
+ // let masterdb = await this.ConnectToDb({
495
+ // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
496
+ // DBName: this.masterConfig.MASTER_DB_NAME
497
+ // })
498
+ // return this.FindAndReturnDBConnection(DBName, DBAddress)
499
+ // }
500
+ }
501
+ catch (ex) {
502
+ //To Do: Error pass properly
503
+ resolve([new Error('Error in Get db session'), undefined]);
504
+ }
505
+ })];
506
+ });
507
+ });
508
+ };
509
+ /**
510
+ * @param DBName
511
+ * @returns Promise
512
+ * @description return session from client
513
+ */
514
+ Connection.prototype.GetDBClient = function (dbName, dbAddress) {
515
+ return __awaiter(this, void 0, void 0, function () {
516
+ var _this = this;
517
+ return __generator(this, function (_a) {
518
+ return [2 /*return*/, new Promise(function (resolve, reject) {
519
+ try {
520
+ // if (this.connections && this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]) {
521
+ //return this.FindAndReturnDBConnection(DBName, DBAddress)
522
+ // if (dbName == this.masterConfig.MASTER_DB_NAME) {
523
+ // resolve([undefined, this.connections[Buffer.from(this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')].startSession()]);
524
+ // }
525
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
526
+ resolve([undefined, _this.connections[Buffer.from(_this.masterConfig.MASTER_CONNECTION_STRING).toString('base64')]]);
527
+ }
528
+ else {
529
+ _this.ConnectToDb({
530
+ DBAddress: dbAddress,
531
+ DBName: dbName
532
+ }).then(function (success) {
533
+ if (_this.connections[Buffer.from(dbAddress).toString('base64')]) {
534
+ resolve([undefined, _this.connections[Buffer.from(dbAddress).toString('base64')]]);
535
+ }
536
+ else {
537
+ resolve([undefined, undefined]);
538
+ }
539
+ });
540
+ }
541
+ // } else {
542
+ // let masterdb = await this.ConnectToDb({
543
+ // DBAddress: this.masterConfig.MASTER_CONNECTION_STRING,
544
+ // DBName: this.masterConfig.MASTER_DB_NAME
545
+ // })
546
+ // return this.FindAndReturnDBConnection(DBName, DBAddress)
547
+ // }
548
+ }
549
+ catch (ex) {
550
+ //To Do: Error pass properly
551
+ resolve([new Error('Error in Get db session'), undefined]);
552
+ }
553
+ })];
554
+ });
555
+ });
556
+ };
461
557
  return Connection;
462
558
  }());
463
559
  exports.Connection = Connection;
@@ -47,8 +47,10 @@ declare const GetEmailSubscribeStatus: (db: Db, email: string) => Promise<Error
47
47
  * @param {isSubscribe} boolean
48
48
  * @param {companyID} mongodb object id, comany id of email
49
49
  * @param {comment} string , to add comment
50
+ * @param {mongodbQueryOptions} object, params to pass on db queries
51
+ * @returns resolve success | error object
50
52
  */
51
- declare const SubscribeEmailForAllDomains: (db: Db, email: string, isSubscribe: boolean, companyID: ObjectID, comment?: string) => Promise<unknown>;
53
+ declare const SubscribeEmailForAllDomains: (db: Db, email: string, isSubscribe: boolean, companyID: ObjectID, comment?: string, mongodbQueryOptions?: any) => Promise<unknown>;
52
54
  /**
53
55
  * checking phone number is valid and has dialing code
54
56
  * if it has dialing code then get country code, get its optimiser country phone code
@@ -687,18 +687,25 @@ exports.GetEmailSubscribeStatus = GetEmailSubscribeStatus;
687
687
  * @param {isSubscribe} boolean
688
688
  * @param {companyID} mongodb object id, comany id of email
689
689
  * @param {comment} string , to add comment
690
+ * @param {mongodbQueryOptions} object, params to pass on db queries
691
+ * @returns resolve success | error object
690
692
  */
691
- var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, comment) {
693
+ var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, comment, mongodbQueryOptions) {
692
694
  if (comment === void 0) { comment = ""; }
695
+ if (mongodbQueryOptions === void 0) { mongodbQueryOptions = null; }
693
696
  return new Promise(function (resolve, reject) {
694
697
  return __awaiter(this, void 0, void 0, function () {
695
- var marketingSettingDetail, marketingCategoryKeys, domainIds_1, domainDetail, existEmailSub, isRequireUpdate, marketingCategoryData, _loop_2, i, error_2;
698
+ var mongodbQueryOpts, marketingSettingDetail, marketingCategoryKeys, domainIds_1, domainDetail, existEmailSub, isRequireUpdate, marketingCategoryData, _loop_2, i, error_2;
696
699
  return __generator(this, function (_a) {
697
700
  switch (_a.label) {
698
701
  case 0:
699
702
  _a.trys.push([0, 7, , 8]);
703
+ mongodbQueryOpts = {};
704
+ if (mongodbQueryOptions) {
705
+ mongodbQueryOpts = mongodbQueryOptions;
706
+ }
700
707
  if (!email) return [3 /*break*/, 6];
701
- return [4 /*yield*/, db.collection('Company').findOne({ IsActive: true }, { projection: { "Setting.MarketingSetting": 1 } })];
708
+ return [4 /*yield*/, db.collection('Company').findOne({ IsActive: true }, { projection: { "Setting.MarketingSetting": 1 } }, mongodbQueryOpts)];
702
709
  case 1:
703
710
  marketingSettingDetail = _a.sent();
704
711
  marketingCategoryKeys = [], domainIds_1 = [];
@@ -714,7 +721,7 @@ var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, c
714
721
  }
715
722
  existEmailSub = {}, isRequireUpdate = false;
716
723
  if (!(domainIds_1 && domainIds_1.length > 0)) return [3 /*break*/, 4];
717
- return [4 /*yield*/, db.collection('EmailStatus').findOne({ 'EmailID': new RegExp("^" + email + "$", "i"), CompanyID: companyID }, { projection: { "Domains": 1 } })];
724
+ return [4 /*yield*/, db.collection('EmailStatus').findOne({ 'EmailID': new RegExp("^" + email + "$", "i"), CompanyID: companyID }, { projection: { "Domains": 1 } }, mongodbQueryOpts)];
718
725
  case 2:
719
726
  existEmailSub = _a.sent();
720
727
  isRequireUpdate = true;
@@ -725,7 +732,7 @@ var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, c
725
732
  Domains: []
726
733
  };
727
734
  }
728
- return [4 /*yield*/, db.collection('ListSchema').findOne({ Name: "CampaignCategory", "Data": { "$elemMatch": { "DomainID": { $in: domainIds_1 } } } }, { projection: { "Data.DomainID": 1, "Data.Key": 1, "Data.IsActive": 1 } })];
735
+ return [4 /*yield*/, db.collection('ListSchema').findOne({ Name: "CampaignCategory", "Data": { "$elemMatch": { "DomainID": { $in: domainIds_1 } } } }, { projection: { "Data.DomainID": 1, "Data.Key": 1, "Data.IsActive": 1 } }, mongodbQueryOpts)];
729
736
  case 3:
730
737
  marketingCategoryData = _a.sent();
731
738
  _loop_2 = function (i) {
@@ -791,9 +798,12 @@ var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, c
791
798
  }
792
799
  _a.label = 4;
793
800
  case 4:
801
+ mongodbQueryOpts["upsert"] = true;
794
802
  if (!isRequireUpdate) return [3 /*break*/, 6];
795
- return [4 /*yield*/, db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })];
803
+ //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
804
+ return [4 /*yield*/, db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, mongodbQueryOpts)];
796
805
  case 5:
806
+ //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
797
807
  _a.sent();
798
808
  _a.label = 6;
799
809
  case 6:
@@ -0,0 +1,39 @@
1
+ /// <reference types="node" />
2
+ import * as net from 'net';
3
+ import { AnyObjectInterface } from '../modals/utility.modal';
4
+ declare class MemoryDBConnect {
5
+ private client?;
6
+ private portNo;
7
+ private host;
8
+ private isConnected;
9
+ private messages;
10
+ /**
11
+ * @param masterConfig Master Connectivity Object
12
+ * @param redisClient Redisclient
13
+ * @description connect to master database and maintain master config and redis client for furture ref
14
+ */
15
+ constructor(portNumber: number, hostName: string);
16
+ /**
17
+ * @description connect to memory server on specified port and host
18
+ * @returns Promise with error first approach and success | failed.
19
+ */
20
+ Initialize(): Promise<[Error?, string?]>;
21
+ /**
22
+ * @param method specifies the function of memory server which needs to execute
23
+ * @param data an object which has data for memory server
24
+ * @param data.CompanyID
25
+ * @param data.DataSet name of dataset to refer the data in memory server
26
+ * @param data.findQuery query by data need to retrieve from memory server
27
+ * @param data.FullDoc data to add, update and delete in memeory server
28
+ * @description write to server stream of memory server and data data from memory server by specific message id
29
+ * LOV:
30
+ * method : search | execute | insertInDataSet | updateInDataSet | deleteInDataSet
31
+ */
32
+ Fetch(method: string, data: AnyObjectInterface): Promise<[any?, AnyObjectInterface?]>;
33
+ /**
34
+ * @description get connection object of memory server if already created other wise create and provide.
35
+ * @returns null | socket client
36
+ */
37
+ Connect(): Promise<net.Socket | undefined>;
38
+ }
39
+ export { MemoryDBConnect };
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ var __generator = (this && this.__generator) || function (thisArg, body) {
31
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
32
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
33
+ function verb(n) { return function (v) { return step([n, v]); }; }
34
+ function step(op) {
35
+ if (f) throw new TypeError("Generator is already executing.");
36
+ while (_) try {
37
+ 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;
38
+ if (y = 0, t) op = [op[0] & 2, t.value];
39
+ switch (op[0]) {
40
+ case 0: case 1: t = op; break;
41
+ case 4: _.label++; return { value: op[1], done: false };
42
+ case 5: _.label++; y = op[1]; op = [0]; continue;
43
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
44
+ default:
45
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
46
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
47
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
48
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
49
+ if (t[2]) _.ops.pop();
50
+ _.trys.pop(); continue;
51
+ }
52
+ op = body.call(thisArg, _);
53
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
54
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
55
+ }
56
+ };
57
+ Object.defineProperty(exports, "__esModule", { value: true });
58
+ exports.MemoryDBConnect = void 0;
59
+ //var net = require('net');
60
+ var net = __importStar(require("net"));
61
+ var crypto = __importStar(require("crypto"));
62
+ var MemoryDBConnect = /** @class */ (function () {
63
+ /**
64
+ * @param masterConfig Master Connectivity Object
65
+ * @param redisClient Redisclient
66
+ * @description connect to master database and maintain master config and redis client for furture ref
67
+ */
68
+ function MemoryDBConnect(portNumber, hostName) {
69
+ this.client = undefined;
70
+ this.portNo = 0;
71
+ this.host = "";
72
+ this.isConnected = false;
73
+ this.messages = {};
74
+ this.portNo = portNumber;
75
+ this.host = hostName;
76
+ // this.Initialize().then(([error, result]) => {
77
+ // if (result == 'failed') {
78
+ // console.log('connection to memory server failed');
79
+ // }
80
+ // })
81
+ }
82
+ /**
83
+ * @description connect to memory server on specified port and host
84
+ * @returns Promise with error first approach and success | failed.
85
+ */
86
+ MemoryDBConnect.prototype.Initialize = function () {
87
+ var _this = this;
88
+ return new Promise(function (resolve, reject) {
89
+ var newConnectRequest = true;
90
+ _this.client = new net.Socket();
91
+ _this.client.connect(_this.portNo, _this.host, function () {
92
+ _this.isConnected = true;
93
+ console.log("client connected to " + _this.portNo + ":" + _this.host);
94
+ if (newConnectRequest) {
95
+ resolve([undefined, 'success']);
96
+ newConnectRequest = false;
97
+ }
98
+ });
99
+ _this.client.on('data', function (data) {
100
+ //console.log("")
101
+ data = JSON.parse(data);
102
+ var message = _this.messages[data.id];
103
+ if (message) {
104
+ delete _this.messages[data.id];
105
+ message(data);
106
+ }
107
+ });
108
+ _this.client.on('close', function () {
109
+ _this.isConnected = false;
110
+ console.log("Client closed for port:host - " + _this.portNo + ":" + _this.host);
111
+ if (newConnectRequest) {
112
+ resolve([undefined, 'failed']);
113
+ newConnectRequest = false;
114
+ }
115
+ });
116
+ _this.client.on('error', function (err) {
117
+ console.error('Error in Memory server socket', err);
118
+ });
119
+ });
120
+ };
121
+ /**
122
+ * @param method specifies the function of memory server which needs to execute
123
+ * @param data an object which has data for memory server
124
+ * @param data.CompanyID
125
+ * @param data.DataSet name of dataset to refer the data in memory server
126
+ * @param data.findQuery query by data need to retrieve from memory server
127
+ * @param data.FullDoc data to add, update and delete in memeory server
128
+ * @description write to server stream of memory server and data data from memory server by specific message id
129
+ * LOV:
130
+ * method : search | execute | insertInDataSet | updateInDataSet | deleteInDataSet
131
+ */
132
+ MemoryDBConnect.prototype.Fetch = function (method, data) {
133
+ var _this = this;
134
+ return new Promise(function (resolve, reject) {
135
+ var _a;
136
+ try {
137
+ console.log('socket connected==>', (_a = _this.client) === null || _a === void 0 ? void 0 : _a.connect);
138
+ var id = crypto.randomBytes(16).toString("hex");
139
+ var message_1 = { id: id, method: method, data: data, status: "0" };
140
+ _this.messages[id] = function (res) {
141
+ if (message_1.status == "0") {
142
+ resolve([undefined, res]);
143
+ message_1.status = "1";
144
+ }
145
+ };
146
+ //timeout event binding : after 30seconds request willbe timeout
147
+ setTimeout(function () {
148
+ if (message_1.status == "0") {
149
+ console.log("memory server request timed out");
150
+ resolve([new Error("REQUEST_TIMEDOUT"), undefined]);
151
+ message_1.status = "-1";
152
+ }
153
+ }, 30000);
154
+ if (_this.client && _this.isConnected) {
155
+ _this.client.write(JSON.stringify(message_1));
156
+ }
157
+ else {
158
+ //to avoid again resolve by set timeout
159
+ message_1.status = "-1";
160
+ resolve([new Error('CLIENT_NOT_CONNECTED'), undefined]);
161
+ }
162
+ }
163
+ catch (err) {
164
+ resolve([err, undefined]);
165
+ }
166
+ });
167
+ };
168
+ /**
169
+ * @description get connection object of memory server if already created other wise create and provide.
170
+ * @returns null | socket client
171
+ */
172
+ MemoryDBConnect.prototype.Connect = function () {
173
+ return __awaiter(this, void 0, void 0, function () {
174
+ var _a, error, result;
175
+ return __generator(this, function (_b) {
176
+ switch (_b.label) {
177
+ case 0:
178
+ if (!(this.client == null || this.isConnected == false)) return [3 /*break*/, 2];
179
+ return [4 /*yield*/, this.Initialize()];
180
+ case 1:
181
+ _a = _b.sent(), error = _a[0], result = _a[1];
182
+ if (result != 'success') {
183
+ console.log('memory server socket connection not initialized');
184
+ //To Do : add code for handling this situation after getting some clarity on work.
185
+ }
186
+ _b.label = 2;
187
+ case 2:
188
+ //check client connected code : to do list by satyam
189
+ return [2 /*return*/, this.client];
190
+ }
191
+ });
192
+ });
193
+ };
194
+ return MemoryDBConnect;
195
+ }());
196
+ exports.MemoryDBConnect = MemoryDBConnect;
@@ -3,4 +3,63 @@ import { AnyObjectInterface } from "../modals/utility.modal";
3
3
  declare const GetIntegrationSettings: (db: Db, hotelCode: string) => Promise<Error | AnyObjectInterface | null>;
4
4
  declare const SyncContactWithOperaOnEmailUnsubscribe: (db: Db, email: string) => void;
5
5
  declare const OperaErrorHandler: (db: Db, ex: Error) => void;
6
- export { GetIntegrationSettings, SyncContactWithOperaOnEmailUnsubscribe, OperaErrorHandler };
6
+ /**
7
+ * This function is used to search profiles by dynamics fields in both Memory server and db.
8
+ * If data found in memory server then it search data by _id in db the return data.
9
+ *
10
+ * @param params.ModuleName Name of Module either Account | Contact.
11
+ * @param params.MappingFields fields which is used for searching
12
+ * @param params.ModuleData Data of fields
13
+ * @param params.db database objects
14
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
15
+ * @param params.SelectedFields to get only selected fields
16
+ * @param params.AllowInactive to search data without IsActive field.
17
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
18
+ * @param params.MemoryServerClient memory server client object to get data from memory server
19
+ * @param params.CompanyId to indicate searcing is to do from memory server
20
+ * @param params.DataSet to indicate searcing is to do from memory server
21
+ *
22
+ * @returns [error,ResultData]
23
+ */
24
+ declare const GetProfileDetailByDynamicFields: (params: AnyObjectInterface) => Promise<any[]>;
25
+ /**
26
+ * This function is used to update data.
27
+ * @param params.ModuleName Name of Module either Account | Contact.
28
+ * @param params.Collection Name of Collection
29
+ * @param params.Id which doucment has to update
30
+ * @param params.db database objects
31
+ * @param params.MongodbTransactionQueryOptions Mongodb query option object , it may have transaction as well.
32
+ * @param params.UpdateObj to update data in collection.
33
+
34
+ * @returns
35
+ */
36
+ declare const UpdateInitialSyncData: (params: AnyObjectInterface) => Promise<unknown>;
37
+ /**
38
+ * This function is used to stop unnecessary databse hits for checking any data available send to opera.
39
+ * this flag will be in reddis
40
+ * @param params.RedisClient reddis client
41
+ * @param params.CompanyId to create/check opera key with company id
42
+ * @param params.Mode GET/SET operation to perform on reddis
43
+ * @param params.db database objects
44
+ * @param params.isAvailable value to set in reddis
45
+
46
+ * @returns
47
+ */
48
+ declare const AddToQueueForOpera: (params: AnyObjectInterface) => Promise<any[] | undefined>;
49
+ /**
50
+ * This function is used to search data in case of contact from memory server using email
51
+ * @param params.db database objects
52
+ * @param params.ProfileType profile type account/contact
53
+ * @param params.PrimaryEmail primary email
54
+ * @param params.SecondaryEmail secondary email
55
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
56
+ * @param params.SelectedFields to get only selected fields
57
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
58
+ * @param params.MemoryServerClient memory server client object to get data from memory server
59
+ * @param params.CompanyId to indicate searcing is to do from memory server
60
+ * @param params.DataSet to indicate searcing is to do from memory server
61
+ *
62
+ * @returns
63
+ */
64
+ declare const EmailPrioritySearch: (params: AnyObjectInterface) => Promise<unknown>;
65
+ export { GetIntegrationSettings, SyncContactWithOperaOnEmailUnsubscribe, OperaErrorHandler, GetProfileDetailByDynamicFields, UpdateInitialSyncData, AddToQueueForOpera, EmailPrioritySearch };
@@ -1,9 +1,47 @@
1
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
+ };
2
38
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
40
  };
5
41
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.OperaErrorHandler = exports.SyncContactWithOperaOnEmailUnsubscribe = exports.GetIntegrationSettings = void 0;
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("..");
7
45
  var constants_1 = __importDefault(require("../constants"));
8
46
  var GetIntegrationSettings = function (db, hotelCode) {
9
47
  return new Promise(function (resolve, reject) {
@@ -106,3 +144,476 @@ var OperaErrorHandler = function (db, ex) {
106
144
  });
107
145
  };
108
146
  exports.OperaErrorHandler = OperaErrorHandler;
147
+ /**
148
+ * This function is used to search profiles by dynamics fields in both Memory server and db.
149
+ * If data found in memory server then it search data by _id in db the return data.
150
+ *
151
+ * @param params.ModuleName Name of Module either Account | Contact.
152
+ * @param params.MappingFields fields which is used for searching
153
+ * @param params.ModuleData Data of fields
154
+ * @param params.db database objects
155
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
156
+ * @param params.SelectedFields to get only selected fields
157
+ * @param params.AllowInactive to search data without IsActive field.
158
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
159
+ * @param params.MemoryServerClient memory server client object to get data from memory server
160
+ * @param params.CompanyId to indicate searcing is to do from memory server
161
+ * @param params.DataSet to indicate searcing is to do from memory server
162
+ *
163
+ * @returns [error,ResultData]
164
+ */
165
+ var GetProfileDetailByDynamicFields = function (params) {
166
+ return __awaiter(this, void 0, void 0, function () {
167
+ 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;
168
+ return __generator(this, function (_b) {
169
+ switch (_b.label) {
170
+ case 0:
171
+ mongodbTransactionQueryopts = {};
172
+ //if query options passed then setting them to pass into query.
173
+ if (params.MongodbTransactionQueryOptions) {
174
+ mongodbTransactionQueryopts = params.MongodbTransactionQueryOptions;
175
+ }
176
+ if (!params.SearchFromMemoryServer) return [3 /*break*/, 10];
177
+ searchObj = "x=>";
178
+ searchItems = new Array();
179
+ /*Preparing searching object for memory server*/
180
+ for (len = params.MappingFields.length, i = 0; i < len; i++) {
181
+ field = params.MappingFields[i];
182
+ appendSearch = "";
183
+ switch (field.UIDataType) {
184
+ case 'email':
185
+ case 'text':
186
+ //left hand part
187
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
188
+ //right hand part
189
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
190
+ break;
191
+ // case 'multilookup':
192
+ // break;
193
+ // case 'multiselect':
194
+ // break;
195
+ case 'lookup':
196
+ case 'objectid':
197
+ //left hand part
198
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
199
+ //right hand part
200
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
201
+ break;
202
+ case 'phone':
203
+ //left hand part
204
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString().toLowerCase().trim()";
205
+ //right hand part
206
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString().toLowerCase().trim()";
207
+ break;
208
+ case 'dropdown':
209
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
210
+ //right hand part
211
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
212
+ break;
213
+ default:
214
+ appendSearch += "x." + field.Name + " && x." + field.Name + ".toString()";
215
+ //right hand part
216
+ appendSearch += " === ('" + params.ModuleData[field.Name] + "').toString()";
217
+ break;
218
+ }
219
+ if (appendSearch && appendSearch.length > 0) {
220
+ searchItems.push(appendSearch);
221
+ }
222
+ }
223
+ if (!(searchItems.length > 0)) return [3 /*break*/, 8];
224
+ searchObj += searchItems.join(' && ');
225
+ //if search required on InActive data
226
+ // if (params.AllowInactive != true) {
227
+ // searchObj += " && x.IsActive== true";
228
+ // }
229
+ console.log("Search query===>", searchObj);
230
+ return [4 /*yield*/, params.MemoryServerClient.Fetch('search', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'findQuery': searchObj })];
231
+ case 1:
232
+ _a = _b.sent(), memoryServerSearchError = _a[0], dataResult = _a[1];
233
+ if (!(dataResult && dataResult.response && dataResult.response._id)) return [3 /*break*/, 6];
234
+ projection = {};
235
+ //to get only required field otherwise get all data of object by id
236
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
237
+ for (i = 0; i < params.SelectedFields.length; i++) {
238
+ projection[params.SelectedFields[i]] = 1;
239
+ }
240
+ }
241
+ else {
242
+ projection = {};
243
+ }
244
+ resultData = null;
245
+ _b.label = 2;
246
+ case 2:
247
+ _b.trys.push([2, 4, , 5]);
248
+ return [4 /*yield*/, params.db.collection(params.ModuleName).findOne({ _id: new mongodb_1.ObjectId(dataResult.response._id) }, projection, mongodbTransactionQueryopts)];
249
+ case 3:
250
+ resultData = _b.sent();
251
+ return [2 /*return*/, [null, resultData]];
252
+ case 4:
253
+ ex_1 = _b.sent();
254
+ return [2 /*return*/, [ex_1, null]];
255
+ case 5: return [3 /*break*/, 7];
256
+ case 6:
257
+ if (memoryServerSearchError) {
258
+ console.log("Error while searching in memory server", memoryServerSearchError);
259
+ return [2 /*return*/, [memoryServerSearchError, null]];
260
+ }
261
+ else {
262
+ console.log("data not found in memory server");
263
+ return [2 /*return*/, [null, null]];
264
+ }
265
+ _b.label = 7;
266
+ case 7: return [3 /*break*/, 9];
267
+ case 8:
268
+ console.log("Search object not prepared");
269
+ return [2 /*return*/, [null, null]];
270
+ case 9: return [3 /*break*/, 14];
271
+ case 10:
272
+ searchObj = {};
273
+ projection = {};
274
+ /*Preparing searching object*/
275
+ for (len = params.MappingFields.length, i = 0; i < len; i++) {
276
+ field = params.MappingFields[i];
277
+ switch (field.UIDataType) {
278
+ case 'email':
279
+ case 'text':
280
+ searchObj[field.Name] = new RegExp('^' + params.ModuleData[field.Name] + '$', 'i');
281
+ break;
282
+ // case 'multilookup':
283
+ // break;
284
+ // case 'multiselect':
285
+ // break;
286
+ case 'lookup':
287
+ case 'objectid':
288
+ searchObj[field.Name] = params.ModuleData[field.Name];
289
+ break;
290
+ case 'phone':
291
+ case 'dropdown':
292
+ searchObj[field.Name] = params.ModuleData[field.Name];
293
+ break;
294
+ default:
295
+ searchObj[field.Name] = params.ModuleData[field.Name];
296
+ break;
297
+ }
298
+ }
299
+ //If serch object build adding IsActive flag
300
+ if (!__1._utility.isEmptyObj(searchObj)) {
301
+ //if search required on InActive data
302
+ if (params.AllowInactive != true) {
303
+ searchObj["IsActive"] = true;
304
+ //to show data is InActive so adding IsActive field in SelectedFields array if not available.
305
+ if (params.SelectedFields && params.SelectedFields.length > 0 && !params.SelectedFields.find(function (x) { return x.Name == "IsActive"; })) {
306
+ params.SelectedFields.push("IsActive");
307
+ }
308
+ }
309
+ }
310
+ else {
311
+ console.log("Search object not prepared");
312
+ return [2 /*return*/, [null, null]];
313
+ }
314
+ //to get only required field otherwise get all data of object by id
315
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
316
+ for (i = 0; i < params.SelectedFields.length; i++) {
317
+ projection[params.SelectedFields[i]] = 1;
318
+ }
319
+ }
320
+ else {
321
+ projection = {};
322
+ }
323
+ resultData = null;
324
+ _b.label = 11;
325
+ case 11:
326
+ _b.trys.push([11, 13, , 14]);
327
+ return [4 /*yield*/, params.db.collection(params.ModuleName).findOne(searchObj, projection, mongodbTransactionQueryopts)];
328
+ case 12:
329
+ resultData = _b.sent();
330
+ return [2 /*return*/, [null, resultData]];
331
+ case 13:
332
+ ex_2 = _b.sent();
333
+ return [2 /*return*/, [ex_2, null]];
334
+ case 14: return [2 /*return*/];
335
+ }
336
+ });
337
+ });
338
+ };
339
+ exports.GetProfileDetailByDynamicFields = GetProfileDetailByDynamicFields;
340
+ /**
341
+ * This function is used to update data.
342
+ * @param params.ModuleName Name of Module either Account | Contact.
343
+ * @param params.Collection Name of Collection
344
+ * @param params.Id which doucment has to update
345
+ * @param params.db database objects
346
+ * @param params.MongodbTransactionQueryOptions Mongodb query option object , it may have transaction as well.
347
+ * @param params.UpdateObj to update data in collection.
348
+
349
+ * @returns
350
+ */
351
+ var UpdateInitialSyncData = function (params) { return __awaiter(void 0, void 0, void 0, function () {
352
+ var mongodbQueryOpts;
353
+ return __generator(this, function (_a) {
354
+ mongodbQueryOpts = {};
355
+ if (params.MongodbQueryOpts) {
356
+ mongodbQueryOpts = params.MongodbQueryOpts;
357
+ }
358
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
359
+ var updatedData, error_1;
360
+ return __generator(this, function (_a) {
361
+ switch (_a.label) {
362
+ case 0:
363
+ _a.trys.push([0, 3, , 4]);
364
+ if (!params) return [3 /*break*/, 2];
365
+ updatedData = null;
366
+ return [4 /*yield*/, params.db.collection(params.Collection).update({ '_id': params.Id }, { $set: params.UpdateObj }, mongodbQueryOpts)];
367
+ case 1:
368
+ updatedData = _a.sent();
369
+ if (updatedData) {
370
+ resolve([null, true]);
371
+ }
372
+ _a.label = 2;
373
+ case 2: return [3 /*break*/, 4];
374
+ case 3:
375
+ error_1 = _a.sent();
376
+ resolve([error_1, null]);
377
+ return [3 /*break*/, 4];
378
+ case 4: return [2 /*return*/];
379
+ }
380
+ });
381
+ }); })];
382
+ });
383
+ }); };
384
+ exports.UpdateInitialSyncData = UpdateInitialSyncData;
385
+ /**
386
+ * This function is used to stop unnecessary databse hits for checking any data available send to opera.
387
+ * this flag will be in reddis
388
+ * @param params.RedisClient reddis client
389
+ * @param params.CompanyId to create/check opera key with company id
390
+ * @param params.Mode GET/SET operation to perform on reddis
391
+ * @param params.db database objects
392
+ * @param params.isAvailable value to set in reddis
393
+
394
+ * @returns
395
+ */
396
+ var AddToQueueForOpera = function (params) { return __awaiter(void 0, void 0, void 0, function () {
397
+ var key, redisDataOnKey, setDataOnKey, setDataOnKey, status_1, setDataOnKey, error_2;
398
+ return __generator(this, function (_a) {
399
+ switch (_a.label) {
400
+ case 0:
401
+ _a.trys.push([0, 14, , 15]);
402
+ key = 'opera-queue:' + params.CompanyId.toString();
403
+ if (!(params.Mode === 'GET')) return [3 /*break*/, 5];
404
+ return [4 /*yield*/, params.RedisClient.hget(key, 'DataAvailable')];
405
+ case 1:
406
+ redisDataOnKey = _a.sent();
407
+ if (!(redisDataOnKey === null || redisDataOnKey === undefined)) return [3 /*break*/, 3];
408
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
409
+ case 2:
410
+ setDataOnKey = _a.sent();
411
+ // reddis returns 1 when data inserted
412
+ if (setDataOnKey === 1) {
413
+ return [2 /*return*/, [null, 'true']];
414
+ }
415
+ return [3 /*break*/, 4];
416
+ case 3: return [2 /*return*/, [null, redisDataOnKey]];
417
+ case 4: return [3 /*break*/, 13];
418
+ case 5:
419
+ if (!(params.Mode === 'SET')) return [3 /*break*/, 13];
420
+ //
421
+ console.log("Request receive to set in Opera Queue : ", params.isAvailable);
422
+ if (!(params.isAvailable === true)) return [3 /*break*/, 7];
423
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
424
+ case 6:
425
+ setDataOnKey = _a.sent();
426
+ // reddis returns 1 when data inserted and 0 when data already exists
427
+ if (setDataOnKey === 1 || setDataOnKey === 0) {
428
+ return [2 /*return*/, [null, 'true']];
429
+ }
430
+ return [3 /*break*/, 13];
431
+ case 7:
432
+ if (!(params.isAvailable === false)) return [3 /*break*/, 13];
433
+ console.log("Checking data available or not in OperaApiLogs");
434
+ return [4 /*yield*/, params.db.collection("OperaApiLogs").findOne({ 'Status': { $in: ["-1", "2", "3"] } })];
435
+ case 8:
436
+ status_1 = _a.sent();
437
+ if (!!status_1) return [3 /*break*/, 10];
438
+ console.log("Checking data available or not in OperaDataSyncRequest");
439
+ return [4 /*yield*/, params.db.collection("OperaDataSyncRequest").findOne({ 'Status': '1', 'IsActive': true })];
440
+ case 9:
441
+ status_1 = _a.sent();
442
+ _a.label = 10;
443
+ case 10:
444
+ if (!(status_1 === null || status_1 === undefined)) return [3 /*break*/, 12];
445
+ console.log("Setting Opera Queue as data not available");
446
+ return [4 /*yield*/, params.RedisClient.hset(key, { "DataAvailable": params.isAvailable })];
447
+ case 11:
448
+ setDataOnKey = _a.sent();
449
+ if (setDataOnKey === 1 || setDataOnKey === 0) {
450
+ return [2 /*return*/, [null, 'success']];
451
+ }
452
+ return [3 /*break*/, 13];
453
+ case 12:
454
+ console.log("Data available in queue");
455
+ _a.label = 13;
456
+ case 13: return [3 /*break*/, 15];
457
+ case 14:
458
+ error_2 = _a.sent();
459
+ console.error(error_2);
460
+ return [2 /*return*/, [error_2, null]];
461
+ case 15: return [2 /*return*/];
462
+ }
463
+ });
464
+ }); };
465
+ exports.AddToQueueForOpera = AddToQueueForOpera;
466
+ // email prioritysearch
467
+ /**
468
+ * This function is used to search data in case of contact from memory server using email
469
+ * @param params.db database objects
470
+ * @param params.ProfileType profile type account/contact
471
+ * @param params.PrimaryEmail primary email
472
+ * @param params.SecondaryEmail secondary email
473
+ * @param params.MongodbTransactionQueryOptions Mongodb query option, it may have transaction as well.
474
+ * @param params.SelectedFields to get only selected fields
475
+ * @param params.SearchFromMemoryServer to indicate searcing is to do from memory server
476
+ * @param params.MemoryServerClient memory server client object to get data from memory server
477
+ * @param params.CompanyId to indicate searcing is to do from memory server
478
+ * @param params.DataSet to indicate searcing is to do from memory server
479
+ *
480
+ * @returns
481
+ */
482
+ var EmailPrioritySearch = function (params) { return __awaiter(void 0, void 0, void 0, function () {
483
+ return __generator(this, function (_a) {
484
+ return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(void 0, void 0, void 0, function () {
485
+ 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;
486
+ var _b;
487
+ return __generator(this, function (_c) {
488
+ switch (_c.label) {
489
+ case 0:
490
+ _c.trys.push([0, 11, , 12]);
491
+ $project = {};
492
+ if (params.SelectedFields && params.SelectedFields.length > 0) {
493
+ for (i = 0; i < params.SelectedFields.length; i++) {
494
+ $project[params.SelectedFields[i]] = 1;
495
+ }
496
+ }
497
+ else {
498
+ //setting dummy field in projection for fast query processing
499
+ $project = {};
500
+ }
501
+ if (!(params && params.SearchFromMemoryServer === true)) return [3 /*break*/, 6];
502
+ script = "";
503
+ primaryEmail = null;
504
+ secondaryEmail = null;
505
+ if (params.PrimaryEmail && params.SecondaryEmail) {
506
+ primaryEmail = params.PrimaryEmail.toString().toLowerCase().trim();
507
+ secondaryEmail = params.SecondaryEmail.toString().toLowerCase().trim();
508
+ 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 }";
509
+ }
510
+ else if (params.PrimaryEmail) {
511
+ primaryEmail_1 = params.PrimaryEmail.toString().toLowerCase().trim();
512
+ 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 }";
513
+ }
514
+ mongodbTransactionQueryopts = {};
515
+ return [4 /*yield*/, params.MemoryServerClient.Fetch('execute', { 'CompanyID': params.CompanyId, 'DataSet': params.DataSet, 'Script': script })];
516
+ case 1:
517
+ _a = _c.sent(), memoryServerSearchError = _a[0], memoryServerSearchData = _a[1];
518
+ if (!(memoryServerSearchData && Object.keys(memoryServerSearchData.response).length !== 0)) return [3 /*break*/, 4];
519
+ id = (_b = memoryServerSearchData === null || memoryServerSearchData === void 0 ? void 0 : memoryServerSearchData.response) === null || _b === void 0 ? void 0 : _b._id;
520
+ if (!(id && id !== '')) return [3 /*break*/, 3];
521
+ convertedToObjectID = new mongodb_1.ObjectID(id);
522
+ return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': convertedToObjectID }, mongodbTransactionQueryopts)];
523
+ case 2:
524
+ result = _c.sent();
525
+ if (result) {
526
+ result.Type = memoryServerSearchData.response.type;
527
+ resolve([null, result]);
528
+ }
529
+ else {
530
+ resolve([null, 'result not found']);
531
+ }
532
+ _c.label = 3;
533
+ case 3: return [3 /*break*/, 5];
534
+ case 4:
535
+ resolve([null, 'memory server search data not found']);
536
+ _c.label = 5;
537
+ case 5: return [3 /*break*/, 10];
538
+ case 6:
539
+ mongodbTransactionQueryopts = {};
540
+ return [4 /*yield*/, params.db.collection(params.ProfileType).find({}, { projection: { Email: 1, SecondaryEmail: 1, _id: 1 } }, mongodbTransactionQueryopts).toArray()];
541
+ case 7:
542
+ allContactData = _c.sent();
543
+ console.log(allContactData);
544
+ if (!(allContactData && allContactData.length > 0)) return [3 /*break*/, 10];
545
+ objectID = null;
546
+ type = "";
547
+ result = null;
548
+ if (params.PrimaryEmail && params.SecondaryEmail) {
549
+ primaryEmail_2 = params.PrimaryEmail.toString().toLowerCase().trim();
550
+ secondaryEmail_1 = params.SecondaryEmail.toString().toLowerCase().trim();
551
+ result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
552
+ if (result) {
553
+ objectID = result._id;
554
+ type = 'primary_email';
555
+ }
556
+ else {
557
+ result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === primaryEmail_2; });
558
+ if (result) {
559
+ objectID = result._id;
560
+ type = 'primary_email';
561
+ }
562
+ else {
563
+ result = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
564
+ if (result) {
565
+ objectID = result._id;
566
+ type = 'secondary_email';
567
+ }
568
+ else {
569
+ result = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === secondaryEmail_1; });
570
+ if (result) {
571
+ objectID = result._id;
572
+ type = 'secondary_email';
573
+ }
574
+ }
575
+ }
576
+ }
577
+ }
578
+ else if (params.PrimaryEmail) {
579
+ primaryEmailrResult = allContactData.find(function (x) { var _a; return ((_a = x.Email) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
580
+ if (primaryEmailrResult) {
581
+ objectID = primaryEmailrResult._id;
582
+ type = 'primary_email';
583
+ }
584
+ else {
585
+ secondaryEmailResult = allContactData.find(function (x) { var _a; return ((_a = x.SecondaryEmail) === null || _a === void 0 ? void 0 : _a.toString().toLowerCase().trim()) === params.PrimaryEmail; });
586
+ if (secondaryEmailResult) {
587
+ type = 'primary_email';
588
+ objectID = primaryEmailrResult._id;
589
+ }
590
+ }
591
+ }
592
+ if (!(objectID === null)) return [3 /*break*/, 8];
593
+ resolve(null);
594
+ return [3 /*break*/, 10];
595
+ case 8:
596
+ if (!objectID) return [3 /*break*/, 10];
597
+ return [4 /*yield*/, params.db.collection(params.ProfileType).findOne({ '_id': objectID }, { projection: $project }, mongodbTransactionQueryopts)];
598
+ case 9:
599
+ result_1 = _c.sent();
600
+ if (result_1) {
601
+ result_1.Type = type;
602
+ resolve([null, result_1]);
603
+ }
604
+ else {
605
+ resolve([null, 'result not found']);
606
+ }
607
+ _c.label = 10;
608
+ case 10: return [3 /*break*/, 12];
609
+ case 11:
610
+ ex_3 = _c.sent();
611
+ resolve([ex_3, null]);
612
+ return [3 /*break*/, 12];
613
+ case 12: return [2 /*return*/];
614
+ }
615
+ });
616
+ }); })];
617
+ });
618
+ }); };
619
+ exports.EmailPrioritySearch = EmailPrioritySearch;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optimiser/common",
3
- "version": "1.0.244",
3
+ "version": "1.0.245",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {