Compare commits

..

2 Commits

Author SHA1 Message Date
Jakub P.
a82dff5c79 test: use alert selector on role and user delete error 2024-12-12 10:57:20 +00:00
kasia.oczkowska
112baad65f feat: introduce inline error messages when deleting role or user 2024-12-12 10:57:20 +00:00
11 changed files with 243 additions and 262 deletions

View File

@@ -1,4 +1,4 @@
import { BasePage } from './base-page'; import { BasePage } from "./base-page";
const { faker } = require('@faker-js/faker'); const { faker } = require('@faker-js/faker');
const { expect } = require('@playwright/test'); const { expect } = require('@playwright/test');
@@ -14,10 +14,8 @@ export class AdminSetupPage extends BasePage {
this.fullNameTextField = this.page.getByTestId('fullName-text-field'); this.fullNameTextField = this.page.getByTestId('fullName-text-field');
this.emailTextField = this.page.getByTestId('email-text-field'); this.emailTextField = this.page.getByTestId('email-text-field');
this.passwordTextField = this.page.getByTestId('password-text-field'); this.passwordTextField = this.page.getByTestId('password-text-field');
this.repeatPasswordTextField = this.page.getByTestId( this.repeatPasswordTextField = this.page.getByTestId('repeat-password-text-field');
'repeat-password-text-field' this.createAdminButton = this.page.getByTestId('signUp-button');
);
this.createAdminButton = this.page.getByTestId('installation-button');
this.invalidFields = this.page.locator('p.Mui-error'); this.invalidFields = this.page.locator('p.Mui-error');
this.successAlert = this.page.getByTestId('success-alert'); this.successAlert = this.page.getByTestId('success-alert');
} }
@@ -61,10 +59,7 @@ export class AdminSetupPage extends BasePage {
} }
async expectSuccessMessageToContainLoginLink() { async expectSuccessMessageToContainLoginLink() {
await expect(await this.successAlert.locator('a')).toHaveAttribute( await expect(await this.successAlert.locator('a')).toHaveAttribute('href', '/login');
'href',
'/login'
);
} }
generateUser() { generateUser() {
@@ -74,7 +69,7 @@ export class AdminSetupPage extends BasePage {
fullName: faker.person.fullName(), fullName: faker.person.fullName(),
email: faker.internet.email(), email: faker.internet.email(),
password: faker.internet.password(), password: faker.internet.password(),
wronglyRepeatedPassword: faker.internet.password(), wronglyRepeatedPassword: faker.internet.password()
}; };
} }
} };

View File

@@ -9,6 +9,7 @@ export class DeleteRoleModal {
this.modal = page.getByTestId('delete-role-modal'); this.modal = page.getByTestId('delete-role-modal');
this.cancelButton = this.modal.getByTestId('confirmation-cancel-button'); this.cancelButton = this.modal.getByTestId('confirmation-cancel-button');
this.deleteButton = this.modal.getByTestId('confirmation-confirm-button'); this.deleteButton = this.modal.getByTestId('confirmation-confirm-button');
this.deleteAlert = this.modal.getByTestId('confirmation-dialog-error-alert');
} }
async close () { async close () {

View File

@@ -218,12 +218,7 @@ test.describe('Role management page', () => {
const row = await adminRolesPage.getRoleRowByName('Delete Role'); const row = await adminRolesPage.getRoleRowByName('Delete Role');
const modal = await adminRolesPage.clickDeleteRole(row); const modal = await adminRolesPage.clickDeleteRole(row);
await modal.deleteButton.click(); await modal.deleteButton.click();
await adminRolesPage.snackbar.waitFor({ await expect(modal.deleteAlert).toHaveCount(1);
state: 'attached',
});
const snackbar = await adminRolesPage.getSnackbarData('snackbar-delete-role-error');
await expect(snackbar.variant).toBe('error');
await adminRolesPage.closeSnackbar();
await modal.close(); await modal.close();
} }
); );
@@ -318,7 +313,6 @@ test.describe('Role management page', () => {
const row = await adminUsersPage.findUserPageWithEmail( const row = await adminUsersPage.findUserPageWithEmail(
'user-delete-role-test@automatisch.io' 'user-delete-role-test@automatisch.io'
); );
// await test.waitForTimeout(10000);
const modal = await adminUsersPage.clickDeleteUser(row); const modal = await adminUsersPage.clickDeleteUser(row);
await modal.deleteButton.click(); await modal.deleteButton.click();
await adminUsersPage.snackbar.waitFor({ await adminUsersPage.snackbar.waitFor({
@@ -335,15 +329,7 @@ test.describe('Role management page', () => {
const row = await adminRolesPage.getRoleRowByName('Cannot Delete Role'); const row = await adminRolesPage.getRoleRowByName('Cannot Delete Role');
const modal = await adminRolesPage.clickDeleteRole(row); const modal = await adminRolesPage.clickDeleteRole(row);
await modal.deleteButton.click(); await modal.deleteButton.click();
await adminRolesPage.snackbar.waitFor({ await expect(modal.deleteAlert).toHaveCount(1);
state: 'attached',
});
/*
* TODO: await snackbar - make assertions based on product
* decisions
const snackbar = await adminRolesPage.getSnackbarData();
await expect(snackbar.variant).toBe('...');
*/
await adminRolesPage.closeSnackbar(); await adminRolesPage.closeSnackbar();
}); });
}); });

