@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.
- package/.circleci/config.yml +1 -1
- package/CHANGELOG.md +47 -0
- package/Dockerfile +3 -2
- package/Dockerfile-en +3 -2
- package/Dockerfile-jobs +3 -2
- package/Dockerfile-profiler +3 -2
- package/README.md +15 -0
- package/app.js +12 -1
- package/bin/quota-reset +68 -0
- package/bin/quota-restore +86 -0
- package/channels/chat21/chat21Handler.js +50 -34
- package/channels/chat21/chat21JoinTracker.js +43 -0
- package/config/database.js +5 -5
- package/config/native_mcp/native_mcp_servers.json +1 -0
- package/controllers/chatbot.controller.js +80 -27
- package/controllers/intents.controller.js +42 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-chat21-ionic.md +468 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-design-studio.md +1349 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md +1694 -0
- package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-tybot.md +789 -0
- package/docs/superpowers/plans/2026-09-29-hitl-known-limits-server.md +83 -0
- package/docs/superpowers/plans/2026-09-29-hitl-known-limits-tybot.md +76 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-chat21-ionic.md +97 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-design-studio.md +72 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-server.md +223 -0
- package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-tybot.md +121 -0
- package/docs/superpowers/plans/2026-09-29-hitl-pre-branch-ports.md +65 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-design-studio.md +88 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-server.md +103 -0
- package/docs/superpowers/plans/2026-09-30-flow-start-points-tybot.md +43 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-design-studio.md +80 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-runtime.md +39 -0
- package/docs/superpowers/plans/2026-10-01-scheduled-start-point-server.md +106 -0
- package/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md +715 -0
- package/docs/superpowers/specs/2026-09-30-flow-start-points-design.md +156 -0
- package/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md +303 -0
- package/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md +191 -0
- package/event/botEvent.js +12 -1
- package/event/emailEvent.js +3 -0
- package/event/messageEvent.js +44 -0
- package/jobs.js +10 -0
- package/jobsManager.js +19 -0
- package/middleware/errorHandler.js +6 -2
- package/models/analyticResult.js +1 -1
- package/models/channelConstants.js +3 -2
- package/models/dataTable.js +16 -0
- package/models/location.js +6 -12
- package/models/quotaUsage.js +71 -0
- package/models/request.js +71 -61
- package/models/requestSnapshot.js +12 -0
- package/models/routerLogger.js +1 -1
- package/models/webhook.js +44 -0
- package/package.json +9 -7
- package/pubmodules/emailNotification/requestNotification.js +14 -22
- package/pubmodules/events/test/eventRoute.js +7 -6
- package/pubmodules/rules/conciergeBot.js +9 -4
- package/routes/auth.js +1 -12
- package/routes/campaigns.js +0 -13
- package/routes/dataTable.js +23 -3
- package/routes/faq_kb.js +12 -1
- package/routes/messagesRoot.js +0 -1
- package/routes/quotes.js +38 -1
- package/routes/request.js +81 -5
- package/routes/users.js +0 -1
- package/routes/webhook.js +160 -8
- package/routes/webhooks.js +276 -6
- package/routes/widgetLoader.js +6 -3
- package/services/QuoteManager.js +77 -16
- package/services/aiService.js +1 -1
- package/services/chatbotService.js +55 -1
- package/services/dataTableService.js +436 -42
- package/services/departmentService.js +60 -43
- package/services/dolphinSchedulerClient.js +116 -0
- package/services/emailService.js +6 -1
- package/services/hitlParticipantListener.js +260 -0
- package/services/participantInviteService.js +302 -0
- package/services/participantRemoveService.js +79 -0
- package/services/quotaSnapshotService.js +1167 -0
- package/services/requestService.js +102 -144
- package/services/scheduledStart/dolphinBackend.js +246 -0
- package/services/scheduledStart/schedulerBackend.js +101 -0
- package/services/scheduledStart/schedulerServiceClient.js +41 -0
- package/services/scheduledStartPublishListener.js +186 -0
- package/services/scheduledStartRules.js +173 -0
- package/services/scheduledStartService.js +130 -0
- package/services/startPointCleanupListener.js +30 -0
- package/services/startPointService.js +158 -0
- package/services/testWsService.js +1 -4
- package/services/updateRequestSnapshotQueued.js +8 -9
- package/services/webhookConversationService.js +185 -0
- package/services/webhookSettingsValidator.js +61 -0
- package/template/email/checkpointReachedEmail.html +5 -0
- package/test/agentPromptsRoute.test.js +3 -2
- package/test/agentTokensQuota.js +237 -0
- package/test/botEventHitlFallback.js +19 -0
- package/test/chat21HandlerJoinWiring.js +59 -0
- package/test/dataTablesRoute.test.js +649 -2
- package/test/dateUtils.test.js +0 -3
- package/test/departmentService.js +8 -12
- package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
- package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
- package/test/faqRoute.js +6 -1
- package/test/faqkbRoute.js +14 -10
- package/test/faqkbV3Route.js +1 -1
- package/test/filepRoute.js +4 -50
- package/test/hitlParticipantListener.js +446 -0
- package/test/hitlQueueWiring.js +191 -0
- package/test/hitlWaitingReset.js +124 -0
- package/test/inviteParticipantsRoute.js +492 -0
- package/test/kbRoute.js +1 -1
- package/test/messageRoute.js +33 -21
- package/test/nativemcp.test.js +7 -1
- package/test/openaiRoute.js +2 -8
- package/test/publishFailLoud.test.js +414 -0
- package/test/quotaSnapshots.js +1044 -0
- package/test/removeParticipantsRoute.js +186 -0
- package/test/requestService.js +24 -16
- package/test/requestServiceRemoveParticipant.js +144 -0
- package/test/requestVisibility.test.js +186 -0
- package/test/scheduledStartFacade.js +184 -0
- package/test/scheduledStartHandover.js +95 -0
- package/test/scheduledStartPublish.js +320 -0
- package/test/scheduledStartRoute.js +163 -0
- package/test/scheduledStartRules.js +177 -0
- package/test/scheduledStartRun.js +299 -0
- package/test/scheduledStartSchedulerBackend.js +116 -0
- package/test/scheduledStartService.js +290 -0
- package/test/startPointsCleanup.js +69 -0
- package/test/startPointsRegression.js +169 -0
- package/test/startPointsRoute.js +158 -0
- package/test/webhookConversationRoute.js +347 -0
- package/test/webhookConversationService.js +261 -0
- package/test/webhookConversationTestUtils.js +55 -0
- package/utils/aiUtils.js +95 -1
- package/utils/dataTableUtils.js +99 -9
- package/utils/intentFieldNames.js +192 -0
- package/utils/quotaCliUtil.js +43 -0
- package/utils/requestVisibility.js +355 -0
- package/websocket/webSocketServer.js +36 -31
- /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Field names MongoDB cannot store in a block (intent): a name containing '.' or starting with '$'.
|
|
3
|
+
*
|
|
4
|
+
* An update stores such a name without complaint (block saves keep doing so), but every later
|
|
5
|
+
* insert of the same block (publish, fork, import, restore) is refused by the driver. These helpers
|
|
6
|
+
* find the name before such an insert and say, in plain words, which block and which field are wrong.
|
|
7
|
+
*/
|
|
8
|
+
const AppError = require("./AppError");
|
|
9
|
+
|
|
10
|
+
// The block fields that hold free-form objects written by the editors.
|
|
11
|
+
const CHECKED_FIELDS = ["actions", "attributes", "reply", "form", "question", "answer"];
|
|
12
|
+
|
|
13
|
+
function isPlainObject(value) {
|
|
14
|
+
if (value === null || typeof value !== "object") {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
const proto = Object.getPrototypeOf(value);
|
|
18
|
+
return proto === Object.prototype || proto === null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function badName(key) {
|
|
22
|
+
if (key.includes(".")) {
|
|
23
|
+
return "contains '.'";
|
|
24
|
+
}
|
|
25
|
+
if (key.startsWith("$")) {
|
|
26
|
+
return "starts with '$'";
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* First invalid field name inside `value`, depth first: `{ key, problem, path }` where `path`
|
|
33
|
+
* is the list of keys/indexes from `value` to the object holding the name. `null` when clean.
|
|
34
|
+
*/
|
|
35
|
+
function findInvalidFieldName(value, path = [], seen = new Set()) {
|
|
36
|
+
if (Array.isArray(value)) {
|
|
37
|
+
if (seen.has(value)) { return null; }
|
|
38
|
+
seen.add(value);
|
|
39
|
+
for (let i = 0; i < value.length; i++) {
|
|
40
|
+
const found = findInvalidFieldName(value[i], path.concat(i), seen);
|
|
41
|
+
if (found) { return found; }
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (!isPlainObject(value)) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
if (seen.has(value)) { return null; }
|
|
49
|
+
seen.add(value);
|
|
50
|
+
for (const key of Object.keys(value)) {
|
|
51
|
+
const problem = badName(key);
|
|
52
|
+
if (problem) {
|
|
53
|
+
return { key, problem, path };
|
|
54
|
+
}
|
|
55
|
+
const found = findInvalidFieldName(value[key], path.concat(key), seen);
|
|
56
|
+
if (found) { return found; }
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** "in action 3 (setattribute-v2)", "in the block attributes", ... */
|
|
62
|
+
function describeLocation(fields, path) {
|
|
63
|
+
if (!path.length) {
|
|
64
|
+
return "";
|
|
65
|
+
}
|
|
66
|
+
const [field, index] = path;
|
|
67
|
+
if (field === "actions" && typeof index === "number") {
|
|
68
|
+
const action = Array.isArray(fields.actions) ? fields.actions[index] : null;
|
|
69
|
+
const type = action && typeof action._tdActionType === "string" ? " (" + action._tdActionType + ")" : "";
|
|
70
|
+
return " in action " + (index + 1) + type;
|
|
71
|
+
}
|
|
72
|
+
return " in the block " + field;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Checks the block fields of `fields` (a block, or the fields an update writes).
|
|
77
|
+
* Returns `{ key, problem, path, reason }` for the first invalid name, or `null`.
|
|
78
|
+
*/
|
|
79
|
+
function checkIntentFields(fields) {
|
|
80
|
+
if (!fields || typeof fields !== "object") {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
for (const field of CHECKED_FIELDS) {
|
|
84
|
+
if (fields[field] === undefined || fields[field] === null) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const found = findInvalidFieldName(fields[field], [field]);
|
|
88
|
+
if (found) {
|
|
89
|
+
found.reason = 'field name "' + found.key + '"' + describeLocation(fields, found.path) +
|
|
90
|
+
" " + found.problem + ", which is not allowed";
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function blockLabel(name, intent_id) {
|
|
98
|
+
if (name) {
|
|
99
|
+
return '"' + name + '"';
|
|
100
|
+
}
|
|
101
|
+
if (intent_id) {
|
|
102
|
+
return "with id " + intent_id;
|
|
103
|
+
}
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Every block of `intents` with an invalid name: `[{ intent_id, intent_display_name, field, reason }]`. */
|
|
108
|
+
function collectIntentErrors(intents) {
|
|
109
|
+
const errors = [];
|
|
110
|
+
(intents || []).forEach((intent) => {
|
|
111
|
+
const found = checkIntentFields(intent);
|
|
112
|
+
if (found) {
|
|
113
|
+
errors.push({
|
|
114
|
+
intent_id: intent.intent_id,
|
|
115
|
+
intent_display_name: intent.intent_display_name,
|
|
116
|
+
field: found.key,
|
|
117
|
+
reason: found.reason
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
return errors;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The agent's own attributes (faq_kb.attributes): `[{ agent, field, reason }]` or `[]`. */
|
|
125
|
+
function collectAgentErrors(agentName, attributes) {
|
|
126
|
+
const found = findInvalidFieldName(attributes, ["attributes"]);
|
|
127
|
+
if (!found) {
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
return [{
|
|
131
|
+
agent: agentName,
|
|
132
|
+
field: found.key,
|
|
133
|
+
reason: 'field name "' + found.key + '" in the agent attributes ' + found.problem + ", which is not allowed"
|
|
134
|
+
}];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function itemLabel(e) {
|
|
138
|
+
if (e.agent !== undefined) {
|
|
139
|
+
return "the agent settings" + (e.agent ? ' of "' + e.agent + '"' : "");
|
|
140
|
+
}
|
|
141
|
+
return blockLabel(e.intent_display_name, e.intent_id) || "a block";
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** "1 block could not be published — "X": field name ..." */
|
|
145
|
+
function summarizeErrors(errors, verb = "saved") {
|
|
146
|
+
const blocks = errors.filter((e) => e.agent === undefined).length;
|
|
147
|
+
const subjects = [];
|
|
148
|
+
if (blocks > 0) {
|
|
149
|
+
subjects.push(blocks + (blocks === 1 ? " block" : " blocks"));
|
|
150
|
+
}
|
|
151
|
+
if (blocks < errors.length) {
|
|
152
|
+
subjects.push("the agent settings");
|
|
153
|
+
}
|
|
154
|
+
const details = errors.map((e) => itemLabel(e) + ": " + e.reason).join("; ");
|
|
155
|
+
return subjects.join(" and ") + " could not be " + verb + " — " + details;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function whatToFix(errors) {
|
|
159
|
+
const blocks = errors.filter((e) => e.agent === undefined).length;
|
|
160
|
+
if (blocks === errors.length) {
|
|
161
|
+
return blocks === 1 ? "the block" : "the blocks";
|
|
162
|
+
}
|
|
163
|
+
return blocks === 0 ? "the agent settings" : "them";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Refused import, fork or restore: nothing was written. */
|
|
167
|
+
function invalidFlowError(errors, status = 422) {
|
|
168
|
+
const err = new AppError(status, "The flow could not be imported: " + summarizeErrors(errors, "stored") +
|
|
169
|
+
". Fix " + whatToFix(errors) + " and try again.");
|
|
170
|
+
err.code = "INVALID_FIELD_NAME";
|
|
171
|
+
err.errors = errors;
|
|
172
|
+
return err;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Refused publish: nothing was written. */
|
|
176
|
+
function publishError(errors, status = 422) {
|
|
177
|
+
const err = new AppError(status, "The flow was not published: " + summarizeErrors(errors, "published") +
|
|
178
|
+
". Fix " + whatToFix(errors) + " and publish again.");
|
|
179
|
+
err.code = "PUBLISH_BLOCKS_INVALID";
|
|
180
|
+
err.errors = errors;
|
|
181
|
+
return err;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = {
|
|
185
|
+
findInvalidFieldName,
|
|
186
|
+
checkIntentFields,
|
|
187
|
+
collectIntentErrors,
|
|
188
|
+
collectAgentErrors,
|
|
189
|
+
invalidFlowError,
|
|
190
|
+
publishError,
|
|
191
|
+
summarizeErrors
|
|
192
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bootstrap shared by bin/quota-restore and bin/quota-reset: loads the env like app.js and connects
|
|
3
|
+
* to the server's mongo (DATABASE_URI / MONGODB_URI, test db when NODE_ENV=test) and Redis (CACHE_REDIS_*).
|
|
4
|
+
*/
|
|
5
|
+
let dotenvPath = undefined;
|
|
6
|
+
if (process.env.DOTENV_PATH) {
|
|
7
|
+
dotenvPath = process.env.DOTENV_PATH;
|
|
8
|
+
}
|
|
9
|
+
if (process.env.LOAD_DOTENV_SUBFOLDER) {
|
|
10
|
+
dotenvPath = __dirname + '/../confenv/.env';
|
|
11
|
+
}
|
|
12
|
+
require('dotenv').config({ path: dotenvPath });
|
|
13
|
+
|
|
14
|
+
const mongoose = require('mongoose');
|
|
15
|
+
const config = require('../config/database');
|
|
16
|
+
const { TdCache } = require('./TdCache');
|
|
17
|
+
|
|
18
|
+
async function connect() {
|
|
19
|
+
let databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI || config.database;
|
|
20
|
+
if (process.env.NODE_ENV == 'test') {
|
|
21
|
+
databaseUri = config.databasetest;
|
|
22
|
+
}
|
|
23
|
+
mongoose.set('useCreateIndex', true);
|
|
24
|
+
mongoose.set('useFindAndModify', false);
|
|
25
|
+
await mongoose.connect(databaseUri, { useNewUrlParser: true, useUnifiedTopology: process.env.MONGOOSE_UNIFIED_TOPOLOGY === 'true' });
|
|
26
|
+
|
|
27
|
+
const tdCache = new TdCache({
|
|
28
|
+
host: process.env.CACHE_REDIS_HOST,
|
|
29
|
+
port: process.env.CACHE_REDIS_PORT,
|
|
30
|
+
password: process.env.CACHE_REDIS_PASSWORD
|
|
31
|
+
});
|
|
32
|
+
await tdCache.connect();
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
tdCache: tdCache,
|
|
36
|
+
close: async () => {
|
|
37
|
+
tdCache.getClient().quit();
|
|
38
|
+
await mongoose.disconnect();
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { connect };
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const Project_user = require('../models/project_user');
|
|
4
|
+
const RoleConstants = require('../models/roleConstants');
|
|
5
|
+
const Group = require('../models/group');
|
|
6
|
+
|
|
7
|
+
const VISIBILITY_PROJECT = 'project';
|
|
8
|
+
const VISIBILITY_AGENTS = 'agents';
|
|
9
|
+
|
|
10
|
+
function sameId(a, b) {
|
|
11
|
+
if (a == null || b == null) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
const left = a._id || a.id || a;
|
|
15
|
+
const right = b._id || b.id || b;
|
|
16
|
+
return String(left) === String(right);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function userIdOf(agent) {
|
|
20
|
+
if (!agent) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
if (agent.id_user) {
|
|
24
|
+
return agent.id_user._id || agent.id_user.id || agent.id_user;
|
|
25
|
+
}
|
|
26
|
+
return agent._id || agent.id || agent;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Group ids configured on a multi-group department: department.groups, or the
|
|
31
|
+
* same list stored as JSON in description.
|
|
32
|
+
*/
|
|
33
|
+
function departmentGroupIds(department) {
|
|
34
|
+
if (!department) {
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
const ids = [];
|
|
38
|
+
const push = function (value) {
|
|
39
|
+
if (value == null || value === '') {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const id = String(value._id || value.id || value);
|
|
43
|
+
if (ids.indexOf(id) === -1) {
|
|
44
|
+
ids.push(id);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
if (Array.isArray(department.groups)) {
|
|
49
|
+
department.groups.forEach(entry => push(entry && (entry.group_id || entry.id)));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (ids.length === 0 && typeof department.description === 'string' && department.description.indexOf('[') !== -1) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(department.description);
|
|
55
|
+
if (Array.isArray(parsed)) {
|
|
56
|
+
parsed.forEach(entry => push(entry && (entry.group_id || entry.id)));
|
|
57
|
+
}
|
|
58
|
+
} catch (err) {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return ids;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function departmentUsesMultipleGroups(department) {
|
|
67
|
+
return departmentGroupIds(department).length > 0;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function unionMemberIds(groups) {
|
|
71
|
+
const seen = new Set();
|
|
72
|
+
const ids = [];
|
|
73
|
+
(groups || []).forEach(group => {
|
|
74
|
+
(group && group.members || []).forEach(member => {
|
|
75
|
+
const raw = member && (member._id || member.id) ? (member._id || member.id) : member;
|
|
76
|
+
if (raw == null || raw === '') {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const key = String(raw);
|
|
80
|
+
if (!seen.has(key)) {
|
|
81
|
+
seen.add(key);
|
|
82
|
+
ids.push(raw);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
return ids;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Agents who belong to any group configured on the department. The routing
|
|
91
|
+
* percentage picks who is assigned; visibility stays the whole department.
|
|
92
|
+
*/
|
|
93
|
+
async function agentIdsForDepartmentGroups(operatorsResult) {
|
|
94
|
+
const department = operatorsResult && operatorsResult.department;
|
|
95
|
+
const configuredIds = departmentGroupIds(department);
|
|
96
|
+
if (configuredIds.length === 0) {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const embedded = Array.isArray(operatorsResult.groups) ? operatorsResult.groups : [];
|
|
101
|
+
const configured = new Set(configuredIds);
|
|
102
|
+
const embeddedMatches = embedded.filter(group => {
|
|
103
|
+
const id = group && (group._id || group.id);
|
|
104
|
+
return id != null && configured.has(String(id)) && Array.isArray(group.members);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
let groups = embeddedMatches;
|
|
108
|
+
if (groups.length === 0) {
|
|
109
|
+
groups = await Group.find({
|
|
110
|
+
_id: { $in: configuredIds },
|
|
111
|
+
$or: [{ enabled: true }, { enabled: { $exists: false } }]
|
|
112
|
+
}).select('members').lean();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const memberIds = unionMemberIds(groups);
|
|
116
|
+
const idProject = (department && department.id_project) || (operatorsResult && operatorsResult.id_project);
|
|
117
|
+
if (!idProject || memberIds.length === 0) {
|
|
118
|
+
return memberIds;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const projectUsers = await Project_user.find({
|
|
122
|
+
id_project: idProject,
|
|
123
|
+
id_user: { $in: memberIds },
|
|
124
|
+
roleType: RoleConstants.TYPE_AGENTS,
|
|
125
|
+
status: 'active'
|
|
126
|
+
}).select('id_user').lean();
|
|
127
|
+
|
|
128
|
+
return projectUsers.map(projectUser => projectUser.id_user).filter(Boolean);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* A single id_group, or every group configured on the department, is visible
|
|
133
|
+
* only to those agents. Otherwise the audience is the whole project at routing time.
|
|
134
|
+
*/
|
|
135
|
+
function isGroupAudience(operatorsResult) {
|
|
136
|
+
const department = operatorsResult && operatorsResult.department;
|
|
137
|
+
if (!department) {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
if (departmentUsesMultipleGroups(department)) {
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
return department.id_group != null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Mutates snapshot. New requests store ids (or a project flag), never the
|
|
148
|
+
* embedded project_user documents. snapshot.agents is cleared so a reroute
|
|
149
|
+
* drops the legacy array.
|
|
150
|
+
*/
|
|
151
|
+
async function applySnapshotVisibility(snapshot, operatorsResult, at) {
|
|
152
|
+
const target = snapshot || {};
|
|
153
|
+
const when = at || new Date();
|
|
154
|
+
const agents = (operatorsResult && operatorsResult.agents) || [];
|
|
155
|
+
|
|
156
|
+
if (isGroupAudience(operatorsResult)) {
|
|
157
|
+
const department = operatorsResult && operatorsResult.department;
|
|
158
|
+
target.visibility = VISIBILITY_AGENTS;
|
|
159
|
+
target.agentIds = departmentUsesMultipleGroups(department)
|
|
160
|
+
? await agentIdsForDepartmentGroups(operatorsResult)
|
|
161
|
+
: agents.map(userIdOf).filter(Boolean);
|
|
162
|
+
target.visibilitySince = undefined;
|
|
163
|
+
} else {
|
|
164
|
+
target.visibility = VISIBILITY_PROJECT;
|
|
165
|
+
target.visibilitySince = when;
|
|
166
|
+
target.agentIds = undefined;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
target.agents = undefined;
|
|
170
|
+
return target;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function visibilityUpdate(snapshot) {
|
|
174
|
+
const $set = {};
|
|
175
|
+
const $unset = { 'snapshot.agents': 1 };
|
|
176
|
+
|
|
177
|
+
if (!snapshot || !snapshot.visibility) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
$set['snapshot.visibility'] = snapshot.visibility;
|
|
182
|
+
|
|
183
|
+
if (snapshot.visibility === VISIBILITY_AGENTS) {
|
|
184
|
+
$set['snapshot.agentIds'] = snapshot.agentIds || [];
|
|
185
|
+
$unset['snapshot.visibilitySince'] = 1;
|
|
186
|
+
} else if (snapshot.visibility === VISIBILITY_PROJECT) {
|
|
187
|
+
$set['snapshot.visibilitySince'] = snapshot.visibilitySince || new Date();
|
|
188
|
+
$unset['snapshot.agentIds'] = 1;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { $set, $unset };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* $or clauses for an agent with request_read_group.
|
|
196
|
+
* Legacy docs match snapshot.agents.id_user. New group docs match agentIds.
|
|
197
|
+
* New project-wide docs match visibilitySince >= the agent's join date.
|
|
198
|
+
*/
|
|
199
|
+
function visibilityOr(userId, projectUserCreatedAt) {
|
|
200
|
+
const or = [
|
|
201
|
+
{ 'snapshot.agents.id_user': userId },
|
|
202
|
+
{ 'snapshot.agentIds': userId },
|
|
203
|
+
{ participants: userId }
|
|
204
|
+
];
|
|
205
|
+
|
|
206
|
+
if (projectUserCreatedAt) {
|
|
207
|
+
or.push({
|
|
208
|
+
'snapshot.visibility': VISIBILITY_PROJECT,
|
|
209
|
+
'snapshot.visibilitySince': { $gte: projectUserCreatedAt }
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return or;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function readScope(projectuser) {
|
|
217
|
+
if (!projectuser || typeof projectuser.hasPermissionOrRole !== 'function') {
|
|
218
|
+
return 'mine';
|
|
219
|
+
}
|
|
220
|
+
if (projectuser.hasPermissionOrRole('request_read_all', ['owner', 'admin'])) {
|
|
221
|
+
return 'all';
|
|
222
|
+
}
|
|
223
|
+
if (projectuser.hasPermissionOrRole('request_read_group', ['agent'])) {
|
|
224
|
+
return 'group';
|
|
225
|
+
}
|
|
226
|
+
return 'mine';
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function bypassesVisibility(user) {
|
|
230
|
+
if (!user) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
const Subscription = require('../models/subscription');
|
|
234
|
+
const Faq_kb = require('../models/faq_kb');
|
|
235
|
+
if (user instanceof Subscription || user instanceof Faq_kb) {
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
const adminEmail = process.env.ADMIN_EMAIL || 'admin@tiledesk.com';
|
|
239
|
+
return !!(user.email && user.email === adminEmail);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function canSeeRequest(request, userId, projectUserCreatedAt, scope) {
|
|
243
|
+
if (scope === 'all') {
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
if (!request) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const participants = request.participants || [];
|
|
251
|
+
if (participants.some(participant => sameId(participant, userId))) {
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
if (scope !== 'group') {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const snapshot = request.snapshot || {};
|
|
259
|
+
if (Array.isArray(snapshot.agentIds) && snapshot.agentIds.some(id => sameId(id, userId))) {
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
if (Array.isArray(snapshot.agents) && snapshot.agents.some(agent => sameId(userIdOf(agent), userId))) {
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
if (snapshot.visibility === VISIBILITY_PROJECT && snapshot.visibilitySince && projectUserCreatedAt) {
|
|
266
|
+
return new Date(snapshot.visibilitySince).getTime() >= new Date(projectUserCreatedAt).getTime();
|
|
267
|
+
}
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function hasAudience(snapshot) {
|
|
272
|
+
if (!snapshot) {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
if (snapshot.visibility === VISIBILITY_PROJECT || snapshot.visibility === VISIBILITY_AGENTS) {
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
return Array.isArray(snapshot.agents) && snapshot.agents.length > 0;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Project users to notify. New snapshots are ids or a project flag, so the
|
|
283
|
+
* current project_user (settings included) is loaded at send time. Legacy
|
|
284
|
+
* snapshots still return the embedded documents.
|
|
285
|
+
*/
|
|
286
|
+
async function loadNotifiableProjectUsers(snapshot, id_project) {
|
|
287
|
+
if (!snapshot) {
|
|
288
|
+
return [];
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (snapshot.visibility === VISIBILITY_AGENTS) {
|
|
292
|
+
const agentIds = snapshot.agentIds || [];
|
|
293
|
+
if (agentIds.length === 0) {
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
return Project_user.find({
|
|
297
|
+
id_project: id_project,
|
|
298
|
+
id_user: { $in: agentIds },
|
|
299
|
+
roleType: RoleConstants.TYPE_AGENTS
|
|
300
|
+
}).exec();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (snapshot.visibility === VISIBILITY_PROJECT && snapshot.visibilitySince) {
|
|
304
|
+
return Project_user.find({
|
|
305
|
+
id_project: id_project,
|
|
306
|
+
roleType: RoleConstants.TYPE_AGENTS,
|
|
307
|
+
createdAt: { $lte: snapshot.visibilitySince }
|
|
308
|
+
}).exec();
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (Array.isArray(snapshot.agents) && snapshot.agents.length > 0) {
|
|
312
|
+
return snapshot.agents;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return [];
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Client payload keeps { id_user } for group and legacy snapshots.
|
|
320
|
+
* Project-wide audience has no agent list.
|
|
321
|
+
*/
|
|
322
|
+
function agentsForClient(snapshot) {
|
|
323
|
+
if (!snapshot) {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
if (snapshot.visibility === VISIBILITY_PROJECT) {
|
|
327
|
+
return [];
|
|
328
|
+
}
|
|
329
|
+
if (snapshot.visibility === VISIBILITY_AGENTS && Array.isArray(snapshot.agentIds)) {
|
|
330
|
+
return snapshot.agentIds.map(id => ({ id_user: id }));
|
|
331
|
+
}
|
|
332
|
+
if (Array.isArray(snapshot.agents) && snapshot.agents.length > 0) {
|
|
333
|
+
return snapshot.agents.map(agent => ({ id_user: userIdOf(agent) }));
|
|
334
|
+
}
|
|
335
|
+
return null;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
module.exports = {
|
|
339
|
+
VISIBILITY_PROJECT,
|
|
340
|
+
VISIBILITY_AGENTS,
|
|
341
|
+
isGroupAudience,
|
|
342
|
+
departmentGroupIds,
|
|
343
|
+
departmentUsesMultipleGroups,
|
|
344
|
+
unionMemberIds,
|
|
345
|
+
agentIdsForDepartmentGroups,
|
|
346
|
+
applySnapshotVisibility,
|
|
347
|
+
visibilityUpdate,
|
|
348
|
+
visibilityOr,
|
|
349
|
+
readScope,
|
|
350
|
+
bypassesVisibility,
|
|
351
|
+
canSeeRequest,
|
|
352
|
+
hasAudience,
|
|
353
|
+
loadNotifiableProjectUsers,
|
|
354
|
+
agentsForClient
|
|
355
|
+
};
|