@tiledesk/tiledesk-server 2.4.99 → 2.4.101

Sign up to get free protection for your applications and to get access to all the features.
@@ -3,6 +3,7 @@
3
3
  var departmentService = require('../services/departmentService');
4
4
  var Request = require("../models/request");
5
5
  var Project_user = require("../models/project_user");
6
+ var Project = require("../models/project");
6
7
  var messageService = require('../services/messageService');
7
8
  const requestEvent = require('../event/requestEvent');
8
9
  const leadEvent = require('../event/leadEvent');
@@ -13,6 +14,16 @@ var cacheUtil = require("../utils/cacheUtil");
13
14
  var arrayUtil = require("../utils/arrayUtil");
14
15
  var cacheEnabler = require("../services/cacheEnabler");
15
16
  var UIDGenerator = require("../utils/UIDGenerator");
17
+ const { TdCache } = require('../utils/TdCache');
18
+ const { QuoteManager } = require('./QuoteManager');
19
+
20
+ let tdCache = new TdCache({
21
+ host: process.env.CACHE_REDIS_HOST,
22
+ port: process.env.CACHE_REDIS_PORT,
23
+ password: process.env.CACHE_REDIS_PASSWORD
24
+ });
25
+ tdCache.connect();
26
+ let qm = new QuoteManager({ tdCache: tdCache });
16
27
 
17
28
  class RequestService {
18
29
 
@@ -25,355 +36,357 @@ class RequestService {
25
36
  this.sendMessageUpdateLead();
26
37
  }
27
38
  updateSnapshotLead() {
28
- leadEvent.on('lead.update', function(lead) {
39
+ leadEvent.on('lead.update', function (lead) {
29
40
  setImmediate(() => {
30
- winston.debug("updateSnapshotLead on lead.update ", lead);
31
-
32
- Request.updateMany({lead: lead._id, id_project: lead.id_project}, {"$set": {"snapshot.lead": lead}}, function (err, updates) {
33
- if (err) {
34
- winston.error("Error updating requests updateSnapshotLead", err);
35
- return 0;
36
- }
37
- winston.verbose("updateSnapshotLead updated for " + updates.nModified + " request")
38
- requestEvent.emit('request.update.snapshot.lead',{lead:lead,updates:updates});
39
- return;
40
- });
41
- // Request.find({lead: lead._id, id_project: lead.id_project}, function(err, requests) {
41
+ winston.debug("updateSnapshotLead on lead.update ", lead);
42
42
 
43
- // if (err) {
44
- // winston.error("Error getting request by lead", err);
45
- // return 0;
46
- // }
47
- // if (!requests || (requests && requests.length==0)) {
48
- // winston.warn("No request found for lead id " +lead._id );
49
- // return 0;
50
- // }
51
-
52
- // requests.forEach(function(request) {
53
-
43
+ Request.updateMany({ lead: lead._id, id_project: lead.id_project }, { "$set": { "snapshot.lead": lead } }, function (err, updates) {
44
+ if (err) {
45
+ winston.error("Error updating requests updateSnapshotLead", err);
46
+ return 0;
47
+ }
48
+ winston.verbose("updateSnapshotLead updated for " + updates.nModified + " request")
49
+ requestEvent.emit('request.update.snapshot.lead', { lead: lead, updates: updates });
50
+ return;
51
+ });
52
+ // Request.find({lead: lead._id, id_project: lead.id_project}, function(err, requests) {
54
53
 
55
- // });
54
+ // if (err) {
55
+ // winston.error("Error getting request by lead", err);
56
+ // return 0;
57
+ // }
58
+ // if (!requests || (requests && requests.length==0)) {
59
+ // winston.warn("No request found for lead id " +lead._id );
60
+ // return 0;
61
+ // }
56
62
 
57
- // });
63
+ // requests.forEach(function(request) {
58
64
 
59
65
 
60
- });
61
- });
66
+ // });
67
+
68
+ // });
69
+
70
+
71
+ });
72
+ });
62
73
  }
63
74
 
64
75
 
