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

Implementation of sorting of requests in Request screen #1082

Merged
merged 6 commits into from
Dec 9, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions public/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@
"noRequestFound": "No Request Found",
"sort": "Sort",
"filter": "Filter",
"Oldest": "Oldest First",
"Latest": "Latest First",
"noOrgError": "Organizations not found, please create an organization through dashboard",
"userApproved": "User Approved",
"userRejected": "User Rejected",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@
"noRequestFound": "Aucune demande trouvée",
"sort": "Trier",
"filter": "Filtre",
"Oldest": "Les plus anciennes d'abord",
"Latest": "Les plus récentes d'abord",
"userApproved": "Approuvé par l'utilisateur",
"userRejected": "Utilisateur rejeté",
"noResultsFoundFor": "Aucun résultat trouvé pour ",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@
"noRequestFound": "कोई अनुरोध नहीं मिला।",
"sort": "छांटें",
"filter": "फ़िल्टर",
"Oldest": "सबसे पुराना पहले",
"Latest": "सबसे नवीनतम पहले",
"userApproved": "उपयोगकर्ता स्वीकृत",
"userRejected": "उपयोगकर्ता अस्वीकृत",
"noResultsFoundFor": "के लिए कोई परिणाम नहीं मिला ",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/sp.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@
"noRequestFound": "No se encontró ninguna solicitud.",
"sort": "Ordenar",
"filter": "Filtrar",
"Oldest": "Más Antiguas Primero",
"Latest": "Más Recientes Primero",
"userApproved": "Aprobado por el usuario",
"userRejected": "Usuario rechazado",
"noResultsFoundFor": "No se encontraron resultados para ",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@
"noRequestFound": "找不到請求。",
"sort": "排序",
"filter": "過濾",
"Oldest": "最旧的优先",
"Latest": "最新的优先",
"userApproved": "用戶批准",
"userRejected": "用戶被拒絕",
"noResultsFoundFor": "未找到结果 ",
Expand Down
109 changes: 92 additions & 17 deletions src/screens/Requests/Requests.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { act, render, screen } from '@testing-library/react';
import { act, render, screen, fireEvent } from '@testing-library/react';
import 'jest-localstorage-mock';
import 'jest-location-mock';
import { I18nextProvider } from 'react-i18next';
Expand Down Expand Up @@ -75,22 +75,6 @@ describe('Testing Request screen', () => {
await wait();
});

test('Testing seach by name functionality', async () => {
render(
<MockedProvider addTypename={false} link={link3}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<Requests />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>
);

await wait();
});

test('Testing accept user functionality', async () => {
render(
<MockedProvider addTypename={false} link={link3}>
Expand Down Expand Up @@ -166,4 +150,95 @@ describe('Testing Request screen', () => {
'Organizations not found, please create an organization through dashboard'
);
});

test('Testing search latest and oldest toggle', async () => {
await act(async () => {
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<Requests />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>
);

await wait();

const searchInput = screen.getByTestId('sort');
expect(searchInput).toBeInTheDocument();

const inputText = screen.getByTestId('sortuser');

fireEvent.click(inputText);
const toggleText = screen.getByTestId('latest');

fireEvent.click(toggleText);

expect(searchInput).toBeInTheDocument();
fireEvent.click(inputText);
const toggleTite = screen.getByTestId('oldest');
fireEvent.click(toggleTite);
expect(searchInput).toBeInTheDocument();
});
});
test('Testing seach by name functionality', async () => {
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<Requests />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>
);

await wait();

const search1 = 'John{backspace}{backspace}{backspace}{backspace}';
userEvent.type(screen.getByTestId(/searchByName/i), search1);

const search2 = 'Pete{backspace}{backspace}{backspace}{backspace}';
userEvent.type(screen.getByTestId(/searchByName/i), search2);

const search3 =
'John{backspace}{backspace}{backspace}{backspace}Sam{backspace}{backspace}{backspace}';
userEvent.type(screen.getByTestId(/searchByName/i), search3);

const search4 = 'Sam{backspace}{backspace}P{backspace}';
userEvent.type(screen.getByTestId(/searchByName/i), search4);

const search5 = 'Xe';
userEvent.type(screen.getByTestId(/searchByName/i), search5);
userEvent.type(screen.getByTestId(/searchByName/i), '');
});

test('Does not display loading state when isLoading is false and usersData is present', async () => {
// Mock the scenario where isLoading is false and there is some data in usersData
render(
<MockedProvider addTypename={false} link={link}>
<BrowserRouter>
<Provider store={store}>
<I18nextProvider i18n={i18nForTest}>
<ToastContainer />
<Requests />
</I18nextProvider>
</Provider>
</BrowserRouter>
</MockedProvider>
);

// Wait for the component to finish rendering
await wait();

// Check if the loading state is NOT displayed
const loadingState = screen.queryByText(/Loading/i);
expect(loadingState).toBeNull();

// Add any additional assertions based on your test case
});
});
93 changes: 72 additions & 21 deletions src/screens/Requests/Requests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ const Requests = (): JSX.Element => {
const [hasMore, sethasMore] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const [searchByName, setSearchByName] = useState('');
const [sortingOption, setSortingOption] = useState('latest');
const [displayedUsers, setDisplayedUsers] = useState<
InterfaceQueryRequestListItem[]
>([]);

const [acceptAdminFunc] = useMutation(ACCEPT_ADMIN_MUTATION);
const [rejectAdminFunc] = useMutation(REJECT_ADMIN_MUTATION);
Expand Down Expand Up @@ -93,10 +97,14 @@ const Requests = (): JSX.Element => {
// To manage loading states
useEffect(() => {
if (!usersData) {
setDisplayedUsers([]);
return;
}
/* istanbul ignore next */
chandel-aman marked this conversation as resolved.
Show resolved Hide resolved
if (usersData.users.length < perPageResult) {
sethasMore(false);
} else {
setDisplayedUsers(usersData?.users);
}
}, [usersData]);

Expand Down Expand Up @@ -127,6 +135,13 @@ const Requests = (): JSX.Element => {
}
}, [loading]);

