Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] Black screen when try to open a chat with a non-existent department #27609

Merged
merged 15 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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/Departments';

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
54 changes: 54 additions & 0 deletions apps/meteor/app/livechat/server/lib/Departments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
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`,
);

const promiseResponses = await Promise.allSettled([
LivechatDepartmentAgents.removeByDepartmentId(_id),
LivechatDepartment.unsetFallbackDepartmentByDepartmentId(_id),
LivechatRooms.bulkRemoveDepartmentFromRooms(_id),
]);
promiseResponses.forEach((response, index) => {
if (response.status === 'rejected') {
this.logger.error(`Error while performing post-department-removal actions: ${_id}. Action No: ${index}. Error:`, response.reason);
}
});

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/Departments';

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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Box, Skeleton } from '@rocket.chat/fuselage';
import { useTranslation } from '@rocket.chat/ui-contexts';
import React from 'react';

import Field from '../../../components/Field';
import Info from '../../../components/Info';
import Label from '../../../components/Label';
import { useDepartmentInfo } from '../../hooks/useDepartmentInfo';

type DepartmentFieldProps = {
departmentId: string;
};

const DepartmentField = ({ departmentId }: DepartmentFieldProps) => {
const t = useTranslation();
const { data, isLoading, isError } = useDepartmentInfo(departmentId);

return (
<Field>
<Label>{t('Department')}</Label>
{isLoading && <Skeleton />}
{isError && <Box color='danger'>{t('Something_went_wrong')}</Box>}
{!isLoading && !isError && <Info>{data?.department?.name || t('Department_not_found')}</Info>}
</Field>
);
};

export default DepartmentField;
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { OperationResult } from '@rocket.chat/rest-typings';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import type { UseQueryResult } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';

export const useDepartmentInfo = (departmentId: string): UseQueryResult<OperationResult<'GET', '/v1/livechat/department/:_id'>> => {
const deptInfo = useEndpoint('GET', `/v1/livechat/department/${departmentId}`);

return useQuery(['livechat/department', departmentId], () => deptInfo({}));
};
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 } });
}
}
65 changes: 64 additions & 1 deletion apps/meteor/tests/end-to-end/api/livechat/10-departments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ import type { Response } from 'supertest';

import { getCredentials, api, request, credentials } from '../../../data/api-data';
import { updatePermission, updateSetting } from '../../../data/permissions.helper';
import { makeAgentAvailable, createAgent, createDepartment } from '../../../data/livechat/rooms';
import {
makeAgentAvailable,
createAgent,
createDepartment,
createVisitor,
createLivechatRoom,
getLivechatRoomInfo,
} from '../../../data/livechat/rooms';
import { createDepartmentWithAnOnlineAgent } from '../../../data/livechat/department';

describe('LIVECHAT - Departments', function () {
before((done) => getCredentials(done));
Expand Down Expand Up @@ -153,6 +161,61 @@ describe('LIVECHAT - Departments', function () {
});
});

describe('DELETE livechat/department/:_id', () => {
it('should return unauthorized error when the user does not have the necessary permission', async () => {
await updatePermission('manage-livechat-departments', []);
await updatePermission('remove-livechat-department', []);

await request
.delete(api('livechat/department/testetetetstetete'))
.set(credentials)
.expect('Content-Type', 'application/json')
.expect(403);
});

it('should return an error when the department does not exist', async () => {
await updatePermission('manage-livechat-departments', ['admin']);

const resp: Response = await request
.delete(api('livechat/department/testesteteste'))
.set(credentials)
.expect('Content-Type', 'application/json')
.expect(400);

expect(resp.body).to.have.property('success', false);
expect(resp.body).to.have.property('error', 'error-department-not-found');
});

it('it should remove the department', async () => {
const department = await createDepartment();

const resp: Response = await request
.delete(api(`livechat/department/${department._id}`))
.set(credentials)
.expect('Content-Type', 'application/json')
.expect(200);

expect(resp.body).to.have.property('success', true);
});

it('it should remove the department and disassociate the rooms from it', async () => {
const { department } = await createDepartmentWithAnOnlineAgent();
const newVisitor = await createVisitor(department._id);
const newRoom = await createLivechatRoom(newVisitor.token);

const resp: Response = await request
.delete(api(`livechat/department/${department._id}`))
.set(credentials)
.expect('Content-Type', 'application/json')
.expect(200);

expect(resp.body).to.have.property('success', true);

const latestRoom = await getLivechatRoomInfo(newRoom._id);
expect(latestRoom.departmentId).to.be.undefined;
});
});

describe('GET livechat/department.autocomplete', () => {
it('should return an error when the user does not have the necessary permission', (done) => {
updatePermission('view-livechat-departments', [])
Expand Down
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<Document | UpdateResult>;
}