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

Chore: Convert current-chats to useQuery #26931

Merged
merged 4 commits into from
Sep 23, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@ import { GenericTable } from '../../../components/GenericTable/V2/GenericTable';
import { usePagination } from '../../../components/GenericTable/hooks/usePagination';
import { useSort } from '../../../components/GenericTable/hooks/useSort';
import Page from '../../../components/Page';
import { useEndpointData } from '../../../hooks/useEndpointData';
import { AsyncStatePhase } from '../../../lib/asyncState';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
import Chat from '../directory/chats/Chat';
import CustomFieldsVerticalBar from './CustomFieldsVerticalBar';
import FilterByText from './FilterByText';
import RemoveChatButton from './RemoveChatButton';
import { useAllCustomFields } from './useAllCustomFields';
import { useAllCustomFields } from './hooks/useAllCustomFields';
import { useCurrentChats } from './hooks/useCurrentChats';

type useQueryType = (
debouncedParams: {
Expand All @@ -41,74 +40,73 @@ type useQueryType = (
},
customFields: { [key: string]: string } | undefined,
[column, direction]: [string, 'asc' | 'desc'],
) => GETLivechatRoomsParams | undefined;
) => GETLivechatRoomsParams;

const sortDir = (sortDir: 'asc' | 'desc'): 1 | -1 => (sortDir === 'asc' ? 1 : -1);

const useQuery: useQueryType = (
const currentChatQuery: useQueryType = (
{ guest, servedBy, department, status, from, to, tags, itemsPerPage, current },
customFields,
[column, direction],
) =>
useMemo(() => {
const query: {
agents?: string[];
offset?: number;
roomName?: string;
departmentId?: string;
open?: boolean;
createdAt?: string;
closedAt?: string;
tags?: string[];
onhold?: boolean;
customFields?: string;
sort: string;
count?: number;
} = {
...(guest && { roomName: guest }),
sort: JSON.stringify({
[column]: sortDir(direction),
ts: column === 'ts' ? sortDir(direction) : undefined,
}),
...(itemsPerPage && { count: itemsPerPage }),
...(current && { offset: current }),
};
) => {
const query: {
agents?: string[];
offset?: number;
roomName?: string;
departmentId?: string;
open?: boolean;
createdAt?: string;
closedAt?: string;
tags?: string[];
onhold?: boolean;
customFields?: string;
sort: string;
count?: number;
} = {
...(guest && { roomName: guest }),
sort: JSON.stringify({
[column]: sortDir(direction),
ts: column === 'ts' ? sortDir(direction) : undefined,
}),
...(itemsPerPage && { count: itemsPerPage }),
...(current && { offset: current }),
};

if (from || to) {
query.createdAt = JSON.stringify({
...(from && {
start: moment(new Date(from)).set({ hour: 0, minutes: 0, seconds: 0 }).format('YYYY-MM-DDTHH:mm:ss'),
}),
...(to && {
end: moment(new Date(to)).set({ hour: 23, minutes: 59, seconds: 59 }).format('YYYY-MM-DDTHH:mm:ss'),
}),
});
}
if (from || to) {
query.createdAt = JSON.stringify({
...(from && {
start: moment(new Date(from)).set({ hour: 0, minutes: 0, seconds: 0 }).format('YYYY-MM-DDTHH:mm:ss'),
}),
...(to && {
end: moment(new Date(to)).set({ hour: 23, minutes: 59, seconds: 59 }).format('YYYY-MM-DDTHH:mm:ss'),
}),
});
}

if (status !== 'all') {
query.open = status === 'opened' || status === 'onhold';
query.onhold = status === 'onhold';
}
if (servedBy && servedBy !== 'all') {
query.agents = [servedBy];
}
if (department && department !== 'all') {
query.departmentId = department;
}
if (status !== 'all') {
query.open = status === 'opened' || status === 'onhold';
query.onhold = status === 'onhold';
}
if (servedBy && servedBy !== 'all') {
query.agents = [servedBy];
}
if (department && department !== 'all') {
query.departmentId = department;
}

if (tags && tags.length > 0) {
query.tags = tags;
}
if (tags && tags.length > 0) {
query.tags = tags;
}

if (customFields && Object.keys(customFields).length > 0) {
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);
}
if (customFields && Object.keys(customFields).length > 0) {
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);
}
}

return query;
}, [guest, column, direction, itemsPerPage, current, from, to, status, servedBy, department, tags, customFields]);
return query;
};

const CurrentChatsRoute = (): ReactElement => {
const { sortBy, sortDirection, setSort } = useSort<'fname' | 'departmentId' | 'servedBy' | 'ts' | 'lm' | 'open'>('ts', 'desc');
Expand Down Expand Up @@ -136,12 +134,13 @@ const CurrentChatsRoute = (): ReactElement => {
500,
) as ['fname' | 'departmentId' | 'servedBy' | 'ts' | 'lm' | 'open', 'asc' | 'desc'];

const query = useQuery(debouncedParams, debouncedCustomFields, debouncedSort);
const query = currentChatQuery(debouncedParams, debouncedCustomFields, debouncedSort);
const canViewCurrentChats = usePermission('view-livechat-current-chats');
const canRemoveClosedChats = usePermission('remove-closed-livechat-room');
const directoryRoute = useRoute('omnichannel-current-chats');

const { reload, ...result } = useEndpointData('/v1/livechat/rooms', query);
const result = useCurrentChats(query);

const { data: allCustomFields } = useAllCustomFields();

const { current, itemsPerPage, setItemsPerPage, setCurrent, ...paginationProps } = usePagination();
Expand Down Expand Up @@ -184,13 +183,13 @@ const CurrentChatsRoute = (): ReactElement => {
</GenericTableCell>
{canRemoveClosedChats && !open && (
<GenericTableCell withTruncatedText>
<RemoveChatButton _id={_id} reload={reload} />
<RemoveChatButton _id={_id} />
</GenericTableCell>
)}
</GenericTableRow>
);
},
[canRemoveClosedChats, onRowClick, reload, t],
[canRemoveClosedChats, onRowClick, t],
);

