@tiledesk/tiledesk-server 3.0.1 → 3.1.0

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 (136) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/CHANGELOG.md +34 -0
  3. package/Dockerfile +3 -2
  4. package/Dockerfile-en +3 -2
  5. package/Dockerfile-jobs +3 -2
  6. package/Dockerfile-profiler +3 -2
  7. package/README.md +15 -0
  8. package/app.js +12 -1
  9. package/bin/quota-reset +68 -0
  10. package/bin/quota-restore +86 -0
  11. package/channels/chat21/chat21Handler.js +50 -34
  12. package/channels/chat21/chat21JoinTracker.js +43 -0
  13. package/config/database.js +5 -5
  14. package/config/native_mcp/native_mcp_servers.json +1 -0
  15. package/controllers/chatbot.controller.js +80 -27
  16. package/controllers/intents.controller.js +42 -0
  17. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-chat21-ionic.md +468 -0
  18. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-design-studio.md +1349 -0
  19. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md +1694 -0
  20. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-tybot.md +789 -0
  21. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-server.md +83 -0
  22. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-tybot.md +76 -0
  23. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-chat21-ionic.md +97 -0
  24. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-design-studio.md +72 -0
  25. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-server.md +223 -0
  26. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-tybot.md +121 -0
  27. package/docs/superpowers/plans/2026-09-29-hitl-pre-branch-ports.md +65 -0
  28. package/docs/superpowers/plans/2026-09-30-flow-start-points-design-studio.md +88 -0
  29. package/docs/superpowers/plans/2026-09-30-flow-start-points-server.md +103 -0
  30. package/docs/superpowers/plans/2026-09-30-flow-start-points-tybot.md +43 -0
  31. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-design-studio.md +80 -0
  32. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-runtime.md +39 -0
  33. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-server.md +106 -0
  34. package/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md +715 -0
  35. package/docs/superpowers/specs/2026-09-30-flow-start-points-design.md +156 -0
  36. package/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md +303 -0
  37. package/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md +191 -0
  38. package/event/botEvent.js +12 -1
  39. package/event/emailEvent.js +3 -0
  40. package/event/messageEvent.js +44 -0
  41. package/jobs.js +10 -0
  42. package/jobsManager.js +19 -0
  43. package/middleware/errorHandler.js +6 -2
  44. package/models/analyticResult.js +1 -1
  45. package/models/channelConstants.js +3 -2
  46. package/models/quotaUsage.js +71 -0
  47. package/models/request.js +6 -0
  48. package/models/requestSnapshot.js +12 -0
  49. package/models/routerLogger.js +1 -1
  50. package/models/webhook.js +44 -0
  51. package/package.json +7 -5
  52. package/pubmodules/emailNotification/requestNotification.js +14 -22
  53. package/pubmodules/events/test/eventRoute.js +7 -6
  54. package/pubmodules/rules/conciergeBot.js +9 -4
  55. package/routes/auth.js +1 -12
  56. package/routes/campaigns.js +0 -13
  57. package/routes/dataTable.js +0 -3
  58. package/routes/faq_kb.js +12 -1
  59. package/routes/messagesRoot.js +0 -1
  60. package/routes/quotes.js +38 -1
  61. package/routes/request.js +81 -5
  62. package/routes/users.js +0 -1
  63. package/routes/webhook.js +160 -8
  64. package/routes/webhooks.js +276 -6
  65. package/routes/widgetLoader.js +6 -3
  66. package/services/QuoteManager.js +77 -16
  67. package/services/aiService.js +1 -1
  68. package/services/chatbotService.js +55 -1
  69. package/services/departmentService.js +60 -43
  70. package/services/dolphinSchedulerClient.js +116 -0
  71. package/services/emailService.js +6 -1
  72. package/services/hitlParticipantListener.js +260 -0
  73. package/services/participantInviteService.js +302 -0
  74. package/services/participantRemoveService.js +79 -0
  75. package/services/quotaSnapshotService.js +1167 -0
  76. package/services/requestService.js +102 -144
  77. package/services/scheduledStart/dolphinBackend.js +246 -0
  78. package/services/scheduledStart/schedulerBackend.js +101 -0
  79. package/services/scheduledStart/schedulerServiceClient.js +41 -0
  80. package/services/scheduledStartPublishListener.js +186 -0
  81. package/services/scheduledStartRules.js +173 -0
  82. package/services/scheduledStartService.js +130 -0
  83. package/services/startPointCleanupListener.js +30 -0
  84. package/services/startPointService.js +158 -0
  85. package/services/testWsService.js +1 -4
  86. package/services/updateRequestSnapshotQueued.js +8 -9
  87. package/services/webhookConversationService.js +185 -0
  88. package/services/webhookSettingsValidator.js +61 -0
  89. package/template/email/checkpointReachedEmail.html +5 -0
  90. package/test/agentPromptsRoute.test.js +3 -2
  91. package/test/agentTokensQuota.js +237 -0
  92. package/test/botEventHitlFallback.js +19 -0
  93. package/test/chat21HandlerJoinWiring.js +59 -0
  94. package/test/dataTablesRoute.test.js +10 -2
  95. package/test/dateUtils.test.js +0 -3
  96. package/test/departmentService.js +8 -12
  97. package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
  98. package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
  99. package/test/faqRoute.js +6 -1
  100. package/test/faqkbRoute.js +14 -10
  101. package/test/faqkbV3Route.js +1 -1
  102. package/test/filepRoute.js +4 -50
  103. package/test/hitlParticipantListener.js +446 -0
  104. package/test/hitlQueueWiring.js +191 -0
  105. package/test/hitlWaitingReset.js +124 -0
  106. package/test/inviteParticipantsRoute.js +492 -0
  107. package/test/kbRoute.js +1 -1
  108. package/test/messageRoute.js +33 -21
  109. package/test/nativemcp.test.js +7 -1
  110. package/test/openaiRoute.js +2 -8
  111. package/test/publishFailLoud.test.js +414 -0
  112. package/test/quotaSnapshots.js +1044 -0
  113. package/test/removeParticipantsRoute.js +186 -0
  114. package/test/requestService.js +24 -16
  115. package/test/requestServiceRemoveParticipant.js +144 -0
  116. package/test/requestVisibility.test.js +186 -0
  117. package/test/scheduledStartFacade.js +184 -0
  118. package/test/scheduledStartHandover.js +95 -0
  119. package/test/scheduledStartPublish.js +320 -0
  120. package/test/scheduledStartRoute.js +163 -0
  121. package/test/scheduledStartRules.js +177 -0
  122. package/test/scheduledStartRun.js +299 -0
  123. package/test/scheduledStartSchedulerBackend.js +116 -0
  124. package/test/scheduledStartService.js +290 -0
  125. package/test/startPointsCleanup.js +69 -0
  126. package/test/startPointsRegression.js +169 -0
  127. package/test/startPointsRoute.js +158 -0
  128. package/test/webhookConversationRoute.js +347 -0
  129. package/test/webhookConversationService.js +261 -0
  130. package/test/webhookConversationTestUtils.js +55 -0
  131. package/utils/aiUtils.js +95 -1
  132. package/utils/intentFieldNames.js +192 -0
  133. package/utils/quotaCliUtil.js +43 -0
  134. package/utils/requestVisibility.js +355 -0
  135. package/websocket/webSocketServer.js +36 -31
  136. /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
