@optimiser/common 1.0.225 → 1.0.229

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * as cryptoService from "./utility/crypto";
7
7
  export * as helperLib from "./lib/helper";
8
8
  export * as _activity from "./lib/activity";
9
9
  export * as _operaUtilCommon from "./lib/operautilitycommon";
10
+ export * as taskutils from "./lib/taskutils";
10
11
  export * from "./modals/connection.modal";
11
12
  export * from "./modals/redisconfig.modal";
12
13
  export * from "./modals/notificationData.modal";
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ exports.cryptoService = __importStar(require("./utility/crypto"));
37
37
  exports.helperLib = __importStar(require("./lib/helper"));
38
38
  exports._activity = __importStar(require("./lib/activity"));
39
39
  exports._operaUtilCommon = __importStar(require("./lib/operautilitycommon"));
40
+ exports.taskutils = __importStar(require("./lib/taskutils"));
40
41
  // Interface Exports
41
42
  __exportStar(require("./modals/connection.modal"), exports);
42
43
  __exportStar(require("./modals/redisconfig.modal"), exports);
@@ -187,6 +187,8 @@ var Connection = /** @class */ (function () {
187
187
  SES_REGION: this.masterConfig.SES_REGION
188
188
  }).then(function (response) {
189
189
  // console.log(response)
190
+ }).catch(function (err) {
191
+ console.log("Error While SendMail. => ", err);
190
192
  });
191
193
  if (!db) return [3 /*break*/, 4];
192
194
  return [4 /*yield*/, db.collection("Error").insertOne(errorObj)];
