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

Admin should be able to disable or enable users #769

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open
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
22 changes: 21 additions & 1 deletion src/common/api/userApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export type UpdateProfilePictureRequest = {
profilePicture: FormData;
};
export type DeleteProfilePictureRequest = Pick<User, 'id'>;
export type DisableUserRequest = Pick<User, 'id'>;
export type EnableUserRequest = Pick<User, 'id'>;

export const userApi = createApi({
reducerPath: 'userApi',
Expand Down Expand Up @@ -76,7 +78,7 @@ export const userApi = createApi({
}),

getUserHistory: builder.query<PaginatedResult<HistoricalRecord<User>>, string>({
query: url => url
query: url => url,
}),

inviteUser: builder.mutation<User, CreateUserRequest>({
Expand Down Expand Up @@ -215,6 +217,22 @@ export const userApi = createApi({
}),
invalidatesTags: ['User'],
}),

disableUser: builder.mutation<User, DisableUserRequest>({
query: ({ id }) => ({
url: `/users/${id}/disable/`,
method: 'POST',
}),
invalidatesTags: ['User'],
}),

enableUser: builder.mutation<User, EnableUserRequest>({
query: ({ id }) => ({
url: `/users/${id}/enable/`,
method: 'POST',
}),
invalidatesTags: ['User'],
}),
}),
});

Expand All @@ -240,4 +258,6 @@ export const {
useUpdateProfilePictureMutation,
useDeleteProfilePictureMutation,
useGetUserHistoryQuery,
useDisableUserMutation,
useEnableUserMutation,
} = userApi;
2 changes: 2 additions & 0 deletions src/common/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ export interface User {
profilePicture: Image | null;
role: Role;
newEmail: string | null;
isActive: boolean;
disabledAt: string | null;
}
96 changes: 89 additions & 7 deletions src/features/user-dashboard/components/UserDetailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,31 @@ import WithUnsavedChangesPrompt from 'common/components/WithUnsavedChangesPrompt
import { addServerErrors } from 'common/error/utilities';
import { Role, User, RoleOption, ServerValidationErrors } from 'common/models';
import { FC, useEffect } from 'react';
import { Col, Row } from 'react-bootstrap';
import { Button, Col, Row } from 'react-bootstrap';
import Form from 'react-bootstrap/Form';
import { Controller, useForm } from 'react-hook-form';
import * as yup from 'yup';
import styled from 'styled-components';
import { useModalWithData } from 'common/hooks/useModalWithData';
import { SimpleConfirmModal } from 'common/components/SimpleConfirmModal';
import * as notificationService from 'common/services/notification';
import { useDisableUserMutation, useEnableUserMutation } from 'common/api/userApi';
import { handleApiError, isFetchBaseQueryError } from 'common/api/handleApiError';
import { Trans, useTranslation } from 'react-i18next';
import { Constants } from 'utils/constants';

export type FormData = Pick<User, 'email' | 'firstName' | 'lastName' | 'role'>;
const DisableButton = styled(Button)`
margin-left: 100px;
.spinner-container {
padding-right: 8px;
}
`;

export type DisableUserRequest = {
id: string;
};

export type FormData = Pick<User, 'email' | 'firstName' | 'lastName' | 'role' | 'id' | 'isActive'>;

