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:
9
apps/meteor/ee/server/models/raw/AuditLog.ts
Normal file
9
apps/meteor/ee/server/models/raw/AuditLog.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { RocketChatRecordDeleted, IAuditLog } from '@rocket.chat/core-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { Collection, Db } from 'mongodb';
|
||||
|
||||
export class AuditLogRaw extends BaseRaw<IAuditLog> {
|
||||
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<IAuditLog>>) {
|
||||
super(db, 'audit_log', trash);
|
||||
}
|
||||
}
|
||||
115
apps/meteor/ee/server/models/raw/CannedResponse.ts
Normal file
115
apps/meteor/ee/server/models/raw/CannedResponse.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import type { IOmnichannelCannedResponse } from '@rocket.chat/core-typings';
|
||||
import type { ICannedResponseModel, DocumentWithProjection, FindOptionsWithProjection } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { Db, DeleteResult, FindCursor, IndexDescription, UpdateFilter, Document } from 'mongodb';
|
||||
|
||||
// TODO need to define type for CannedResponse object
|
||||
export class CannedResponseRaw extends BaseRaw<IOmnichannelCannedResponse> implements ICannedResponseModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'canned_response');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [
|
||||
{
|
||||
key: {
|
||||
shortcut: 1,
|
||||
},
|
||||
unique: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async updateCannedResponse(
|
||||
_id: string,
|
||||
{ shortcut, text, tags, scope, userId, departmentId, createdBy }: Omit<IOmnichannelCannedResponse, '_id' | '_updatedAt' | '_createdAt'>,
|
||||
): Promise<Omit<IOmnichannelCannedResponse, '_updatedAt' | '_createdAt'>> {
|
||||
const record = {
|
||||
shortcut,
|
||||
text,
|
||||
scope,
|
||||
tags,
|
||||
userId,
|
||||
departmentId,
|
||||
createdBy,
|
||||
};
|
||||
|
||||
await this.updateOne({ _id }, { $set: record });
|
||||
|
||||
return Object.assign(record, { _id });
|
||||
}
|
||||
|
||||
async createCannedResponse({
|
||||
shortcut,
|
||||
text,
|
||||
tags,
|
||||
scope,
|
||||
userId,
|
||||
departmentId,
|
||||
createdBy,
|
||||
_createdAt,
|
||||
}: Omit<IOmnichannelCannedResponse, '_id' | '_updatedAt'>): Promise<Omit<IOmnichannelCannedResponse, '_updatedAt'>> {
|
||||
const record = {
|
||||
shortcut,
|
||||
text,
|
||||
scope,
|
||||
tags,
|
||||
userId,
|
||||
departmentId,
|
||||
createdBy,
|
||||
_createdAt,
|
||||
};
|
||||
|
||||
const _id = (await this.insertOne(record)).insertedId;
|
||||
return Object.assign(record, { _id });
|
||||
}
|
||||
|
||||
override findOneById<
|
||||
P extends Document = IOmnichannelCannedResponse,
|
||||
O extends FindOptionsWithProjection<P> = FindOptionsWithProjection<P>,
|
||||
>(_id: string, options?: O): Promise<DocumentWithProjection<P, O> | null> {
|
||||
const query = { _id };
|
||||
|
||||
return this.findOne<P, O>(query, options);
|
||||
}
|
||||
|
||||
findOneByShortcut<T extends Document = IOmnichannelCannedResponse, O extends FindOptionsWithProjection<T> = FindOptionsWithProjection<T>>(
|
||||
shortcut: string,
|
||||
options?: O,
|
||||
): Promise<DocumentWithProjection<T, O> | null> {
|
||||
const query = {
|
||||
shortcut,
|
||||
};
|
||||
|
||||
return this.findOne<T, O>(query, options);
|
||||
}
|
||||
|
||||
findByDepartmentId<
|
||||
T extends Document = IOmnichannelCannedResponse,
|
||||
O extends FindOptionsWithProjection<T> = FindOptionsWithProjection<T>,
|
||||
>(departmentId: string, options?: O): FindCursor<DocumentWithProjection<T, O>> {
|
||||
const query = {
|
||||
scope: 'department',
|
||||
departmentId,
|
||||
};
|
||||
|
||||
return this.find<T, O>(query, options);
|
||||
}
|
||||
|
||||
// REMOVE
|
||||
override removeById(_id: string): Promise<DeleteResult> {
|
||||
const query = { _id };
|
||||
|
||||
return this.deleteOne(query);
|
||||
}
|
||||
|
||||
removeTagFromCannedResponses(tagId: string) {
|
||||
const update: UpdateFilter<IOmnichannelCannedResponse> = {
|
||||
$pull: {
|
||||
tags: tagId,
|
||||
},
|
||||
};
|
||||
|
||||
return this.updateMany({ tags: tagId }, update);
|
||||
}
|
||||
}
|
||||
95
apps/meteor/ee/server/models/raw/LivechatDepartment.ts
Normal file
95
apps/meteor/ee/server/models/raw/LivechatDepartment.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import type { ILivechatDepartment, RocketChatRecordDeleted, LivechatDepartmentDTO } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatDepartmentModel, DocumentWithProjection, FindOptionsWithProjection } from '@rocket.chat/model-typings';
|
||||
import { LivechatDepartmentRaw } from '@rocket.chat/models';
|
||||
import type { Collection, Document, FindCursor, FindOptions, UpdateResult, Db, AggregationCursor } from 'mongodb';
|
||||
|
||||
declare module '@rocket.chat/model-typings' {
|
||||
interface ILivechatDepartmentModel {
|
||||
removeDepartmentFromForwardListById(departmentId: string): Promise<void>;
|
||||
removeParentAndAncestorById(id: string): Promise<UpdateResult | Document>;
|
||||
findEnabledWithAgentsAndBusinessUnit<T extends Document = ILivechatDepartment>(
|
||||
businessUnit?: string,
|
||||
projection?: FindOptions<T>['projection'],
|
||||
): FindCursor<T>;
|
||||
findByParentId(parentId: string, options?: FindOptions<ILivechatDepartment>): FindCursor<ILivechatDepartment>;
|
||||
findAgentsByBusinessHourId(businessHourId: string): AggregationCursor<{ agentIds: string[] }>;
|
||||
}
|
||||
}
|
||||
|
||||
export class LivechatDepartmentEE extends LivechatDepartmentRaw implements ILivechatDepartmentModel {
|
||||
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<ILivechatDepartment>>) {
|
||||
super(db, trash);
|
||||
}
|
||||
|
||||
override async removeDepartmentFromForwardListById(departmentId: string): Promise<void> {
|
||||
await this.updateMany({ departmentsAllowedToForward: departmentId }, { $pull: { departmentsAllowedToForward: departmentId } });
|
||||
}
|
||||
|
||||
override createOrUpdateDepartment(_id: string | null, data: LivechatDepartmentDTO): Promise<ILivechatDepartment> {
|
||||
return super.createOrUpdateDepartment(_id, { ...data, type: 'd' });
|
||||
}
|
||||
|
||||
override removeParentAndAncestorById(id: string): Promise<UpdateResult | Document> {
|
||||
return this.updateMany({ parentId: id }, { $unset: { parentId: 1 }, $pull: { ancestors: id } });
|
||||
}
|
||||
|
||||
override findActiveByUnitIds<
|
||||
T extends Document = ILivechatDepartment,
|
||||
O extends FindOptionsWithProjection<T> = FindOptionsWithProjection<T>,
|
||||
>(unitIds: string[], options?: O): FindCursor<DocumentWithProjection<T, O>> {
|
||||
const query = {
|
||||
enabled: true,
|
||||
numAgents: { $gt: 0 },
|
||||
parentId: {
|
||||
$exists: true,
|
||||
$in: unitIds,
|
||||
},
|
||||
};
|
||||
|
||||
return this.find<T, O>(query, options);
|
||||
}
|
||||
|
||||
override findEnabledWithAgentsAndBusinessUnit<T extends Document = ILivechatDepartment>(
|
||||
businessUnit?: string,
|
||||
projection?: FindOptions<T>['projection'],
|
||||
): FindCursor<T> {
|
||||
if (!businessUnit) {
|
||||
return super.findEnabledWithAgents<T>(projection);
|
||||
}
|
||||
|
||||
return this.findActiveByUnitIds<T>([businessUnit], { projection });
|
||||
}
|
||||
|
||||
override findByParentId(parentId: string, options?: FindOptions<ILivechatDepartment>): FindCursor<ILivechatDepartment> {
|
||||
return this.col.find({ parentId }, options);
|
||||
}
|
||||
|
||||
override findAgentsByBusinessHourId(businessHourId: string): AggregationCursor<{ agentIds: string[] }> {
|
||||
return this.col.aggregate<{ agentIds: string[] }>([
|
||||
{
|
||||
$match: {
|
||||
businessHourId,
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'rocketchat_livechat_department_agents',
|
||||
localField: '_id',
|
||||
foreignField: 'departmentId',
|
||||
as: 'agents',
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: '$agents',
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
agentIds: {
|
||||
$addToSet: '$agents.agentId',
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
94
apps/meteor/ee/server/models/raw/LivechatInquiry.ts
Normal file
94
apps/meteor/ee/server/models/raw/LivechatInquiry.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { ILivechatInquiryRecord, ILivechatPriority } from '@rocket.chat/core-typings';
|
||||
import { DEFAULT_SLA_CONFIG, LivechatPriorityWeight } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatInquiryModel } from '@rocket.chat/model-typings';
|
||||
import { LivechatInquiryRaw } from '@rocket.chat/models';
|
||||
import type { UpdateResult, Document, WithId } from 'mongodb';
|
||||
|
||||
declare module '@rocket.chat/model-typings' {
|
||||
interface ILivechatInquiryModel {
|
||||
setSlaForRoom(rid: string, sla: { estimatedWaitingTimeQueue: number; slaId: string }): Promise<null | WithId<ILivechatInquiryRecord>>;
|
||||
unsetSlaForRoom(rid: string): Promise<null | WithId<ILivechatInquiryRecord>>;
|
||||
bulkUnsetSla(roomIds: string[]): Promise<Document | UpdateResult>;
|
||||
setPriorityForRoom(rid: string, priority: Pick<ILivechatPriority, '_id' | 'sortItem'>): Promise<null | WithId<ILivechatInquiryRecord>>;
|
||||
unsetPriorityForRoom(rid: string): Promise<null | WithId<ILivechatInquiryRecord>>;
|
||||
}
|
||||
}
|
||||
|
||||
// Note: Expect a circular dependency error here 😓
|
||||
export class LivechatInquiryRawEE extends LivechatInquiryRaw implements ILivechatInquiryModel {
|
||||
override setSlaForRoom(
|
||||
rid: string,
|
||||
sla: { estimatedWaitingTimeQueue: number; slaId: string },
|
||||
): Promise<null | WithId<ILivechatInquiryRecord>> {
|
||||
const { estimatedWaitingTimeQueue, slaId } = sla;
|
||||
|
||||
return this.findOneAndUpdate(
|
||||
{ rid },
|
||||
{
|
||||
$set: {
|
||||
slaId,
|
||||
estimatedWaitingTimeQueue,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override unsetSlaForRoom(rid: string): Promise<null | WithId<ILivechatInquiryRecord>> {
|
||||
return this.findOneAndUpdate(
|
||||
{ rid },
|
||||
{
|
||||
$unset: {
|
||||
slaId: 1,
|
||||
},
|
||||
$set: {
|
||||
estimatedWaitingTimeQueue: DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override bulkUnsetSla(roomIds: string[]): Promise<Document | UpdateResult> {
|
||||
return this.updateMany(
|
||||
{
|
||||
rid: { $in: roomIds },
|
||||
},
|
||||
{
|
||||
$unset: {
|
||||
slaId: 1,
|
||||
},
|
||||
$set: {
|
||||
estimatedWaitingTimeQueue: DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override setPriorityForRoom(
|
||||
rid: string,
|
||||
priority: Pick<ILivechatPriority, '_id' | 'sortItem'>,
|
||||
): Promise<null | WithId<ILivechatInquiryRecord>> {
|
||||
return this.findOneAndUpdate(
|
||||
{ rid },
|
||||
{
|
||||
$set: {
|
||||
priorityId: priority._id,
|
||||
priorityWeight: priority.sortItem,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override unsetPriorityForRoom(rid: string): Promise<null | WithId<ILivechatInquiryRecord>> {
|
||||
return this.findOneAndUpdate(
|
||||
{ rid },
|
||||
{
|
||||
$unset: {
|
||||
priorityId: 1,
|
||||
},
|
||||
$set: {
|
||||
priorityWeight: LivechatPriorityWeight.NOT_SPECIFIED,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
749
apps/meteor/ee/server/models/raw/LivechatRooms.ts
Normal file
749
apps/meteor/ee/server/models/raw/LivechatRooms.ts
Normal file
@@ -0,0 +1,749 @@
|
||||
import type {
|
||||
ILivechatPriority,
|
||||
IOmnichannelRoom,
|
||||
IOmnichannelServiceLevelAgreements,
|
||||
RocketChatRecordDeleted,
|
||||
ReportResult,
|
||||
ILivechatContact,
|
||||
} from '@rocket.chat/core-typings';
|
||||
import { LivechatPriorityWeight, DEFAULT_SLA_CONFIG } from '@rocket.chat/core-typings';
|
||||
import type { FindPaginated, ILivechatRoomsModel } from '@rocket.chat/model-typings';
|
||||
import type { Updater } from '@rocket.chat/models';
|
||||
import { LivechatRoomsRaw } from '@rocket.chat/models';
|
||||
import { escapeRegExp } from '@rocket.chat/tools';
|
||||
import type { FindCursor, UpdateResult, Document, FindOptions, Db, Collection, Filter, AggregationCursor, UpdateOptions } from 'mongodb';
|
||||
|
||||
import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred';
|
||||
|
||||
declare module '@rocket.chat/model-typings' {
|
||||
interface ILivechatRoomsModel {
|
||||
associateRoomsWithDepartmentToUnit: (departments: string[], unit: string) => Promise<void>;
|
||||
removeUnitAssociationFromRooms: (unit: string) => Promise<void>;
|
||||
updateDepartmentAncestorsById: (rid: string, ancestors?: string[]) => Promise<UpdateResult>;
|
||||
unsetPredictedVisitorAbandonmentByRoomId(rid: string): Promise<UpdateResult>;
|
||||
findAbandonedOpenRooms(date: Date, extraQuery?: Filter<IOmnichannelRoom>): FindCursor<IOmnichannelRoom>;
|
||||
setPredictedVisitorAbandonmentByRoomId(roomId: string, date: Date): Promise<UpdateResult>;
|
||||
getPredictedVisitorAbandonmentByRoomIdUpdateQuery(date: Date, roomUpdater: Updater<IOmnichannelRoom>): Updater<IOmnichannelRoom>;
|
||||
unsetAllPredictedVisitorAbandonment(): Promise<void>;
|
||||
setOnHoldByRoomId(roomId: string): Promise<UpdateResult>;
|
||||
unsetOnHoldByRoomId(roomId: string): Promise<UpdateResult>;
|
||||
setSlaForRoomById(
|
||||
roomId: string,
|
||||
sla: Pick<IOmnichannelServiceLevelAgreements, '_id' | 'dueTimeInMinutes'>,
|
||||
): Promise<UpdateResult | Document>;
|
||||
removeSlaFromRoomById(roomId: string): Promise<UpdateResult | Document>;
|
||||
bulkRemoveSlaFromRoomsById(slaId: string): Promise<UpdateResult | Document>;
|
||||
findOpenBySlaId(
|
||||
slaId: string,
|
||||
options: FindOptions<IOmnichannelRoom>,
|
||||
extraQuery?: Filter<IOmnichannelRoom>,
|
||||
): FindCursor<IOmnichannelRoom>;
|
||||
setPriorityByRoomId(roomId: string, priority: Pick<ILivechatPriority, '_id' | 'sortItem'>): Promise<UpdateResult>;
|
||||
unsetPriorityByRoomId(roomId: string): Promise<UpdateResult>;
|
||||
countPrioritizedRooms(): Promise<number>;
|
||||
countRoomsWithSla(): Promise<number>;
|
||||
countRoomsWithTranscriptSent(): Promise<number>;
|
||||
getConversationsBySource(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): AggregationCursor<ReportResult>;
|
||||
getConversationsByStatus(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): AggregationCursor<ReportResult>;
|
||||
getConversationsByDepartment(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult>;
|
||||
getConversationsByTags(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult>;
|
||||
getConversationsByAgents(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult>;
|
||||
getConversationsWithoutTagsBetweenDate(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): Promise<number>;
|
||||
getTotalConversationsWithoutAgentsBetweenDate(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): Promise<number>;
|
||||
getTotalConversationsWithoutDepartmentBetweenDates(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): Promise<number>;
|
||||
updateMergedContactIds(
|
||||
contactIdsThatWereMerged: ILivechatContact['_id'][],
|
||||
newContactId: ILivechatContact['_id'],
|
||||
options?: UpdateOptions,
|
||||
): Promise<UpdateResult | Document>;
|
||||
}
|
||||
}
|
||||
|
||||
export class LivechatRoomsRawEE extends LivechatRoomsRaw implements ILivechatRoomsModel {
|
||||
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<IOmnichannelRoom>>) {
|
||||
super(db, trash);
|
||||
}
|
||||
|
||||
override countPrioritizedRooms(): Promise<number> {
|
||||
return this.countDocuments({ priorityId: { $exists: true } });
|
||||
}
|
||||
|
||||
override countRoomsWithSla(): Promise<number> {
|
||||
return this.countDocuments({ slaId: { $exists: true } });
|
||||
}
|
||||
|
||||
override countRoomsWithTranscriptSent(): Promise<number> {
|
||||
return this.countDocuments({ pdfTranscriptFileId: { $exists: true } });
|
||||
}
|
||||
|
||||
override async unsetAllPredictedVisitorAbandonment(): Promise<void> {
|
||||
return this.updateMany(
|
||||
{
|
||||
'open': true,
|
||||
't': 'l',
|
||||
'omnichannel.predictedVisitorAbandonmentAt': { $exists: true },
|
||||
},
|
||||
{
|
||||
$unset: { 'omnichannel.predictedVisitorAbandonmentAt': 1 },
|
||||
},
|
||||
).then();
|
||||
}
|
||||
|
||||
override setOnHoldByRoomId(roomId: string): Promise<UpdateResult> {
|
||||
return this.updateOne({ _id: roomId }, { $set: { onHold: true } });
|
||||
}
|
||||
|
||||
override unsetOnHoldByRoomId(roomId: string): Promise<UpdateResult> {
|
||||
return this.updateOne({ _id: roomId }, { $unset: { onHold: 1 } });
|
||||
}
|
||||
|
||||
override setSlaForRoomById(
|
||||
roomId: string,
|
||||
sla: Pick<IOmnichannelServiceLevelAgreements, '_id' | 'dueTimeInMinutes'>,
|
||||
): Promise<UpdateResult | Document> {
|
||||
const { _id: slaId, dueTimeInMinutes } = sla;
|
||||
|
||||
return this.updateOne(
|
||||
{
|
||||
_id: roomId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
slaId,
|
||||
estimatedWaitingTimeQueue: dueTimeInMinutes,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override removeSlaFromRoomById(roomId: string): Promise<UpdateResult | Document> {
|
||||
return this.updateOne(
|
||||
{
|
||||
_id: roomId,
|
||||
},
|
||||
{
|
||||
$unset: {
|
||||
slaId: 1,
|
||||
},
|
||||
$set: {
|
||||
estimatedWaitingTimeQueue: DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override bulkRemoveSlaFromRoomsById(slaId: string): Promise<UpdateResult | Document> {
|
||||
return this.updateMany(
|
||||
{
|
||||
open: true,
|
||||
t: 'l',
|
||||
slaId,
|
||||
},
|
||||
{
|
||||
$unset: { slaId: 1 },
|
||||
$set: {
|
||||
estimatedWaitingTimeQueue: DEFAULT_SLA_CONFIG.ESTIMATED_WAITING_TIME_QUEUE,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override findOpenBySlaId(
|
||||
slaId: string,
|
||||
options: FindOptions<IOmnichannelRoom>,
|
||||
extraQuery?: Filter<IOmnichannelRoom>,
|
||||
): FindCursor<IOmnichannelRoom> {
|
||||
const query = {
|
||||
t: 'l' as const,
|
||||
open: true,
|
||||
slaId,
|
||||
...extraQuery,
|
||||
};
|
||||
|
||||
return this.find(query, options);
|
||||
}
|
||||
|
||||
override async setPriorityByRoomId(roomId: string, priority: Pick<ILivechatPriority, '_id' | 'sortItem'>): Promise<UpdateResult> {
|
||||
const { _id: priorityId, sortItem: priorityWeight } = priority;
|
||||
|
||||
return this.updateOne({ _id: roomId }, { $set: { priorityId, priorityWeight } });
|
||||
}
|
||||
|
||||
override async unsetPriorityByRoomId(roomId: string): Promise<UpdateResult> {
|
||||
return this.updateOne(
|
||||
{ _id: roomId },
|
||||
{
|
||||
$unset: {
|
||||
priorityId: 1,
|
||||
},
|
||||
$set: {
|
||||
priorityWeight: LivechatPriorityWeight.NOT_SPECIFIED,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override getPredictedVisitorAbandonmentByRoomIdUpdateQuery(
|
||||
date: Date,
|
||||
roomUpdater: Updater<IOmnichannelRoom> = this.getUpdater(),
|
||||
): Updater<IOmnichannelRoom> {
|
||||
return roomUpdater.set('omnichannel.predictedVisitorAbandonmentAt', date);
|
||||
}
|
||||
|
||||
override setPredictedVisitorAbandonmentByRoomId(rid: string, willBeAbandonedAt: Date): Promise<UpdateResult> {
|
||||
const query = {
|
||||
_id: rid,
|
||||
};
|
||||
const update = {
|
||||
$set: {
|
||||
'omnichannel.predictedVisitorAbandonmentAt': willBeAbandonedAt,
|
||||
},
|
||||
};
|
||||
|
||||
return this.updateOne(query, update);
|
||||
}
|
||||
|
||||
override findAbandonedOpenRooms(date: Date, extraQuery?: Filter<IOmnichannelRoom>): FindCursor<IOmnichannelRoom> {
|
||||
return this.find({
|
||||
'omnichannel.predictedVisitorAbandonmentAt': { $lte: date },
|
||||
'waitingResponse': { $exists: false },
|
||||
'closedAt': { $exists: false },
|
||||
'open': true,
|
||||
...extraQuery,
|
||||
});
|
||||
}
|
||||
|
||||
override async unsetPredictedVisitorAbandonmentByRoomId(roomId: string): Promise<UpdateResult> {
|
||||
return this.updateOne(
|
||||
{
|
||||
_id: roomId,
|
||||
},
|
||||
{
|
||||
$unset: { 'omnichannel.predictedVisitorAbandonmentAt': 1 },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
override async associateRoomsWithDepartmentToUnit(departments: string[], unitId: string): Promise<void> {
|
||||
const query = {
|
||||
$and: [
|
||||
{
|
||||
departmentId: { $in: departments },
|
||||
},
|
||||
{
|
||||
$or: [
|
||||
{
|
||||
departmentAncestors: { $exists: false },
|
||||
},
|
||||
{
|
||||
$and: [
|
||||
{
|
||||
departmentAncestors: { $exists: true },
|
||||
},
|
||||
{
|
||||
departmentAncestors: { $ne: unitId },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const update = { $set: { departmentAncestors: [unitId] } };
|
||||
await this.updateMany(query, update);
|
||||
|
||||
const queryToDisassociateOldRoomsConnectedToUnit = {
|
||||
departmentAncestors: unitId,
|
||||
departmentId: { $nin: departments },
|
||||
};
|
||||
const updateToDisassociateRooms = { $unset: { departmentAncestors: 1 } };
|
||||
await this.updateMany(queryToDisassociateOldRoomsConnectedToUnit, updateToDisassociateRooms);
|
||||
}
|
||||
|
||||
override async removeUnitAssociationFromRooms(unitId: string): Promise<void> {
|
||||
const query = {
|
||||
departmentAncestors: unitId,
|
||||
};
|
||||
const update = { $unset: { departmentAncestors: 1 } };
|
||||
await this.updateMany(query, update);
|
||||
}
|
||||
|
||||
override async updateDepartmentAncestorsById(rid: string, departmentAncestors?: string[]) {
|
||||
const query = {
|
||||
_id: rid,
|
||||
};
|
||||
const update = departmentAncestors ? { $set: { departmentAncestors } } : { $unset: { departmentAncestors: 1 } };
|
||||
return this.updateOne(query, update);
|
||||
}
|
||||
|
||||
override getConversationsBySource(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): AggregationCursor<ReportResult> {
|
||||
return this.col.aggregate(
|
||||
[
|
||||
{
|
||||
$match: {
|
||||
source: {
|
||||
$exists: true,
|
||||
},
|
||||
t: 'l',
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
...extraQuery,
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
type: '$source.type',
|
||||
alias: '$source.alias',
|
||||
},
|
||||
value: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: { value: -1 },
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: '$value' },
|
||||
data: {
|
||||
$push: {
|
||||
label: {
|
||||
$ifNull: ['$_id.alias', '$_id.type'],
|
||||
},
|
||||
value: '$value',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
{ hint: 'source_1_ts_1', readPreference: readSecondaryPreferred() },
|
||||
);
|
||||
}
|
||||
|
||||
override getConversationsByStatus(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): AggregationCursor<ReportResult> {
|
||||
return this.col.aggregate(
|
||||
[
|
||||
{
|
||||
$match: {
|
||||
t: 'l',
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
...extraQuery,
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: 1 },
|
||||
open: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{
|
||||
$and: [
|
||||
{ $eq: ['$open', true] },
|
||||
{
|
||||
$or: [{ $not: ['$onHold'] }, { $eq: ['$onHold', false] }],
|
||||
},
|
||||
{ $ifNull: ['$servedBy', false] },
|
||||
],
|
||||
},
|
||||
1,
|
||||
0,
|
||||
],
|
||||
},
|
||||
},
|
||||
closed: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{
|
||||
$ifNull: ['$metrics.chatDuration', false],
|
||||
},
|
||||
1,
|
||||
0,
|
||||
],
|
||||
},
|
||||
},
|
||||
queued: {
|
||||
$sum: {
|
||||
$cond: [
|
||||
{
|
||||
$and: [
|
||||
{ $eq: ['$open', true] },
|
||||
{
|
||||
$eq: [
|
||||
{
|
||||
$ifNull: ['$servedBy', null],
|
||||
},
|
||||
null,
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
1,
|
||||
0,
|
||||
],
|
||||
},
|
||||
},
|
||||
onhold: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ['$onHold', true] }, 1, 0],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
total: 1,
|
||||
data: [
|
||||
{ label: 'Open', value: '$open' },
|
||||
{ label: 'Closed', value: '$closed' },
|
||||
{ label: 'Queued', value: '$queued' },
|
||||
{ label: 'On_Hold', value: '$onhold' },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: '$data',
|
||||
},
|
||||
{
|
||||
$sort: { 'data.value': -1 },
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$_id',
|
||||
total: { $first: '$total' },
|
||||
data: { $push: '$data' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
{ readPreference: readSecondaryPreferred() },
|
||||
);
|
||||
}
|
||||
|
||||
override getConversationsByDepartment(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult> {
|
||||
return this.col.aggregate(
|
||||
[
|
||||
{
|
||||
$match: {
|
||||
t: 'l',
|
||||
departmentId: {
|
||||
$exists: true,
|
||||
},
|
||||
ts: {
|
||||
$lt: end,
|
||||
$gte: start,
|
||||
},
|
||||
...extraQuery,
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$departmentId',
|
||||
total: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'rocketchat_livechat_department',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'department',
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$arrayElemAt: ['$department.name', 0],
|
||||
},
|
||||
total: {
|
||||
$sum: '$total',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$match: {
|
||||
_id: {
|
||||
$ne: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: sort || { total: 1 },
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: '$total' },
|
||||
data: {
|
||||
$push: {
|
||||
label: '$_id',
|
||||
value: '$total',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
{ hint: 'departmentId_1_ts_1', readPreference: readSecondaryPreferred() },
|
||||
);
|
||||
}
|
||||
|
||||
override getTotalConversationsWithoutDepartmentBetweenDates(
|
||||
start: Date,
|
||||
end: Date,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): Promise<number> {
|
||||
return this.countDocuments({
|
||||
t: 'l',
|
||||
departmentId: {
|
||||
$exists: false,
|
||||
},
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
...extraQuery,
|
||||
});
|
||||
}
|
||||
|
||||
override getConversationsByTags(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult> {
|
||||
return this.col.aggregate(
|
||||
[
|
||||
{
|
||||
$match: {
|
||||
t: 'l',
|
||||
ts: {
|
||||
$lt: end,
|
||||
$gte: start,
|
||||
},
|
||||
tags: {
|
||||
$exists: true,
|
||||
$ne: [],
|
||||
},
|
||||
...extraQuery,
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$tags',
|
||||
total: {
|
||||
$sum: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$unwind: '$_id',
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$_id',
|
||||
total: { $sum: '$total' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: sort || { total: 1 },
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: '$total' },
|
||||
data: {
|
||||
$push: {
|
||||
label: '$_id',
|
||||
value: '$total',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
{ hint: 'tags.0_1_ts_1', readPreference: readSecondaryPreferred() },
|
||||
);
|
||||
}
|
||||
|
||||
override getConversationsWithoutTagsBetweenDate(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): Promise<number> {
|
||||
return this.countDocuments({
|
||||
t: 'l',
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
$or: [
|
||||
{
|
||||
tags: {
|
||||
$exists: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
tags: {
|
||||
$eq: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
...extraQuery,
|
||||
});
|
||||
}
|
||||
|
||||
override getConversationsByAgents(
|
||||
start: Date,
|
||||
end: Date,
|
||||
sort: Record<string, 1 | -1>,
|
||||
extraQuery: Filter<IOmnichannelRoom>,
|
||||
): AggregationCursor<ReportResult> {
|
||||
return this.col.aggregate(
|
||||
[
|
||||
{
|
||||
$match: {
|
||||
t: 'l',
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
servedBy: {
|
||||
$exists: true,
|
||||
},
|
||||
...extraQuery,
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: '$servedBy._id',
|
||||
total: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: 'users',
|
||||
localField: '_id',
|
||||
foreignField: '_id',
|
||||
as: 'agent',
|
||||
},
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
agent: { $first: '$agent' },
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
name: {
|
||||
$ifNull: ['$agent.name', '$_id'],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: sort || { name: 1 },
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: '$total' },
|
||||
data: {
|
||||
$push: {
|
||||
label: '$name',
|
||||
value: '$total',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
{ hint: 'servedBy_1_ts_1', readPreference: readSecondaryPreferred() },
|
||||
);
|
||||
}
|
||||
|
||||
override getTotalConversationsWithoutAgentsBetweenDate(start: Date, end: Date, extraQuery: Filter<IOmnichannelRoom>): Promise<number> {
|
||||
return this.countDocuments({
|
||||
t: 'l',
|
||||
ts: {
|
||||
$gte: start,
|
||||
$lt: end,
|
||||
},
|
||||
servedBy: {
|
||||
$exists: false,
|
||||
},
|
||||
...extraQuery,
|
||||
});
|
||||
}
|
||||
|
||||
override updateMergedContactIds(
|
||||
contactIdsThatWereMerged: ILivechatContact['_id'][],
|
||||
newContactId: ILivechatContact['_id'],
|
||||
options?: UpdateOptions,
|
||||
): Promise<UpdateResult | Document> {
|
||||
return this.updateMany({ contactId: { $in: contactIdsThatWereMerged } }, { $set: { contactId: newContactId } }, options);
|
||||
}
|
||||
|
||||
override findClosedRoomsByContactAndSourcePaginated({
|
||||
contactId,
|
||||
source,
|
||||
options = {},
|
||||
}: {
|
||||
contactId: string;
|
||||
source?: string;
|
||||
options?: FindOptions;
|
||||
}): FindPaginated<FindCursor<IOmnichannelRoom>> {
|
||||
return this.findPaginated<IOmnichannelRoom>(
|
||||
{
|
||||
contactId,
|
||||
closedAt: { $exists: true },
|
||||
...(source && {
|
||||
$or: [{ 'source.type': new RegExp(escapeRegExp(source), 'i') }, { 'source.alias': new RegExp(escapeRegExp(source), 'i') }],
|
||||
}),
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
50
apps/meteor/ee/server/models/raw/LivechatTag.ts
Normal file
50
apps/meteor/ee/server/models/raw/LivechatTag.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { ILivechatTag } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatTagModel } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { Db, DeleteResult, IndexDescription } from 'mongodb';
|
||||
|
||||
export class LivechatTagRaw extends BaseRaw<ILivechatTag> implements ILivechatTagModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'livechat_tag');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [
|
||||
{
|
||||
key: {
|
||||
name: 1,
|
||||
},
|
||||
unique: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async createOrUpdateTag(
|
||||
_id: string | undefined,
|
||||
{ name, description }: { name: string; description?: string },
|
||||
departments: string[] = [],
|
||||
): Promise<Omit<ILivechatTag, '_updatedAt'>> {
|
||||
const record = {
|
||||
name,
|
||||
description,
|
||||
numDepartments: departments.length,
|
||||
departments,
|
||||
};
|
||||
|
||||
if (_id) {
|
||||
await this.updateOne({ _id }, { $set: record });
|
||||
} else {
|
||||
_id = (await this.insertOne(record)).insertedId;
|
||||
}
|
||||
|
||||
// updateOne/insertOne mutate `record` by injecting `_updatedAt` (setUpdatedAt), so rebuild the declared shape
|
||||
return { _id, name, description, numDepartments: departments.length, departments };
|
||||
}
|
||||
|
||||
// REMOVE
|
||||
override removeById(_id: string): Promise<DeleteResult> {
|
||||
const query = { _id };
|
||||
|
||||
return this.deleteOne(query);
|
||||
}
|
||||
}
|
||||
200
apps/meteor/ee/server/models/raw/LivechatUnit.ts
Normal file
200
apps/meteor/ee/server/models/raw/LivechatUnit.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import type { IOmnichannelBusinessUnit, ILivechatDepartment } from '@rocket.chat/core-typings';
|
||||
import type { FindPaginated, ILivechatUnitModel, DocumentWithProjection, FindOptionsWithProjection } from '@rocket.chat/model-typings';
|
||||
import { LivechatUnitMonitors, LivechatDepartment, LivechatRooms, BaseRaw } from '@rocket.chat/models';
|
||||
import type { Filter, FindCursor, Db, FilterOperators, UpdateResult, DeleteResult, Document, UpdateFilter } from 'mongodb';
|
||||
|
||||
const addQueryRestrictions = async (originalQuery: Filter<IOmnichannelBusinessUnit> = {}, unitsFromUser?: string[]) => {
|
||||
const query: FilterOperators<IOmnichannelBusinessUnit> = { ...originalQuery, type: 'u' };
|
||||
|
||||
if (Array.isArray(unitsFromUser)) {
|
||||
const expressions = query.$and || [];
|
||||
const condition = { $or: [{ ancestors: { $in: unitsFromUser } }, { _id: { $in: unitsFromUser } }] };
|
||||
query.$and = [condition, ...expressions];
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
// We don't actually need Units to extends from Departments
|
||||
export class LivechatUnitRaw extends BaseRaw<IOmnichannelBusinessUnit> implements ILivechatUnitModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'livechat_department');
|
||||
}
|
||||
|
||||
findPaginatedUnits<T extends Document = IOmnichannelBusinessUnit, O extends FindOptionsWithProjection<T> = FindOptionsWithProjection<T>>(
|
||||
query: Filter<IOmnichannelBusinessUnit>,
|
||||
options?: O,
|
||||
): FindPaginated<FindCursor<DocumentWithProjection<T, O>>> {
|
||||
return super.findPaginated<T, O>({ ...query, type: 'u' }, options);
|
||||
}
|
||||
|
||||
// @ts-expect-error - Overriding base types :)
|
||||
async findOne<P extends Document = IOmnichannelBusinessUnit, O extends FindOptionsWithProjection<P> = FindOptionsWithProjection<P>>(
|
||||
originalQuery: Filter<IOmnichannelBusinessUnit>,
|
||||
options?: O,
|
||||
extra?: Record<string, any>,
|
||||
): Promise<DocumentWithProjection<P, O> | null> {
|
||||
const query = await addQueryRestrictions(originalQuery, extra?.unitsFromUser);
|
||||
return super.findOne<P, O>(query, options);
|
||||
}
|
||||
|
||||
override async findOneById<
|
||||
P extends Document = IOmnichannelBusinessUnit,
|
||||
O extends FindOptionsWithProjection<P> = FindOptionsWithProjection<P>,
|
||||
>(_id: IOmnichannelBusinessUnit['_id'], options?: O, extra?: Record<string, any>): Promise<DocumentWithProjection<P, O> | null> {
|
||||
return this.findOne<P, O>({ _id }, options, extra);
|
||||
}
|
||||
|
||||
async createOrUpdateUnit(
|
||||
_id: string | null,
|
||||
{ name, visibility }: { name: string; visibility: IOmnichannelBusinessUnit['visibility'] },
|
||||
ancestors: string[],
|
||||
monitors: { monitorId: string; username: string }[],
|
||||
departments: { departmentId: string }[],
|
||||
): Promise<Omit<IOmnichannelBusinessUnit, '_updatedAt'>> {
|
||||
monitors = ([] as { monitorId: string; username: string }[]).concat(monitors || []);
|
||||
ancestors = ([] as string[]).concat(ancestors || []);
|
||||
|
||||
const record = {
|
||||
name,
|
||||
visibility,
|
||||
type: 'u',
|
||||
numMonitors: monitors.length,
|
||||
numDepartments: departments.length,
|
||||
};
|
||||
|
||||
if (_id) {
|
||||
await this.updateOne({ _id }, { $set: record });
|
||||
} else {
|
||||
_id = (await this.insertOne(record)).insertedId;
|
||||
}
|
||||
|
||||
if (!_id) {
|
||||
throw new Error('Error creating/updating unit');
|
||||
}
|
||||
|
||||
ancestors.splice(0, 0, _id);
|
||||
|
||||
const savedMonitors = (await LivechatUnitMonitors.findByUnitId(_id).toArray()).map(({ monitorId }) => monitorId);
|
||||
const monitorsToSave = monitors.map(({ monitorId }) => monitorId);
|
||||
|
||||
// remove other monitors
|
||||
for await (const monitorId of savedMonitors) {
|
||||
if (!monitorsToSave.includes(monitorId)) {
|
||||
await LivechatUnitMonitors.removeByUnitIdAndMonitorId(_id, monitorId);
|
||||
}
|
||||
}
|
||||
|
||||
for await (const monitor of monitors) {
|
||||
await LivechatUnitMonitors.saveMonitor({
|
||||
monitorId: monitor.monitorId,
|
||||
unitId: _id,
|
||||
username: monitor.username,
|
||||
});
|
||||
}
|
||||
|
||||
const savedDepartments = (await LivechatDepartment.findByParentId(_id, { projection: { _id: 1 } }).toArray()).map(({ _id }) => _id);
|
||||
const departmentsToSave = departments.map(({ departmentId }) => departmentId);
|
||||
|
||||
// remove other departments
|
||||
for await (const departmentId of savedDepartments) {
|
||||
if (!departmentsToSave.includes(departmentId)) {
|
||||
await LivechatDepartment.removeDepartmentFromUnit(departmentId);
|
||||
}
|
||||
}
|
||||
|
||||
for await (const departmentId of departmentsToSave) {
|
||||
await LivechatDepartment.addDepartmentToUnit(departmentId, _id, ancestors);
|
||||
}
|
||||
|
||||
await LivechatRooms.associateRoomsWithDepartmentToUnit(departmentsToSave, _id);
|
||||
|
||||
return {
|
||||
...record,
|
||||
_id,
|
||||
};
|
||||
}
|
||||
|
||||
removeParentAndAncestorById(parentId: string): Promise<UpdateResult | Document> {
|
||||
const query = {
|
||||
parentId,
|
||||
};
|
||||
|
||||
const update: UpdateFilter<IOmnichannelBusinessUnit> = {
|
||||
$unset: { parentId: 1 },
|
||||
$pull: { ancestors: parentId },
|
||||
};
|
||||
|
||||
return this.updateMany(query, update);
|
||||
}
|
||||
|
||||
incrementDepartmentsCount(_id: string): Promise<UpdateResult | Document> {
|
||||
return this.updateOne({ _id }, { $inc: { numDepartments: 1 } });
|
||||
}
|
||||
|
||||
decrementDepartmentsCount(_id: string): Promise<UpdateResult | Document> {
|
||||
return this.updateOne({ _id }, { $inc: { numDepartments: -1 } });
|
||||
}
|
||||
|
||||
override async removeById(_id: string): Promise<DeleteResult> {
|
||||
await LivechatUnitMonitors.removeByUnitId(_id);
|
||||
await this.removeParentAndAncestorById(_id);
|
||||
await LivechatRooms.removeUnitAssociationFromRooms(_id);
|
||||
|
||||
const query = { _id };
|
||||
return this.deleteOne(query);
|
||||
}
|
||||
|
||||
async removeByIdAndUnit(_id: string, unitsFromUser?: string[]): Promise<DeleteResult> {
|
||||
const originalQuery = { _id };
|
||||
const query = await addQueryRestrictions(originalQuery, unitsFromUser);
|
||||
const result = await this.deleteOne(query);
|
||||
if (result.deletedCount > 0) {
|
||||
await LivechatUnitMonitors.removeByUnitId(_id);
|
||||
await this.removeParentAndAncestorById(_id);
|
||||
await LivechatRooms.removeUnitAssociationFromRooms(_id);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
findOneByIdOrName<T extends Document = IOmnichannelBusinessUnit, O extends FindOptionsWithProjection<T> = FindOptionsWithProjection<T>>(
|
||||
_idOrName: string,
|
||||
options?: O,
|
||||
): Promise<DocumentWithProjection<T, O> | null> {
|
||||
const query = {
|
||||
$or: [
|
||||
{
|
||||
_id: _idOrName,
|
||||
},
|
||||
{
|
||||
name: _idOrName,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return this.findOne<T, O>(query, options);
|
||||
}
|
||||
|
||||
async findByMonitorId(monitorId: string): Promise<string[]> {
|
||||
const monitoredUnits = await LivechatUnitMonitors.findByMonitorId(monitorId).toArray();
|
||||
if (monitoredUnits.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return monitoredUnits.map((u) => u.unitId);
|
||||
}
|
||||
|
||||
async findMonitoredDepartmentsByMonitorId(monitorId: string, includeDisabled: boolean): Promise<ILivechatDepartment[]> {
|
||||
const monitoredUnits = await this.findByMonitorId(monitorId);
|
||||
|
||||
if (includeDisabled) {
|
||||
return LivechatDepartment.findByUnitIds(monitoredUnits, {}).toArray();
|
||||
}
|
||||
return LivechatDepartment.findActiveByUnitIds(monitoredUnits, {}).toArray();
|
||||
}
|
||||
|
||||
countUnits(): Promise<number> {
|
||||
return this.countDocuments({ type: 'u' });
|
||||
}
|
||||
}
|
||||
62
apps/meteor/ee/server/models/raw/LivechatUnitMonitors.ts
Normal file
62
apps/meteor/ee/server/models/raw/LivechatUnitMonitors.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { ILivechatUnitMonitor } from '@rocket.chat/core-typings';
|
||||
import type { ILivechatUnitMonitorsModel } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { Db, FindCursor, UpdateResult, DeleteResult, IndexDescription } from 'mongodb';
|
||||
|
||||
export class LivechatUnitMonitorsRaw extends BaseRaw<ILivechatUnitMonitor> implements ILivechatUnitMonitorsModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'livechat_unit_monitors');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [
|
||||
{
|
||||
key: {
|
||||
unitId: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
key: {
|
||||
monitorId: 1,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
findByUnitId(unitId: string): FindCursor<ILivechatUnitMonitor> {
|
||||
return this.find({ unitId });
|
||||
}
|
||||
|
||||
findByMonitorId(monitorId: string): FindCursor<ILivechatUnitMonitor> {
|
||||
return this.find({ monitorId });
|
||||
}
|
||||
|
||||
saveMonitor(monitor: { monitorId: string; unitId: string; username: string }): Promise<UpdateResult> {
|
||||
return this.updateOne(
|
||||
{
|
||||
monitorId: monitor.monitorId,
|
||||
unitId: monitor.unitId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
monitorId: monitor.monitorId,
|
||||
unitId: monitor.unitId,
|
||||
username: monitor.username,
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
|
||||
removeByUnitIdAndMonitorId(unitId: string, monitorId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ unitId, monitorId });
|
||||
}
|
||||
|
||||
removeByUnitId(unitId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ unitId });
|
||||
}
|
||||
|
||||
removeByMonitorId(monitorId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ monitorId });
|
||||
}
|
||||
}
|
||||
50
apps/meteor/ee/server/models/raw/ReadReceipts.ts
Normal file
50
apps/meteor/ee/server/models/raw/ReadReceipts.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { IReadReceipt } from '@rocket.chat/core-typings';
|
||||
import type { IReadReceiptsModel } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { FindCursor, Db, IndexDescription, DeleteResult } from 'mongodb';
|
||||
|
||||
export class ReadReceiptsRaw extends BaseRaw<IReadReceipt> implements IReadReceiptsModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'read_receipts');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [
|
||||
// Unique index removed to increase performance. Uniqueness in now handled via composite value of _id
|
||||
// TODO: Drop existent index on database migration of 9.0
|
||||
// { key: { roomId: 1, userId: 1, messageId: 1 }, unique: true },
|
||||
{ key: { messageId: 1 } },
|
||||
{ key: { userId: 1 } },
|
||||
{ key: { roomId: 1 } },
|
||||
{ key: { ts: -1 } },
|
||||
];
|
||||
}
|
||||
|
||||
findByMessageId(messageId: string): FindCursor<IReadReceipt> {
|
||||
return this.find({ messageId });
|
||||
}
|
||||
|
||||
removeByUserId(userId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ userId });
|
||||
}
|
||||
|
||||
removeByRoomId(roomId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ roomId });
|
||||
}
|
||||
|
||||
removeByRoomIds(roomIds: string[]): Promise<DeleteResult> {
|
||||
return this.deleteMany({ roomId: { $in: roomIds } });
|
||||
}
|
||||
|
||||
removeByMessageId(messageId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ messageId });
|
||||
}
|
||||
|
||||
removeByMessageIds(messageIds: string[]): Promise<DeleteResult> {
|
||||
return this.deleteMany({ messageId: { $in: messageIds } });
|
||||
}
|
||||
|
||||
findOlderThan(date: Date): FindCursor<IReadReceipt> {
|
||||
return this.find({ ts: { $lt: date } });
|
||||
}
|
||||
}
|
||||
46
apps/meteor/ee/server/models/raw/ReadReceiptsArchive.ts
Normal file
46
apps/meteor/ee/server/models/raw/ReadReceiptsArchive.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { IReadReceipt } from '@rocket.chat/core-typings';
|
||||
import type { IReadReceiptsModel } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw, readSecondaryPreferred } from '@rocket.chat/models';
|
||||
import type { FindCursor, Db, IndexDescription, DeleteResult } from 'mongodb';
|
||||
|
||||
export class ReadReceiptsArchiveRaw extends BaseRaw<IReadReceipt> implements IReadReceiptsModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'read_receipts_archive');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [{ key: { messageId: 1 } }, { key: { userId: 1 } }, { key: { roomId: 1 } }, { key: { ts: -1 } }];
|
||||
}
|
||||
|
||||
findByMessageId(messageId: string): FindCursor<IReadReceipt> {
|
||||
// Pass read preference directly to the find query to prefer reading from secondary replicas
|
||||
return this.find({ messageId }, { readPreference: readSecondaryPreferred() });
|
||||
}
|
||||
|
||||
// Archive doesn't need all the delete methods from hot storage
|
||||
// But we implement them to satisfy the interface
|
||||
removeByUserId(userId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ userId });
|
||||
}
|
||||
|
||||
removeByRoomId(roomId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ roomId });
|
||||
}
|
||||
|
||||
removeByRoomIds(roomIds: string[]): Promise<DeleteResult> {
|
||||
return this.deleteMany({ roomId: { $in: roomIds } });
|
||||
}
|
||||
|
||||
removeByMessageId(messageId: string): Promise<DeleteResult> {
|
||||
return this.deleteMany({ messageId });
|
||||
}
|
||||
|
||||
removeByMessageIds(messageIds: string[]): Promise<DeleteResult> {
|
||||
return this.deleteMany({ messageId: { $in: messageIds } });
|
||||
}
|
||||
|
||||
findOlderThan(date: Date): FindCursor<IReadReceipt> {
|
||||
// Pass read preference directly to the find query to prefer reading from secondary replicas
|
||||
return this.find({ ts: { $lt: date } }, { readPreference: readSecondaryPreferred() });
|
||||
}
|
||||
}
|
||||
59
apps/meteor/ee/server/models/raw/ServiceLevelAgreements.ts
Normal file
59
apps/meteor/ee/server/models/raw/ServiceLevelAgreements.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { IOmnichannelServiceLevelAgreements } from '@rocket.chat/core-typings';
|
||||
import type { IOmnichannelServiceLevelAgreementsModel } from '@rocket.chat/model-typings';
|
||||
import { BaseRaw } from '@rocket.chat/models';
|
||||
import type { Db, IndexDescription } from 'mongodb';
|
||||
|
||||
export class ServiceLevelAgreements extends BaseRaw<IOmnichannelServiceLevelAgreements> implements IOmnichannelServiceLevelAgreementsModel {
|
||||
constructor(db: Db) {
|
||||
super(db, 'omnichannel_service_level_agreements');
|
||||
}
|
||||
|
||||
protected override modelIndexes(): IndexDescription[] {
|
||||
return [
|
||||
{ key: { name: 1 }, unique: true },
|
||||
{ key: { dueTimeInMinutes: 1 }, unique: true },
|
||||
];
|
||||
}
|
||||
|
||||
findDuplicate(
|
||||
_id: string | null,
|
||||
name: string,
|
||||
dueTimeInMinutes: number,
|
||||
): Promise<Pick<IOmnichannelServiceLevelAgreements, '_id'> | null> {
|
||||
return this.findOne({ ...(_id && { _id: { $ne: _id } }), $or: [{ name }, { dueTimeInMinutes }] }, { projection: { _id: 1 } });
|
||||
}
|
||||
|
||||
findOneByIdOrName(_idOrName: string, options = {}): Promise<IOmnichannelServiceLevelAgreements | null> {
|
||||
const query = {
|
||||
$or: [
|
||||
{
|
||||
_id: _idOrName,
|
||||
},
|
||||
{
|
||||
name: _idOrName,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return this.findOne(query, options);
|
||||
}
|
||||
|
||||
async createOrUpdatePriority(
|
||||
{ name, description, dueTimeInMinutes }: Pick<IOmnichannelServiceLevelAgreements, 'name' | 'description' | 'dueTimeInMinutes'>,
|
||||
_id: string | null,
|
||||
): Promise<Omit<IOmnichannelServiceLevelAgreements, '_updatedAt'>> {
|
||||
const record = {
|
||||
name,
|
||||
description,
|
||||
dueTimeInMinutes: parseInt(`${dueTimeInMinutes}`),
|
||||
};
|
||||
|
||||
if (_id) {
|
||||
await this.updateOne({ _id }, { $set: record });
|
||||
} else {
|
||||
_id = (await this.insertOne(record)).insertedId;
|
||||
}
|
||||
|
||||
return Object.assign(record, { _id });
|
||||
}
|
||||
}
|
||||
102
apps/meteor/ee/server/models/raw/Users.ts
Normal file
102
apps/meteor/ee/server/models/raw/Users.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import type { RocketChatRecordDeleted, IUser, AvailableAgentsAggregation } from '@rocket.chat/core-typings';
|
||||
import { queryStatusAgentOnline, UsersRaw } from '@rocket.chat/models';
|
||||
import type { Db, Collection, Filter } from 'mongodb';
|
||||
|
||||
import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred';
|
||||
|
||||
declare module '@rocket.chat/model-typings' {
|
||||
interface IUsersModel {
|
||||
getUnavailableAgents(
|
||||
departmentId: string,
|
||||
customFilter: Filter<AvailableAgentsAggregation>,
|
||||
enabledWhenIdle?: boolean,
|
||||
enabledWhenOffline?: boolean,
|
||||
): Promise<Pick<AvailableAgentsAggregation, 'username'>[]>;
|
||||
}
|
||||
}
|
||||
|
||||
export class UsersEE extends UsersRaw {
|
||||
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<IUser>>) {
|
||||
super(db, trash);
|
||||
}
|
||||
|
||||
override getUnavailableAgents(
|
||||
departmentId: string,
|
||||
customFilter: Filter<AvailableAgentsAggregation>,
|
||||
enabledWhenIdle = false,
|
||||
enabledWhenOffline = false,
|
||||
): Promise<Pick<AvailableAgentsAggregation, 'username'>[]> {
|
||||
// if department is provided, remove the agents that are not from the selected department
|
||||
const departmentFilter = departmentId
|
||||
? [
|
||||
{
|
||||
$lookup: {
|
||||
from: 'rocketchat_livechat_department_agents',
|
||||
let: { userId: '$_id' },
|
||||
pipeline: [
|
||||
{
|
||||
$match: {
|
||||
$expr: {
|
||||
$and: [{ $eq: ['$$userId', '$agentId'] }, { $eq: ['$departmentId', departmentId] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
as: 'department',
|
||||
},
|
||||
},
|
||||
{
|
||||
$match: { department: { $size: 1 } },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
return this.col
|
||||
.aggregate<AvailableAgentsAggregation>(
|
||||
[
|
||||
{
|
||||
$match: queryStatusAgentOnline({}, enabledWhenIdle, enabledWhenOffline),
|
||||
},
|
||||
...departmentFilter,
|
||||
{
|
||||
$lookup: {
|
||||
from: 'rocketchat_subscription',
|
||||
localField: '_id',
|
||||
foreignField: 'u._id',
|
||||
pipeline: [{ $match: { $and: [{ t: 'l' }, { open: true }, { onHold: { $ne: true } }] } }],
|
||||
as: 'subs',
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
'agentId': '$_id',
|
||||
'maxChatsForAgent': { $convert: { input: '$livechat.maxNumberSimultaneousChat', to: 'double', onError: 0, onNull: 0 } },
|
||||
'username': 1,
|
||||
...(departmentId
|
||||
? {
|
||||
'queueInfo.chatsForDepartment': {
|
||||
$size: {
|
||||
$filter: {
|
||||
input: '$subs',
|
||||
as: 'sub',
|
||||
cond: {
|
||||
$and: [{ $eq: ['$$sub.department', departmentId] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
'queueInfo.chats': {
|
||||
$size: '$subs',
|
||||
},
|
||||
},
|
||||
},
|
||||
...(customFilter ? [customFilter] : []),
|
||||
{ $project: { username: 1 } },
|
||||
],
|
||||
{ allowDiskUse: true, readPreference: readSecondaryPreferred() },
|
||||
)
|
||||
.toArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user