useEffect(() => {
if (usersData && usersData?.users.length > 0) {
const newDisplayedUsers = sortRequests(usersData?.users, sortingOption);
setDisplayedUsers(newDisplayedUsers);
}
}, [usersData, sortingOption]);

/* istanbul ignore next */
const resetAndRefetch = (): void => {
refetchUsers({
Expand Down Expand Up @@ -235,6 +250,31 @@ const Requests = (): JSX.Element => {
t('reject'),
];

const handleSorting = (option: string): void => {
setSortingOption(option);
};

const sortRequests = (
users: InterfaceQueryRequestListItem[],
sortingOption: string
): InterfaceQueryRequestListItem[] => {
const sortedRequest = [...users];

if (sortingOption === 'latest') {
sortedRequest.sort(
(a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
);
} else if (sortingOption === 'oldest') {
sortedRequest.sort(
(a, b) =>
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
);
}

return sortedRequest;
};

return (
<>
<SuperAdminScreen title={t('requests')} screenName="Requests">
Expand All @@ -261,6 +301,7 @@ const Requests = (): JSX.Element => {
onChange={debouncedHandleSearchByName}
/>
<Button
data-testid="searchButton"
tabIndex={-1}
className={`position-absolute z-10 bottom-0 end-0 h-100 d-flex justify-content-center align-items-center`}
>
Expand All @@ -270,15 +311,31 @@ const Requests = (): JSX.Element => {
</div>
<div className={styles.btnsBlock}>
<div className="d-flex">
<Dropdown aria-expanded="false" title="Sort organizations">
<Dropdown.Toggle variant="outline-success">
<Dropdown
aria-expanded="false"
title="Sort organizations"
data-testid="sort"
>
<Dropdown.Toggle
variant="outline-success"
data-testid="sortuser"
>
<SortIcon className={'me-1'} />
{t('sort')}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here instead of Sort text you should show the selected option, and the sort button should become of variant='success' meaning sorting is active now

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">Action 1</Dropdown.Item>
<Dropdown.Item href="#/action-2">Action 2</Dropdown.Item>
<Dropdown.Item href="#/action-3">Action 3</Dropdown.Item>
<Dropdown.Item
onClick={(): void => handleSorting('latest')}
data-testid="latest"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whichever option is selected should be highlighted

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

>
{t('Latest')}
</Dropdown.Item>
<Dropdown.Item
onClick={(): void => handleSorting('oldest')}
data-testid="oldest"
>
{t('Oldest')}
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Dropdown aria-expanded="false" title="Filter organizations">
Expand All @@ -295,19 +352,7 @@ const Requests = (): JSX.Element => {
</div>
</div>
</div>
{isLoading == false &&
usersData?.users.length === 0 &&
searchByName.length > 0 ? (
<div className={styles.notFound}>
<h4>
{t('noResultsFoundFor')} &quot;{searchByName}&quot;
</h4>
</div>
) : isLoading == false && usersData?.users.length === 0 ? (
<div className={styles.notFound}>
<h4>{t('noRequestFound')}</h4>
</div>
) : isLoading ? (
{isLoading ? (
<TableLoader headerTitles={headerTitles} noOfRows={perPageResult} />
) : (
<InfiniteScroll
Expand Down Expand Up @@ -336,10 +381,11 @@ const Requests = (): JSX.Element => {
</tr>
</thead>
<tbody>
{usersData?.users &&
usersData.users.map((user, index) => {
{displayedUsers &&
displayedUsers.length > 0 &&
displayedUsers.map((user, index) => {
return (
<tr key={user._id}>
<tr key={user._id} data-testid="displayedUsers">
<th scope="row">{index + 1}</th>
<td>{`${user.firstName} ${user.lastName}`}</td>
<td>{user.email}</td>
Expand Down Expand Up @@ -372,6 +418,11 @@ const Requests = (): JSX.Element => {
</Table>
</InfiniteScroll>
)}
{!isLoading && displayedUsers.length === 0 && (
<div className="w-100 text-center my-4">
<h5 className="m-0 ">{t('noRequestFound')}</h5>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why remove this line ?

{t('noResultsFoundFor')} &quot;{searchByName}&quot;

If no request is found for a particular search, the above text should be displayed

</div>
)}
</SuperAdminScreen>
</>
);
Expand Down
Loading