View File

@@ -6,6 +6,7 @@ import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent'; import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText'; import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import Alert from '@mui/material/Alert';
function ConfirmationDialog(props) { function ConfirmationDialog(props) {
const { const {
@@ -16,6 +17,7 @@ function ConfirmationDialog(props) {
cancelButtonChildren, cancelButtonChildren,
confirmButtonChildren, confirmButtonChildren,
open = true, open = true,
errorMessage,
} = props; } = props;
const dataTest = props['data-test']; const dataTest = props['data-test'];
return ( return (
@@ -44,6 +46,11 @@ function ConfirmationDialog(props) {
</Button> </Button>
)} )}
</DialogActions> </DialogActions>
{errorMessage && (
<Alert data-test="confirmation-dialog-error-alert" severity="error">
{errorMessage}
</Alert>
)}
</Dialog> </Dialog>
); );
} }
@@ -57,6 +64,7 @@ ConfirmationDialog.propTypes = {
confirmButtonChildren: PropTypes.node.isRequired, confirmButtonChildren: PropTypes.node.isRequired,
open: PropTypes.bool, open: PropTypes.bool,
'data-test': PropTypes.string, 'data-test': PropTypes.string,
errorMessage: PropTypes.string,
}; };
export default ConfirmationDialog; export default ConfirmationDialog;

View File

