Skip to content

Commit

Permalink
Cleanup department props from room once a department is removed
Browse files Browse the repository at this point in the history
  • Loading branch information
murtaza98 committed Dec 27, 2022
1 parent 7ef6267 commit ecff71a
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 50 deletions.
10 changes: 5 additions & 5 deletions apps/meteor/app/livechat/imports/server/rest/departments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
findDepartmentsBetweenIds,
findDepartmentAgents,
} from '../../../server/api/lib/departments';
import { DepartmentHelper } from '../../../server/lib/DepartmentsHelper';

API.v1.addRoute(
'livechat/department',
Expand Down Expand Up @@ -133,15 +134,14 @@ API.v1.addRoute(

return API.v1.failure();
},
delete() {
async delete() {
check(this.urlParams, {
_id: String,
});

if (Livechat.removeDepartment(this.urlParams._id)) {
return API.v1.success();
}
return API.v1.failure();
await DepartmentHelper.removeDepartment(this.urlParams._id);

return API.v1.success();
},
},
);
Expand Down
49 changes: 49 additions & 0 deletions apps/meteor/app/livechat/server/lib/DepartmentsHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { LivechatDepartment, LivechatDepartmentAgents, LivechatRooms } from '@rocket.chat/models';

import { callbacks } from '../../../../lib/callbacks';
import { Logger } from '../../../logger/server';

class DepartmentHelperClass {
logger = new Logger('Omnichannel:DepartmentHelper');

async removeDepartment(departmentId: string) {
this.logger.debug(`Removing department: ${departmentId}`);

const department = await LivechatDepartment.findOneById(departmentId, { projection: { _id: 1 } });
if (!department) {
this.logger.debug(`Department not found: ${departmentId}`);
throw new Error('error-department-not-found');
}

const { _id } = department;

const ret = await LivechatDepartment.removeById(_id);
if (ret.acknowledged !== true) {
this.logger.error(`Department record not removed: ${_id}. Result from db: ${ret}`);
throw new Error('error-failed-to-delete-department');
}
this.logger.debug(`Department record removed: ${_id}`);

const agentsIds = LivechatDepartmentAgents.findAgentsByDepartmentId(department._id).cursor.map((agent) => agent.agentId);

this.logger.debug(
`Performing post-department-removal actions: ${_id}. Removing department agents, unsetting fallback department and removing department from rooms`,
);

await Promise.all([
LivechatDepartmentAgents.removeByDepartmentId(_id),
LivechatDepartment.unsetFallbackDepartmentByDepartmentId(_id),
LivechatRooms.bulkRemoveDepartmentFromRooms(_id),
]);

this.logger.debug(`Post-department-removal actions completed: ${_id}. Notifying callbacks with department and agentsIds`);

Meteor.defer(() => {
callbacks.run('livechat.afterRemoveDepartment', { department, agentsIds });
});

return ret;
}
}

export const DepartmentHelper = new DepartmentHelperClass();
24 changes: 0 additions & 24 deletions apps/meteor/app/livechat/server/lib/Livechat.js
Original file line number Diff line number Diff line change
Expand Up @@ -1129,30 +1129,6 @@ export const Livechat = {
return true;
},

removeDepartment(_id) {
check(_id, String);

const department = LivechatDepartment.findOneById(_id, { fields: { _id: 1 } });

if (!department) {
throw new Meteor.Error('department-not-found', 'Department not found', {
method: 'livechat:removeDepartment',
});
}
const ret = LivechatDepartment.removeById(_id);
const agentsIds = LivechatDepartmentAgents.findByDepartmentId(_id)
.fetch()
.map((agent) => agent.agentId);
LivechatDepartmentAgents.removeByDepartmentId(_id);
LivechatDepartment.unsetFallbackDepartmentByDepartmentId(_id);
if (ret) {
Meteor.defer(() => {
callbacks.run('livechat.afterRemoveDepartment', { department, agentsIds });
});
}
return ret;
},

showConnecting() {
const { showConnecting } = RoutingManager.getConfig();
return showConnecting;
Expand Down
7 changes: 5 additions & 2 deletions apps/meteor/app/livechat/server/methods/removeDepartment.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';

import { hasPermission } from '../../../authorization';
import { Livechat } from '../lib/Livechat';
import { methodDeprecationLogger } from '../../../lib/server/lib/deprecationWarningLogger';
import { DepartmentHelper } from '../lib/DepartmentsHelper';

Meteor.methods({
'livechat:removeDepartment'(_id) {
methodDeprecationLogger.warn('livechat:removeDepartment will be deprecated in future versions of Rocket.Chat');

check(_id, String);

if (!Meteor.userId() || !hasPermission(Meteor.userId(), 'manage-livechat-departments')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'livechat:removeDepartment',
});
}

return Livechat.removeDepartment(_id);
return DepartmentHelper.removeDepartment(_id);
},
});
12 changes: 0 additions & 12 deletions apps/meteor/app/models/server/models/LivechatDepartment.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,18 +152,6 @@ export class LivechatDepartment extends Base {

return this.find(query, options);
}

