@tiledesk/tiledesk-server 2.17.4 → 2.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +8 -3
  2. package/app.js +4 -0
  3. package/channels/chat21/chat21WebHook.js +6 -1
  4. package/docs/routes-answered.md +153 -0
  5. package/event/authEvent.js +16 -0
  6. package/event/projectUserEvent.js +39 -0
  7. package/event/roleEvent.js +9 -0
  8. package/middleware/has-role.js +160 -121
  9. package/middleware/passport.js +180 -179
  10. package/migrations/1757601159298-project_user_role_type.js +104 -0
  11. package/models/department.js +3 -0
  12. package/models/groupMemberSchama.js +19 -0
  13. package/models/kb_setting.js +74 -4
  14. package/models/permissionConstants.js +19 -0
  15. package/models/project_user.js +86 -8
  16. package/models/request.js +1 -0
  17. package/models/role.js +31 -0
  18. package/models/roleConstants.js +2 -0
  19. package/package.json +1 -1
  20. package/pubmodules/analytics/analytics.js +2 -2
  21. package/pubmodules/cache/mongoose-cachegoose-fn.js +37 -0
  22. package/pubmodules/canned/cannedResponseRoute.js +34 -6
  23. package/pubmodules/routing-queue/listener.js +7 -1
  24. package/pubmodules/trigger/rulesTrigger.js +1 -6
  25. package/routes/answered.js +227 -0
  26. package/routes/auth.js +3 -1
  27. package/routes/department.js +7 -1
  28. package/routes/message.js +4 -1
  29. package/routes/project.js +41 -3
  30. package/routes/project_user.js +62 -11
  31. package/routes/request.js +32 -30
  32. package/routes/roles.js +151 -0
  33. package/routes/unanswered.js +32 -19
  34. package/routes/widget.js +3 -1
  35. package/services/cacheEnabler.js +5 -8
  36. package/services/departmentService.js +39 -11
  37. package/services/emailService.js +2 -2
  38. package/services/pendingInvitationService.js +2 -0
  39. package/services/projectService.js +3 -1
  40. package/services/projectUserService.js +67 -4
  41. package/services/subscriptionNotifierQueued.js +8 -0
  42. package/services/updateRequestSnapshotQueued.js +0 -3
  43. package/test/departmentService.js +5 -0
  44. package/test/messageRoute.js +7 -4
  45. package/test/projectUserRoute.js +116 -0
  46. package/test/requestService.js +7 -3
  47. package/test-int/bot.js +3 -2
  48. package/websocket/webSocketServer.js +273 -225
  49. package/routes/auth_newjwt.js +0 -648
@@ -24,6 +24,7 @@ var cacheUtil = require('../utils/cacheUtil');
24
24
  var mongoose = require('mongoose');
25
25
  const requestConstants = require("../models/requestConstants");
26
26
  var RoleConstants = require('../models/roleConstants');
27
+ var projectUserService = require("../services/projectUserService");
27
28
 
28
29
  let configSecretOrPubicKay = process.env.GLOBAL_SECRET || config.secret;
29
30
 