if (!canViewCurrentChats) {
Expand Down Expand Up @@ -282,15 +281,15 @@ const CurrentChatsRoute = (): ReactElement => {
)}
</GenericTableHeader>
<GenericTableBody data-qa='GenericTableCurrentChatsBody'>
{result.phase === AsyncStatePhase.LOADING && <GenericTableLoadingTable headerCells={4} />}
{result.phase === AsyncStatePhase.RESOLVED && result.value.rooms.map((room) => renderRow({ ...room }))}
{result.isLoading && <GenericTableLoadingTable headerCells={4} />}
{result.isSuccess && result.data.rooms.map((room) => renderRow({ ...room }))}
</GenericTableBody>
</GenericTable>
{result.phase === AsyncStatePhase.RESOLVED && (
{result.isSuccess && (
<Pagination
current={current}
itemsPerPage={itemsPerPage}
count={result.value.total}
count={result.data.total}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
{...paginationProps}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
import { Table, IconButton } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { useSetModal, useToastMessageDispatch, useMethod, useTranslation } from '@rocket.chat/ui-contexts';
import { useSetModal, useToastMessageDispatch, useTranslation } from '@rocket.chat/ui-contexts';
import React, { FC } from 'react';

import GenericModal from '../../../components/GenericModal';
import { useRemoveCurrentChatMutation } from './hooks/useRemoveCurrentChatMutation';

const RemoveChatButton: FC<{ _id: string; reload: () => void }> = ({ _id, reload }) => {
const removeChat = useMethod('livechat:removeRoom');
const RemoveChatButton: FC<{ _id: string }> = ({ _id }) => {
const removeCurrentChatMutation = useRemoveCurrentChatMutation();
const setModal = useSetModal();
const dispatchToastMessage = useToastMessageDispatch();
const t = useTranslation();

const handleRemoveClick = useMutableCallback(async () => {
try {
await removeChat(_id);
} catch (error) {
console.log(error);
}
reload();
removeCurrentChatMutation.mutate(_id);
});

const handleDelete = useMutableCallback((e) => {
Expand All @@ -43,7 +39,7 @@ const RemoveChatButton: FC<{ _id: string; reload: () => void }> = ({ _id, reload

return (
<Table.Cell fontScale='p2' color='hint' withTruncatedText data-qa='current-chats-cell-delete'>
<IconButton small icon='trash' title={t('Remove')} onClick={handleDelete} />
<IconButton small icon='trash' title={t('Remove')} disabled={removeCurrentChatMutation.isLoading} onClick={handleDelete} />
</Table.Cell>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { GETLivechatRoomsParams, OperationResult } from '@rocket.chat/rest-typings';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useQuery, UseQueryResult } from '@tanstack/react-query';

export const useCurrentChats = (query: GETLivechatRoomsParams): UseQueryResult<OperationResult<'GET', '/v1/livechat/rooms'>> => {
const currentChats = useEndpoint('GET', '/v1/livechat/rooms');

return useQuery(['current-chats', query], () => currentChats(query));
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { IRoom } from '@rocket.chat/core-typings';
import { useMethod } from '@rocket.chat/ui-contexts';
import { useQueryClient, useMutation, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';

export const useRemoveCurrentChatMutation = (
options?: Omit<UseMutationOptions<void, Error, IRoom['_id']>, 'mutationFn'>,
): UseMutationResult<void, Error, IRoom['_id']> => {
const removeRoom = useMethod('livechat:removeRoom');
const queryClient = useQueryClient();

return useMutation((rid) => removeRoom(rid), {
...options,
onSuccess: (...args) => {
queryClient.invalidateQueries(['current-chats']);
options?.onSuccess?.(...args);
},
});
};
3 changes: 2 additions & 1 deletion apps/meteor/definition/methods/omnichannel.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { IRoom } from '@rocket.chat/core-typings';
import '@rocket.chat/ui-contexts';

declare module '@rocket.chat/ui-contexts' {
Expand Down Expand Up @@ -30,7 +31,7 @@ declare module '@rocket.chat/ui-contexts' {
'livechat:removeCustomField': (...args: any[]) => any;
'livechat:removeMonitor': (...args: any[]) => any;
'livechat:removePriority': (...args: any[]) => any;
'livechat:removeRoom': (...args: any[]) => any;
'livechat:removeRoom': (rid: IRoom['_id']) => void;
'livechat:removeTag': (...args: any[]) => any;
'livechat:removeTrigger': (...args: any[]) => any;
'livechat:removeUnit': (...args: any[]) => any;
Expand Down