feat: introduce inline error messages in EditUser form
This commit is contained in:
18
packages/web/src/helpers/errors.js
Normal file
18
packages/web/src/helpers/errors.js
Normal file
@@ -0,0 +1,18 @@
|
||||
// Helpers to extract errors received from the API
|
||||
|
||||
export const getGeneralErrorMessage = ({ error, fallbackMessage }) => {
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
|
||||
const errors = error?.response?.data?.errors;
|
||||
const generalError = errors?.general;
|
||||
|
||||
if (generalError && Array.isArray(generalError)) {
|
||||
return generalError.join(' ');
|
||||
}
|
||||
|
||||
if (!errors) {
|
||||
return error?.message || fallbackMessage;
|
||||
}
|
||||
};
|
||||
@@ -1,12 +1,8 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import api from 'helpers/api';
|
||||
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
||||
import useFormatMessage from 'hooks/useFormatMessage';
|
||||
|
||||
export default function useAdminUpdateUser(userId) {
|
||||
const queryClient = useQueryClient();
|
||||
const enqueueSnackbar = useEnqueueSnackbar();
|
||||
const formatMessage = useFormatMessage();
|
||||
|
||||
const query = useMutation({
|
||||
mutationFn: async (payload) => {
|
||||
@@ -19,15 +15,6 @@ export default function useAdminUpdateUser(userId) {
|
||||
queryKey: ['admin', 'users'],
|
||||
});
|
||||
},
|
||||
onError: () => {
|
||||
enqueueSnackbar(formatMessage('editUser.error'), {
|
||||
variant: 'error',
|
||||
persist: true,
|
||||
SnackbarProps: {
|
||||
'data-test': 'snackbar-error',
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return query;
|
||||
|
||||
@@ -226,6 +226,8 @@
|
||||
"userForm.email": "Email",
|
||||
"userForm.role": "Role",
|
||||
"userForm.password": "Password",
|
||||
"userForm.mandatoryInput": "{inputName} is required.",
|
||||
"userForm.validateEmail": "Email must be valid.",
|
||||
"createUser.submit": "Create",
|
||||
"createUser.successfullyCreated": "The user has been created.",
|
||||
"createUser.invitationEmailInfo": "Invitation email will be sent if SMTP credentials are valid. Otherwise, you can share the invitation link manually: <link></link>",
|
||||
|
||||
@@ -5,9 +5,12 @@ import Stack from '@mui/material/Stack';
|
||||
import Chip from '@mui/material/Chip';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import MuiTextField from '@mui/material/TextField';
|
||||
import Alert from '@mui/material/Alert';
|
||||
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
||||
import * as React from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import * as yup from 'yup';
|
||||
|
||||
import Can from 'components/Can';
|
||||
import Container from 'components/Container';
|
||||
@@ -20,11 +23,45 @@ import useFormatMessage from 'hooks/useFormatMessage';
|
||||
import useRoles from 'hooks/useRoles.ee';
|
||||
import useAdminUpdateUser from 'hooks/useAdminUpdateUser';
|
||||
import useAdminUser from 'hooks/useAdminUser';
|
||||
import useCurrentUserAbility from 'hooks/useCurrentUserAbility';
|
||||
import { getGeneralErrorMessage } from 'helpers/errors';
|
||||
|
||||
function generateRoleOptions(roles) {
|
||||
return roles?.map(({ name: label, id: value }) => ({ label, value }));
|
||||
}
|
||||
|
||||
const getValidationSchema = (formatMessage, canUpdateRole) => {
|
||||
const getMandatoryFieldMessage = (fieldTranslationId) =>
|
||||
formatMessage('userForm.mandatoryInput', {
|
||||
inputName: formatMessage(fieldTranslationId),
|
||||
});
|
||||
|
||||
return yup.object().shape({
|
||||
fullName: yup
|
||||
.string()
|
||||
.trim()
|
||||
.required(getMandatoryFieldMessage('userForm.fullName')),
|
||||
email: yup
|
||||
.string()
|
||||
.trim()
|
||||
.email(formatMessage('userForm.validateEmail'))
|
||||
.required(getMandatoryFieldMessage('userForm.email')),
|
||||
...(canUpdateRole
|
||||
? {
|
||||
roleId: yup
|
||||
.string()
|
||||
.required(getMandatoryFieldMessage('userForm.role')),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
};
|
||||
|
||||
const defaultValues = {
|
||||
fullName: '',
|
||||
email: '',
|
||||
roleId: '',
|
||||
};
|
||||
|
||||
export default function EditUser() {
|
||||
const formatMessage = useFormatMessage();
|
||||
const { userId } = useParams();
|
||||
@@ -36,13 +73,15 @@ export default function EditUser() {
|
||||
const roles = data?.data;
|
||||
const enqueueSnackbar = useEnqueueSnackbar();
|
||||
const navigate = useNavigate();
|
||||
const currentUserAbility = useCurrentUserAbility();
|
||||
const canUpdateRole = currentUserAbility.can('update', 'Role');
|
||||
|
||||
const handleUserUpdate = async (userDataToUpdate) => {
|
||||
const handleUserUpdate = async (userDataToUpdate, e, setError) => {
|
||||
try {
|
||||
await updateUser({
|
||||
fullName: userDataToUpdate.fullName,
|
||||
email: userDataToUpdate.email,
|
||||
roleId: userDataToUpdate.role?.id,
|
||||
roleId: userDataToUpdate.roleId,
|
||||
});
|
||||
|
||||
enqueueSnackbar(formatMessage('editUser.successfullyUpdated'), {
|
||||
@@ -55,7 +94,31 @@ export default function EditUser() {
|
||||
|
||||
navigate(URLS.USERS);
|
||||
} catch (error) {
|
||||
throw new Error('Failed while updating!');
|
||||
const errors = error?.response?.data?.errors;
|
||||
|
||||
if (errors) {
|
||||
const fieldNames = Object.keys(defaultValues);
|
||||
Object.entries(errors).forEach(([fieldName, fieldErrors]) => {
|
||||
if (fieldNames.includes(fieldName) && Array.isArray(fieldErrors)) {
|
||||
setError(fieldName, {
|
||||
type: 'fieldRequestError',
|
||||
message: fieldErrors.join(', '),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const generalError = getGeneralErrorMessage({
|
||||
error,
|
||||
fallbackMessage: formatMessage('editUser.error'),
|
||||
});
|
||||
|
||||
if (generalError) {
|
||||
setError('root.general', {
|
||||
type: 'requestError',
|
||||
message: generalError,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -80,65 +143,94 @@ export default function EditUser() {
|
||||
)}
|
||||
|
||||
{!isUserLoading && (
|
||||
<Form defaultValues={user} onSubmit={handleUserUpdate}>
|
||||
<Stack direction="column" gap={2}>
|
||||
<Stack direction="row" gap={2} mb={2} alignItems="center">
|
||||
<Typography variant="h6" noWrap>
|
||||
{formatMessage('editUser.status')}
|
||||
</Typography>
|
||||
<Form
|
||||
defaultValues={
|
||||
user
|
||||
? {
|
||||
fullName: user.fullName,
|
||||
email: user.email,
|
||||
roleId: user.role.id,
|
||||
}
|
||||
: defaultValues
|
||||
}
|
||||
onSubmit={handleUserUpdate}
|
||||
resolver={yupResolver(
|
||||
getValidationSchema(formatMessage, canUpdateRole),
|
||||
)}
|
||||
noValidate
|
||||
render={({ formState: { errors } }) => (
|
||||
<Stack direction="column" gap={2}>
|
||||
<Stack direction="row" gap={2} mb={2} alignItems="center">
|
||||
<Typography variant="h6" noWrap>
|
||||
{formatMessage('editUser.status')}
|
||||
</Typography>
|
||||
|
||||
<Chip
|
||||
label={user.status}
|
||||
variant="outlined"
|
||||
color={user.status === 'active' ? 'success' : 'warning'}
|
||||
/>
|
||||
</Stack>
|
||||
<Chip
|
||||
label={user.status}
|
||||
variant="outlined"
|
||||
color={user.status === 'active' ? 'success' : 'warning'}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<TextField
|
||||
required={true}
|
||||
name="fullName"
|
||||
label={formatMessage('userForm.fullName')}
|
||||
data-test="full-name-input"
|
||||
fullWidth
|
||||
/>
|
||||
|
||||
<TextField
|
||||
required={true}
|
||||
name="email"
|
||||
label={formatMessage('userForm.email')}
|
||||
data-test="email-input"
|
||||
fullWidth
|
||||
/>
|
||||
|
||||
<Can I="update" a="Role">
|
||||
<ControlledAutocomplete
|
||||
name="role.id"
|
||||
<TextField
|
||||
required={true}
|
||||
name="fullName"
|
||||
label={formatMessage('userForm.fullName')}
|
||||
data-test="full-name-input"
|
||||
fullWidth
|
||||
disablePortal
|
||||
disableClearable={true}
|
||||
options={generateRoleOptions(roles)}
|
||||
renderInput={(params) => (
|
||||
<MuiTextField
|
||||
{...params}
|
||||
label={formatMessage('userForm.role')}
|
||||
/>
|
||||
)}
|
||||
loading={isRolesLoading}
|
||||
error={!!errors?.fullName}
|
||||
helperText={errors?.fullName?.message}
|
||||
/>
|
||||
</Can>
|
||||
|
||||
<LoadingButton
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
sx={{ boxShadow: 2 }}
|
||||
loading={isAdminUpdateUserPending}
|
||||
data-test="update-button"
|
||||
>
|
||||
{formatMessage('editUser.submit')}
|
||||
</LoadingButton>
|
||||
</Stack>
|
||||
</Form>
|
||||
<TextField
|
||||
required={true}
|
||||
name="email"
|
||||
label={formatMessage('userForm.email')}
|
||||
data-test="email-input"
|
||||
fullWidth
|
||||
error={!!errors?.email}
|
||||
helperText={errors?.email?.message}
|
||||
/>
|
||||
|
||||
<Can I="update" a="Role">
|
||||
<ControlledAutocomplete
|
||||
name="roleId"
|
||||
fullWidth
|
||||
disablePortal
|
||||
disableClearable={true}
|
||||
options={generateRoleOptions(roles)}
|
||||
renderInput={(params) => (
|
||||
<MuiTextField
|
||||
{...params}
|
||||
label={formatMessage('userForm.role')}
|
||||
error={!!errors?.roleId}
|
||||
helperText={errors?.roleId?.message}
|
||||
/>
|
||||
)}
|
||||
loading={isRolesLoading}
|
||||
showHelperText={false}
|
||||
/>
|
||||
</Can>
|
||||
|
||||
{errors?.root?.general && (
|
||||
<Alert data-test="update-user-error-alert" severity="error">
|
||||
{errors?.root?.general?.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<LoadingButton
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
sx={{ boxShadow: 2 }}
|
||||
loading={isAdminUpdateUserPending}
|
||||
data-test="update-button"
|
||||
>
|
||||
{formatMessage('editUser.submit')}
|
||||
</LoadingButton>
|
||||
</Stack>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
Reference in New Issue
Block a user