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 all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions apps/meteor/app/livechat/imports/server/rest/departments.ts
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
56 changes: 56 additions & 0 deletions apps/meteor/app/livechat/server/lib/Departments.ts
@@ -0,0 +1,56 @@
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);
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: string[] = await LivechatDepartmentAgents.findAgentsByDepartmentId(department._id)
.cursor.map((agent) => agent.agentId)
.toArray();

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.bulkRemoveDepartmentAndUnitsFromRooms(_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
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
@@ -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
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();
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.

@@ -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;
@@ -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/:_id`, { _id: departmentId });

return useQuery(['livechat/department', departmentId], () => deptInfo({}));
};

This file was deleted.

@@ -0,0 +1,30 @@
import type { ILivechatAgent, ILivechatDepartmentRecord } from '@rocket.chat/core-typings';
import { LivechatDepartment } from '@rocket.chat/models';

import { callbacks } from '../../../../../lib/callbacks';
import { cbLogger } from '../lib/logger';

const afterRemoveDepartment = async (options: { department: ILivechatDepartmentRecord; agentsId: ILivechatAgent['_id'][] }) => {
cbLogger.debug(`Performing post-department-removal actions in EE: ${options?.department?._id}. Removing department from forward list`);
if (!options || !options.department) {
cbLogger.warn('No department found in options', options);
return options;
}

const { department } = options;

cbLogger.debug(`Removing department from forward list: ${department._id}`);
await LivechatDepartment.removeDepartmentFromForwardListById(department._id);
cbLogger.debug(`Removed department from forward list: ${department._id}`);

cbLogger.debug(`Post-department-removal actions completed in EE: ${department._id}`);

return options;
};

callbacks.add(
'livechat.afterRemoveDepartment',
(options) => Promise.await(afterRemoveDepartment(options)),
callbacks.priority.HIGH,
'livechat-after-remove-department',
);
4 changes: 0 additions & 4 deletions apps/meteor/ee/app/models/server/models/LivechatDepartment.js
Expand Up @@ -55,8 +55,4 @@ overwriteClassOnLicense('livechat-enterprise', LivechatDepartment, {
},
});

LivechatDepartment.prototype.removeDepartmentFromForwardListById = function (_id) {
return this.update({ departmentsAllowedToForward: _id }, { $pull: { departmentsAllowedToForward: _id } }, { multi: true });
};

export default LivechatDepartment;
6 changes: 6 additions & 0 deletions apps/meteor/ee/server/models/LivechatDepartment.ts
@@ -0,0 +1,6 @@
import { registerModel } from '@rocket.chat/models';

import { db } from '../../../server/database/utils';
import { LivechatDepartmentEE } from './raw/LivechatDepartment';

registerModel('ILivechatDepartmentModel', new LivechatDepartmentEE(db));
15 changes: 15 additions & 0 deletions apps/meteor/ee/server/models/raw/LivechatDepartment.ts
@@ -0,0 +1,15 @@
import type { ILivechatDepartmentModel } from '@rocket.chat/model-typings';

import { LivechatDepartmentRaw } from '../../../../server/models/raw/LivechatDepartment';

declare module '@rocket.chat/model-typings' {
export interface ILivechatDepartmentModel {
removeDepartmentFromForwardListById(departmentId: string): Promise<void>;
}
}

export class LivechatDepartmentEE extends LivechatDepartmentRaw implements ILivechatDepartmentModel {
async removeDepartmentFromForwardListById(departmentId: string): Promise<void> {
await this.updateMany({ departmentsAllowedToForward: departmentId }, { $pull: { departmentsAllowedToForward: departmentId } });
}
}
1 change: 1 addition & 0 deletions apps/meteor/ee/server/models/startup.ts
Expand Up @@ -7,4 +7,5 @@ onLicense('livechat-enterprise', () => {
import('./LivechatUnit');
import('./LivechatUnitMonitors');
import('./LivechatRooms');
import('./LivechatDepartment');
});
2 changes: 1 addition & 1 deletion apps/meteor/lib/callbacks.ts
Expand Up @@ -107,7 +107,7 @@ type ChainedCallbackSignatures = {
oldDepartmentId: ILivechatDepartmentRecord['_id'];
};
'livechat.afterInquiryQueued': (inquiry: ILivechatInquiryRecord) => ILivechatInquiryRecord;
'livechat.afterRemoveDepartment': (params: { departmentId: ILivechatDepartmentRecord['_id']; agentsId: ILivechatAgent['_id'][] }) => {
'livechat.afterRemoveDepartment': (params: { department: ILivechatDepartmentRecord; agentsId: ILivechatAgent['_id'][] }) => {
departmentId: ILivechatDepartmentRecord['_id'];
agentsId: ILivechatAgent['_id'][];
};
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/packages/rocketchat-i18n/i18n/en.i18n.json
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"
}
}
8 changes: 8 additions & 0 deletions apps/meteor/server/models/raw/LivechatDepartment.ts
Expand Up @@ -110,4 +110,12 @@ 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 } });
}

removeDepartmentFromForwardListById(_departmentId: string): Promise<void> {
throw new Error('Method not implemented in Community Edition.');
}
}
6 changes: 5 additions & 1 deletion apps/meteor/server/models/raw/LivechatDepartmentAgents.ts
@@ -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
Expand Up @@ -1288,4 +1288,8 @@ export class LivechatRoomsRaw extends BaseRaw {
},
]);
}

bulkRemoveDepartmentAndUnitsFromRooms(departmentId) {
return this.updateMany({ departmentId }, { $unset: { departmentId: 1, departmentAncestors: 1 } });
}
}