@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,1009 +1,1016 @@
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.IsFutureDate = exports.ValidateData = exports.IsValidPhoneNumber = exports.SubscribeEmailForAllDomains = exports.GetEmailSubscribeStatus = exports.GetDateRangeFromOperatorValue = exports.CheckDateExistInRange = exports.AddLog = exports.UpdatePipelineMailStatus = exports.MapAccountContact = exports.CreateContact = exports.UpdateContactDetails = exports.GetSystemEmailTemplate = exports.GetContactDetailByEmail = exports.GetAccountDetailByName = exports.GenerateAutoIncrementFieldValue = exports.GetEmailwiseUnsubscribeData = exports.GetListSchema = exports.GetCompanyDetails = void 0;
43
- var mongodb_1 = require("mongodb");
44
- var constants_1 = __importDefault(require("../constants"));
45
- var moment_1 = __importDefault(require("moment"));
46
- var libphonenumber_js_1 = require("libphonenumber-js");
47
- function GetCompanyDetails(Master_DB, companyId) {
48
- return Master_DB.collection('Company').findOne({ _id: new mongodb_1.ObjectId(companyId) });
49
- }
50
- exports.GetCompanyDetails = GetCompanyDetails;
51
- function GetListSchema(db, listName) {
52
- return new Promise(function (resolve, reject) {
53
- db.collection("ListSchema").findOne({ "Name": listName }, function (errorDQL, resultDQL) {
54
- if (errorDQL)
55
- reject(errorDQL);
56
- else {
57
- if (resultDQL) {
58
- var ListSchema = resultDQL.Data;
59
- if (ListSchema) {
60
- ListSchema = ListSchema.filter(function (item) {
61
- return item.IsActive == true || item.IsActive == undefined;
62
- });
63
- resolve(ListSchema);
64
- }
65
- else {
66
- resolve([]);
67
- }
68
- }
69
- else {
70
- resolve([]);
71
- }
72
- }
73
- });
74
- });
75
- }
76
- exports.GetListSchema = GetListSchema;
77
- function GetEmailwiseUnsubscribeData(db, mailID, domainID) {
78
- return new Promise(function (resolve, reject) {
79
- db.collection("ListSchema").findOne({ "Name": "CampaignCategory" }, function (errorDQL, resultDQL) {
80
- if (errorDQL)
81
- reject(errorDQL);
82
- else {
83
- if (resultDQL) {
84
- var listSchema_1 = resultDQL.Data.filter(function (p) { return p.IsActive == true; });
85
- if (listSchema_1) {
86
- db.collection("EmailStatus").findOne({ "EmailID": new RegExp('^' + mailID.toString() + '$', "i") }, function (error, result) {
87
- if (error)
88
- reject(error);
89
- var lstData = result;
90
- var obj = [];
91
- if (result && result.Domains) {
92
- lstData.CampaignUnsubsCategory = [];
93
- var domainsData = result.Domains;
94
- for (var i = 0; i < domainsData.length; i++) {
95
- if (domainID && domainsData[i].DomainID && domainID == domainsData[i].DomainID.toString()) {
96
- lstData = domainsData[i];
97
- }
98
- else if (domainID == undefined) {
99
- if (domainsData[i].CampaignUnsubsCategory) {
100
- for (var j = 0; j < domainsData[i].CampaignUnsubsCategory.length; j++) {
101
- lstData.CampaignUnsubsCategory.push(domainsData[i].CampaignUnsubsCategory[j]);
102
- }
103
- }
104
- }
105
- }
106
- }
107
- var _loop_1 = function (i) {
108
- compaignObj = listSchema_1[i];
109
- if (lstData != null && lstData.CampaignUnsubsCategory && lstData.CampaignUnsubsCategory.length > 0 && lstData.CampaignUnsubsCategory.filter(function (p) { return p == listSchema_1[i].Key; }).length > 0) {
110
- obj.push({ 'Key': compaignObj.Key, 'Value': compaignObj.Value, 'DomainID': compaignObj.DomainID, 'checked': true, 'HideForUser': compaignObj.HideForUser });
111
- }
112
- else {
113
- obj.push({ 'Key': compaignObj.Key, 'Value': compaignObj.Value, 'DomainID': compaignObj.DomainID, 'checked': false, 'HideForUser': compaignObj.HideForUser });
114
- }
115
- };
116
- var compaignObj;
117
- for (var i = 0; i < listSchema_1.length; i++) {
118
- _loop_1(i);
119
- }
120
- resolve(obj);
121
- });
122
- }
123
- else {
124
- resolve([]);
125
- }
126
- }
127
- else {
128
- resolve([]);
129
- }
130
- }
131
- });
132
- });
133
- }
134
- exports.GetEmailwiseUnsubscribeData = GetEmailwiseUnsubscribeData;
135
- function GenerateAutoIncrementFieldValue(db, autoIncrementID) {
136
- var _this = this;
137
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
138
- var sequenceDocument, val, j, item, num, ex_1;
139
- return __generator(this, function (_a) {
140
- switch (_a.label) {
141
- case 0:
142
- _a.trys.push([0, 2, , 3]);
143
- return [4 /*yield*/, db.collection('AutoIncrement').findOneAndUpdate({ _id: autoIncrementID }, { $inc: { SequenceValue: 1 } })];
144
- case 1:
145
- sequenceDocument = _a.sent();
146
- val = "";
147
- for (j = 0; j < sequenceDocument.value.Formats.length; j++) {
148
- item = sequenceDocument.value.Formats[j];
149
- if (item.Type == "Constant") {
150
- val += item.Value;
151
- }
152
- else if (item.Type == "AutoIncrement") {
153
- num = sequenceDocument.value.SequenceValue.toString();
154
- if (item.MinimumLength && item.MinimumLength > 0) {
155
- num = ("0000000000").substring(0, item.MinimumLength - num.length) + num;
156
- }
157
- val += num;
158
- }
159
- }
160
- resolve(val);
161
- return [3 /*break*/, 3];
162
- case 2:
163
- ex_1 = _a.sent();
164
- resolve(null);
165
- return [3 /*break*/, 3];
166
- case 3: return [2 /*return*/];
167
- }
168
- });
169
- }); });
170
- }
171
- exports.GenerateAutoIncrementFieldValue = GenerateAutoIncrementFieldValue;
172
- function GetAccountDetailByName(db, accountName) {
173
- return new Promise(function (resolve, reject) {
174
- db.collection("Account").findOne({ Name: new RegExp('^' + accountName + '$', "i"), "IsActive": true }, { projection: { "_id": 1 } }, function (error, result) {
175
- if (error) {
176
- resolve(null);
177
- }
178
- if (result) {
179
- resolve(result);
180
- }
181
- else {
182
- resolve(null);
183
- }
184
- });
185
- });
186
- }
187
- exports.GetAccountDetailByName = GetAccountDetailByName;
188
- function GetContactDetailByEmail(db, contactEmail) {
189
- return new Promise(function (resolve, reject) {
190
- db.collection("Contact").aggregate([
191
- { $match: { "Email": new RegExp('^' + contactEmail + '$', "i"), "IsActive": true } },
192
- { $project: { "_id": 1, "AccountID": 1 } },
193
- {
194
- $lookup: {
195
- from: "Account",
196
- localField: "AccountID",
197
- foreignField: "_id",
198
- as: "Account"
199
- }
200
- },
201
- { $project: { "_id": 1, "AccountID": 1, "AccountName": { $arrayElemAt: ["$Account.Name", 0] } } }
202
- ]).toArray(function (errorDQL, resultDQL) {
203
- if (errorDQL) {
204
- resolve(null);
205
- }
206
- else if (resultDQL && resultDQL.length > 0) {
207
- resolve(resultDQL[0]);
208
- }
209
- else {
210
- resolve(null);
211
- }
212
- });
213
- });
214
- }
215
- exports.GetContactDetailByEmail = GetContactDetailByEmail;
216
- function GetSystemEmailTemplate(db, TemplateIDArray) {
217
- return new Promise(function (resolve, reject) {
218
- db.collection("SystemEmailTemplate").find({ "_id": { $in: TemplateIDArray } }).toArray(function (errorDQL, resultDQL) {
219
- if (errorDQL) {
220
- resolve(null);
221
- }
222
- else if (resultDQL && resultDQL.length > 0) {
223
- resolve(resultDQL);
224
- }
225
- else {
226
- resolve(null);
227
- }
228
- });
229
- });
230
- }
231
- exports.GetSystemEmailTemplate = GetSystemEmailTemplate;
232
- function UpdateContactDetails(db, contactData) {
233
- db.collection("Contact").updateOne({ "_id": contactData._id }, {
234
- $set: {
235
- "FirstName": contactData.FirstName, "LastName": contactData.LastName,
236
- "PrimaryEmailCategory": contactData.PrimaryEmailCategory, "PhoneCountryCode": contactData.PhoneCountryCode,
237
- "Phone": contactData.Phone, "JobTitle": contactData.JobTitle,
238
- "ModifiedDate": new Date(), "ModifiedBy": contactData.OwnerID
239
- }
240
- }, function (error, result) {
241
- if (error) {
242
- }
243
- if (result) {
244
- }
245
- });
246
- }
247
- exports.UpdateContactDetails = UpdateContactDetails;
248
- // function CreateContact(db: Db, contactData: AnyObjectInterface): Promise<null | AnyObjectInterface> {
249
- // return new Promise(function (resolve, reject) {
250
- // let contactObj = {
251
- // "Salutation": null,
252
- // "OwnerID": contactData.OwnerID,
253
- // "FirstName": contactData.FirstName,
254
- // "LastName": contactData.LastName,
255
- // "ReportsTo": null,
256
- // "JobTitle": contactData.JobTitle,
257
- // "Department": null,
258
- // "Email": contactData.Email,
259
- // "PrimaryEmailCategory": contactData.PrimaryEmailCategory,
260
- // "PhoneCountryCode": contactData.PhoneCountryCode,
261
- // "Phone": contactData.Phone,
262
- // "Mobile": null,
263
- // "Birthdate": null,
264
- // "LinkedIn": null,
265
- // "AccountID": null,
266
- // "Address": null,
267
- // "City": null,
268
- // "State": null,
269
- // "Country": null,
270
- // "PostalCode": null,
271
- // "SearchAddress": {
272
- // "lat": "",
273
- // "lng": ""
274
- // },
275
- // "CreatedBy": contactData.OwnerID,
276
- // "CreatedDate": new Date(),
277
- // "IsActive": true,
278
- // "RelationID": null
279
- // }
280
- // db.collection("Contact").insertOne(contactObj, function (error, result) {
281
- // if (error) {
282
- // resolve(null);
283
- // }
284
- // if (result) {
285
- // resolve(result);
286
- // } else {
287
- // resolve(null);
288
- // }
289
- // });
290
- // });
291
- // }
292
- function CreateContact(db, contactData) {
293
- return new Promise(function (resolve, reject) {
294
- return __awaiter(this, void 0, void 0, function () {
295
- var contactObj;
296
- return __generator(this, function (_a) {
297
- contactObj = {
298
- "Salutation": contactData.Salutation,
299
- "OwnerID": contactData.OwnerID,
300
- "FirstName": contactData.FirstName,
301
- "LastName": contactData.LastName,
302
- "ReportsTo": null,
303
- "JobTitle": contactData.JobTitle,
304
- "Department": null,
305
- "Email": contactData.Email,
306
- "PrimaryEmailCategory": contactData.PrimaryEmailCategory,
307
- "PhoneCountryCode": contactData.PhoneCountryCode,
308
- "Phone": contactData.Phone,
309
- "Mobile": null,
310
- "Birthdate": null,
311
- "LinkedIn": null,
312
- "AccountID": null,
313
- "Address": null,
314
- "City": null,
315
- "State": null,
316
- "Country": null,
317
- "PostalCode": null,
318
- "SearchAddress": {
319
- "lat": "",
320
- "lng": ""
321
- },
322
- "CreatedBy": contactData.OwnerID,
323
- "CreatedDate": new Date(),
324
- "IsActive": true,
325
- "RelationID": null,
326
- "OwnerID_LookupData": contactData.OwnerID_LookupData
327
- };
328
- // let validationMsg = await ValidateData(db,contactObj,"Contact");
329
- // if(validationMsg == 'success'){
330
- db.collection("Contact").insertOne(contactObj, function (error, result) {
331
- if (error) {
332
- resolve([error, null]);
333
- }
334
- if (result) {
335
- resolve([null, result]);
336
- }
337
- });
338
- return [2 /*return*/];
339
- });
340
- });
341
- });
342
- }
343
- exports.CreateContact = CreateContact;
344
- function MapAccountContact(db, dataObj) {
345
- var _a;
346
- var relationObj = (_a = {
347
- "AccountID": dataObj.AccountID,
348
- "Roles": null,
349
- "Branch": null,
350
- "IsInternal": false,
351
- "IsWorking": true,
352
- "ContactID": dataObj.ContactID,
353
- "OwnerID": dataObj.OwnerID,
354
- "CreatedBy": dataObj.OwnerID,
355
- "CreatedDate": new Date()
356
- },
357
- _a["AccountID" + constants_1.default.LookupAlias] = dataObj["AccountID" + constants_1.default.LookupAlias],
358
- _a["ContactID" + constants_1.default.LookupAlias] = dataObj["ContactID" + constants_1.default.LookupAlias],
359
- _a["IsActive"] = true,
360
- _a);
361
- db.collection('AccountContactRelation').findOne({ AccountID: dataObj.AccountID, ContactID: dataObj.ContactID, IsActive: true }, { projection: { "_id": 1 } }, function (errorSearch, resultSearch) {
362
- if (errorSearch) {
363
- return;
364
- }
365
- if (!resultSearch) {
366
- db.collection("AccountContactRelation").insertOne(relationObj, function (error, result) {
367
- if (error) {
368
- return;
369
- }
370
- });
371
- }
372
- });
373
- }
374
- exports.MapAccountContact = MapAccountContact;
375
- function UpdatePipelineMailStatus(db, pipelineID, mailStatus) {
376
- db.collection("Pipeline").updateOne({ "_id": pipelineID }, {
377
- $set: {
378
- "MailStatus": mailStatus
379
- }
380
- }, function (error, result) {
381
- if (error) {
382
- }
383
- if (result) {
384
- }
385
- });
386
- }
387
- exports.UpdatePipelineMailStatus = UpdatePipelineMailStatus;
388
- function AddLog(db, data) {
389
- db.collection("ExternalApiLogs").insertOne(data, function (err1, res1) {
390
- if (err1) {
391
- console.log("Error in ExternalApiLogs writing");
392
- }
393
- });
394
- }
395
- exports.AddLog = AddLog;
396
- /**
397
- * Returns object - To and From date from given operator value
398
- *
399
- * @param {string} operator today/yesterday/tomorrow
400
- * @return { dates } object container start and end date
401
- */
402
- var GetDateRangeFromOperatorValue = function (operator, fiscalMonth, fiscalFrom) {
403
- if (operator === void 0) { operator = ""; }
404
- var startDate = null, endDate = null;
405
- var currentDateFormat = "DD-MMM-YYYY";
406
- var requiredDateFormat = currentDateFormat;
407
- var momentObj = moment_1.default();
408
- var getFiscalMonthIndex = moment_1.default.monthsShort().findIndex(function (month) { return month === fiscalMonth; });
409
- // GET FISCAL MONTH INDEX
410
- // if (operator.includes("Fiscal")) {
411
- if (operator.toLowerCase().includes("fiscal") || ["Year to Date", "year-to-date"].includes(operator)) {
412
- if (fiscalFrom === "End") {
413
- fiscalMonth = momentObj.clone().month(fiscalMonth).add(1, "months").format('MMM'); // Modify FiscalMonth in FiscalFrom - End
414
- }
415
- // SET FISCAL QUARTER
416
- var firstFisQuarterStart = momentObj.clone().month(fiscalMonth).startOf('month').quarter(1).format(requiredDateFormat);
417
- var secondFisQuarterStart = moment_1.default(firstFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(2).format(requiredDateFormat);
418
- var thirdFisQuarterStart = moment_1.default(secondFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(3).format(requiredDateFormat);
419
- var fourthFisQuarterStart = moment_1.default(thirdFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(4).format(requiredDateFormat);
420
- var firstFisQuarterEnd = moment_1.default(firstFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
421
- var secondFisQuarterEnd = moment_1.default(secondFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
422
- var thirdFisQuarterEnd = moment_1.default(thirdFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
423
- var fourthFisQuarterEnd = moment_1.default(fourthFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
424
- var currentDate = moment_1.default(moment_1.default().format('DD-MM-YYYY'), "DD/MM/YYYY");
425
- var arrIndex = ["first", "second", "third", "fourth"];
426
- for (var i = 0; i < arrIndex.length; i++) {
427
- if (CheckDateExistInRange(currentDate, eval(arrIndex[i] + "FisQuarterStart"), eval(arrIndex[i] + "FisQuarterEnd"))) {
428
- startDate = eval(arrIndex[i] + "FisQuarterStart");
429
- endDate = eval(arrIndex[i] + "FisQuarterEnd");
430
- break;
431
- }
432
- }
433
- ;
434
- }
435
- switch (operator) {
436
- case "Yesterday":
437
- case "yesterday":
438
- startDate = momentObj.clone().subtract(1, "days").format(requiredDateFormat);
439
- endDate = momentObj.clone().subtract(1, "days").format(requiredDateFormat);
440
- break;
441
- case "Today":
442
- case "today":
443
- startDate = momentObj.clone().format(requiredDateFormat);
444
- endDate = momentObj.clone().format(requiredDateFormat);
445
- break;
446
- case "Tomorrow":
447
- case "tomorrow":
448
- startDate = momentObj.clone().add(1, "days").format(requiredDateFormat);
449
- endDate = momentObj.clone().add(1, "days").format(requiredDateFormat);
450
- break;
451
- case "Last 7 Days":
452
- case "last-7-days":
453
- startDate = momentObj.clone().subtract(6, "days").format(requiredDateFormat);
454
- endDate = momentObj.clone().format(requiredDateFormat);
455
- break;
456
- case "Last 30 Days":
457
- case "last-30-days":
458
- startDate = momentObj.clone().subtract(29, "days").format(requiredDateFormat);
459
- endDate = momentObj.clone().format(requiredDateFormat);
460
- break;
461
- case "Last 60 Days":
462
- case "last-60-days":
463
- startDate = momentObj.clone().subtract(59, "days").format(requiredDateFormat);
464
- endDate = momentObj.clone().format(requiredDateFormat);
465
- break;
466
- case "Last 90 Days":
467
- case "last-90-days":
468
- startDate = momentObj.clone().subtract(89, "days").format(requiredDateFormat);
469
- endDate = momentObj.clone().format(requiredDateFormat);
470
- break;
471
- case "Last 120 Days":
472
- case "last-120-days":
473
- startDate = momentObj.clone().subtract(119, "days").format(requiredDateFormat);
474
- endDate = momentObj.clone().format(requiredDateFormat);
475
- break;
476
- case "Next 7 Days":
477
- case "next-7-days":
478
- startDate = momentObj.clone().format(requiredDateFormat);
479
- endDate = momentObj.clone().add(6, "days").format(requiredDateFormat);
480
- break;
481
- case "Next 30 Days":
482
- case "next-30-days":
483
- startDate = momentObj.clone().format(requiredDateFormat);
484
- endDate = momentObj.clone().add(29, "days").format(requiredDateFormat);
485
- break;
486
- case "Next 60 Days":
487
- case "next-60-days":
488
- startDate = momentObj.clone().format(requiredDateFormat);
489
- endDate = momentObj.clone().add(59, "days").format(requiredDateFormat);
490
- break;
491
- case "Next 90 Days":
492
- case "next-90-days":
493
- startDate = momentObj.clone().format(requiredDateFormat);
494
- endDate = momentObj.clone().add(89, "days").format(requiredDateFormat);
495
- break;
496
- case "Next 120 Days":
497
- case "next-120-days":
498
- startDate = momentObj.clone().format(requiredDateFormat);
499
- endDate = momentObj.clone().add(119, "days").format(requiredDateFormat);
500
- break;
501
- case "Last Week":
502
- case "last-week":
503
- startDate = momentObj.clone().subtract(1, "weeks").startOf('isoWeek').format(requiredDateFormat);
504
- endDate = momentObj.clone().subtract(1, "weeks").endOf('isoWeek').format(requiredDateFormat);
505
- break;
506
- case "This Week":
507
- case "this-week":
508
- startDate = momentObj.clone().startOf('isoWeek').format(requiredDateFormat);
509
- endDate = momentObj.clone().endOf('isoWeek').format(requiredDateFormat);
510
- break;
511
- case "Next Week":
512
- case "next-week":
513
- startDate = momentObj.clone().add(1, "weeks").startOf('isoWeek').format(requiredDateFormat);
514
- endDate = momentObj.clone().add(1, "weeks").endOf('isoWeek').format(requiredDateFormat);
515
- break;
516
- case "Last Month":
517
- case "last-month":
518
- startDate = momentObj.clone().subtract(1, "months").startOf('month').format(requiredDateFormat);
519
- endDate = momentObj.clone().subtract(1, "months").endOf('month').format(requiredDateFormat);
520
- break;
521
- case "This Month":
522
- case "this-month":
523
- startDate = momentObj.clone().startOf('month').format(requiredDateFormat);
524
- endDate = momentObj.clone().endOf('month').format(requiredDateFormat);
525
- break;
526
- case "Next Month":
527
- case "next-month":
528
- startDate = momentObj.clone().add(1, "months").startOf('month').format(requiredDateFormat);
529
- endDate = momentObj.clone().add(1, "months").endOf('month').format(requiredDateFormat);
530
- break;
531
- case "Last Quarter":
532
- case "last-quarter":
533
- startDate = momentObj.clone().subtract(1, "quarters").startOf('quarter').format(requiredDateFormat);
534
- endDate = momentObj.clone().subtract(1, "quarters").endOf('quarter').format(requiredDateFormat);
535
- break;
536
- case "This Quarter":
537
- case "this-quarter":
538
- startDate = momentObj.clone().startOf('quarter').format(requiredDateFormat);
539
- endDate = momentObj.clone().endOf('quarter').format(requiredDateFormat);
540
- break;
541
- case "Next Quarter":
542
- case "next-quarter":
543
- startDate = momentObj.clone().add(1, "quarters").startOf('quarter').format(requiredDateFormat);
544
- endDate = momentObj.clone().add(1, "quarters").endOf('quarter').format(requiredDateFormat);
545
- break;
546
- case "Last Fiscal Quarter":
547
- case "last-fiscal-quarter":
548
- startDate = moment_1.default(startDate, currentDateFormat).clone().subtract(3, "months").startOf('month').format(requiredDateFormat);
549
- endDate = moment_1.default(startDate, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
550
- break;
551
- case "This Fiscal Quarter":
552
- case "this-fiscal-quarter":
553
- startDate = startDate;
554
- endDate = endDate;
555
- break;
556
- case "Next Fiscal Quarter":
557
- case "next-fiscal-quarter":
558
- startDate = moment_1.default(startDate, currentDateFormat).clone().add(3, "months").startOf('month').format(requiredDateFormat);
559
- endDate = moment_1.default(startDate, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
560
- break;
561
- case "Last Year":
562
- case "last-year":
563
- startDate = momentObj.clone().subtract(1, "years").startOf('year').format(requiredDateFormat);
564
- endDate = momentObj.clone().subtract(1, "years").endOf('year').format(requiredDateFormat);
565
- break;
566
- case "This Year":
567
- case "this-year":
568
- startDate = momentObj.clone().startOf('year').format(requiredDateFormat);
569
- endDate = momentObj.clone().endOf('year').format(requiredDateFormat);
570
- break;
571
- case "Next Year":
572
- case "next-year":
573
- startDate = momentObj.clone().add(1, "years").startOf('year').format(requiredDateFormat);
574
- endDate = momentObj.clone().add(1, "years").endOf('year').format(requiredDateFormat);
575
- break;
576
- case "Last Fiscal Year":
577
- case "last-fiscal-year":
578
- if (fiscalFrom === "Start") {
579
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
580
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
581
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
582
- }
583
- else {
584
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(24, "months").startOf('month').format(requiredDateFormat);
585
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
586
- }
587
- }
588
- else {
589
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
590
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(1, "year").startOf('month').format(requiredDateFormat);
591
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
592
- }
593
- else {
594
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(2, "year").startOf('month').format(requiredDateFormat);
595
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
596
- }
597
- }
598
- break;
599
- case "This Fiscal Year":
600
- case "this-fiscal-year":
601
- if (fiscalFrom === "Start") {
602
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
603
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
604
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
605
- }
606
- else {
607
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
608
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
609
- }
610
- }
611
- else {
612
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
613
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
614
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
615
- }
616
- else {
617
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
618
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
619
- }
620
- }
621
- break;
622
- case "Next Fiscal Year":
623
- case "next-fiscal-year":
624
- if (fiscalFrom === "Start") {
625
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
626
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(1, "years").startOf('month').format(requiredDateFormat);
627
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
628
- }
629
- else {
630
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
631
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
632
- }
633
- }
634
- else {
635
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
636
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(1, "years").startOf('month').format(requiredDateFormat);
637
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
638
- }
639
- else {
640
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
641
- endDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
642
- }
643
- }
644
- break;
645
- case "Current Calendar Year":
646
- case "current-calendar-year":
647
- startDate = momentObj.clone().startOf('year').format(requiredDateFormat);
648
- endDate = momentObj.clone().endOf('year').format(requiredDateFormat);
649
- break;
650
- case "Previous Calendar Year":
651
- case "previous-calendar-year":
652
- startDate = momentObj.clone().subtract(1, "years").startOf('year').format(requiredDateFormat);
653
- endDate = momentObj.clone().subtract(1, "years").endOf('year').format(requiredDateFormat);
654
- break;
655
- case "Next Calendar Year":
656
- case "next-calendar-year":
657
- startDate = momentObj.clone().add(1, "years").startOf('year').format(requiredDateFormat);
658
- endDate = momentObj.clone().add(1, "years").endOf('year').format(requiredDateFormat);
659
- break;
660
- case "Year to Date":
661
- case "year-to-date":
662
- endDate = momentObj.clone().format(requiredDateFormat);
663
- // Commented Below Hanisha's Code - Implemented following as per QPC-6370
664
- // if (parseInt(momentObj.format('M')) > 3) {
665
- // startDate = momentObj.clone().startOf('month').month("Apr").format(requiredDateFormat);
666
- // } else {
667
- // startDate = momentObj.clone().subtract(1, "years").startOf('month').month("Apr").format(requiredDateFormat);
668
- // }
669
- if (fiscalFrom === "Start") {
670
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
671
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
672
- }
673
- else {
674
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
675
- }
676
- }
677
- else {
678
- if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
679
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
680
- }
681
- else {
682
- startDate = moment_1.default(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
683
- }
684
- }
685
- break;
686
- default:
687
- break;
688
- }
689
- return {
690
- startDate: startDate, endDate: endDate
691
- };
692
- };
693
- exports.GetDateRangeFromOperatorValue = GetDateRangeFromOperatorValue;
694
- /**
695
- * Returns boolean - Check date exist in Given Date Range(Quarter)
696
- *
697
- * @param {string} date date to compare
698
- * @param {string} startDate format DD-MMM-YYYY
699
- * @param {string} endDate format DD-MMM-YYYY
700
- * @return { boolean } true/false
701
- */
702
- var CheckDateExistInRange = function (date, startDate, endDate) {
703
- var currentDateFormat = "DD-MMM-YYYY";
704
- var compareDate = moment_1.default(moment_1.default(date).format("DD-MM-YYYY"), "DD/MM/YYYY");
705
- var startCompareDate = moment_1.default(moment_1.default(startDate, currentDateFormat).format('DD-MM-YYYY'), "DD/MM/YYYY");
706
- var endCompareDate = moment_1.default(moment_1.default(endDate, currentDateFormat).format('DD-MM-YYYY'), "DD/MM/YYYY");
707
- return compareDate.isBetween(startCompareDate, endCompareDate) || compareDate.isSame(startCompareDate) || compareDate.isSame(endCompareDate);
708
- };
709
- exports.CheckDateExistInRange = CheckDateExistInRange;
710
- /**
711
- * To get the email subscribe status. By default it take email as subscribed
712
- * and check if email is unsusbscribed for all categories of all domains then it give it as unsubscribe.
713
- * @param {db} database object
714
- * @param {email} string
715
- *
716
- * @param retunrs true|false|error for subscribe or unsubscribe.
717
- */
718
- var GetEmailSubscribeStatus = function (db, email) {
719
- var _this = this;
720
- return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
721
- var emailSubscribeStatus, emailUnsubcData, error_1;
722
- return __generator(this, function (_a) {
723
- switch (_a.label) {
724
- case 0:
725
- _a.trys.push([0, 2, , 3]);
726
- emailSubscribeStatus = true;
727
- return [4 /*yield*/, GetEmailwiseUnsubscribeData(db, email)];
728
- case 1:
729
- emailUnsubcData = _a.sent();
730
- if (emailUnsubcData && emailUnsubcData.length > 0) {
731
- if (emailUnsubcData.filter(function (x) { return x.checked != null && x.checked != undefined && x.checked; }).length == emailUnsubcData.length)
732
- emailSubscribeStatus = false;
733
- }
734
- resolve(emailSubscribeStatus);
735
- return [3 /*break*/, 3];
736
- case 2:
737
- error_1 = _a.sent();
738
- reject(error_1);
739
- return [3 /*break*/, 3];
740
- case 3: return [2 /*return*/];
741
- }
742
- });
743
- }); });
744
- };
745
- exports.GetEmailSubscribeStatus = GetEmailSubscribeStatus;
746
- /**
747
- * To subscribe or unsubscribe email id for all domains
748
- * @param {db} database object
749
- * @param {email} string
750
- * @param {isSubscribe} boolean
751
- * @param {companyID} mongodb object id, comany id of email
752
- * @param {comment} string , to add comment
753
- * @param {mongodbQueryOptions} object, params to pass on db queries
754
- * @returns resolve success | error object
755
- */
756
- var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, comment, mongodbQueryOptions) {
757
- if (comment === void 0) { comment = ""; }
758
- if (mongodbQueryOptions === void 0) { mongodbQueryOptions = null; }
759
- return new Promise(function (resolve, reject) {
760
- return __awaiter(this, void 0, void 0, function () {
761
- var mongodbQueryOpts, marketingSettingDetail, marketingCategoryKeys, domainIds_1, domainDetail, existEmailSub, isRequireUpdate, marketingCategoryData, _loop_2, i, error_2;
762
- return __generator(this, function (_a) {
763
- switch (_a.label) {
764
- case 0:
765
- _a.trys.push([0, 7, , 8]);
766
- mongodbQueryOpts = {};
767
- if (mongodbQueryOptions) {
768
- mongodbQueryOpts = mongodbQueryOptions;
769
- }
770
- if (!email) return [3 /*break*/, 6];
771
- return [4 /*yield*/, db.collection('Company').findOne({ IsActive: true }, { projection: { "Setting.MarketingSetting": 1 } }, mongodbQueryOpts)];
772
- case 1:
773
- marketingSettingDetail = _a.sent();
774
- marketingCategoryKeys = [], domainIds_1 = [];
775
- if (marketingSettingDetail && marketingSettingDetail.Setting
776
- && marketingSettingDetail.Setting
777
- && marketingSettingDetail.Setting.MarketingSetting
778
- && marketingSettingDetail.Setting.MarketingSetting.Domains
779
- && marketingSettingDetail.Setting.MarketingSetting.Domains.length > 0) {
780
- domainDetail = marketingSettingDetail.Setting.MarketingSetting.Domains.filter(function (x) { return x.IsActive == true; });
781
- if (domainDetail && domainDetail.length > 0) {
782
- domainIds_1 = domainDetail.map(function (x) { return x._id; });
783
- }
784
- }
785
- existEmailSub = {}, isRequireUpdate = false;
786
- if (!(domainIds_1 && domainIds_1.length > 0)) return [3 /*break*/, 4];
787
- return [4 /*yield*/, db.collection('EmailStatus').findOne({ 'EmailID': new RegExp("^" + email + "$", "i"), CompanyID: companyID }, { projection: { "Domains": 1 } }, mongodbQueryOpts)];
788
- case 2:
789
- existEmailSub = _a.sent();
790
- isRequireUpdate = true;
791
- if (!existEmailSub) {
792
- existEmailSub = {
793
- CompanyID: companyID,
794
- EmailID: email,
795
- Domains: []
796
- };
797
- }
798
- 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)];
799
- case 3:
800
- marketingCategoryData = _a.sent();
801
- _loop_2 = function (i) {
802
- marketingCategoryKeys = [];
803
- if (marketingCategoryData && marketingCategoryData.Data)
804
- marketingCategoryKeys = marketingCategoryData.Data.filter(function (x) { return x.IsActive == true && x.DomainID && x.DomainID.toString() == domainIds_1[i].toString(); }).map(function (x) { return x.Key; });
805
- var domainObj = null;
806
- var domainExist = false;
807
- if (existEmailSub && existEmailSub.Domains && existEmailSub.Domains.length > 0) {
808
- domainObj = existEmailSub.Domains.find(function (x) { return x.DomainID.toString() == domainIds_1[i].toString(); });
809
- if (domainObj) {
810
- domainExist = true;
811
- }
812
- else {
813
- domainExist = false;
814
- }
815
- }
816
- //if Domains array not available on existing email status data then adding an empty array and also checking domains property should of Array type
817
- if (existEmailSub && !existEmailSub.Domains) {
818
- existEmailSub.Domains = [];
819
- }
820
- if (domainExist == false) {
821
- domainObj = {
822
- "DomainID": domainIds_1[i],
823
- "Comment": comment,
824
- "CampaignID": null,
825
- "CampaignSubsCategory": [],
826
- "CampaignUnsubsCategory": [],
827
- "IsSubscribe": true
828
- };
829
- }
830
- if (isSubscribe == true) {
831
- if (domainExist == true) {
832
- // existEmailSub.Domains[i].CampaignSubsCategory = marketingCategoryKeys;
833
- // existEmailSub.Domains[i].CampaignUnsubsCategory = [];
834
- domainObj.CampaignSubsCategory = marketingCategoryKeys;
835
- domainObj.CampaignUnsubsCategory = [];
836
- domainObj.IsSubscribe = true;
837
- }
838
- else if (domainExist == false && domainObj) {
839
- domainObj.CampaignSubsCategory = marketingCategoryKeys;
840
- //existEmailSub.Domains[i] = domainObj;
841
- existEmailSub.Domains.push(domainObj);
842
- }
843
- }
844
- else {
845
- if (domainExist == true) {
846
- // existEmailSub.Domains[i].CampaignSubsCategory = [];
847
- // existEmailSub.Domains[i].CampaignUnsubsCategory = marketingCategoryKeys;
848
- domainObj.CampaignSubsCategory = [];
849
- domainObj.CampaignUnsubsCategory = marketingCategoryKeys;
850
- }
851
- else if (domainExist == false && domainObj) {
852
- domainObj.CampaignUnsubsCategory = marketingCategoryKeys;
853
- //existEmailSub.Domains[i] = domainObj;
854
- existEmailSub.Domains.push(domainObj);
855
- }
856
- domainObj.IsSubscribe = false;
857
- }
858
- };
859
- for (i = 0; i < domainIds_1.length; i++) {
860
- _loop_2(i);
861
- }
862
- _a.label = 4;
863
- case 4:
864
- mongodbQueryOpts["upsert"] = true;
865
- if (!isRequireUpdate) return [3 /*break*/, 6];
866
- //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
867
- return [4 /*yield*/, db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, mongodbQueryOpts)];
868
- case 5:
869
- //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
870
- _a.sent();
871
- _a.label = 6;
872
- case 6:
873
- resolve("success");
874
- return [3 /*break*/, 8];
875
- case 7:
876
- error_2 = _a.sent();
877
- //console.log("SubscribeEmailForAllDomains error");
878
- if (error_2 instanceof Error) {
879
- error_2.name += "- Error while SubscribeEmailForAllDomains Function";
880
- }
881
- //OperaUtility.OperaErrorHandler(db, error);
882
- reject(error_2);
883
- return [3 /*break*/, 8];
884
- case 8: return [2 /*return*/];
885
- }
886
- });
887
- });
888
- });
889
- };
890
- exports.SubscribeEmailForAllDomains = SubscribeEmailForAllDomains;
891
- /**
892
- * checking phone number is valid and has dialing code
893
- * if it has dialing code then get country code, get its optimiser country phone code
894
- * if it doesn't has dialing code then try to pasrse it with countryCode
895
- * if phone is valid then use it other wise ignore that no.
896
- * @param {phoneNumber} string, phone no with or without dialing code
897
- * @param {countryCode} string, ISO country code
898
- * @returns {
899
- IsValid: boolean, //phone is valid or not
900
- CountryCode?: string, //phone country code
901
- PhoneCallingCode?: CountryCallingCode, //phone country calling code
902
- PhoneNumberParsed?: NationalNumber, //phone no local to the country, without country calling code and only digits
903
- Error: Error
904
- }
905
- */
906
- var IsValidPhoneNumber = function (phoneNumber, countryCode) {
907
- var result = {}; //{ IsValid: false, CountryCode: string, PhoneCallingCode: null, PhoneNumberParsed: null };
908
- result.IsValid = false;
909
- result.CountryCode = result.PhoneCallingCode = result.PhoneNumberParsed = "";
910
- try {
911
- var phoneNumberParsed = null;
912
- try {
913
- phoneNumberParsed = libphonenumber_js_1.parsePhoneNumber(phoneNumber);
914
- }
915
- catch (error) {
916
- //console.log("Error while parsing phone number ===>", error);
917
- console.log("Error while parsing phone number");
918
- }
919
- if (phoneNumberParsed) {
920
- if (phoneNumberParsed.isValid()) {
921
- result.IsValid = true;
922
- result.CountryCode = phoneNumberParsed.country;
923
- result.PhoneCallingCode = phoneNumberParsed.countryCallingCode;
924
- result.PhoneNumberParsed = phoneNumberParsed.nationalNumber;
925
- }
926
- }
927
- if (result.IsValid == false) {
928
- //try {
929
- var phoneNumberParsedWithAddressCountry = null;
930
- try {
931
- phoneNumberParsedWithAddressCountry = libphonenumber_js_1.parsePhoneNumber(phoneNumber, countryCode);
932
- }
933
- catch (error) {
934
- //console.log("Error while parsing phone number with address country code ===>", error);
935
- console.log("Error while parsing phone number with address country code ===>");
936
- }
937
- if (phoneNumberParsedWithAddressCountry) {
938
- if (phoneNumberParsedWithAddressCountry.isValid()) {
939
- result.IsValid = true;
940
- result.CountryCode = phoneNumberParsedWithAddressCountry.country;
941
- result.PhoneCallingCode = phoneNumberParsedWithAddressCountry.countryCallingCode;
942
- result.PhoneNumberParsed = phoneNumberParsedWithAddressCountry.nationalNumber;
943
- }
944
- }
945
- }
946
- //just as final check confirmation for phone no shouldn't have any character other than digits.
947
- if (result.PhoneNumberParsed) {
948
- result.PhoneNumberParsed = libphonenumber_js_1.parseDigits(result.PhoneNumberParsed.toString());
949
- }
950
- //console.dir(phoneNumberParsed);
951
- }
952
- catch (ex) {
953
- if (ex instanceof Error) {
954
- console.log("Error in validating phone number ==>", ex);
955
- result.Error = ex;
956
- }
957
- }
958
- return result;
959
- };
960
- exports.IsValidPhoneNumber = IsValidPhoneNumber;
961
- /**
962
- *
963
- * Server side field validatinon
964
- * @param {db} object database connection
965
- * @param {dataObj} object contains field data
966
- * @param {objectType} string object name
967
- * @param {countryCode} string, ISO country code
968
- * @returns {
969
- IsValid: boolean, //phone is valid or not
970
- CountryCode?: string, //phone country code
971
- PhoneCallingCode?: CountryCallingCode, //phone country calling code
972
- PhoneNumberParsed?: NationalNumber, //phone no local to the country, without country calling code and only digits
973
- Error: Error
974
- }
975
- */
976
- function ValidateData(db, dataObj, objectType) {
977
- return new Promise(function (resolve, reject) {
978
- db.collection("ObjectSchema").findOne({ "Name": objectType }, function (error, result) {
979
- if (error) {
980
- resolve('error');
981
- }
982
- if (result && result.Fields) {
983
- var emailRegexp = /^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
984
- for (var i = 0; i < result.Fields.length; i++) {
985
- if (result.Fields[i].IsRequired && result.Fields[i].IsRequired == true && result.Fields[i].UIDataType != 'formula' && (dataObj[result.Fields[i].Name] == '' || dataObj[result.Fields[i].Name] == null)) {
986
- resolve(result.Fields[i].Name + ' is required');
987
- }
988
- if (result.Fields[i].Name == 'Email' && (!emailRegexp.test(dataObj[result.Fields[i].Name]))) {
989
- resolve(result.Fields[i].Name + ' is not valid');
990
- }
991
- }
992
- resolve('success');
993
- }
994
- });
995
- });
996
- }
997
- exports.ValidateData = ValidateData;
998
- /**
999
- * Returns boolean - Whether given date is future or not
1000
- *
1001
- * @param {string} date date
1002
- * @return { boolean } true/false
1003
- */
1004
- var IsFutureDate = function (date) {
1005
- var currentDate = +new Date();
1006
- var reqDate = +new Date(date);
1007
- return reqDate > currentDate;
1008
- };
1009
- exports.IsFutureDate = IsFutureDate;
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.IsFutureDate = exports.ValidateData = exports.IsValidPhoneNumber = exports.SubscribeEmailForAllDomains = exports.GetEmailSubscribeStatus = exports.GetDateRangeFromOperatorValue = exports.CheckDateExistInRange = exports.AddLog = exports.UpdatePipelineMailStatus = exports.MapAccountContact = exports.CreateContact = exports.UpdateContactDetails = exports.GetSystemEmailTemplate = exports.GetContactDetailByEmail = exports.GetAccountDetailByName = exports.GenerateAutoIncrementFieldValue = exports.GetEmailwiseUnsubscribeData = exports.GetListSchema = exports.GetCompanyDetails = void 0;
43
+ var mongodb_1 = require("mongodb");
44
+ var constants_1 = __importDefault(require("../constants"));
45
+ var moment_1 = __importDefault(require("moment"));
46
+ var libphonenumber_js_1 = require("libphonenumber-js");
47
+ function GetCompanyDetails(Master_DB, companyId) {
48
+ return Master_DB.collection('Company').findOne({ _id: new mongodb_1.ObjectId(companyId) });
49
+ }
50
+ exports.GetCompanyDetails = GetCompanyDetails;
51
+ function GetListSchema(db, listName) {
52
+ return new Promise(function (resolve, reject) {
53
+ db.collection("ListSchema").findOne({ "Name": listName }, function (errorDQL, resultDQL) {
54
+ if (errorDQL)
55
+ reject(errorDQL);
56
+ else {
57
+ if (resultDQL) {
58
+ var ListSchema = resultDQL.Data;
59
+ if (ListSchema) {
60
+ ListSchema = ListSchema.filter(function (item) {
61
+ return item.IsActive == true || item.IsActive == undefined;
62
+ });
63
+ resolve(ListSchema);
64
+ }
65
+ else {
66
+ resolve([]);
67
+ }
68
+ }
69
+ else {
70
+ resolve([]);
71
+ }
72
+ }
73
+ });
74
+ });
75
+ }
76
+ exports.GetListSchema = GetListSchema;
77
+ function GetEmailwiseUnsubscribeData(db, mailID, domainID) {
78
+ return new Promise(function (resolve, reject) {
79
+ db.collection("ListSchema").findOne({ "Name": "CampaignCategory" }, function (errorDQL, resultDQL) {
80
+ if (errorDQL)
81
+ reject(errorDQL);
82
+ else {
83
+ if (resultDQL) {
84
+ var listSchema_1 = resultDQL.Data.filter(function (p) { return p.IsActive == true; });
85
+ if (listSchema_1) {
86
+ db.collection("EmailStatus").findOne({ "EmailID": new RegExp('^' + mailID.toString() + '$', "i") }, function (error, result) {
87
+ if (error)
88
+ reject(error);
89
+ var lstData = result;
90
+ var obj = [];
91
+ if (result && result.Domains) {
92
+ lstData.CampaignUnsubsCategory = [];
93
+ var domainsData = result.Domains;
94
+ for (var i = 0; i < domainsData.length; i++) {
95
+ if (domainID && domainsData[i].DomainID && domainID == domainsData[i].DomainID.toString()) {
96
+ lstData = domainsData[i];
97
+ }
98
+ else if (domainID == undefined) {
99
+ if (domainsData[i].CampaignUnsubsCategory) {
100
+ for (var j = 0; j < domainsData[i].CampaignUnsubsCategory.length; j++) {
101
+ lstData.CampaignUnsubsCategory.push(domainsData[i].CampaignUnsubsCategory[j]);
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+ var _loop_1 = function (i) {
108
+ compaignObj = listSchema_1[i];
109
+ if (lstData != null && lstData.CampaignUnsubsCategory && lstData.CampaignUnsubsCategory.length > 0 && lstData.CampaignUnsubsCategory.filter(function (p) { return p == listSchema_1[i].Key; }).length > 0) {
110
+ obj.push({ 'Key': compaignObj.Key, 'Value': compaignObj.Value, 'DomainID': compaignObj.DomainID, 'checked': true, 'HideForUser': compaignObj.HideForUser });
111
+ }
112
+ else {
113
+ obj.push({ 'Key': compaignObj.Key, 'Value': compaignObj.Value, 'DomainID': compaignObj.DomainID, 'checked': false, 'HideForUser': compaignObj.HideForUser });
114
+ }
115
+ };
116
+ var compaignObj;
117
+ for (var i = 0; i < listSchema_1.length; i++) {
118
+ _loop_1(i);
119
+ }
120
+ resolve(obj);
121
+ });
122
+ }
123
+ else {
124
+ resolve([]);
125
+ }
126
+ }
127
+ else {
128
+ resolve([]);
129
+ }
130
+ }
131
+ });
132
+ });
133
+ }
134
+ exports.GetEmailwiseUnsubscribeData = GetEmailwiseUnsubscribeData;
135
+ function GenerateAutoIncrementFieldValue(db, autoIncrementID) {
136
+ var _this = this;
137
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
138
+ var sequenceDocument, val, j, item, num, ex_1;
139
+ return __generator(this, function (_a) {
140
+ switch (_a.label) {
141
+ case 0:
142
+ _a.trys.push([0, 2, , 3]);
143
+ return [4 /*yield*/, db.collection('AutoIncrement').findOneAndUpdate({ _id: autoIncrementID }, { $inc: { SequenceValue: 1 } })];
144
+ case 1:
145
+ sequenceDocument = _a.sent();
146
+ val = "";
147
+ for (j = 0; j < sequenceDocument.value.Formats.length; j++) {
148
+ item = sequenceDocument.value.Formats[j];
149
+ if (item.Type == "Constant") {
150
+ val += item.Value;
151
+ }
152
+ else if (item.Type == "AutoIncrement") {
153
+ num = sequenceDocument.value.SequenceValue.toString();
154
+ if (item.MinimumLength && item.MinimumLength > 0) {
155
+ num = ("0000000000").substring(0, item.MinimumLength - num.length) + num;
156
+ }
157
+ val += num;
158
+ }
159
+ }
160
+ resolve(val);
161
+ return [3 /*break*/, 3];
162
+ case 2:
163
+ ex_1 = _a.sent();
164
+ resolve(null);
165
+ return [3 /*break*/, 3];
166
+ case 3: return [2 /*return*/];
167
+ }
168
+ });
169
+ }); });
170
+ }
171
+ exports.GenerateAutoIncrementFieldValue = GenerateAutoIncrementFieldValue;
172
+ function GetAccountDetailByName(db, accountName) {
173
+ return new Promise(function (resolve, reject) {
174
+ db.collection("Account").findOne({ Name: new RegExp('^' + accountName + '$', "i"), "IsActive": true }, { projection: { "_id": 1 } }, function (error, result) {
175
+ if (error) {
176
+ resolve(null);
177
+ }
178
+ if (result) {
179
+ resolve(result);
180
+ }
181
+ else {
182
+ resolve(null);
183
+ }
184
+ });
185
+ });
186
+ }
187
+ exports.GetAccountDetailByName = GetAccountDetailByName;
188
+ function GetContactDetailByEmail(db, contactEmail) {
189
+ return new Promise(function (resolve, reject) {
190
+ db.collection("Contact").aggregate([
191
+ { $match: { "Email": new RegExp('^' + contactEmail + '$', "i"), "IsActive": true } },
192
+ { $project: { "_id": 1, "AccountID": 1 } },
193
+ {
194
+ $lookup: {
195
+ from: "Account",
196
+ localField: "AccountID",
197
+ foreignField: "_id",
198
+ as: "Account"
199
+ }
200
+ },
201
+ { $project: { "_id": 1, "AccountID": 1, "AccountName": { $arrayElemAt: ["$Account.Name", 0] } } }
202
+ ]).toArray(function (errorDQL, resultDQL) {
203
+ if (errorDQL) {
204
+ resolve(null);
205
+ }
206
+ else if (resultDQL && resultDQL.length > 0) {
207
+ resolve(resultDQL[0]);
208
+ }
209
+ else {
210
+ resolve(null);
211
+ }
212
+ });
213
+ });
214
+ }
215
+ exports.GetContactDetailByEmail = GetContactDetailByEmail;
216
+ function GetSystemEmailTemplate(db, TemplateIDArray) {
217
+ return new Promise(function (resolve, reject) {
218
+ db.collection("SystemEmailTemplate").find({ "_id": { $in: TemplateIDArray } }).toArray(function (errorDQL, resultDQL) {
219
+ if (errorDQL) {
220
+ resolve(null);
221
+ }
222
+ else if (resultDQL && resultDQL.length > 0) {
223
+ resolve(resultDQL);
224
+ }
225
+ else {
226
+ resolve(null);
227
+ }
228
+ });
229
+ });
230
+ }
231
+ exports.GetSystemEmailTemplate = GetSystemEmailTemplate;
232
+ function UpdateContactDetails(db, contactData) {
233
+ db.collection("Contact").updateOne({ "_id": contactData._id }, {
234
+ $set: {
235
+ "FirstName": contactData.FirstName, "LastName": contactData.LastName,
236
+ "PrimaryEmailCategory": contactData.PrimaryEmailCategory, "PhoneCountryCode": contactData.PhoneCountryCode,
237
+ "Phone": contactData.Phone, "JobTitle": contactData.JobTitle,
238
+ "ModifiedDate": new Date(), "ModifiedBy": contactData.OwnerID
239
+ }
240
+ }, function (error, result) {
241
+ if (error) {
242
+ }
243
+ if (result) {
244
+ }
245
+ });
246
+ }
247
+ exports.UpdateContactDetails = UpdateContactDetails;
248
+ // function CreateContact(db: Db, contactData: AnyObjectInterface): Promise<null | AnyObjectInterface> {
249
+ // return new Promise(function (resolve, reject) {
250
+ // let contactObj = {
251
+ // "Salutation": null,
252
+ // "OwnerID": contactData.OwnerID,
253
+ // "FirstName": contactData.FirstName,
254
+ // "LastName": contactData.LastName,
255
+ // "ReportsTo": null,
256
+ // "JobTitle": contactData.JobTitle,
257
+ // "Department": null,
258
+ // "Email": contactData.Email,
259
+ // "PrimaryEmailCategory": contactData.PrimaryEmailCategory,
260
+ // "PhoneCountryCode": contactData.PhoneCountryCode,
261
+ // "Phone": contactData.Phone,
262
+ // "Mobile": null,
263
+ // "Birthdate": null,
264
+ // "LinkedIn": null,
265
+ // "AccountID": null,
266
+ // "Address": null,
267
+ // "City": null,
268
+ // "State": null,
269
+ // "Country": null,
270
+ // "PostalCode": null,
271
+ // "SearchAddress": {
272
+ // "lat": "",
273
+ // "lng": ""
274
+ // },
275
+ // "CreatedBy": contactData.OwnerID,
276
+ // "CreatedDate": new Date(),
277
+ // "IsActive": true,
278
+ // "RelationID": null
279
+ // }
280
+ // db.collection("Contact").insertOne(contactObj, function (error, result) {
281
+ // if (error) {
282
+ // resolve(null);
283
+ // }
284
+ // if (result) {
285
+ // resolve(result);
286
+ // } else {
287
+ // resolve(null);
288
+ // }
289
+ // });
290
+ // });
291
+ // }
292
+ function CreateContact(db, contactData) {
293
+ return new Promise(function (resolve, reject) {
294
+ return __awaiter(this, void 0, void 0, function () {
295
+ var contactObj;
296
+ return __generator(this, function (_a) {
297
+ contactObj = {
298
+ "Salutation": contactData.Salutation,
299
+ "OwnerID": contactData.OwnerID,
300
+ "FirstName": contactData.FirstName,
301
+ "LastName": contactData.LastName,
302
+ "ReportsTo": null,
303
+ "JobTitle": contactData.JobTitle,
304
+ "Department": null,
305
+ "Email": contactData.Email,
306
+ "PrimaryEmailCategory": contactData.PrimaryEmailCategory,
307
+ "PhoneCountryCode": contactData.PhoneCountryCode,
308
+ "Phone": contactData.Phone,
309
+ "Mobile": null,
310
+ "Birthdate": null,
311
+ "LinkedIn": null,
312
+ "AccountID": null,
313
+ "Address": null,
314
+ "City": null,
315
+ "State": null,
316
+ "Country": null,
317
+ "PostalCode": null,
318
+ "SearchAddress": {
319
+ "lat": "",
320
+ "lng": ""
321
+ },
322
+ "CreatedBy": contactData.OwnerID,
323
+ "CreatedDate": new Date(),
324
+ "IsActive": true,
325
+ "RelationID": null,
326
+ "OwnerID_LookupData": contactData.OwnerID_LookupData
327
+ };
328
+ // let validationMsg = await ValidateData(db,contactObj,"Contact");
329
+ // if(validationMsg == 'success'){
330
+ db.collection("Contact").insertOne(contactObj, function (error, result) {
331
+ if (error) {
332
+ resolve([error, null]);
333
+ }
334
+ if (result) {
335
+ resolve([null, result]);
336
+ }
337
+ });
338
+ return [2 /*return*/];
339
+ });
340
+ });
341
+ });
342
+ }
343
+ exports.CreateContact = CreateContact;
344
+ function MapAccountContact(db, dataObj) {
345
+ var _a;
346
+ var relationObj = (_a = {
347
+ "AccountID": dataObj.AccountID,
348
+ "Roles": null,
349
+ "Branch": null,
350
+ "IsInternal": false,
351
+ "IsWorking": true,
352
+ "ContactID": dataObj.ContactID,
353
+ "OwnerID": dataObj.OwnerID,
354
+ "CreatedBy": dataObj.OwnerID,
355
+ "CreatedDate": new Date()
356
+ },
357
+ _a["AccountID" + constants_1.default.LookupAlias] = dataObj["AccountID" + constants_1.default.LookupAlias],
358
+ _a["ContactID" + constants_1.default.LookupAlias] = dataObj["ContactID" + constants_1.default.LookupAlias],
359
+ _a["IsActive"] = true,
360
+ _a);
361
+ db.collection('AccountContactRelation').findOne({ AccountID: dataObj.AccountID, ContactID: dataObj.ContactID, IsActive: true }, { projection: { "_id": 1 } }, function (errorSearch, resultSearch) {
362
+ if (errorSearch) {
363
+ return;
364
+ }
365
+ if (!resultSearch) {
366
+ db.collection("AccountContactRelation").insertOne(relationObj, function (error, result) {
367
+ if (error) {
368
+ return;
369
+ }
370
+ });
371
+ }
372
+ });
373
+ }
374
+ exports.MapAccountContact = MapAccountContact;
375
+ function UpdatePipelineMailStatus(db, pipelineID, mailStatus) {
376
+ db.collection("Pipeline").updateOne({ "_id": pipelineID }, {
377
+ $set: {
378
+ "MailStatus": mailStatus
379
+ }
380
+ }, function (error, result) {
381
+ if (error) {
382
+ }
383
+ if (result) {
384
+ }
385
+ });
386
+ }
387
+ exports.UpdatePipelineMailStatus = UpdatePipelineMailStatus;
388
+ function AddLog(db, data) {
389
+ db.collection("ExternalApiLogs").insertOne(data, function (err1, res1) {
390
+ if (err1) {
391
+ console.log("Error in ExternalApiLogs writing");
392
+ }
393
+ });
394
+ }
395
+ exports.AddLog = AddLog;
396
+ /**
397
+ * Returns object - To and From date from given operator value
398
+ *
399
+ * @param {string} operator today/yesterday/tomorrow
400
+ * @return { dates } object container start and end date
401
+ */
402
+ var GetDateRangeFromOperatorValue = function (operator, fiscalMonth, fiscalFrom) {
403
+ if (operator === void 0) { operator = ""; }
404
+ var startDate = null, endDate = null;
405
+ var currentDateFormat = "DD-MMM-YYYY";
406
+ var requiredDateFormat = currentDateFormat;
407
+ var momentObj = (0, moment_1.default)();
408
+ var getFiscalMonthIndex = moment_1.default.monthsShort().findIndex(function (month) { return month === fiscalMonth; });
409
+ // GET FISCAL MONTH INDEX
410
+ // if (operator.includes("Fiscal")) {
411
+ if (operator.toLowerCase().includes("fiscal") || ["Year to Date", "year-to-date"].includes(operator)) {
412
+ if (fiscalFrom === "End") {
413
+ fiscalMonth = momentObj.clone().month(fiscalMonth).add(1, "months").format('MMM'); // Modify FiscalMonth in FiscalFrom - End
414
+ }
415
+ // SET FISCAL QUARTER
416
+ var firstFisQuarterStart = momentObj.clone().month(fiscalMonth).startOf('month').quarter(1).format(requiredDateFormat);
417
+ var secondFisQuarterStart = (0, moment_1.default)(firstFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(2).format(requiredDateFormat);
418
+ var thirdFisQuarterStart = (0, moment_1.default)(secondFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(3).format(requiredDateFormat);
419
+ var fourthFisQuarterStart = (0, moment_1.default)(thirdFisQuarterStart, currentDateFormat).clone().startOf("month").quarter(4).format(requiredDateFormat);
420
+ var firstFisQuarterEnd = (0, moment_1.default)(firstFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
421
+ var secondFisQuarterEnd = (0, moment_1.default)(secondFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
422
+ var thirdFisQuarterEnd = (0, moment_1.default)(thirdFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
423
+ var fourthFisQuarterEnd = (0, moment_1.default)(fourthFisQuarterStart, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
424
+ var currentDate = (0, moment_1.default)((0, moment_1.default)().format('DD-MM-YYYY'), "DD/MM/YYYY");
425
+ var arrIndex = ["first", "second", "third", "fourth"];
426
+ for (var i = 0; i < arrIndex.length; i++) {
427
+ if (CheckDateExistInRange(currentDate, eval(arrIndex[i] + "FisQuarterStart"), eval(arrIndex[i] + "FisQuarterEnd"))) {
428
+ startDate = eval(arrIndex[i] + "FisQuarterStart");
429
+ endDate = eval(arrIndex[i] + "FisQuarterEnd");
430
+ break;
431
+ }
432
+ }
433
+ ;
434
+ }
435
+ switch (operator) {
436
+ case "Yesterday":
437
+ case "yesterday":
438
+ startDate = momentObj.clone().subtract(1, "days").format(requiredDateFormat);
439
+ endDate = momentObj.clone().subtract(1, "days").format(requiredDateFormat);
440
+ break;
441
+ case "Today":
442
+ case "today":
443
+ startDate = momentObj.clone().format(requiredDateFormat);
444
+ endDate = momentObj.clone().format(requiredDateFormat);
445
+ break;
446
+ case "Tomorrow":
447
+ case "tomorrow":
448
+ startDate = momentObj.clone().add(1, "days").format(requiredDateFormat);
449
+ endDate = momentObj.clone().add(1, "days").format(requiredDateFormat);
450
+ break;
451
+ case "Last 7 Days":
452
+ case "last-7-days":
453
+ startDate = momentObj.clone().subtract(6, "days").format(requiredDateFormat);
454
+ endDate = momentObj.clone().format(requiredDateFormat);
455
+ break;
456
+ case "Last 30 Days":
457
+ case "last-30-days":
458
+ startDate = momentObj.clone().subtract(29, "days").format(requiredDateFormat);
459
+ endDate = momentObj.clone().format(requiredDateFormat);
460
+ break;
461
+ case "Last 60 Days":
462
+ case "last-60-days":
463
+ startDate = momentObj.clone().subtract(59, "days").format(requiredDateFormat);
464
+ endDate = momentObj.clone().format(requiredDateFormat);
465
+ break;
466
+ case "Last 90 Days":
467
+ case "last-90-days":
468
+ startDate = momentObj.clone().subtract(89, "days").format(requiredDateFormat);
469
+ endDate = momentObj.clone().format(requiredDateFormat);
470
+ break;
471
+ case "Last 120 Days":
472
+ case "last-120-days":
473
+ startDate = momentObj.clone().subtract(119, "days").format(requiredDateFormat);
474
+ endDate = momentObj.clone().format(requiredDateFormat);
475
+ break;
476
+ case "Next 7 Days":
477
+ case "next-7-days":
478
+ startDate = momentObj.clone().format(requiredDateFormat);
479
+ endDate = momentObj.clone().add(6, "days").format(requiredDateFormat);
480
+ break;
481
+ case "Next 30 Days":
482
+ case "next-30-days":
483
+ startDate = momentObj.clone().format(requiredDateFormat);
484
+ endDate = momentObj.clone().add(29, "days").format(requiredDateFormat);
485
+ break;
486
+ case "Next 60 Days":
487
+ case "next-60-days":
488
+ startDate = momentObj.clone().format(requiredDateFormat);
489
+ endDate = momentObj.clone().add(59, "days").format(requiredDateFormat);
490
+ break;
491
+ case "Next 90 Days":
492
+ case "next-90-days":
493
+ startDate = momentObj.clone().format(requiredDateFormat);
494
+ endDate = momentObj.clone().add(89, "days").format(requiredDateFormat);
495
+ break;
496
+ case "Next 120 Days":
497
+ case "next-120-days":
498
+ startDate = momentObj.clone().format(requiredDateFormat);
499
+ endDate = momentObj.clone().add(119, "days").format(requiredDateFormat);
500
+ break;
501
+ case "Last Week":
502
+ case "last-week":
503
+ startDate = momentObj.clone().subtract(1, "weeks").startOf('isoWeek').format(requiredDateFormat);
504
+ endDate = momentObj.clone().subtract(1, "weeks").endOf('isoWeek').format(requiredDateFormat);
505
+ break;
506
+ case "This Week":
507
+ case "this-week":
508
+ startDate = momentObj.clone().startOf('isoWeek').format(requiredDateFormat);
509
+ endDate = momentObj.clone().endOf('isoWeek').format(requiredDateFormat);
510
+ break;
511
+ case "Next Week":
512
+ case "next-week":
513
+ startDate = momentObj.clone().add(1, "weeks").startOf('isoWeek').format(requiredDateFormat);
514
+ endDate = momentObj.clone().add(1, "weeks").endOf('isoWeek').format(requiredDateFormat);
515
+ break;
516
+ case "Last Month":
517
+ case "last-month":
518
+ startDate = momentObj.clone().subtract(1, "months").startOf('month').format(requiredDateFormat);
519
+ endDate = momentObj.clone().subtract(1, "months").endOf('month').format(requiredDateFormat);
520
+ break;
521
+ case "This Month":
522
+ case "this-month":
523
+ startDate = momentObj.clone().startOf('month').format(requiredDateFormat);
524
+ endDate = momentObj.clone().endOf('month').format(requiredDateFormat);
525
+ break;
526
+ case "Next Month":
527
+ case "next-month":
528
+ startDate = momentObj.clone().add(1, "months").startOf('month').format(requiredDateFormat);
529
+ endDate = momentObj.clone().add(1, "months").endOf('month').format(requiredDateFormat);
530
+ break;
531
+ case "Last Quarter":
532
+ case "last-quarter":
533
+ startDate = momentObj.clone().subtract(1, "quarters").startOf('quarter').format(requiredDateFormat);
534
+ endDate = momentObj.clone().subtract(1, "quarters").endOf('quarter').format(requiredDateFormat);
535
+ break;
536
+ case "This Quarter":
537
+ case "this-quarter":
538
+ startDate = momentObj.clone().startOf('quarter').format(requiredDateFormat);
539
+ endDate = momentObj.clone().endOf('quarter').format(requiredDateFormat);
540
+ break;
541
+ case "Next Quarter":
542
+ case "next-quarter":
543
+ startDate = momentObj.clone().add(1, "quarters").startOf('quarter').format(requiredDateFormat);
544
+ endDate = momentObj.clone().add(1, "quarters").endOf('quarter').format(requiredDateFormat);
545
+ break;
546
+ case "Last Fiscal Quarter":
547
+ case "last-fiscal-quarter":
548
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().subtract(3, "months").startOf('month').format(requiredDateFormat);
549
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
550
+ break;
551
+ case "This Fiscal Quarter":
552
+ case "this-fiscal-quarter":
553
+ startDate = startDate;
554
+ endDate = endDate;
555
+ break;
556
+ case "Next Fiscal Quarter":
557
+ case "next-fiscal-quarter":
558
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().add(3, "months").startOf('month').format(requiredDateFormat);
559
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().add(2, "months").endOf('month').format(requiredDateFormat);
560
+ break;
561
+ case "Last Year":
562
+ case "last-year":
563
+ startDate = momentObj.clone().subtract(1, "years").startOf('year').format(requiredDateFormat);
564
+ endDate = momentObj.clone().subtract(1, "years").endOf('year').format(requiredDateFormat);
565
+ break;
566
+ case "This Year":
567
+ case "this-year":
568
+ startDate = momentObj.clone().startOf('year').format(requiredDateFormat);
569
+ endDate = momentObj.clone().endOf('year').format(requiredDateFormat);
570
+ break;
571
+ case "Next Year":
572
+ case "next-year":
573
+ startDate = momentObj.clone().add(1, "years").startOf('year').format(requiredDateFormat);
574
+ endDate = momentObj.clone().add(1, "years").endOf('year').format(requiredDateFormat);
575
+ break;
576
+ case "Last Fiscal Year":
577
+ case "last-fiscal-year":
578
+ if (fiscalFrom === "Start") {
579
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
580
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
581
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
582
+ }
583
+ else {
584
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(24, "months").startOf('month').format(requiredDateFormat);
585
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
586
+ }
587
+ }
588
+ else {
589
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
590
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(1, "year").startOf('month').format(requiredDateFormat);
591
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
592
+ }
593
+ else {
594
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(2, "year").startOf('month').format(requiredDateFormat);
595
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
596
+ }
597
+ }
598
+ break;
599
+ case "This Fiscal Year":
600
+ case "this-fiscal-year":
601
+ if (fiscalFrom === "Start") {
602
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
603
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
604
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
605
+ }
606
+ else {
607
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
608
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
609
+ }
610
+ }
611
+ else {
612
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
613
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
614
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
615
+ }
616
+ else {
617
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
618
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
619
+ }
620
+ }
621
+ break;
622
+ case "Next Fiscal Year":
623
+ case "next-fiscal-year":
624
+ if (fiscalFrom === "Start") {
625
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
626
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(1, "years").startOf('month').format(requiredDateFormat);
627
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
628
+ }
629
+ else {
630
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
631
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
632
+ }
633
+ }
634
+ else {
635
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
636
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(1, "years").startOf('month').format(requiredDateFormat);
637
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
638
+ }
639
+ else {
640
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
641
+ endDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).add(11, "months").endOf('month').format(requiredDateFormat);
642
+ }
643
+ }
644
+ break;
645
+ case "Current Calendar Year":
646
+ case "current-calendar-year":
647
+ startDate = momentObj.clone().startOf('year').format(requiredDateFormat);
648
+ endDate = momentObj.clone().endOf('year').format(requiredDateFormat);
649
+ break;
650
+ case "Previous Calendar Year":
651
+ case "previous-calendar-year":
652
+ startDate = momentObj.clone().subtract(1, "years").startOf('year').format(requiredDateFormat);
653
+ endDate = momentObj.clone().subtract(1, "years").endOf('year').format(requiredDateFormat);
654
+ break;
655
+ case "Next Calendar Year":
656
+ case "next-calendar-year":
657
+ startDate = momentObj.clone().add(1, "years").startOf('year').format(requiredDateFormat);
658
+ endDate = momentObj.clone().add(1, "years").endOf('year').format(requiredDateFormat);
659
+ break;
660
+ case "Year to Date":
661
+ case "year-to-date":
662
+ endDate = momentObj.clone().format(requiredDateFormat);
663
+ // Commented Below Hanisha's Code - Implemented following as per QPC-6370
664
+ // if (parseInt(momentObj.format('M')) > 3) {
665
+ // startDate = momentObj.clone().startOf('month').month("Apr").format(requiredDateFormat);
666
+ // } else {
667
+ // startDate = momentObj.clone().subtract(1, "years").startOf('month').month("Apr").format(requiredDateFormat);
668
+ // }
669
+ if (fiscalFrom === "Start") {
670
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex <= momentObj.clone().month()) {
671
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
672
+ }
673
+ else {
674
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
675
+ }
676
+ }
677
+ else {
678
+ if (getFiscalMonthIndex == 0 || getFiscalMonthIndex && getFiscalMonthIndex < momentObj.clone().month() || getFiscalMonthIndex == 11) {
679
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).startOf('month').format(requiredDateFormat);
680
+ }
681
+ else {
682
+ startDate = (0, moment_1.default)(startDate, currentDateFormat).clone().month(fiscalMonth).subtract(12, "months").startOf('month').format(requiredDateFormat);
683
+ }
684
+ }
685
+ break;
686
+ default:
687
+ break;
688
+ }
689
+ return {
690
+ startDate: startDate,
691
+ endDate: endDate
692
+ };
693
+ };
694
+ exports.GetDateRangeFromOperatorValue = GetDateRangeFromOperatorValue;
695
+ /**
696
+ * Returns boolean - Check date exist in Given Date Range(Quarter)
697
+ *
698
+ * @param {string} date date to compare
699
+ * @param {string} startDate format DD-MMM-YYYY
700
+ * @param {string} endDate format DD-MMM-YYYY
701
+ * @return { boolean } true/false
702
+ */
703
+ var CheckDateExistInRange = function (date, startDate, endDate) {
704
+ var currentDateFormat = "DD-MMM-YYYY";
705
+ var compareDate = (0, moment_1.default)((0, moment_1.default)(date).format("DD-MM-YYYY"), "DD/MM/YYYY");
706
+ var startCompareDate = (0, moment_1.default)((0, moment_1.default)(startDate, currentDateFormat).format('DD-MM-YYYY'), "DD/MM/YYYY");
707
+ var endCompareDate = (0, moment_1.default)((0, moment_1.default)(endDate, currentDateFormat).format('DD-MM-YYYY'), "DD/MM/YYYY");
708
+ return compareDate.isBetween(startCompareDate, endCompareDate) || compareDate.isSame(startCompareDate) || compareDate.isSame(endCompareDate);
709
+ };
710
+ exports.CheckDateExistInRange = CheckDateExistInRange;
711
+ /**
712
+ * To get the email subscribe status. By default it take email as subscribed
713
+ * and check if email is unsusbscribed for all categories of all domains then it give it as unsubscribe.
714
+ * @param {db} database object
715
+ * @param {email} string
716
+ *
717
+ * @param retunrs true|false|error for subscribe or unsubscribe.
718
+ */
719
+ var GetEmailSubscribeStatus = function (db, email) {
720
+ var _this = this;
721
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
722
+ var emailSubscribeStatus, emailUnsubcData, error_1;
723
+ return __generator(this, function (_a) {
724
+ switch (_a.label) {
725
+ case 0:
726
+ _a.trys.push([0, 2, , 3]);
727
+ emailSubscribeStatus = true;
728
+ return [4 /*yield*/, GetEmailwiseUnsubscribeData(db, email)];
729
+ case 1:
730
+ emailUnsubcData = _a.sent();
731
+ if (emailUnsubcData && emailUnsubcData.length > 0) {
732
+ if (emailUnsubcData.filter(function (x) { return x.checked != null && x.checked != undefined && x.checked; }).length == emailUnsubcData.length)
733
+ emailSubscribeStatus = false;
734
+ }
735
+ resolve(emailSubscribeStatus);
736
+ return [3 /*break*/, 3];
737
+ case 2:
738
+ error_1 = _a.sent();
739
+ reject(error_1);
740
+ return [3 /*break*/, 3];
741
+ case 3: return [2 /*return*/];
742
+ }
743
+ });
744
+ }); });
745
+ };
746
+ exports.GetEmailSubscribeStatus = GetEmailSubscribeStatus;
747
+ /**
748
+ * To subscribe or unsubscribe email id for all domains
749
+ * @param {db} database object
750
+ * @param {email} string
751
+ * @param {isSubscribe} boolean
752
+ * @param {companyID} mongodb object id, comany id of email
753
+ * @param {comment} string , to add comment
754
+ * @param {mongodbQueryOptions} object, params to pass on db queries
755
+ * @returns resolve success | error object
756
+ */
757
+ var SubscribeEmailForAllDomains = function (db, email, isSubscribe, companyID, comment, mongodbQueryOptions) {
758
+ if (comment === void 0) { comment = ""; }
759
+ if (mongodbQueryOptions === void 0) { mongodbQueryOptions = null; }
760
+ return new Promise(function (resolve, reject) {
761
+ return __awaiter(this, void 0, void 0, function () {
762
+ var mongodbQueryOpts, marketingSettingDetail, marketingCategoryKeys, domainIds_1, domainDetail, existEmailSub, isRequireUpdate, marketingCategoryData, _loop_2, i, error_2;
763
+ return __generator(this, function (_a) {
764
+ switch (_a.label) {
765
+ case 0:
766
+ _a.trys.push([0, 7, , 8]);
767
+ mongodbQueryOpts = {};
768
+ if (mongodbQueryOptions) {
769
+ mongodbQueryOpts = mongodbQueryOptions;
770
+ }
771
+ if (!email) return [3 /*break*/, 6];
772
+ return [4 /*yield*/, db.collection('Company').findOne({ IsActive: true }, { projection: { "Setting.MarketingSetting": 1 } }, mongodbQueryOpts)];
773
+ case 1:
774
+ marketingSettingDetail = _a.sent();
775
+ marketingCategoryKeys = [], domainIds_1 = [];
776
+ if (marketingSettingDetail && marketingSettingDetail.Setting
777
+ && marketingSettingDetail.Setting
778
+ && marketingSettingDetail.Setting.MarketingSetting
779
+ && marketingSettingDetail.Setting.MarketingSetting.Domains
780
+ && marketingSettingDetail.Setting.MarketingSetting.Domains.length > 0) {
781
+ domainDetail = marketingSettingDetail.Setting.MarketingSetting.Domains.filter(function (x) { return x.IsActive == true; });
782
+ if (domainDetail && domainDetail.length > 0) {
783
+ domainIds_1 = domainDetail.map(function (x) { return x._id; });
784
+ }
785
+ }
786
+ existEmailSub = {}, isRequireUpdate = false;
787
+ if (!(domainIds_1 && domainIds_1.length > 0)) return [3 /*break*/, 4];
788
+ return [4 /*yield*/, db.collection('EmailStatus').findOne({ 'EmailID': new RegExp("^" + email + "$", "i"), CompanyID: companyID }, { projection: { "Domains": 1 } }, mongodbQueryOpts)];
789
+ case 2:
790
+ existEmailSub = _a.sent();
791
+ isRequireUpdate = true;
792
+ if (!existEmailSub) {
793
+ existEmailSub = {
794
+ CompanyID: companyID,
795
+ EmailID: email,
796
+ Domains: []
797
+ };
798
+ }
799
+ 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)];
800
+ case 3:
801
+ marketingCategoryData = _a.sent();
802
+ _loop_2 = function (i) {
803
+ marketingCategoryKeys = [];
804
+ if (marketingCategoryData && marketingCategoryData.Data)
805
+ marketingCategoryKeys = marketingCategoryData.Data.filter(function (x) { return x.IsActive == true && x.DomainID && x.DomainID.toString() == domainIds_1[i].toString(); }).map(function (x) { return x.Key; });
806
+ var domainObj = null;
807
+ var domainExist = false;
808
+ if (existEmailSub && existEmailSub.Domains && existEmailSub.Domains.length > 0) {
809
+ domainObj = existEmailSub.Domains.find(function (x) { return x.DomainID.toString() == domainIds_1[i].toString(); });
810
+ if (domainObj) {
811
+ domainExist = true;
812
+ }
813
+ else {
814
+ domainExist = false;
815
+ }
816
+ }
817
+ //if Domains array not available on existing email status data then adding an empty array and also checking domains property should of Array type
818
+ if (existEmailSub && !existEmailSub.Domains) {
819
+ existEmailSub.Domains = [];
820
+ }
821
+ if (domainExist == false) {
822
+ domainObj = {
823
+ "DomainID": domainIds_1[i],
824
+ "Comment": comment,
825
+ "CampaignID": null,
826
+ "CampaignSubsCategory": [],
827
+ "CampaignUnsubsCategory": [],
828
+ "IsSubscribe": true
829
+ };
830
+ }
831
+ if (isSubscribe == true) {
832
+ if (domainExist == true) {
833
+ // existEmailSub.Domains[i].CampaignSubsCategory = marketingCategoryKeys;
834
+ // existEmailSub.Domains[i].CampaignUnsubsCategory = [];
835
+ domainObj.CampaignSubsCategory = marketingCategoryKeys;
836
+ domainObj.CampaignUnsubsCategory = [];
837
+ domainObj.IsSubscribe = true;
838
+ }
839
+ else if (domainExist == false && domainObj) {
840
+ domainObj.CampaignSubsCategory = marketingCategoryKeys;
841
+ //existEmailSub.Domains[i] = domainObj;
842
+ existEmailSub.Domains.push(domainObj);
843
+ }
844
+ }
845
+ else {
846
+ if (domainExist == true) {
847
+ // existEmailSub.Domains[i].CampaignSubsCategory = [];
848
+ // existEmailSub.Domains[i].CampaignUnsubsCategory = marketingCategoryKeys;
849
+ domainObj.CampaignSubsCategory = [];
850
+ domainObj.CampaignUnsubsCategory = marketingCategoryKeys;
851
+ }
852
+ else if (domainExist == false && domainObj) {
853
+ domainObj.CampaignUnsubsCategory = marketingCategoryKeys;
854
+ //existEmailSub.Domains[i] = domainObj;
855
+ existEmailSub.Domains.push(domainObj);
856
+ }
857
+ domainObj.IsSubscribe = false;
858
+ }
859
+ };
860
+ for (i = 0; i < domainIds_1.length; i++) {
861
+ _loop_2(i);
862
+ }
863
+ _a.label = 4;
864
+ case 4:
865
+ mongodbQueryOpts["upsert"] = true;
866
+ if (!isRequireUpdate) return [3 /*break*/, 6];
867
+ //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
868
+ return [4 /*yield*/, db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, mongodbQueryOpts)];
869
+ case 5:
870
+ //await db.collection('EmailStatus').updateOne({ 'EmailID': email, CompanyID: companyID }, { $set: { Domains: existEmailSub.Domains } }, { upsert: true })
871
+ _a.sent();
872
+ _a.label = 6;
873
+ case 6:
874
+ resolve("success");
875
+ return [3 /*break*/, 8];
876
+ case 7:
877
+ error_2 = _a.sent();
878
+ //console.log("SubscribeEmailForAllDomains error");
879
+ if (error_2 instanceof Error) {
880
+ error_2.name += "- Error while SubscribeEmailForAllDomains Function";
881
+ }
882
+ //OperaUtility.OperaErrorHandler(db, error);
883
+ reject(error_2);
884
+ return [3 /*break*/, 8];
885
+ case 8: return [2 /*return*/];
886
+ }
887
+ });
888
+ });
889
+ });
890
+ };
891
+ exports.SubscribeEmailForAllDomains = SubscribeEmailForAllDomains;
892
+ /**
893
+ * checking phone number is valid and has dialing code
894
+ * if it has dialing code then get country code, get its optimiser country phone code
895
+ * if it doesn't has dialing code then try to pasrse it with countryCode
896
+ * if phone is valid then use it other wise ignore that no.
897
+ * @param {phoneNumber} string, phone no with or without dialing code
898
+ * @param {countryCode} string, ISO country code
899
+ * @returns {
900
+ IsValid: boolean, //phone is valid or not
901
+ CountryCode?: string, //phone country code
902
+ PhoneCallingCode?: CountryCallingCode, //phone country calling code
903
+ PhoneNumberParsed?: NationalNumber, //phone no local to the country, without country calling code and only digits
904
+ ValidatedBy? : string, //Possible Values are SELF | COUNTRY_CODE, this field tells Phone No is valid by self or found valid with Country code
905
+ Error: Error
906
+ }
907
+ */
908
+ var IsValidPhoneNumber = function (phoneNumber, countryCode) {
909
+ var result = {}; //{ IsValid: false, CountryCode: string, PhoneCallingCode: null, PhoneNumberParsed: null };
910
+ result.IsValid = false;
911
+ result.CountryCode = result.PhoneCallingCode = result.PhoneNumberParsed = "";
912
+ //defaulty setting ValidatedBy flag that phone is validated by only phone no, so setting SELF.
913
+ result.ValidatedBy = "SELF";
914
+ try {
915
+ var phoneNumberParsed = null;
916
+ try {
917
+ phoneNumberParsed = (0, libphonenumber_js_1.parsePhoneNumber)(phoneNumber);
918
+ }
919
+ catch (error) {
920
+ //console.log("Error while parsing phone number ===>", error);
921
+ console.log("Error while parsing phone number");
922
+ }
923
+ if (phoneNumberParsed) {
924
+ if (phoneNumberParsed.isValid()) {
925
+ result.IsValid = true;
926
+ result.CountryCode = phoneNumberParsed.country;
927
+ result.PhoneCallingCode = phoneNumberParsed.countryCallingCode;
928
+ result.PhoneNumberParsed = phoneNumberParsed.nationalNumber;
929
+ }
930
+ }
931
+ //if any value is coming in countryCode then only we need to check phone number with country code
932
+ if (result.IsValid == false && countryCode) {
933
+ //try {
934
+ var phoneNumberParsedWithAddressCountry = null;
935
+ try {
936
+ //checking phone no with given country code
937
+ phoneNumberParsedWithAddressCountry = (0, libphonenumber_js_1.parsePhoneNumber)(phoneNumber, countryCode);
938
+ }
939
+ catch (error) {
940
+ //console.log("Error while parsing phone number with address country code ===>", error);
941
+ console.log("Error while parsing phone number with address country code ===>");
942
+ }
943
+ if (phoneNumberParsedWithAddressCountry) {
944
+ if (phoneNumberParsedWithAddressCountry.isValid()) {
945
+ result.IsValid = true;
946
+ result.CountryCode = phoneNumberParsedWithAddressCountry.country;
947
+ result.PhoneCallingCode = phoneNumberParsedWithAddressCountry.countryCallingCode;
948
+ result.PhoneNumberParsed = phoneNumberParsedWithAddressCountry.nationalNumber;
949
+ result.ValidatedBy = "COUNTRY_CODE";
950
+ }
951
+ }
952
+ }
953
+ //just as final check confirmation for phone no shouldn't have any character other than digits.
954
+ if (result.PhoneNumberParsed) {
955
+ result.PhoneNumberParsed = (0, libphonenumber_js_1.parseDigits)(result.PhoneNumberParsed.toString());
956
+ }
957
+ //console.dir(phoneNumberParsed);
958
+ }
959
+ catch (ex) {
960
+ if (ex instanceof Error) {
961
+ console.log("Error in validating phone number ==>", ex);
962
+ result.Error = ex;
963
+ }
964
+ }
965
+ return result;
966
+ };
967
+ exports.IsValidPhoneNumber = IsValidPhoneNumber;
968
+ /**
969
+ *
970
+ * Server side field validatinon
971
+ * @param {db} object database connection
972
+ * @param {dataObj} object contains field data
973
+ * @param {objectType} string object name
974
+ * @param {countryCode} string, ISO country code
975
+ * @returns {
976
+ IsValid: boolean, //phone is valid or not
977
+ CountryCode?: string, //phone country code
978
+ PhoneCallingCode?: CountryCallingCode, //phone country calling code
979
+ PhoneNumberParsed?: NationalNumber, //phone no local to the country, without country calling code and only digits
980
+ Error: Error
981
+ }
982
+ */
983
+ function ValidateData(db, dataObj, objectType) {
984
+ return new Promise(function (resolve, reject) {
985
+ db.collection("ObjectSchema").findOne({ "Name": objectType }, function (error, result) {
986
+ if (error) {
987
+ resolve('error');
988
+ }
989
+ if (result && result.Fields) {
990
+ var emailRegexp = /^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
991
+ for (var i = 0; i < result.Fields.length; i++) {
992
+ if (result.Fields[i].IsRequired && result.Fields[i].IsRequired == true && result.Fields[i].UIDataType != 'formula' && (dataObj[result.Fields[i].Name] == '' || dataObj[result.Fields[i].Name] == null)) {
993
+ resolve(result.Fields[i].Name + ' is required');
994
+ }
995
+ if (result.Fields[i].Name == 'Email' && (!emailRegexp.test(dataObj[result.Fields[i].Name]))) {
996
+ resolve(result.Fields[i].Name + ' is not valid');
997
+ }
998
+ }
999
+ resolve('success');
1000
+ }
1001
+ });
1002
+ });
1003
+ }
1004
+ exports.ValidateData = ValidateData;
1005
+ /**
1006
+ * Returns boolean - Whether given date is future or not
1007
+ *
1008
+ * @param {string} date date
1009
+ * @return { boolean } true/false
1010
+ */
1011
+ var IsFutureDate = function (date) {
1012
+ var currentDate = +new Date();
1013
+ var reqDate = +new Date(date);
1014
+ return reqDate > currentDate;
1015
+ };
1016
+ exports.IsFutureDate = IsFutureDate;