@@ -0,0 +1,302 @@
1
+ const mongoose = require('mongoose');
2
+ const Request = require('../models/request');
3
+ const Project = require('../models/project');
4
+ const Project_user = require('../models/project_user');
5
+ const User = require('../models/user');
6
+ const Department = require('../models/department');
7
+ const RequestConstants = require('../models/requestConstants');
8
+ const RoleConstants = require('../models/roleConstants');
9
+ const ChannelConstants = require('../models/channelConstants');
10
+ const requestService = require('./requestService');
11
+ const departmentService = require('./departmentService');
12
+ const emailService = require('./emailService');
13
+ const requestEvent = require('../event/requestEvent');
14
+ const chat21JoinTracker = require('../channels/chat21/chat21JoinTracker');
15
+ const winston = require('../config/winston');
16
+
17
+ const PENDING = 'pending';
18
+ const DEFAULT_CHAT21_JOIN_TIMEOUT_MS = 5000;
19
+ // mongoose.Types.ObjectId.isValid also accepts any 12-character string (a raw 12-byte
20
+ // ObjectId), which silently swallows short emails (e.g. "ops@acme.org" is 12 characters).
21
+ // Only treat a member as a user id when it actually looks like one: 24 hex characters.
22
+ const OBJECT_ID_RE = /^[a-f0-9]{24}$/i;
23
+
24
+ class InviteError extends Error {
25
+ constructor(status, message) {
26
+ super(message);
27
+ this.status = status;
28
+ }
29
+ }
30
+
31
+ function toId(value) {
32
+ return value && value.toString();
33
+ }
34
+
35
+ class ParticipantInviteService {
36
+
37
+ async invite(id_project, request_id, { department_id, members, fallback_intent } = {}) {
38
+ const request = await Request.findOne({ request_id: request_id, id_project: id_project }).exec();
39
+ if (!request) {
40
+ throw new InviteError(404, 'Request not found with id ' + request_id);
41
+ }
42
+ if (request.status === RequestConstants.CLOSED) {
43
+ throw new InviteError(409, 'Request ' + request_id + ' is closed');
44
+ }
45
+ if (!request.channel || request.channel.name !== ChannelConstants.WEBHOOK) {
46
+ throw new InviteError(422, 'Invite human requires a conversation started by a webhook or a schedule');
47
+ }
48
+
49
+ const participants = (request.participants || []).map(toId);
50
+ let invitees = await this.resolveMembers(id_project, members);
51
+ let resolvedDepartmentId = null;
52
+
53
+ if (invitees.length === 0) {
54
+ const department = await this.resolveDepartment(id_project, department_id || toId(request.department));
55
+ resolvedDepartmentId = toId(department._id);
56
+ invitees = await this.pickFromDepartment(id_project, department, request, participants);
57
+ } else {
58
+ // members path: no department pick; resolve best-effort, never fail the invite
59
+ try {
60
+ const department = await this.resolveDepartment(id_project, department_id || toId(request.department));
61
+ resolvedDepartmentId = toId(department._id);
62
+ } catch (err) {
63
+ resolvedDepartmentId = null;
64
+ }
65
+ }
66
+
67
+ if (invitees.length === 0) {
68
+ return { request_id: request_id, department_id: resolvedDepartmentId, invited: [], reason: 'no_available_agents' };
69
+ }
70
+
71
+ const invited = [];
72
+ const newlyAdded = [];
73
+ const chat21Joins = [];
74
+ for (const id_user of invitees) {
75
+ const already_participant = participants.includes(id_user);
76
+ if (!already_participant) {
77
+ await requestService.addParticipantByRequestId(request_id, id_project, id_user);
78
+ newlyAdded.push(id_user);
79
+ // registered by chat21Handler while the participants.join event was emitted (absent when it is not listening)
80
+ const join = chat21JoinTracker.get(request_id, id_user);
81
+ if (join) {
82
+ chat21Joins.push(join);
83
+ }
84
+ }
85
+ invited.push({ id_user: id_user, fullname: await this.fullnameOf(id_user), already_participant: already_participant });
86
+ }
87
+
88
+ const updatedRequest = await this.markWaiting(request_id, id_project, {
89
+ invitedIds: invited.map((i) => i.id_user),
90
+ department_id: resolvedDepartmentId,
91
+ fallback_intent: fallback_intent
92
+ });
93
+ this.notifyInvited(id_project, updatedRequest, newlyAdded);
94
+
95
+ // The flow sends its next message as soon as this returns: answer only once chat21 has the
96
+ // invited humans in the group, or they would miss that message (bounded; never fails the invite).
97
+ if (request.channelOutbound && request.channelOutbound.name === ChannelConstants.CHAT21) {
98
+ await this.waitForChat21Joins(request_id, chat21Joins);
99
+ }
100
+
101
+ return { request_id: request_id, department_id: resolvedDepartmentId, invited: invited };
102
+ }
103
+
104
+ /** Waits for the given chat21 join settle promises, at most HITL_CHAT21_JOIN_TIMEOUT_MS (default 5000). Never throws. */
105
+ async waitForChat21Joins(request_id, joins) {
106
+ if (!joins || joins.length === 0) {
107
+ return;
108
+ }
109
+ const parsed = parseInt(process.env.HITL_CHAT21_JOIN_TIMEOUT_MS, 10);
110
+ const timeoutMs = Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_CHAT21_JOIN_TIMEOUT_MS;
111
+ let timer;
112
+ const timeout = new Promise((resolve) => {
113
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
114
+ });
115
+ try {
116
+ const outcome = await Promise.race([Promise.all(joins), timeout]);
117
+ if (outcome === 'timeout') {
118
+ winston.warn('(ParticipantInviteService) chat21 join not completed within ' + timeoutMs + 'ms for request ' + request_id + ': answering the invite anyway');
119
+ return;
120
+ }
121
+ outcome.filter((r) => !r.ok).forEach((r) => {
122
+ winston.warn('(ParticipantInviteService) chat21 join failed for member ' + r.member + ' in group ' + r.groupId + ': answering the invite anyway', r.error);
123
+ });
124
+ } catch (err) {
125
+ winston.warn('(ParticipantInviteService) error waiting for the chat21 join for request ' + request_id, err);
126
+ } finally {
127
+ clearTimeout(timer);
128
+ }
129
+ }
130
+
131
+ /** Resolves ids or emails to active agent-type project users of the project. */
132
+ async resolveMembers(id_project, members) {
133
+ if (!Array.isArray(members) || members.length === 0) {
134
+ return [];
135
+ }
136
+ const ids = [];
137
+ for (const rawMember of members) {
138
+ if (!rawMember || typeof rawMember !== 'string') {
139
+ continue;
140
+ }
141
+ const member = rawMember.trim();
142
+ if (!member) {
143
+ continue;
144
+ }
145
+ let id_user = null;
146
+ if (OBJECT_ID_RE.test(member)) {
147
+ id_user = member;
148
+ } else {
149
+ const user = await User.findOne({ email: member.toLowerCase(), status: 100 }).lean().exec();
150
+ id_user = user ? toId(user._id) : null;
151
+ }
152
+ if (!id_user) {
153
+ continue;
154
+ }
155
+ const project_user = await Project_user.findOne({ id_project: id_project, id_user: id_user, roleType: RoleConstants.TYPE_AGENTS, status: 'active' }).lean().exec();
156
+ if (project_user && !ids.includes(id_user)) {
157
+ ids.push(id_user);
158
+ }
159
+ }
160
+ return ids;
161
+ }
162
+
163
+ async resolveDepartment(id_project, department_id) {
164
+ let department;
165
+ if (department_id) {
166
+ if (!mongoose.Types.ObjectId.isValid(department_id)) {
167
+ throw new InviteError(422, 'Department not found with id ' + department_id);
168
+ }
169
+ department = await Department.findOne({ _id: department_id, id_project: id_project }).lean().exec();
170
+ if (!department) {
171
+ throw new InviteError(422, 'Department not found with id ' + department_id);
172
+ }
173
+ return department;
174
+ }
175
+ department = await Department.findOne({ id_project: id_project, default: true }).lean().exec();
176
+ if (!department) {
177
+ throw new InviteError(422, 'Default department not found for project ' + id_project);
178
+ }
179
+ return department;
180
+ }
181
+
182
+ /** One agent: the operator selected by assigned routing, or one random available agent for pooled routing. */
183
+ async pickFromDepartment(id_project, department, request, participants) {
184
+ const result = await departmentService.getOperators(toId(department._id), id_project, true, undefined, { request: request });
185
+
186
+ // humans who left this conversation are never picked again by a department invite
187
+ const left = ((request.attributes && request.attributes.hitl_left) || []).map(toId);
188
+ const operators = (result.operators || []).map((op) => toId(op.id_user)).filter((id_user) => id_user && !left.includes(id_user));
189
+ const freeOperators = operators.filter((id_user) => !participants.includes(id_user));
190
+ if (freeOperators.length > 0) {
191
+ return [freeOperators[0]];
192
+ }
193
+ if (operators.length > 0) {
194
+ // the selected operator is already in the conversation: count it as invited
195
+ return [operators[0]];
196
+ }
197
+
198
+ const availableAgents = (result.available_agents || []).filter((pu) => !left.includes(toId(pu.id_user)));
199
+ const freeAvailable = availableAgents.filter((pu) => !participants.includes(toId(pu.id_user)));
200
+ // If everyone available is already a participant, still report one of them as invited
201
+ // (already_participant: true) rather than as unavailable - mirrors the operators fallback above.
202
+ const pool = freeAvailable.length > 0 ? freeAvailable : availableAgents;
203
+ const picked = departmentService.getRandomAvailableOperator(pool);
204
+ return (picked || []).map((op) => toId(op.id_user));
205
+ }
206
+
207
+ /**
208
+ * One replacement agent for a human who left: the routing operator, else one random available agent.
209
+ * Never returns an id in `excluded` (unlike pickFromDepartment, which falls back to participants).
210
+ */
211
+ async pickReplacement(id_project, department, request, excluded) {
212
+ const excludedIds = (excluded || []).map(toId);
213
+ const result = await departmentService.getOperators(toId(department._id), id_project, true, undefined, { request: request });
214
+
215
+ const operators = (result.operators || []).map((op) => toId(op.id_user)).filter(Boolean);
216
+ const freeOperator = operators.find((id_user) => !excludedIds.includes(id_user));
217
+ if (freeOperator) {
218
+ return freeOperator;
219
+ }
220
+
221
+ const freeAvailable = (result.available_agents || []).filter((pu) => !excludedIds.includes(toId(pu.id_user)));
222
+ const picked = departmentService.getRandomAvailableOperator(freeAvailable);
223
+ const id_user = picked && picked.length > 0 ? toId(picked[0].id_user) : null;
224
+ return id_user && !excludedIds.includes(id_user) ? id_user : null;
225
+ }
226
+
227
+ async fullnameOf(id_user) {
228
+ const user = await User.findById(id_user).lean().exec();
229
+ if (!user) {
230
+ return '';
231
+ }
232
+ return ((user.firstname || '') + ' ' + (user.lastname || '')).trim();
233
+ }
234
+
235
+ async markWaiting(request_id, id_project, { invitedIds, department_id, fallback_intent } = {}) {
236
+ const $set = { workingStatus: PENDING, 'attributes.hitl_waiting': true };
237
+ if (department_id) {
238
+ $set['attributes.hitl_department_id'] = department_id;
239
+ }
240
+ const update = { $set };
241
+ if (invitedIds && invitedIds.length > 0) {
242
+ // the fallback belongs to the latest invite that brought a human in: replace or drop the earlier one
243
+ if (typeof fallback_intent === 'string' && fallback_intent) {
244
+ $set['attributes.hitl_fallback'] = { intent: fallback_intent };
245
+ } else {
246
+ update.$unset = { 'attributes.hitl_fallback': '' };
247
+ }
248
+ update.$addToSet = { 'attributes.hitl_invited': { $each: invitedIds } };
249
+ }
250
+ const updatedRequest = await Request.findOneAndUpdate(
251
+ { request_id: request_id, id_project: id_project },
252
+ update,
253
+ { new: true }
254
+ )
255
+ .populate('lead')
256
+ .populate('department')
257
+ .populate('participatingBots')
258
+ .populate('participatingAgents')
259
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
260
+ .exec();
261
+ requestEvent.emit('request.workingStatus.update', { request: updatedRequest });
262
+ requestEvent.emit('request.update', updatedRequest);
263
+ return updatedRequest;
264
+ }
265
+
266
+ /** Same opt-outs as requestNotification.sendAgentEmail (assigned branch). Fire and forget. */
267
+ notifyInvited(id_project, request, userIds) {
268
+ if (!userIds || userIds.length === 0) {
269
+ return;
270
+ }
271
+ setImmediate(async () => {
272
+ try {
273
+ const project = await Project.findOne({ _id: id_project, status: 100 }).select('+settings').exec();
274
+ if (!project) {
275
+ return;
276
+ }
277
+ const conversationSettings = project.settings && project.settings.email && project.settings.email.notification && project.settings.email.notification.conversation;
278
+ if (conversationSettings && (conversationSettings.blocked === true || conversationSettings.assigned === false)) {
279
+ return;
280
+ }
281
+ for (const id_user of userIds) {
282
+ const project_user = await Project_user.findOne({ id_user: id_user, id_project: id_project, status: 'active' }).lean().exec();
283
+ const userSettings = project_user && project_user.settings && project_user.settings.email && project_user.settings.email.notification && project_user.settings.email.notification.conversation;
284
+ if (!project_user || (userSettings && userSettings.assigned && userSettings.assigned.toyou === false)) {
285
+ continue;
286
+ }
287
+ const user = await User.findOne({ _id: id_user, status: 100 }).lean().exec();
288
+ if (user) {
289
+ emailService.sendNewAssignedRequestNotification(user.email, request, project);
290
+ }
291
+ }
292
+ } catch (err) {
293
+ winston.error('(ParticipantInviteService) error sending invite emails', err);
294
+ }
295
+ });
296
+ }
297
+ }
298
+
299
+ const participantInviteService = new ParticipantInviteService();
300
+ participantInviteService.InviteError = InviteError;
301
+
302
+ module.exports = participantInviteService;
@@ -0,0 +1,79 @@
1
+ const Request = require('../models/request');
2
+ const RequestConstants = require('../models/requestConstants');
3
+ const ChannelConstants = require('../models/channelConstants');
4
+ const requestService = require('./requestService');
5
+ const participantInviteService = require('./participantInviteService');
6
+ const requestEvent = require('../event/requestEvent');
7
+
8
+ const InviteError = participantInviteService.InviteError;
9
+ const PENDING = 'pending';
10
+ const OPEN = 'open';
11
+
12
+ function toId(value) {
13
+ return value && value.toString();
14
+ }
15
+
16
+ class ParticipantRemoveService {
17
+
18
+ /** Removes the humans (never the bot) from a webhook conversation and clears its HITL state. */
19
+ async remove(id_project, request_id, { scope = 'invited' } = {}) {
20
+ const request = await Request.findOne({ request_id: request_id, id_project: id_project }).exec();
21
+ if (!request) {
22
+ throw new InviteError(404, 'Request not found with id ' + request_id);
23
+ }
24
+ if (request.status === RequestConstants.CLOSED) {
25
+ throw new InviteError(409, 'Request ' + request_id + ' is closed');
26
+ }
27
+ if (!request.channel || request.channel.name !== ChannelConstants.WEBHOOK) {
28
+ throw new InviteError(422, 'Remove human requires a conversation started by a webhook or a schedule');
29
+ }
30
+
31
+ // Clear the HITL context first, atomically, so a later listener never treats these removals
32
+ // as a human leaving. new:false returns the pre-clear document (hitl_invited, workingStatus).
33
+ const before = await Request.findOneAndUpdate(
34
+ { request_id: request_id, id_project: id_project },
35
+ { $unset: { 'attributes.hitl_waiting': 1, 'attributes.hitl_invited': 1, 'attributes.hitl_fallback': 1 } },
36
+ { new: false }
37
+ ).lean().exec();
38
+ if (!before) {
39
+ throw new InviteError(404, 'Request not found with id ' + request_id);
40
+ }
41
+
42
+ if (before.workingStatus === PENDING) {
43
+ const reopened = await Request.findOneAndUpdate(
44
+ { request_id: request_id, id_project: id_project, workingStatus: PENDING },
45
+ { $set: { workingStatus: OPEN } },
46
+ { new: true }
47
+ )
48
+ .populate('lead')
49
+ .populate('department')
50
+ .populate('participatingBots')
51
+ .populate('participatingAgents')
52
+ .populate({ path: 'requester', populate: { path: 'id_user' } })
53
+ .exec();
54
+ if (reopened) {
55
+ requestEvent.emit('request.workingStatus.update', { request: reopened });
56
+ requestEvent.emit('request.update', reopened);
57
+ }
58
+ }
59
+
60
+ const participants = (before.participants || []).map(toId);
61
+ let targets;
62
+ if (scope === 'all_humans') {
63
+ targets = participants.filter((p) => !p.startsWith('bot_'));
64
+ } else {
65
+ const invited = ((before.attributes && before.attributes.hitl_invited) || []).map(toId);
66
+ targets = invited.filter((id) => participants.includes(id) && !id.startsWith('bot_'));
67
+ }
68
+
69
+ const removed = [];
70
+ for (const id_user of targets) {
71
+ await requestService.removeParticipantByRequestId(request_id, id_project, id_user, {});
72
+ removed.push({ id_user: id_user, fullname: await participantInviteService.fullnameOf(id_user) });
73
+ }
74
+
75
+ return { request_id: request_id, removed: removed };
76
+ }
77
+ }
78
+
79
+ module.exports = new ParticipantRemoveService();