@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
package/models/request.js CHANGED
@@ -52,8 +52,8 @@ var RequestSchema = new Schema({
52
52
  // TODO attiva solo condizionalmente per performance
53
53
  ticket_id: {
54
54
  type: Number,
55
- // required: true,
56
- index: true
55
+ // required: true
56
+ // index: true //Deprecated indexes
57
57
  },
58
58
  // The user who is asking for support through a ticket is the requester. For most businesses that use Tiledesk Support, the requester is a customer, but requesters can also be agents in your Tiledesk Support instance. requester: {
59
59
  requester: {
@@ -108,14 +108,14 @@ var RequestSchema = new Schema({
108
108
 
109
109
  preflight: {
110
110
  type: Boolean,
111
- default: false,
112
- index:true
111
+ default: false
112
+ // index: true //Deprecated indexes
113
113
  },
114
114
 
115
115
  hasBot: {
116
116
  type: Boolean,
117
- default: false,
118
- index:true
117
+ default: false
118
+ // index: true //Deprecated indexes
119
119
  },
120
120
 
121
121
  // The admin the conversation is currently assigned to.
@@ -127,14 +127,14 @@ var RequestSchema = new Schema({
127
127
 
128
128
  participants: { //TODO trasformare in objectid di tipo project_user
129
129
  type: Array,
130
- required: false,
131
- index: true,
130
+ required: false
131
+ // index: true //Deprecated indexes
132
132
  },
133
133
 
134
134
  priority: {
135
135
  type: String,
136
- index: true,
137
136
  default: "medium" //translate on client side
137
+ // index: true //Deprecated indexes
138
138
  },
139
139
 
140
140
  followers: [{
@@ -153,8 +153,8 @@ var RequestSchema = new Schema({
153
153
  },
154
154
  department: {
155
155
  type: Schema.Types.ObjectId,
156
- ref: 'department',
157
- index: true
156
+ ref: 'department'
157
+ // index: true //Deprecated indexes
158
158
  // required: true
159
159
  },
160
160
 
@@ -202,9 +202,15 @@ var RequestSchema = new Schema({
202
202
  type: Number
203
203
  },
204
204
 
205
- tags: [TagSchema],
205
+ tags: {
206
+ type: [TagSchema],
207
+ excludeIndexes: true //Deprecated indexes
208
+ },
206
209
 
207
- notes: [NoteSchema],
210
+ notes: {
211
+ type: [NoteSchema],
212
+ excludeIndexes: true //Deprecated indexes
213
+ },
208
214
 
209
215
  rating: {
210
216
  type: Number,
@@ -270,13 +276,13 @@ var RequestSchema = new Schema({
270
276
  },
271
277
  location: LocationSchema,
272
278
  auto_close: {
273
- type: Number,
274
- index: true
279
+ type: Number
280
+ // index: true //Deprecated indexes
275
281
  },
276
282
  id_project: {
277
283
  type: String,
278
- required: true,
279
- index: true
284
+ required: true
285
+ // index: true //Deprecated indexes
280
286
  },
281
287
  smartAssignment: {
282
288
  type: Boolean,
@@ -289,13 +295,13 @@ var RequestSchema = new Schema({
289
295
  // winston.info("smartAssignment default return true");
290
296
  return true;
291
297
  }
292
- },
293
- index: true
298
+ }
299
+ // index: true //Deprecated indexes
294
300
  },
295
301
  workingStatus: { //new, pending, open
296
302
  type: String,
297
- required: false,
298
- index: true
303
+ required: false
304
+ // index: true //Deprecated indexes
299
305
  },
300
306
  createdBy: {
301
307
  type: String,
@@ -303,8 +309,8 @@ var RequestSchema = new Schema({
303
309
  },
304
310
  draft: {
305
311
  type: Boolean,
306
- required: false,
307
- index: true
312
+ required: false
313
+ // index: true //Deprecated indexes
308
314
  },
309
315
  contact: ContactSchema,
310
316
  }, {
@@ -446,13 +452,12 @@ RequestSchema.method("getBotId", function () {
446
452
 
447
453
  // https://docs.mongodb.com/manual/indexes/
448
454
  // For a single-field index and sort operations, the sort order (i.e. ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction.
449
- RequestSchema.index({ createdAt: -1 }); // schema level
450
- RequestSchema.index({ updatedAt: -1 }); // schema level
451
- RequestSchema.index({ id_project: 1 }); // schema level
452
455
  // https://stackoverflow.com/questions/27179664/error-when-using-a-text-index-on-mongodb/27180032
456
+ // { request_id, id_project } is the lookup used by messages, websocket and updates.
457
+ // The planner picks this over the unique request_id index when both fields are in the query.
453
458
  RequestSchema.index({ id_project: 1, request_id: 1 }
454
459
  // , { unique: true }
455
- ); // query for websocket
460
+ );
456
461
 
457
462
  // https://docs.mongodb.com/manual/core/index-text/
458
463
  // https://docs.mongodb.com/manual/tutorial/specify-language-for-text-index/
@@ -464,55 +469,60 @@ RequestSchema.index({ id_project: 1, request_id: 1 }
464
469
  RequestSchema.index({id_project: 1, transcript: 'text', rating_message: 'text', subject: 'text', "tags.tag": 'text', "notes.text": 'text', "snapshot.lead.email": 'text', "snapshot.lead.fullname": 'text' },
465
470
  {"name":"request_fulltext","default_language": defaultFullTextLanguage,"language_override": "dummy"}); // schema level
466
471
 
467
- // let query = {id_project: operatorSelectedEvent.id_project, participants: { $exists: true, $ne: [] }};
468
- RequestSchema.index({ id_project: 1, participants: 1});
469
-
470
- // https://docs.mongodb.com/manual/core/index-compound/ The order of the fields listed in a compound index is important. The index will contain references to documents sorted first by the values of the item field and, within each value of the item field, sorted by values of the stock field. See Sort Order for more information
471
- RequestSchema.index({ id_project: 1, status: 1, updatedAt: -1 }); // query for websocket
472
- RequestSchema.index({ id_project: 1, status: 1, preflight:1, updatedAt: -1 }); // query for websocket
473
- RequestSchema.index({ id_project: 1, preflight:1, updatedAt: -1 }); // used query ws (topic.endsWith('/requests'))
474
-
475
- RequestSchema.index({ hasBot: 1, createdAt: 1 }); // suggested by atlas
476
-
477
-
478
- // suggested by atlas
479
- RequestSchema.index({ lead: 1, id_project: 1, participants: 1, preflight: 1, createdAt: -1 });
480
472
  // suggested by atlas
481
473
  RequestSchema.index({ lead: 1, id_project: 1, preflight: 1, createdAt: -1 });
482
474
 
483
- // suggested by atlas
484
- RequestSchema.index({ lead: 1, "snapshot.agents.id_user": 1, id_project: 1, preflight: 1, createdAt: -1 });
485
-
475
+ // Same lead query for the new visibility shape. One key per request, not per agent.
476
+ RequestSchema.index({ lead: 1, "snapshot.agentIds": 1, id_project: 1, preflight: 1, createdAt: -1 });
477
+ RequestSchema.index({ lead: 1, "snapshot.visibility": 1, "snapshot.visibilitySince": 1, id_project: 1, preflight: 1, createdAt: -1 });
486
478
 
487
479
  // suggested by atlas
488
480
  RequestSchema.index({ id_project: 1, ticket_id: 1 });
489
481
 
490
- // suggested by atlas
491
- RequestSchema.index({ id_project: 1, createdAt: 1, preflight: 1});
492
-
493
- //suggested by atlas profiler. Used by auto closing requests
494
- RequestSchema.index({ hasBot: 1, status: 1, createdAt: 1});
495
-
496
- // suggested by atlas
482
+ // Widget history filtered by channel. Chosen only when channel.name is an equality.
497
483
  RequestSchema.index({ "channel.name": 1, id_project: 1, preflight: 1, "snapshot.requester.uuid_user": 1, createdAt: - 1, status: 1 })
498
484
  RequestSchema.index({ id_project: 1, preflight: 1, "snapshot.agents.id_user": 1, updatedAt: -1, draft: 1, status: 1 })
485
+ // Inbox and websocket for the new visibility shape. One key per request, not per agent.
486
+ RequestSchema.index({ id_project: 1, preflight: 1, "snapshot.agentIds": 1, updatedAt: -1, draft: 1, status: 1 })
487
+ RequestSchema.index({ id_project: 1, preflight: 1, "snapshot.visibility": 1, "snapshot.visibilitySince": 1, updatedAt: -1, draft: 1, status: 1 })
499
488
  RequestSchema.index({ id_project: 1, participants: 1, preflight: 1, updatedAt: -1, draft: 1, status: 1 })
489
+ // Websocket /requests: equality on id_project + preflight, sort updatedAt. Status and draft stay residual.
490
+ RequestSchema.index({ id_project: 1, preflight:1, updatedAt: -1 });
500
491
  RequestSchema.index({ id_project: 1, preflight: 1, updatedAt: -1, draft: 1, status: 1 })
501
492
  RequestSchema.index({ id_project: 1, preflight: 1, "snapshot.requester.uuid_user": 1, createdAt: -1, status: 1 })
502
- RequestSchema.index({ department: 1, id_project: 1, participants: 1, preflight: 1, createdAt: -1, status: 1 })
493
+ // ?dept_id= on the request list: department + id_project + preflight, then createdAt.
494
+ RequestSchema.index({ department: 1, id_project: 1, preflight: 1, createdAt: -1, status: 1 })
503
495
  RequestSchema.index({ id_project: 1, preflight: 1, createdAt: -1, status: 1 });
504
- RequestSchema.index({ id_project: 1, preflight: 1, createdAt: 1 })
505
- RequestSchema.index({ participants: 1, id_project: 1, createdAt: -1, status: 1 })
506
496
  RequestSchema.index({ id_project: 1, "snapshot.lead.email": 1, createdAt: -1, status: 1 })
507
497
  RequestSchema.index({ id_project: 1, createdAt: -1, status: 1 })
508
- RequestSchema.index({ id_project: 1, preflight: 1, smartAssignment: 1, "snapshot.department.routing": 1, createdAt: 1, status: 1 })
509
-
510
- RequestSchema.index({ status: 1, hasBot: 1, updatedAt: 1 }) // For closing unresponsive requests
511
- RequestSchema.index({ status: 1, hasBot: 1, workingStatus: 1, updatedAt: 1 }) // For closing unresponsive requests
512
-
513
- // Contact search by phone / email
514
- RequestSchema.index({ id_project: 1, 'contact.phone': 1 });
515
- RequestSchema.index({ id_project: 1, 'contact.email': 1 });
498
+ // List and history when status is an equality (or $in) and the sort is createdAt.
499
+ RequestSchema.index({ id_project: 1, status: 1, createdAt: -1 });
500
+ // Round-robin in departmentService: { id_project, hasBot:false, preflight:false, status:{$gt:100} } sort _id desc.
501
+ RequestSchema.index({ id_project: 1, hasBot: 1, preflight: 1, _id: -1, status: 1 });
502
+ // Routing queue: count of open chats per agent.
503
+ RequestSchema.index({ id_project: 1, participantsAgents: 1, status: 1, draft: 1 });
504
+
505
+ RequestSchema.index({ status: 1, hasBot: 1, updatedAt: 1 }) // For closing unresponsive requests. Hinted by the close tasks.
506
+
507
+ //Deprecated indexes
508
+ //RequestSchema.index({ createdAt: -1 }); // schema level
509
+ //RequestSchema.index({ updatedAt: -1 }); // schema level
510
+ //RequestSchema.index({ id_project: 1 }); // schema level
511
+ //RequestSchema.index({ id_project: 1, participants: 1});
512
+ //RequestSchema.index({ id_project: 1, status: 1, updatedAt: -1 }); // query for websocket
513
+ //RequestSchema.index({ id_project: 1, status: 1, preflight:1, updatedAt: -1 }); // query for websocket
514
+ //RequestSchema.index({ hasBot: 1, createdAt: 1 }); // suggested by atlas
515
+ //RequestSchema.index({ lead: 1, id_project: 1, participants: 1, preflight: 1, createdAt: -1 });
516
+ //RequestSchema.index({ lead: 1, "snapshot.agents.id_user": 1, id_project: 1, preflight: 1, createdAt: -1 });
517
+ //RequestSchema.index({ id_project: 1, createdAt: 1, preflight: 1});
518
+ //RequestSchema.index({ hasBot: 1, status: 1, createdAt: 1}); // old auto-close on createdAt; live jobs hint status+hasBot+updatedAt
519
+ //RequestSchema.index({ department: 1, id_project: 1, participants: 1, preflight: 1, createdAt: -1, status: 1 })
520
+ //RequestSchema.index({ id_project: 1, preflight: 1, createdAt: 1 })
521
+ //RequestSchema.index({ participants: 1, id_project: 1, createdAt: -1, status: 1 })
522
+ //RequestSchema.index({ id_project: 1, preflight: 1, smartAssignment: 1, "snapshot.department.routing": 1, createdAt: 1, status: 1 })
523
+ //RequestSchema.index({ status: 1, hasBot: 1, workingStatus: 1, updatedAt: 1 }) // close tasks hint the index without workingStatus
524
+ //RequestSchema.index({ id_project: 1, 'contact.phone': 1 }); // phone filter is an unanchored regex
525
+ //RequestSchema.index({ id_project: 1, 'contact.email': 1 });
516
526
 
517
527
  // ERROR DURING DEPLOY OF 2.10.27
518
528
  //RequestSchema.index({ id_project: 1, participants: 1, "snapshot.agents.id_user": 1, createdAt: -1, status: 1 })
@@ -21,6 +21,18 @@ var RequestSnapshotSchema = new Schema({
21
21
  // select: true
22
22
  select: false
23
23
  },
24
+ // 'project': every teammate who had already joined at visibilitySince.
25
+ // 'agents': only snapshot.agentIds (the department group at routing time).
26
+ // Legacy documents have neither and use snapshot.agents instead.
27
+ visibility: {
28
+ type: String
29
+ },
30
+ visibilitySince: {
31
+ type: Date
32
+ },
33
+ agentIds: [{
34
+ type: Schema.Types.ObjectId
35
+ }],
24
36
  // participatingAgents
25
37
  availableAgentsCount: {
26
38
  type: Number,
@@ -12,7 +12,7 @@ winston.info('VisitorCounterSchema dbUrl: '+dbUrl);
12
12
  // mongoose.set('useCreateIndex', true);
13
13
  // mongoose.set('useUnifiedTopology', true);
14
14
 
15
- var conn = mongoose.createConnection(dbUrl, { "autoIndex": true });
15
+ var conn = mongoose.createConnection(dbUrl, { "useNewUrlParser": true, "autoIndex": true });
16
16
  // var conn = mongoose.connect(dbUrl, { "useNewUrlParser": true, "autoIndex": true });
17
17
 
18
18
  // db.getCollection('reqlogs').aggregate([ {$group:{_id:{id_project:"$id_project"}, "count":{$sum:1}}},{$sort:{"count":-1}}])
package/models/webhook.js CHANGED
@@ -2,6 +2,36 @@ const mongoose = require('mongoose');
2
2
  const { customAlphabet } = require('nanoid');
3
3
  const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 32);
4
4
 
5
+ const StartPointSchema = mongoose.Schema({
6
+ type: {
7
+ type: String,
8
+ enum: ['webhook', 'scheduled'],
9
+ required: true
10
+ },
11
+ block_id: {
12
+ type: String,
13
+ required: true
14
+ },
15
+ enabled: {
16
+ type: Boolean,
17
+ default: true
18
+ },
19
+ mapping: {
20
+ source_name: {
21
+ type: String,
22
+ required: false
23
+ },
24
+ payload: {
25
+ type: mongoose.Schema.Types.Mixed,
26
+ required: false
27
+ }
28
+ },
29
+ schedule: {
30
+ type: mongoose.Schema.Types.Mixed,
31
+ required: false
32
+ }
33
+ }, { _id: false })
34
+
5
35
  const WebhookSchema = mongoose.Schema({
6
36
  webhook_id: {
7
37
  type: String,
@@ -38,6 +68,20 @@ const WebhookSchema = mongoose.Schema({
38
68
  type: Boolean,
39
69
  required: true,
40
70
  default: true
71
+ },
72
+ mode: {
73
+ type: String,
74
+ enum: ['conversation'],
75
+ required: false
76
+ },
77
+ start_points: {
78
+ type: [StartPointSchema],
79
+ default: undefined
80
+ },
81
+ // Server-owned snapshot of the schedule active in the scheduler; written only by the publish sync.
82
+ scheduled_live: {
83
+ type: mongoose.Schema.Types.Mixed,
84
+ required: false
41
85
  }
42
86
  }, {
43
87
  timestamps: true
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-server",
3
3
  "description": "The Tiledesk server module",
4
- "version": "3.0.1",
4
+ "version": "3.2.1",
5
5
  "scripts": {
6
6
  "start": "node ./bin/www",
7
+ "quota-restore": "node ./bin/quota-restore",
8
+ "quota-reset": "node ./bin/quota-reset",
7
9
  "pretest": "mongodb-runner start",
8
10
  "watchenv": "nodemon --watch .env --watch ./confenv/.env ./bin/www",
9
11
  "test": "mocha ./test/*.js ./pubmodules/**/test/*.js ./modules/**/test/*.js ./channels/*/test/*.js ./node_modules/@tiledesk-ent/**/test/*.js --exit",
@@ -22,8 +24,8 @@
22
24
  "url": "git+https://github.com/Tiledesk/tiledesk-server.git"
23
25
  },
24
26
  "engines": {
25
- "node": "16.17.0",
26
- "npm": "8.15.0"
27
+ "node": "24.22.1",
28
+ "npm": "11.19.1"
27
29
  },
28
30
  "bin": {
29
31
  "tiledesk-server": "./bin/www"
@@ -38,7 +40,7 @@
38
40
  "dependencies": {
39
41
  "@tiledesk/tiledesk-apps": "^1.0.28",
40
42
  "@tiledesk/tiledesk-chat21-app": "^1.1.8",
41
- "@tiledesk/tiledesk-chatbot-templates": "^0.1.3",
43
+ "@tiledesk/tiledesk-chatbot-templates": "^0.1.7",
42
44
  "@tiledesk/tiledesk-chatbot-util": "^0.8.33",
43
45
  "@tiledesk/tiledesk-client": "^0.10.10",
44
46
  "@tiledesk/tiledesk-dialogflow-connector": "^1.8.4",
@@ -49,9 +51,9 @@
49
51
  "@tiledesk/tiledesk-rasa-connector": "^1.0.10",
50
52
  "@tiledesk/tiledesk-sms-connector": "^0.1.13",
51
53
  "@tiledesk/tiledesk-telegram-connector": "^0.1.14",
52
- "@tiledesk/tiledesk-tybot-connector": "^2.3.0",
54
+ "@tiledesk/tiledesk-tybot-connector": "^3.0.2",
53
55
  "@tiledesk/tiledesk-voice-twilio-connector": "^0.3.2",
54
- "@tiledesk/tiledesk-vxml-connector": "^0.1.91",
56
+ "@tiledesk/tiledesk-vxml-connector": "^0.2.7",
55
57
  "@tiledesk/tiledesk-whatsapp-connector": "1.0.31",
56
58
  "@tiledesk/tiledesk-whatsapp-jobworker": "^0.0.14",
57
59
  "amqplib": "^0.5.5",
@@ -114,7 +116,7 @@
114
116
  "request-promise": "^4.2.6",
115
117
  "retry-request": "^4.2.2",
116
118
  "serve-favicon": "~2.5.0",
117
- "sharp": "^0.27.2",
119
+ "sharp": "^0.35.5",
118
120
  "sitemapper": "^3.2.24",
119
121
  "stripe": "^7.2.0",
120
122
  "uniqid": "^5.4.0",
@@ -14,6 +14,7 @@ var winston = require('../../config/winston');
14
14
  var RoleConstants = require("../../models/roleConstants");
15
15
  var ChannelConstants = require("../../models/channelConstants");
16
16
  var cacheUtil = require('../../utils/cacheUtil');
17
+ var requestVisibility = require('../../utils/requestVisibility');
17
18
  const { TdCache } = require('../../utils/TdCache');
18
19
 
19
20
  const messageEvent = require('../../event/messageEvent');
@@ -572,12 +573,13 @@ sendToAgentEmailChannelEmail(projectid, message) {
572
573
 
573
574
  // winston.info("savedRequest.snapshot.agents", savedRequest.snapshot.agents);
574
575
  // agents è selected false quindi nn va sicuro
575
- if (!snapshotAgents.snapshot.agents) {
576
- return winston.warn("RequestNotification snapshotAgents.snapshot.agents is null :(. You are closing an old request?", savedRequest);
576
+ var allAgents = await requestVisibility.loadNotifiableProjectUsers(
577
+ snapshotAgents && snapshotAgents.snapshot,
578
+ savedRequest.id_project
579
+ );
580
+ if (!allAgents || allAgents.length === 0) {
581
+ return winston.warn("RequestNotification snapshot audience is empty. You are closing an old request?", savedRequest);
577
582
  }
578
-
579
- // var allAgents = savedRequest.agents;
580
- var allAgents = snapshotAgents.snapshot.agents;
581
583
  // winston.debug("allAgents", allAgents);
582
584
 
583
585
  allAgents.forEach(project_user => {
@@ -937,30 +939,20 @@ sendAgentEmail(projectid, savedRequest) {
937
939
 
938
940
  var snapshotAgents = savedRequest; //riassegno varibile cosi nn cambio righe successive
939
941
 
940
-
941
-
942
-
943
- // winston.info("savedRequest.snapshot.agents", savedRequest.snapshot.agents);
944
- // agents è selected false quindi nn va sicuro
945
- if (!snapshotAgents.snapshot.agents) {
946
- //return winston.warn("RequestNotification snapshotAgents.snapshot.agents is null :(. You are closing an old request?", savedRequest);
947
-
942
+ if (!requestVisibility.hasAudience(snapshotAgents.snapshot)) {
948
943
  // agents già c'è in quanto viene creato con departmentService.getOperator nella request.create ma nn c'è per request.participants.update
949
944
  snapshotAgents = await Request.findById(savedRequest.id).select({"snapshot":1}).exec();
950
945
  winston.debug('load snapshotAgents with Request.findById ');
951
946
  }
952
947
  winston.debug('snapshotAgents', snapshotAgents);
953
948
 
954
- if (!snapshotAgents.snapshot.agents) {
955
- return winston.warn("RequestNotification snapshotAgents.snapshot.agents is null :(. You are closing an old request?", savedRequest);
949
+ var allAgents = await requestVisibility.loadNotifiableProjectUsers(
950
+ snapshotAgents && snapshotAgents.snapshot,
951
+ savedRequest.id_project
952
+ );
953
+ if (!allAgents || allAgents.length === 0) {
954
+ return winston.warn("RequestNotification snapshot audience is empty. You are closing an old request?", savedRequest);
956
955
  }
957
-
958
- // var allAgents = savedRequest.agents;
959
- var allAgents = snapshotAgents.snapshot.agents;
960
-
961
- // // var allAgents = savedRequest.agents;
962
- // var allAgents = savedRequest.snapshot.agents;
963
- // // winston.debug("allAgents", allAgents);
964
956
 
965
957
  allAgents.forEach(project_user => {
966
958
  // winston.debug("project_user", project_user); //DON'T UNCOMMENT THIS. OTHERWISE this.agents.filter of models/request.js:availableAgentsCount has .filter not found.
@@ -2,7 +2,7 @@
2
2
  process.env.NODE_ENV = 'test';
3
3
 
4
4
  var User = require('../../../models/user');
5
- var Project_user = require('../../../models/project_user');
5
+ var Event = require('../event');
6
6
 
7
7
  var projectService = require('../../../services/projectService');
8
8
  var userService = require('../../../services/userService');
@@ -51,11 +51,12 @@ describe('EventRoute', () => {
51
51
  expect(res.body.name).to.equal("event1");
52
52
  expect(res.body.attributes.attr1).to.equal("val1");
53
53
 
54
- Project_user.findOne({ id_user: savedUser.id, status: "active"} )
55
- .populate('events')
56
- .exec(function (err, project_user) {
57
- if (log) { console.log("project_user", project_user.toJSON()); }
58
- expect(project_user.events.length).to.equal(1);
54
+ Event.find({ name: "event1", id_project: savedProject._id.toString() })
55
+ .exec(function (err, events) {
56
+ if (err) { console.error("err: ", err); }
57
+ if (log) { console.log("events", events); }
58
+ expect(events).to.have.lengthOf(1);
59
+ expect(events[0].attributes.attr1).to.equal("val1");
59
60
  done();
60
61
  });
61
62
 
@@ -11,6 +11,7 @@ var i8nUtil = require("../../utils/i8nUtil");
11
11
  var BotFromParticipant = require("../../utils/botFromParticipant");
12
12
  var assignmentContextUtil = require('../../utils/assignmentContextUtil');
13
13
  const RequestConstants = require('../../models/requestConstants');
14
+ var ChannelConstants = require("../../models/channelConstants");
14
15
 
15
16
  class ConciergeBot {
16
17
 
@@ -142,18 +143,22 @@ devi mandare un messaggio welcome tu altrimenti il bot inserito successivamente
142
143
  winston.debug("ConciergeBot member: " + member);
143
144
  // botprefix
144
145
  if (member.indexOf("bot_")==-1) {
146
+ if (request.channel && request.channel.name === ChannelConstants.WEBHOOK) {
147
+ winston.debug("ConciergeBot: keeping the bot in the request with request_id: " + request.request_id + " because the conversation channel is webhook");
148
+ } else {
145
149
  var botId = BotFromParticipant.getBotFromParticipants(request.participants);
146
150
  if (botId) {
147
151
  winston.verbose("ConciergeBot: removing bot with id: " + botId + " from the request with request_id: " + request.request_id + " from the project with id: " + request.id_project);
148
-
152
+
149
153
  // botprefix
150
- // removeParticipantByRequestId(request_id, id_project, member)
154
+ // removeParticipantByRequestId(request_id, id_project, member)
151
155
  requestService.removeParticipantByRequestId(request.request_id, request.id_project,"bot_"+botId ).catch((err) => {
152
156
  winston.error("(ConciergeBot) removeParticipantByRequestId error", err)
153
157
  });
154
- }
158
+ }
159
+ }
155
160
  }
156
-
161
+
157
162
 
158
163
  });
159
164
  });
package/routes/auth.js CHANGED
@@ -27,7 +27,6 @@ var UserUtil = require('../utils/userUtil');
27
27
 
28
28
  let configSecret = process.env.GLOBAL_SECRET || config.secret;
29
29
  var pKey = process.env.GLOBAL_SECRET_OR_PRIVATE_KEY;
30
- // console.log("pKey",pKey);
31
30
 
32
31
  if (pKey) {
33
32
  configSecret = pKey.replace(/\\n/g, '\n');
@@ -713,10 +712,6 @@ router.get("/google", function(req,res,next){
713
712
  )(req,res,next);
714
713
  });
715
714
 
716
- // router.get("/google/callbacks", passport.authenticate("google", { session: false }), (req, res) => {
717
- // console.log("callback_signup");
718
- // res.redirect("/google/callback");
719
- // });
720
715
 
721
716
  // Retrieve user data using the access token received</em>
722
717
  router.get("/google/callback", passport.authenticate("google", { session: false }), (req, res) => {
@@ -865,12 +860,6 @@ router.get(
865
860
  );
866
861
 
867
862
 
868
- // profile route after successful sign in</em>
869
- // router.get("/profile", (req, res) => {
870
- // console.log(req);
871
- // res.send("Welcome");
872
- // });
873
-
874
863
  // VERIFY EMAIL
875
864
  router.put('/verifyemail/:userid/:code', async function (req, res) {
876
865
 
@@ -887,7 +876,7 @@ router.put('/verifyemail/:userid/:code', async function (req, res) {
887
876
  let redis_client = req.app.get('redis_client');
888
877
  let key = "emailverify:verify-" + verify_email_code;
889
878
  let value = await redis_client.get(key);
890
- console.log("(Auth) verify value: ", value);
879
+
891
880
  if (!value) {
892
881
  return res.status(401).send({ success: false, error: "Unable to verify email: the verification code is expired or invalid.", error_code: errorCodes.AUTH.ERRORS.VERIFICATION_CODE_EXPIRED})
893
882
  }
@@ -240,19 +240,6 @@ router.post('/directDEPRECATED?', async function (req, res) {
240
240
  //TODO RESTORE IT
241
241
  const cursor = Lead.find(queryLead).cursor();
242
242
 
243
-
244
-
245
- // if (doc!= null) {
246
- // doc = await cursor.next()
247
- // }
248
-
249
- // cursor.next(function(error, doc) {
250
- // console.log(doc);
251
-
252
- // setTimout()
253
- // });
254
-
255
-
256
243
  function sleep(ms) {
257
244
  return new Promise((resolve) => {
258
245
  setTimeout(resolve, ms);
@@ -148,8 +148,6 @@ function getRowsListParams(req) {
148
148
  }
149
149
 
150
150
  router.get('/:id/rows/list', async function (req, res) {
151
-
152
- console.log("List rows")
153
151
  try {
154
152
  const rows = await dataTableService.listRowsWithFilter(
155
153
  req.projectid,
@@ -164,7 +162,6 @@ router.get('/:id/rows/list', async function (req, res) {
164
162
  });
165
163
 
166
164
  router.post('/:id/row/insert', async function (req, res) {
167
- console.log("Insert row")
168
165
  try {
169
166
  const row = await dataTableService.insertRowByBody(req.projectid, req.params.id, req.body);
170
167
  if (!row) return res.status(404).send({ success: false, error: 'Table not found' });
@@ -174,6 +171,16 @@ router.post('/:id/row/insert', async function (req, res) {
174
171
  }
175
172
  });
176
173
 
174
+ router.post('/:id/rows/insert', async function (req, res) {
175
+ try {
176
+ const rows = await dataTableService.insertRowsByBody(req.projectid, req.params.id, req.body);
177
+ if (!rows) return res.status(404).send({ success: false, error: 'Table not found' });
178
+ res.status(200).send(rows);
179
+ } catch (err) {
180
+ handleError(res, err, 'inserting rows');
181
+ }
182
+ });
183
+
177
184
  router.put('/:id/row/update', async function (req, res) {
178
185
  try {
179
186
  const row = await dataTableService.updateRowByBody(req.projectid, req.params.id, req.body);
@@ -198,6 +205,19 @@ router.put('/:id/row/upsert', async function (req, res) {
198
205
  }
199
206
  });
200
207
 
208
+ router.put('/:id/rows/upsert', async function (req, res) {
209
+ try {
210
+ const rows = await dataTableService.upsertRowsByBody(req.projectid, req.params.id, req.body);
211
+ if (rows === null) return res.status(404).send({ success: false, error: 'Table not found' });
212
+ res.status(200).send(rows);
213
+ } catch (err) {
214
+ if (err.message === 'Multiple rows match the conditions') {
215
+ return res.status(409).send({ success: false, message: err.message });
216
+ }
217
+ handleError(res, err, 'upserting rows');
218
+ }
219
+ });
220
+
201
221
  router.put('/:id/row/delete', async function (req, res) {
202
222
  try {
203
223
  const row = await dataTableService.deleteRowByBody(req.projectid, req.params.id, req.body);
package/routes/faq_kb.js CHANGED
@@ -285,6 +285,13 @@ router.put('/:faq_kbid/publish', roleChecker.hasRole('admin'), async (req, res)
285
285
  return res.status(200).send({ message: "Chatbot published successfully", bot_id: published.bot_id });
286
286
  } catch (e) {
287
287
  winston.error("Error Unable publish chatbot: ", e);
288
+ if (e instanceof AppError) {
289
+ const body = { success: false, message: e.message };
290
+ if (Array.isArray(e.errors)) {
291
+ body.errors = e.errors;
292
+ }
293
+ return res.status(e.status).send(body);
294
+ }
288
295
  return res.status(500).send({ success: false, message: "Unable publish chatbot" });
289
296
  }
290
297
  });
@@ -331,7 +338,11 @@ router.put('/:faq_kbid/publish/multi', roleChecker.hasRole('admin'), asyncHandle
331
338
  } catch (err) {
332
339
  const error = err?.response?.data?.message || err?.response?.data?.error || err?.message || "Publish failed";
333
340
  winston.error("Error publishing chatbot " + id_faq_kb + ": ", err);
334
- results.push({ id: id_faq_kb, success: false, error });
341
+ const result = { id: id_faq_kb, success: false, error };
342
+ if (Array.isArray(err?.errors)) {
343
+ result.errors = err.errors;
344
+ }
345
+ results.push(result);
335
346
  }
336
347
  }
337
348
 
@@ -126,7 +126,6 @@ router.get('/csv', roleChecker.hasRoleOrTypes('owner'), function(req, res) {
126
126
 
127
127
  res.flushHeaders();
128
128
 
129
- console.log("fastCsv",fastCsv)
130
129
  var csvStream = fastCsv.format({headers: true})//.transform(transformer)
131
130
  // var csvStream = fastCsv.createWriteStream({headers: true}).transform(transformer)
132
131
  cursor.stream().pipe(csvStream).pipe(res);