snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
411
apps/meteor/server/services/omnichannel-analytics/AgentData.ts
Normal file
411
apps/meteor/server/services/omnichannel-analytics/AgentData.ts
Normal file
@@ -0,0 +1,411 @@
|
||||
/* eslint-disable new-cap */
|
||||
import type { ConversationData } from '@rocket.chat/core-services';
|
||||
import type { IOmnichannelRoom } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatRoomsModel } from '@rocket.chat/model-typings';
|
||||
import type moment from 'moment';
|
||||
import type { Filter } from 'mongodb';
|
||||
|
||||
import { secondsToHHMMSS } from '../../../lib/utils/secondsToHHMMSS';
|
||||
|
||||
type AgentOverviewValidActions =
|
||||
| 'Total_conversations'
|
||||
| 'Avg_chat_duration'
|
||||
| 'Total_messages'
|
||||
| 'Avg_first_response_time'
|
||||
| 'Best_first_response_time'
|
||||
| 'Avg_response_time'
|
||||
| 'Avg_reaction_time';
|
||||
|
||||
export class AgentOverviewData {
|
||||
constructor(private readonly roomsModel: ILivechatRoomsModel) {}
|
||||
|
||||
updateMap<K>(map: Map<K, number>, key: K, value: number) {
|
||||
const currentKeyValue = map.get(key);
|
||||
map.set(key, currentKeyValue ? currentKeyValue + value : value);
|
||||
}
|
||||
|
||||
sortByValue(data: { value: string }[], inv = false) {
|
||||
data.sort((a, b) => {
|
||||
// sort array
|
||||
if (parseFloat(a.value) > parseFloat(b.value)) {
|
||||
return inv ? -1 : 1; // if inv, reverse sort
|
||||
}
|
||||
if (parseFloat(a.value) < parseFloat(b.value)) {
|
||||
return inv ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
isActionAllowed(action: string | undefined): action is AgentOverviewValidActions {
|
||||
if (!action) {
|
||||
return false;
|
||||
}
|
||||
return [
|
||||
'Total_conversations',
|
||||
'Avg_chat_duration',
|
||||
'Total_messages',
|
||||
'Avg_first_response_time',
|
||||
'Best_first_response_time',
|
||||
'Avg_response_time',
|
||||
'Avg_reaction_time',
|
||||
].includes(action);
|
||||
}
|
||||
|
||||
callAction<T extends AgentOverviewValidActions>(action: T, ...args: [moment.Moment, moment.Moment, string?, Filter<IOmnichannelRoom>?]) {
|
||||
switch (action) {
|
||||
case 'Total_conversations':
|
||||
return this.Total_conversations(...args);
|
||||
case 'Avg_chat_duration':
|
||||
return this.Avg_chat_duration(...args);
|
||||
case 'Total_messages':
|
||||
return this.Total_messages(...args);
|
||||
case 'Avg_first_response_time':
|
||||
return this.Avg_first_response_time(...args);
|
||||
case 'Best_first_response_time':
|
||||
return this.Best_first_response_time(...args);
|
||||
case 'Avg_response_time':
|
||||
return this.Avg_response_time(...args);
|
||||
case 'Avg_reaction_time':
|
||||
return this.Avg_reaction_time(...args);
|
||||
default:
|
||||
throw new Error('Invalid action');
|
||||
}
|
||||
}
|
||||
|
||||
async Total_conversations(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let total = 0;
|
||||
const agentConversations = new Map(); // stores total conversations for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: '%_of_conversations',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel
|
||||
.getAnalyticsMetricsBetweenDateWithMessages(
|
||||
'l',
|
||||
date,
|
||||
{
|
||||
departmentId,
|
||||
},
|
||||
{},
|
||||
extraQuery,
|
||||
)
|
||||
.forEach((room) => {
|
||||
if (room.servedBy) {
|
||||
this.updateMap(agentConversations, room.servedBy.username, 1);
|
||||
total++;
|
||||
}
|
||||
});
|
||||
|
||||
agentConversations.forEach((value, key) => {
|
||||
// calculate percentage
|
||||
const percentage = ((value / total) * 100).toFixed(2);
|
||||
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: `${percentage}%`,
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, true); // reverse sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Avg_chat_duration(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentChatDurations = new Map(); // stores total conversations for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Avg_chat_duration',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics, servedBy }) => {
|
||||
if (servedBy && metrics && metrics.chatDuration) {
|
||||
if (agentChatDurations.has(servedBy.username)) {
|
||||
agentChatDurations.set(servedBy.username, {
|
||||
chatDuration: agentChatDurations.get(servedBy.username).chatDuration + metrics.chatDuration,
|
||||
total: agentChatDurations.get(servedBy.username).total + 1,
|
||||
});
|
||||
} else {
|
||||
agentChatDurations.set(servedBy.username, {
|
||||
chatDuration: metrics.chatDuration,
|
||||
total: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
agentChatDurations.forEach((obj, key) => {
|
||||
// calculate percentage
|
||||
const avg = (obj.chatDuration / obj.total).toFixed(2);
|
||||
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: secondsToHHMMSS(avg),
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, true); // reverse sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Total_messages(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentMessages = new Map(); // stores total conversations for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Total_messages',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
// we don't want to count visitor messages
|
||||
const extraFilter = { $lte: ['$token', null] };
|
||||
await this.roomsModel
|
||||
.getAnalyticsMetricsBetweenDateWithMessages('l', date, { departmentId }, extraFilter, extraQuery)
|
||||
.forEach(({ servedBy, msgs }) => {
|
||||
if (servedBy) {
|
||||
this.updateMap(agentMessages, servedBy.username, msgs);
|
||||
}
|
||||
});
|
||||
|
||||
agentMessages.forEach((value, key) => {
|
||||
// calculate percentage
|
||||
data.data.push({
|
||||
name: key,
|
||||
value,
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, true); // reverse sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Avg_first_response_time(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentAvgRespTime = new Map(); // stores avg response time for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Avg_first_response_time',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics, responseBy }) => {
|
||||
if (responseBy && metrics && metrics.response && metrics.response.ft) {
|
||||
if (agentAvgRespTime.has(responseBy.username)) {
|
||||
agentAvgRespTime.set(responseBy.username, {
|
||||
frt: agentAvgRespTime.get(responseBy.username).frt + metrics.response.ft,
|
||||
total: agentAvgRespTime.get(responseBy.username).total + 1,
|
||||
});
|
||||
} else {
|
||||
agentAvgRespTime.set(responseBy.username, {
|
||||
frt: metrics.response.ft,
|
||||
total: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
agentAvgRespTime.forEach((obj, key) => {
|
||||
// calculate avg
|
||||
const avg = obj.frt / obj.total;
|
||||
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: secondsToHHMMSS(avg.toFixed(2)),
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, false); // sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Best_first_response_time(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentFirstRespTime = new Map(); // stores best response time for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Best_first_response_time',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics, responseBy }) => {
|
||||
if (responseBy && metrics && metrics.response && metrics.response.ft) {
|
||||
if (agentFirstRespTime.has(responseBy.username)) {
|
||||
agentFirstRespTime.set(responseBy.username, Math.min(agentFirstRespTime.get(responseBy.username), metrics.response.ft));
|
||||
} else {
|
||||
agentFirstRespTime.set(responseBy.username, metrics.response.ft);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
agentFirstRespTime.forEach((value, key) => {
|
||||
// calculate avg
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: secondsToHHMMSS(value.toFixed(2)),
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, false); // sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Avg_response_time(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentAvgRespTime = new Map(); // stores avg response time for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Avg_response_time',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics, servedBy }) => {
|
||||
if (servedBy && metrics && metrics.response && metrics.response.avg) {
|
||||
if (agentAvgRespTime.has(servedBy.username)) {
|
||||
agentAvgRespTime.set(servedBy.username, {
|
||||
avg: agentAvgRespTime.get(servedBy.username).avg + metrics.response.avg,
|
||||
total: agentAvgRespTime.get(servedBy.username).total + 1,
|
||||
});
|
||||
} else {
|
||||
agentAvgRespTime.set(servedBy.username, {
|
||||
avg: metrics.response.avg,
|
||||
total: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
agentAvgRespTime.forEach((obj, key) => {
|
||||
// calculate avg
|
||||
const avg = obj.avg / obj.total;
|
||||
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: secondsToHHMMSS(avg.toFixed(2)),
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, false); // sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async Avg_reaction_time(from: moment.Moment, to: moment.Moment, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
const agentAvgReactionTime = new Map(); // stores avg reaction time for each agent
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
const data: ConversationData = {
|
||||
head: [
|
||||
{
|
||||
name: 'Agent',
|
||||
},
|
||||
{
|
||||
name: 'Avg_reaction_time',
|
||||
},
|
||||
],
|
||||
data: [],
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics, servedBy }) => {
|
||||
if (servedBy && metrics && metrics.reaction && metrics.reaction.ft) {
|
||||
if (agentAvgReactionTime.has(servedBy.username)) {
|
||||
agentAvgReactionTime.set(servedBy.username, {
|
||||
frt: agentAvgReactionTime.get(servedBy.username).frt + metrics.reaction.ft,
|
||||
total: agentAvgReactionTime.get(servedBy.username).total + 1,
|
||||
});
|
||||
} else {
|
||||
agentAvgReactionTime.set(servedBy.username, {
|
||||
frt: metrics.reaction.ft,
|
||||
total: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
agentAvgReactionTime.forEach((obj, key) => {
|
||||
// calculate avg
|
||||
const avg = obj.frt / obj.total;
|
||||
|
||||
data.data.push({
|
||||
name: key,
|
||||
value: secondsToHHMMSS(avg.toFixed(2)),
|
||||
});
|
||||
});
|
||||
|
||||
this.sortByValue(data.data, false); // sort array
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
154
apps/meteor/server/services/omnichannel-analytics/ChartData.ts
Normal file
154
apps/meteor/server/services/omnichannel-analytics/ChartData.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
import type { IOmnichannelRoom } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatRoomsModel } from '@rocket.chat/model-typings';
|
||||
import type { Filter } from 'mongodb';
|
||||
|
||||
/* eslint-disable new-cap */
|
||||
type ChartDataValidActions =
|
||||
| 'Total_conversations'
|
||||
| 'Avg_chat_duration'
|
||||
| 'Total_messages'
|
||||
| 'Avg_first_response_time'
|
||||
| 'Avg_reaction_time'
|
||||
| 'Best_first_response_time'
|
||||
| 'Avg_response_time';
|
||||
|
||||
type DateParam = {
|
||||
gte: Date;
|
||||
lte: Date;
|
||||
};
|
||||
|
||||
export class ChartData {
|
||||
constructor(private readonly roomsModel: ILivechatRoomsModel) {}
|
||||
|
||||
isActionAllowed(action: string | undefined): action is ChartDataValidActions {
|
||||
if (!action) {
|
||||
return false;
|
||||
}
|
||||
return [
|
||||
'Total_conversations',
|
||||
'Avg_chat_duration',
|
||||
'Total_messages',
|
||||
'Avg_first_response_time',
|
||||
'Avg_reaction_time',
|
||||
'Best_first_response_time',
|
||||
'Avg_response_time',
|
||||
].includes(action);
|
||||
}
|
||||
|
||||
callAction<T extends ChartDataValidActions>(action: T, ...args: [DateParam, string?, Filter<IOmnichannelRoom>?]) {
|
||||
switch (action) {
|
||||
case 'Total_conversations':
|
||||
return this.Total_conversations(...args);
|
||||
case 'Avg_chat_duration':
|
||||
return this.Avg_chat_duration(...args);
|
||||
case 'Total_messages':
|
||||
return this.Total_messages(...args);
|
||||
case 'Avg_first_response_time':
|
||||
return this.Avg_first_response_time(...args);
|
||||
case 'Avg_reaction_time':
|
||||
return this.Avg_reaction_time(...args);
|
||||
case 'Best_first_response_time':
|
||||
return this.Best_first_response_time(...args);
|
||||
case 'Avg_response_time':
|
||||
return this.Avg_response_time(...args);
|
||||
default:
|
||||
throw new Error('Invalid action');
|
||||
}
|
||||
}
|
||||
|
||||
async Total_conversations(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
// @ts-expect-error - Check extraquery usage on this func
|
||||
return this.roomsModel.getTotalConversationsBetweenDate('l', date, { departmentId }, extraQuery);
|
||||
}
|
||||
|
||||
async Avg_chat_duration(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let total = 0;
|
||||
let count = 0;
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.chatDuration) {
|
||||
total += metrics.chatDuration;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgCD = count ? total / count : 0;
|
||||
return Math.round(avgCD * 100) / 100;
|
||||
}
|
||||
|
||||
async Total_messages(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let total = 0;
|
||||
|
||||
// we don't want to count visitor messages
|
||||
const extraFilter = { $lte: ['$token', null] };
|
||||
await this.roomsModel
|
||||
.getAnalyticsMetricsBetweenDateWithMessages('l', date, { departmentId }, extraFilter, extraQuery)
|
||||
.forEach(({ msgs }) => {
|
||||
if (msgs) {
|
||||
total += msgs;
|
||||
}
|
||||
});
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
async Avg_first_response_time(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let frt = 0;
|
||||
let count = 0;
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.response?.ft) {
|
||||
frt += metrics.response.ft;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgFrt = count ? frt / count : 0;
|
||||
return Math.round(avgFrt * 100) / 100;
|
||||
}
|
||||
|
||||
async Best_first_response_time(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let maxFrt = 0;
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.response?.ft) {
|
||||
maxFrt = maxFrt ? Math.min(maxFrt, metrics.response.ft) : metrics.response.ft;
|
||||
}
|
||||
});
|
||||
|
||||
if (!maxFrt) {
|
||||
maxFrt = 0;
|
||||
}
|
||||
|
||||
return Math.round(maxFrt * 100) / 100;
|
||||
}
|
||||
|
||||
async Avg_response_time(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let art = 0;
|
||||
let count = 0;
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.response?.avg) {
|
||||
art += metrics.response.avg;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgArt = count ? art / count : 0;
|
||||
|
||||
return Math.round(avgArt * 100) / 100;
|
||||
}
|
||||
|
||||
async Avg_reaction_time(date: DateParam, departmentId?: string, extraQuery: Filter<IOmnichannelRoom> = {}) {
|
||||
let arnt = 0;
|
||||
let count = 0;
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.reaction?.ft) {
|
||||
arnt += metrics.reaction.ft;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
const avgArnt = count ? arnt / count : 0;
|
||||
|
||||
return Math.round(avgArnt * 100) / 100;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/* eslint-disable new-cap */
|
||||
import type { IOmnichannelRoom } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatRoomsModel } from '@rocket.chat/model-typings';
|
||||
import moment from 'moment-timezone';
|
||||
import type { Filter } from 'mongodb';
|
||||
|
||||
import { secondsToHHMMSS } from '../../../lib/utils/secondsToHHMMSS';
|
||||
|
||||
type OverviewDataValidActions = 'Conversations' | 'Productivity';
|
||||
|
||||
export class OverviewData {
|
||||
constructor(private readonly roomsModel: ILivechatRoomsModel) {}
|
||||
|
||||
isActionAllowed(action: string | undefined): action is OverviewDataValidActions {
|
||||
if (!action) {
|
||||
return false;
|
||||
}
|
||||
return ['Conversations', 'Productivity'].includes(action);
|
||||
}
|
||||
|
||||
callAction<T extends OverviewDataValidActions>(
|
||||
action: T,
|
||||
...args: [moment.Moment, moment.Moment, string?, string?, ((v: string) => string)?, Filter<IOmnichannelRoom>?]
|
||||
) {
|
||||
switch (action) {
|
||||
case 'Conversations':
|
||||
return this.Conversations(...args);
|
||||
case 'Productivity':
|
||||
return this.Productivity(...args);
|
||||
default:
|
||||
throw new Error('Invalid action');
|
||||
}
|
||||
}
|
||||
|
||||
getKeyHavingMaxValue<T>(map: Map<T, number>, def: T): T {
|
||||
let maxValue = 0;
|
||||
let maxKey = def; // default
|
||||
|
||||
map.forEach((value, key) => {
|
||||
if (value > maxValue) {
|
||||
maxValue = value;
|
||||
maxKey = key;
|
||||
}
|
||||
});
|
||||
|
||||
return maxKey;
|
||||
}
|
||||
|
||||
sumAllMapKeys<T>(map: Map<T, number>): number {
|
||||
let sum = 0;
|
||||
|
||||
map.forEach((value) => {
|
||||
sum += value;
|
||||
});
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
getBusiestDay(map: Map<string, Map<string, number>>): string {
|
||||
let mostMessages = -1;
|
||||
let busiestDay = '-';
|
||||
|
||||
map.forEach((value, key) => {
|
||||
const v = this.sumAllMapKeys(value);
|
||||
if (v > mostMessages) {
|
||||
mostMessages = v;
|
||||
busiestDay = key;
|
||||
}
|
||||
});
|
||||
|
||||
return busiestDay;
|
||||
}
|
||||
|
||||
getAllMapKeysSize<T>(map: Map<T, Map<T, number>>): number {
|
||||
let size = 0;
|
||||
|
||||
[...map.keys()].forEach((key) => {
|
||||
size += map.get(key)?.size || 0;
|
||||
});
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
async Conversations(
|
||||
from: moment.Moment,
|
||||
to: moment.Moment,
|
||||
departmentId?: string,
|
||||
timezone = 'UTC',
|
||||
t = (v: string): string => v,
|
||||
extraQuery: Filter<IOmnichannelRoom> = {},
|
||||
) {
|
||||
const analyticsMap = new Map();
|
||||
let openConversations = 0; // open conversations
|
||||
let totalMessages = 0; // total msgs
|
||||
let totalConversations = 0; // Total conversations
|
||||
const days = to.diff(from, 'days') + 1; // total days
|
||||
|
||||
const date = {
|
||||
gte: moment.tz(from, timezone).startOf('day').utc(),
|
||||
lte: moment.tz(to, timezone).endOf('day').utc(),
|
||||
};
|
||||
|
||||
// @ts-expect-error - Check extraquery usage on this func
|
||||
const cursor = this.roomsModel.getAnalyticsBetweenDate(date, { departmentId }, extraQuery);
|
||||
|
||||
for await (const room of cursor) {
|
||||
totalConversations++;
|
||||
|
||||
if (room.metrics && !room.metrics.chatDuration && !room.onHold) {
|
||||
openConversations++;
|
||||
}
|
||||
const creationDay = moment.tz(room.ts, timezone).format('DD-MM-YYYY'); // @string: 01-01-2021
|
||||
const creationHour = moment.tz(room.ts, timezone).format('H'); // @int : 0, 1, ... 23
|
||||
|
||||
if (!analyticsMap.has(creationDay)) {
|
||||
analyticsMap.set(creationDay, new Map());
|
||||
}
|
||||
|
||||
const dayMap = analyticsMap.get(creationDay);
|
||||
|
||||
if (!dayMap.has(creationHour)) {
|
||||
dayMap.set(creationHour, 0);
|
||||
}
|
||||
|
||||
dayMap.set(creationHour, dayMap.get(creationHour) ? dayMap.get(creationHour) + room.msgs : room.msgs);
|
||||
totalMessages += room.msgs;
|
||||
}
|
||||
|
||||
// @ts-expect-error - Check extraquery usage on this func
|
||||
const onHoldConversations = await this.roomsModel.getOnHoldConversationsBetweenDate(from, to, departmentId, extraQuery);
|
||||
const busiestDayFromMap = this.getBusiestDay(analyticsMap); // returns busiest day based on the number of messages sent on that day
|
||||
const busiestHour = this.getKeyHavingMaxValue<number>(analyticsMap.get(busiestDayFromMap) || new Map(), -1); // returns key with max value
|
||||
const busiestTimeFrom = busiestHour >= 0 ? moment.tz(`${busiestHour}`, 'H', timezone).format('hA') : ''; // @string: 12AM, 1AM ...
|
||||
const busiestTimeTo = busiestHour >= 0 ? moment.tz(`${busiestHour}`, 'H', timezone).add(1, 'hour').format('hA') : ''; // @string: 1AM, 2AM ...
|
||||
const busiestDay = busiestDayFromMap !== '-' ? moment.tz(busiestDayFromMap, 'DD-MM-YYYY', timezone).format('dddd') : ''; // @string: Monday, Tuesday ...
|
||||
|
||||
return [
|
||||
{
|
||||
title: 'Total_conversations',
|
||||
value: totalConversations,
|
||||
},
|
||||
{
|
||||
title: 'Open_conversations',
|
||||
value: openConversations,
|
||||
},
|
||||
{
|
||||
title: 'On_Hold_conversations',
|
||||
value: onHoldConversations,
|
||||
},
|
||||
{
|
||||
title: 'Total_messages',
|
||||
value: totalMessages,
|
||||
},
|
||||
{
|
||||
title: 'Busiest_day',
|
||||
value: t(busiestDay) || '-',
|
||||
},
|
||||
{
|
||||
title: 'Conversations_per_day',
|
||||
value: (totalConversations / days).toFixed(2),
|
||||
},
|
||||
{
|
||||
title: 'Busiest_time',
|
||||
value: `${busiestTimeFrom}${busiestTimeTo ? ` - ${busiestTimeTo}` : ''}` || '-',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async Productivity(
|
||||
from: moment.Moment,
|
||||
to: moment.Moment,
|
||||
departmentId?: string,
|
||||
_timezone?: string,
|
||||
_t = (v: string): string => v,
|
||||
extraQuery?: Filter<IOmnichannelRoom>,
|
||||
) {
|
||||
let avgResponseTime = 0;
|
||||
let firstResponseTime = 0;
|
||||
let avgReactionTime = 0;
|
||||
let count = 0;
|
||||
|
||||
const date = {
|
||||
gte: from.toDate(),
|
||||
lte: to.toDate(),
|
||||
};
|
||||
|
||||
await this.roomsModel.getAnalyticsMetricsBetweenDate('l', date, { departmentId }, extraQuery).forEach(({ metrics }) => {
|
||||
if (metrics?.response && metrics.reaction) {
|
||||
avgResponseTime += metrics.response.avg;
|
||||
firstResponseTime += metrics.response.ft;
|
||||
avgReactionTime += metrics.reaction.ft;
|
||||
count++;
|
||||
}
|
||||
});
|
||||
|
||||
if (count) {
|
||||
avgResponseTime /= count;
|
||||
firstResponseTime /= count;
|
||||
avgReactionTime /= count;
|
||||
}
|
||||
|
||||
const data = [
|
||||
{
|
||||
title: 'Avg_response_time',
|
||||
value: secondsToHHMMSS(avgResponseTime.toFixed(2)),
|
||||
},
|
||||
{
|
||||
title: 'Avg_first_response_time',
|
||||
value: secondsToHHMMSS(firstResponseTime.toFixed(2)),
|
||||
},
|
||||
{
|
||||
title: 'Avg_reaction_time',
|
||||
value: secondsToHHMMSS(avgReactionTime.toFixed(2)),
|
||||
},
|
||||
];
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { Logger } from '@rocket.chat/logger';
|
||||
|
||||
export const serviceLogger = new Logger('OmnichannelAnalyticsService');
|
||||
175
apps/meteor/server/services/omnichannel-analytics/service.ts
Normal file
175
apps/meteor/server/services/omnichannel-analytics/service.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { ServiceClassInternal } from '@rocket.chat/core-services';
|
||||
import type {
|
||||
AgentOverviewDataOptions,
|
||||
AnalyticsOverviewDataOptions,
|
||||
ChartDataOptions,
|
||||
IOmnichannelAnalyticsService,
|
||||
} from '@rocket.chat/core-services';
|
||||
import { LivechatRooms } from '@rocket.chat/models';
|
||||
import moment from 'moment-timezone';
|
||||
|
||||
import { AgentOverviewData } from './AgentData';
|
||||
import { ChartData } from './ChartData';
|
||||
import { OverviewData } from './OverviewData';
|
||||
import { serviceLogger } from './logger';
|
||||
import { dayIterator } from './utils';
|
||||
import { callbacks } from '../../lib/callbacks';
|
||||
import { i18n } from '../../lib/i18n';
|
||||
import { getTimezone } from '../../lib/utils/lib/getTimezone';
|
||||
|
||||
const HOURS_IN_DAY = 24;
|
||||
|
||||
// TODO: move EE analytics to this service & remove callback usage
|
||||
export class OmnichannelAnalyticsService extends ServiceClassInternal implements IOmnichannelAnalyticsService {
|
||||
protected name = 'omnichannel-analytics';
|
||||
|
||||
readonly overview: OverviewData;
|
||||
|
||||
readonly chart: ChartData;
|
||||
|
||||
readonly agentOverview: AgentOverviewData;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.overview = new OverviewData(LivechatRooms);
|
||||
this.chart = new ChartData(LivechatRooms);
|
||||
this.agentOverview = new AgentOverviewData(LivechatRooms);
|
||||
}
|
||||
|
||||
async getAgentOverviewData(options: AgentOverviewDataOptions) {
|
||||
const { departmentId, utcOffset, daterange: { from: fDate, to: tDate } = {}, chartOptions: { name } = {}, executedBy } = options;
|
||||
const timezone = getTimezone({ utcOffset });
|
||||
const from = moment
|
||||
.tz(fDate || '', 'YYYY-MM-DD', timezone)
|
||||
.startOf('day')
|
||||
.utc();
|
||||
const to = moment
|
||||
.tz(tDate || '', 'YYYY-MM-DD', timezone)
|
||||
.endOf('day')
|
||||
.utc();
|
||||
|
||||
if (!moment(from).isValid() || !moment(to).isValid()) {
|
||||
serviceLogger.error('AgentOverview -> Invalid dates');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.agentOverview.isActionAllowed(name)) {
|
||||
serviceLogger.error({ msg: 'AgentOverview action is not valid', name });
|
||||
return;
|
||||
}
|
||||
|
||||
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {}, { userId: executedBy });
|
||||
return this.agentOverview.callAction(name, from, to, departmentId, extraQuery);
|
||||
}
|
||||
|
||||
async getAnalyticsChartData(options: ChartDataOptions) {
|
||||
const {
|
||||
utcOffset,
|
||||
departmentId,
|
||||
daterange: { from: fDate, to: tDate } = {},
|
||||
chartOptions: { name: chartLabel },
|
||||
executedBy,
|
||||
} = options;
|
||||
|
||||
// Check if function exists, prevent server error in case property altered
|
||||
if (!this.chart.isActionAllowed(chartLabel)) {
|
||||
serviceLogger.error({ msg: 'ChartData action is not valid', chartLabel });
|
||||
return;
|
||||
}
|
||||
|
||||
const timezone = getTimezone({ utcOffset });
|
||||
const from = moment
|
||||
.tz(fDate || '', 'YYYY-MM-DD', timezone)
|
||||
.startOf('day')
|
||||
.utc();
|
||||
const to = moment
|
||||
.tz(tDate || '', 'YYYY-MM-DD', timezone)
|
||||
.endOf('day')
|
||||
.utc();
|
||||
const isSameDay = from.diff(to, 'days') === 0;
|
||||
|
||||
if (!moment(from).isValid() || !moment(to).isValid()) {
|
||||
serviceLogger.error('ChartData -> Invalid dates');
|
||||
return;
|
||||
}
|
||||
|
||||
const data: {
|
||||
chartLabel: string;
|
||||
dataLabels: string[];
|
||||
dataPoints: number[];
|
||||
} = {
|
||||
chartLabel,
|
||||
dataLabels: [],
|
||||
dataPoints: [],
|
||||
};
|
||||
|
||||
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {}, { userId: executedBy });
|
||||
if (isSameDay) {
|
||||
// data for single day
|
||||
const m = moment(from);
|
||||
for await (const currentHour of Array.from({ length: HOURS_IN_DAY }, (_, i) => i)) {
|
||||
const hour = parseInt(m.add(currentHour ? 1 : 0, 'hour').format('H'));
|
||||
const label = {
|
||||
from: moment.utc().set({ hour }).tz(timezone).format('hA'),
|
||||
to: moment.utc().set({ hour }).endOf('hour').tz(timezone).format('hA'),
|
||||
};
|
||||
data.dataLabels.push(`${label.from}-${label.to}`);
|
||||
|
||||
const date = {
|
||||
gte: m.toDate(),
|
||||
lte: moment(m).endOf('hour').toDate(),
|
||||
};
|
||||
|
||||
data.dataPoints.push(await this.chart.callAction(chartLabel, date, departmentId, extraQuery));
|
||||
}
|
||||
} else {
|
||||
for await (const m of dayIterator(from, to)) {
|
||||
data.dataLabels.push(m.format('M/D'));
|
||||
|
||||
const date = {
|
||||
gte: m.toDate(),
|
||||
lte: moment(m).endOf('day').toDate(),
|
||||
};
|
||||
|
||||
data.dataPoints.push(await this.chart.callAction(chartLabel, date, departmentId, extraQuery));
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async getAnalyticsOverviewData(options: AnalyticsOverviewDataOptions) {
|
||||
const {
|
||||
departmentId,
|
||||
utcOffset = 0,
|
||||
language,
|
||||
daterange: { from: fDate, to: tDate } = {},
|
||||
analyticsOptions: { name } = {},
|
||||
executedBy,
|
||||
} = options;
|
||||
const timezone = getTimezone({ utcOffset });
|
||||
const from = moment
|
||||
.tz(fDate || '', 'YYYY-MM-DD', timezone)
|
||||
.startOf('day')
|
||||
.utc();
|
||||
const to = moment
|
||||
.tz(tDate || '', 'YYYY-MM-DD', timezone)
|
||||
.endOf('day')
|
||||
.utc();
|
||||
|
||||
if (!moment(from).isValid() || !moment(to).isValid()) {
|
||||
serviceLogger.error('OverviewData -> Invalid dates');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.overview.isActionAllowed(name)) {
|
||||
serviceLogger.error({ msg: 'OverviewData action is not valid', name });
|
||||
return;
|
||||
}
|
||||
|
||||
const t = i18n.getFixedT(language);
|
||||
|
||||
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {}, { userId: executedBy });
|
||||
return this.overview.callAction(name, from, to, departmentId, timezone, t, extraQuery);
|
||||
}
|
||||
}
|
||||
30
apps/meteor/server/services/omnichannel-analytics/utils.ts
Normal file
30
apps/meteor/server/services/omnichannel-analytics/utils.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import moment from 'moment-timezone';
|
||||
|
||||
const HOURS_IN_DAY = 24;
|
||||
|
||||
export async function* dayIterator(from: moment.Moment, to: moment.Moment): AsyncGenerator<moment.Moment> {
|
||||
const m = from.clone().startOf('day');
|
||||
const f = to.clone().startOf('day');
|
||||
while (m.diff(f, 'days') <= 0) {
|
||||
yield m;
|
||||
m.add(1, 'days');
|
||||
}
|
||||
}
|
||||
|
||||
export async function* weekIterator(from: moment.Moment, to: moment.Moment, timezone: string): AsyncGenerator<moment.Moment> {
|
||||
const m = moment.tz(from, timezone);
|
||||
while (m.diff(to, 'weeks') <= 0) {
|
||||
yield moment(m);
|
||||
m.add(1, 'weeks');
|
||||
}
|
||||
}
|
||||
|
||||
export async function* hourIterator(day: moment.Moment): AsyncGenerator<moment.Moment> {
|
||||
const m = moment(day).startOf('day');
|
||||
let passedHours = 0;
|
||||
while (passedHours < HOURS_IN_DAY) {
|
||||
yield moment(m);
|
||||
m.add(1, 'hours');
|
||||
passedHours++;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user