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 { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import api from 'helpers/api';
|
import api from 'helpers/api';
|
||||||
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
|
||||||
import useFormatMessage from 'hooks/useFormatMessage';
|
|
||||||
|
|
||||||
export default function useAdminUpdateUser(userId) {
|
export default function useAdminUpdateUser(userId) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const enqueueSnackbar = useEnqueueSnackbar();
|
|
||||||
const formatMessage = useFormatMessage();
|
|
||||||
|
|
||||||
const query = useMutation({
|
const query = useMutation({
|
||||||
mutationFn: async (payload) => {
|
mutationFn: async (payload) => {
|
||||||
@@ -19,15 +15,6 @@ export default function useAdminUpdateUser(userId) {
|
|||||||
queryKey: ['admin', 'users'],
|
queryKey: ['admin', 'users'],
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onError: () => {
|
|
||||||
enqueueSnackbar(formatMessage('editUser.error'), {
|
|
||||||
variant: 'error',
|
|
||||||
persist: true,
|
|
||||||
SnackbarProps: {
|
|
||||||
'data-test': 'snackbar-error',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
|
|||||||
@@ -226,6 +226,8 @@
|
|||||||
"userForm.email": "Email",
|
"userForm.email": "Email",
|
||||||
"userForm.role": "Role",
|
"userForm.role": "Role",
|
||||||
"userForm.password": "Password",
|
"userForm.password": "Password",
|
||||||
|
"userForm.mandatoryInput": "{inputName} is required.",
|
||||||
|
"userForm.validateEmail": "Email must be valid.",
|
||||||
"createUser.submit": "Create",
|
"createUser.submit": "Create",
|
||||||
"createUser.successfullyCreated": "The user has been created.",
|
"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>",
|
"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 Chip from '@mui/material/Chip';
|
||||||
import Typography from '@mui/material/Typography';
|
import Typography from '@mui/material/Typography';
|
||||||
import MuiTextField from '@mui/material/TextField';
|
import MuiTextField from '@mui/material/TextField';
|
||||||
|
import Alert from '@mui/material/Alert';
|
||||||
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router-dom';
|
||||||
|
import { yupResolver } from '@hookform/resolvers/yup';
|
||||||
|
import * as yup from 'yup';
|
||||||
|
|
||||||
import Can from 'components/Can';
|
import Can from 'components/Can';
|
||||||
import Container from 'components/Container';
|
import Container from 'components/Container';
|
||||||
@@ -20,11 +23,45 @@ import useFormatMessage from 'hooks/useFormatMessage';
|
|||||||
import useRoles from 'hooks/useRoles.ee';
|
import useRoles from 'hooks/useRoles.ee';
|
||||||
import useAdminUpdateUser from 'hooks/useAdminUpdateUser';
|
import useAdminUpdateUser from 'hooks/useAdminUpdateUser';
|
||||||
import useAdminUser from 'hooks/useAdminUser';
|
import useAdminUser from 'hooks/useAdminUser';
|
||||||
|
import useCurrentUserAbility from 'hooks/useCurrentUserAbility';
|
||||||
|
import { getGeneralErrorMessage } from 'helpers/errors';
|
||||||
|
|
||||||
function generateRoleOptions(roles) {
|
function generateRoleOptions(roles) {
|
||||||
return roles?.map(({ name: label, id: value }) => ({ label, value }));
|
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() {
|
export default function EditUser() {
|
||||||
const formatMessage = useFormatMessage();
|
const formatMessage = useFormatMessage();
|
||||||
const { userId } = useParams();
|
const { userId } = useParams();
|
||||||
@@ -36,13 +73,15 @@ export default function EditUser() {
|
|||||||
const roles = data?.data;
|
const roles = data?.data;
|
||||||
const enqueueSnackbar = useEnqueueSnackbar();
|
const enqueueSnackbar = useEnqueueSnackbar();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const currentUserAbility = useCurrentUserAbility();
|
||||||
|
const canUpdateRole = currentUserAbility.can('update', 'Role');
|
||||||
|
|
||||||
const handleUserUpdate = async (userDataToUpdate) => {
|
const handleUserUpdate = async (userDataToUpdate, e, setError) => {
|
||||||
try {
|
try {
|
||||||
await updateUser({
|
await updateUser({
|
||||||
fullName: userDataToUpdate.fullName,
|
fullName: userDataToUpdate.fullName,
|
||||||
email: userDataToUpdate.email,
|
email: userDataToUpdate.email,
|
||||||
roleId: userDataToUpdate.role?.id,
|
roleId: userDataToUpdate.roleId,
|
||||||
});
|
});
|
||||||
|
|
||||||
enqueueSnackbar(formatMessage('editUser.successfullyUpdated'), {
|
enqueueSnackbar(formatMessage('editUser.successfullyUpdated'), {
|
||||||
@@ -55,7 +94,31 @@ export default function EditUser() {
|
|||||||
|
|
||||||
navigate(URLS.USERS);
|
navigate(URLS.USERS);
|
||||||
} catch (error) {
|
} 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 && (
|
{!isUserLoading && (
|
||||||
<Form defaultValues={user} onSubmit={handleUserUpdate}>
|
<Form
|
||||||
<Stack direction="column" gap={2}>
|
defaultValues={
|
||||||
<Stack direction="row" gap={2} mb={2} alignItems="center">
|
user
|
||||||
<Typography variant="h6" noWrap>
|
? {
|
||||||
{formatMessage('editUser.status')}
|
fullName: user.fullName,
|
||||||
</Typography>
|
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
|
<Chip
|
||||||
label={user.status}
|
label={user.status}
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
color={user.status === 'active' ? 'success' : 'warning'}
|
color={user.status === 'active' ? 'success' : 'warning'}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
<TextField
|
<TextField
|
||||||
required={true}
|
required={true}
|
||||||
name="fullName"
|
name="fullName"
|
||||||
label={formatMessage('userForm.fullName')}
|
label={formatMessage('userForm.fullName')}
|
||||||
data-test="full-name-input"
|
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"
|
|
||||||
fullWidth
|
fullWidth
|
||||||
disablePortal
|
error={!!errors?.fullName}
|
||||||
disableClearable={true}
|
helperText={errors?.fullName?.message}
|
||||||
options={generateRoleOptions(roles)}
|
|
||||||
renderInput={(params) => (
|
|
||||||
<MuiTextField
|
|
||||||
{...params}
|
|
||||||
label={formatMessage('userForm.role')}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
loading={isRolesLoading}
|
|
||||||
/>
|
/>
|
||||||
</Can>
|
|
||||||
|
|
||||||
<LoadingButton
|
<TextField
|
||||||
type="submit"
|
required={true}
|
||||||
variant="contained"
|
name="email"
|
||||||
color="primary"
|
label={formatMessage('userForm.email')}
|
||||||
sx={{ boxShadow: 2 }}
|
data-test="email-input"
|
||||||
loading={isAdminUpdateUserPending}
|
fullWidth
|
||||||
data-test="update-button"
|
error={!!errors?.email}
|
||||||
>
|
helperText={errors?.email?.message}
|
||||||
{formatMessage('editUser.submit')}
|
/>
|
||||||
</LoadingButton>
|
|
||||||
</Stack>
|
<Can I="update" a="Role">
|
||||||
</Form>
|
<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>
|
||||||
</Grid>
|
</Grid>
|
||||||
|
|||||||
Reference in New Issue
Block a user