@@ -0,0 +1,40 @@
1
+ import { NextFunction } from "express";
2
+ import { ObjectId, Db } from "mongodb";
3
+ import { AnyObjectInterface } from "../modals/utility.modal";
4
+ import { OPT_Request } from "../modals/connection.modal";
5
+ import 'moment-timezone';
6
+ /**
7
+ * @param obj object contains data of task
8
+ * @param assignees - assignees object ids array
9
+ * @param userID user object id
10
+ * @param db db connection
11
+ * @param next next function
12
+ * @description Generating Next auto-increment number and return array for each assignee
13
+ */
14
+ declare function GenerateTaskNumber(obj: AnyObjectInterface, assignees: ObjectId[], userID: ObjectId, db: Db, next: NextFunction): Promise<unknown>;
15
+ /**
16
+ * @param req - request obj
17
+ * @param options object contains data of task
18
+ * @param db db connection
19
+ * @param event event passed from optimiser to send notifications
20
+ * @description initiates notifications to be send after action performed in Task
21
+ */
22
+ declare function GenerateTaskNotifications(req: OPT_Request, options: any, db: Db, event: any): Promise<void>;
23
+ /**
24
+ * @param types contains notification type to be executed
25
+ * @param data - notification data
26
+ * @param req - request obj
27
+ * @param db db connection
28
+ * @param event event passed from optimiser to send notifications
29
+ * @description sends notifications
30
+ */
31
+ declare function TriggerNotifications(types: any[] | undefined, data: AnyObjectInterface, req: OPT_Request, db: Db, event: any): Promise<void>;
32
+ /**
33
+ * @param info data of task
34
+ * @param req - request obj
35
+ * @param db db connection
36
+ * @param event event passed from optimiser to send notifications
37
+ * @description creates notification content
38
+ */
39
+ declare function CreateNotificationContent(info: AnyObjectInterface, req: OPT_Request, db: Db, event: any): Promise<void>;
40
+ export { GenerateTaskNumber, GenerateTaskNotifications, TriggerNotifications, CreateNotificationContent };
@@ -0,0 +1,656 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ 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;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
52
+ Object.defineProperty(exports, "__esModule", { value: true });
53
+ exports.CreateNotificationContent = exports.TriggerNotifications = exports.GenerateTaskNotifications = exports.GenerateTaskNumber = void 0;
54
+ var moment_1 = __importDefault(require("moment"));
55
+ var mongodb_1 = require("mongodb");
56
+ var constants_1 = __importDefault(require("../constants"));
57
+ require("moment-timezone");
58
+ var utility_1 = require("./utility");
59
+ /**
60
+ * @param obj object contains data of task
61
+ * @param assignees - assignees object ids array
62
+ * @param userID user object id
63
+ * @param db db connection
64
+ * @param next next function
65
+ * @description Generating Next auto-increment number and return array for each assignee
66
+ */
67
+ function GenerateTaskNumber(obj, assignees, userID, db, next) {
68
+ return __awaiter(this, void 0, void 0, function () {
69
+ return __generator(this, function (_a) {
70
+ try {
71
+ return [2 /*return*/, new Promise(function (resolve) {
72
+ utility_1.GetPageObjectSchema('Task', db, next, function (pageData) {
73
+ return __awaiter(this, void 0, void 0, function () {
74
+ var tasks, i, task;
75
+ return __generator(this, function (_a) {
76
+ switch (_a.label) {
77
+ case 0:
78
+ tasks = [];
79
+ i = 0;
80
+ _a.label = 1;
81
+ case 1:
82
+ if (!(i < assignees.length)) return [3 /*break*/, 4];
83
+ task = __assign(__assign({}, obj), { AssignedTo: assignees[i] });
84
+ task.Acknowledged = assignees[i] == userID ? true : false;
85
+ task.Assignees = [];
86
+ return [4 /*yield*/, utility_1.CheckDataBeforeAdd(task, pageData.ObjectSchema, db)];
87
+ case 2:
88
+ _a.sent();
89
+ tasks.push(task);
90
+ _a.label = 3;
91
+ case 3:
92
+ i++;
93
+ return [3 /*break*/, 1];
94
+ case 4:
95
+ resolve(tasks);
96
+ return [2 /*return*/];
97
+ }
98
+ });
99
+ });
100
+ });
101
+ })];
102
+ }
103
+ catch (error) {
104
+ console.log("Error occurred in generateTaskNumber: " + error + ".");
105
+ }
106
+ return [2 /*return*/];
107
+ });
108
+ });
109
+ }
110
+ exports.GenerateTaskNumber = GenerateTaskNumber;
111
+ /**
112
+ * @param req - request obj
113
+ * @param options object contains data of task
114
+ * @param db db connection
115
+ * @param event event passed from optimiser to send notifications
116
+ * @description initiates notifications to be send after action performed in Task
117
+ */
118
+ function GenerateTaskNotifications(req, options, db, event) {
119
+ return __awaiter(this, void 0, void 0, function () {
120
+ var info, users, list, _a, tasks_1, task;
121
+ return __generator(this, function (_b) {
122
+ switch (_b.label) {
123
+ case 0:
124
+ info = {};
125
+ info['page'] = options.page;
126
+ info['isPrivate'] = options.isPrivate;
127
+ info['ListID'] = options.ListID;
128
+ users = [];
129
+ _a = options.page;
130
+ switch (_a) {
131
+ case "TaskList": return [3 /*break*/, 1];
132
+ case "Task": return [3 /*break*/, 2];
133
+ case "Comment": return [3 /*break*/, 4];
134
+ }
135
+ return [3 /*break*/, 7];
136
+ case 1:
137
+ if (!options.isPrivate && options.isEdit)
138
+ return [2 /*return*/];
139
+ options.NewList = options.NewList || [];
140
+ if (options.OldList) {
141
+ options.OldList = options.OldList.map(function (ol) { return ol.toString(); });
142
+ users = options.NewList.filter(function (nl) { return options.OldList.indexOf(nl.toString()) == -1; });
143
+ }
144
+ else {
145
+ users = options.NewList;
146
+ }
147
+ if (users.length == 0 && options.isPrivate)
148
+ return [2 /*return*/];
149
+ info['users'] = users;
150
+ info['event'] = 'ADDED_TO_LIST';
151
+ return [3 /*break*/, 8];
152
+ case 2:
153
+ info['taskNumbers'] = {};
154
+ tasks_1 = options.Tasks;
155
+ if (tasks_1.length == 0)
156
+ return [2 /*return*/];
157
+ if (!tasks_1[0].ListSublist)
158
+ return [2 /*return*/];
159
+ return [4 /*yield*/, db.collection('TaskList').findOne({
160
+ _id: new mongodb_1.ObjectID(tasks_1[0].ListSublist)
161
+ })];
162
+ case 3:
163
+ list = _b.sent();
164
+ if (list && list.IsPublic)
165
+ return [2 /*return*/];
166
+ if (!list.IsPublic && tasks_1.find(function (task) { return task.AssignedTo == tasks_1[0].OwnerID; }))
167
+ return [2 /*return*/];
168
+ users = [];
169
+ tasks_1.forEach(function (task) {
170
+ info['taskNumbers'][task.AssignedTo] = task.TaskNumber;
171
+ users.push(task.AssignedTo);
172
+ });
173
+ info['isPrivate'] = !list.IsPublic;
174
+ info['users'] = users;
175
+ info['TaskNumber'] = tasks_1[0].TaskNumber;
176
+ info['event'] = options.isEdit ? 'EDIT_TASK' : 'ASSIGNED_A_TASK';
177
+ info['isEdit'] = options.isEdit;
178
+ info['sender'] = options.sender;
179
+ info['taskBeforeEdit'] = options.taskBeforeEdit;
180
+ return [3 /*break*/, 8];
181
+ case 4: return [4 /*yield*/, db.collection('Task').findOne({
182
+ _id: new mongodb_1.ObjectID(options.taskID)
183
+ })];
184
+ case 5:
185
+ task = _b.sent();
186
+ return [4 /*yield*/, db.collection('TaskList').findOne({
187
+ _id: new mongodb_1.ObjectID(task.ListSublist)
188
+ })];
189
+ case 6:
190
+ list = _b.sent();
191
+ if (list.IsPublic)
192
+ return [2 /*return*/];
193
+ if (!list.IsPublic && (task.AssignedTo).toString() == (task.OwnerID).toString())
194
+ return [2 /*return*/];
195
+ info['task'] = task;
196
+ info['list'] = list;
197
+ info['event'] = options.event;
198
+ return [3 /*break*/, 8];
199
+ case 7: return [3 /*break*/, 8];
200
+ case 8:
201
+ info.body = req.body;
202
+ CreateNotificationContent(info, req, db, event);
203
+ return [2 /*return*/];
204
+ }
205
+ });
206
+ });
207
+ }
208
+ exports.GenerateTaskNotifications = GenerateTaskNotifications;
209
+ ;
210
+ /**
211
+ * @param types contains notification type to be executed
212
+ * @param data - notification data
213
+ * @param req - request obj
214
+ * @param db db connection
215
+ * @param event event passed from optimiser to send notifications
216
+ * @description sends notifications
217
+ */
218
+ function TriggerNotifications(types, data, req, db, event) {
219
+ if (types === void 0) { types = []; }
220
+ return __awaiter(this, void 0, void 0, function () {
221
+ var stack, error_1;
222
+ return __generator(this, function (_a) {
223
+ switch (_a.label) {
224
+ case 0:
225
+ _a.trys.push([0, 2, , 3]);
226
+ stack = [];
227
+ if (types.includes('desktop_notification')) { /* Bell Notification */
228
+ stack.push(event.SetGlobalNotification(data.desktopObj, db, req));
229
+ }
230
+ if (types.includes('push_notification')) {
231
+ // stack.push(sendNotificationToUserByUserIds(db, data.users, data.pushObj))
232
+ stack.push(event.CreateEvents(data.users, db, { PushNotificationObj: data.pushObj }));
233
+ }
234
+ if (types.includes('email_notification')) {
235
+ // stack.push(...data.emails.map(email => SendMailWithPromise(email)))
236
+ stack.push.apply(stack, data.emails.map(function (email) { return event.CreateEvent(null, null, { EmailObj: email }); }));
237
+ }
238
+ return [4 /*yield*/, Promise.all(stack)];
239
+ case 1:
240
+ _a.sent();
241
+ return [3 /*break*/, 3];
242
+ case 2:
243
+ error_1 = _a.sent();
244
+ console.log("Error occured in TriggerNotifications Function : " + error_1 + ".");
245
+ return [3 /*break*/, 3];
246
+ case 3: return [2 /*return*/];
247
+ }
248
+ });
249
+ });
250
+ }
251
+ exports.TriggerNotifications = TriggerNotifications;
252
+ /**
253
+ * @param info data of task
254
+ * @param req - request obj
255
+ * @param db db connection
256
+ * @param event event passed from optimiser to send notifications
257
+ * @description creates notification content
258
+ */
259
+ function CreateNotificationContent(info, req, db, event) {
260
+ return __awaiter(this, void 0, void 0, function () {
261
+ var UserID, Payload, FetchUsers, ListInfo, TaskInfo, users, list, listType, creator, task, oldTaskData, dueDate, NotificationContent, _a, receiverId_1, receiverData_1, senderData_1, taskNotificationType, receiverId_2, receiverData_2, senderData_2, taskNotificationType, bothUsers, senderData_3, receiverData_3;
262
+ return __generator(this, function (_b) {
263
+ switch (_b.label) {
264
+ case 0:
265
+ UserID = new mongodb_1.ObjectID(req.cookies.msp_d.ui);
266
+ Payload = {};
267
+ FetchUsers = function (query) { return db.collection('User').find(query).toArray(); };
268
+ ListInfo = function (id) { return db.collection('TaskList').findOne({ _id: new mongodb_1.ObjectID(id) }); };
269
+ TaskInfo = function (TaskNumber) { return db.collection('Task').findOne({ TaskNumber: TaskNumber }); };
270
+ NotificationContent = {};
271
+ _a = info.page;
272
+ switch (_a) {
273
+ case 'TaskList': return [3 /*break*/, 1];
274
+ case 'Task': return [3 /*break*/, 5];
275
+ case 'Comment': return [3 /*break*/, 21];
276
+ }
277
+ return [3 /*break*/, 25];
278
+ case 1: return [4 /*yield*/, FetchUsers({
279
+ _id: info.isPrivate ? {
280
+ $in: info.users
281
+ } : {
282
+ $ne: UserID
283
+ },
284
+ "UserStatus": { $not: { $eq: "Blocked" } }
285
+ })];
286
+ case 2:
287
+ users = _b.sent();
288
+ return [4 /*yield*/, FetchUsers({
289
+ _id: UserID,
290
+ "UserStatus": { $not: { $eq: "Blocked" } }
291
+ })];
292
+ case 3:
293
+ creator = _b.sent();
294
+ if (users && !users.length && creator && !creator.length)
295
+ return [2 /*return*/];
296
+ creator = creator[0];
297
+ Payload['users'] = users.map(function (u) { return u._id; });
298
+ return [4 /*yield*/, ListInfo(info.ListID)];
299
+ case 4:
300
+ list = _b.sent();
301
+ listType = list.IsMasterList ? 'list' : 'sub-list';
302
+ if (info.event == 'ADDED_TO_LIST') {
303
+ Payload['emails'] = users.map(function (user) {
304
+ return {
305
+ to: user.Email,
306
+ from: constants_1.default.ProjectName + " <" + constants_1.default.SystemEmail + ">",
307
+ subject: "New " + listType + " assigned: " + list.ListName,
308
+ html: utility_1.MailTemplateStructure("\n <p>Hi " + user.FirstName + ",</p>\n <p>You have been added to the following " + listType + " by " + creator.FirstName + " " + creator.LastName + ":</p>\n <p>List:&nbsp; " + list.ListName + "</p>\n " + (list.Description ? "<p>Description:&nbsp; " + list.Description + "</p>" : '') + "\n <p>Please refer to the " + listType + " in Optimiser for any additional information or documents.</p>\n ")
309
+ };
310
+ });
311
+ Payload['pushObj'] = {
312
+ title: "New " + listType + " assigned: " + list.ListName,
313
+ message: creator.FirstName + " " + creator.LastName + " has added you to this " + listType,
314
+ attr: "TaskList:" + list._id + ":" + list.IsMasterList + ":" + list.IsPublic + ":" + list.OwnerID
315
+ };
316
+ Payload['desktopObj'] = {
317
+ EventObjectName: "TaskList",
318
+ EventID: list._id,
319
+ UserIds: Payload['users'],
320
+ Message: creator.FirstName + " " + creator.LastName + " has added you to this " + listType + ": " + list.ListName,
321
+ CreatedBy: creator._id
322
+ };
323
+ TriggerNotifications(list.TaskNotification, Payload, req, db, event);
324
+ }
325
+ return [3 /*break*/, 26];
326
+ case 5:
327
+ if (!!info.fromEdit) return [3 /*break*/, 8];
328
+ return [4 /*yield*/, TaskInfo(info.TaskNumber)];
329
+ case 6:
330
+ task = _b.sent();
331
+ return [4 /*yield*/, ListInfo(task.ListSublist)];
332
+ case 7:
333
+ list = _b.sent();
334
+ _b.label = 8;
335
+ case 8:
336
+ oldTaskData = info.taskBeforeEdit || task;
337
+ if (!(info.event == 'ASSIGNED_A_TASK')) return [3 /*break*/, 14];
338
+ if (!!info.fromEdit) return [3 /*break*/, 11];
339
+ return [4 /*yield*/, FetchUsers({
340
+ _id: info.isPrivate ? {
341
+ $in: info.users
342
+ } : {
343
+ $ne: UserID
344
+ },
345
+ "UserStatus": { $not: { $eq: "Blocked" } }
346
+ })];
347
+ case 9:
348
+ users = _b.sent();
349
+ return [4 /*yield*/, FetchUsers({
350
+ _id: UserID,
351
+ "UserStatus": { $not: { $eq: "Blocked" } }
352
+ })];
353
+ case 10:
354
+ creator = _b.sent();
355
+ creator = creator[0];
356
+ return [3 /*break*/, 13];
357
+ case 11: return [4 /*yield*/, FetchUsers({ _id: new mongodb_1.ObjectID(info.receiverId), "UserStatus": { $not: { $eq: "Blocked" } } })];
358
+ case 12:
359
+ users = _b.sent();
360
+ creator = info.senderData[0];
361
+ task = info.taskBeforeEdit;
362
+ list = info.list;
363
+ _b.label = 13;
364
+ case 13:
365
+ if (users && !users.length && !creator)
366
+ return [2 /*return*/];
367
+ Payload['users'] = users.map(function (u) { return u._id; });
368
+ if (info.body && info.body.DueDate) {
369
+ dueDate = moment_1.default(info.body.DueDate.$date || info.body.DueDate).tz(creator.MySettings.Timezone).format('DD-MM-YYYY h:mm a');
370
+ }
371
+ else {
372
+ dueDate = moment_1.default(task.DueDate).tz(creator.MySettings.Timezone).format('DD-MM-YYYY h:mm a');
373
+ }
374
+ Payload['emails'] = users.map(function (user) {
375
+ /* Mail template with profile picture code in on drive(optimiser/google): Contact: JatinSablok, File_Name: TaskUtility-Mail_with_profile_picture.pdf */
376
+ return {
377
+ to: user.Email,
378
+ from: constants_1.default.ProjectName + " <" + constants_1.default.SystemEmail + ">",
379
+ subject: "New task assigned: " + (info.body.Subject || task.Subject),
380
+ html: utility_1.MailTemplateStructure("\n <p>Hi " + user.FirstName + ",</p>\n <p>You have been assigned with a new task by " + creator.FirstName + " " + creator.LastName + ":</p>\n <p>Task No:&nbsp; " + (info.isPrivate ? info.taskNumbers[user._id] : task.TaskNumber) + "</p>\n <p>Subject:&nbsp; " + (info.body.Subject || task.Subject) + "</p>\n <p>Status:&nbsp; " + task.Status_LookupData.Value + "</p>\n " + (task.DueDate ? "<p>Due:&nbsp; " + dueDate + "</p>" : '') + "\n <p>Please refer to the task in Optimiser for any additional information or documents.</p>\n ")
381
+ };
382
+ });
383
+ Payload['pushObj'] = {
384
+ title: "New task assigned: " + (info.body.Subject || task.Subject),
385
+ message: "You have been assigned a new task by " + creator.FirstName + " " + creator.LastName + " " + (task.DueDate ? " which is due on " + dueDate + "." : '.'),
386
+ attr: "Task:" + task._id + ":" + task.OwnerID
387
+ };
388
+ Payload['desktopObj'] = {
389
+ EventObjectName: "Task",
390
+ EventID: task._id,
391
+ UserIds: Payload['users'],
392
+ Message: creator.FirstName + " " + creator.LastName + " has assigned a task to you: " + (info.body.Subject || task.Subject),
393
+ CreatedBy: creator._id
394
+ };
395
+ TriggerNotifications(list.TaskNotification, Payload, req, db, event);
396
+ return [3 /*break*/, 20];
397
+ case 14:
398
+ if (!(info.event == 'EDIT_TASK')) return [3 /*break*/, 17];
399
+ if ((req.body.AssignedTo ? req.body.AssignedTo.$oid : (oldTaskData.AssignedTo).toString()) == (oldTaskData.OwnerID).toString())
400
+ return [2 /*return*/];
401
+ receiverId_1 = new mongodb_1.ObjectID((req.cookies.msp_d.ui == (oldTaskData.AssignedTo).toString()) ? oldTaskData.OwnerID : (oldTaskData.AssignedTo).toString());
402
+ return [4 /*yield*/, FetchUsers({
403
+ _id: receiverId_1,
404
+ "UserStatus": { $not: { $eq: "Blocked" } }
405
+ })];
406
+ case 15:
407
+ receiverData_1 = _b.sent();
408
+ return [4 /*yield*/, FetchUsers({
409
+ _id: UserID,
410
+ "UserStatus": { $not: { $eq: "Blocked" } }
411
+ })];
412
+ case 16:
413
+ senderData_1 = _b.sent();
414
+ if (receiverData_1 && !receiverData_1.length && senderData_1 && !senderData_1.length)
415
+ return [2 /*return*/];
416
+ Payload['users'] = receiverData_1.map(function (u) { return u._id; });
417
+ if (req.body.DueDate && req.body.DueDate.$date) {
418
+ dueDate = moment_1.default(req.body.DueDate.$date).tz(receiverData_1[0].MySettings.Timezone).format('DD-MM-YYYY h:mm a');
419
+ }
420
+ taskNotificationType = [];
421
+ if (oldTaskData.Status != req.body.Status) {
422
+ taskNotificationType.push("STATUS");
423
+ }
424
+ ;
425
+ if (oldTaskData.Subject != req.body.Subject) {
426
+ taskNotificationType.push("SUBJECT");
427
+ }
428
+ ;
429
+ if (req.body.DueDate && (new Date(oldTaskData.DueDate).getTime() != new Date(req.body.DueDate.$date || req.body.DueDate).getTime())) {
430
+ taskNotificationType.push("DUE_DATE");
431
+ }
432
+ ;
433
+ if ((oldTaskData.AssignedTo).toString() != req.body.AssignedTo.$oid) {
434
+ taskNotificationType.push("TASK_OWNER");
435
+ CreateNotificationContent({
436
+ page: "Task",
437
+ event: 'ASSIGNED_A_TASK',
438
+ fromEdit: true,
439
+ senderData: senderData_1,
440
+ taskBeforeEdit: oldTaskData,
441
+ list: list,
442
+ receiverId: req.body.AssignedTo.$oid,
443
+ body: req.body
444
+ }, req, db, event);
445
+ }
446
+ ;
447
+ if (taskNotificationType.length) {
448
+ taskNotificationType.map(function (value) {
449
+ switch (value) {
450
+ case "DUE_DATE":
451
+ NotificationContent.subject = senderData_1[0].FirstName + " " + senderData_1[0].LastName + " has updated due date of " + req.body.TaskNumber + " - " + req.body.Subject;
452
+ NotificationContent.contentChange = "due date";
453
+ break;
454
+ case "SUBJECT":
455
+ NotificationContent.subject = senderData_1[0].FirstName + " " + senderData_1[0].LastName + " has updated subject of " + req.body.TaskNumber + " - " + req.body.Subject;
456
+ NotificationContent.contentChange = "subject";
457
+ break;
458
+ case "STATUS":
459
+ NotificationContent.subject = senderData_1[0].FirstName + " " + senderData_1[0].LastName + " has updated status of " + req.body.TaskNumber + " - " + req.body.Subject;
460
+ NotificationContent.contentChange = "status";
461
+ break;
462
+ case "TASK_OWNER":
463
+ NotificationContent.subject = senderData_1[0].FirstName + " " + senderData_1[0].LastName + " has updated task owner of " + req.body.TaskNumber + " - " + req.body.Subject;
464
+ NotificationContent.contentChange = "task owner";
465
+ break;
466
+ default:
467
+ break;
468
+ }
469
+ Payload['emails'] = receiverData_1.map(function (user) {
470
+ return {
471
+ to: user.Email,
472
+ from: constants_1.default.ProjectName + " <" + constants_1.default.SystemEmail + ">",
473
+ subject: NotificationContent.subject,
474
+ html: utility_1.MailTemplateStructure("\n <p>Hi " + user.FirstName + ",</p>\n <p>" + NotificationContent.subject + "</p>\n <p>Task No:&nbsp; " + task.TaskNumber + "</p>\n <p>Subject:&nbsp; " + req.body.Subject + "</p>\n <p>Status:&nbsp; " + task.Status_LookupData.Value + "</p>\n " + (req.body.DueDate ? "<p>Due:&nbsp; " + dueDate + "</p>" : '') + "\n <p>Please refer to the task in Optimiser for any additional information or documents.</p>\n ")
475
+ };
476
+ });
477
+ Payload['pushObj'] = {
478
+ title: "Task updated : " + req.body.Subject,
479
+ message: "" + NotificationContent.subject,
480
+ attr: "Task:" + req.body._id
481
+ };
482
+ Payload['desktopObj'] = {
483
+ EventObjectName: "Task",
484
+ EventID: req.body._id,
485
+ UserIds: [receiverId_1],
486
+ Message: "" + NotificationContent.subject,
487
+ CreatedBy: senderData_1[0]._id
488
+ };
489
+ TriggerNotifications(list.TaskNotification, Payload, req, db, event);
490
+ });
491
+ }
492
+ return [3 /*break*/, 20];
493
+ case 17:
494
+ if (!(info.event == "EDIT_TASK_INLINE")) return [3 /*break*/, 20];
495
+ receiverId_2 = new mongodb_1.ObjectID((req.cookies.msp_d.ui == (oldTaskData.AssignedTo).toString()) ? oldTaskData.OwnerID : (oldTaskData.AssignedTo).toString());
496
+ return [4 /*yield*/, FetchUsers({ _id: receiverId_2, "UserStatus": { $not: { $eq: "Blocked" } } })];
497
+ case 18:
498
+ receiverData_2 = _b.sent();
499
+ return [4 /*yield*/, FetchUsers({ _id: UserID, "UserStatus": { $not: { $eq: "Blocked" } } })];
500
+ case 19:
501
+ senderData_2 = _b.sent();
502
+ if (receiverData_2 && receiverData_2.length && senderData_2 && senderData_2.length && (receiverData_2[0]._id).toString() == (senderData_2[0]._id).toString())
503
+ return [2 /*return*/];
504
+ Payload['users'] = receiverData_2.map(function (u) { return u._id; });
505
+ if (info.body.DueDate && info.body.DueDate.$date) {
506
+ dueDate = moment_1.default((info.body.DueDate ? info.body.DueDate.$date : null) || task.DueDate).tz(receiverData_2[0].MySettings.Timezone).format('DD-MM-YYYY h:mm a');
507
+ }
508
+ taskNotificationType = [];
509
+ if (info.body && info.body.Subject && info.body.Subject != oldTaskData.Subject) {
510
+ taskNotificationType.push("SUBJECT");
511
+ }
512
+ if (info.body && info.body.Status && info.body.Status != oldTaskData.Status) {
513
+ taskNotificationType.push("STATUS");
514
+ }
515
+ if (info.body && info.body.DueDate && info.body.DueDate.$date && info.body.DueDate.$date != oldTaskData.DueDate) {
516
+ taskNotificationType.push("DUE_DATE");
517
+ }
518
+ if (info.body && info.body.AssignedTo && info.body.AssignedTo.$oid && info.body.AssignedTo.$oid != (oldTaskData.AssignedTo).toString()) {
519
+ taskNotificationType.push("TASK_OWNER");
520
+ CreateNotificationContent({
521
+ page: "Task",
522
+ event: 'ASSIGNED_A_TASK',
523
+ fromEdit: true,
524
+ senderData: senderData_2,
525
+ taskBeforeEdit: oldTaskData,
526
+ list: list,
527
+ receiverId: info.body.AssignedTo.$oid,
528
+ body: info.body
529
+ }, req, db, event);
530
+ }
531
+ if (taskNotificationType.length) {
532
+ taskNotificationType.map(function (value) {
533
+ switch (value) {
534
+ case "DUE_DATE":
535
+ NotificationContent.subject = senderData_2[0].FirstName + " " + senderData_2[0].LastName + " has updated due date of " + task.TaskNumber + " - " + (info.body.Subject || oldTaskData.Subject);
536
+ NotificationContent.contentChange = "due date";
537
+ break;
538
+ case "SUBJECT":
539
+ NotificationContent.subject = senderData_2[0].FirstName + " " + senderData_2[0].LastName + " has updated subject of " + task.TaskNumber + " - " + (info.body.Subject || oldTaskData.Subject);
540
+ NotificationContent.contentChange = "subject";
541
+ break;
542
+ case "STATUS":
543
+ NotificationContent.subject = senderData_2[0].FirstName + " " + senderData_2[0].LastName + " has updated status of " + task.TaskNumber + " - " + (info.body.Subject || oldTaskData.Subject);
544
+ NotificationContent.contentChange = "status";
545
+ break;
546
+ case "TASK_OWNER":
547
+ NotificationContent.subject = senderData_2[0].FirstName + " " + senderData_2[0].LastName + " has updated task owner of " + task.TaskNumber + " - " + (info.body.Subject || oldTaskData.Subject);
548
+ NotificationContent.contentChange = "task owner";
549
+ break;
550
+ default:
551
+ break;
552
+ }
553
+ Payload['emails'] = receiverData_2.map(function (user) {
554
+ return {
555
+ to: user.Email,
556
+ from: constants_1.default.ProjectName + " <" + constants_1.default.SystemEmail + ">",
557
+ subject: NotificationContent.subject,
558
+ html: utility_1.MailTemplateStructure("\n <p>Hi " + user.FirstName + ",</p>\n <p>" + NotificationContent.subject + "</p>\n <p>Task No:&nbsp; " + task.TaskNumber + "</p>\n <p>Subject:&nbsp; " + (info.body.Subject || task.Subject) + "</p>\n <p>Status:&nbsp; " + task.Status_LookupData.Value + "</p>\n " + (dueDate ? "<p>Due:&nbsp; " + dueDate + "</p>" : '') + "\n <p>Please refer to the task in Optimiser for any additional information or documents.</p>\n ")
559
+ };
560
+ });
561
+ Payload['pushObj'] = {
562
+ title: "Task updated : " + (info.body.Subject || task.Subject),
563
+ message: "" + NotificationContent.subject,
564
+ attr: "Task:" + task._id
565
+ };
566
+ Payload['desktopObj'] = {
567
+ EventObjectName: "Task",
568
+ EventID: task._id,
569
+ UserIds: [receiverId_2],
570
+ Message: "" + NotificationContent.subject,
571
+ CreatedBy: senderData_2[0]._id
572
+ };
573
+ TriggerNotifications(list.TaskNotification, Payload, req, db, event);
574
+ });
575
+ }
576
+ _b.label = 20;
577
+ case 20: return [3 /*break*/, 26];
578
+ case 21:
579
+ list = info.list;
580
+ return [4 /*yield*/, FetchUsers({
581
+ $or: [
582
+ { _id: info.task.AssignedTo },
583
+ { _id: info.task.OwnerID }
584
+ ], "UserStatus": { $not: { $eq: "Blocked" } }
585
+ })];
586
+ case 22:
587
+ bothUsers = _b.sent();
588
+ if (bothUsers && !bothUsers.length)
589
+ return [2 /*return*/]; /* If creator and task owner are same. */
590
+ receiverData_3 = [];
591
+ task = info["task"];
592
+ bothUsers.map(function (user) {
593
+ if ((user._id).toString() == req.cookies.msp_d.ui) {
594
+ senderData_3 = user;
595
+ }
596
+ else {
597
+ receiverData_3.push(user);
598
+ }
599
+ });
600
+ if (!!(bothUsers.find(function (u) { return u._id == req.cookies.msp_d.ui; }))) return [3 /*break*/, 24];
601
+ return [4 /*yield*/, FetchUsers({ _id: UserID })];
602
+ case 23:
603
+ senderData_3 = _b.sent();
604
+ senderData_3 = senderData_3[0];
605
+ _b.label = 24;
606
+ case 24:
607
+ Payload['users'] = receiverData_3.map(function (u) { return u._id; });
608
+ switch (info.event) {
609
+ case "COMMENT_ADDED":
610
+ NotificationContent.subject = senderData_3.FirstName + " " + senderData_3.LastName + " has added a comment " + task.TaskNumber + " - " + task.Subject + ".";
611
+ NotificationContent.contentChange = "added";
612
+ break;
613
+ case "COMMENT_UPDATED":
614
+ NotificationContent.subject = senderData_3.FirstName + " " + senderData_3.LastName + " has updated a comment " + task.TaskNumber + " - " + task.Subject + ".";
615
+ NotificationContent.contentChange = "updated";
616
+ break;
617
+ case "COMMENT_DELETED":
618
+ NotificationContent.subject = senderData_3.FirstName + " " + senderData_3.LastName + " has deleted a comment " + task.TaskNumber + " - " + task.Subject + ".";
619
+ NotificationContent.contentChange = "deleted";
620
+ break;
621
+ default:
622
+ break;
623
+ }
624
+ Payload['emails'] = receiverData_3.map(function (user) {
625
+ if (user && user.MySettings && task.DueDate) {
626
+ dueDate = moment_1.default(task.DueDate).tz(user.MySettings.Timezone).format('DD-MM-YYYY h:mm a');
627
+ }
628
+ return {
629
+ to: user.Email,
630
+ from: constants_1.default.ProjectName + " <" + constants_1.default.SystemEmail + ">",
631
+ subject: NotificationContent.subject,
632
+ html: utility_1.MailTemplateStructure("\n <p>Hi " + user.FirstName + ",</p>\n <p>" + NotificationContent.subject + "</p>\n <p>Task No:&nbsp; " + task.TaskNumber + "</p>\n <p>Subject:&nbsp; " + task.Subject + "</p>\n <p>Status:&nbsp; " + task.Status_LookupData.Value + "</p>\n " + (task.DueDate ? "<p>Due:&nbsp; " + dueDate + "</p>" : '') + "\n <p>Please refer to the task in Optimiser for any additional information or documents.</p>\n ")
633
+ };
634
+ });
635
+ Payload['pushObj'] = {
636
+ title: NotificationContent.subject,
637
+ message: senderData_3.FirstName + " has " + NotificationContent.contentChange + " a comment.",
638
+ attr: "Task:" + task._id
639
+ };
640
+ /* Bell Notification. */
641
+ Payload['desktopObj'] = {
642
+ EventObjectName: "Task",
643
+ EventID: task._id,
644
+ UserIds: Payload['users'],
645
+ Message: NotificationContent.subject,
646
+ CreatedBy: senderData_3._id
647
+ };
648
+ TriggerNotifications(list.TaskNotification, Payload, req, db, event);
649
+ return [3 /*break*/, 26];
650
+ case 25: return [3 /*break*/, 26];
651
+ case 26: return [2 /*return*/];
652
+ }
653
+ });
654
+ });
655
+ }
656
+ exports.CreateNotificationContent = CreateNotificationContent;
@@ -185,4 +185,5 @@ declare function GetUserProfile(msp_d: AnyObjectInterface, db: Db, mdb: Db, next
185
185
  */
186
186
  declare function ErrorHandlerForServices(Error: OPT_ERROR, ServiceOrigin: string, EmailConfig: any, Module?: string, db?: Db): Promise<any>;
187
187
  declare function CheckCaptcha(token: string, captcha: string, redisClient: Redis): Promise<unknown>;
188
- export { CheckForWhiteListedDomain, ReturnJsonResponse, ConvertFileByteSize, GetObjectByKeyValueFromList, IsEqualArrays, IsEqualValue, CheckUserProfileField, GetPageFieldData, GetPageObjectSchema, GetFieldDetail, UpdateRecentViewObject, SyncChildObjectData, SyncParentObjectData, DeleteFieldInOtherCollection, SyncFieldInSameCollection, SyncFieldInSameCollectionByObjectID, SyncFieldInSameCollectionByObjectIDWithPromise, SyncFieldInOtherCollection, SyncUserInOtherCollection, BuildLookupDataField, CheckDataBeforeAdd, CheckDataBeforeUpdate, BuildGridFieldProjection, BuildFieldProjection, BuildLookupFieldProjection, FilterConditions, GirdHeaderFilters, AddLog, CheckFilterFieldsProjection, VerifyEmailPassword, GetMyTeamUsers, ExtractChildUsersTree, GetMaxKeyValueListSchema, VerifyAWSEmailConfig, GenerateId, SyncUserDetailsWithMasterDB, SignoutUserFromAllDevices, SignoutUsersWithPromise, SignoutMultipleUsersFromAllDevices, UserLicenseConsumeCalculate, sendMailWithUserAccount, GetEmailClientConfigs, GetCompanyEncryptionKey, ExecuteDynamicDMLQuery, ExecuteDynamicDQLQuery, GetUserProfilePermissions, MakeUserPasswordInvalid, ConvertJsonToXLXS, SendResetPasswordMail, SendMailToSupport, MailTemplateStructure, SendMailToCustomer, parseMSPCookie, GetIPDetailsFromReq, isEmptyObj, SyncListSchemaFieldInOtherCollection, UpdateTagCountAfterDelete, SyncTagCountAfterUpdate, ReactivateFieldInOtherCollection, SyncUserLicenceConsumedCount, BroadCastEventToAllCompanyUsers, CheckDataPermission, SyncCompanyLicenceInMasterCompanyAfterAdd, NextServiceDateForDashboard, CheckDateNotInPast, GetWeekDayByDayAndOccurance, GetInterValFromOccurance, GetWeekDayInfoInMonth, GetDayIndex, GetUserProfile, ErrorHandlerForServices, CheckCaptcha };
188
+ declare function ValidateSanitizeUserInput(inputFields: AnyObjectInterface, pageData: AnyObjectInterface): Promise<AnyObjectInterface[] | undefined>;
189
+ export { CheckForWhiteListedDomain, ReturnJsonResponse, ConvertFileByteSize, GetObjectByKeyValueFromList, IsEqualArrays, IsEqualValue, CheckUserProfileField, GetPageFieldData, GetPageObjectSchema, GetFieldDetail, UpdateRecentViewObject, SyncChildObjectData, SyncParentObjectData, DeleteFieldInOtherCollection, SyncFieldInSameCollection, SyncFieldInSameCollectionByObjectID, SyncFieldInSameCollectionByObjectIDWithPromise, SyncFieldInOtherCollection, SyncUserInOtherCollection, BuildLookupDataField, CheckDataBeforeAdd, CheckDataBeforeUpdate, BuildGridFieldProjection, BuildFieldProjection, BuildLookupFieldProjection, FilterConditions, GirdHeaderFilters, AddLog, CheckFilterFieldsProjection, VerifyEmailPassword, GetMyTeamUsers, ExtractChildUsersTree, GetMaxKeyValueListSchema, VerifyAWSEmailConfig, GenerateId, SyncUserDetailsWithMasterDB, SignoutUserFromAllDevices, SignoutUsersWithPromise, SignoutMultipleUsersFromAllDevices, UserLicenseConsumeCalculate, sendMailWithUserAccount, GetEmailClientConfigs, GetCompanyEncryptionKey, ExecuteDynamicDMLQuery, ExecuteDynamicDQLQuery, GetUserProfilePermissions, MakeUserPasswordInvalid, ConvertJsonToXLXS, SendResetPasswordMail, SendMailToSupport, MailTemplateStructure, SendMailToCustomer, parseMSPCookie, GetIPDetailsFromReq, isEmptyObj, SyncListSchemaFieldInOtherCollection, UpdateTagCountAfterDelete, SyncTagCountAfterUpdate, ReactivateFieldInOtherCollection, SyncUserLicenceConsumedCount, BroadCastEventToAllCompanyUsers, CheckDataPermission, SyncCompanyLicenceInMasterCompanyAfterAdd, NextServiceDateForDashboard, CheckDateNotInPast, GetWeekDayByDayAndOccurance, GetInterValFromOccurance, GetWeekDayInfoInMonth, GetDayIndex, GetUserProfile, ErrorHandlerForServices, CheckCaptcha, ValidateSanitizeUserInput };
@@ -80,7 +80,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
80
80
  return (mod && mod.__esModule) ? mod : { "default": mod };
81
81
  };
