@tiledesk/tiledesk-server 2.14.9 → 2.14.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,13 @@
5
5
  🚀 IN PRODUCTION 🚀
6
6
  (https://www.npmjs.com/package/@tiledesk/tiledesk-server/v/2.3.77)
7
7
 
8
+ # 2.14.12
9
+ - Updated handling of unresponsive requests to close based on the updatedAt field instead of createdAt.
10
+
11
+ # 2.14.10
12
+ - Added support for a custom reranking_multiplier parameter in the /qa endpoint
13
+ - Improved DB performance by optimizing the query used to find conversations to be closed automatically
14
+
8
15
  # 2.14.9
9
16
  - Improved the requests search function and added the ability to specify a timezone when searching
10
17
 
@@ -3,6 +3,8 @@ var Schema = mongoose.Schema;
3
3
  // mongoose.set('debug', true);
4
4
  var winston = require('../config/winston');
5
5
 
6
+ let config = require('../config/database');
7
+
6
8
 
7
9
  var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI || config.database;
8
10
 
package/models/request.js CHANGED
@@ -506,6 +506,8 @@ RequestSchema.index({ id_project: 1, "snapshot.lead.email": 1, createdAt: -1, st
506
506
  RequestSchema.index({ id_project: 1, createdAt: -1, status: 1 })
507
507
  RequestSchema.index({ id_project: 1, preflight: 1, smartAssignment: 1, "snapshot.department.routing": 1, createdAt: 1, status: 1 })
508
508
 
509
+ RequestSchema.index({ status: 1, hasBot: 1, updatedAt: 1 }) // For closing unresponsive requests
510
+
509
511
  // ERROR DURING DEPLOY OF 2.10.27
510
512
  //RequestSchema.index({ id_project: 1, participants: 1, "snapshot.agents.id_user": 1, createdAt: -1, status: 1 })
511
513
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-server",
3
3
  "description": "The Tiledesk server module",
4
- "version": "2.14.9",
4
+ "version": "2.14.11",
5
5
  "scripts": {
6
6
  "start": "node ./bin/www",
7
7
  "pretest": "mongodb-runner start",
@@ -1,120 +1,157 @@
1
-
2
1
  'use strict';
3
2
 
3
+ const schedule = require('node-schedule');
4
+ const winston = require('../../../config/winston');
5
+ const Request = require("../../../models/request");
6
+ const requestService = require("../../../services/requestService");
4
7
 
5
- var schedule = require('node-schedule');
6
- var winston = require('../../../config/winston');
7
- var Request = require("../../../models/request");
8
- var requestService = require("../../../services/requestService");
9
-
10
-
8
+ /**
9
+ * Task scheduler for automatically closing agent unresponsive requests.
10
+ * Finds requests with agents that haven't been updated within a specified timeout
11
+ * and closes them automatically.
12
+ */
11
13
  class CloseAgentUnresponsiveRequestTask {
12
14
 
13
- constructor() {
14
- this.enabled = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_ENABLE || "false";
15
- this.cronExp = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_CRON_EXPRESSION || '*/30 * * * *'; //every 30 minutes
16
- this.queryAfterTimeout = parseInt(process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_AFTER_TIMEOUT) || 5 * 24 * 60 * 60 * 1000; //five days ago // 86400000 a day
17
- this.queryLimit = parseInt(process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_QUERY_LIMIT) || 10;
18
- this.queryProject = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_QUERY_FILTER_ONLY_PROJECT;
15
+ constructor() {
19
16
 
20
- if (this.queryProject) {
21
- winston.info("CloseAgentUnresponsiveRequestTask filter only by projects enabled: " + this.queryProject );
22
- }
23
-
24
- // var stringQuery = process.env.CLOSE_UNRESPONSIVE_REQUESTS_QUERY;
25
- // if (stringQuery) {
26
- // this.query = JSON.parse(stringQuery) || {hasBot:true, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
27
- // }else {
28
- // this.query = {hasBot:true, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
29
- // }
30
-
31
- }
17
+ this.enabled = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_ENABLE || "false";
18
+ this.cronExp = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_CRON_EXPRESSION || '*/30 * * * *'; //every 30 minutes
19
+ this.queryAfterTimeout = parseInt(process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_AFTER_TIMEOUT) || 5 * 24 * 60 * 60 * 1000; //five days ago // 86400000 a day
20
+ this.queryLimit = parseInt(process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_QUERY_LIMIT) || 10;
21
+ this.queryProject = process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_QUERY_FILTER_ONLY_PROJECT;
22
+ this.delayBeforeClosing = parseInt(process.env.CLOSE_AGENT_UNRESPONSIVE_REQUESTS_DELAY) || 1000;
32
23
 
33
- run() {
34
- if (this.enabled == "true") {
35
- winston.info("CloseAgentUnresponsiveRequestTask started" );
36
- this.scheduleUnresponsiveRequests();
37
- } else {
38
- winston.info("CloseAgentUnresponsiveRequestTask disabled" );
24
+ if (this.queryProject) {
25
+ winston.info("CloseAgentUnresponsiveRequestTask filter only by projects enabled: " + this.queryProject );
39
26
  }
40
- }
27
+
28
+ }
41
29
 
42
- scheduleUnresponsiveRequests() {
43
- var that = this;
44
- winston.info("CloseAgentUnresponsiveRequestTask task scheduleUnresponsiveRequests launched with closeAfter : " + this.queryAfterTimeout + " milliseconds, cron expression: " + this.cronExp + " and query limit: " +this.queryLimit);
45
- // if (this.queryProject) {
46
- // winston.info("CloseAgentUnresponsiveRequestTask query altered: "+ JSON.stringify(this.query));
47
- // }
48
-
49
- //https://crontab.guru/examples.html
50
- var s= schedule.scheduleJob(this.cronExp, function(fireDate){
51
- winston.debug('CloseAgentUnresponsiveRequestTask ScheduleUnresponsiveRequests job was supposed to run at ' + fireDate + ', but actually ran at ' + new Date());
52
- that.findUnresponsiveRequests();
53
- });
54
- }
30
+ /**
31
+ * Starts the scheduler if enabled.
32
+ */
33
+ run() {
34
+ if (this.enabled === "true") {
35
+ winston.info("CloseAgentUnresponsiveRequestTask started" );
36
+ this.scheduleUnresponsiveRequests();
37
+ } else {
38
+ winston.info("CloseAgentUnresponsiveRequestTask disabled" );
39
+ }
40
+ }
55
41
 
42
+ /**
43
+ * Schedules the recurring job to find and close unresponsive requests.
44
+ */
45
+ scheduleUnresponsiveRequests() {
46
+ winston.info(
47
+ `CloseAgentUnresponsiveRequestTask task scheduleUnresponsiveRequests launched with ` +
48
+ `closeAfter: ${this.queryAfterTimeout} milliseconds, ` +
49
+ `cron expression: ${this.cronExp} and query limit: ${this.queryLimit}`
50
+ );
51
+
52
+ schedule.scheduleJob(this.cronExp, (fireDate) => {
53
+ winston.debug(`CloseAgentUnresponsiveRequestTask ScheduleUnresponsiveRequests job was supposed to run at ${fireDate}, but actually ran at ${new Date()}`);
54
+ this.findUnresponsiveRequests();
55
+ });
56
+ }
56
57
 
57
- findUnresponsiveRequests() {
58
-
59
58
 
60
- // db.getCollection('requests').find({"hasBot":true, "status": { "$lt": 1000 }, "createdAt": { "$lte" :new ISODate("2020-11-28T20:15:31Z")} }).count()
61
-
62
- //RETEST IT
63
- var query = {hasBot:false, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
59
+ /**
60
+ * Finds unresponsive agent requests and schedules their closure.
61
+ * Queries for requests with agents that haven't been updated within the timeout period.
62
+ */
63
+ findUnresponsiveRequests() {
64
+ const cutoffDate = new Date(Date.now() - this.queryAfterTimeout);
65
+ const query = {
66
+ hasBot: false,
67
+ status: { $lt: 1000 },
68
+ updatedAt: { $lte: cutoffDate }
69
+ };
64
70
 
65
71
  if (this.queryProject) {
66
- query.id_project = this.queryProject;
72
+ try {
73
+ query.id_project = JSON.parse(this.queryProject);
74
+ } catch (err) {
75
+ winston.error("CloseAgentUnresponsiveRequestTask error parsing queryProject filter", err);
76
+ return;
77
+ }
67
78
  }
79
+
68
80
  winston.debug("CloseAgentUnresponsiveRequestTask query",query);
69
81
 
70
- Request.find(query).limit(this.queryLimit).exec(function(err, requests) {
71
- //it is limited to 1000 results but after same days it all ok
72
- if (err) {
73
- winston.error("CloseAgentUnresponsiveRequestTask error getting unresponsive requests ", err);
74
- return 0;
75
- }
76
- if (!requests || (requests && requests.length==0)) {
82
+ //console.log("[CloseUnresponsive] Searching with query: ", query);
83
+ Request.find(query)
84
+ .sort({ updatedAt: 'asc' })
85
+ .limit(this.queryLimit)
86
+ .hint({ status: 1, hasBot: 1, updatedAt: 1 })
87
+ .exec((err, requests) => {
88
+ if (err) {
89
+ winston.error("CloseAgentUnresponsiveRequestTask error getting unresponsive requests ", err);
90
+ return;
91
+ }
92
+
93
+ if (!requests || requests.length === 0) {
77
94
  winston.verbose("CloseAgentUnresponsiveRequestTask no unresponsive requests found ");
78
- return 0;
79
- }
95
+ return;
96
+ }
80
97
 
81
- winston.verbose("CloseAgentUnresponsiveRequestTask: found " + requests.length + " unresponsive requests");
82
- winston.debug("CloseAgentUnresponsiveRequestTask: found unresponsive requests ", requests);
98
+ //console.log("[CloseUnresponsive] Found ", requests.length, " unresponsive requests");
83
99
 
84
- requests.forEach(request => {
85
- winston.debug("********unresponsive request ", request);
100
+ winston.verbose("CloseAgentUnresponsiveRequestTask: found " + requests.length + " unresponsive requests");
101
+ winston.debug("CloseAgentUnresponsiveRequestTask: found unresponsive requests ", requests);
86
102
 
87
- // closeRequestByRequestId(request_id, id_project, skipStatsUpdate, notify, closed_by)
88
- const closed_by = "_bot_unresponsive";
89
- return requestService.closeRequestByRequestId(request.request_id, request.id_project, false, false, closed_by).then(function(updatedStatusRequest) {
90
- winston.verbose("CloseAgentUnresponsiveRequestTask: Request closed with request_id: " + request.request_id);
91
- // winston.info("Request closed",updatedStatusRequest);
92
- }).catch(function(err) {
93
- if (process.env.HIDE_CLOSE_REQUEST_ERRORS == true || process.env.HIDE_CLOSE_REQUEST_ERRORS == "true" ) {
94
-
95
- } else {
96
- winston.error("CloseAgentUnresponsiveRequestTask: Error closing the request with request_id: " + request.request_id, err);
97
- }
98
-
99
- })
100
-
101
- });
102
-
103
-
103
+ this.scheduleRequestClosures(requests);
104
104
 
105
105
  });
106
106
  }
107
107
 
108
+ /**
109
+ * Schedules the closure of multiple requests with staggered delays.
110
+ * @param {Array} requests - Array of request objects to close
111
+ */
112
+ scheduleRequestClosures(requests) {
113
+ requests.forEach((request, index) => {
114
+ // Stagger delays: 2 * delayBeforeClosing * (index + 1)
115
+ const delay = 2 * this.delayBeforeClosing * (index + 1);
116
+ winston.debug(`CloseAgentUnresponsiveRequestTask: scheduling closure with delay: ${delay}ms for request_id: ${request.request_id}`);
117
+
118
+ setTimeout(() => {
119
+ this.closeRequest(request);
120
+ }, delay);
121
+ });
122
+ }
108
123
 
109
-
124
+ /**
125
+ * Closes a single unresponsive request.
126
+ * @param {Object} request - The request object to close
127
+ */
128
+ closeRequest(request) {
129
+ winston.debug(`CloseAgentUnresponsiveRequestTask: processing unresponsive request: ${request.first_text}`);
130
+
131
+ const closedBy = "_bot_unresponsive";
132
+ const shouldSkipStatsUpdate = false;
133
+ const shouldNotify = false;
134
+
135
+ requestService.closeRequestByRequestId(
136
+ request.request_id,
137
+ request.id_project,
138
+ shouldSkipStatsUpdate,
139
+ shouldNotify,
140
+ closedBy
141
+ ).then(() => {
142
+ winston.info(`CloseAgentUnresponsiveRequestTask: Request closed with request_id: ${request.request_id}`);
143
+ }).catch((err) => {
144
+ const hideErrors = process.env.HIDE_CLOSE_REQUEST_ERRORS === true || process.env.HIDE_CLOSE_REQUEST_ERRORS === "true";
145
+
146
+ if (!hideErrors) {
147
+ winston.error(`CloseAgentUnresponsiveRequestTask: Error closing the request with request_id: ${request.request_id}`, err);
148
+ }
149
+ });
110
150
 
151
+ }
111
152
 
112
153
  }
113
154
 
114
-
115
-
116
-
117
- var closeAgentUnresponsiveRequestTask = new CloseAgentUnresponsiveRequestTask();
118
-
155
+ const closeAgentUnresponsiveRequestTask = new CloseAgentUnresponsiveRequestTask();
119
156
 
120
157
  module.exports = closeAgentUnresponsiveRequestTask;
@@ -1,153 +1,164 @@
1
-
2
1
  'use strict';
3
2
 
3
+ const schedule = require('node-schedule');
4
+ const winston = require('../../../config/winston');
5
+ const Request = require("../../../models/request");
6
+ const requestService = require("../../../services/requestService");
4
7
 
5
- var schedule = require('node-schedule');
6
- var winston = require('../../../config/winston');
7
- var Request = require("../../../models/request");
8
- var requestService = require("../../../services/requestService");
8
+ /**
9
+ * Task scheduler for automatically closing bot unresponsive requests.
10
+ * Finds requests with bots that haven't been updated within a specified timeout
11
+ * and closes them automatically.
12
+ */
13
+ class CloseBotUnresponsiveRequestTask {
9
14
 
15
+ constructor() {
10
16
 
11
- class CloseBotUnresponsiveRequestTask {
17
+ this.enabled = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_ENABLE || "true";
18
+ this.cronExp = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_CRON_EXPRESSION || '*/5 * * * *'; // every 5 minutes // every 30 seconds '*/30 * * * * *';
19
+ this.queryAfterTimeout = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_AFTER_TIMEOUT) || 2 * 24 * 60 * 60 * 1000; //two days ago //172800000 two days // 86400000 a day
20
+ this.queryLimit = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_QUERY_LIMIT) || 10;
21
+ this.queryProject = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_QUERY_FILTER_ONLY_PROJECT; //example in PRE: {"$in":["5fc224ce05416200342af18a","5fb3e3cb0150a00034ab77d5"]}
22
+ this.delayBeforeClosing = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_DELAY) || 1000;
12
23
 
13
- constructor() {
14
- this.enabled = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_ENABLE || "true";
15
- this.cronExp = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_CRON_EXPRESSION || '*/5 * * * *'; // every 5 minutes // every 30 seconds '*/30 * * * * *';
16
- this.queryAfterTimeout = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_AFTER_TIMEOUT) || 2 * 24 * 60 * 60 * 1000; //two days ago //172800000 two days // 86400000 a day
17
- this.queryLimit = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_QUERY_LIMIT) || 10;
18
- this.queryProject = process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_QUERY_FILTER_ONLY_PROJECT; //example in PRE: {"$in":["5fc224ce05416200342af18a","5fb3e3cb0150a00034ab77d5"]}
19
- this.delayBeforeClosing = parseInt(process.env.CLOSE_BOT_UNRESPONSIVE_REQUESTS_DELAY) || 1000;
20
- // winston.info("delayBeforeClosing: "+ this.delayBeforeClosing);
21
-
22
- if (this.queryProject) {
23
- winston.info("CloseBotUnresponsiveRequestTask filter only by projects enabled: " + this.queryProject );
24
+ if (this.queryProject) {
25
+ winston.info("CloseBotUnresponsiveRequestTask filter only by projects enabled: " + this.queryProject);
26
+ }
24
27
  }
25
- // qui ha senso la query?????? nn viene piu ricaricata?
26
-
27
- // var stringQuery = process.env.CLOSE_UNRESPONSIVE_REQUESTS_QUERY;
28
- // if (stringQuery) {
29
- // this.query = JSON.parse(stringQuery) || {hasBot:true, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
30
- // }else {
31
- // this.query = {hasBot:true, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
32
- // }
33
-
34
- }
35
28
 
36
- run() {
37
- if (this.enabled == "true") {
38
- winston.info("CloseBotUnresponsiveRequestTask started" );
29
+ /**
30
+ * Starts the scheduler if enabled.
31
+ */
32
+ run() {
33
+ if (this.enabled === "true") {
34
+ winston.info("CloseBotUnresponsiveRequestTask started");
39
35
  this.scheduleUnresponsiveRequests();
40
36
  } else {
41
- winston.info("CloseBotUnresponsiveRequestTask disabled" );
37
+ winston.info("CloseBotUnresponsiveRequestTask disabled");
42
38
  }
43
- }
44
-
45
- scheduleUnresponsiveRequests() {
46
- var that = this;
47
- winston.info("CloseBotUnresponsiveRequestTask task scheduleUnresponsiveRequests launched with closeAfter : " + this.queryAfterTimeout + " milliseconds, cron expression: " + this.cronExp + " and query limit: " +this.queryLimit);
48
- // if (this.queryProject) {
49
- // winston.info("CloseBotUnresponsiveRequestTask query altered: " + JSON.stringify(this.query));
50
- // }
51
-
52
- //https://crontab.guru/examples.html
53
- var s= schedule.scheduleJob(this.cronExp, function(fireDate){ //TODO aggiungi un bias random
54
-
55
- let timeInMs = Math.random() * (1000); // avoid cluster concurrent jobs in multiple nodes delay between 0 and 1sec
56
- winston.debug('timeInMs => '+ timeInMs);
57
-
58
- setTimeout(function () {
59
- winston.debug('CloseBotUnresponsiveRequestTask scheduleUnresponsiveRequests job was supposed to run at ' + fireDate + ', but actually ran at ' + new Date());
60
- that.findUnresponsiveRequests();
61
- },timeInMs );
62
- });
63
- }
64
-
39
+ }
65
40
 
66
- findUnresponsiveRequests() {
67
- var that = this;
41
+ /**
42
+ * Schedules the recurring job to find and close unresponsive requests.
43
+ * Includes a random delay to avoid concurrent execution in cluster environments.
44
+ */
45
+ scheduleUnresponsiveRequests() {
46
+ winston.info(
47
+ `CloseBotUnresponsiveRequestTask task scheduleUnresponsiveRequests launched with ` +
48
+ `closeAfter: ${this.queryAfterTimeout} milliseconds, ` +
49
+ `cron expression: ${this.cronExp} and query limit: ${this.queryLimit}`
50
+ );
51
+
52
+ schedule.scheduleJob(this.cronExp, (fireDate) => {
53
+ const randomDelay = Math.random() * 1000;
54
+ winston.debug(`CloseBotUnresponsiveRequestTask random delay: ${randomDelay}ms`);
55
+
56
+ setTimeout(() => {
57
+ winston.debug(
58
+ `CloseBotUnresponsiveRequestTask scheduleUnresponsiveRequests job was supposed to run at ${fireDate}, ` +
59
+ `but actually ran at ${new Date()}`
60
+ );
61
+ this.findUnresponsiveRequests();
62
+ }, randomDelay);
68
63
 
69
- // db.getCollection('requests').find({"hasBot":true, "status": { "$lt": 1000 }, "createdAt": { "$lte" :new ISODate("2020-11-28T20:15:31Z")} }).count()
70
-
64
+ });
65
+ }
71
66
 
72
- // TODO escludi i ticket offline
73
- // var query = { };
74
- var query = {hasBot:true, status: { $lt: 1000 }, createdAt: { $lte :new Date(Date.now() - this.queryAfterTimeout ).toISOString()} };
67
+ /**
68
+ * Finds unresponsive bot requests and schedules their closure.
69
+ * Queries for requests with bots that haven't been updated within the timeout period.
70
+ */
71
+ findUnresponsiveRequests() {
72
+ const cutoffDate = new Date(Date.now() - this.queryAfterTimeout);
73
+ const query = {
74
+ hasBot: true,
75
+ status: { $lt: 1000 },
76
+ updatedAt: { $lte: cutoffDate }
77
+ };
75
78
 
76
79
  if (this.queryProject) {
77
- query.id_project = JSON.parse(this.queryProject);
80
+ try {
81
+ query.id_project = JSON.parse(this.queryProject);
82
+ } catch (err) {
83
+ winston.error("CloseBotUnresponsiveRequestTask error parsing queryProject filter", err);
84
+ return;
85
+ }
78
86
  }
79
87
 
88
+ winston.debug("CloseBotUnresponsiveRequestTask query", query);
80
89
 
81
- // TODO dovrei fare una query escludendo tutti gli id_project su cui è disabilitato oppure dovrei salvare un attribute in ogni singola request
82
-
83
- winston.debug("CloseBotUnresponsiveRequestTask query",query);
84
-
90
+ //console.log("[CloseUnresponsive] Searching with query: ", query);
85
91
  Request.find(query)
86
- .sort({createdAt: 'asc'}) //DA TESTARE
87
- .limit(this.queryLimit).exec(function(err, requests) {
88
- //it is limited to 1000 results but after same days it all ok
89
- if (err) {
92
+ .sort({ updatedAt: 'asc' })
93
+ .limit(this.queryLimit)
94
+ .hint({ status: 1, hasBot: 1, updatedAt: 1 })
95
+ .exec((err, requests) => {
96
+ if (err) {
90
97
  winston.error("CloseBotUnresponsiveRequestTask error getting unresponsive requests ", err);
91
- return 0;
92
- }
98
+ return;
99
+ }
93
100
 
94
- // winston.info("delayBeforeClosing: "+ that.delayBeforeClosing);
95
-
96
- if (!requests || (requests && requests.length==0)) {
101
+ if (!requests || requests.length === 0) {
97
102
  winston.verbose("CloseBotUnresponsiveRequestTask no unresponsive requests found ");
98
- return 0;
99
- }
100
-
101
- winston.info("CloseBotUnresponsiveRequestTask: found " + requests.length + " unresponsive requests");
102
- winston.debug("CloseBotUnresponsiveRequestTask: found unresponsive requests ", requests);
103
-
104
- let i = 0;
105
- let delay = 0;
106
- // winston.info("delay" + delay);
103
+ return;
104
+ }
107
105
 
108
- requests.forEach(request => {
109
- i++;
110
- delay = 2*that.delayBeforeClosing*i;
111
- winston.debug("CloseBotUnresponsiveRequestTask: delay : " + delay);
106
+ //console.log("[CloseUnresponsive] Found ", requests.length, " unresponsive requests");
112
107
 
113
- setTimeout(function(){
114
-
115
- // TODO aggiungi uno sleep
116
- winston.debug("********unresponsive request : "+ request.first_text);
117
- // winston.debug("********unresponsive request ", request);
118
-
119
- // closeRequestByRequestId(request_id, id_project, skipStatsUpdate, notify, closed_by)
120
- const closed_by = "_bot_unresponsive";
121
- return requestService.closeRequestByRequestId(request.request_id, request.id_project, false, false, closed_by).then(function(updatedStatusRequest) {
122
- winston.info("CloseBotUnresponsiveRequestTask: Request closed with request_id: " + request.request_id);
123
- // winston.info("Request closed",updatedStatusRequest);
124
- }).catch(function(err) {
125
- if (process.env.HIDE_CLOSE_REQUEST_ERRORS == true || process.env.HIDE_CLOSE_REQUEST_ERRORS == "true" ) {
126
-
127
- } else {
128
- winston.error("CloseBotUnresponsiveRequestTask: Error closing the request with request_id: " + request.request_id, err);
129
- }
130
-
131
- })
132
- }, delay)
108
+ winston.info("CloseBotUnresponsiveRequestTask: found " + requests.length + " unresponsive requests");
109
+ winston.debug("CloseBotUnresponsiveRequestTask: found unresponsive requests ", requests);
133
110
 
111
+ this.scheduleRequestClosures(requests);
134
112
  });
113
+ }
135
114
 
136
-
137
-
115
+ /**
116
+ * Schedules the closure of multiple requests with staggered delays.
117
+ * @param {Array} requests - Array of request objects to close
118
+ */
119
+ scheduleRequestClosures(requests) {
120
+ requests.forEach((request, index) => {
121
+ // Stagger delays: 2 * delayBeforeClosing * (index + 1)
122
+ const delay = 2 * this.delayBeforeClosing * (index + 1);
123
+ winston.debug(`CloseBotUnresponsiveRequestTask: scheduling closure with delay: ${delay}ms for request_id: ${request.request_id}`);
124
+
125
+ setTimeout(() => {
126
+ this.closeRequest(request);
127
+ }, delay);
138
128
  });
139
129
  }
140
130
 
131
+ /**
132
+ * Closes a single unresponsive request.
133
+ * @param {Object} request - The request object to close
134
+ */
135
+ closeRequest(request) {
136
+ winston.debug(`CloseBotUnresponsiveRequestTask: processing unresponsive request: ${request.first_text}`);
137
+
138
+ const closedBy = "_bot_unresponsive";
139
+ const shouldSkipStatsUpdate = false;
140
+ const shouldNotify = false;
141
+
142
+ requestService.closeRequestByRequestId(
143
+ request.request_id,
144
+ request.id_project,
145
+ shouldSkipStatsUpdate,
146
+ shouldNotify,
147
+ closedBy
148
+ ).then(() => {
149
+ winston.info(`CloseBotUnresponsiveRequestTask: Request closed with request_id: ${request.request_id}`);
150
+ }).catch((err) => {
151
+ const hideErrors = process.env.HIDE_CLOSE_REQUEST_ERRORS === true || process.env.HIDE_CLOSE_REQUEST_ERRORS === "true";
152
+
153
+ if (!hideErrors) {
154
+ winston.error(`CloseBotUnresponsiveRequestTask: Error closing the request with request_id: ${request.request_id}`, err);
155
+ }
156
+ });
141
157
 
142
-
158
+ }
143
159
 
144
-
145
160
  }
146
-
147
-
148
-
149
-
150
- var closeBotUnresponsiveRequestTask = new CloseBotUnresponsiveRequestTask();
151
161
 
162
+ const closeBotUnresponsiveRequestTask = new CloseBotUnresponsiveRequestTask();
152
163
 
153
164
  module.exports = closeBotUnresponsiveRequestTask;
@@ -1164,9 +1164,9 @@ class RulesTrigger {
1164
1164
  lead: createdLead, requester: puser
1165
1165
  };
1166
1166
 
1167
- let t1 = Date.now();
1167
+ //let t1 = Date.now();
1168
1168
  return requestService.create(new_request).then(function (savedRequest) {
1169
- console.log("[Performance] (rulesTrigger) requestService.create time: " + (Date.now() - t1));
1169
+ //console.log("[Performance] (rulesTrigger) requestService.create time: " + (Date.now() - t1));
1170
1170
  // performance console log
1171
1171
  // console.log("************* request created trigger: "+new Date().toISOString());
1172
1172
 
@@ -1177,9 +1177,9 @@ class RulesTrigger {
1177
1177
  var senderFullname = fullname || 'Guest'; // guest_here
1178
1178
 
1179
1179
  // create(sender, senderFullname, recipient, text, id_project, createdBy, status, attributes, type, metadata, language) {
1180
- let t2 = Date.now();
1180
+ //let t2 = Date.now();
1181
1181
  return messageService.create( id_user, senderFullname , savedRequest.request_id, text, id_project, id_user, MessageConstants.CHAT_MESSAGE_STATUS.SENDING, attributes, type, eventTrigger.event.metadata, language).then(function(savedMessage) {
1182
- console.log("[Performance] (rulesTrigger) messageService.create time: " + (Date.now() - t2));
1182
+ //console.log("[Performance] (rulesTrigger) messageService.create time: " + (Date.now() - t2));
1183
1183
  return savedMessage;
1184
1184
  });
1185
1185
  }).catch(function (err) {
package/routes/kb.js CHANGED
@@ -364,8 +364,19 @@ router.post('/qa', async (req, res) => {
364
364
  data.search_type = 'hybrid';
365
365
 
366
366
  if (data.reranking === true) {
367
- data.reranking_multiplier = 3;
368
367
  data.reranker_model = "cross-encoder/ms-marco-MiniLM-L-6-v2";
368
+
369
+ if (!data.reranking_multiplier) {
370
+ data.reranking_multiplier = 3;
371
+ }
372
+
373
+ if ((data.top_k * data.reranking_multiplier) > 100) {
374
+ let calculatedRerankingMultiplier = Math.floor(100 / data.top_k);
375
+ if (calculatedRerankingMultiplier < 1) {
376
+ calculatedRerankingMultiplier = 1;
377
+ }
378
+ data.reranking_multiplier = calculatedRerankingMultiplier;
379
+ }
369
380
  }
370
381
  }
371
382
 
@@ -205,7 +205,7 @@ class AiService {
205
205
  base_url = kb_endpoint_qa_gpu;
206
206
  }
207
207
  winston.debug("[OPENAI SERVICE] kb endpoint: " + base_url);
208
- console.log("aa1")
208
+
209
209
  return new Promise((resolve, reject) => {
210
210
 
211
211
  axios({
@@ -216,10 +216,8 @@ class AiService {
216
216
  data: data,
217
217
  method: 'POST'
218
218
  }).then((resbody) => {
219
- console.log("aa2")
220
219
  resolve(resbody);
221
220
  }).catch((err) => {
222
- console.log("aa3")
223
221
  reject(err);
224
222
  })
225
223
 
@@ -221,8 +221,8 @@ class RequestService {
221
221
  request.assigned_at = assigned_at;
222
222
  request.waiting_time = undefined //reset waiting_time on reroute
223
223
 
224
- console.log("request.snapshot for ", request.request_id ," exists: ", request.snapshot ? "yes" : "no\n", new Date());
225
- console.log("request.snapshot.agents for ", request.request_id ," exists: ", request.snapshot?.agents ? "yes" : "no\n", new Date());
224
+ //console.log("request.snapshot for ", request.request_id ," exists: ", request.snapshot ? "yes" : "no\n", new Date());
225
+ //console.log("request.snapshot.agents for ", request.request_id ," exists: ", request.snapshot?.agents ? "yes" : "no\n", new Date());
226
226
  if (!request.snapshot) { //if used other methods than .create
227
227
  request.snapshot = {}
228
228
  }
@@ -252,7 +252,7 @@ class RequestService {
252
252
  winston.debug("departmentid:" + departmentid);
253
253
  winston.debug("id_project:" + id_project);
254
254
  winston.debug("nobot:" + nobot);
255
- winston.info("main_flow_cache_3 route");
255
+ //winston.info("main_flow_cache_3 route");
256
256
 
257
257
  // Find request
258
258
  let query = Request.findOne({ request_id, id_project });
@@ -656,7 +656,7 @@ class RequestService {
656
656
  }
657
657
 
658
658
  winston.debug('newRequest.', newRequest);
659
- winston.info("main_flow_cache_ requestService create");
659
+ //winston.info("main_flow_cache_ requestService create");
660
660
 
661
661
  // Save request
662
662
  try {