@tiledesk/tiledesk-server 3.0.1 → 3.2.1

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 (140) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/CHANGELOG.md +47 -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/dataTable.js +16 -0
  47. package/models/location.js +6 -12
  48. package/models/quotaUsage.js +71 -0
  49. package/models/request.js +71 -61
  50. package/models/requestSnapshot.js +12 -0
  51. package/models/routerLogger.js +1 -1
  52. package/models/webhook.js +44 -0
  53. package/package.json +9 -7
  54. package/pubmodules/emailNotification/requestNotification.js +14 -22
  55. package/pubmodules/events/test/eventRoute.js +7 -6
  56. package/pubmodules/rules/conciergeBot.js +9 -4
  57. package/routes/auth.js +1 -12
  58. package/routes/campaigns.js +0 -13
  59. package/routes/dataTable.js +23 -3
  60. package/routes/faq_kb.js +12 -1
  61. package/routes/messagesRoot.js +0 -1
  62. package/routes/quotes.js +38 -1
  63. package/routes/request.js +81 -5
  64. package/routes/users.js +0 -1
  65. package/routes/webhook.js +160 -8
  66. package/routes/webhooks.js +276 -6
  67. package/routes/widgetLoader.js +6 -3
  68. package/services/QuoteManager.js +77 -16
  69. package/services/aiService.js +1 -1
  70. package/services/chatbotService.js +55 -1
  71. package/services/dataTableService.js +436 -42
  72. package/services/departmentService.js +60 -43
  73. package/services/dolphinSchedulerClient.js +116 -0
  74. package/services/emailService.js +6 -1
  75. package/services/hitlParticipantListener.js +260 -0
  76. package/services/participantInviteService.js +302 -0
  77. package/services/participantRemoveService.js +79 -0
  78. package/services/quotaSnapshotService.js +1167 -0
  79. package/services/requestService.js +102 -144
  80. package/services/scheduledStart/dolphinBackend.js +246 -0
  81. package/services/scheduledStart/schedulerBackend.js +101 -0
  82. package/services/scheduledStart/schedulerServiceClient.js +41 -0
  83. package/services/scheduledStartPublishListener.js +186 -0
  84. package/services/scheduledStartRules.js +173 -0
  85. package/services/scheduledStartService.js +130 -0
  86. package/services/startPointCleanupListener.js +30 -0
  87. package/services/startPointService.js +158 -0
  88. package/services/testWsService.js +1 -4
  89. package/services/updateRequestSnapshotQueued.js +8 -9
  90. package/services/webhookConversationService.js +185 -0
  91. package/services/webhookSettingsValidator.js +61 -0
  92. package/template/email/checkpointReachedEmail.html +5 -0
  93. package/test/agentPromptsRoute.test.js +3 -2
  94. package/test/agentTokensQuota.js +237 -0
  95. package/test/botEventHitlFallback.js +19 -0
  96. package/test/chat21HandlerJoinWiring.js +59 -0
  97. package/test/dataTablesRoute.test.js +649 -2
  98. package/test/dateUtils.test.js +0 -3
  99. package/test/departmentService.js +8 -12
  100. package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
  101. package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
  102. package/test/faqRoute.js +6 -1
  103. package/test/faqkbRoute.js +14 -10
  104. package/test/faqkbV3Route.js +1 -1
  105. package/test/filepRoute.js +4 -50
  106. package/test/hitlParticipantListener.js +446 -0
  107. package/test/hitlQueueWiring.js +191 -0
  108. package/test/hitlWaitingReset.js +124 -0
  109. package/test/inviteParticipantsRoute.js +492 -0
  110. package/test/kbRoute.js +1 -1
  111. package/test/messageRoute.js +33 -21
  112. package/test/nativemcp.test.js +7 -1
  113. package/test/openaiRoute.js +2 -8
  114. package/test/publishFailLoud.test.js +414 -0
  115. package/test/quotaSnapshots.js +1044 -0
  116. package/test/removeParticipantsRoute.js +186 -0
  117. package/test/requestService.js +24 -16
  118. package/test/requestServiceRemoveParticipant.js +144 -0
  119. package/test/requestVisibility.test.js +186 -0
  120. package/test/scheduledStartFacade.js +184 -0
  121. package/test/scheduledStartHandover.js +95 -0
  122. package/test/scheduledStartPublish.js +320 -0
  123. package/test/scheduledStartRoute.js +163 -0
  124. package/test/scheduledStartRules.js +177 -0
  125. package/test/scheduledStartRun.js +299 -0
  126. package/test/scheduledStartSchedulerBackend.js +116 -0
  127. package/test/scheduledStartService.js +290 -0
  128. package/test/startPointsCleanup.js +69 -0
  129. package/test/startPointsRegression.js +169 -0
  130. package/test/startPointsRoute.js +158 -0
  131. package/test/webhookConversationRoute.js +347 -0
  132. package/test/webhookConversationService.js +261 -0
  133. package/test/webhookConversationTestUtils.js +55 -0
  134. package/utils/aiUtils.js +95 -1
  135. package/utils/dataTableUtils.js +99 -9
  136. package/utils/intentFieldNames.js +192 -0
  137. package/utils/quotaCliUtil.js +43 -0
  138. package/utils/requestVisibility.js +355 -0
  139. package/websocket/webSocketServer.js +36 -31
  140. /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