export interface Props {
availableRoles: Role[];
Expand All @@ -26,9 +43,9 @@ export interface Props {
export const UserDetailForm: FC<Props> = ({
availableRoles,
defaultValues = {},
isRoleSelectorDisabled,
onSubmit,
submitButtonLabel = 'Submit',
isRoleSelectorDisabled,
serverValidationErrors,
}) => {
const { t } = useTranslation(['translation', 'common']);
Expand Down Expand Up @@ -66,6 +83,62 @@ export const UserDetailForm: FC<Props> = ({
}
}, [serverValidationErrors, setError]);

const [disableUser] = useDisableUserMutation();
const [enableUser] = useEnableUserMutation();

const [showDisableModal, hideDisableModal] = useModalWithData<User>(
user =>
// eslint-disable-next-line react/no-unstable-nested-components
({ in: open, onExited }) => {
const onSubmit = async () => {
try {
if (user.isActive) {
await disableUser({ id: user.id }).unwrap();
notificationService.showSuccessMessage('User disabled.');
} else {
await enableUser({ id: user.id }).unwrap();
notificationService.showSuccessMessage('User enabled.');
}

hideDisableModal();
} catch (error) {
if (isFetchBaseQueryError(error)) {
handleApiError(error);
} else {
if (user.isActive) {
notificationService.showErrorMessage('Could not disable user.');
} else {
notificationService.showErrorMessage('Could not enable user.');
}
throw error;
}
}
};

return (
<SimpleConfirmModal
title={user.isActive ? 'Disable User' : 'Enable User'}
show={open}
onCancel={hideDisableModal}
onConfirm={onSubmit}
confirmLabel={user.isActive ? 'Disable User' : 'Enable User'}
confirmVariant='danger'
onExited={onExited}
body={
<div>
<p className='m-0'>
{user.isActive
? 'Are you sure you want to disable this user?'
: 'Are you sure you want to enable this user?'}
</p>
</div>
}
/>
);
},
[],
);

return (
<WithUnsavedChangesPrompt when={isDirty && !(isSubmitting || isSubmitted)}>
<Form name='create-user-form' onSubmit={handleSubmit(onSubmit)}>
Expand Down Expand Up @@ -138,10 +211,19 @@ export const UserDetailForm: FC<Props> = ({
</Form.Text>
</Form.Group>

<div className='mt-3'>
<LoadingButton type='submit' disabled={!isValid} loading={isSubmitting}>
{submitButtonLabel}
</LoadingButton>
<div className='mt-3 d-flex justify-content-between'>
<div>
<LoadingButton type='submit' disabled={!isValid} loading={isSubmitting}>
{submitButtonLabel}
</LoadingButton>
</div>
<div>
{defaultValues.id ? (
<DisableButton onClick={() => showDisableModal(defaultValues as User)} variant='btn btn-danger'>
{defaultValues.isActive ? 'Disable' : 'Enable'}
</DisableButton>
) : null}
</div>
</div>
</Form>
</WithUnsavedChangesPrompt>
Expand Down
26 changes: 25 additions & 1 deletion src/features/user-dashboard/hooks/useUserTableData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ export type UserTableItem = {
role: RoleType;
profilePicture: Image | null;
actions: ActionButtonProps[];
isActive: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
disabledAt: string | null | any;
};

export const useUserTableData = (users: User[] = []) => {
const { userHasPermission } = useRbac();
const { t, i18n } = useTranslation(['translation', 'common']);
Expand Down Expand Up @@ -194,6 +196,11 @@ export const useUserTableData = (users: User[] = []) => {
</SubtleBadge>
),
},
{
accessor: 'isActive',
Header: 'Account Status',
Cell: ({ value: isActive }) => <span>{isActive ? 'Enabled' : 'Disabled'}</span>,
},
{
accessor: 'activatedAt',
Header: t('activatedDate', { ns: 'common' })!,
Expand All @@ -212,6 +219,21 @@ export const useUserTableData = (users: User[] = []) => {
</>
),
},
{
accessor: 'disabledAt',
Header: 'Disabled On',
Cell: ({ value: disabledAt }) => (
<>
{disabledAt instanceof Date ? (
<time dateTime={disabledAt.toISOString()}>
{new Intl.DateTimeFormat('en-US', { dateStyle: 'long' }).format(disabledAt)}
</time>
) : (
<></>
)}
</>
),
},
{
accessor: 'actions',
Header: '',
Expand Down Expand Up @@ -246,7 +268,9 @@ export const useUserTableData = (users: User[] = []) => {
firstName: user.firstName,
email: user.email,
role: user.role,
isActive: user.isActive,
profilePicture: user.profilePicture,
disabledAt: user.disabledAt ? new Date(user.disabledAt) : '',
activatedAt: user.activatedAt
? new Date(user.activatedAt)
: {
Expand Down
13 changes: 13 additions & 0 deletions src/features/user-dashboard/pages/UserListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,24 @@ export const UserListView: FC = () => {
{ label: t('admin', { ns: 'common' }), value: 'ADMIN' },
]),
},
{
attribute: 'active',
attributeLabel: 'Account Status',
FilterUI: EnumFilter([
{ label: 'Enabled', value: 'ENABLED' },
{ label: 'Disabled', value: 'DISABLED' },
]),
},
{
attribute: 'activatedAt',
attributeLabel: t('activatedDate', { ns: 'common' }),
FilterUI: RecentDateFilter([30, 90, 180]),
},
{
attribute: 'deactivatedAt',
attributeLabel: 'Deactivated Date',
FilterUI: RecentDateFilter([30, 90, 180]),
},
],
[t],
);
Expand Down