@@ -60,6 +61,7 @@ function logInvalidToken(req, err) {
60
61
  var cacheEnabler = require("../services/cacheEnabler");
61
62
 
62
63
 
64
+
63
65
  var lastRequestsLimit = process.env.WS_HISTORY_REQUESTS_LIMIT || 100;
64
66
  winston.debug('lastRequestsLimit:' + lastRequestsLimit);
65
67
 
@@ -129,7 +131,7 @@ class WebSocketServer {
129
131
  // winston.debug('hasRoleAsPromise project_user',project_user);
130
132
  // winston.debug('ok websocket');
131
133
 
132
- User.findOne({ _id: identifier, status: 100 }, 'email firstname lastname emailverified id') //TODO user_cache_here ma attento select.. ATTENTO SERVER SELECT??
134
+ User.findOne({ _id: identifier, status: 100 }, 'email firstname lastname emailverified id') //TODO user_cache_here ma attento select.. ATTENTO SERVER SELECT??
133
135
  //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, "users:id:"+identifier) //user_cache
134
136
  .exec(function (err, user) {
135
137
 
@@ -229,7 +231,7 @@ class WebSocketServer {
229
231
  winston.debug('project cache enabled for websocket');
230
232
  }
231
233
 
232
- return q.exec(function (err, project) {
234
+ return q.exec(async (err, project) => {
233
235
  if (err) {
234
236
  winston.error('WebSocket - Error getting Project', err);
235
237
  return reject(err);
@@ -248,68 +250,81 @@ class WebSocketServer {
248
250
  // winston.debug(' req.: ',req);
249
251
 
250
252
 
251
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
252
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
253
- .exec(function (err, projectuser) {
254
- if (err) {
255
- winston.error('WebSocket error getting Project_user', err);
256
- return reject(err);
257
- }
258
- if (!projectuser) {
259
- winston.verbose('WebSocket project_user not found for user id ' + req.user._id + ' and projectid ' + projectId);
260
- return reject({ err: 'Project_user not found for user id ' + req.user._id + ' and projectid ' + projectId });
261
- }
253
+ try {
254
+ var projectuser = await projectUserService.getWithPermissions(req.user._id, projectId, req.user.sub);
255
+ } catch(err) {
256
+ winston.error('WebSocket error getting Project_user', err);
257
+ return reject(err);
258
+ }
262
259
 
263
- var queryRequest = { id_project: projectId, request_id: recipientId };
260
+ // Project_user.findOne({ id_project: projectId, id_user: req.user._id, roleType: RoleConstants.TYPE_AGENTS, status: "active" })
261
+ // //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
262
+ // .exec(function (err, projectuser) {
263
+ // if (err) {
264
+ // winston.error('WebSocket error getting Project_user', err);
265
+ // return reject(err);
266
+ // }
267
+ if (!projectuser) {
268
+ winston.verbose('WebSocket project_user not found for user id ' + req.user._id + ' and projectid ' + projectId);
269
+ return reject({ err: 'Project_user not found for user id ' + req.user._id + ' and projectid ' + projectId });
270
+ }
271
+
272
+ var queryRequest = { id_project: projectId, request_id: recipientId };
273
+
274
+ // request_role_check_imp
275
+ if (projectuser.hasPermissionOrRole('request_read_all', ["owner", "admin"])) {
276
+ winston.debug('queryRequest admin: ' + JSON.stringify(queryRequest));
277
+ }
278
+ else if (projectuser.hasPermissionOrRole('request_read_group', ["agent"])) {
279
+ queryRequest["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
280
+ } else {
281
+ winston.debug('queryRequest agent: ' + JSON.stringify(queryRequest));
282
+ queryRequest["participants"] = req.user.id;
283
+ }
284
+
285
+ // requestcachefarequi nocachepopulatereqired
286
+ winston.debug("main_flow_cache_3 websocket1");
287
+
288
+ Request.findOne(queryRequest)
289
+ .exec(function (err, request) {
264
290
 
265
- if (projectuser.role == "owner" || projectuser.role == "admin") {
266
- winston.debug('queryRequest admin: ' + JSON.stringify(queryRequest));
267
- } else {
268
- queryRequest["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
269
- winston.debug('queryRequest agent: ' + JSON.stringify(queryRequest));
270
- }
291
+ if (err) {
292
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
293
+ return reject(err);
294
+ }
295
+ if (!request) {
296
+ winston.verbose('WebSocket Request query not found for user id ' + req.user._id + ' and projectid ' + projectId);
297
+ return reject({ err: 'Request query not found for user id ' + req.user._id + ' and projectid ' + projectId });
298
+ }
271
299
 
272
- // requestcachefarequi nocachepopulatereqired
273
- Request.findOne(queryRequest)
274
- .exec(function (err, request) {
300
+ winston.debug('found request for onSubscribeCallback', request);
275
301
 
276
- if (err) {
277
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
278
- return reject(err);
279
- }
280
- if (!request) {
281
- winston.verbose('WebSocket Request query not found for user id ' + req.user._id + ' and projectid ' + projectId);
282
- return reject({ err: 'Request query not found for user id ' + req.user._id + ' and projectid ' + projectId });
283
- }
284
302
 
285
- winston.debug('found request for onSubscribeCallback', request);
286
303
 
304
+ var query = { id_project: projectId, recipient: recipientId };
305
+ winston.debug('query : ' + JSON.stringify(query));
287
306
 
307
+ Message.find(query).sort({ createdAt: 'asc' })
308
+ .limit(messagesLimit).exec(function (err, messages) {
288
309
 
289
- var query = { id_project: projectId, recipient: recipientId };
290
- winston.debug('query : ' + JSON.stringify(query));
310
+ if (err) {
311
+ winston.error('WebSocket Error finding message for onSubscribeCallback', err);
312
+ return reject(err);
313
+ }
314
+ winston.debug('onSubscribeCallback find', messages);
291
315
 
292
- Message.find(query).sort({ createdAt: 'asc' })
293
- .limit(messagesLimit).exec(function (err, messages) {
294
316
 
295
- if (err) {
296
- winston.error('WebSocket Error finding message for onSubscribeCallback', err);
297
- return reject(err);
317
+ return resolve({
318
+ publishFunction: function () {
319
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
320
+ pubSubServer.handlePublishMessageToClientId(topic, messages, clientId, "CREATE");
298
321
  }
299
- winston.debug('onSubscribeCallback find', messages);
300
-
301
-
302
- return resolve({
303
- publishFunction: function () {
304
- // handlePublishMessageToClientId (topic, message, clientId, method) {
305
- pubSubServer.handlePublishMessageToClientId(topic, messages, clientId, "CREATE");
306
- }
307
- });
308
-
309
322
  });
310
- });
311
323
 
312
- });
324
+ });
325
+ });
326
+
327
+ // });
313
328
 
314
329
  } else if (topic.endsWith('/requests')) {
315
330
 
@@ -319,179 +334,186 @@ class WebSocketServer {
319
334
  winston.debug('find project_user');
320
335
 
321
336
 
322
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
323
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
324
- .exec(function (err, projectuser) {
325
- if (err) {
326
- winston.error('WebSocket error getting Project_user', err);
327
- return reject(err);
328
- }
329
- if (!projectuser) {
330
- winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
331
- return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
332
- }
333
- winston.debug('projectuser', projectuser.toObject());
334
-
335
- // db.getCollection('requests').find({"id_project":"5e15bef09877c800176d217f","status":{"$lt":1000},"$or":[{"agents":{"id_user":"5ddd30bff0195f0017f72c6d"}},{"participants":"5ddd30bff0195f0017f72c6d"}]})
336
- // pubblica dopo toni
337
- var query = { "id_project": projectId, "status": { $lt: 1000, $gt: 50 }, preflight: false, "draft": { $in: [false, null] } };
338
- // add hasBot:false
339
-
340
- // var query = {"id_project":projectId, "status": { $lt: 1000, $gt: 50 }, $or:[ {preflight:false}, { preflight : { $exists: false } } ] };
341
-
342
- // qui1000
343
- // var query = { id_project: projectId, statusObj: {closed:false, preflight:false} };
344
-
345
- var cacheUserId;
346
- if (projectuser.role == "owner" || projectuser.role == "admin") {
347
- winston.debug('query admin: ' + JSON.stringify(query));
348
- cacheUserId = "/admin-owner";
349
- } else {
350
- query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
351
- winston.debug('query agent: ' + JSON.stringify(query));
352
- cacheUserId = "/agent/" + req.user.id;
353
- }
354
-
355
- //cacheimportantehere
356
- // requestcachefarequi populaterequired
357
-
358
- // TODO proviamo a fare esempio con 100 agenti tutti
359
- // elimina capo availableAgents (chiedi a Nico se gli usa altrimenti metti a select false)
360
- var startDate = new Date();
361
- Request.find(query)
362
- .select("+snapshot.agents")
363
- // .populate('lead') //??
364
- // .populate('department')
365
- // .populate('participatingBots')
366
- // .populate('participatingAgents')
367
- // .populate({path:'requester',populate:{path:'id_user'}})
368
- .sort({ updatedAt: 'desc' })
369
- .limit(lastRequestsLimit)
370
- // DISABLED 23Marzo2021 per problema request.snapshot.requester.isAuthenticated = undefined
371
- .lean() //https://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/ https://stackoverflow.com/questions/33104136/mongodb-mongoose-slow-query-when-fetching-10k-documents
372
- //@DISABLED_CACHE .cache(cacheUtil.queryTTL, projectId+":requests:query:status-50-1000:preflight-false:select_snapshot_agents:"+cacheUserId)
373
- .exec(function (err, requests) {
374
-
375
- if (err) {
376
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
377
- return reject(err);
378
- }
379
- winston.debug('found requests for onSubscribeCallback', requests);
380
-
381
- if (requests && requests.length > 0) {
382
- requests.forEach(request => {
337
+ try {
338
+ var projectuser = await projectUserService.getWithPermissions(req.user._id, projectId, req.user.sub);
339
+ } catch(err) {
340
+ winston.error('WebSocket error getting Project_user', err);
341
+ return reject(err);
342
+ }
343
+ // Project_user.findOne({ id_project: projectId, id_user: req.user._id, roleType: RoleConstants.TYPE_AGENTS, status: "active" })
344
+ // //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
345
+ // .exec(function (err, projectuser) {
346
+ // if (err) {
347
+ // winston.error('WebSocket error getting Project_user', err);
348
+ // return reject(err);
349
+ // }
350
+ if (!projectuser) {
351
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
352
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
353
+ }
354
+ winston.debug('projectuser', projectuser.toObject());
355
+
356
+ var query = { "id_project": projectId, "status": { $lt: 1000, $gt: 50, $ne: 150 }, preflight: false, "draft": { $in: [false, null] } };
357
+
358
+ if (projectuser.hasPermissionOrRole('request_read_all', ["owner", "admin"])) {
359
+ winston.debug('ws requests query admin: ' + JSON.stringify(query));
360
+ } else if (projectuser.hasPermissionOrRole('request_read_group', ["agent"])) {
361
+ query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }];
362
+ winston.debug('ws requests query agent: ' + JSON.stringify(query));
363
+ } else {
364
+ query["participants"] = req.user.id;
365
+ winston.debug('ws requests query agent limited: ' + JSON.stringify(query));
366
+ }
383
367
 
384
- request.id = request._id; //importante
385
368
 
369
+ //cacheimportantehere
370
+ // requestcachefarequi populaterequired
371
+ winston.debug('found Request.find(query)');
372
+
373
+ // TODO proviamo a fare esempio con 100 agenti tutti
374
+ // elimina capo availableAgents (chiedi a Nico se gli usa altrimenti metti a select false)
375
+ var startDate = new Date();
376
+ Request.find(query)
377
+ .select("+snapshot.agents")
378
+ // .populate('lead') //??
379
+ // .populate('department')
380
+ // .populate('participatingBots')
381
+ // .populate('participatingAgents')
382
+ // .populate({path:'requester',populate:{path:'id_user'}})
383
+ .sort({ updatedAt: 'desc' })
384
+ .limit(lastRequestsLimit)
385
+ // DISABLED 23Marzo2021 per problema request.snapshot.requester.isAuthenticated = undefined
386
+ .lean() //https://www.tothenew.com/blog/high-performance-find-query-using-lean-in-mongoose-2/ https://stackoverflow.com/questions/33104136/mongodb-mongoose-slow-query-when-fetching-10k-documents
387
+ //@DISABLED_CACHE .cache(cacheUtil.queryTTL, projectId+":requests:query:status-50-1000:preflight-false:select_snapshot_agents:"+cacheUserId)
388
+ .exec(function (err, requests) {
386
389
 
387
- if (request.lead) {
388
- // request.requester_id = request.lead._id; //parla con NICO di questo
389
- request.requester_id = request.lead;
390
- } else {
391
- request.requester_id = null;
392
- }
390
+ if (err) {
391
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
392
+ return reject(err);
393
+ }
394
+ winston.debug('found requests for onSubscribeCallback', requests);
393
395
 
394
- if (request.snapshot.requester) {
395
- if (request.snapshot.requester.role === RoleConstants.GUEST) {
396
- request.snapshot.requester.isAuthenticated = false;
397
- } else {
398
- request.snapshot.requester.isAuthenticated = true;
399
- }
396
+ if (requests && requests.length > 0) {
397
+ requests.forEach(request => {
400
398
 
401
- }
399
+ request.id = request._id; //importante
402
400
 
403
- // attento qui
404
- if (request.snapshot.agents && request.snapshot.agents.length > 0) {
405
- var agentsnew = [];
406
- request.snapshot.agents.forEach(a => {
407
- agentsnew.push({ id_user: a.id_user }) //remove unnecessary request.agents[].project_user fields. keep only id_user
408
- });
409
- request.snapshot.agents = agentsnew;
410
- }
411
401
 
402
+ if (request.lead) {
403
+ // request.requester_id = request.lead._id; //parla con NICO di questo
404
+ request.requester_id = request.lead;
405
+ } else {
406
+ request.requester_id = null;
407
+ }
412
408
 
409
+ if (request.snapshot.requester) {
410
+ if (request.snapshot.requester.role === RoleConstants.GUEST) {
411
+ request.snapshot.requester.isAuthenticated = false;
412
+ } else {
413
+ request.snapshot.requester.isAuthenticated = true;
414
+ }
413
415
 
416
+ }
414
417
 
418
+ // attento qui
419
+ if (request.snapshot.agents && request.snapshot.agents.length > 0) {
420
+ var agentsnew = [];
421
+ request.snapshot.agents.forEach(a => {
422
+ agentsnew.push({ id_user: a.id_user }) //remove unnecessary request.agents[].project_user fields. keep only id_user
415
423
  });
424
+ request.snapshot.agents = agentsnew;
416
425
  }
417
426
 
418
- var endDate = new Date();
419
- winston.debug('ws count: ' + query + ' ' + requests.length + ' ' + startDate + ' ' + endDate + ' ' + endDate - startDate)
420
- return resolve({
421
- publishFunction: function () {
422
- // handlePublishMessageToClientId (topic, message, clientId, method) {
423
- pubSubServer.handlePublishMessageToClientId(topic, requests, clientId, "CREATE");
424
- }
425
- });
427
+
426
428
 
427
429
 
428
430
  });
431
+ }
432
+
433
+ var endDate = new Date();
434
+ winston.debug('ws count: ' + query + ' ' + requests.length + ' ' + startDate + ' ' + endDate + ' ' + endDate - startDate)
435
+ return resolve({
436
+ publishFunction: function () {
437
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
438
+ pubSubServer.handlePublishMessageToClientId(topic, requests, clientId, "CREATE");
439
+ }
440
+ });
441
+
429
442
 
430
443
  });
431
444
 
445
+ // });
446
+
432
447
 
433
448
  } else if (topic.indexOf('/project_users/users/') > -1) {
434
449
 
435
450
  var userId = urlSub[4];
436
451
  winston.debug('userId: ' + userId);
437
452
 
438
- //check if current user can see the data
439
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
440
- //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
441
- .exec(function (err, currentProjectuser) {
442
- if (err) {
443
- winston.error('WebSocket error getting Project_user', err);
444
- return reject(err);
445
- }
446
- if (!currentProjectuser) {
447
- winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
448
- return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
449
- }
450
- winston.debug('currentProjectuser', currentProjectuser.toObject());
453
+ try {
454
+ var currentProjectuser = await projectUserService.getWithPermissions(req.user._id, projectId, req.user.sub);
455
+ } catch(err) {
456
+ winston.error('WebSocket error getting Project_user', err);
457
+ return reject(err);
458
+ }
451
459
 
460
+ // //check if current user can see the data
461
+ // Project_user.findOne({ id_project: projectId, id_user: req.user._id, roleType: RoleConstants.TYPE_AGENTS, status: "active" })
462
+ // //@DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
463
+ // .exec(function (err, currentProjectuser) {
464
+ // if (err) {
465
+ // winston.error('WebSocket error getting Project_user', err);
466
+ // return reject(err);
467
+ // }
468
+ if (!currentProjectuser) {
469
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
470
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
471
+ }
472
+ winston.debug('currentProjectuser', currentProjectuser.toObject());
452
473
 
453
- var isObjectId = mongoose.Types.ObjectId.isValid(userId);
454
- winston.debug("isObjectId:" + isObjectId);
455
474
 
456
- var query = { id_project: projectId, status: "active" };
457
- winston.debug(' query: ', query);
475
+ var isObjectId = mongoose.Types.ObjectId.isValid(userId);
476
+ winston.debug("isObjectId:" + isObjectId);
458
477
 
459
- if (isObjectId) {
460
- query.id_user = userId;
461
- } else {
462
- query.uuid_user = userId;
463
- }
478
+ var query = { id_project: projectId, status: "active" };
479
+ winston.debug(' query: ', query);
464
480
 
465
- Project_user.findOne(query)
466
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:users:"+userId)
467
- .exec(function (err, projectuser) {
468
- if (err) {
469
- winston.error('WebSocket error getting Project_user', err);
470
- return reject(err);
471
- }
472
- if (!projectuser) {
473
- winston.verbose('WebSocket Project_user not found with user id ' + userId + ' and projectid ' + projectId);
474
- return reject({ err: 'Project_user not found with user id ' + userId + ' and projectid ' + projectId });
475
- }
481
+ if (isObjectId) {
482
+ query.id_user = userId;
483
+ } else {
484
+ query.uuid_user = userId;
485
+ }
486
+
487
+ Project_user.findOne(query)
488
+ // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:users:"+userId)
489
+ .exec(function (err, projectuser) {
490
+ if (err) {
491
+ winston.error('WebSocket error getting Project_user', err);
492
+ return reject(err);
493
+ }
494
+ if (!projectuser) {
495
+ winston.verbose('WebSocket Project_user not found with user id ' + userId + ' and projectid ' + projectId);
496
+ return reject({ err: 'Project_user not found with user id ' + userId + ' and projectid ' + projectId });
497
+ }
476
498
 
477
499
 
478
- var pu = projectuser.toJSON();
479
- pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
500
+ var pu = projectuser.toJSON();
501
+ pu.isBusy = ProjectUserUtil.isBusy(projectuser, project.settings && project.settings.max_agent_assigned_chat);
480
502
 
481
503
 
482
- return resolve({
483
- publishFunction: function () {
484
- // handlePublishMessageToClientId (topic, message, clientId, method) {
485
- pubSubServer.handlePublishMessageToClientId(topic, pu, clientId, "CREATE");
486
- }
487
- });
504
+ return resolve({
505
+ publishFunction: function () {
506
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
507
+ pubSubServer.handlePublishMessageToClientId(topic, pu, clientId, "CREATE");
508
+ }
509
+ });
488
510
 
489
- });
511
+ });
490
512
 
491
513
 
492
514
 
493
515
 
494
- });
516
+ // });
495
517
 
496
518
 
497
519
  // tilebase.send('{ "action": "subscribe", "payload": { "topic": "/5e71139f61dd040bc9594cee/project_users/5e71139f61dd040bc9594cef"}}')
@@ -505,7 +527,7 @@ class WebSocketServer {
505
527
  winston.debug('puId: ' + puId);
506
528
 
507
529
  //var query = { _id: puId, id_project: projectId};
508
- var query = { _id: puId, id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" };
530
+ var query = { _id: puId, id_project: projectId, id_user: req.user._id, roleType: RoleConstants.TYPE_AGENTS, status: "active" };
509
531
  winston.debug(' query: ', query);
510
532
 
511
533
  Project_user.findOne(query)
@@ -610,55 +632,74 @@ class WebSocketServer {
610
632
  var recipientId = urlSub[3];
611
633
  winston.debug('recipientId: ' + recipientId);
612
634
 
613
- Project_user.findOne({ id_project: projectId, id_user: req.user._id, $or: [{ "role": "agent" }, { "role": "admin" }, { "role": "owner" }], status: "active" })
614
- // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
615
- .exec(function (err, projectuser) {
616
- if (err) {
617
- winston.error('WebSocket error getting Project_user', err);
618
- return reject(err);
619
- }
620
- if (!projectuser) {
621
- winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
622
- return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
623
- }
635
+ try {
636
+ var projectuser = await projectUserService.getWithPermissions(req.user._id, projectId, req.user.sub);
637
+ } catch(err) {
638
+ winston.error('WebSocket error getting Project_user', err);
639
+ return reject(err);
640
+ }
624
641
 
625
- var query = { id_project: projectId, request_id: recipientId };
626
- winston.debug('query: ' + JSON.stringify(query));
642
+ // Project_user.findOne({ id_project: projectId, id_user: req.user._id, roleType: RoleConstants.TYPE_AGENTS, status: "active" })
643
+ // // @DISABLED_CACHE .cache(cacheUtil.defaultTTL, projectId+":project_users:role:teammate:"+req.user._id)
644
+ // .exec(function (err, projectuser) {
645
+ // if (err) {
646
+ // winston.error('WebSocket error getting Project_user', err);
647
+ // return reject(err);
648
+ // }
649
+ if (!projectuser) {
650
+ winston.verbose('WebSocket Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId);
651
+ return reject({ err: 'Project_user not found with user id ' + req.user._id + ' and projectid ' + projectId });
652
+ }
627
653
 
628
- if (projectuser.role == "owner" || projectuser.role == "admin") {
629
- winston.debug('query admin: ' + JSON.stringify(query));
630
- } else {
631
- query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
632
- winston.debug('query agent: ' + JSON.stringify(query));
633
- }
654
+ var query = { id_project: projectId, request_id: recipientId };
655
+ winston.debug('query: ' + JSON.stringify(query));
634
656
 
635
- // requestcachefarequi populaterequired
657
+ // request_role_check
636
658
 
637
- Request.findOne(query)
638
- .populate('lead')
639
- .populate('department')
640
- .populate('participatingBots')
641
- .populate('participatingAgents')
642
- .populate({ path: 'requester', populate: { path: 'id_user' } })
643
- .sort({ updatedAt: 'asc' }).exec(function (err, request) {
659
+ if (projectuser.hasPermissionOrRole('request_read_all', ["owner", "admin"])) {
660
+ winston.debug('query admin: ' + JSON.stringify(query));
661
+ } else if (projectuser.hasPermissionOrRole('request_read_group', ["agent"])) {
644
662
 
645
- if (err) {
646
- winston.error('WebSocket Error finding request for onSubscribeCallback', err);
647
- return reject(err);
648
- }
649
- winston.debug('onSubscribeCallback find', request);
663
+ query["$or"] = [{ "snapshot.agents.id_user": req.user.id }, { "participants": req.user.id }]
650
664
 
651
- return resolve({
652
- publishFunction: function () {
653
- // handlePublishMessageToClientId (topic, message, clientId, method) {
654
- pubSubServer.handlePublishMessageToClientId(topic, request, clientId, "CREATE");
655
- }
656
- });
665
+ }
666
+ // else if (projectuser.hasPermissionOrRole('request_read_mine', ["????"])) {
667
+ // query["participants"] = req.user.id;
668
+ // }
669
+ else {
670
+ query["participants"] = req.user.id;
671
+ // generate empty requests response
672
+ }
657
673
 
658
- });
674
+
675
+ // requestcachefarequi populaterequired
676
+ winston.debug('info: main_flow_cache_2.2');
677
+
678
+ Request.findOne(query)
679
+ .populate('lead')
680
+ .populate('department')
681
+ .populate('participatingBots')
682
+ .populate('participatingAgents')
683
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
684
+ .sort({ updatedAt: 'asc' }).exec(function (err, request) {
685
+
686
+ if (err) {
687
+ winston.error('WebSocket Error finding request for onSubscribeCallback', err);
688
+ return reject(err);
689
+ }
690
+ winston.debug('onSubscribeCallback find', request);
691
+
692
+ return resolve({
693
+ publishFunction: function () {
694
+ // handlePublishMessageToClientId (topic, message, clientId, method) {
695
+ pubSubServer.handlePublishMessageToClientId(topic, request, clientId, "CREATE");
696
+ }
697
+ });
659
698
 
660
699
  });
661
700
 
701
+ // });
702
+
662
703
  }
663
704
 
664
705
 
@@ -726,6 +767,8 @@ class WebSocketServer {
726
767
 
727
768
  // ATTENTO https://stackoverflow.com/questions/64059795/mongodb-get-error-message-mongoerror-path-collision-at-activity
728
769
  try {
770
+ winston.debug("main_flow_cache_ws request find");
771
+
729
772
  var snapshotAgents = await Request.findById(request.id).select({ "snapshot": 1 }).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
730
773
  winston.debug('snapshotAgents', snapshotAgents);
731
774
  // requestJSON.snapshot.agents = snapshotAgents;
@@ -743,6 +786,7 @@ class WebSocketServer {
743
786
  winston.error('Error getting snapshotAgents in ws. This is a mongo issue', e);
744
787
  }
745
788
 
789
+ // aggiungere controllo sui permessi qui
746
790
  pubSubServer.handlePublishMessage('/' + request.id_project + '/requests', request, undefined, true, "CREATE");
747
791
  pubSubServer.handlePublishMessage('/' + request.id_project + '/requests/' + request.request_id, request, undefined, true, "CREATE");
748
792
  }
@@ -777,6 +821,8 @@ class WebSocketServer {
777
821
  // ATTENTO https://stackoverflow.com/questions/64059795/mongodb-get-error-message-mongoerror-path-collision-at-activity
778
822
 
779
823
  try {
824
+ winston.debug("main_flow_cache_ws request find 2");
825
+ // cache_next
780
826
  var snapshotAgents = await Request.findById(request.id).select({ "snapshot": 1 }).exec(); //SEMBRA CHE RITORNI TUTTO LO SNAPSHOT INVECE CHE SOLO AGENTS
781
827
  winston.debug('snapshotAgents', snapshotAgents);
782
828
  // requestJSON.snapshot.agents = snapshotAgents;
@@ -795,6 +841,8 @@ class WebSocketServer {
795
841
  winston.error('Error getting snapshotAgents in ws. This is a mongo issue', e);
796
842
  }
797
843
 
844
+ // aggiungere controllo sui permessi qui
845
+
798
846
  if (requestJSON.draft !== true) {
799
847
  pubSubServer.handlePublishMessage('/' + request.id_project + '/requests', requestJSON, undefined, true, "UPDATE");
800
848
  }