@@ -0,0 +1,186 @@
1
+ //During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+ process.env.LOG_LEVEL = 'error';
4
+
5
+ const chai = require('chai');
6
+ const chaiHttp = require('chai-http');
7
+ const server = require('../app');
8
+ const expect = chai.expect;
9
+ chai.use(chaiHttp);
10
+
11
+ const userService = require('../services/userService');
12
+ const projectService = require('../services/projectService');
13
+ const departmentService = require('../services/departmentService');
14
+ const faqService = require('../services/faqService');
15
+ const requestService = require('../services/requestService');
16
+ const Project_user = require('../models/project_user');
17
+ const Request = require('../models/request');
18
+ const Department = require('../models/department');
19
+ const RoleConstants = require('../models/roleConstants');
20
+ const { uniqueEmail, PWD, waitFor } = require('./webhookConversationTestUtils');
21
+
22
+ async function addAgent(project, owner, { available = true, email } = {}) {
23
+ email = email || uniqueEmail('test-remove-agent');
24
+ const agent = await userService.signup(email, PWD, 'Agent', 'Smith');
25
+ await new Project_user({
26
+ id_project: project._id.toString(),
27
+ id_user: agent._id.toString(),
28
+ role: RoleConstants.AGENT,
29
+ roleType: RoleConstants.TYPE_AGENTS,
30
+ user_available: available,
31
+ createdBy: owner._id.toString(),
32
+ updatedBy: owner._id.toString()
33
+ }).save();
34
+ return { agent, email };
35
+ }
36
+
37
+ // beforeRequest(project, owner), when given, runs after the project exists and before the
38
+ // request is created (e.g. to set up a department and its agents so any project_user query
39
+ // that requestService.create() triggers along the way already sees them - see
40
+ // departmentService.getOperators's ~30s project_user query cache, cacheEnabler.project_user /
41
+ // cacheUtil.queryTTL). Its return value (an object) is merged into the returned context.
42
+ async function setup({ ownerAvailable = true, beforeRequest } = {}) {
43
+ const ownerEmail = uniqueEmail('test-remove-owner');
44
+ const owner = await userService.signup(ownerEmail, PWD, 'Owner', 'User');
45
+ const project = await projectService.create('test-remove-participants', owner._id);
46
+ if (!ownerAvailable) {
47
+ await Project_user.findOneAndUpdate({ id_project: project._id, id_user: owner._id }, { user_available: false }).exec();
48
+ }
49
+ const chatbot = await faqService.create(project._id, owner._id, { name: 'hitl-bot', type: 'tilebot', language: 'en', template: 'blank' });
50
+ const hookResult = beforeRequest ? await beforeRequest(project, owner) : undefined;
51
+ const request = await requestService.create({
52
+ request_id: 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000),
53
+ id_project: project._id.toString(),
54
+ first_text: '/start',
55
+ participants: ['bot_' + chatbot._id.toString()],
56
+ channel: { name: 'webhook' },
57
+ preflight: false,
58
+ createdBy: 'system'
59
+ });
60
+ return { owner, ownerEmail, project, chatbot, request, ...(hookResult || {}) };
61
+ }
62
+
63
+ function post(ctx, path, body, auth) {
64
+ const req = chai.request(server).post('/' + ctx.project._id + '/requests/' + ctx.request.request_id + path);
65
+ if (auth && auth.jwt) {
66
+ req.set('Authorization', 'JWT ' + auth.jwt);
67
+ } else {
68
+ req.auth(ctx.ownerEmail, PWD);
69
+ }
70
+ return req.send(body);
71
+ }
72
+
73
+ const invite = (ctx, body, auth) => post(ctx, '/participants/invite', body, auth);
74
+ const remove = (ctx, body, auth) => post(ctx, '/participants/remove', body, auth);
75
+
76
+ const load = (ctx) => Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
77
+
78
+ describe('RemoveParticipantsRoute', function () {
79
+
80
+ this.timeout(20000);
81
+
82
+ it('removes only the humans invited by the flow and keeps the bot', async () => {
83
+ const ctx = await setup({ ownerAvailable: false });
84
+ const a = await addAgent(ctx.project, ctx.owner);
85
+ const b = await addAgent(ctx.project, ctx.owner);
86
+ await invite(ctx, { members: [a.email] });
87
+ await requestService.addParticipantByRequestId(ctx.request.request_id, ctx.project._id.toString(), b.agent._id.toString());
88
+
89
+ const res = await remove(ctx, { scope: 'invited' });
90
+
91
+ expect(res).to.have.status(200);
92
+ expect(res.body.removed).to.deep.equal([{ id_user: a.agent._id.toString(), fullname: 'Agent Smith' }]);
93
+ const request = await load(ctx);
94
+ expect(request.participants).to.deep.equal(['bot_' + ctx.chatbot._id.toString(), b.agent._id.toString()]);
95
+ });
96
+
97
+ it('removes every human with all_humans and keeps the bot', async () => {
98
+ const ctx = await setup({ ownerAvailable: false });
99
+ const a = await addAgent(ctx.project, ctx.owner);
100
+ const b = await addAgent(ctx.project, ctx.owner);
101
+ await invite(ctx, { members: [a.email] });
102
+ await requestService.addParticipantByRequestId(ctx.request.request_id, ctx.project._id.toString(), b.agent._id.toString());
103
+
104
+ const res = await remove(ctx, { scope: 'all_humans' });
105
+
106
+ expect(res).to.have.status(200);
107
+ expect(res.body.removed.map((r) => r.id_user).sort()).to.deep.equal([a.agent._id.toString(), b.agent._id.toString()].sort());
108
+ const request = await load(ctx);
109
+ expect(request.participants).to.deep.equal(['bot_' + ctx.chatbot._id.toString()]);
110
+ });
111
+
112
+ it('clears the HITL context and reopens a pending conversation', async () => {
113
+ const ctx = await setup({ ownerAvailable: false });
114
+ const a = await addAgent(ctx.project, ctx.owner);
115
+ await invite(ctx, { members: [a.email], fallback_intent: '#noone-id' });
116
+ expect((await load(ctx)).workingStatus).to.equal('pending');
117
+
118
+ const res = await remove(ctx, {});
119
+
120
+ expect(res).to.have.status(200);
121
+ const request = await load(ctx);
122
+ expect(request.attributes.hitl_waiting).to.equal(undefined);
123
+ expect(request.attributes.hitl_invited).to.equal(undefined);
124
+ expect(request.attributes.hitl_fallback).to.equal(undefined);
125
+ expect(request.workingStatus).to.equal('open');
126
+ });
127
+
128
+ it('answers 200 with an empty list when nobody is left to remove', async () => {
129
+ const ctx = await setup({ ownerAvailable: false });
130
+
131
+ const res = await remove(ctx, { scope: 'all_humans' });
132
+
133
+ expect(res).to.have.status(200);
134
+ expect(res.body.removed).to.deep.equal([]);
135
+ expect(res.body.request_id).to.equal(ctx.request.request_id);
136
+ });
137
+
138
+ it('does not reassign the removed humans', async () => {
139
+ const ctx = await setup({ ownerAvailable: false, beforeRequest: async (project, owner) => {
140
+ const department = await departmentService.create('SRE pooled', project._id, 'pooled', owner._id);
141
+ const a = await addAgent(project, owner);
142
+ const b = await addAgent(project, owner);
143
+ return { department, agents: [a, b] };
144
+ }});
145
+ const inviteRes = await invite(ctx, { department_id: ctx.department._id.toString(), fallback_intent: '#noone-id' });
146
+ expect(inviteRes).to.have.status(200);
147
+ const invitedId = inviteRes.body.invited[0].id_user;
148
+
149
+ const res = await remove(ctx, {});
150
+ expect(res).to.have.status(200);
151
+ expect(res.body.removed.map((r) => r.id_user)).to.deep.equal([invitedId]);
152
+
153
+ await new Promise((resolve) => setTimeout(resolve, 1500));
154
+ const request = await load(ctx);
155
+ expect(request.participants).to.deep.equal(['bot_' + ctx.chatbot._id.toString()]);
156
+ expect(request.attributes.hitl_left).to.equal(undefined);
157
+ });
158
+
159
+ it('rejects an unknown scope with 422', async () => {
160
+ const ctx = await setup();
161
+ const res = await remove(ctx, { scope: 'everyone' });
162
+ expect(res).to.have.status(422);
163
+ expect(res.body).to.deep.equal({ success: false, error: 'scope must be "invited" or "all_humans"' });
164
+ });
165
+
166
+ it('returns 404 for unknown and other-project requests, 409 for closed, 422 for non-webhook', async () => {
167
+ const ctx = await setup();
168
+
169
+ const unknown = await post({ ...ctx, request: { request_id: 'nope-' + Date.now() } }, '/participants/remove', {});
170
+ expect(unknown).to.have.status(404);
171
+
172
+ const other = await setup();
173
+ const cross = await post({ ...ctx, request: other.request }, '/participants/remove', {});
174
+ expect(cross).to.have.status(404);
175
+ expect((await load(other)).participants).to.include('bot_' + other.chatbot._id.toString());
176
+
177
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { 'channel.name': 'chat21' } }).exec();
178
+ const nonWebhook = await remove(ctx, {});
179
+ expect(nonWebhook).to.have.status(422);
180
+ expect(nonWebhook.body.error).to.equal('Remove human requires a conversation started by a webhook or a schedule');
181
+
182
+ await Request.updateOne({ request_id: ctx.request.request_id }, { $set: { 'channel.name': 'webhook', status: 1000 } }).exec();
183
+ const closed = await remove(ctx, {});
184
+ expect(closed).to.have.status(409);
185
+ });
186
+ });
@@ -36,6 +36,7 @@ var Group = require("../models/group");
36
36
  var Project_user = require("../models/project_user");