82
82
  Object.defineProperty(exports, "__esModule", { value: true });
83
- exports.CheckCaptcha = exports.ErrorHandlerForServices = exports.GetUserProfile = exports.GetDayIndex = exports.GetWeekDayInfoInMonth = exports.GetInterValFromOccurance = exports.GetWeekDayByDayAndOccurance = exports.CheckDateNotInPast = exports.NextServiceDateForDashboard = exports.SyncCompanyLicenceInMasterCompanyAfterAdd = exports.CheckDataPermission = exports.BroadCastEventToAllCompanyUsers = exports.SyncUserLicenceConsumedCount = exports.ReactivateFieldInOtherCollection = exports.SyncTagCountAfterUpdate = exports.UpdateTagCountAfterDelete = exports.SyncListSchemaFieldInOtherCollection = exports.isEmptyObj = exports.GetIPDetailsFromReq = exports.parseMSPCookie = exports.SendMailToCustomer = exports.MailTemplateStructure = exports.SendMailToSupport = exports.SendResetPasswordMail = exports.ConvertJsonToXLXS = exports.MakeUserPasswordInvalid = exports.GetUserProfilePermissions = exports.ExecuteDynamicDQLQuery = exports.ExecuteDynamicDMLQuery = exports.GetCompanyEncryptionKey = exports.GetEmailClientConfigs = exports.sendMailWithUserAccount = exports.UserLicenseConsumeCalculate = exports.SignoutMultipleUsersFromAllDevices = exports.SignoutUsersWithPromise = exports.SignoutUserFromAllDevices = exports.SyncUserDetailsWithMasterDB = exports.GenerateId = exports.VerifyAWSEmailConfig = exports.GetMaxKeyValueListSchema = exports.ExtractChildUsersTree = exports.GetMyTeamUsers = exports.VerifyEmailPassword = exports.CheckFilterFieldsProjection = exports.AddLog = exports.GirdHeaderFilters = exports.FilterConditions = exports.BuildLookupFieldProjection = exports.BuildFieldProjection = exports.BuildGridFieldProjection = exports.CheckDataBeforeUpdate = exports.CheckDataBeforeAdd = exports.BuildLookupDataField = exports.SyncUserInOtherCollection = exports.SyncFieldInOtherCollection = exports.SyncFieldInSameCollectionByObjectIDWithPromise = exports.SyncFieldInSameCollectionByObjectID = exports.SyncFieldInSameCollection = exports.DeleteFieldInOtherCollection = exports.SyncParentObjectData = exports.SyncChildObjectData = exports.UpdateRecentViewObject = exports.GetFieldDetail = exports.GetPageObjectSchema = exports.GetPageFieldData = exports.CheckUserProfileField = exports.IsEqualValue = exports.IsEqualArrays = exports.GetObjectByKeyValueFromList = exports.ConvertFileByteSize = exports.ReturnJsonResponse = exports.CheckForWhiteListedDomain = void 0;
83
+ exports.ValidateSanitizeUserInput = exports.CheckCaptcha = exports.ErrorHandlerForServices = exports.GetUserProfile = exports.GetDayIndex = exports.GetWeekDayInfoInMonth = exports.GetInterValFromOccurance = exports.GetWeekDayByDayAndOccurance = exports.CheckDateNotInPast = exports.NextServiceDateForDashboard = exports.SyncCompanyLicenceInMasterCompanyAfterAdd = exports.CheckDataPermission = exports.BroadCastEventToAllCompanyUsers = exports.SyncUserLicenceConsumedCount = exports.ReactivateFieldInOtherCollection = exports.SyncTagCountAfterUpdate = exports.UpdateTagCountAfterDelete = exports.SyncListSchemaFieldInOtherCollection = exports.isEmptyObj = exports.GetIPDetailsFromReq = exports.parseMSPCookie = exports.SendMailToCustomer = exports.MailTemplateStructure = exports.SendMailToSupport = exports.SendResetPasswordMail = exports.ConvertJsonToXLXS = exports.MakeUserPasswordInvalid = exports.GetUserProfilePermissions = exports.ExecuteDynamicDQLQuery = exports.ExecuteDynamicDMLQuery = exports.GetCompanyEncryptionKey = exports.GetEmailClientConfigs = exports.sendMailWithUserAccount = exports.UserLicenseConsumeCalculate = exports.SignoutMultipleUsersFromAllDevices = exports.SignoutUsersWithPromise = exports.SignoutUserFromAllDevices = exports.SyncUserDetailsWithMasterDB = exports.GenerateId = exports.VerifyAWSEmailConfig = exports.GetMaxKeyValueListSchema = exports.ExtractChildUsersTree = exports.GetMyTeamUsers = exports.VerifyEmailPassword = exports.CheckFilterFieldsProjection = exports.AddLog = exports.GirdHeaderFilters = exports.FilterConditions = exports.BuildLookupFieldProjection = exports.BuildFieldProjection = exports.BuildGridFieldProjection = exports.CheckDataBeforeUpdate = exports.CheckDataBeforeAdd = exports.BuildLookupDataField = exports.SyncUserInOtherCollection = exports.SyncFieldInOtherCollection = exports.SyncFieldInSameCollectionByObjectIDWithPromise = exports.SyncFieldInSameCollectionByObjectID = exports.SyncFieldInSameCollection = exports.DeleteFieldInOtherCollection = exports.SyncParentObjectData = exports.SyncChildObjectData = exports.UpdateRecentViewObject = exports.GetFieldDetail = exports.GetPageObjectSchema = exports.GetPageFieldData = exports.CheckUserProfileField = exports.IsEqualValue = exports.IsEqualArrays = exports.GetObjectByKeyValueFromList = exports.ConvertFileByteSize = exports.ReturnJsonResponse = exports.CheckForWhiteListedDomain = void 0;
84
84
  var moment_1 = __importDefault(require("moment"));