@@ -4,6 +4,7 @@ import IconButton from '@mui/material/IconButton';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar'; import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
import * as React from 'react'; import * as React from 'react';
import { getGeneralErrorMessage, getFieldErrorMessage } from 'helpers/errors';
import Can from 'components/Can'; import Can from 'components/Can';
import ConfirmationDialog from 'components/ConfirmationDialog'; import ConfirmationDialog from 'components/ConfirmationDialog';
import useFormatMessage from 'hooks/useFormatMessage'; import useFormatMessage from 'hooks/useFormatMessage';
@@ -15,7 +16,21 @@ function DeleteRoleButton(props) {
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar(); const enqueueSnackbar = useEnqueueSnackbar();
const { mutateAsync: deleteRole } = useAdminDeleteRole(roleId); const {
mutateAsync: deleteRole,
error: deleteRoleError,
reset: resetDeleteRole,
} = useAdminDeleteRole(roleId);
const roleErrorMessage = getFieldErrorMessage({
fieldName: 'role',
error: deleteRoleError,
});
const generalErrorMessage = getGeneralErrorMessage({
error: deleteRoleError,
fallbackMessage: formatMessage('deleteRoleButton.generalError'),
});
const handleConfirm = React.useCallback(async () => { const handleConfirm = React.useCallback(async () => {
try { try {
@@ -28,24 +43,14 @@ function DeleteRoleButton(props) {
'data-test': 'snackbar-delete-role-success', 'data-test': 'snackbar-delete-role-success',
}, },
}); });
} catch (error) { } catch {}
const errors = Object.values(
error.response.data.errors || [['Failed while deleting!']],
);
for (const [error] of errors) {
enqueueSnackbar(error, {
variant: 'error',
SnackbarProps: {
'data-test': 'snackbar-delete-role-error',
},
});
}
throw new Error('Failed while deleting!');
}
}, [deleteRole, enqueueSnackbar, formatMessage]); }, [deleteRole, enqueueSnackbar, formatMessage]);
const handleClose = () => {
setShowConfirmation(false);
resetDeleteRole();
};
return ( return (
<> <>
<Can I="delete" a="Role" passThrough> <Can I="delete" a="Role" passThrough>
@@ -65,11 +70,12 @@ function DeleteRoleButton(props) {
open={showConfirmation} open={showConfirmation}
title={formatMessage('deleteRoleButton.title')} title={formatMessage('deleteRoleButton.title')}
description={formatMessage('deleteRoleButton.description')} description={formatMessage('deleteRoleButton.description')}
onClose={() => setShowConfirmation(false)} onClose={handleClose}
onConfirm={handleConfirm} onConfirm={handleConfirm}
cancelButtonChildren={formatMessage('deleteRoleButton.cancel')} cancelButtonChildren={formatMessage('deleteRoleButton.cancel')}
confirmButtonChildren={formatMessage('deleteRoleButton.confirm')} confirmButtonChildren={formatMessage('deleteRoleButton.confirm')}
data-test="delete-role-modal" data-test="delete-role-modal"
errorMessage={roleErrorMessage || generalErrorMessage}
/> />
</> </>
); );

View File

@@ -3,6 +3,7 @@ import DeleteIcon from '@mui/icons-material/Delete';
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import { getGeneralErrorMessage } from 'helpers/errors';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar'; import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
import * as React from 'react'; import * as React from 'react';
import ConfirmationDialog from 'components/ConfirmationDialog'; import ConfirmationDialog from 'components/ConfirmationDialog';
@@ -12,12 +13,21 @@ import useAdminUserDelete from 'hooks/useAdminUserDelete';
function DeleteUserButton(props) { function DeleteUserButton(props) {
const { userId } = props; const { userId } = props;
const [showConfirmation, setShowConfirmation] = React.useState(false); const [showConfirmation, setShowConfirmation] = React.useState(false);
const { mutateAsync: deleteUser } = useAdminUserDelete(userId); const {
mutateAsync: deleteUser,
error: deleteUserError,
reset: resetDeleteUser,
} = useAdminUserDelete(userId);
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar(); const enqueueSnackbar = useEnqueueSnackbar();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const generalErrorMessage = getGeneralErrorMessage({
error: deleteUserError,
fallbackMessage: formatMessage('deleteUserButton.deleteError'),
});
const handleConfirm = React.useCallback(async () => { const handleConfirm = React.useCallback(async () => {
try { try {
await deleteUser(); await deleteUser();
@@ -29,16 +39,14 @@ function DeleteUserButton(props) {
'data-test': 'snackbar-delete-user-success', 'data-test': 'snackbar-delete-user-success',
}, },
}); });
} catch (error) { } catch {}
enqueueSnackbar(
error?.message || formatMessage('deleteUserButton.deleteError'),
{
variant: 'error',
},
);
}
}, [deleteUser]); }, [deleteUser]);
const handleClose = () => {
setShowConfirmation(false);
resetDeleteUser();
};
return ( return (
<> <>
<IconButton <IconButton
@@ -53,11 +61,12 @@ function DeleteUserButton(props) {
open={showConfirmation} open={showConfirmation}
title={formatMessage('deleteUserButton.title')} title={formatMessage('deleteUserButton.title')}
description={formatMessage('deleteUserButton.description')} description={formatMessage('deleteUserButton.description')}
onClose={() => setShowConfirmation(false)} onClose={handleClose}
onConfirm={handleConfirm} onConfirm={handleConfirm}
cancelButtonChildren={formatMessage('deleteUserButton.cancel')} cancelButtonChildren={formatMessage('deleteUserButton.cancel')}
confirmButtonChildren={formatMessage('deleteUserButton.confirm')} confirmButtonChildren={formatMessage('deleteUserButton.confirm')}
data-test="delete-user-modal" data-test="delete-user-modal"
errorMessage={generalErrorMessage}
/> />
</> </>
); );

View File

@@ -46,12 +46,7 @@ function Form(props) {
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form <form onSubmit={methods.handleSubmit(onSubmit)} {...formProps}>
onSubmit={methods.handleSubmit((data, event) =>
onSubmit?.(data, event, methods.setError),
)}
{...formProps}
>
{render ? render(methods) : children} {render ? render(methods) : children}
</form> </form>
</FormProvider> </FormProvider>

View File

@@ -2,55 +2,35 @@ import * as React from 'react';
import { Link as RouterLink } from 'react-router-dom'; import { Link as RouterLink } from 'react-router-dom';
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import Alert from '@mui/material/Alert'; import { Alert } from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton'; import LoadingButton from '@mui/lab/LoadingButton';
import * as yup from 'yup'; import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup'; import { yupResolver } from '@hookform/resolvers/yup';
import { enqueueSnackbar } from 'notistack';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import Link from '@mui/material/Link'; import Link from '@mui/material/Link';
import { getGeneralErrorMessage } from 'helpers/errors';
import useFormatMessage from 'hooks/useFormatMessage'; import useFormatMessage from 'hooks/useFormatMessage';
import useInstallation from 'hooks/useInstallation'; import useInstallation from 'hooks/useInstallation';
import * as URLS from 'config/urls'; import * as URLS from 'config/urls';
import Form from 'components/Form'; import Form from 'components/Form';
import TextField from 'components/TextField'; import TextField from 'components/TextField';
const getValidationSchema = (formatMessage) => { const validationSchema = yup.object().shape({
const getMandatoryInputMessage = (inputNameId) => fullName: yup.string().trim().required('installationForm.mandatoryInput'),
formatMessage('installationForm.mandatoryInput', {
inputName: formatMessage(inputNameId),
});
return yup.object().shape({
fullName: yup
.string()
.trim()
.required(
getMandatoryInputMessage('installationForm.fullNameFieldLabel'),
),
email: yup email: yup
.string() .string()
.trim() .trim()
.required(getMandatoryInputMessage('installationForm.emailFieldLabel')) .email('installationForm.validateEmail')
.email(formatMessage('installationForm.validateEmail')), .required('installationForm.mandatoryInput'),
password: yup password: yup.string().required('installationForm.mandatoryInput'),
.string()
.required(getMandatoryInputMessage('installationForm.passwordFieldLabel'))
.min(6, formatMessage('installationForm.passwordMinLength')),
confirmPassword: yup confirmPassword: yup
.string() .string()
.required( .required('installationForm.mandatoryInput')
getMandatoryInputMessage('installationForm.confirmPasswordFieldLabel'), .oneOf([yup.ref('password')], 'installationForm.passwordsMustMatch'),
) });
.oneOf(
[yup.ref('password')],
formatMessage('installationForm.passwordsMustMatch'),
),
});
};
const defaultValues = { const initialValues = {
fullName: '', fullName: '',
email: '', email: '',
password: '', password: '',
@@ -59,7 +39,7 @@ const defaultValues = {
function InstallationForm() { function InstallationForm() {
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const { mutateAsync: install, isSuccess, isPending } = useInstallation(); const install = useInstallation();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const handleOnRedirect = () => { const handleOnRedirect = () => {
@@ -68,38 +48,21 @@ function InstallationForm() {
}); });
}; };
const handleSubmit = async ({ fullName, email, password }, e, setError) => { const handleSubmit = async (values) => {
const { fullName, email, password } = values;
try { try {
await install({ await install.mutateAsync({
fullName, fullName,
email, email,
password, password,
}); });
} catch (error) { } catch (error) {
const errors = error?.response?.data?.errors; enqueueSnackbar(
if (errors) { error?.message || formatMessage('installationForm.error'),
const fieldNames = Object.keys(defaultValues); {
Object.entries(errors).forEach(([fieldName, fieldErrors]) => { variant: 'error',
if (fieldNames.includes(fieldName) && Array.isArray(fieldErrors)) { },
setError(fieldName, { );
type: 'fieldRequestError',
message: fieldErrors.join(', '),
});
}
});
}
const generalError = getGeneralErrorMessage({
error,
fallbackMessage: formatMessage('installationForm.error'),
});
if (generalError) {
setError('root.general', {
type: 'requestError',
message: generalError,
});
}
} }
}; };
@@ -119,13 +82,11 @@ function InstallationForm() {
{formatMessage('installationForm.title')} {formatMessage('installationForm.title')}
</Typography> </Typography>
<Form <Form
automaticValidation={false} defaultValues={initialValues}
noValidate
defaultValues={defaultValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
resolver={yupResolver(getValidationSchema(formatMessage))} resolver={yupResolver(validationSchema)}
mode="onChange" mode="onChange"
render={({ formState: { errors } }) => ( render={({ formState: { errors, touchedFields } }) => (
<> <>
<TextField <TextField
label={formatMessage('installationForm.fullNameFieldLabel')} label={formatMessage('installationForm.fullNameFieldLabel')}
@@ -134,12 +95,19 @@ function InstallationForm() {
margin="dense" margin="dense"
autoComplete="fullName" autoComplete="fullName"
data-test="fullName-text-field" data-test="fullName-text-field"
error={!!errors?.fullName} error={touchedFields.fullName && !!errors?.fullName}
helperText={errors?.fullName?.message} helperText={
touchedFields.fullName && errors?.fullName?.message
? formatMessage(errors?.fullName?.message, {
inputName: formatMessage(
'installationForm.fullNameFieldLabel',
),
})
: ''
}
required required
readOnly={isSuccess} readOnly={install.isSuccess}
/> />
<TextField <TextField
label={formatMessage('installationForm.emailFieldLabel')} label={formatMessage('installationForm.emailFieldLabel')}
name="email" name="email"
@@ -147,12 +115,19 @@ function InstallationForm() {
margin="dense" margin="dense"
autoComplete="email" autoComplete="email"
data-test="email-text-field" data-test="email-text-field"
error={!!errors?.email} error={touchedFields.email && !!errors?.email}
helperText={errors?.email?.message} helperText={
touchedFields.email && errors?.email?.message
? formatMessage(errors?.email?.message, {
inputName: formatMessage(
'installationForm.emailFieldLabel',
),
})
: ''
}
required required
readOnly={isSuccess} readOnly={install.isSuccess}
/> />
<TextField <TextField
label={formatMessage('installationForm.passwordFieldLabel')} label={formatMessage('installationForm.passwordFieldLabel')}
name="password" name="password"
@@ -160,12 +135,19 @@ function InstallationForm() {
margin="dense" margin="dense"
type="password" type="password"
data-test="password-text-field" data-test="password-text-field"
error={!!errors?.password} error={touchedFields.password && !!errors?.password}
helperText={errors?.password?.message} helperText={
touchedFields.password && errors?.password?.message
? formatMessage(errors?.password?.message, {
inputName: formatMessage(
'installationForm.passwordFieldLabel',
),
})
: ''
}
required required
readOnly={isSuccess} readOnly={install.isSuccess}
/> />
<TextField <TextField
label={formatMessage( label={formatMessage(
'installationForm.confirmPasswordFieldLabel', 'installationForm.confirmPasswordFieldLabel',
@@ -175,24 +157,38 @@ function InstallationForm() {
margin="dense" margin="dense"
type="password" type="password"
data-test="repeat-password-text-field" data-test="repeat-password-text-field"
error={!!errors?.confirmPassword} error={touchedFields.confirmPassword && !!errors?.confirmPassword}
helperText={errors?.confirmPassword?.message} helperText={
touchedFields.confirmPassword &&
errors?.confirmPassword?.message
? formatMessage(errors?.confirmPassword?.message, {
inputName: formatMessage(
'installationForm.confirmPasswordFieldLabel',
),
})
: ''
}
required required
readOnly={isSuccess} readOnly={install.isSuccess}
/> />
{errors?.root?.general && ( <LoadingButton
<Alert data-test="error-alert" severity="error" sx={{ mt: 2 }}> type="submit"
{errors.root.general.message} variant="contained"
</Alert> color="primary"
)} sx={{ boxShadow: 2, mt: 3 }}
loading={install.isPending}
{isSuccess && ( disabled={install.isSuccess}
<Alert fullWidth
data-test="success-alert" data-test="signUp-button"
severity="success"
sx={{ mt: 2 }}
> >
{formatMessage('installationForm.submit')}
</LoadingButton>
</>
)}
/>
{install.isSuccess && (
<Alert data-test="success-alert" severity="success" sx={{ mt: 3 }}>
{formatMessage('installationForm.success', { {formatMessage('installationForm.success', {
link: (str) => ( link: (str) => (
<Link <Link
@@ -207,21 +203,6 @@ function InstallationForm() {
})} })}
</Alert> </Alert>
)} )}
<LoadingButton
type="submit"
variant="contained"
color="primary"
sx={{ boxShadow: 2, mt: 2 }}
loading={isPending}
disabled={isSuccess}
fullWidth
data-test="installation-button"
>
{formatMessage('installationForm.submit')}
</LoadingButton>
</>
)}
/>
</Paper> </Paper>
); );
} }

View File

@@ -3,52 +3,33 @@ import { useNavigate } from 'react-router-dom';
import Paper from '@mui/material/Paper'; import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton'; import LoadingButton from '@mui/lab/LoadingButton';
import Alert from '@mui/material/Alert';
import * as yup from 'yup'; import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup'; import { yupResolver } from '@hookform/resolvers/yup';
import { getGeneralErrorMessage } from 'helpers/errors';
import useAuthentication from 'hooks/useAuthentication'; import useAuthentication from 'hooks/useAuthentication';
import * as URLS from 'config/urls'; import * as URLS from 'config/urls';
import Form from 'components/Form'; import Form from 'components/Form';
import TextField from 'components/TextField'; import TextField from 'components/TextField';
import useFormatMessage from 'hooks/useFormatMessage'; import useFormatMessage from 'hooks/useFormatMessage';
import useCreateAccessToken from 'hooks/useCreateAccessToken'; import useCreateAccessToken from 'hooks/useCreateAccessToken';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
import useRegisterUser from 'hooks/useRegisterUser'; import useRegisterUser from 'hooks/useRegisterUser';
const getValidationSchema = (formatMessage) => { const validationSchema = yup.object().shape({
const getMandatoryInputMessage = (inputNameId) => fullName: yup.string().trim().required('signupForm.mandatoryInput'),
formatMessage('signupForm.mandatoryInput', {
inputName: formatMessage(inputNameId),
});
return yup.object().shape({
fullName: yup
.string()
.trim()
.required(getMandatoryInputMessage('signupForm.fullNameFieldLabel')),
email: yup email: yup
.string() .string()
.trim() .trim()
.required(getMandatoryInputMessage('signupForm.emailFieldLabel')) .email('signupForm.validateEmail')
.email(formatMessage('signupForm.validateEmail')), .required('signupForm.mandatoryInput'),
password: yup password: yup.string().required('signupForm.mandatoryInput'),
.string()
.required(getMandatoryInputMessage('signupForm.passwordFieldLabel'))
.min(6, formatMessage('signupForm.passwordMinLength')),
confirmPassword: yup confirmPassword: yup
.string() .string()
.required( .required('signupForm.mandatoryInput')
getMandatoryInputMessage('signupForm.confirmPasswordFieldLabel'), .oneOf([yup.ref('password')], 'signupForm.passwordsMustMatch'),
) });
.oneOf(
[yup.ref('password')],
formatMessage('signupForm.passwordsMustMatch'),
),
});
};
const defaultValues = { const initialValues = {
fullName: '', fullName: '',
email: '', email: '',
password: '', password: '',
@@ -59,6 +40,7 @@ function SignUpForm() {
const navigate = useNavigate(); const navigate = useNavigate();
const authentication = useAuthentication(); const authentication = useAuthentication();
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar();
const { mutateAsync: registerUser, isPending: isRegisterUserPending } = const { mutateAsync: registerUser, isPending: isRegisterUserPending } =
useRegisterUser(); useRegisterUser();
const { mutateAsync: createAccessToken, isPending: loginLoading } = const { mutateAsync: createAccessToken, isPending: loginLoading } =
@@ -70,7 +52,7 @@ function SignUpForm() {
} }
}, [authentication.isAuthenticated]); }, [authentication.isAuthenticated]);
const handleSubmit = async (values, e, setError) => { const handleSubmit = async (values) => {
try { try {
const { fullName, email, password } = values; const { fullName, email, password } = values;
await registerUser({ await registerUser({
@@ -85,28 +67,25 @@ function SignUpForm() {
const { token } = data; const { token } = data;
authentication.updateToken(token); authentication.updateToken(token);
} catch (error) { } catch (error) {
const errors = error?.response?.data?.errors; const errors = error?.response?.data?.errors
if (errors) { ? Object.values(error.response.data.errors)
const fieldNames = Object.keys(defaultValues); : [];
Object.entries(errors).forEach(([fieldName, fieldErrors]) => {
if (fieldNames.includes(fieldName) && Array.isArray(fieldErrors)) { if (errors.length) {
setError(fieldName, { for (const [error] of errors) {
type: 'fieldRequestError', enqueueSnackbar(error, {
message: fieldErrors.join(', '), variant: 'error',
SnackbarProps: {
'data-test': 'snackbar-sign-up-error',
},
}); });
} }
}); } else {
} enqueueSnackbar(error?.message || formatMessage('signupForm.error'), {
variant: 'error',
const generalError = getGeneralErrorMessage({ SnackbarProps: {
error, 'data-test': 'snackbar-sign-up-error',
fallbackMessage: formatMessage('signupForm.error'), },
});
if (generalError) {
setError('root.general', {
type: 'requestError',
message: generalError,
}); });
} }
} }
@@ -129,13 +108,11 @@ function SignUpForm() {
</Typography> </Typography>
<Form <Form
automaticValidation={false} defaultValues={initialValues}
noValidate
defaultValues={defaultValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
resolver={yupResolver(getValidationSchema(formatMessage))} resolver={yupResolver(validationSchema)}
mode="onChange" mode="onChange"
render={({ formState: { errors } }) => ( render={({ formState: { errors, touchedFields } }) => (
<> <>
<TextField <TextField
label={formatMessage('signupForm.fullNameFieldLabel')} label={formatMessage('signupForm.fullNameFieldLabel')}
@@ -144,9 +121,14 @@ function SignUpForm() {
margin="dense" margin="dense"
autoComplete="fullName" autoComplete="fullName"
data-test="fullName-text-field" data-test="fullName-text-field"
error={!!errors?.fullName} error={touchedFields.fullName && !!errors?.fullName}
helperText={errors?.fullName?.message} helperText={
required touchedFields.fullName && errors?.fullName?.message
? formatMessage(errors?.fullName?.message, {
inputName: formatMessage('signupForm.fullNameFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -156,9 +138,14 @@ function SignUpForm() {
margin="dense" margin="dense"
autoComplete="email" autoComplete="email"
data-test="email-text-field" data-test="email-text-field"
error={!!errors?.email} error={touchedFields.email && !!errors?.email}
helperText={errors?.email?.message} helperText={
required touchedFields.email && errors?.email?.message
? formatMessage(errors?.email?.message, {
inputName: formatMessage('signupForm.emailFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -167,9 +154,14 @@ function SignUpForm() {
fullWidth fullWidth
margin="dense" margin="dense"
type="password" type="password"
error={!!errors?.password} error={touchedFields.password && !!errors?.password}
helperText={errors?.password?.message} helperText={
required touchedFields.password && errors?.password?.message
? formatMessage(errors?.password?.message, {
inputName: formatMessage('signupForm.passwordFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -178,21 +170,19 @@ function SignUpForm() {
fullWidth fullWidth
margin="dense" margin="dense"
type="password" type="password"
error={!!errors?.confirmPassword} error={touchedFields.confirmPassword && !!errors?.confirmPassword}
helperText={errors?.confirmPassword?.message} helperText={
required touchedFields.confirmPassword &&
errors?.confirmPassword?.message
? formatMessage(errors?.confirmPassword?.message, {
inputName: formatMessage(
'signupForm.confirmPasswordFieldLabel',
),
})
: ''
}
/> />
{errors?.root?.general && (
<Alert
data-test="alert-sign-up-error"
severity="error"
sx={{ mt: 2 }}
>
{errors.root.general.message}
</Alert>
)}
<LoadingButton <LoadingButton
type="submit" type="submit"
variant="contained" variant="contained"

View File

@@ -16,3 +16,14 @@ export const getGeneralErrorMessage = ({ error, fallbackMessage }) => {
return error?.message || fallbackMessage; return error?.message || fallbackMessage;
} }
}; };
export const getFieldErrorMessage = ({ fieldName, error }) => {
const errors = error?.response?.data?.errors;
const fieldErrors = errors?.[fieldName];
if (fieldErrors && Array.isArray(fieldErrors)) {
return fieldErrors.join(', ');
}
return '';
};

View File

@@ -138,7 +138,6 @@
"installationForm.submit": "Create admin", "installationForm.submit": "Create admin",
"installationForm.validateEmail": "Email must be valid.", "installationForm.validateEmail": "Email must be valid.",
"installationForm.passwordsMustMatch": "Passwords must match.", "installationForm.passwordsMustMatch": "Passwords must match.",
"installationForm.passwordMinLength": "Password must be at least 6 characters long.",
"installationForm.mandatoryInput": "{inputName} is required.", "installationForm.mandatoryInput": "{inputName} is required.",
"installationForm.success": "The admin account has been created, and thus, the installation has been completed. You can now log in <link>here</link>.", "installationForm.success": "The admin account has been created, and thus, the installation has been completed. You can now log in <link>here</link>.",
"installationForm.error": "Something went wrong. Please try again.", "installationForm.error": "Something went wrong. Please try again.",
@@ -150,7 +149,6 @@
"signupForm.submit": "Sign up", "signupForm.submit": "Sign up",
"signupForm.validateEmail": "Email must be valid.", "signupForm.validateEmail": "Email must be valid.",
"signupForm.passwordsMustMatch": "Passwords must match.", "signupForm.passwordsMustMatch": "Passwords must match.",
"signupForm.passwordMinLength": "Password must be at least 6 characters long.",
"signupForm.mandatoryInput": "{inputName} is required.", "signupForm.mandatoryInput": "{inputName} is required.",
"signupForm.error": "Something went wrong. Please try again.", "signupForm.error": "Something went wrong. Please try again.",
"loginForm.title": "Login", "loginForm.title": "Login",
@@ -247,6 +245,7 @@
"deleteRoleButton.cancel": "Cancel", "deleteRoleButton.cancel": "Cancel",
"deleteRoleButton.confirm": "Delete", "deleteRoleButton.confirm": "Delete",
"deleteRoleButton.successfullyDeleted": "The role has been deleted.", "deleteRoleButton.successfullyDeleted": "The role has been deleted.",
"deleteRoleButton.generalError": "Failed while deleting!",
"editRolePage.title": "Edit role", "editRolePage.title": "Edit role",
"createRolePage.title": "Create role", "createRolePage.title": "Create role",
"roleForm.name": "Name", "roleForm.name": "Name",