37
37
  // var Tag = require('../models/tag');
38
38
  var requestEvent = require('../event/requestEvent');
39
+ var UpdateLeadQueued = require('../services/updateLeadQueued');
39
40
 
40
41
  var { QuoteManager } = require('../services/QuoteManager');
41
42
  const projectMock = require('./mock/projectMock');
@@ -235,8 +236,17 @@ describe('RequestService', function () {
235
236
 
236
237
  // mocha test/requestService.js --grep 'createObjSimpleUpdateLeadUpdateSnapshot'
237
238
 
239
+ let updateLeadQueuedListening = false;
240
+
238
241
  it('createObjSimpleUpdateLeadUpdateSnapshot', function (done) {
239
- // this.timeout(10000);
242
+ this.timeout(10000);
243
+
244
+ // With JOB_WORKER_ENABLED the API process does not start this listener.
245
+ if (!updateLeadQueuedListening) {
246
+ UpdateLeadQueued.listen();
247
+ updateLeadQueuedListening = true;
248
+ }
249
+
240
250
  var email = "test-request-create-" + Date.now() + "@email.com";
241
251
  var pwd = "pwd";
242
252
 
@@ -286,6 +296,19 @@ describe('RequestService', function () {
286
296
  expect(savedRequest.id_project).to.equal(savedProject._id.toString());
287
297
 
288
298
 
299
+ requestEvent.once('request.update.snapshot.lead', function (data) {
300
+
301
+ Request.findById(savedRequest._id, function (err, request) {
302
+
303
+ if (err) { console.error("err", err); }
304
+
305
+ expect(request.request_id).to.equal("request_idcreateObjSimpleUpdateLeadUpdateSnapshot-" + now);
306
+ //expect(request.snapshot.lead.fullname).to.equal("fullname2");
307
+ done();
308
+ });
309
+
310
+ });
311
+
289
312
  leadService.updateWitId(createdLead.lead_id, "fullname2", "email2@email2.com", savedProject._id).then(function (updatedLead) {
290
313
 
291
314
  expect(updatedLead.fullname).to.equal("fullname2");
@@ -294,21 +317,6 @@ describe('RequestService', function () {
294
317
  expect(updatedLead.lead_id).to.not.equal(createdLead.id);
295
318
  if (log) { console.log("updatedLead", updatedLead); }
296
319
 
297
- requestEvent.on('request.update.snapshot.lead', function (data) {
298
-
299
- Request.findById(savedRequest._id, function (err, request) {
300
-
301
- if (err) { console.error("err", err); }
302
-
303
- expect(request.request_id).to.equal("request_idcreateObjSimpleUpdateLeadUpdateSnapshot-" + now);
304
- //expect(request.snapshot.lead.fullname).to.equal("fullname2");
305
- done();
306
- });
307
-
308
- });
309
-
310
-
311
-
312
320
  });
313
321
 
314
322
 
@@ -0,0 +1,144 @@
1
+ //During the test the env variable is set to test
2
+ process.env.NODE_ENV = 'test';
3
+ process.env.LOG_LEVEL = 'error';
4
+
5
+ const chai = require('chai');
6
+ const expect = chai.expect;
7
+ require('../app');
8
+
9
+ const userService = require('../services/userService');
10
+ const projectService = require('../services/projectService');
11
+ const faqService = require('../services/faqService');
12
+ const requestService = require('../services/requestService');
13
+ const requestEvent = require('../event/requestEvent');
14
+ const Project_user = require('../models/project_user');
15
+ const Request = require('../models/request');
16
+ const RoleConstants = require('../models/roleConstants');
17
+ const { uniqueEmail, PWD } = require('./webhookConversationTestUtils');
18
+
19
+ async function addAgent(project, owner) {
20
+ const agent = await userService.signup(uniqueEmail('test-remove-agent'), PWD, 'Agent', 'Smith');
21
+ const pu = await new Project_user({
22
+ id_project: project._id.toString(),
23
+ id_user: agent._id.toString(),
24
+ role: RoleConstants.AGENT,
25
+ roleType: RoleConstants.TYPE_AGENTS,
26
+ user_available: true,
27
+ createdBy: owner._id.toString(),
28
+ updatedBy: owner._id.toString()
29
+ }).save();
30
+ return { id: agent._id.toString(), pu };
31
+ }
32
+
33
+ // bot + agents A and B as participants
34
+ async function setup() {
35
+ const owner = await userService.signup(uniqueEmail('test-remove-owner'), PWD, 'Owner', 'User');
36
+ const project = await projectService.create('test-remove-participant', owner._id);
37
+ const chatbot = await faqService.create(project._id, owner._id, { name: 'rm-bot', type: 'tilebot', language: 'en', template: 'blank' });
38
+ const request = await requestService.create({
39
+ request_id: 'support-group-' + project._id + '-' + Date.now() + Math.floor(Math.random() * 1000),
40
+ id_project: project._id.toString(),
41
+ first_text: '/start',
42
+ participants: ['bot_' + chatbot._id.toString()],
43
+ channel: { name: 'webhook' },
44
+ preflight: false,
45
+ createdBy: 'system'
46
+ });
47
+ const a = await addAgent(project, owner);
48
+ const b = await addAgent(project, owner);
49
+ const botId = chatbot._id.toString();
50
+ await Request.updateOne({ request_id: request.request_id }, {
51
+ $set: { participants: ['bot_' + botId, a.id, b.id], participantsAgents: [a.id, b.id], participantsBots: [botId], hasBot: true, status: 200 }
52
+ }).exec();
53
+ return { project, request, request_id: request.request_id, id_project: project._id.toString(), botId, a, b };
54
+ }
55
+
56
+ async function captureLeaves(fn) {
57
+ const leaves = [];
58
+ const onLeave = (e) => leaves.push(e);
59
+ requestEvent.on('request.participants.leave', onLeave);
60
+ try {
61
+ await fn();
62
+ await new Promise((r) => setTimeout(r, 200));
63
+ } finally {
64
+ requestEvent.removeListener('request.participants.leave', onLeave);
65
+ }
66
+ return leaves;
67
+ }
68
+
69
+ describe('requestService.removeParticipantByRequestId (atomic)', function () {
70
+ this.timeout(30000);
71
+
72
+ it('removes both members when two removals run at the same time', async () => {
73
+ const ctx = await setup();
74
+ const leaves = await captureLeaves(() => Promise.all([
75
+ requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.a.id),
76
+ requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.b.id)
77
+ ]));
78
+ const r = await Request.findOne({ request_id: ctx.request_id }).lean().exec();
79
+ expect(r.participants).to.deep.equal(['bot_' + ctx.botId]);
80
+ expect(r.participantsAgents).to.deep.equal([]);
81
+ expect(r.status).to.equal(200);
82
+ expect(leaves.filter((l) => l.request.request_id === ctx.request_id).map((l) => l.member).sort())
83
+ .to.deep.equal([ctx.a.id, ctx.b.id].sort());
84
+ });
85
+
86
+ it('keeps a concurrent HITL write', async () => {
87
+ const ctx = await setup();
88
+ await Promise.all([
89
+ requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.a.id),
90
+ Request.updateOne({ request_id: ctx.request_id }, { $addToSet: { 'attributes.hitl_left': 'x' } }).exec()
91
+ ]);
92
+ const r = await Request.findOne({ request_id: ctx.request_id }).lean().exec();
93
+ expect(r.attributes.hitl_left).to.include('x');
94
+ expect(r.attributes.abandoned_by_project_users).to.have.property(ctx.a.pu._id.toString());
95
+ });
96
+
97
+ it('emits one leave event when the same member is removed twice at once', async () => {
98
+ const ctx = await setup();
99
+ const leaves = await captureLeaves(() => Promise.all([
100
+ requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.a.id),
101
+ requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.a.id)
102
+ ]));
103
+ expect(leaves.filter((l) => l.request.request_id === ctx.request_id)).to.have.length(1);
104
+ });
105
+
106
+ it('sets unassigned when the last participant leaves and never touches a closed request', async () => {
107
+ const ctx = await setup();
108
+ await requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.a.id);
109
+ await requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, ctx.b.id);
110
+ await requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, 'bot_' + ctx.botId);
111
+ let r = await Request.findOne({ request_id: ctx.request_id }).lean().exec();
112
+ expect(r.participants).to.deep.equal([]);
113
+ expect(r.hasBot).to.equal(false);
114
+ expect(r.participantsBots).to.deep.equal([]);
115
+ expect(r.status).to.equal(100);
116
+
117
+ const ctx2 = await setup();
118
+ await Request.updateOne({ request_id: ctx2.request_id }, { $set: { status: 1000 } }).exec();
119
+ await requestService.removeParticipantByRequestId(ctx2.request_id, ctx2.id_project, ctx2.a.id);
120
+ r = await Request.findOne({ request_id: ctx2.request_id }).lean().exec();
121
+ expect(r.status).to.equal(1000);
122
+ expect(r.participants).to.not.include(ctx2.a.id);
123
+ });
124
+
125
+ it('resolves without events for a member that is not a participant', async () => {
126
+ const ctx = await setup();
127
+ let result;
128
+ const leaves = await captureLeaves(async () => {
129
+ result = await requestService.removeParticipantByRequestId(ctx.request_id, ctx.id_project, 'nobody');
130
+ });
131
+ expect(result.request_id).to.equal(ctx.request_id);
132
+ expect(leaves.filter((l) => l.request.request_id === ctx.request_id)).to.have.length(0);
133
+ });
134
+
135
+ it('passes actor, source and trackLeave to the leave event', async () => {
136
+ const ctx = await setup();
137
+ const leaves = await captureLeaves(() => requestService.removeParticipantByRequestId(
138
+ ctx.request_id, ctx.id_project, ctx.a.id, { actor: { id: 'u1' }, source: 'test', trackLeave: true }));
139
+ const leave = leaves.find((l) => l.request.request_id === ctx.request_id);
140
+ expect(leave.actor).to.deep.equal({ id: 'u1' });
141
+ expect(leave.source).to.equal('test');
142
+ expect(leave.trackLeave).to.equal(true);
143
+ });
144
+ });
@@ -0,0 +1,186 @@
1
+ process.env.NODE_ENV = 'test';
2
+
3
+ var expect = require('chai').expect;
4
+ var requestVisibility = require('../utils/requestVisibility');
5
+
6
+ function projectUser(role, permissions) {
7
+ return {
8
+ role: role,
9
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
10
+ hasPermissionOrRole: function (permission, roles) {
11
+ if (permissions && permissions.indexOf(permission) !== -1) {
12
+ return true;
13
+ }
14
+ if (!roles) {
15
+ return false;
16
+ }
17
+ var list = Array.isArray(roles) ? roles : [roles];
18
+ return list.indexOf(role) !== -1;
19
+ }
20
+ };
21
+ }
22
+
23
+ describe('requestVisibility', function () {
24
+
25
+ it('stores only group member ids when the department has a group', function () {
26
+ var snapshot = {};
27
+ requestVisibility.applySnapshotVisibility(snapshot, {
28
+ department: { id_group: 'group-1' },
29
+ agents: [
30
+ { id_user: 'user-a', role: 'agent', settings: { email: true } },
31
+ { id_user: 'user-b', role: 'admin', presence: { status: 'online' } }
32
+ ]
33
+ }, new Date('2024-06-01T00:00:00.000Z'));
34
+
35
+ expect(snapshot.visibility).to.equal('agents');
36
+ expect(snapshot.agentIds).to.deep.equal(['user-a', 'user-b']);
37
+ expect(snapshot.visibilitySince).to.equal(undefined);
38
+ expect(snapshot.agents).to.equal(undefined);
39
+ });
40
+
41
+ it('stores every agent of the department groups, not only the group chosen for assignment', function () {
42
+ var snapshot = {};
43
+ return requestVisibility.applySnapshotVisibility(snapshot, {
44
+ department: {
45
+ groups: [{ group_id: 'g1', percentage: 70 }, { group_id: 'g2', percentage: 30 }]
46
+ },
47
+ agents: [{ id_user: 'user-a' }],
48
+ groups: [
49
+ { _id: 'g1', members: ['user-a', 'user-b'] },
50
+ { _id: 'g2', members: ['user-c', 'user-a'] }
51
+ ]
52
+ }, new Date('2024-06-01T00:00:00.000Z')).then(function () {
53
+ expect(snapshot.visibility).to.equal('agents');
54
+ expect(snapshot.agentIds.map(String)).to.deep.equal(['user-a', 'user-b', 'user-c']);
55
+ expect(snapshot.agents).to.equal(undefined);
56
+ });
57
+ });
58
+
59
+ it('stores a project flag instead of every agent when there is no group', function () {
60
+ var routedAt = new Date('2024-06-15T00:00:00.000Z');
61
+ var snapshot = { agents: [{ id_user: 'old' }] };
62
+ requestVisibility.applySnapshotVisibility(snapshot, {
63
+ department: { id_group: null },
64
+ agents: [{ id_user: 'user-a' }, { id_user: 'user-b' }]
65
+ }, routedAt);
66
+
67
+ expect(snapshot.visibility).to.equal('project');
68
+ expect(snapshot.visibilitySince).to.equal(routedAt);
69
+ expect(snapshot.agentIds).to.equal(undefined);
70
+ expect(snapshot.agents).to.equal(undefined);
71
+ });
72
+
73
+ it('keeps legacy, group ids and project cutoff in the same query', function () {
74
+ var joinedAt = new Date('2024-03-01T00:00:00.000Z');
75
+ var or = requestVisibility.visibilityOr('user-a', joinedAt);
76
+
77
+ expect(or).to.deep.equal([
78
+ { 'snapshot.agents.id_user': 'user-a' },
79
+ { 'snapshot.agentIds': 'user-a' },
80
+ { participants: 'user-a' },
81
+ {
82
+ 'snapshot.visibility': 'project',
83
+ 'snapshot.visibilitySince': { $gte: joinedAt }
84
+ }
85
+ ]);
86
+ });
87
+
88
+ it('lets an agent see a project conversation routed after they joined', function () {
89
+ var agent = projectUser('agent');
90
+ var request = {
91
+ participants: [],
92
+ snapshot: {
93
+ visibility: 'project',
94
+ visibilitySince: new Date('2024-06-01T00:00:00.000Z')
95
+ }
96
+ };
97
+
98
+ expect(requestVisibility.canSeeRequest(request, 'user-a', agent.createdAt, 'group')).to.equal(true);
99
+ });
100
+
101
+ it('hides a project conversation routed before the agent joined', function () {
102
+ var request = {
103
+ participants: [],
104
+ snapshot: {
105
+ visibility: 'project',
106
+ visibilitySince: new Date('2023-01-01T00:00:00.000Z')
107
+ }
108
+ };
109
+
110
+ expect(requestVisibility.canSeeRequest(
111
+ request,
112
+ 'user-a',
113
+ new Date('2024-01-01T00:00:00.000Z'),
114
+ 'group'
115
+ )).to.equal(false);
116
+ });
117
+
118
+ it('does not use agent status: a previously disabled agent still matches the project audience', function () {
119
+ var request = {
120
+ participants: [],
121
+ snapshot: {
122
+ visibility: 'project',
123
+ visibilitySince: new Date('2024-06-01T00:00:00.000Z')
124
+ }
125
+ };
126
+
127
+ expect(requestVisibility.canSeeRequest(
128
+ request,
129
+ 'user-a',
130
+ new Date('2024-01-01T00:00:00.000Z'),
131
+ 'group'
132
+ )).to.equal(true);
133
+ });
134
+
135
+ it('lets a group member see the request and hides everyone else except participants', function () {
136
+ var request = {
137
+ participants: ['user-c'],
138
+ snapshot: {
139
+ visibility: 'agents',
140
+ agentIds: ['user-a']
141
+ }
142
+ };
143
+
144
+ expect(requestVisibility.canSeeRequest(request, 'user-a', new Date(), 'group')).to.equal(true);
145
+ expect(requestVisibility.canSeeRequest(request, 'user-b', new Date(), 'group')).to.equal(false);
146
+ expect(requestVisibility.canSeeRequest(request, 'user-c', new Date(), 'group')).to.equal(true);
147
+ expect(requestVisibility.canSeeRequest(request, 'user-c', new Date(), 'mine')).to.equal(true);
148
+ expect(requestVisibility.canSeeRequest(request, 'user-a', new Date(), 'mine')).to.equal(false);
149
+ });
150
+
151
+ it('still matches a legacy embedded snapshot', function () {
152
+ var request = {
153
+ participants: [],
154
+ snapshot: {
155
+ agents: [{ id_user: 'user-a', settings: { email: true } }]
156
+ }
157
+ };
158
+
159
+ expect(requestVisibility.canSeeRequest(request, 'user-a', new Date(), 'group')).to.equal(true);
160
+ expect(requestVisibility.canSeeRequest(request, 'user-b', new Date(), 'group')).to.equal(false);
161
+ });
162
+
163
+ it('gives owner and admin every request', function () {
164
+ expect(requestVisibility.readScope(projectUser('owner'))).to.equal('all');
165
+ expect(requestVisibility.readScope(projectUser('admin'))).to.equal('all');
166
+ expect(requestVisibility.readScope(projectUser('agent'))).to.equal('group');
167
+ expect(requestVisibility.canSeeRequest({ participants: [] }, 'user-a', new Date(), 'all')).to.equal(true);
168
+ });
169
+
170
+ it('publishes group ids and an empty list for a project audience', function () {
171
+ expect(requestVisibility.agentsForClient({
172
+ visibility: 'agents',
173
+ agentIds: ['user-a']
174
+ })).to.deep.equal([{ id_user: 'user-a' }]);
175
+
176
+ expect(requestVisibility.agentsForClient({
177
+ visibility: 'project',
178
+ visibilitySince: new Date()
179
+ })).to.deep.equal([]);
180
+
181
+ expect(requestVisibility.agentsForClient({
182
+ agents: [{ id_user: 'user-legacy', role: 'agent' }]
183
+ })).to.deep.equal([{ id_user: 'user-legacy' }]);
184
+ });
185
+
186
+ });