85
85
  var nodemailer_1 = __importDefault(require("nodemailer"));
86
86
  var mongodb_1 = require("mongodb");
@@ -96,6 +96,7 @@ var errorHandlerForServices_1 = __importDefault(require("../utility/errorHandler
96
96
  var cryptoService = __importStar(require("../utility/crypto"));
97
97
  var https_1 = __importDefault(require("https"));
98
98
  require("moment-timezone");
99
+ var sanitize = require('mongo-sanitize');
99
100
  function GetObjectByKeyValueFromList(list, key, val) {
100
101
  if (list && list.length > 0) {
101
102
  for (var i = 0; i < list.length; i++) {
@@ -3806,6 +3807,14 @@ function ErrorHandlerForServices(Error, ServiceOrigin, EmailConfig, Module, db)
3806
3807
  });
3807
3808
  }
3808
3809
  exports.ErrorHandlerForServices = ErrorHandlerForServices;
3810
+ /*
3811
+ * Created by: Brijesh and edited by Shazaib as on 15-11-21
3812
+ * Desc: This function is used for verifying captcha
3813
+ * @param1: token (from user form)
3814
+ * @param2: captcha code (from user form)
3815
+ * @param3: redisClient , object of the redis client.
3816
+ * return value: message string
3817
+ */
3809
3818
  function CheckCaptcha(token, captcha, redisClient) {
3810
3819
  return new Promise(function (resolve, reject) {
3811
3820
  redisClient.hgetall(token, function (err, data) {
@@ -3829,3 +3838,94 @@ function CheckCaptcha(token, captcha, redisClient) {
3829
3838
  });
3830
3839
  }
3831
3840
  exports.CheckCaptcha = CheckCaptcha;
3841
+ /*
3842
+ * this function isused tp capitalized first latter of a string.
3843
+ * @param1: string ex: 'lazy boy'
3844
+ * return value: Lazy boy else false if value is not a string
3845
+ */
3846
+ function CapitalizeFirstLetter(str) {
3847
+ if (typeof str !== 'string' || !str) {
3848
+ return false;
3849
+ }
3850
+ return str.charAt(0).toUpperCase() + str.slice(1);
3851
+ }
3852
+ function EmailValidation(elmValue) {
3853
+ var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
3854
+ if (filter.test(elmValue)) {
3855
+ return true;
3856
+ }
3857
+ return false;
3858
+ }
3859
+ /*
3860
+ * Created by: Mohan as on 09-11-21
3861
+ * This is a common function and used to validate and sanitise user input.
3862
+ * @param1: inputFields (from user form)
3863
+ * {
3864
+ OwnerID: { '$oid': '6123438f6693ea0012919e9a' },
3865
+ Salutation: '1',
3866
+ FirstName: 'Santa',
3867
+ LastName: 'Singh',
3868
+ VIPStatus: null,
3869
+ OperaProfileId: null
3870
+ }
3871
+
3872
+ * @param2: pageData objectdata from ObjectSchema collection
3873
+ * Desc: This fuinction maps all fields from user form with objectdata from ObjectSchema collection.
3874
+ * return value: array.
3875
+ * example: [{"msg":'Invalid email'}, {all validated and sanitized fields with key:value}]
3876
+ */
3877
+ function ValidateSanitizeUserInput(inputFields, pageData) {
3878
+ return __awaiter(this, void 0, void 0, function () {
3879
+ var objElement, inputItem, key, val, sanitizeInput, msg, _i, _a, item, elm, elmValue;
3880
+ return __generator(this, function (_b) {
3881
+ try {
3882
+ objElement = {};
3883
+ inputItem = {};
3884
+ for (key in inputFields) {
3885
+ if (inputFields.hasOwnProperty(key)) {
3886
+ val = inputFields[key];
3887
+ //if (val !== null && (typeof val === 'object' || mongodb.ObjectID.isValid(val))) {
3888
+ if (val !== null && (typeof val === 'object' || mongodb_1.ObjectID.isValid(val))) {
3889
+ inputItem[key] = val;
3890
+ }
3891
+ else {
3892
+ inputItem[key] = (typeof val === 'string') ? sanitize(val.toString().trim()) : sanitize(val); // sanitize input values
3893
+ }
3894
+ objElement[key] = inputItem[key];
3895
+ }
3896
+ }
3897
+ sanitizeInput = [];
3898
+ msg = '';
3899
+ for (_i = 0, _a = pageData.Fields; _i < _a.length; _i++) {
3900
+ item = _a[_i];
3901
+ elm = item.Name.toString();
3902
+ elmValue = inputItem[elm];
3903
+ if (item.IsRequired == true && item.IsRequired !== undefined) {
3904
+ // check for required input fileds
3905
+ if (elmValue && item.UIDataType == 'email' && elmValue != '' && elmValue != null && elmValue !== undefined) {
3906
+ if (!EmailValidation(elmValue.toString())) {
3907
+ msg = 'Invalid email format!';
3908
+ }
3909
+ }
3910
+ else {
3911
+ // other required field
3912
+ if (elmValue == '' || elmValue == 'null' || elmValue === null) {
3913
+ msg = CapitalizeFirstLetter(item.DisplayName) + ' is required!';
3914
+ }
3915
+ }
3916
+ }
3917
+ // }
3918
+ }
3919
+ sanitizeInput.push({ "msg": msg });
3920
+ sanitizeInput.push(objElement);
3921
+ //console.log("=============>",sanitizeInput);
3922
+ return [2 /*return*/, sanitizeInput];
3923
+ }
3924
+ catch (err) {
3925
+ console.log("Error in validateSanitizeUserInput() in utility.js: ", err);
3926
+ }
3927
+ return [2 /*return*/];
3928
+ });
3929
+ });
3930
+ }
3931
+ exports.ValidateSanitizeUserInput = ValidateSanitizeUserInput;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optimiser/common",
3
- "version": "1.0.225",
3
+ "version": "1.0.229",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -30,6 +30,7 @@
30
30
  "libphonenumber-js": "^1.9.23",
31
31
  "moment": "^2.25.3",
32
32
  "moment-timezone": "^0.5.27",
33
+ "mongo-sanitize": "^1.1.0",
33
34
  "mongodb": "^3.6.2",
34
35
  "nodemailer": "^6.4.11",
35
36
  "promise.allsettled": "^1.0.2",