65
76
  sendMessageUpdateLead() {
66
- leadEvent.on('lead.fullname.email.update', function(lead) {
77
+ leadEvent.on('lead.fullname.email.update', function (lead) {
67
78
  winston.debug("lead.fullname.email.update ");
68
79
  // leadEvent.on('lead.update', function(lead) {
69
-
80
+
70
81
  setImmediate(() => {
71
- winston.debug("sendMessageUpdateLead on lead.update ", lead);
72
-
73
- Request.find({lead: lead._id, id_project: lead.id_project}, function(err, requests) {
82
+ winston.debug("sendMessageUpdateLead on lead.update ", lead);
74
83
 
75
- if (err) {
76
- winston.error("Error getting sendMessageUpdateLead request by lead", err);
77
- return 0;
78
- }
79
- if (!requests || (requests && requests.length==0)) {
80
- winston.warn("sendMessageUpdateLead No request found for lead id " +lead._id );
81
- return 0;
82
- }
83
-
84
- // winston.info("sendMessageUpdateLead requests ", requests);
85
-
86
- requests.forEach(function(request) {
87
-
88
- winston.debug("sendMessageUpdateLead request ", request);
89
-
90
- // send(sender, senderFullname, recipient, text, id_project, createdBy, attributes, type, metadata, language)
91
- messageService.send(
92
- 'system',
93
- 'Bot',
94
- // lead.fullname,
95
- request.request_id,
96
- "Lead updated",
97
- request.id_project,
98
- 'system',
99
- {
100
- subtype:"info/support",
101
- "updateconversation" : false,
102
- messagelabel: {key: "LEAD_UPDATED"},
103
- updateUserEmail: lead.email,
104
- updateUserFullname: lead.fullname
105
- },
106
- undefined,
107
- request.language
108
-
109
- );
84
+ Request.find({ lead: lead._id, id_project: lead.id_project }, function (err, requests) {
110
85
 
111
- });
86
+ if (err) {
87
+ winston.error("Error getting sendMessageUpdateLead request by lead", err);
88
+ return 0;
89
+ }
90
+ if (!requests || (requests && requests.length == 0)) {
91
+ winston.warn("sendMessageUpdateLead No request found for lead id " + lead._id);
92
+ return 0;
93
+ }
94
+
95
+ // winston.info("sendMessageUpdateLead requests ", requests);
96
+
97
+ requests.forEach(function (request) {
98
+
99
+ winston.debug("sendMessageUpdateLead request ", request);
100
+
101
+ // send(sender, senderFullname, recipient, text, id_project, createdBy, attributes, type, metadata, language)
102
+ messageService.send(
103
+ 'system',
104
+ 'Bot',
105
+ // lead.fullname,
106
+ request.request_id,
107
+ "Lead updated",
108
+ request.id_project,
109
+ 'system',
110
+ {
111
+ subtype: "info/support",
112
+ "updateconversation": false,
113
+ messagelabel: { key: "LEAD_UPDATED" },
114
+ updateUserEmail: lead.email,
115
+ updateUserFullname: lead.fullname
116
+ },
117
+ undefined,
118
+ request.language
119
+
120
+ );
121
+
122
+ });
112
123
 
113
- });
114
-
115
124
  });
125
+
126
+ });
116
127
  });
117
128
  }
118
129
 
119
130
 
120
131
  getAvailableAgentsCount(agents) {
121
-
122
- var project_users_available = agents.filter(function (projectUser) {
123
- if (projectUser.user_available == true) {
124
- return true;
125
- }
126
- });
127
- winston.debug('++ AVAILABLE PROJECT USERS count ', project_users_available)
128
-
129
- if (project_users_available && project_users_available.length>0){
130
- return project_users_available.length;
131
- }else {
132
- return 0;
132
+
133
+ var project_users_available = agents.filter(function (projectUser) {
134
+ if (projectUser.user_available == true) {
135
+ return true;
133
136
  }
137
+ });
138
+ winston.debug('++ AVAILABLE PROJECT USERS count ', project_users_available)
139
+
140
+ if (project_users_available && project_users_available.length > 0) {
141
+ return project_users_available.length;
142
+ } else {
143
+ return 0;
144
+ }
145
+
134
146
 
135
-
136
147
  }
137
148
 
138
- //change create with this
139
- routeInternal (request, departmentid, id_project, nobot) {
140
- var that = this;
149
+ //change create with this
150
+ routeInternal(request, departmentid, id_project, nobot) {
151
+ var that = this;
141
152
 
142
153
  return new Promise(function (resolve, reject) {
143
154
 
144
- var context = {request: request};
155
+ var context = { request: request };
145
156
 
146
- // getOperators(departmentid, projectid, nobot, disableWebHookCall, context)
147
- return departmentService.getOperators(departmentid, id_project, nobot, undefined, context).then(function (result) {
157
+ // getOperators(departmentid, projectid, nobot, disableWebHookCall, context)
158
+ return departmentService.getOperators(departmentid, id_project, nobot, undefined, context).then(function (result) {
148
159
 
149
- // winston.debug("getOperators", result);
160
+ // winston.debug("getOperators", result);
150
161
 
151
- var assigned_at = undefined;
152
-
153
- var status = RequestConstants.UNASSIGNED;
154
- var assigned_operator_id;
155
- var participants = [];
156
- var participantsAgents = [];
157
- var participantsBots = [];
158
- var hasBot = false;
162
+ var assigned_at = undefined;
159
163
 
160
- if (result.operators && result.operators.length>0) {
161
- assigned_operator_id = result.operators[0].id_user;
164
+ var status = RequestConstants.UNASSIGNED;
165
+ var assigned_operator_id;
166
+ var participants = [];
167
+ var participantsAgents = [];
168
+ var participantsBots = [];
169
+ var hasBot = false;
162
170
 
163
- status = RequestConstants.ASSIGNED;
171
+ if (result.operators && result.operators.length > 0) {
172
+ assigned_operator_id = result.operators[0].id_user;
164
173
 
165
- var assigned_operator_idString = assigned_operator_id.toString();
166
- participants.push(assigned_operator_idString);
174
+ status = RequestConstants.ASSIGNED;
167
175
 
168
- // botprefix
169
- if (assigned_operator_idString.startsWith("bot_")) {
170
- hasBot = true;
171
-
172
- // botprefix
173
- var assigned_operator_idStringBot = assigned_operator_idString.replace("bot_","");
174
- participantsBots.push(assigned_operator_idStringBot);
175
- }else {
176
- participantsAgents.push(assigned_operator_idString);
177
- hasBot = false; //??
178
- }
176
+ var assigned_operator_idString = assigned_operator_id.toString();
177
+ participants.push(assigned_operator_idString);
178
+
179
+ // botprefix
180
+ if (assigned_operator_idString.startsWith("bot_")) {
181
+ hasBot = true;
179
182
 
180
- assigned_at = Date.now();
183
+ // botprefix
184
+ var assigned_operator_idStringBot = assigned_operator_idString.replace("bot_", "");
185
+ participantsBots.push(assigned_operator_idStringBot);
186
+ } else {
187
+ participantsAgents.push(assigned_operator_idString);
188
+ hasBot = false; //??
181
189
  }
182
- winston.debug("routeInternal assigned_operator_id: "+ assigned_operator_id);
183
- winston.debug("routeInternal status: "+ status);
184
190
 
191
+ assigned_at = Date.now();
192
+ }
193
+ winston.debug("routeInternal assigned_operator_id: " + assigned_operator_id);
194
+ winston.debug("routeInternal status: " + status);
185
195
 
186
196
 
187
- // cosi modifica la request originale forse devi fare il clone?????
188
- request.status = status;
189
197
 
190
- request.participants = participants;
191
- request.participantsAgents = participantsAgents;
192
- request.participantsBots = participantsBots;
193
- request.hasBot = hasBot;
198
+ // cosi modifica la request originale forse devi fare il clone?????
199
+ request.status = status;
194
200
 
195
- request.department = result.department._id;
196
- // request.agents = result.agents;
197
- request.assigned_at = assigned_at;
198
- request.waiting_time = undefined //reset waiting_time on reroute
199
-
200
- if (!request.snapshot) { //if used other methods than .create
201
- request.snapshot = {}
202
- }
201
+ request.participants = participants;
202
+ request.participantsAgents = participantsAgents;
203
+ request.participantsBots = participantsBots;
204
+ request.hasBot = hasBot;
203
205
 
204
-
205
- request.snapshot.department = result.department;
206
- request.snapshot.agents = result.agents;
207
- request.snapshot.availableAgentsCount = that.getAvailableAgentsCount(result.agents);
206
+ request.department = result.department._id;
207
+ // request.agents = result.agents;
208
+ request.assigned_at = assigned_at;
209
+ request.waiting_time = undefined //reset waiting_time on reroute
208
210
 
209
- return resolve(request);
210
-
211
-
212
- }).catch(function(err){
213
- return reject(err);
214
- });
211
+ if (!request.snapshot) { //if used other methods than .create
212
+ request.snapshot = {}
213
+ }
214
+
215
+
216
+ request.snapshot.department = result.department;
217
+ request.snapshot.agents = result.agents;
218
+ request.snapshot.availableAgentsCount = that.getAvailableAgentsCount(result.agents);
219
+
220
+ return resolve(request);
221
+
222
+
223
+ }).catch(function (err) {
224
+ return reject(err);
225
+ });
215
226
 
216
227
 
217
228
  });
218
229
  }
219
-
230
+
220
231
  // TODO changePreflightByRequestId se un agente entra in request freflight true disabilitare add agente e reassing ma mettere un bottone removePreflight???
221
232
  // usalo no_populate
222
233
  route(request_id, departmentid, id_project, nobot, no_populate) {
223
- var that = this;
234
+ var that = this;
224
235
 
225
- return new Promise(function (resolve, reject) {
226
- winston.debug("request_id:" + request_id);
227
- winston.debug("departmentid:" + departmentid);
228
- winston.debug("id_project:" + id_project);
229
- winston.debug("nobot:"+ nobot);
236
+ return new Promise(function (resolve, reject) {
237
+ winston.debug("request_id:" + request_id);
238
+ winston.debug("departmentid:" + departmentid);
239
+ winston.debug("id_project:" + id_project);
240
+ winston.debug("nobot:" + nobot);
230
241
 
231
- let q= Request
232
- .findOne({request_id: request_id, id_project: id_project});
242
+ let q = Request
243
+ .findOne({ request_id: request_id, id_project: id_project });
233
244
 
234
- // if (cacheEnabler.request) { //(node:60837) UnhandledPromiseRejectionWarning: VersionError: No matching document found for id "633efe246a6cc0eda5732684" version 0 modifiedPaths "status, participants, participantsAgents, department, assigned_at, snapshot, snapshot.department, snapshot.department.updatedAt, snapshot.agents"
235
- // q.cache(cacheUtil.defaultTTL, id_project+":requests:request_id:"+request_id+":simple") //request_cache
236
- // winston.debug('request cache enabled');
237
- // }
238
- return q.exec( function(err, request) {
245
+ // if (cacheEnabler.request) { //(node:60837) UnhandledPromiseRejectionWarning: VersionError: No matching document found for id "633efe246a6cc0eda5732684" version 0 modifiedPaths "status, participants, participantsAgents, department, assigned_at, snapshot, snapshot.department, snapshot.department.updatedAt, snapshot.agents"
246
+ // q.cache(cacheUtil.defaultTTL, id_project+":requests:request_id:"+request_id+":simple") //request_cache
247
+ // winston.debug('request cache enabled');
248
+ // }
249
+ return q.exec(function (err, request) {
239
250
 
240
- if (err) {
241
- winston.error(err);
242
- return reject(err);
243
- }
244
-
245
- winston.debug('request return',request);
251
+ if (err) {
252
+ winston.error(err);
253
+ return reject(err);
254
+ }
246
255
 
247
- // cambia var in let
256
+ winston.debug('request return', request);
248
257
 
249
- //it is important to clone here
250
- var requestBeforeRoute = Object.assign({}, request.toObject());
251
- winston.debug("requestBeforeRoute",requestBeforeRoute);
258
+ // cambia var in let
252
259
 
253
- var beforeParticipants = requestBeforeRoute.participants;
254
- winston.debug("beforeParticipants: ", beforeParticipants);
260
+ //it is important to clone here
261
+ var requestBeforeRoute = Object.assign({}, request.toObject());
262
+ winston.debug("requestBeforeRoute", requestBeforeRoute);
255
263
 
256
- return that.routeInternal(request, departmentid, id_project, nobot ).then(function(routedRequest){
264
+ var beforeParticipants = requestBeforeRoute.participants;
265
+ winston.debug("beforeParticipants: ", beforeParticipants);
257
266
 
258
- winston.debug("after routeInternal",routedRequest);
259
- // winston.info("requestBeforeRoute.participants " +requestBeforeRoute.request_id , requestBeforeRoute.participants);
260
- // console.log("routedRequest.participants " +routedRequest.request_id , routedRequest.participants);
261
- winston.debug("requestBeforeRoute.status:" + requestBeforeRoute.status);
262
- winston.debug("routedRequest.status:" + routedRequest.status);
267
+ return that.routeInternal(request, departmentid, id_project, nobot).then(function (routedRequest) {
263
268
 
264
- let beforeDepartmentId;
265
- if (requestBeforeRoute.department) { //requestBeforeRoute.department can be empty for internal ticket
266
- beforeDepartmentId = requestBeforeRoute.department.toString();
267
- winston.debug("beforeDepartmentId:"+ beforeDepartmentId);
268
- }
269
-
270
- let afterDepartmentId;
271
- if (routedRequest.department) {
272
- afterDepartmentId = routedRequest.department.toString();
273
- winston.debug("afterDepartmentId:"+ afterDepartmentId);
274
- }
275
-
276
-
277
- if (requestBeforeRoute.status === routedRequest.status &&
278
- beforeDepartmentId === afterDepartmentId &&
279
- requestUtil.arraysEqual(beforeParticipants, routedRequest.participants)) {
269
+ winston.debug("after routeInternal", routedRequest);
270
+ // winston.info("requestBeforeRoute.participants " +requestBeforeRoute.request_id , requestBeforeRoute.participants);
271
+ // console.log("routedRequest.participants " +routedRequest.request_id , routedRequest.participants);
272
+ winston.debug("requestBeforeRoute.status:" + requestBeforeRoute.status);
273
+ winston.debug("routedRequest.status:" + routedRequest.status);
280
274
 
281
- winston.verbose("Request " +request.request_id + " contains already the same participants at the same request status. Routed to the same participants");
275
+ let beforeDepartmentId;
276
+ if (requestBeforeRoute.department) { //requestBeforeRoute.department can be empty for internal ticket
277
+ beforeDepartmentId = requestBeforeRoute.department.toString();
278
+ winston.debug("beforeDepartmentId:" + beforeDepartmentId);
279
+ }
282
280
 
283
- if (no_populate==="true" || no_populate===true) {
284
- winston.debug("no_populate is true");
285
- return resolve(request);
286
- }
281
+ let afterDepartmentId;
282
+ if (routedRequest.department) {
283
+ afterDepartmentId = routedRequest.department.toString();
284
+ winston.debug("afterDepartmentId:" + afterDepartmentId);
285
+ }
286
+
287
+
288
+ if (requestBeforeRoute.status === routedRequest.status &&
289
+ beforeDepartmentId === afterDepartmentId &&
290
+ requestUtil.arraysEqual(beforeParticipants, routedRequest.participants)) {
291
+
292
+ winston.verbose("Request " + request.request_id + " contains already the same participants at the same request status. Routed to the same participants");
293
+
294
+ if (no_populate === "true" || no_populate === true) {
295
+ winston.debug("no_populate is true");
296
+ return resolve(request);
297
+ }
287
298
 
288
- return request
289
- .populate('lead')
299
+ return request
300
+ .populate('lead')
290
301
  .populate('department')
291
302
  .populate('participatingBots')
292
- .populate('participatingAgents')
293
- .populate({path:'requester',populate:{path:'id_user'}})
294
- .execPopulate( function(err, requestComplete) {
295
- winston.debug("requestComplete",requestComplete);
296
-
303
+ .populate('participatingAgents')
304
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
305
+ .execPopulate(function (err, requestComplete) {
306
+ winston.debug("requestComplete", requestComplete);
307
+
297
308
  return resolve(requestComplete);
298
309
  });
310
+ }
311
+
312
+ //cacheinvalidation
313
+ return routedRequest.save(function (err, savedRequest) {
314
+ // https://stackoverflow.com/questions/54792749/mongoose-versionerror-no-matching-document-found-for-id-when-document-is-being
315
+ //return routedRequest.update(function(err, savedRequest) {
316
+ if (err) {
317
+ winston.error('Error saving the request. ', { err: err, routedRequest: routedRequest });
318
+ return reject(err);
299
319
  }
300
320
 
301
- //cacheinvalidation
302
- return routedRequest.save(function(err, savedRequest) {
303
- // https://stackoverflow.com/questions/54792749/mongoose-versionerror-no-matching-document-found-for-id-when-document-is-being
304
- //return routedRequest.update(function(err, savedRequest) {
305
- if (err) {
306
- winston.error('Error saving the request. ', {err:err, routedRequest:routedRequest});
307
- return reject(err);
308
- }
309
-
310
- winston.debug("after save savedRequest", savedRequest);
321
+ winston.debug("after save savedRequest", savedRequest);
311
322
 
312
- return savedRequest
323
+ return savedRequest
313
324
  .populate('lead')
314
325
  .populate('department')
315
326
  .populate('participatingBots')
316
- .populate('participatingAgents')
317
- .populate({path:'requester',populate:{path:'id_user'}})
318
- .execPopulate( function(err, requestComplete) {
319
-
320
- // return Request //to populate correctly i must re-exec the query
321
- // .findById(savedRequest.id)
322
- // .populate('lead')
323
- // .populate('department')
324
- // .populate('participatingBots')
325
- // .populate('participatingAgents')
326
- // .populate({path:'requester',populate:{path:'id_user'}})
327
- // .exec( function(err, requestComplete) {
328
-
329
-
330
- if (err) {
331
- winston.error('Error populating the request.',err);
332
- return reject(err);
333
- }
327
+ .populate('participatingAgents')
328
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
329
+ .execPopulate(function (err, requestComplete) {
330
+
331
+ // return Request //to populate correctly i must re-exec the query
332
+ // .findById(savedRequest.id)
333
+ // .populate('lead')
334
+ // .populate('department')
335
+ // .populate('participatingBots')
336
+ // .populate('participatingAgents')
337
+ // .populate({path:'requester',populate:{path:'id_user'}})
338
+ // .exec( function(err, requestComplete) {
339
+
340
+
341
+ if (err) {
342
+ winston.error('Error populating the request.', err);
343
+ return reject(err);
344
+ }
334
345
 
335
- winston.verbose("Request routed",requestComplete.toObject());
336
-
346
+ winston.verbose("Request routed", requestComplete.toObject());
337
347
 
338
- var oldParticipants = beforeParticipants;
339
- winston.debug("oldParticipants ", oldParticipants);
340
348
 
341
- let newParticipants = requestComplete.participants;
342
- winston.debug("newParticipants ", newParticipants);
349
+ var oldParticipants = beforeParticipants;
350
+ winston.debug("oldParticipants ", oldParticipants);
343
351
 
344
- var removedParticipants = oldParticipants.filter(d => !newParticipants.includes(d));
345
- winston.debug("removedParticipants ", removedParticipants);
352
+ let newParticipants = requestComplete.participants;
353
+ winston.debug("newParticipants ", newParticipants);
346
354
 
347
- var addedParticipants = newParticipants.filter(d => !oldParticipants.includes(d));
348
- winston.debug("addedParticipants ", addedParticipants);
355
+ var removedParticipants = oldParticipants.filter(d => !newParticipants.includes(d));
356
+ winston.debug("removedParticipants ", removedParticipants);
349
357
 
350
-
351
- requestEvent.emit('request.update',requestComplete);
352
- requestEvent.emit("request.update.comment", {comment:"REROUTE",request:requestComplete});//Deprecated
353
- requestEvent.emit("request.updated", {comment:"REROUTE",request:requestComplete, patch:{removedParticipants: removedParticipants, addedParticipants:addedParticipants}});
358
+ var addedParticipants = newParticipants.filter(d => !oldParticipants.includes(d));
359
+ winston.debug("addedParticipants ", addedParticipants);
354
360
 
355
- requestEvent.emit('request.participants.update', {beforeRequest:request,
356
- removedParticipants:removedParticipants,
357
- addedParticipants:addedParticipants,
358
- request:requestComplete});
359
361
 
360
- requestEvent.emit('request.department.update',requestComplete); //se req ha bot manda messaggio \welcome
362
+ requestEvent.emit('request.update', requestComplete);
363
+ requestEvent.emit("request.update.comment", { comment: "REROUTE", request: requestComplete });//Deprecated
364
+ requestEvent.emit("request.updated", { comment: "REROUTE", request: requestComplete, patch: { removedParticipants: removedParticipants, addedParticipants: addedParticipants } });
361
365
 
362
- winston.debug("here end");
366
+ requestEvent.emit('request.participants.update', {
367
+ beforeRequest: request,
368
+ removedParticipants: removedParticipants,
369
+ addedParticipants: addedParticipants,
370
+ request: requestComplete
371
+ });
363
372
 
364
- return resolve(requestComplete);
365
- });
373
+ requestEvent.emit('request.department.update', requestComplete); //se req ha bot manda messaggio \welcome
366
374
 
375
+ winston.debug("here end");
376
+
377
+ return resolve(requestComplete);
378
+ });
367
379
 
368
-
369
- });
370
380
 
371
- }).catch(function(err) {
372
- return reject(err);
373
- });
374
381
 
375
-
376
382
  });
383
+
384
+ }).catch(function (err) {
385
+ return reject(err);
386
+ });
387
+
388
+
389
+ });
377
390
  });
378
391
  }
379
392
 
@@ -384,413 +397,741 @@ class RequestService {
384
397
  return new Promise(function (resolve, reject) {
385
398
  // winston.debug("request_id", request_id);
386
399
  // winston.debug("newstatus", newstatus);
387
-
388
- let q = Request
389
- .findOne({request_id: request_id, id_project: id_project});
390
400
 
391
- if (cacheEnabler.request) {
392
- q.cache(cacheUtil.defaultTTL, id_project+":requests:request_id:"+request_id+":simple") //request_cache
393
- winston.debug('request cache enabled');
401
+ let q = Request
402
+ .findOne({ request_id: request_id, id_project: id_project });
403
+
404
+ if (cacheEnabler.request) {
405
+ q.cache(cacheUtil.defaultTTL, id_project + ":requests:request_id:" + request_id + ":simple") //request_cache
406
+ winston.debug('request cache enabled');
407
+ }
408
+
409
+ return q.exec(function (err, request) {
410
+
411
+ if (err) {
412
+ winston.error(err);
413
+ return reject(err);
394
414
  }
395
415
 
396
- return q.exec( function(err, request) {
397
-
398
- if (err) {
399
- winston.error(err);
400
- return reject(err);
401
- }
416
+ winston.debug('request cache simple 3', request);
417
+
418
+ winston.debug("here reroute1 ");
402
419
 
403
- winston.debug('request cache simple 3', request);
420
+ // Cannot read property 'toString' of undefined at /usr/src/app/services/requestService.js:404:61 at /usr/src/app/node_modules/cachegoose/out/extend-query.js:44:13 at Command.cb [as callback] (/usr/src/app/node_modules/cacheman-redis/node/index.js:142:9) at normal_reply (/usr/src/app/node_modules/redis/index.js:655:21) at RedisClient.return_reply (/usr/src/app/node_modules/redis/index.js:753:9) at JavascriptRedisParser.returnReply (/usr/src/app/node_modules/redis/index.js:138:18) at JavascriptRedisParser.execute (/usr/src/app/node_modules/redis-parser/lib/parser.js:544:14) at Socket.<anonymous> (/usr/src/app/node_modules/redis/index.js:219:27) at Socket.emit (events.js:314:20) at addChunk (_stream_readable.js:297:12) at readableAddChunk (_stream_readable.js:272:9) at Socket.Readable.push (_stream_readable.js:213:10) at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {"date":"Tue Mar 21 2023 18:45:47 GMT+0000 (Coordinated Unive
421
+ if (request.department === undefined) {
422
+ winston.error("Request with request_id " + request_id + " has empty department. So I can't reroute");
423
+ return reject("Request with request_id " + request_id + " has empty department. So I can't reroute");
424
+ }
404
425
 
405
- winston.debug("here reroute1 ");
406
426
 
407
- // Cannot read property 'toString' of undefined at /usr/src/app/services/requestService.js:404:61 at /usr/src/app/node_modules/cachegoose/out/extend-query.js:44:13 at Command.cb [as callback] (/usr/src/app/node_modules/cacheman-redis/node/index.js:142:9) at normal_reply (/usr/src/app/node_modules/redis/index.js:655:21) at RedisClient.return_reply (/usr/src/app/node_modules/redis/index.js:753:9) at JavascriptRedisParser.returnReply (/usr/src/app/node_modules/redis/index.js:138:18) at JavascriptRedisParser.execute (/usr/src/app/node_modules/redis-parser/lib/parser.js:544:14) at Socket.<anonymous> (/usr/src/app/node_modules/redis/index.js:219:27) at Socket.emit (events.js:314:20) at addChunk (_stream_readable.js:297:12) at readableAddChunk (_stream_readable.js:272:9) at Socket.Readable.push (_stream_readable.js:213:10) at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {"date":"Tue Mar 21 2023 18:45:47 GMT+0000 (Coordinated Unive
408
- if (request.department === undefined) {
409
- winston.error("Request with request_id " + request_id + " has empty department. So I can't reroute");
410
- return reject("Request with request_id " + request_id + " has empty department. So I can't reroute");
411
- }
427
+ return that.route(request_id, request.department.toString(), id_project, nobot).then(function (routedRequest) {
412
428
 
413
-
414
- return that.route(request_id, request.department.toString(), id_project, nobot).then(function(routedRequest){
429
+ var endDate = new Date();
430
+ winston.verbose("Performance Request reroute in millis: " + endDate - startDate);
415
431
 
416
- var endDate = new Date();
417
- winston.verbose("Performance Request reroute in millis: " + endDate-startDate);
432
+ return resolve(routedRequest);
433
+ }).catch(function (err) {
434
+ return reject(err);
435
+ });
436
+
437
+ });
438
+ });
439
+ }
418
440
 
419
- return resolve(routedRequest);
420
- }).catch(function(err) {
421
- return reject(err);
422
- });
423
-
424
- });
425
- });
426
- }
427
-
428
441
 
429
442
 
430
443
  createWithRequester(project_user_id, lead_id, id_project, first_text, departmentid, sourcePage, language, userAgent, status, createdBy, attributes, subject, preflight) {
431
444
 
432
- var request_id = 'support-group-'+ id_project + "-" + UIDGenerator.generate();
433
- winston.debug("request_id: "+request_id);
434
-
445
+ var request_id = 'support-group-' + id_project + "-" + UIDGenerator.generate();
446
+ winston.debug("request_id: " + request_id);
447
+
435
448
  return this.createWithIdAndRequester(request_id, project_user_id, lead_id, id_project, first_text, departmentid, sourcePage, language, userAgent, status, createdBy, attributes, subject, preflight);
436
449
  }
437
450
 
438
451
  createWithIdAndRequester(request_id, project_user_id, lead_id, id_project, first_text, departmentid, sourcePage, language, userAgent, status, createdBy, attributes, subject, preflight, channel, location) {
439
-
452
+
440
453
  var request = {
441
- request_id:request_id, project_user_id:project_user_id, lead_id:lead_id, id_project:id_project,first_text:first_text,
442
- departmentid:departmentid, sourcePage:sourcePage, language:language, userAgent:userAgent, status:status, createdBy:createdBy,
443
- attributes:attributes, subject:subject, preflight:preflight, channel:channel, location:location
444
- };
454
+ request_id: request_id, project_user_id: project_user_id, lead_id: lead_id, id_project: id_project, first_text: first_text,
455
+ departmentid: departmentid, sourcePage: sourcePage, language: language, userAgent: userAgent, status: status, createdBy: createdBy,
456
+ attributes: attributes, subject: subject, preflight: preflight, channel: channel, location: location
457
+ };
445
458
 
446
459
  return this.create(request);
447
- };
460
+ };
448
461
 
449
- create(request) {
462
+ async create(request) {
450
463
 
451
464
  var startDate = new Date();
452
465
 
453
- var request_id = request.request_id;
454
- var project_user_id = request.project_user_id;
455
- var lead_id = request.lead_id;
456
- var id_project = request.id_project;
466
+ if (!request.createdAt) {
467
+ request.createdAt = new Date();
468
+ }
457
469
 
458
- var first_text = request.first_text;
459
- //removed for ticket
460
- // // lascia che sia nico a fare il replace...certo tu devi fare il test che tutto sia ok quindi dopo demo
461
- // var first_text;
462
- // if (request.first_text) { //first_text can be empty for type image
463
- // first_text = request.first_text.replace(/[\n\r]+/g, ' '); //replace new line with space
464
- // }
465
-
466
- var departmentid = request.departmentid;
467
- var sourcePage = request.sourcePage;
468
- var language = request.language;
469
- var userAgent = request.userAgent;
470
- var status = request.status;
471
- var createdBy = request.createdBy;
472
- var attributes = request.attributes;
473
- var subject = request.subject;
474
- var preflight = request.preflight;
475
- var channel = request.channel;
476
- var location = request.location;
477
- var participants = request.participants || [];
478
470
 
479
- var tags = request.tags;
480
- var notes = request.notes;
481
- var priority = request.priority;
471
+ var request_id = request.request_id;
472
+ var project_user_id = request.project_user_id;
473
+ var lead_id = request.lead_id;
474
+ var id_project = request.id_project;
482
475
 
483
- var auto_close = request.auto_close;
476
+ var first_text = request.first_text;
484
477
 
485
- var followers = request.followers;
478
+ //removed for ticket
479
+ // // lascia che sia nico a fare il replace...certo tu devi fare il test che tutto sia ok quindi dopo demo
480
+ // var first_text;
481
+ // if (request.first_text) { //first_text can be empty for type image
482
+ // first_text = request.first_text.replace(/[\n\r]+/g, ' '); //replace new line with space
483
+ // }
486
484
 
487
- if (!departmentid) {
488
- departmentid ='default';
489
- }
485
+ var departmentid = request.departmentid;
486
+ var sourcePage = request.sourcePage;
487
+ var language = request.language;
488
+ var userAgent = request.userAgent;
489
+ var status = request.status;
490
+ var createdBy = request.createdBy;
491
+ var attributes = request.attributes;
492
+ var subject = request.subject;
493
+ var preflight = request.preflight;
494
+ var channel = request.channel;
495
+ var location = request.location;
496
+ var participants = request.participants || [];
497
+
498
+ var tags = request.tags;
499
+ var notes = request.notes;
500
+ var priority = request.priority;
501
+
502
+ var auto_close = request.auto_close;
503
+
504
+ var followers = request.followers;
505
+ let createdAt = request.createdAt;
506
+
507
+ if (!departmentid) {
508
+ departmentid = 'default';
509
+ }
510
+
511
+ if (!createdBy) {
512
+ if (project_user_id) {
513
+ createdBy = project_user_id;
514
+ } else {
515
+ createdBy = "system";
516
+ }
490
517
 
491
- if (!createdBy) {
492
- if (project_user_id) {
493
- createdBy = project_user_id;
494
- }else {
495
- createdBy = "system";
496
518
  }
497
-
498
- }
499
-
500
- var that = this;
501
519
 
502
- return new Promise(async (resolve, reject) => {
520
+ var that = this;
503
521
 
504
- var context = {request: {request_id:request_id, project_user_id:project_user_id, lead_id:lead_id, id_project:id_project,
505
- first_text:first_text, departmentid:departmentid, sourcePage:sourcePage, language:language, userAgent:userAgent, status:status,
506
- createdBy:createdBy, attributes:attributes, subject:subject, preflight: preflight, channel: channel, location: location,
507
- participants:participants, tags: tags, notes:notes,
508
- priority: priority, auto_close: auto_close, followers: followers}};
522
+ return new Promise(async (resolve, reject) => {
509
523
 
510
- winston.debug("context",context);
524
+ let q = Project.findOne({ _id: request.id_project, status: 100 });
525
+ if (cacheEnabler.project) {
526
+ q.cache(cacheUtil.longTTL, "projects:id:" + request.id_project) //project_cache
527
+ winston.debug('project cache enabled for /project detail');
528
+ }
529
+ q.exec(async function (err, p) {
530
+ if (err) {
531
+ winston.error('Error getting project ', err);
532
+ }
533
+ if (!p) {
534
+ winston.warn('Project not found ');
535
+ }
536
+
537
+
538
+ let payload = {
539
+ project: p,
540
+ request: request
541
+ }
542
+
543
+ let available = await qm.checkQuote(p, request, 'requests');
544
+ if (available === false) {
545
+ winston.info("Requests limits reached for project " + p._id)
546
+ return false;
547
+ }
548
+
511
549
 
512
- var participantsAgents = [];
513
- var participantsBots = [];
514
- var hasBot = false;
550
+ var context = {
551
+ request: {
552
+ request_id: request_id, project_user_id: project_user_id, lead_id: lead_id, id_project: id_project,
553
+ first_text: first_text, departmentid: departmentid, sourcePage: sourcePage, language: language, userAgent: userAgent, status: status,
554
+ createdBy: createdBy, attributes: attributes, subject: subject, preflight: preflight, channel: channel, location: location,
555
+ participants: participants, tags: tags, notes: notes,
556
+ priority: priority, auto_close: auto_close, followers: followers
557
+ }
558
+ };
515
559
 
516
- var dep_id = undefined;
560
+ winston.debug("context", context);
517
561
 
518
- var assigned_at = undefined;
519
-
520
- var agents = [];
562
+ var participantsAgents = [];
563
+ var participantsBots = [];
564
+ var hasBot = false;
521
565
 
522
- var snapshot = {};
566
+ var dep_id = undefined;
523
567
 
524
- try {
525
- // getOperators(departmentid, projectid, nobot, disableWebHookCall, context) {
526
- var result = await departmentService.getOperators(departmentid, id_project, false, undefined, context);
527
- // console.log("************* after get operator: "+new Date().toISOString());
568
+ var assigned_at = undefined;
528
569
 
529
- winston.debug("getOperators", result);
530
- } catch(err) {
531
- return reject(err);
532
- }
533
-
534
-
535
-
536
- agents = result.agents;
570
+ var agents = [];
537
571
 
538
- if (status == 50) {
539
- // skip assignment
540
- if (participants.length == 0 ) {
541
- dep_id = result.department._id;
542
- }
543
- } else {
544
-
545
- if (participants.length == 0 ) {
546
- if (result.operators && result.operators.length>0) {
547
- participants.push(result.operators[0].id_user.toString());
548
- }
549
- // for preflight it is important to save agents in req for trigger. try to optimize it
550
- dep_id = result.department._id;
572
+ var snapshot = {};
551
573
 
552
- }
574
+ try {
575
+ // getOperators(departmentid, projectid, nobot, disableWebHookCall, context) {
576
+ var result = await departmentService.getOperators(departmentid, id_project, false, undefined, context);
577
+ // console.log("************* after get operator: "+new Date().toISOString());
553
578
 
554
- if (participants.length > 0) {
555
-
556
- status = RequestConstants.ASSIGNED;
557
-
558
- // botprefix
559
- if (participants[0].startsWith("bot_")) {
560
-
561
- hasBot = true;
562
- winston.debug("hasBot:"+hasBot);
563
-
564
- // botprefix
565
- var assigned_operator_idStringBot = participants[0].replace("bot_","");
566
- winston.debug("assigned_operator_idStringBot:"+assigned_operator_idStringBot);
567
-
568
- participantsBots.push(assigned_operator_idStringBot);
569
-
570
- } else {
571
-
572
- participantsAgents.push(participants[0]);
573
-
574
- }
575
-
576
- assigned_at = Date.now();
579
+ winston.debug("getOperators", result);
580
+ } catch (err) {
581
+ return reject(err);
582
+ }
577
583
 
578
- } else {
579
584
 
580
- status = RequestConstants.UNASSIGNED;
581
585
 
582
- }
586
+ agents = result.agents;
583
587
 
588
+ if (status == 50) {
589
+ // skip assignment
590
+ if (participants.length == 0) {
591
+ dep_id = result.department._id;
584
592
  }
593
+ } else {
585
594
 
586
-
587
-
595
+ if (participants.length == 0) {
596
+ if (result.operators && result.operators.length > 0) {
597
+ participants.push(result.operators[0].id_user.toString());
598
+ }
599
+ // for preflight it is important to save agents in req for trigger. try to optimize it
600
+ dep_id = result.department._id;
588
601
 
589
- if (dep_id) {
590
- snapshot.department = result.department;
591
602
  }
592
-
593
- // console.log("result.agents",result.agents);
594
- snapshot.agents = agents;
595
- snapshot.availableAgentsCount = that.getAvailableAgentsCount(agents);
596
603
 
597
- if (request.requester) { //.toObject()????
598
- snapshot.requester = request.requester;
599
- }
600
- if (request.lead) {
601
- snapshot.lead = request.lead;
602
- }
603
-
604
- // winston.debug("assigned_operator_id", assigned_operator_id);
605
- // winston.debug("req status", status);
606
-
607
- var newRequest = new Request({
608
- request_id: request_id,
609
- requester: project_user_id,
610
- lead: lead_id,
611
- first_text: first_text,
612
- subject: subject,
613
- status: status,
614
- participants: participants,
615
- participantsAgents:participantsAgents,
616
- participantsBots: participantsBots,
617
- hasBot: hasBot,
618
- department: dep_id,
619
- // agents: agents,
620
-
621
- //others
622
- sourcePage: sourcePage,
623
- language: language,
624
- userAgent: userAgent,
625
- assigned_at : assigned_at,
626
-
627
- attributes: attributes,
628
- //standard
629
- id_project: id_project,
630
- createdBy: createdBy,
631
- updatedBy: createdBy,
632
- preflight: preflight,
633
- channel: channel,
634
- location: location,
635
- snapshot: snapshot,
636
- tags: tags,
637
- notes: notes,
638
- priority: priority,
639
- auto_close: auto_close,
640
- followers: followers
641
- });
604
+ if (participants.length > 0) {
642
605
 
643
- winston.debug('newRequest.',newRequest);
606
+ status = RequestConstants.ASSIGNED;
644
607
 
645
-
646
- //cacheinvalidation
647
- return newRequest.save(function(err, savedRequest) {
648
- if (err) {
649
- winston.error('RequestService error for method createWithIdAndRequester for newRequest' + JSON.stringify(newRequest), err);
650
- return reject(err);
651
- }
652
-
653
-
654
- winston.verbose("Request created",savedRequest.toObject());
655
-
656
- var endDate = new Date();
657
- winston.verbose("Performance Request created in millis: " + endDate-startDate);
658
-
659
- requestEvent.emit('request.create.simple', savedRequest);
660
-
661
- return resolve(savedRequest);
662
-
663
- });
664
- // }).catch(function(err){
665
- // return reject(err);
666
- // });
608
+ // botprefix
609
+ if (participants[0].startsWith("bot_")) {
667
610
 
611
+ hasBot = true;
612
+ winston.debug("hasBot:" + hasBot);
668
613
 
669
- });
670
- }
614
+ // botprefix
615
+ var assigned_operator_idStringBot = participants[0].replace("bot_", "");
616
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
671
617
 
618
+ participantsBots.push(assigned_operator_idStringBot);
672
619
 
620
+ } else {
673
621
 
622
+ participantsAgents.push(participants[0]);
674
623
 
624
+ }
675
625
 
676
- //DEPRECATED. USED ONLY IN SAME TESTS
677
- createWithId(request_id, requester_id, id_project, first_text, departmentid, sourcePage, language, userAgent, status, createdBy, attributes) {
626
+ assigned_at = Date.now();
678
627
 
679
- // winston.debug("request_id", request_id);
628
+ } else {
680
629
 
630
+ status = RequestConstants.UNASSIGNED;
681
631
 
682
- if (!departmentid) {
683
- departmentid ='default';
684
- }
632
+ }
685
633
 
686
- if (!createdBy) {
687
- createdBy = requester_id;
688
- }
689
-
690
- var that = this;
634
+ }
691
635
 
692
- return new Promise(function (resolve, reject) {
693
636
 
694
- var context = {request: {request_id:request_id, requester_id:requester_id, id_project:id_project,
695
- first_text:first_text, departmentid:departmentid, sourcePage:sourcePage, language:language, userAgent:userAgent, status:status,
696
- createdBy:createdBy, attributes:attributes}};
697
637
 
698
- // getOperators(departmentid, projectid, nobot, disableWebHookCall, context)
699
638
 
700
- return departmentService.getOperators(departmentid, id_project, false, undefined, context).then(function (result) {
639
+ if (dep_id) {
640
+ snapshot.department = result.department;
641
+ }
701
642
 
702
- // winston.debug("getOperators", result);
643
+ // console.log("result.agents",result.agents);
644
+ snapshot.agents = agents;
645
+ snapshot.availableAgentsCount = that.getAvailableAgentsCount(agents);
703
646
 
704
- var status = RequestConstants.UNASSIGNED;
705
- var assigned_operator_id;
706
- var participants = [];
707
- var participantsAgents = [];
708
- var participantsBots = [];
709
- var hasBot = false;
647
+ if (request.requester) { //.toObject()????
648
+ snapshot.requester = request.requester;
649
+ }
650
+ if (request.lead) {
651
+ snapshot.lead = request.lead;
652
+ }
710
653
 
711
- var assigned_at = undefined;
712
- if (result.operators && result.operators.length>0) {
713
- assigned_operator_id = result.operators[0].id_user;
714
- status = RequestConstants.ASSIGNED;
654
+ // winston.debug("assigned_operator_id", assigned_operator_id);
655
+ // winston.debug("req status", status);
656
+
657
+ var newRequest = new Request({
658
+ request_id: request_id,
659
+ requester: project_user_id,
660
+ lead: lead_id,
661
+ first_text: first_text,
662
+ subject: subject,
663
+ status: status,
664
+ participants: participants,
665
+ participantsAgents: participantsAgents,
666
+ participantsBots: participantsBots,
667
+ hasBot: hasBot,
668
+ department: dep_id,
669
+ // agents: agents,
670
+
671
+ //others
672
+ sourcePage: sourcePage,
673
+ language: language,
674
+ userAgent: userAgent,
675
+ assigned_at: assigned_at,
676
+
677
+ attributes: attributes,
678
+ //standard
679
+ id_project: id_project,
680
+ createdBy: createdBy,
681
+ updatedBy: createdBy,
682
+ preflight: preflight,
683
+ channel: channel,
684
+ location: location,
685
+ snapshot: snapshot,
686
+ tags: tags,
687
+ notes: notes,
688
+ priority: priority,
689
+ auto_close: auto_close,
690
+ followers: followers,
691
+ createdAt: createdAt
692
+ });
715
693
 
716
- var assigned_operator_idString = assigned_operator_id.toString();
717
- participants.push(assigned_operator_idString);
694
+ winston.debug('newRequest.', newRequest);
718
695
 
719
- // botprefix
720
- if (assigned_operator_idString.startsWith("bot_")) {
721
- hasBot = true;
722
696
 
723
- // botprefix
724
- var assigned_operator_idStringBot = assigned_operator_idString.replace("bot_","");
725
- winston.debug("assigned_operator_idStringBot:"+assigned_operator_idStringBot);
726
- participantsBots.push(assigned_operator_idStringBot);
697
+ //cacheinvalidation
698
+ return newRequest.save( async function (err, savedRequest) {
727
699
 
728
- }else {
729
- participantsAgents.push(assigned_operator_idString);
730
- }
731
- assigned_at = Date.now();
700
+ if (err) {
701
+ winston.error('RequestService error for method createWithIdAndRequester for newRequest' + JSON.stringify(newRequest), err);
702
+ return reject(err);
732
703
  }
733
- // winston.debug("assigned_operator_id", assigned_operator_id);
734
- // winston.debug("status", status);
735
-
736
- var newRequest = new Request({
737
- request_id: request_id,
738
- requester_id: requester_id,
739
- first_text: first_text,
740
- status: status,
741
- participants: participants,
742
- participantsAgents:participantsAgents,
743
- participantsBots: participantsBots,
744
- hasBot:hasBot,
745
- department: result.department._id,
746
- agents: result.agents,
747
- //availableAgents: result.available_agents,
748
-
749
- // assigned_operator_id: result.assigned_operator_id,
750
-
751
- //others
752
- sourcePage: sourcePage,
753
- language: language,
754
- userAgent: userAgent,
755
- assigned_at:assigned_at,
756
- attributes: attributes,
757
- //standard
758
- id_project: id_project,
759
- createdBy: createdBy,
760
- updatedBy: createdBy
761
- });
762
-
763
704
 
764
- // winston.debug('newRequest.',newRequest);
765
705
 
706
+ winston.debug("Request created", savedRequest.toObject());
707
+
708
+ var endDate = new Date();
709
+ winston.verbose("Performance Request created in millis: " + endDate - startDate);
710
+
711
+ requestEvent.emit('request.create.simple', savedRequest);
712
+
713
+ // let q = Project.findOne({ _id: request.id_project, status: 100 });
714
+ // if (cacheEnabler.project) {
715
+ // q.cache(cacheUtil.longTTL, "projects:id:" + request.id_project) //project_cache
716
+ // winston.debug('project cache enabled for /project detail');
717
+ // }
718
+ // q.exec(async function (err, p) {
719
+ // if (err) {
720
+ // winston.error('Error getting project ', err);
721
+ // }
722
+ // if (!p) {
723
+ // winston.warn('Project not found ');
724
+ // }
725
+ // //TODO REMOVE settings from project
726
+ // let payload = {
727
+ // project: p,
728
+ // request: request
729
+ // }
730
+
731
+ // });
732
+ requestEvent.emit('request.create.quote', payload);;
733
+ // if (result === false) {
734
+ // winston.info("Requests limits reached for project " + p._id)
735
+ // // return false in the second phase
736
+ // }
737
+
738
+ return resolve(savedRequest);
766
739
 
767
-
768
- //cacheinvalidation
769
- return newRequest.save(function(err, savedRequest) {
770
- if (err) {
771
- winston.error('RequestService error for method createWithId for newRequest' + JSON.stringify(newRequest), err);
772
- return reject(err);
773
- }
774
-
775
-
776
- winston.verbose("Request created",savedRequest.toObject());
777
-
778
-
779
- requestEvent.emit('request.create.simple',savedRequest);
780
-
781
- return resolve(savedRequest);
782
-
783
- });
784
- }).catch(function(err){
785
- return reject(err);
786
- });
740
+ });
741
+ // }).catch(function(err){
742
+ // return reject(err);
743
+ // });
787
744
 
745
+ })
746
+ });
747
+
748
+ }
788
749
 
789
- });
750
+
751
+ async _create(request) {
752
+
753
+ var startDate = new Date();
754
+
755
+ if (!request.createdAt) {
756
+ request.createdAt = new Date();
757
+ }
790
758
 
791
759
 
792
-
793
-
760
+ var request_id = request.request_id;
761
+ var project_user_id = request.project_user_id;
762
+ var lead_id = request.lead_id;
763
+ var id_project = request.id_project;
764
+
765
+ var first_text = request.first_text;
766
+
767
+ //removed for ticket
768
+ // // lascia che sia nico a fare il replace...certo tu devi fare il test che tutto sia ok quindi dopo demo
769
+ // var first_text;
770
+ // if (request.first_text) { //first_text can be empty for type image
771
+ // first_text = request.first_text.replace(/[\n\r]+/g, ' '); //replace new line with space
772
+ // }
773
+
774
+ var departmentid = request.departmentid;
775
+ var sourcePage = request.sourcePage;
776
+ var language = request.language;
777
+ var userAgent = request.userAgent;
778
+ var status = request.status;
779
+ var createdBy = request.createdBy;
780
+ var attributes = request.attributes;
781
+ var subject = request.subject;
782
+ var preflight = request.preflight;
783
+ var channel = request.channel;
784
+ var location = request.location;
785
+ var participants = request.participants || [];
786
+
787
+ var tags = request.tags;
788
+ var notes = request.notes;
789
+ var priority = request.priority;
790
+
791
+ var auto_close = request.auto_close;
792
+
793
+ var followers = request.followers;
794
+ let createdAt = request.createdAt;
795
+
796
+ if (!departmentid) {
797
+ departmentid = 'default';
798
+ }
799
+
800
+ if (!createdBy) {
801
+ if (project_user_id) {
802
+ createdBy = project_user_id;
803
+ } else {
804
+ createdBy = "system";
805
+ }
806
+
807
+ }
808
+
809
+ var that = this;
810
+
811
+ return new Promise(async (resolve, reject) => {
812
+
813
+ var context = {
814
+ request: {
815
+ request_id: request_id, project_user_id: project_user_id, lead_id: lead_id, id_project: id_project,
816
+ first_text: first_text, departmentid: departmentid, sourcePage: sourcePage, language: language, userAgent: userAgent, status: status,
817
+ createdBy: createdBy, attributes: attributes, subject: subject, preflight: preflight, channel: channel, location: location,
818
+ participants: participants, tags: tags, notes: notes,
819
+ priority: priority, auto_close: auto_close, followers: followers
820
+ }
821
+ };
822
+
823
+ winston.debug("context", context);
824
+
825
+ var participantsAgents = [];
826
+ var participantsBots = [];
827
+ var hasBot = false;
828
+
829
+ var dep_id = undefined;
830
+
831
+ var assigned_at = undefined;
832
+
833
+ var agents = [];
834
+
835
+ var snapshot = {};
836
+
837
+ try {
838
+ // getOperators(departmentid, projectid, nobot, disableWebHookCall, context) {
839
+ var result = await departmentService.getOperators(departmentid, id_project, false, undefined, context);
840
+ // console.log("************* after get operator: "+new Date().toISOString());
841
+
842
+ winston.debug("getOperators", result);
843
+ } catch (err) {
844
+ return reject(err);
845
+ }
846
+
847
+
848
+
849
+ agents = result.agents;
850
+
851
+ if (status == 50) {
852
+ // skip assignment
853
+ if (participants.length == 0) {
854
+ dep_id = result.department._id;
855
+ }
856
+ } else {
857
+
858
+ if (participants.length == 0) {
859
+ if (result.operators && result.operators.length > 0) {
860
+ participants.push(result.operators[0].id_user.toString());
861
+ }
862
+ // for preflight it is important to save agents in req for trigger. try to optimize it
863
+ dep_id = result.department._id;
864
+
865
+ }
866
+
867
+ if (participants.length > 0) {
868
+
869
+ status = RequestConstants.ASSIGNED;
870
+
871
+ // botprefix
872
+ if (participants[0].startsWith("bot_")) {
873
+
874
+ hasBot = true;
875
+ winston.debug("hasBot:" + hasBot);
876
+
877
+ // botprefix
878
+ var assigned_operator_idStringBot = participants[0].replace("bot_", "");
879
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
880
+
881
+ participantsBots.push(assigned_operator_idStringBot);
882
+
883
+ } else {
884
+
885
+ participantsAgents.push(participants[0]);
886
+
887
+ }
888
+
889
+ assigned_at = Date.now();
890
+
891
+ } else {
892
+
893
+ status = RequestConstants.UNASSIGNED;
894
+
895
+ }
896
+
897
+ }
898
+
899
+
900
+
901
+
902
+ if (dep_id) {
903
+ snapshot.department = result.department;
904
+ }
905
+
906
+ // console.log("result.agents",result.agents);
907
+ snapshot.agents = agents;
908
+ snapshot.availableAgentsCount = that.getAvailableAgentsCount(agents);
909
+
910
+ if (request.requester) { //.toObject()????
911
+ snapshot.requester = request.requester;
912
+ }
913
+ if (request.lead) {
914
+ snapshot.lead = request.lead;
915
+ }
916
+
917
+ // winston.debug("assigned_operator_id", assigned_operator_id);
918
+ // winston.debug("req status", status);
919
+
920
+ var newRequest = new Request({
921
+ request_id: request_id,
922
+ requester: project_user_id,
923
+ lead: lead_id,
924
+ first_text: first_text,
925
+ subject: subject,
926
+ status: status,
927
+ participants: participants,
928
+ participantsAgents: participantsAgents,
929
+ participantsBots: participantsBots,
930
+ hasBot: hasBot,
931
+ department: dep_id,
932
+ // agents: agents,
933
+
934
+ //others
935
+ sourcePage: sourcePage,
936
+ language: language,
937
+ userAgent: userAgent,
938
+ assigned_at: assigned_at,
939
+
940
+ attributes: attributes,
941
+ //standard
942
+ id_project: id_project,
943
+ createdBy: createdBy,
944
+ updatedBy: createdBy,
945
+ preflight: preflight,
946
+ channel: channel,
947
+ location: location,
948
+ snapshot: snapshot,
949
+ tags: tags,
950
+ notes: notes,
951
+ priority: priority,
952
+ auto_close: auto_close,
953
+ followers: followers,
954
+ createdAt: createdAt
955
+ });
956
+
957
+ winston.debug('newRequest.', newRequest);
958
+
959
+
960
+ //cacheinvalidation
961
+ return newRequest.save(function (err, savedRequest) {
962
+
963
+ if (err) {
964
+ winston.error('RequestService error for method createWithIdAndRequester for newRequest' + JSON.stringify(newRequest), err);
965
+ return reject(err);
966
+ }
967
+
968
+
969
+ winston.debug("Request created", savedRequest.toObject());
970
+
971
+ var endDate = new Date();
972
+ winston.verbose("Performance Request created in millis: " + endDate - startDate);
973
+
974
+ requestEvent.emit('request.create.simple', savedRequest);
975
+
976
+ let q = Project.findOne({ _id: request.id_project, status: 100 });
977
+ if (cacheEnabler.project) {
978
+ q.cache(cacheUtil.longTTL, "projects:id:" + request.id_project) //project_cache
979
+ winston.debug('project cache enabled for /project detail');
980
+ }
981
+ q.exec(async function (err, p) {
982
+ if (err) {
983
+ winston.error('Error getting project ', err);
984
+ }
985
+ if (!p) {
986
+ winston.warn('Project not found ');
987
+ }
988
+ //TODO REMOVE settings from project
989
+ let payload = {
990
+ project: p,
991
+ request: request
992
+ }
993
+
994
+ requestEvent.emit('request.create.quote', payload);;
995
+
996
+ });
997
+
998
+ return resolve(savedRequest);
999
+
1000
+ });
1001
+ // }).catch(function(err){
1002
+ // return reject(err);
1003
+ // });
1004
+
1005
+
1006
+ });
1007
+ }
1008
+
1009
+
1010
+
1011
+
1012
+
1013
+ //DEPRECATED. USED ONLY IN SAME TESTS
1014
+ createWithId(request_id, requester_id, id_project, first_text, departmentid, sourcePage, language, userAgent, status, createdBy, attributes) {
1015
+
1016
+ // winston.debug("request_id", request_id);
1017
+
1018
+
1019
+ if (!departmentid) {
1020
+ departmentid = 'default';
1021
+ }
1022
+
1023
+ if (!createdBy) {
1024
+ createdBy = requester_id;
1025
+ }
1026
+
1027
+ var that = this;
1028
+
1029
+ return new Promise(function (resolve, reject) {
1030
+
1031
+ var context = {
1032
+ request: {
1033
+ request_id: request_id, requester_id: requester_id, id_project: id_project,
1034
+ first_text: first_text, departmentid: departmentid, sourcePage: sourcePage, language: language, userAgent: userAgent, status: status,
1035
+ createdBy: createdBy, attributes: attributes
1036
+ }
1037
+ };
1038
+
1039
+ // getOperators(departmentid, projectid, nobot, disableWebHookCall, context)
1040
+
1041
+ return departmentService.getOperators(departmentid, id_project, false, undefined, context).then(function (result) {
1042
+
1043
+ // winston.debug("getOperators", result);
1044
+
1045
+ var status = RequestConstants.UNASSIGNED;
1046
+ var assigned_operator_id;
1047
+ var participants = [];
1048
+ var participantsAgents = [];
1049
+ var participantsBots = [];
1050
+ var hasBot = false;
1051
+
1052
+ var assigned_at = undefined;
1053
+ if (result.operators && result.operators.length > 0) {
1054
+ assigned_operator_id = result.operators[0].id_user;
1055
+ status = RequestConstants.ASSIGNED;
1056
+
1057
+ var assigned_operator_idString = assigned_operator_id.toString();
1058
+ participants.push(assigned_operator_idString);
1059
+
1060
+ // botprefix
1061
+ if (assigned_operator_idString.startsWith("bot_")) {
1062
+ hasBot = true;
1063
+
1064
+ // botprefix
1065
+ var assigned_operator_idStringBot = assigned_operator_idString.replace("bot_", "");
1066
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
1067
+ participantsBots.push(assigned_operator_idStringBot);
1068
+
1069
+ } else {
1070
+ participantsAgents.push(assigned_operator_idString);
1071
+ }
1072
+ assigned_at = Date.now();
1073
+ }
1074
+ // winston.debug("assigned_operator_id", assigned_operator_id);
1075
+ // winston.debug("status", status);
1076
+
1077
+ var newRequest = new Request({
1078
+ request_id: request_id,
1079
+ requester_id: requester_id,
1080
+ first_text: first_text,
1081
+ status: status,
1082
+ participants: participants,
1083
+ participantsAgents: participantsAgents,
1084
+ participantsBots: participantsBots,
1085
+ hasBot: hasBot,
1086
+ department: result.department._id,
1087
+ agents: result.agents,
1088
+ //availableAgents: result.available_agents,
1089
+
1090
+ // assigned_operator_id: result.assigned_operator_id,
1091
+
1092
+ //others
1093
+ sourcePage: sourcePage,
1094
+ language: language,
1095
+ userAgent: userAgent,
1096
+ assigned_at: assigned_at,
1097
+ attributes: attributes,
1098
+ //standard
1099
+ id_project: id_project,
1100
+ createdBy: createdBy,
1101
+ updatedBy: createdBy
1102
+ });
1103
+
1104
+
1105
+ // winston.debug('newRequest.',newRequest);
1106
+
1107
+
1108
+
1109
+ //cacheinvalidation
1110
+ return newRequest.save(function (err, savedRequest) {
1111
+ if (err) {
1112
+ winston.error('RequestService error for method createWithId for newRequest' + JSON.stringify(newRequest), err);
1113
+ return reject(err);
1114
+ }
1115
+
1116
+
1117
+ winston.verbose("Request created", savedRequest.toObject());
1118
+
1119
+
1120
+ requestEvent.emit('request.create.simple', savedRequest);
1121
+
1122
+ return resolve(savedRequest);
1123
+
1124
+ });
1125
+ }).catch(function (err) {
1126
+ return reject(err);
1127
+ });
1128
+
1129
+
1130
+ });
1131
+
1132
+
1133
+
1134
+
794
1135
 
795
1136
  }
796
1137
 
@@ -798,31 +1139,31 @@ class RequestService {
798
1139
  changeStatusByRequestId(request_id, id_project, newstatus) {
799
1140
 
800
1141
  return new Promise(function (resolve, reject) {
801
- // winston.debug("request_id", request_id);
802
- // winston.debug("newstatus", newstatus);
1142
+ // winston.debug("request_id", request_id);
1143
+ // winston.debug("newstatus", newstatus);
803
1144
 
804
- //TODO CHECK IF ALREADY CLOSED
805
- return Request
806
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {status: newstatus}, {new: true, upsert:false})
1145
+ //TODO CHECK IF ALREADY CLOSED
1146
+ return Request
1147
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { status: newstatus }, { new: true, upsert: false })
807
1148
  .populate('lead')
808
1149
  .populate('department')
809
1150
  .populate('participatingBots')
810
- .populate('participatingAgents')
811
- .populate({path:'requester',populate:{path:'id_user'}})
812
- .exec( function(err, updatedRequest) {
1151
+ .populate('participatingAgents')
1152
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1153
+ .exec(function (err, updatedRequest) {
813
1154
 
814
- if (err) {
815
- winston.error(err);
816
- return reject(err);
817
- }
1155
+ if (err) {
1156
+ winston.error(err);
1157
+ return reject(err);
1158
+ }
818
1159
 
819
- requestEvent.emit('request.update',updatedRequest); //deprecated
820
- requestEvent.emit("request.update.comment", {comment:"STATUS_CHANGE",request:updatedRequest});//Deprecated
821
- requestEvent.emit("request.updated", {comment:"STATUS_CHANGE",request:updatedRequest, patch:{status: newstatus}});
822
- //TODO emit request.clone or reopen also
1160
+ requestEvent.emit('request.update', updatedRequest); //deprecated
1161
+ requestEvent.emit("request.update.comment", { comment: "STATUS_CHANGE", request: updatedRequest });//Deprecated
1162
+ requestEvent.emit("request.updated", { comment: "STATUS_CHANGE", request: updatedRequest, patch: { status: newstatus } });
1163
+ //TODO emit request.clone or reopen also
823
1164
 
824
- return resolve(updatedRequest);
825
- });
1165
+ return resolve(updatedRequest);
1166
+ });
826
1167
  });
827
1168
 
828
1169
  }
@@ -832,38 +1173,38 @@ class RequestService {
832
1173
 
833
1174
  return new Promise(function (resolve, reject) {
834
1175
  winston.debug("changeFirstTextAndPreflightByRequestId", request_id);
835
- // winston.debug("request_id", request_id);
836
- // winston.debug("newstatus", newstatus);
1176
+ // winston.debug("request_id", request_id);
1177
+ // winston.debug("newstatus", newstatus);
837
1178
 
838
- if (!first_text) {
839
- winston.error(err);
840
- return reject({err:" Error changing first text. The field first_text is empty"});
841
- }
842
-
843
- return Request
844
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {first_text: first_text, preflight: preflight}, {new: true, upsert:false})
1179
+ if (!first_text) {
1180
+ winston.error(err);
1181
+ return reject({ err: " Error changing first text. The field first_text is empty" });
1182
+ }
1183
+
1184
+ return Request
1185
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { first_text: first_text, preflight: preflight }, { new: true, upsert: false })
845
1186
  .populate('lead')
846
1187
  .populate('department')
847
1188
  .populate('participatingBots')
848
- .populate('participatingAgents')
849
- .populate({path:'requester',populate:{path:'id_user'}})
850
- .exec( function(err, updatedRequest) {
1189
+ .populate('participatingAgents')
1190
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1191
+ .exec(function (err, updatedRequest) {
851
1192
 
852
- if (err) {
853
- winston.error(err);
854
- return reject(err);
855
- }
1193
+ if (err) {
1194
+ winston.error(err);
1195
+ return reject(err);
1196
+ }
856
1197
 
857
-
858
- requestEvent.emit('request.update.preflight',updatedRequest); //archive to audit log
859
- requestEvent.emit('request.update',updatedRequest);
860
- requestEvent.emit("request.update.comment", {comment:"FIRSTTEXT_PREFLIGHT_CHANGE",request:updatedRequest});//Deprecated
861
- requestEvent.emit("request.updated", {comment:"FIRSTTEXT_PREFLIGHT_CHANGE",request:updatedRequest, patch: {first_text: first_text, preflight: preflight}});
862
1198
 
863
- //TODO emit request.clone or reopen also
1199
+ requestEvent.emit('request.update.preflight', updatedRequest); //archive to audit log
1200
+ requestEvent.emit('request.update', updatedRequest);
1201
+ requestEvent.emit("request.update.comment", { comment: "FIRSTTEXT_PREFLIGHT_CHANGE", request: updatedRequest });//Deprecated
1202
+ requestEvent.emit("request.updated", { comment: "FIRSTTEXT_PREFLIGHT_CHANGE", request: updatedRequest, patch: { first_text: first_text, preflight: preflight } });
864
1203
 
865
- return resolve(updatedRequest);
866
- });
1204
+ //TODO emit request.clone or reopen also
1205
+
1206
+ return resolve(updatedRequest);
1207
+ });
867
1208
  });
868
1209
 
869
1210
  }
@@ -871,30 +1212,30 @@ class RequestService {
871
1212
  changeFirstTextByRequestId(request_id, id_project, first_text) {
872
1213
 
873
1214
  return new Promise(function (resolve, reject) {
874
- // winston.debug("request_id", request_id);
875
- // winston.debug("newstatus", newstatus);
1215
+ // winston.debug("request_id", request_id);
1216
+ // winston.debug("newstatus", newstatus);
876
1217
 
877
- return Request
878
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {first_text: first_text}, {new: true, upsert:false})
1218
+ return Request
1219
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { first_text: first_text }, { new: true, upsert: false })
879
1220
  .populate('lead')
880
1221
  .populate('department')
881
1222
  .populate('participatingBots')
882
- .populate('participatingAgents')
883
- .populate({path:'requester',populate:{path:'id_user'}})
884
- .exec( function(err, updatedRequest) {
1223
+ .populate('participatingAgents')
1224
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1225
+ .exec(function (err, updatedRequest) {
885
1226
 
886
- if (err) {
887
- winston.error(err);
888
- return reject(err);
889
- }
890
- requestEvent.emit('request.update',updatedRequest);
891
- requestEvent.emit("request.update.comment", {comment:"FIRSTTEXT_CHANGE",request:updatedRequest});//Deprecated
892
- requestEvent.emit("request.updated", {comment:"FIRSTTEXT_CHANGE",request:updatedRequest, patch: {first_text: first_text}});
1227
+ if (err) {
1228
+ winston.error(err);
1229
+ return reject(err);
1230
+ }
1231
+ requestEvent.emit('request.update', updatedRequest);
1232
+ requestEvent.emit("request.update.comment", { comment: "FIRSTTEXT_CHANGE", request: updatedRequest });//Deprecated
1233
+ requestEvent.emit("request.updated", { comment: "FIRSTTEXT_CHANGE", request: updatedRequest, patch: { first_text: first_text } });
893
1234
 
894
- //TODO emit request.clone or reopen also
1235
+ //TODO emit request.clone or reopen also
895
1236
 
896
- return resolve(updatedRequest);
897
- });
1237
+ return resolve(updatedRequest);
1238
+ });
898
1239
  });
899
1240
 
900
1241
  }
@@ -904,28 +1245,28 @@ class RequestService {
904
1245
  changePreflightByRequestId(request_id, id_project, preflight) {
905
1246
 
906
1247
  return new Promise(function (resolve, reject) {
907
- // winston.debug("request_id", request_id);
908
- // winston.debug("newstatus", newstatus);
1248
+ // winston.debug("request_id", request_id);
1249
+ // winston.debug("newstatus", newstatus);
909
1250
 
910
- return Request
911
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {preflight: preflight}, {new: true, upsert:false})
1251
+ return Request
1252
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { preflight: preflight }, { new: true, upsert: false })
912
1253
  .populate('lead')
913
1254
  .populate('department')
914
1255
  .populate('participatingBots')
915
- .populate('participatingAgents')
916
- .populate({path:'requester',populate:{path:'id_user'}})
917
- .exec( function(err, updatedRequest) {
1256
+ .populate('participatingAgents')
1257
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1258
+ .exec(function (err, updatedRequest) {
918
1259
 
919
- if (err) {
920
- winston.error(err);
921
- return reject(err);
922
- }
923
- requestEvent.emit('request.update',updatedRequest);
924
- requestEvent.emit("request.update.comment", {comment:"PREFLIGHT_CHANGE",request:updatedRequest});//Deprecated
925
- requestEvent.emit("request.updated", {comment:"PREFLIGHT_CHANGE",request:updatedRequest, patch: {preflight: preflight}});
1260
+ if (err) {
1261
+ winston.error(err);
1262
+ return reject(err);
1263
+ }
1264
+ requestEvent.emit('request.update', updatedRequest);
1265
+ requestEvent.emit("request.update.comment", { comment: "PREFLIGHT_CHANGE", request: updatedRequest });//Deprecated
1266
+ requestEvent.emit("request.updated", { comment: "PREFLIGHT_CHANGE", request: updatedRequest, patch: { preflight: preflight } });
926
1267
 
927
- return resolve(updatedRequest);
928
- });
1268
+ return resolve(updatedRequest);
1269
+ });
929
1270
  });
930
1271
 
931
1272
  }
@@ -933,76 +1274,76 @@ class RequestService {
933
1274
  setClosedAtByRequestId(request_id, id_project, closed_at, closed_by) {
934
1275
 
935
1276
  return new Promise(function (resolve, reject) {
936
- // winston.debug("request_id", request_id);
937
- // winston.debug("newstatus", newstatus);
1277
+ // winston.debug("request_id", request_id);
1278
+ // winston.debug("newstatus", newstatus);
938
1279
 
939
- return Request
940
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {closed_at: closed_at, closed_by: closed_by}, {new: true, upsert:false})
1280
+ return Request
1281
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { closed_at: closed_at, closed_by: closed_by }, { new: true, upsert: false })
941
1282
  .populate('lead')
942
1283
  .populate('department')
943
1284
  .populate('participatingBots')
944
- .populate('participatingAgents')
945
- .populate({path:'requester',populate:{path:'id_user'}})
946
- .exec( function(err, updatedRequest) {
947
- if (err) {
948
- winston.error(err);
949
- return reject(err);
950
- }
1285
+ .populate('participatingAgents')
1286
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1287
+ .exec(function (err, updatedRequest) {
1288
+ if (err) {
1289
+ winston.error(err);
1290
+ return reject(err);
1291
+ }
951
1292
 
952
- // winston.debug("updatedRequest", updatedRequest);
953
- return resolve(updatedRequest);
954
- });
1293
+ // winston.debug("updatedRequest", updatedRequest);
1294
+ return resolve(updatedRequest);
1295
+ });
1296
+ });
1297
+
1298
+ }
1299
+
1300
+
1301
+
1302
+ // unused
1303
+ incrementMessagesCountByRequestId(request_id, id_project) {
1304
+
1305
+ return new Promise(function (resolve, reject) {
1306
+ // winston.debug("request_id", request_id);
1307
+ // winston.debug("newstatus", newstatus);
1308
+
1309
+ return Request
1310
+ .findOneAndUpdate({ request_id: request_id, id_project: id_project }, { $inc: { 'messages.messages_count': 1 } }, { new: true, upsert: false }, function (err, updatedRequest) {
1311
+ if (err) {
1312
+ winston.error(err);
1313
+ return reject(err);
1314
+ }
1315
+ winston.debug("Message count +1");
1316
+ return resolve(updatedRequest);
1317
+ });
955
1318
  });
956
1319
 
957
1320
  }
958
1321
 
959
-
960
-
961
- // unused
962
- incrementMessagesCountByRequestId(request_id, id_project) {
963
-
964
- return new Promise(function (resolve, reject) {
965
- // winston.debug("request_id", request_id);
966
- // winston.debug("newstatus", newstatus);
967
-
968
- return Request
969
- .findOneAndUpdate({request_id: request_id, id_project: id_project}, {$inc : {'messages.messages_count' : 1}}, {new: true, upsert:false}, function(err, updatedRequest) {
970
- if (err) {
971
- winston.error(err);
972
- return reject(err);
973
- }
974
- winston.debug("Message count +1");
975
- return resolve(updatedRequest);
976
- });
977
- });
978
-
979
- }
980
-
981
1322
  updateWaitingTimeByRequestId(request_id, id_project, enable_populate) {
982
1323
 
983
1324
  return new Promise(function (resolve, reject) {
984
- // winston.debug("request_id", request_id);
985
- // winston.debug("newstatus", newstatus);
1325
+ // winston.debug("request_id", request_id);
1326
+ // winston.debug("newstatus", newstatus);
986
1327
 
987
- let q = Request
988
- .findOne({request_id: request_id, id_project: id_project});
1328
+ let q = Request
1329
+ .findOne({ request_id: request_id, id_project: id_project });
989
1330
 
990
- if (enable_populate==true) {
1331
+ if (enable_populate == true) {
991
1332
  winston.debug("updateWaitingTimeByRequestId enable_populate");
992
1333
 
993
1334
  q.populate('lead')
994
- .populate('department')
995
- .populate('participatingBots')
996
- .populate('participatingAgents')
997
- .populate({path:'requester',populate:{path:'id_user'}});
1335
+ .populate('department')
1336
+ .populate('participatingBots')
1337
+ .populate('participatingAgents')
1338
+ .populate({ path: 'requester', populate: { path: 'id_user' } });
998
1339
  }
999
-
1340
+
1000
1341
 
1001
1342
  // if (cacheEnabler.request) { //attention this cache is not usable bacause cacheoose don't support populate without .lean.. so if cached populated field is not returned with cacheoose, updateWaitingTime is only used in chat21webhook but i thik it is important for messages route
1002
1343
  // q.cache(cacheUtil.defaultTTL, id_project+":requests:request_id:"+request_id) //request_cache
1003
1344
  // winston.debug('request cache enabled');
1004
1345
  // }
1005
- q.exec(function(err, request) {
1346
+ q.exec(function (err, request) {
1006
1347
  if (err) {
1007
1348
  winston.error(err);
1008
1349
  return reject(err);
@@ -1012,18 +1353,18 @@ class RequestService {
1012
1353
  var now = Date.now();
1013
1354
  var waitingTime = now - request.createdAt;
1014
1355
  // winston.debug("waitingTime", waitingTime);
1015
-
1016
-
1356
+
1357
+
1017
1358
  request.waiting_time = waitingTime;
1018
1359
  // TODO REENABLE SERVED
1019
1360
  // request.status = RequestConstants.SERVED;
1020
1361
  request.first_response_at = now;
1021
1362
 
1022
- // winston.debug(" request", request);
1023
- winston.debug("Request waitingTime setted");
1024
- //cacheinvalidation
1363
+ // winston.debug(" request", request);
1364
+ winston.debug("Request waitingTime setted");
1365
+ //cacheinvalidation
1025
1366
  // return resolve(request.save());
1026
- request.save(function(err, savedRequest) {
1367
+ request.save(function (err, savedRequest) {
1027
1368
  if (err) {
1028
1369
  return reject(err);
1029
1370
  }
@@ -1034,10 +1375,10 @@ class RequestService {
1034
1375
 
1035
1376
 
1036
1377
 
1037
- }else {
1378
+ } else {
1038
1379
  return resolve(request);
1039
1380
  }
1040
-
1381
+
1041
1382
  });
1042
1383
 
1043
1384
  });
@@ -1049,56 +1390,56 @@ class RequestService {
1049
1390
 
1050
1391
  var that = this;
1051
1392
  return new Promise(function (resolve, reject) {
1052
- // winston.debug("request_id", request_id);
1053
-
1054
- if (force==undefined) {
1055
- winston.debug("force is undefined ");
1056
- force = false;
1057
- }
1058
- // else {
1059
- // winston.info("force is: " + force);
1060
- // }
1061
-
1062
- return Request
1063
- .findOne({request_id: request_id, id_project: id_project})
1064
-
1065
- .populate('lead')
1066
- .populate('department')
1067
- .populate('participatingBots')
1068
- .populate('participatingAgents')
1069
- .populate({path:'requester',populate:{path:'id_user'}})
1070
- .exec( function(err, request) {
1071
-
1072
-
1073
- if (err){
1074
- winston.error("Error getting closing request ", err);
1075
- return reject(err);
1076
- }
1077
- if (!request) {
1078
- winston.error("Request not found for request_id "+ request_id + " and id_project " + id_project);
1079
- return reject({"success":false, msg:"Request not found for request_id "+ request_id + " and id_project " + id_project});
1080
- }
1081
- if (force == false && request.status == RequestConstants.CLOSED) {
1082
- // qui1000
1083
- // if (request.statusObj.closed) {
1084
- winston.debug("Request already closed for request_id "+ request_id + " and id_project " + id_project);
1085
- return resolve(request);
1086
- }
1393
+ // winston.debug("request_id", request_id);
1087
1394
 
1088
- winston.debug("sono qui");
1395
+ if (force == undefined) {
1396
+ winston.debug("force is undefined ");
1397
+ force = false;
1398
+ }
1399
+ // else {
1400
+ // winston.info("force is: " + force);
1401
+ // }
1402
+
1403
+ return Request
1404
+ .findOne({ request_id: request_id, id_project: id_project })
1405
+
1406
+ .populate('lead')
1407
+ .populate('department')
1408
+ .populate('participatingBots')
1409
+ .populate('participatingAgents')
1410
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1411
+ .exec(function (err, request) {
1412
+
1413
+
1414
+ if (err) {
1415
+ winston.error("Error getting closing request ", err);
1416
+ return reject(err);
1417
+ }
1418
+ if (!request) {
1419
+ winston.error("Request not found for request_id " + request_id + " and id_project " + id_project);
1420
+ return reject({ "success": false, msg: "Request not found for request_id " + request_id + " and id_project " + id_project });
1421
+ }
1422
+ if (force == false && request.status == RequestConstants.CLOSED) {
1423
+ // qui1000
1424
+ // if (request.statusObj.closed) {
1425
+ winston.debug("Request already closed for request_id " + request_id + " and id_project " + id_project);
1426
+ return resolve(request);
1427
+ }
1428
+
1429
+ winston.debug("sono qui");
1430
+
1431
+ // un utente può chiudere se appartiene a participatingAgents oppure meglio agents del progetto?
1432
+
1433
+
1434
+ return that.changeStatusByRequestId(request_id, id_project, 1000).then(function (updatedRequest) {
1435
+ // qui1000
1436
+ // return that.changeStatusByRequestId(request_id, id_project, {closed:true}).then(function(updatedRequest) {
1089
1437
 
1090
- // un utente può chiudere se appartiene a participatingAgents oppure meglio agents del progetto?
1091
-
1092
-
1093
- return that.changeStatusByRequestId(request_id, id_project, 1000).then(function(updatedRequest) {
1094
- // qui1000
1095
- // return that.changeStatusByRequestId(request_id, id_project, {closed:true}).then(function(updatedRequest) {
1096
-
1097
1438
 
1098
1439
  // winston.debug("updatedRequest", updatedRequest);
1099
- return messageService.getTranscriptByRequestId(request_id, id_project).then(function(transcript) {
1100
- // winston.debug("transcript", transcript);
1101
- return that.updateTrascriptByRequestId(request_id, id_project, transcript).then(function(updatedRequest) {
1440
+ return messageService.getTranscriptByRequestId(request_id, id_project).then(function (transcript) {
1441
+ // winston.debug("transcript", transcript);
1442
+ return that.updateTrascriptByRequestId(request_id, id_project, transcript).then(function (updatedRequest) {
1102
1443
 
1103
1444
 
1104
1445
  if (skipStatsUpdate) {
@@ -1107,18 +1448,18 @@ class RequestService {
1107
1448
  winston.debug("Request closed ", updatedRequest);
1108
1449
  //TODO ?? requestEvent.emit('request.update', updatedRequest);
1109
1450
  requestEvent.emit('request.close', updatedRequest);
1110
- requestEvent.emit('request.close.extended', {request: updatedRequest, notify: notify});
1451
+ requestEvent.emit('request.close.extended', { request: updatedRequest, notify: notify });
1111
1452
  return resolve(updatedRequest);
1112
1453
  }
1113
-
1454
+
1114
1455
  // setClosedAtByRequestId(request_id, id_project, closed_at, closed_by)
1115
- return that.setClosedAtByRequestId(request_id, id_project, new Date().getTime(), closed_by).then(function(updatedRequest) {
1116
-
1117
- winston.verbose("Request closed with id: " + updatedRequest.id);
1118
- winston.debug("Request closed ", updatedRequest);
1119
- //TODO ?? requestEvent.emit('request.update', updatedRequest);
1120
- requestEvent.emit('request.close', updatedRequest);
1121
- requestEvent.emit('request.close.extended', {request: updatedRequest, notify: notify});
1456
+ return that.setClosedAtByRequestId(request_id, id_project, new Date().getTime(), closed_by).then(function (updatedRequest) {
1457
+
1458
+ winston.verbose("Request closed with id: " + updatedRequest.id);
1459
+ winston.debug("Request closed ", updatedRequest);
1460
+ //TODO ?? requestEvent.emit('request.update', updatedRequest);
1461
+ requestEvent.emit('request.close', updatedRequest);
1462
+ requestEvent.emit('request.close.extended', { request: updatedRequest, notify: notify });
1122
1463
 
1123
1464
  return resolve(updatedRequest);
1124
1465
  });
@@ -1127,9 +1468,9 @@ class RequestService {
1127
1468
 
1128
1469
  });
1129
1470
  });
1130
- }).catch(function(err) {
1471
+ }).catch(function (err) {
1131
1472
  winston.error(err);
1132
- return reject(err);
1473
+ return reject(err);
1133
1474
  });
1134
1475
  });
1135
1476
  });
@@ -1141,55 +1482,55 @@ class RequestService {
1141
1482
 
1142
1483
  var that = this;
1143
1484
  return new Promise(function (resolve, reject) {
1144
- // winston.debug("request_id", request_id);
1145
-
1146
- return Request
1147
- .findOne({request_id: request_id, id_project: id_project})
1148
-
1485
+ // winston.debug("request_id", request_id);
1486
+
1487
+ return Request
1488
+ .findOne({ request_id: request_id, id_project: id_project })
1489
+
1149
1490
  .populate('lead')
1150
1491
  .populate('department')
1151
1492
  .populate('participatingBots')
1152
- .populate('participatingAgents')
1153
- .populate({path:'requester',populate:{path:'id_user'}})
1154
- .exec( function(err, request) {
1493
+ .populate('participatingAgents')
1494
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1495
+ .exec(function (err, request) {
1155
1496
 
1156
-
1157
- if (err){
1497
+
1498
+ if (err) {
1158
1499
  winston.error("Error getting reopened request ", err);
1159
1500
  return reject(err);
1160
1501
  }
1161
1502
  if (!request) {
1162
- winston.error("Request not found for request_id "+ request_id + " and id_project " + id_project);
1163
- return reject({"success":false, msg:"Request not found for request_id "+ request_id + " and id_project " + id_project});
1503
+ winston.error("Request not found for request_id " + request_id + " and id_project " + id_project);
1504
+ return reject({ "success": false, msg: "Request not found for request_id " + request_id + " and id_project " + id_project });
1164
1505
  }
1165
1506
 
1166
- if (request.status == RequestConstants.ASSIGNED || request.status == RequestConstants.UNASSIGNED
1507
+ if (request.status == RequestConstants.ASSIGNED || request.status == RequestConstants.UNASSIGNED
1167
1508
  // TODO REENABLE SERVED
1168
1509
  // || request.status == RequestConstants.SERVED
1169
- ) {
1170
- winston.debug("request already open");
1510
+ ) {
1511
+ winston.debug("request already open");
1171
1512
  return resolve(request);
1172
1513
  }
1173
1514
 
1174
- if (request.participants.length>0) {
1175
- request.status = RequestConstants.ASSIGNED;
1515
+ if (request.participants.length > 0) {
1516
+ request.status = RequestConstants.ASSIGNED;
1176
1517
  // assigned_at?
1177
1518
  } else {
1178
- request.status = RequestConstants.UNASSIGNED;
1519
+ request.status = RequestConstants.UNASSIGNED;
1179
1520
  }
1180
1521
  // TODO REENABLE SERVED
1181
1522
  // attento served qui????forse no
1182
1523
 
1183
- //cacheinvalidation
1184
- request.save(function(err, savedRequest) {
1524
+ //cacheinvalidation
1525
+ request.save(function (err, savedRequest) {
1185
1526
  if (err) {
1186
1527
  winston.error("Error saving reopened the request", err);
1187
- return reject(err);
1188
- }
1189
-
1528
+ return reject(err);
1529
+ }
1530
+
1190
1531
  requestEvent.emit('request.update', savedRequest);
1191
- requestEvent.emit("request.update.comment", {comment:"REOPEN",request:savedRequest});//Deprecated
1192
- requestEvent.emit("request.updated", {comment:"REOPEN",request:savedRequest, patch: {status: savedRequest.status}});
1532
+ requestEvent.emit("request.update.comment", { comment: "REOPEN", request: savedRequest });//Deprecated
1533
+ requestEvent.emit("request.updated", { comment: "REOPEN", request: savedRequest, patch: { status: savedRequest.status } });
1193
1534
 
1194
1535
  requestEvent.emit('request.reopen', savedRequest);
1195
1536
 
@@ -1197,18 +1538,18 @@ class RequestService {
1197
1538
 
1198
1539
  // TODO allora neanche qui participatingAgent è ok?
1199
1540
 
1200
-
1541
+
1201
1542
  return resolve(savedRequest);
1202
-
1543
+
1203
1544
  });
1204
1545
 
1205
-
1546
+
1206
1547
 
1207
1548
  })
1208
- // .catch(function(err) {
1209
- // winston.error("Error reopening the request", err);
1210
- // return reject(err);
1211
- // });
1549
+ // .catch(function(err) {
1550
+ // winston.error("Error reopening the request", err);
1551
+ // return reject(err);
1552
+ // });
1212
1553
  });
1213
1554
 
1214
1555
  }
@@ -1219,22 +1560,22 @@ class RequestService {
1219
1560
  // winston.debug("request_id", request_id);
1220
1561
  // winston.debug("transcript", transcript);
1221
1562
 
1222
- //cacheinvalidation
1223
- return Request.findOneAndUpdate({request_id: request_id, id_project: id_project}, {transcript: transcript}, {new: true, upsert:false}, function(err, updatedRequest) {
1224
- if (err) {
1225
- winston.error(err);
1226
- return reject(err);
1227
- }
1228
- // winston.debug("updatedRequest", updatedRequest);
1229
- return resolve(updatedRequest);
1230
- });
1563
+ //cacheinvalidation
1564
+ return Request.findOneAndUpdate({ request_id: request_id, id_project: id_project }, { transcript: transcript }, { new: true, upsert: false }, function (err, updatedRequest) {
1565
+ if (err) {
1566
+ winston.error(err);
1567
+ return reject(err);
1568
+ }
1569
+ // winston.debug("updatedRequest", updatedRequest);
1570
+ return resolve(updatedRequest);
1571
+ });
1231
1572
  });
1232
1573
 
1233
1574
  }
1234
1575
 
1235
1576
  findByRequestId(request_id, id_project) {
1236
1577
  return new Promise(function (resolve, reject) {
1237
- return Request.findOne({request_id: request_id, id_project: id_project}, function(err, request) {
1578
+ return Request.findOne({ request_id: request_id, id_project: id_project }, function (err, request) {
1238
1579
  if (err) {
1239
1580
  return reject(err);
1240
1581
  }
@@ -1247,141 +1588,143 @@ class RequestService {
1247
1588
 
1248
1589
 
1249
1590
  setParticipantsByRequestId(request_id, id_project, newparticipants) {
1250
-
1591
+
1251
1592
  //TODO validate participants
1252
1593
  // validate if array of string newparticipants
1253
1594
  return new Promise(function (resolve, reject) {
1254
-
1595
+
1255
1596
  var isArray = Array.isArray(newparticipants);
1256
1597
 
1257
- if(isArray==false) {
1258
- winston.error('setParticipantsByRequestId error newparticipants is not an array for request_id '+ request_id + ' and id_project '+ id_project);
1259
- return reject('setParticipantsByRequestId error newparticipants is not an array for request_id '+ request_id + ' and id_project '+ id_project);
1598
+ if (isArray == false) {
1599
+ winston.error('setParticipantsByRequestId error newparticipants is not an array for request_id ' + request_id + ' and id_project ' + id_project);
1600
+ return reject('setParticipantsByRequestId error newparticipants is not an array for request_id ' + request_id + ' and id_project ' + id_project);
1260
1601
  }
1261
1602
 
1262
1603
  return Request
1263
-
1264
- .findOne({request_id: request_id, id_project: id_project})
1265
- // qui cache ok
1266
- .exec( function(err, request) {
1267
- if (err) {
1268
- winston.error("Error setParticipantsByRequestId", err);
1269
- return reject(err);
1270
- }
1271
- if (!request) {
1272
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1273
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1274
- }
1275
- var oldParticipants = request.participants;
1276
- winston.debug('oldParticipants', oldParticipants);
1277
- winston.debug('newparticipants', newparticipants);
1278
-
1279
- if (requestUtil.arraysEqual(oldParticipants, newparticipants)){
1280
- //if (oldParticipants === newparticipants) {
1281
- winston.verbose('Request members '+ oldParticipants+ ' already equal to ' + newparticipants + ' for request_id '+ request_id + ' and id_project '+ id_project);
1282
- return request
1283
- .populate('lead')
1284
- .populate('department')
1285
- .populate('participatingBots')
1286
- .populate('participatingAgents')
1287
- .populate({path:'requester',populate:{path:'id_user'}})
1288
- .execPopulate( function(err, requestComplete) {
1289
- return resolve(requestComplete);
1290
- });
1291
1604
 
1292
- }
1605
+ .findOne({ request_id: request_id, id_project: id_project })
1606
+ // qui cache ok
1607
+ .exec(function (err, request) {
1608
+ if (err) {
1609
+ winston.error("Error setParticipantsByRequestId", err);
1610
+ return reject(err);
1611
+ }
1612
+ if (!request) {
1613
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1614
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1615
+ }
1616
+ var oldParticipants = request.participants;
1617
+ winston.debug('oldParticipants', oldParticipants);
1618
+ winston.debug('newparticipants', newparticipants);
1619
+
1620
+ if (requestUtil.arraysEqual(oldParticipants, newparticipants)) {
1621
+ //if (oldParticipants === newparticipants) {
1622
+ winston.verbose('Request members ' + oldParticipants + ' already equal to ' + newparticipants + ' for request_id ' + request_id + ' and id_project ' + id_project);
1623
+ return request
1624
+ .populate('lead')
1625
+ .populate('department')
1626
+ .populate('participatingBots')
1627
+ .populate('participatingAgents')
1628
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1629
+ .execPopulate(function (err, requestComplete) {
1630
+ return resolve(requestComplete);
1631
+ });
1293
1632
 
1294
- request.participants = newparticipants;
1633
+ }
1295
1634
 
1296
- var newparticipantsAgents = [];
1297
- var newparticipantsBots = [];
1635
+ request.participants = newparticipants;
1298
1636
 
1637
+ var newparticipantsAgents = [];
1638
+ var newparticipantsBots = [];
1299
1639
 
1300
- if (newparticipants && newparticipants.length>0) {
1301
- var hasBot = false;
1302
- newparticipants.forEach(newparticipant => {
1303
- // botprefix
1304
- if (newparticipant.startsWith("bot_")) {
1305
- hasBot = true;
1306
- // botprefix
1307
- var assigned_operator_idStringBot = newparticipant.replace("bot_","");
1308
- winston.debug("assigned_operator_idStringBot:"+assigned_operator_idStringBot);
1309
- newparticipantsBots.push(assigned_operator_idStringBot);
1310
-
1311
- }else {
1312
- newparticipantsAgents.push(newparticipant);
1313
- }
1314
- });
1315
- request.hasBot = hasBot;
1316
- }
1317
1640
 
1318
- request.participantsAgents = newparticipantsAgents;
1319
- request.participantsBots = newparticipantsBots;
1320
-
1321
-
1641
+ if (newparticipants && newparticipants.length > 0) {
1642
+ var hasBot = false;
1643
+ newparticipants.forEach(newparticipant => {
1644
+ // botprefix
1645
+ if (newparticipant.startsWith("bot_")) {
1646
+ hasBot = true;
1647
+ // botprefix
1648
+ var assigned_operator_idStringBot = newparticipant.replace("bot_", "");
1649
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
1650
+ newparticipantsBots.push(assigned_operator_idStringBot);
1322
1651
 
1652
+ } else {
1653
+ newparticipantsAgents.push(newparticipant);
1654
+ }
1655
+ });
1656
+ request.hasBot = hasBot;
1657
+ }
1323
1658
 
1659
+ request.participantsAgents = newparticipantsAgents;
1660
+ request.participantsBots = newparticipantsBots;
1324
1661
 
1325
- if (request.participants.length>0) {
1326
- request.status = RequestConstants.ASSIGNED;
1327
- // assigned_at?
1328
- } else {
1329
- request.status = RequestConstants.UNASSIGNED;
1330
- }
1331
-
1332
- request.waiting_time = undefined //reset waiting_time on reroute ????
1333
- // TODO REENABLE SERVED
1334
- // qui potrebbe essere che la richiesta era served con i vecchi agenti e poi facendo setParticipants si riporta ad assigned o unassigned perdendo l'informazione di served
1335
1662
 
1336
- //cacheinvalidation
1337
- return request.save(function(err, updatedRequest) {
1338
- // dopo save non aggiorna participating
1339
- if (err) {
1340
- winston.error("Error setParticipantsByRequestId", err);
1341
- return reject(err);
1663
+
1664
+
1665
+
1666
+ if (request.participants.length > 0) {
1667
+ request.status = RequestConstants.ASSIGNED;
1668
+ // assigned_at?
1669
+ } else {
1670
+ request.status = RequestConstants.UNASSIGNED;
1342
1671
  }
1343
-
1344
- return updatedRequest
1345
- .populate('lead')
1346
- .populate('department')
1347
- .populate('participatingBots')
1348
- .populate('participatingAgents')
1349
- .populate({path:'requester',populate:{path:'id_user'}})
1350
- .execPopulate( function(err, requestComplete) {
1351
1672
 
1673
+ request.waiting_time = undefined //reset waiting_time on reroute ????
1674
+ // TODO REENABLE SERVED
1675
+ // qui potrebbe essere che la richiesta era served con i vecchi agenti e poi facendo setParticipants si riporta ad assigned o unassigned perdendo l'informazione di served
1352
1676
 
1677
+ //cacheinvalidation
1678
+ return request.save(function (err, updatedRequest) {
1679
+ // dopo save non aggiorna participating
1353
1680
  if (err) {
1354
- winston.error("Error getting setParticipantsByRequestId", err);
1681
+ winston.error("Error setParticipantsByRequestId", err);
1355
1682
  return reject(err);
1356
1683
  }
1357
1684
 
1358
- winston.debug("oldParticipants ", oldParticipants);
1685
+ return updatedRequest
1686
+ .populate('lead')
1687
+ .populate('department')
1688
+ .populate('participatingBots')
1689
+ .populate('participatingAgents')
1690
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1691
+ .execPopulate(function (err, requestComplete) {
1692
+
1693
+
1694
+ if (err) {
1695
+ winston.error("Error getting setParticipantsByRequestId", err);
1696
+ return reject(err);
1697
+ }
1698
+
1699
+ winston.debug("oldParticipants ", oldParticipants);
1359
1700
 
1360
- let newParticipants = requestComplete.participants;
1361
- winston.debug("newParticipants ", newParticipants);
1701
+ let newParticipants = requestComplete.participants;
1702
+ winston.debug("newParticipants ", newParticipants);
1362
1703
 
1363
- var removedParticipants = oldParticipants.filter(d => !newParticipants.includes(d));
1364
- winston.debug("removedParticipants ", removedParticipants);
1704
+ var removedParticipants = oldParticipants.filter(d => !newParticipants.includes(d));
1705
+ winston.debug("removedParticipants ", removedParticipants);
1365
1706
 
1366
- var addedParticipants = newParticipants.filter(d => !oldParticipants.includes(d));
1367
- winston.debug("addedParticipants ", addedParticipants);
1707
+ var addedParticipants = newParticipants.filter(d => !oldParticipants.includes(d));
1708
+ winston.debug("addedParticipants ", addedParticipants);
1368
1709
 
1369
1710
 
1370
- requestEvent.emit('request.update', requestComplete);
1371
- requestEvent.emit("request.update.comment", {comment:"PARTICIPANTS_SET",request:requestComplete});//Deprecated
1372
- requestEvent.emit("request.updated", {comment:"PARTICIPANTS_SET",request:requestComplete, patch: {removedParticipants:removedParticipants, addedParticipants:addedParticipants}});
1711
+ requestEvent.emit('request.update', requestComplete);
1712
+ requestEvent.emit("request.update.comment", { comment: "PARTICIPANTS_SET", request: requestComplete });//Deprecated
1713
+ requestEvent.emit("request.updated", { comment: "PARTICIPANTS_SET", request: requestComplete, patch: { removedParticipants: removedParticipants, addedParticipants: addedParticipants } });
1714
+
1715
+ requestEvent.emit('request.participants.update', {
1716
+ beforeRequest: request,
1717
+ removedParticipants: removedParticipants,
1718
+ addedParticipants: addedParticipants,
1719
+ request: requestComplete
1720
+ });
1373
1721
 
1374
- requestEvent.emit('request.participants.update', {beforeRequest:request,
1375
- removedParticipants:removedParticipants,
1376
- addedParticipants:addedParticipants,
1377
- request:requestComplete});
1722
+ // TODO allora neanche qui participatingAgent è ok?
1723
+ return resolve(requestComplete);
1724
+ });
1725
+ });
1378
1726
 
1379
- // TODO allora neanche qui participatingAgent è ok?
1380
- return resolve(requestComplete);
1381
- });
1382
1727
  });
1383
-
1384
- });
1385
1728
 
1386
1729
 
1387
1730
  });
@@ -1392,108 +1735,108 @@ class RequestService {
1392
1735
  winston.debug("id_project: " + id_project);
1393
1736
  winston.debug("addParticipantByRequestId member: " + member);
1394
1737
 
1395
-
1396
1738
 
1397
- //TODO control if member is a valid project_user of the project
1398
- // validate member is string
1739
+
1740
+ //TODO control if member is a valid project_user of the project
1741
+ // validate member is string
1399
1742
  return new Promise(function (resolve, reject) {
1400
1743
 
1401
- if (member==undefined) {
1744
+ if (member == undefined) {
1402
1745
  var err = "addParticipantByRequestId error, member field is null";
1403
1746
  winston.error(err);
1404
1747
  return reject(err);
1405
1748
  }
1406
1749
 
1407
- return Request
1408
- .findOne({request_id: request_id, id_project: id_project})
1409
- // qui cache
1410
- .exec( function(err, request) {
1411
- if (err){
1412
- winston.error("Error adding participant ", err);
1413
- return reject(err);
1414
- }
1415
- if (!request) {
1416
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1417
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1418
- }
1750
+ return Request
1751
+ .findOne({ request_id: request_id, id_project: id_project })
1752
+ // qui cache
1753
+ .exec(function (err, request) {
1754
+ if (err) {
1755
+ winston.error("Error adding participant ", err);
1756
+ return reject(err);
1757
+ }
1758
+ if (!request) {
1759
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1760
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1761
+ }
1419
1762
 
1420
- winston.debug("assigned_operator here1");
1763
+ winston.debug("assigned_operator here1");
1421
1764
 
1422
- // return Request.findById(id).then(function (request) {
1423
- if (request.participants.indexOf(member)==-1){
1424
- request.participants.push(member);
1765
+ // return Request.findById(id).then(function (request) {
1766
+ if (request.participants.indexOf(member) == -1) {
1767
+ request.participants.push(member);
1425
1768
 
1426
- // botprefix
1427
- if (member.startsWith("bot_")) {
1428
- request.hasBot = true;
1769
+ // botprefix
1770
+ if (member.startsWith("bot_")) {
1771
+ request.hasBot = true;
1429
1772
 
1430
- // botprefix
1431
- var assigned_operator_idStringBot = member.replace("bot_","");
1432
- winston.debug("assigned_operator_idStringBot:"+assigned_operator_idStringBot);
1433
- request.participantsBots.push(assigned_operator_idStringBot);
1434
- }else {
1435
- request.participantsAgents.push(member);
1436
- request.hasBot = false; //???
1437
- }
1438
-
1439
-
1440
- if (request.participants.length>0) {
1441
- request.status = RequestConstants.ASSIGNED;
1442
- var assigned_at = Date.now();
1443
- request.assigned_at = assigned_at;
1444
- } else {
1445
- request.status = RequestConstants.UNASSIGNED;
1446
- }
1447
- // check error here
1448
- //cacheinvalidation
1449
- request.save(function(err, savedRequest) {
1450
- if (err) {
1451
- winston.error(err);
1452
- return reject(err);
1773
+ // botprefix
1774
+ var assigned_operator_idStringBot = member.replace("bot_", "");
1775
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
1776
+ request.participantsBots.push(assigned_operator_idStringBot);
1777
+ } else {
1778
+ request.participantsAgents.push(member);
1779
+ request.hasBot = false; //???
1453
1780
  }
1454
1781
 
1455
- winston.debug("saved", savedRequest);
1456
-
1457
- return savedRequest
1458
- .populate('lead')
1459
- .populate('department')
1460
- .populate('participatingBots')
1461
- .populate('participatingAgents')
1462
- .populate({path:'requester',populate:{path:'id_user'}})
1463
- .execPopulate( function(err, requestComplete) {
1464
1782
 
1783
+ if (request.participants.length > 0) {
1784
+ request.status = RequestConstants.ASSIGNED;
1785
+ var assigned_at = Date.now();
1786
+ request.assigned_at = assigned_at;
1787
+ } else {
1788
+ request.status = RequestConstants.UNASSIGNED;
1789
+ }
1790
+ // check error here
1791
+ //cacheinvalidation
1792
+ request.save(function (err, savedRequest) {
1465
1793
  if (err) {
1466
- winston.error("Error getting addParticipantByRequestId", err);
1794
+ winston.error(err);
1467
1795
  return reject(err);
1468
1796
  }
1469
1797
 
1798
+ winston.debug("saved", savedRequest);
1799
+
1800
+ return savedRequest
1801
+ .populate('lead')
1802
+ .populate('department')
1803
+ .populate('participatingBots')
1804
+ .populate('participatingAgents')
1805
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1806
+ .execPopulate(function (err, requestComplete) {
1807
+
1808
+ if (err) {
1809
+ winston.error("Error getting addParticipantByRequestId", err);
1810
+ return reject(err);
1811
+ }
1812
+
1813
+
1814
+ winston.debug("populated", requestComplete);
1815
+
1816
+ requestEvent.emit('request.update', requestComplete);
1817
+ requestEvent.emit("request.update.comment", { comment: "PARTICIPANT_ADD", request: requestComplete });//Deprecated
1818
+ requestEvent.emit("request.updated", { comment: "PARTICIPANT_ADD", request: requestComplete, patch: { member: member } });
1819
+ requestEvent.emit('request.participants.join', { member: member, request: requestComplete });
1820
+
1821
+ return resolve(requestComplete);
1822
+ });
1823
+ });
1824
+ // qui assignetat
1825
+ } else {
1826
+ winston.debug('Request member ' + member + ' already added for request_id ' + request_id + ' and id_project ' + id_project);
1827
+ return request
1828
+ .populate('lead')
1829
+ .populate('department')
1830
+ .populate('participatingBots')
1831
+ .populate('participatingAgents')
1832
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1833
+ .execPopulate(function (err, requestComplete) {
1834
+ return resolve(requestComplete);
1835
+ });
1836
+ }
1470
1837
 
1471
- winston.debug("populated", requestComplete);
1472
-
1473
- requestEvent.emit('request.update', requestComplete);
1474
- requestEvent.emit("request.update.comment", {comment:"PARTICIPANT_ADD",request:requestComplete});//Deprecated
1475
- requestEvent.emit("request.updated", {comment:"PARTICIPANT_ADD",request:requestComplete, patch: {member:member}});
1476
- requestEvent.emit('request.participants.join', {member:member, request: requestComplete});
1477
-
1478
- return resolve(requestComplete);
1479
- });
1480
1838
  });
1481
- // qui assignetat
1482
- } else {
1483
- winston.debug('Request member '+ member+ ' already added for request_id '+ request_id + ' and id_project '+ id_project);
1484
- return request
1485
- .populate('lead')
1486
- .populate('department')
1487
- .populate('participatingBots')
1488
- .populate('participatingAgents')
1489
- .populate({path:'requester',populate:{path:'id_user'}})
1490
- .execPopulate( function(err, requestComplete) {
1491
- return resolve(requestComplete);
1492
- });
1493
- }
1494
-
1495
- });
1496
- });
1839
+ });
1497
1840
  }
1498
1841
 
1499
1842
  removeParticipantByRequestId(request_id, id_project, member) {
@@ -1501,151 +1844,151 @@ class RequestService {
1501
1844
  winston.debug("id_project", id_project);
1502
1845
  winston.debug("member", member);
1503
1846
 
1504
- return new Promise(function (resolve, reject) {
1847
+ return new Promise(function (resolve, reject) {
1505
1848
 
1506
1849
 
1507
1850
 
1508
- if (member==undefined) {
1851
+ if (member == undefined) {
1509
1852
  var err = "removeParticipantByRequestId error, member field is null";
1510
1853
  winston.error(err);
1511
1854
  return reject(err);
1512
1855
  }
1513
1856
 
1514
-
1515
- return Request
1516
- .findOne({request_id: request_id, id_project: id_project})
1857
+
1858
+ return Request
1859
+ .findOne({ request_id: request_id, id_project: id_project })
1517
1860
  // .populate('participatingAgents') //for abandoned_by_project_users
1518
1861
  // qui cache
1519
- .exec( async (err, request) => {
1520
-
1521
- if (err){
1522
- winston.error("Error removing participant ", err);
1523
- return reject(err);
1524
- }
1862
+ .exec(async (err, request) => {
1525
1863
 
1526
- if (!request) {
1527
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1528
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1529
- }
1864
+ if (err) {
1865
+ winston.error("Error removing participant ", err);
1866
+ return reject(err);
1867
+ }
1530
1868
 
1531
- var index = request.participants.indexOf(member);
1532
- // winston.debug("index", index);
1869
+ if (!request) {
1870
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1871
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1872
+ }
1533
1873
 
1534
- if (index > -1) {
1535
- request.participants.splice(index, 1);
1536
- // winston.debug(" request.participants", request.participants);
1874
+ var index = request.participants.indexOf(member);
1875
+ // winston.debug("index", index);
1876
+
1877
+ if (index > -1) {
1878
+ request.participants.splice(index, 1);
1879
+ // winston.debug(" request.participants", request.participants);
1537
1880
 
1538
- // botprefix
1539
- if (member.startsWith("bot_")) {
1540
- request.hasBot = false;
1541
1881
  // botprefix
1542
- var assigned_operator_idStringBot = member.replace("bot_","");
1543
- winston.debug("assigned_operator_idStringBot:"+assigned_operator_idStringBot);
1544
-
1545
- var indexParticipantsBots = request.participantsBots.indexOf(assigned_operator_idStringBot);
1546
- request.participantsBots.splice(indexParticipantsBots, 1);
1547
- }else {
1548
- var indexParticipantsAgents = request.participantsAgents.indexOf(member);
1549
- request.participantsAgents.splice(indexParticipantsAgents, 1);
1550
-
1551
-
1552
-
1553
- try {
1554
-
1555
- //request.attributes.abandoned_by_project_users start TODO move to routing-queue
1556
- if (!request.attributes) {
1557
- winston.debug("removeParticipantByRequestId request.attributes is empty. creating it");
1558
- request.attributes = {};
1559
- }
1560
- if (!request.attributes.abandoned_by_project_users) {
1561
- winston.debug("removeParticipantByRequestId request.attributes.abandoned_by_project_users is empty. creating it");
1562
- request.attributes.abandoned_by_project_users = {}
1563
- }
1882
+ if (member.startsWith("bot_")) {
1883
+ request.hasBot = false;
1884
+ // botprefix
1885
+ var assigned_operator_idStringBot = member.replace("bot_", "");
1886
+ winston.debug("assigned_operator_idStringBot:" + assigned_operator_idStringBot);
1564
1887
 
1565
- /*
1566
- winston.info("request.participatingAgents",request.participatingAgents);
1567
- var pu = request.participatingAgents.find(projectUser => {
1568
- console.log(projectUser);
1569
- projectUser.id_user.toString() === member
1570
- });
1571
- winston.verbose("pu",pu);
1572
- */
1888
+ var indexParticipantsBots = request.participantsBots.indexOf(assigned_operator_idStringBot);
1889
+ request.participantsBots.splice(indexParticipantsBots, 1);
1890
+ } else {
1891
+ var indexParticipantsAgents = request.participantsAgents.indexOf(member);
1892
+ request.participantsAgents.splice(indexParticipantsAgents, 1);
1573
1893
 
1574
- var pu = await Project_user.findOne({ id_user: member, id_project:id_project }).exec();
1575
- winston.debug("pu",pu);
1576
1894
 
1577
- request.attributes.abandoned_by_project_users[pu._id] = new Date().getTime();
1578
- winston.debug("removeParticipantByRequestId request.attributes.abandoned_by_project_users", request.attributes.abandoned_by_project_users);
1579
- //request.attributes.abandoned_by_project_users end
1580
1895
 
1581
- }catch(e) {
1582
- winston.error("Error getting removeParticipantByRequestId pu",e);
1583
- }
1584
-
1896
+ try {
1585
1897
 
1586
- }
1898
+ //request.attributes.abandoned_by_project_users start TODO move to routing-queue
1899
+ if (!request.attributes) {
1900
+ winston.debug("removeParticipantByRequestId request.attributes is empty. creating it");
1901
+ request.attributes = {};
1902
+ }
1903
+ if (!request.attributes.abandoned_by_project_users) {
1904
+ winston.debug("removeParticipantByRequestId request.attributes.abandoned_by_project_users is empty. creating it");
1905
+ request.attributes.abandoned_by_project_users = {}
1906
+ }
1907
+
1908
+ /*
1909
+ winston.info("request.participatingAgents",request.participatingAgents);
1910
+ var pu = request.participatingAgents.find(projectUser => {
1911
+ console.log(projectUser);
1912
+ projectUser.id_user.toString() === member
1913
+ });
1914
+ winston.verbose("pu",pu);
1915
+ */
1916
+
1917
+ var pu = await Project_user.findOne({ id_user: member, id_project: id_project }).exec();
1918
+ winston.debug("pu", pu);
1919
+
1920
+ request.attributes.abandoned_by_project_users[pu._id] = new Date().getTime();
1921
+ winston.debug("removeParticipantByRequestId request.attributes.abandoned_by_project_users", request.attributes.abandoned_by_project_users);
1922
+ //request.attributes.abandoned_by_project_users end
1923
+
1924
+ } catch (e) {
1925
+ winston.error("Error getting removeParticipantByRequestId pu", e);
1926
+ }
1587
1927
 
1588
1928
 
1589
- if (request.status!= RequestConstants.CLOSED) {//don't change the status to 100 or 200 for closed request to resolve this bug. if the agent leave the group and after close the request the status became 100, but if the request is closed the state (1000) must not be changed
1590
- // qui1000 ????
1591
- if (request.participants.length>0) {
1592
- request.status = RequestConstants.ASSIGNED;
1593
- // assignet_at?
1594
- } else {
1595
- request.status = RequestConstants.UNASSIGNED;
1596
- }
1597
- }
1598
-
1599
- request.markModified('attributes');
1600
- // winston.debug(" request", request);
1601
- //cacheinvalidation
1602
- return request.save(function(err, savedRequest) {
1603
- if (err){
1604
- winston.error("Error saving removed participant ", err);
1605
- return reject(err);
1606
1929
  }
1607
-
1608
- return savedRequest
1609
- .populate('lead')
1610
- .populate('department')
1611
- .populate('participatingBots')
1612
- .populate('participatingAgents')
1613
- .populate({path:'requester',populate:{path:'id_user'}})
1614
- .execPopulate( function(err, requestComplete) {
1615
-
1616
- if (err){
1617
- winston.error("Error getting removed participant ", err);
1618
- return reject(err);
1930
+
1931
+
1932
+ if (request.status != RequestConstants.CLOSED) {//don't change the status to 100 or 200 for closed request to resolve this bug. if the agent leave the group and after close the request the status became 100, but if the request is closed the state (1000) must not be changed
1933
+ // qui1000 ????
1934
+ if (request.participants.length > 0) {
1935
+ request.status = RequestConstants.ASSIGNED;
1936
+ // assignet_at?
1937
+ } else {
1938
+ request.status = RequestConstants.UNASSIGNED;
1939
+ }
1619
1940
  }
1620
1941
 
1621
-
1622
- requestEvent.emit('request.update', requestComplete);
1623
- requestEvent.emit("request.update.comment", {comment:"PARTICIPANT_REMOVE",request:requestComplete});//Deprecated
1624
- requestEvent.emit("request.updated", {comment:"PARTICIPANT_REMOVE",request:requestComplete, patch: {member:member}});
1625
- requestEvent.emit('request.participants.leave', {member:member, request: requestComplete});
1626
-
1942
+ request.markModified('attributes');
1943
+ // winston.debug(" request", request);
1944
+ //cacheinvalidation
1945
+ return request.save(function (err, savedRequest) {
1946
+ if (err) {
1947
+ winston.error("Error saving removed participant ", err);
1948
+ return reject(err);
1949
+ }
1950
+
1951
+ return savedRequest
1952
+ .populate('lead')
1953
+ .populate('department')
1954
+ .populate('participatingBots')
1955
+ .populate('participatingAgents')
1956
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1957
+ .execPopulate(function (err, requestComplete) {
1958
+
1959
+ if (err) {
1960
+ winston.error("Error getting removed participant ", err);
1961
+ return reject(err);
1962
+ }
1963
+
1964
+
1965
+ requestEvent.emit('request.update', requestComplete);
1966
+ requestEvent.emit("request.update.comment", { comment: "PARTICIPANT_REMOVE", request: requestComplete });//Deprecated
1967
+ requestEvent.emit("request.updated", { comment: "PARTICIPANT_REMOVE", request: requestComplete, patch: { member: member } });
1968
+ requestEvent.emit('request.participants.leave', { member: member, request: requestComplete });
1969
+
1627
1970
 
1628
- return resolve(requestComplete);
1971
+ return resolve(requestComplete);
1629
1972
 
1630
- });
1631
- });
1973
+ });
1974
+ });
1632
1975
 
1633
1976
 
1634
- }else {
1635
- winston.verbose('Request member '+ member+ ' already not found for request_id '+ request_id + ' and id_project '+ id_project);
1977
+ } else {
1978
+ winston.verbose('Request member ' + member + ' already not found for request_id ' + request_id + ' and id_project ' + id_project);
1636
1979
 
1637
- return request
1638
- .populate('lead')
1639
- .populate('department')
1640
- .populate('participatingBots')
1641
- .populate('participatingAgents')
1642
- .populate({path:'requester',populate:{path:'id_user'}})
1643
- .execPopulate( function(err, requestComplete) {
1644
- return resolve(requestComplete);
1645
- });
1646
- }
1647
-
1648
- });
1980
+ return request
1981
+ .populate('lead')
1982
+ .populate('department')
1983
+ .populate('participatingBots')
1984
+ .populate('participatingAgents')
1985
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
1986
+ .execPopulate(function (err, requestComplete) {
1987
+ return resolve(requestComplete);
1988
+ });
1989
+ }
1990
+
1991
+ });
1649
1992
  });
1650
1993
  }
1651
1994
 
@@ -1653,57 +1996,57 @@ class RequestService {
1653
1996
 
1654
1997
  updateAttributesByRequestId(request_id, id_project, attributes) {
1655
1998
  var data = attributes;
1656
-
1657
- Request.findOne({"request_id":request_id, id_project:id_project})
1658
- .populate('lead')
1659
- .populate('department')
1660
- .populate('participatingBots')
1661
- .populate('participatingAgents')
1662
- .populate({path:'requester',populate:{path:'id_user'}})
1663
- .exec( function(err, request) {
1999
+
2000
+ Request.findOne({ "request_id": request_id, id_project: id_project })
2001
+ .populate('lead')
2002
+ .populate('department')
2003
+ .populate('participatingBots')
2004
+ .populate('participatingAgents')
2005
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2006
+ .exec(function (err, request) {
1664
2007
  if (err) {
1665
2008
  return reject(err);
1666
2009
  }
1667
2010
  if (!request) {
1668
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
2011
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
1669
2012
  }
1670
-
1671
-
2013
+
2014
+
1672
2015
  if (!request.attributes) {
1673
2016
  winston.debug("empty attributes")
1674
2017
  request.attributes = {};
1675
2018
  }
1676
-
2019
+
1677
2020
  winston.debug(" req attributes", request.attributes)
1678
-
1679
- Object.keys(data).forEach(function(key) {
1680
- var val = data[key];
1681
- winston.debug("data attributes "+key+" " +val)
1682
- request.attributes[key] = val;
1683
- });
1684
-
1685
- winston.debug(" req attributes", request.attributes)
1686
-
1687
- // https://stackoverflow.com/questions/24054552/mongoose-not-saving-nested-object
1688
- request.markModified('attributes');
1689
-
1690
- //cacheinvalidation
1691
- return request.save(function (err, savedRequest) {
1692
- if (err) {
1693
- winston.error("error saving request attributes",err)
1694
- return reject({msg:"Error saving request attributes",err:err});
1695
- }
1696
- winston.verbose(" saved request attributes",savedRequest.toObject())
1697
- requestEvent.emit("request.update", savedRequest);
1698
- requestEvent.emit("request.update.comment", {comment:"ATTRIBUTES_UPDATE",request:savedRequest});//Deprecated
1699
- requestEvent.emit("request.updated", {comment:"ATTRIBUTES_UPDATE",request:savedRequest, patch: {attributes:data}});
1700
2021
 
1701
- requestEvent.emit("request.attributes.update", savedRequest);
1702
- // allora neanche qui participatingAgent è ok?
1703
- return resolve(savedRequest);
1704
- });
1705
- });
1706
-
2022
+ Object.keys(data).forEach(function (key) {
2023
+ var val = data[key];
2024
+ winston.debug("data attributes " + key + " " + val)
2025
+ request.attributes[key] = val;
2026
+ });
2027
+
2028
+ winston.debug(" req attributes", request.attributes)
2029
+
2030
+ // https://stackoverflow.com/questions/24054552/mongoose-not-saving-nested-object
2031
+ request.markModified('attributes');
2032
+
2033
+ //cacheinvalidation
2034
+ return request.save(function (err, savedRequest) {
2035
+ if (err) {
2036
+ winston.error("error saving request attributes", err)
2037
+ return reject({ msg: "Error saving request attributes", err: err });
2038
+ }
2039
+ winston.verbose(" saved request attributes", savedRequest.toObject())
2040
+ requestEvent.emit("request.update", savedRequest);
2041
+ requestEvent.emit("request.update.comment", { comment: "ATTRIBUTES_UPDATE", request: savedRequest });//Deprecated
2042
+ requestEvent.emit("request.updated", { comment: "ATTRIBUTES_UPDATE", request: savedRequest, patch: { attributes: data } });
2043
+
2044
+ requestEvent.emit("request.attributes.update", savedRequest);
2045
+ // allora neanche qui participatingAgent è ok?
2046
+ return resolve(savedRequest);
2047
+ });
2048
+ });
2049
+
1707
2050
  }
1708
2051
 
1709
2052
 
@@ -1718,59 +2061,59 @@ class RequestService {
1718
2061
 
1719
2062
  return new Promise(function (resolve, reject) {
1720
2063
 
1721
- if (tag==undefined) {
2064
+ if (tag == undefined) {
1722
2065
  var err = "addTagByRequestId error, tag field is null";
1723
2066
  winston.error(err);
1724
2067
  return reject(err);
1725
2068
  }
1726
-
1727
2069
 
1728
- return Request
1729
- .findOne({request_id: request_id, id_project: id_project})
1730
- .populate('lead')
2070
+
2071
+ return Request
2072
+ .findOne({ request_id: request_id, id_project: id_project })
2073
+ .populate('lead')
1731
2074
  .populate('department')
1732
2075
  .populate('participatingBots')
1733
- .populate('participatingAgents')
1734
- .populate({path:'requester',populate:{path:'id_user'}})
1735
- .exec( function(err, request) {
1736
- if (err){
1737
- winston.error("Error adding tag ", err);
1738
- return reject(err);
1739
- }
1740
- if (!request) {
1741
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1742
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1743
- }
2076
+ .populate('participatingAgents')
2077
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2078
+ .exec(function (err, request) {
2079
+ if (err) {
2080
+ winston.error("Error adding tag ", err);
2081
+ return reject(err);
2082
+ }
2083
+ if (!request) {
2084
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2085
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2086
+ }
1744
2087
 
1745
2088
 
1746
- // return Request.findById(id).then(function (request) {
1747
- if (request.tags.indexOf(tag)==-1){
1748
- request.tags.push(tag);
1749
- // check error here
2089
+ // return Request.findById(id).then(function (request) {
2090
+ if (request.tags.indexOf(tag) == -1) {
2091
+ request.tags.push(tag);
2092
+ // check error here
1750
2093
 
1751
- //cacheinvalidation
1752
- request.save(function(err, savedRequest) {
1753
- if (err) {
1754
- winston.error(err);
1755
- return reject(err);
1756
- }
1757
-
1758
- requestEvent.emit('request.update', savedRequest);
1759
- requestEvent.emit("request.update.comment", {comment:"TAG_ADD",request:savedRequest}); //Deprecated
1760
- requestEvent.emit("request.updated", {comment:"TAG_ADD",request:savedRequest, patch: {tags:tag}});
2094
+ //cacheinvalidation
2095
+ request.save(function (err, savedRequest) {
2096
+ if (err) {
2097
+ winston.error(err);
2098
+ return reject(err);
2099
+ }
1761
2100
 
1762
-
1763
- // allora neanche qui participatingAgent è ok?
1764
- return resolve(savedRequest);
1765
- });
2101
+ requestEvent.emit('request.update', savedRequest);
2102
+ requestEvent.emit("request.update.comment", { comment: "TAG_ADD", request: savedRequest }); //Deprecated
2103
+ requestEvent.emit("request.updated", { comment: "TAG_ADD", request: savedRequest, patch: { tags: tag } });
1766
2104
 
1767
- // qui assignetat
1768
- } else {
1769
- winston.debug('Request tag '+ tag+ ' already added for request_id '+ request_id + ' and id_project '+ id_project);
1770
- return resolve(request);
1771
- }
1772
- });
1773
- });
2105
+
2106
+ // allora neanche qui participatingAgent è ok?
2107
+ return resolve(savedRequest);
2108
+ });
2109
+
2110
+ // qui assignetat
2111
+ } else {
2112
+ winston.debug('Request tag ' + tag + ' already added for request_id ' + request_id + ' and id_project ' + id_project);
2113
+ return resolve(request);
2114
+ }
2115
+ });
2116
+ });
1774
2117
  }
1775
2118
 
1776
2119
 
@@ -1783,66 +2126,66 @@ class RequestService {
1783
2126
 
1784
2127
 
1785
2128
 
1786
- if (tag==undefined) {
2129
+ if (tag == undefined) {
1787
2130
  var err = "removeTagByRequestId error, tag field is null";
1788
2131
  winston.error(err);
1789
2132
  return reject(err);
1790
2133
  }
1791
2134
 
1792
-
1793
- return Request
1794
- .findOne({request_id: request_id, id_project: id_project})
2135
+
2136
+ return Request
2137
+ .findOne({ request_id: request_id, id_project: id_project })
1795
2138
  .populate('lead')
1796
2139
  .populate('department')
1797
2140
  .populate('participatingBots')
1798
- .populate('participatingAgents')
1799
- .populate({path:'requester',populate:{path:'id_user'}})
1800
- .exec( function(err, request) {
1801
-
1802
- if (err){
1803
- winston.error("Error removing tag ", err);
1804
- return reject(err);
1805
- }
2141
+ .populate('participatingAgents')
2142
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2143
+ .exec(function (err, request) {
1806
2144
 
1807
- if (!request) {
1808
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1809
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1810
- }
2145
+ if (err) {
2146
+ winston.error("Error removing tag ", err);
2147
+ return reject(err);
2148
+ }
2149
+
2150
+ if (!request) {
2151
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2152
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2153
+ }
1811
2154
 
1812
- // var index = request.tags.indexOf(tag);
1813
- var index = request.tags.findIndex(t => t.tag === tag);
2155
+ // var index = request.tags.indexOf(tag);
2156
+ var index = request.tags.findIndex(t => t.tag === tag);
1814
2157
 
1815
- winston.debug("index", index);
2158
+ winston.debug("index", index);
1816
2159
 
1817
- if (index > -1) {
1818
- request.tags.splice(index, 1);
1819
- // winston.debug(" request.participants", request.participants);
1820
-
2160
+ if (index > -1) {
2161
+ request.tags.splice(index, 1);
2162
+ // winston.debug(" request.participants", request.participants);
1821
2163
 
1822
- //cacheinvalidation
1823
- request.save(function(err, savedRequest) {
1824
2164
 
1825
- if (!err) {
1826
- requestEvent.emit('request.update', savedRequest);
1827
- requestEvent.emit("request.update.comment", {comment:"TAG_REMOVE",request:savedRequest});//Deprecated
1828
- requestEvent.emit("request.updated", {comment:"TAG_REMOVE",request:savedRequest, patch: {tags:tag}});
2165
+ //cacheinvalidation
2166
+ request.save(function (err, savedRequest) {
1829
2167
 
1830
- }
2168
+ if (!err) {
2169
+ requestEvent.emit('request.update', savedRequest);
2170
+ requestEvent.emit("request.update.comment", { comment: "TAG_REMOVE", request: savedRequest });//Deprecated
2171
+ requestEvent.emit("request.updated", { comment: "TAG_REMOVE", request: savedRequest, patch: { tags: tag } });
1831
2172
 
1832
- // allora neanche qui participatingAgent è ok?
2173
+ }
1833
2174
 
1834
- return resolve(savedRequest);
2175
+ // allora neanche qui participatingAgent è ok?
1835
2176
 
1836
- });
2177
+ return resolve(savedRequest);
1837
2178
 
2179
+ });
1838
2180
 
1839
- }else {
1840
- winston.info('Request tag '+ tag+ ' already not found for request_id '+ request_id + ' and id_project '+ id_project);
1841
- return resolve(request);
1842
- }
1843
-
1844
-
1845
- });
2181
+
2182
+ } else {
2183
+ winston.info('Request tag ' + tag + ' already not found for request_id ' + request_id + ' and id_project ' + id_project);
2184
+ return resolve(request);
2185
+ }
2186
+
2187
+
2188
+ });
1846
2189
  });
1847
2190
  }
1848
2191
 
@@ -1858,87 +2201,87 @@ class RequestService {
1858
2201
  winston.debug("id_project: " + id_project);
1859
2202
  winston.debug("addFollowerByRequestId member: " + member);
1860
2203
 
1861
-
1862
2204
 
1863
- //TODO control if member is a valid project_user of the project
1864
- // validate member is string
2205
+
2206
+ //TODO control if member is a valid project_user of the project
2207
+ // validate member is string
1865
2208
  return new Promise(function (resolve, reject) {
1866
2209
 
1867
- if (member==undefined) {
2210
+ if (member == undefined) {
1868
2211
  var err = "addFollowerByRequestId error, member field is null";
1869
2212
  winston.error(err);
1870
2213
  return reject(err);
1871
2214
  }
1872
2215
 
1873
- return Request
1874
- .findOne({request_id: request_id, id_project: id_project})
1875
- // qui cache
1876
- .exec( function(err, request) {
1877
- if (err){
1878
- winston.error("Error adding follower ", err);
1879
- return reject(err);
1880
- }
1881
- if (!request) {
1882
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1883
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1884
- }
1885
-
1886
- winston.debug("assigned_operator here1");
1887
-
1888
- // return Request.findById(id).then(function (request) {
1889
- if (request.followers.indexOf(member)==-1){
1890
- request.followers.push(member);
1891
-
1892
- request.save(function(err, savedRequest) {
1893
- if (err) {
1894
- winston.error(err);
1895
- return reject(err);
1896
- }
2216
+ return Request
2217
+ .findOne({ request_id: request_id, id_project: id_project })
2218
+ // qui cache
2219
+ .exec(function (err, request) {
2220
+ if (err) {
2221
+ winston.error("Error adding follower ", err);
2222
+ return reject(err);
2223
+ }
2224
+ if (!request) {
2225
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2226
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2227
+ }
1897
2228
 
1898
- winston.debug("saved", savedRequest);
2229
+ winston.debug("assigned_operator here1");
1899
2230
 
1900
- return savedRequest
1901
- .populate('lead')
1902
- .populate('department')
1903
- .populate('participatingBots')
1904
- .populate('participatingAgents')
1905
- // .populate('followers')
1906
- .populate({path:'requester',populate:{path:'id_user'}})
1907
- .execPopulate( function(err, requestComplete) {
2231
+ // return Request.findById(id).then(function (request) {
2232
+ if (request.followers.indexOf(member) == -1) {
2233
+ request.followers.push(member);
1908
2234
 
2235
+ request.save(function (err, savedRequest) {
1909
2236
  if (err) {
1910
- winston.error("Error getting addFollowerByRequestId", err);
2237
+ winston.error(err);
1911
2238
  return reject(err);
1912
2239
  }
1913
2240
 
2241
+ winston.debug("saved", savedRequest);
2242
+
2243
+ return savedRequest
2244
+ .populate('lead')
2245
+ .populate('department')
2246
+ .populate('participatingBots')
2247
+ .populate('participatingAgents')
2248
+ // .populate('followers')
2249
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2250
+ .execPopulate(function (err, requestComplete) {
2251
+
2252
+ if (err) {
2253
+ winston.error("Error getting addFollowerByRequestId", err);
2254
+ return reject(err);
2255
+ }
2256
+
2257
+
2258
+ winston.debug("populated", requestComplete);
2259
+
2260
+ requestEvent.emit('request.update', requestComplete);
2261
+ requestEvent.emit("request.update.comment", { comment: "FOLLOWER_ADD", request: requestComplete });//Deprecated
2262
+ requestEvent.emit("request.updated", { comment: "FOLLOWER_ADD", request: requestComplete, patch: { member: member } });
2263
+ requestEvent.emit('request.followers.join', { member: member, request: requestComplete });
2264
+
2265
+ return resolve(requestComplete);
2266
+ });
2267
+ });
2268
+ // qui assignetat
2269
+ } else {
2270
+ winston.debug('Request member ' + member + ' already added for request_id ' + request_id + ' and id_project ' + id_project);
2271
+ return request
2272
+ .populate('lead')
2273
+ .populate('department')
2274
+ .populate('participatingBots')
2275
+ .populate('participatingAgents')
2276
+ // .populate('followers')
2277
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2278
+ .execPopulate(function (err, requestComplete) {
2279
+ return resolve(requestComplete);
2280
+ });
2281
+ }
1914
2282
 
1915
- winston.debug("populated", requestComplete);
1916
-
1917
- requestEvent.emit('request.update', requestComplete);
1918
- requestEvent.emit("request.update.comment", {comment:"FOLLOWER_ADD",request:requestComplete});//Deprecated
1919
- requestEvent.emit("request.updated", {comment:"FOLLOWER_ADD",request:requestComplete, patch: {member:member}});
1920
- requestEvent.emit('request.followers.join', {member:member, request: requestComplete});
1921
-
1922
- return resolve(requestComplete);
1923
- });
1924
2283
  });
1925
- // qui assignetat
1926
- } else {
1927
- winston.debug('Request member '+ member+ ' already added for request_id '+ request_id + ' and id_project '+ id_project);
1928
- return request
1929
- .populate('lead')
1930
- .populate('department')
1931
- .populate('participatingBots')
1932
- .populate('participatingAgents')
1933
- // .populate('followers')
1934
- .populate({path:'requester',populate:{path:'id_user'}})
1935
- .execPopulate( function(err, requestComplete) {
1936
- return resolve(requestComplete);
1937
- });
1938
- }
1939
-
1940
- });
1941
- });
2284
+ });
1942
2285
  }
1943
2286
 
1944
2287
 
@@ -1946,90 +2289,90 @@ class RequestService {
1946
2289
 
1947
2290
 
1948
2291
  setFollowersByRequestId(request_id, id_project, newfollowers) {
1949
-
2292
+
1950
2293
  //TODO validate participants
1951
2294
  // validate if array of string newparticipants
1952
2295
  return new Promise(function (resolve, reject) {
1953
-
2296
+
1954
2297
  var isArray = Array.isArray(newfollowers);
1955
2298
 
1956
- if(isArray==false) {
1957
- winston.error('setFollowersByRequestId error newfollowers is not an array for request_id '+ request_id + ' and id_project '+ id_project);
1958
- return reject('setFollowersByRequestId error newfollowers is not an array for request_id '+ request_id + ' and id_project '+ id_project);
2299
+ if (isArray == false) {
2300
+ winston.error('setFollowersByRequestId error newfollowers is not an array for request_id ' + request_id + ' and id_project ' + id_project);
2301
+ return reject('setFollowersByRequestId error newfollowers is not an array for request_id ' + request_id + ' and id_project ' + id_project);
1959
2302
  }
1960
2303
 
1961
2304
  return Request
1962
-
1963
- .findOne({request_id: request_id, id_project: id_project})
1964
- // qui cache ok
1965
- .exec( function(err, request) {
1966
- if (err) {
1967
- winston.error("Error setFollowersByRequestId", err);
1968
- return reject(err);
1969
- }
1970
- if (!request) {
1971
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1972
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
1973
- }
1974
- var oldfollowers = request.followers;
1975
- winston.debug('oldParticipants', oldfollowers);
1976
- winston.debug('newparticipants', newfollowers);
1977
-
1978
- if (requestUtil.arraysEqual(oldfollowers, newfollowers)){
1979
- //if (oldParticipants === newparticipants) {
1980
- winston.verbose('Request members '+ oldfollowers+ ' already equal to ' + newfollowers + ' for request_id '+ request_id + ' and id_project '+ id_project);
1981
- return request
1982
- .populate('lead')
1983
- .populate('department')
1984
- .populate('participatingBots')
1985
- .populate('participatingAgents')
1986
- .populate({path:'requester',populate:{path:'id_user'}})
1987
- .execPopulate( function(err, requestComplete) {
1988
- return resolve(requestComplete);
1989
- });
1990
-
1991
- }
1992
2305
 
1993
- request.followers = newfollowers;
1994
-
1995
- //cacheinvalidation
1996
- return request.save(function(err, updatedRequest) {
1997
- // dopo save non aggiorna participating
2306
+ .findOne({ request_id: request_id, id_project: id_project })
2307
+ // qui cache ok
2308
+ .exec(function (err, request) {
1998
2309
  if (err) {
1999
2310
  winston.error("Error setFollowersByRequestId", err);
2000
2311
  return reject(err);
2001
2312
  }
2002
-
2003
- return updatedRequest
2004
- .populate('lead')
2005
- .populate('department')
2006
- .populate('participatingBots')
2007
- .populate('participatingAgents')
2008
- .populate({path:'requester',populate:{path:'id_user'}})
2009
- .execPopulate( function(err, requestComplete) {
2313
+ if (!request) {
2314
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2315
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2316
+ }
2317
+ var oldfollowers = request.followers;
2318
+ winston.debug('oldParticipants', oldfollowers);
2319
+ winston.debug('newparticipants', newfollowers);
2320
+
2321
+ if (requestUtil.arraysEqual(oldfollowers, newfollowers)) {
2322
+ //if (oldParticipants === newparticipants) {
2323
+ winston.verbose('Request members ' + oldfollowers + ' already equal to ' + newfollowers + ' for request_id ' + request_id + ' and id_project ' + id_project);
2324
+ return request
2325
+ .populate('lead')
2326
+ .populate('department')
2327
+ .populate('participatingBots')
2328
+ .populate('participatingAgents')
2329
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2330
+ .execPopulate(function (err, requestComplete) {
2331
+ return resolve(requestComplete);
2332
+ });
2010
2333
 
2334
+ }
2335
+
2336
+ request.followers = newfollowers;
2011
2337
 
2338
+ //cacheinvalidation
2339
+ return request.save(function (err, updatedRequest) {
2340
+ // dopo save non aggiorna participating
2012
2341
  if (err) {
2013
- winston.error("Error getting setFollowersByRequestId", err);
2342
+ winston.error("Error setFollowersByRequestId", err);
2014
2343
  return reject(err);
2015
2344
  }
2016
2345
 
2017
- winston.debug("oldfollowers ", oldfollowers);
2346
+ return updatedRequest
2347
+ .populate('lead')
2348
+ .populate('department')
2349
+ .populate('participatingBots')
2350
+ .populate('participatingAgents')
2351
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2352
+ .execPopulate(function (err, requestComplete) {
2353
+
2354
+
2355
+ if (err) {
2356
+ winston.error("Error getting setFollowersByRequestId", err);
2357
+ return reject(err);
2358
+ }
2359
+
2360
+ winston.debug("oldfollowers ", oldfollowers);
2018
2361
 
2019
- requestEvent.emit('request.update', requestComplete);
2020
- requestEvent.emit("request.update.comment", {comment:"FOLLOWERS_SET",request:requestComplete});//Deprecated
2021
- requestEvent.emit("request.updated", {comment:"FOLLOWERS_SET",request:requestComplete, patch: {}});
2362
+ requestEvent.emit('request.update', requestComplete);
2363
+ requestEvent.emit("request.update.comment", { comment: "FOLLOWERS_SET", request: requestComplete });//Deprecated
2364
+ requestEvent.emit("request.updated", { comment: "FOLLOWERS_SET", request: requestComplete, patch: {} });
2022
2365
 
2023
- // requestEvent.emit('request.followers.update', {beforeRequest:request,
2024
- // removedParticipants:removedParticipants,
2025
- // addedParticipants:addedParticipants,
2026
- // request:requestComplete});
2366
+ // requestEvent.emit('request.followers.update', {beforeRequest:request,
2367
+ // removedParticipants:removedParticipants,
2368
+ // addedParticipants:addedParticipants,
2369
+ // request:requestComplete});
2370
+
2371
+ return resolve(requestComplete);
2372
+ });
2373
+ });
2027
2374
 
2028
- return resolve(requestComplete);
2029
- });
2030
2375
  });
2031
-
2032
- });
2033
2376
 
2034
2377
 
2035
2378
  });
@@ -2045,92 +2388,92 @@ class RequestService {
2045
2388
  winston.debug("id_project", id_project);
2046
2389
  winston.debug("member", member);
2047
2390
 
2048
- return new Promise(function (resolve, reject) {
2391
+ return new Promise(function (resolve, reject) {
2049
2392
 
2050
2393
 
2051
2394
 
2052
- if (member==undefined) {
2395
+ if (member == undefined) {
2053
2396
  var err = "removeFollowerByRequestId error, member field is null";
2054
2397
  winston.error(err);
2055
2398
  return reject(err);
2056
2399
  }
2057
2400
 
2058
-
2059
- return Request
2060
- .findOne({request_id: request_id, id_project: id_project})
2401
+
2402
+ return Request
2403
+ .findOne({ request_id: request_id, id_project: id_project })
2061
2404
  // .populate('participatingAgents') //for abandoned_by_project_users
2062
2405
  // qui cache
2063
- .exec( async (err, request) => {
2064
-
2065
- if (err){
2066
- winston.error("Error removing follower ", err);
2067
- return reject(err);
2068
- }
2406
+ .exec(async (err, request) => {
2069
2407
 
2070
- if (!request) {
2071
- winston.error('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
2072
- return reject('Request not found for request_id '+ request_id + ' and id_project '+ id_project);
2073
- }
2408
+ if (err) {
2409
+ winston.error("Error removing follower ", err);
2410
+ return reject(err);
2411
+ }
2412
+
2413
+ if (!request) {
2414
+ winston.error('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2415
+ return reject('Request not found for request_id ' + request_id + ' and id_project ' + id_project);
2416
+ }
2074
2417
 
2075
- var index = request.followers.indexOf(member);
2076
- winston.debug("index", index);
2418
+ var index = request.followers.indexOf(member);
2419
+ winston.debug("index", index);
2077
2420
 
2078
- if (index > -1) {
2079
- request.followers.splice(index, 1);
2080
- // winston.debug(" request.participants", request.participants);
2081
-
2421
+ if (index > -1) {
2422
+ request.followers.splice(index, 1);
2423
+ // winston.debug(" request.participants", request.participants);
2082
2424
 
2083
- // winston.debug(" request", request);
2084
- //cacheinvalidation
2085
- return request.save(function(err, savedRequest) {
2086
- if (err){
2087
- winston.error("Error saving removed follower ", err);
2088
- return reject(err);
2089
- }
2090
-
2091
- return savedRequest
2092
- .populate('lead')
2093
- .populate('department')
2094
- .populate('participatingBots')
2095
- .populate('participatingAgents')
2096
- // .populate('followers')
2097
- .populate({path:'requester',populate:{path:'id_user'}})
2098
- .execPopulate( function(err, requestComplete) {
2099
-
2100
- if (err){
2101
- winston.error("Error getting removed follower ", err);
2102
- return reject(err);
2103
- }
2104
2425
 
2105
-
2106
- requestEvent.emit('request.update', requestComplete);
2107
- requestEvent.emit("request.update.comment", {comment:"FOLLOWER_REMOVE",request:requestComplete});//Deprecated
2108
- requestEvent.emit("request.updated", {comment:"FOLLOWER_REMOVE",request:requestComplete, patch: {member:member}});
2109
- requestEvent.emit('request.followers.leave', {member:member, request: requestComplete});
2110
-
2426
+ // winston.debug(" request", request);
2427
+ //cacheinvalidation
2428
+ return request.save(function (err, savedRequest) {
2429
+ if (err) {
2430
+ winston.error("Error saving removed follower ", err);
2431
+ return reject(err);
2432
+ }
2111
2433
 
2112
- return resolve(requestComplete);
2434
+ return savedRequest
2435
+ .populate('lead')
2436
+ .populate('department')
2437
+ .populate('participatingBots')
2438
+ .populate('participatingAgents')
2439
+ // .populate('followers')
2440
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2441
+ .execPopulate(function (err, requestComplete) {
2113
2442
 
2114
- });
2115
- });
2443
+ if (err) {
2444
+ winston.error("Error getting removed follower ", err);
2445
+ return reject(err);
2446
+ }
2116
2447
 
2117
2448
 
2118
- }else {
2119
- winston.verbose('Request member '+ member+ ' already not found for request_id '+ request_id + ' and id_project '+ id_project);
2449
+ requestEvent.emit('request.update', requestComplete);
2450
+ requestEvent.emit("request.update.comment", { comment: "FOLLOWER_REMOVE", request: requestComplete });//Deprecated
2451
+ requestEvent.emit("request.updated", { comment: "FOLLOWER_REMOVE", request: requestComplete, patch: { member: member } });
2452
+ requestEvent.emit('request.followers.leave', { member: member, request: requestComplete });
2120
2453
 
2121
- return request
2122
- .populate('lead')
2123
- .populate('department')
2124
- .populate('participatingBots')
2125
- .populate('participatingAgents')
2126
- // .populate('followers')
2127
- .populate({path:'requester',populate:{path:'id_user'}})
2128
- .execPopulate( function(err, requestComplete) {
2129
- return resolve(requestComplete);
2130
- });
2131
- }
2132
-
2133
- });
2454
+
2455
+ return resolve(requestComplete);
2456
+
2457
+ });
2458
+ });
2459
+
2460
+
2461
+ } else {
2462
+ winston.verbose('Request member ' + member + ' already not found for request_id ' + request_id + ' and id_project ' + id_project);
2463
+
2464
+ return request
2465
+ .populate('lead')
2466
+ .populate('department')
2467
+ .populate('participatingBots')
2468
+ .populate('participatingAgents')
2469
+ // .populate('followers')
2470
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
2471
+ .execPopulate(function (err, requestComplete) {
2472
+ return resolve(requestComplete);
2473
+ });
2474
+ }
2475
+
2476
+ });
2134
2477
  });
2135
2478
  }
2136
2479