Skip to content

Commit

Permalink
Merge branch 'regression/visitor-name-overwrite' of github.com:Rocket…
Browse files Browse the repository at this point in the history
…Chat/Rocket.Chat into regression/visitor-name-overwrite
  • Loading branch information
yash-rajpal committed Aug 31, 2022
2 parents 40932a8 + 514ace1 commit 0c0b252
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 43 deletions.
38 changes: 22 additions & 16 deletions apps/meteor/app/livechat/imports/server/rest/rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ API.v1.addRoute(
'livechat/rooms',
{ authRequired: true },
{
get() {
async get() {
const { offset, count } = this.getPaginationItems();
const { sort, fields } = this.parseJsonQuery();
const { agents, departmentId, open, tags, roomName, onhold } = this.requestParams();
Expand All @@ -32,6 +32,7 @@ API.v1.addRoute(
check(open, Match.Maybe(String));
check(onhold, Match.Maybe(String));
check(tags, Match.Maybe([String]));
check(customFields, Match.Maybe(String));

createdAt = validateDateParams('createdAt', createdAt);
closedAt = validateDateParams('closedAt', closedAt);
Expand All @@ -43,24 +44,29 @@ API.v1.addRoute(
}

if (customFields) {
customFields = JSON.parse(customFields);
try {
const parsedCustomFields = JSON.parse(customFields);
check(parsedCustomFields, Object);
// Model's already checking for the keys, so we don't need to do it here.
customFields = parsedCustomFields;
} catch (e) {
throw new Error('The "customFields" query parameter must be a valid JSON.');
}
}

return API.v1.success(
Promise.await(
findRooms({
agents,
roomName,
departmentId,
open: open && open === 'true',
createdAt,
closedAt,
tags,
customFields,
onhold,
options: { offset, count, sort, fields },
}),
),
await findRooms({
agents,
roomName,
departmentId,
open: open && open === 'true',
createdAt,
closedAt,
tags,
customFields,
onhold,
options: { offset, count, sort, fields },
}),
);
},
},
Expand Down
13 changes: 9 additions & 4 deletions apps/meteor/app/livechat/server/lib/Livechat.js
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,12 @@ export const Livechat = {

const customFields = {};

if (!userId || hasPermission(userId, 'edit-livechat-room-customfields')) {
if ((!userId || hasPermission(userId, 'edit-livechat-room-customfields')) && Object.keys(livechatData).length) {
Livechat.logger.debug(`Saving custom fields for visitor ${_id}`);
const fields = LivechatCustomField.findByScope('visitor');
for await (const field of fields) {
if (!livechatData.hasOwnProperty(field._id)) {
return;
continue;
}
const value = s.trim(livechatData[field._id]);
if (value !== '' && field.regexp !== undefined && field.regexp !== '') {
Expand All @@ -408,6 +409,7 @@ export const Livechat = {
customFields[field._id] = value;
}
updateData.livechatData = customFields;
Livechat.logger.debug(`About to update ${Object.keys(customFields).length} custom fields for visitor ${_id}`);
}
const ret = await LivechatVisitors.saveGuestById(_id, updateData);

Expand Down Expand Up @@ -584,7 +586,8 @@ export const Livechat = {
const { livechatData = {} } = roomData;
const customFields = {};

if (!userId || hasPermission(userId, 'edit-livechat-room-customfields')) {
if ((!userId || hasPermission(userId, 'edit-livechat-room-customfields')) && Object.keys(livechatData).length) {
Livechat.logger.debug(`Updating custom fields on room ${roomData._id}`);
const fields = LivechatCustomField.findByScope('room');
for await (const field of fields) {
if (!livechatData.hasOwnProperty(field._id)) {
Expand All @@ -600,9 +603,11 @@ export const Livechat = {
customFields[field._id] = value;
}
roomData.livechatData = customFields;
Livechat.logger.debug(`About to update ${Object.keys(customFields).length} custom fields on room ${roomData._id}`);
}

if (!LivechatRooms.saveRoomById(roomData)) {
Livechat.logger.debug(`Failed to save room information on room ${roomData._id}`);
return false;
}

Expand All @@ -611,7 +616,7 @@ export const Livechat = {
});
callbacks.runAsync('livechat.saveRoom', roomData);

if (!_.isEmpty(guestData.name)) {
if (guestData?.name?.trim().length) {
const { _id: rid } = roomData;
const { name } = guestData;
return (
Expand Down
7 changes: 4 additions & 3 deletions apps/meteor/app/livechat/server/methods/saveInfo.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
import { isOmnichannelRoom } from '@rocket.chat/core-typings';

import { hasPermission } from '../../../authorization';
import { LivechatRooms } from '../../../models/server';
Expand Down Expand Up @@ -37,7 +38,7 @@ Meteor.methods({
);

const room = LivechatRooms.findOneById(roomData._id);
if (room == null || room.t !== 'l') {
if (!room || !isOmnichannelRoom(room)) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'livechat:saveInfo' });
}

Expand All @@ -49,7 +50,7 @@ Meteor.methods({
delete guestData.phone;
}

const ret = (await Livechat.saveGuest(guestData, userId)) && (await Livechat.saveRoomInfo(roomData, guestData, userId));
await Promise.allSettled([Livechat.saveGuest(guestData), Livechat.saveRoomInfo(roomData)]);

const user = Meteor.users.findOne({ _id: userId }, { fields: { _id: 1, username: 1 } });

Expand All @@ -60,6 +61,6 @@ Meteor.methods({
});
});

return ret;
return true;
},
});
1 change: 1 addition & 0 deletions apps/meteor/client/sidebar/search/SearchList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRo
{
staleTime: 60_000,
keepPreviousData: true,
placeholderData: localRooms,
},
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type useQueryType = (
itemsPerPage: 25 | 50 | 100;
current: number;
},
customFields: { [key: string]: string },
customFields: { [key: string]: string } | undefined,
[column, direction]: [string, 'asc' | 'desc'],
) => LivechatRoomsProps | undefined;

Expand Down Expand Up @@ -101,7 +101,7 @@ const useQuery: useQueryType = (
}

if (customFields && Object.keys(customFields).length > 0) {
const customFieldsQuery = Object.fromEntries(Object.entries(customFields).filter((item) => item[1] !== ''));
const customFieldsQuery = Object.fromEntries(Object.entries(customFields).filter((item) => item[1] !== undefined && item[1] !== ''));
if (Object.keys(customFieldsQuery).length > 0) {
query.customFields = JSON.stringify(customFieldsQuery);
}
Expand All @@ -112,7 +112,7 @@ const useQuery: useQueryType = (

const CurrentChatsRoute = (): ReactElement => {
const { sortBy, sortDirection, setSort } = useSort<'fname' | 'departmentId' | 'servedBy' | 'ts' | 'lm' | 'open'>('fname');
const [customFields, setCustomFields] = useState<{ [key: string]: string }>({});
const [customFields, setCustomFields] = useState<{ [key: string]: string }>();
const [params, setParams] = useState({
guest: '',
fname: '',
Expand All @@ -128,12 +128,6 @@ const CurrentChatsRoute = (): ReactElement => {
const t = useTranslation();
const id = useRouteParameter('id');

const onHeaderClick = useMutableCallback((id) => {
if (sortBy === id) {
setSort(id, sortDirection === 'asc' ? 'desc' : 'asc');
}
});

const debouncedParams = useDebouncedValue(params, 500);
const debouncedCustomFields = useDebouncedValue(customFields, 500);

Expand Down Expand Up @@ -224,7 +218,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='fname'
direction={sortDirection}
active={sortBy === 'fname'}
onClick={onHeaderClick}
onClick={setSort}
sort='fname'
data-qa='current-chats-header-name'
>
Expand All @@ -234,7 +228,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='departmentId'
direction={sortDirection}
active={sortBy === 'departmentId'}
onClick={onHeaderClick}
onClick={setSort}
sort='departmentId'
data-qa='current-chats-header-department'
>
Expand All @@ -244,7 +238,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='servedBy'
direction={sortDirection}
active={sortBy === 'servedBy'}
onClick={onHeaderClick}
onClick={setSort}
sort='servedBy'
data-qa='current-chats-header-servedBy'
>
Expand All @@ -254,7 +248,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='ts'
direction={sortDirection}
active={sortBy === 'ts'}
onClick={onHeaderClick}
onClick={setSort}
sort='ts'
data-qa='current-chats-header-startedAt'
>
Expand All @@ -264,7 +258,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='lm'
direction={sortDirection}
active={sortBy === 'lm'}
onClick={onHeaderClick}
onClick={setSort}
sort='lm'
data-qa='current-chats-header-lastMessage'
>
Expand All @@ -274,7 +268,7 @@ const CurrentChatsRoute = (): ReactElement => {
key='open'
direction={sortDirection}
active={sortBy === 'open'}
onClick={onHeaderClick}
onClick={setSort}
sort='open'
w='x100'
data-qa='current-chats-header-status'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Controller, useForm } from 'react-hook-form';
import VerticalBar from '../../../components/VerticalBar';

type CustomFieldsVerticalBarProps = {
setCustomFields: Dispatch<SetStateAction<{ [key: string]: string }>>;
setCustomFields: Dispatch<SetStateAction<{ [key: string]: string } | undefined>>;
allCustomFields: OmnichannelCustomFieldEndpointPayload[];
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import RemoveAllClosed from './RemoveAllClosed';

type FilterByTextType = FC<{
setFilter: Dispatch<SetStateAction<any>>;
setCustomFields: Dispatch<SetStateAction<{ [key: string]: string }>>;
customFields: { [key: string]: string };
setCustomFields: Dispatch<SetStateAction<{ [key: string]: string } | undefined>>;
customFields: { [key: string]: string } | undefined;
hasCustomFields: boolean;
reload?: () => void;
}>;
Expand Down Expand Up @@ -55,7 +55,7 @@ const FilterByText: FilterByTextType = ({ setFilter, reload, customFields, setCu
setFrom('');
setTo('');
setTags([]);
setCustomFields({});
setCustomFields(undefined);
});

const forms = useFormsSubscription() as any;
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/models/raw/LivechatRooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,7 @@ export class LivechatRoomsRaw extends BaseRaw {
if (tags) {
query.tags = { $in: tags };
}
if (customFields) {
if (customFields && Object.keys(customFields).length) {
query.$and = Object.keys(customFields).map((key) => ({
[`livechatData.${key}`]: new RegExp(customFields[key], 'i'),
}));
Expand Down

0 comments on commit 0c0b252

Please sign in to comment.