unsetFallbackDepartmentByDepartmentId(_id) {
return this.update(
{ fallbackForwardDepartment: _id },
{
$unset: {
fallbackForwardDepartment: 1,
},
},
{ multi: true },
);
}
}

export default new LivechatDepartment();
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@ export class LivechatDepartmentAgents extends Base {
this.remove({ departmentId, agentId });
}

removeByDepartmentId(departmentId) {
this.remove({ departmentId });
}

getNextAgentForDepartment(departmentId, ignoreAgentId, extraQuery) {
const agents = this.findByDepartmentId(departmentId).fetch();

Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/packages/rocketchat-i18n/i18n/en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -1880,6 +1880,7 @@
"error-email-domain-blacklisted": "The email domain is blacklisted",
"error-email-send-failed": "Error trying to send email: __message__",
"error-essential-app-disabled": "Error: a Rocket.Chat App that is essential for this is disabled. Please contact your administrator",
"error-failed-to-delete-department": "Failed to delete department",
"error-field-unavailable": "<strong>__field__</strong> is already in use :(",
"error-file-too-large": "File is too large",
"error-forwarding-chat": "Something went wrong while forwarding the chat, Please try again later.",
Expand Down Expand Up @@ -5550,4 +5551,4 @@
"Theme_dark": "Dark",
"Join_your_team": "Join your team",
"Create_an_account": "Create an account"
}
}
4 changes: 4 additions & 0 deletions apps/meteor/server/models/raw/LivechatDepartment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,8 @@ export class LivechatDepartmentRaw extends BaseRaw<ILivechatDepartmentRecord> im

return this.updateMany(query, update);
}

unsetFallbackDepartmentByDepartmentId(departmentId: string): Promise<Document | UpdateResult> {
return this.updateMany({ fallbackDepartment: departmentId }, { $unset: { fallbackDepartment: 1 } });
}
}
6 changes: 5 additions & 1 deletion apps/meteor/server/models/raw/LivechatDepartmentAgents.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ILivechatDepartmentAgents, RocketChatRecordDeleted } from '@rocket.chat/core-typings';
import type { FindPaginated, ILivechatDepartmentAgentsModel } from '@rocket.chat/model-typings';
import type { Collection, FindCursor, Db, Filter, FindOptions } from 'mongodb';
import type { Collection, FindCursor, Db, Filter, FindOptions, DeleteResult } from 'mongodb';

import { BaseRaw } from './BaseRaw';

Expand Down Expand Up @@ -105,4 +105,8 @@ export class LivechatDepartmentAgentsRaw extends BaseRaw<ILivechatDepartmentAgen
findAgentsByAgentIdAndBusinessHourId(_agentId: string, _businessHourId: string): [] {
return [];
}

removeByDepartmentId(departmentId: string): Promise<DeleteResult> {
return this.deleteOne({ departmentId });
}
}
4 changes: 4 additions & 0 deletions apps/meteor/server/models/raw/LivechatRooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -1288,4 +1288,8 @@ export class LivechatRoomsRaw extends BaseRaw {
},
]);
}

bulkRemoveDepartmentFromRooms(departmentId) {
return this.updateMany({ departmentId }, { $unset: { departmentId: 1 } });
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { FindCursor, FindOptions } from 'mongodb';
import type { DeleteResult, FindCursor, FindOptions } from 'mongodb';
import type { ILivechatDepartmentAgents } from '@rocket.chat/core-typings';

import type { FindPaginated, IBaseModel } from './IBaseModel';
Expand Down Expand Up @@ -58,4 +58,5 @@ export interface ILivechatDepartmentAgentsModel extends IBaseModel<ILivechatDepa

findByDepartmentIds(departmentIds: string[], options?: Record<string, any>): FindCursor<ILivechatDepartmentAgents>;
findAgentsByAgentIdAndBusinessHourId(_agentId: string, _businessHourId: string): [];
removeByDepartmentId(departmentId: string): Promise<DeleteResult>;
}
2 changes: 2 additions & 0 deletions packages/model-typings/src/models/ILivechatDepartmentModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ export interface ILivechatDepartmentModel extends IBaseModel<ILivechatDepartment
removeBusinessHourFromDepartmentsByIdsAndBusinessHourId(ids: string[], businessHourId: string): Promise<Document | UpdateResult>;

removeBusinessHourFromDepartmentsByBusinessHourId(businessHourId: string): Promise<Document | UpdateResult>;

unsetFallbackDepartmentByDepartmentId(departmentId: string): Promise<Document | UpdateResult>;
}
2 changes: 2 additions & 0 deletions packages/model-typings/src/models/ILivechatRoomsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,6 @@ export interface ILivechatRoomsModel extends IBaseModel<IOmnichannelRoom> {
setAutoTransferredAtById(roomId: string): Promise<UpdateResult>;

findAvailableSources(): AggregationCursor<Document>;

bulkRemoveDepartmentFromRooms(departmentId: string): Promise<UpdateResult>;
}

0 comments on commit ecff71a

Please sign in to comment.