Merge pull request #2227 from automatisch/AUT-1371

feat: introduce inline error messages for InstallationForm and SignUpForm
This commit is contained in:
Ali BARIN
2025-01-10 12:26:45 +01:00
committed by GitHub
6 changed files with 228 additions and 182 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');
@@ -6,16 +6,18 @@ export class AdminSetupPage extends BasePage {
path = '/installation'; path = '/installation';
/** /**
* @param {import('@playwright/test').Page} page * @param {import('@playwright/test').Page} page
*/ */
constructor(page) { constructor(page) {
super(page); super(page);
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('repeat-password-text-field'); this.repeatPasswordTextField = this.page.getByTestId(
this.createAdminButton = this.page.getByTestId('signUp-button'); 'repeat-password-text-field'
);
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');
} }
@@ -46,7 +48,7 @@ export class AdminSetupPage extends BasePage {
await this.repeatPasswordTextField.fill(testUser.wronglyRepeatedPassword); await this.repeatPasswordTextField.fill(testUser.wronglyRepeatedPassword);
} }
async submitAdminForm() { async submitAdminForm() {
await this.createAdminButton.click(); await this.createAdminButton.click();
} }
@@ -59,7 +61,10 @@ export class AdminSetupPage extends BasePage {
} }
async expectSuccessMessageToContainLoginLink() { async expectSuccessMessageToContainLoginLink() {
await expect(await this.successAlert.locator('a')).toHaveAttribute('href', '/login'); await expect(await this.successAlert.locator('a')).toHaveAttribute(
'href',
'/login'
);
} }
generateUser() { generateUser() {
@@ -69,7 +74,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

@@ -2,6 +2,7 @@ import * as React from 'react';
import { FormProvider, useForm, useWatch } from 'react-hook-form'; import { FormProvider, useForm, useWatch } from 'react-hook-form';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import isEqual from 'lodash/isEqual'; import isEqual from 'lodash/isEqual';
import useFormatMessage from 'hooks/useFormatMessage';
const noop = () => null; const noop = () => null;
@@ -18,6 +19,8 @@ function Form(props) {
...formProps ...formProps
} = props; } = props;
const formatMessage = useFormatMessage();
const methods = useForm({ const methods = useForm({
defaultValues, defaultValues,
reValidateMode, reValidateMode,
@@ -25,6 +28,8 @@ function Form(props) {
mode, mode,
}); });
const { setError } = methods;
const form = useWatch({ control: methods.control }); const form = useWatch({ control: methods.control });
const prevDefaultValues = React.useRef(defaultValues); const prevDefaultValues = React.useRef(defaultValues);
@@ -44,9 +49,53 @@ function Form(props) {
} }
}, [defaultValues]); }, [defaultValues]);
const handleErrors = React.useCallback(
function (errors) {
if (!errors) return;
let shouldSetGenericGeneralError = true;
const fieldNames = Object.keys(defaultValues);
Object.entries(errors).forEach(([fieldName, fieldErrors]) => {
if (fieldNames.includes(fieldName) && Array.isArray(fieldErrors)) {
shouldSetGenericGeneralError = false;
setError(fieldName, {
type: 'fieldRequestError',
message: fieldErrors.join(', '),
});
}
});
// in case of general errors
if (Array.isArray(errors.general)) {
for (const error of errors.general) {
shouldSetGenericGeneralError = false;
setError('root.general', { type: 'requestError', message: error });
}
}
if (shouldSetGenericGeneralError) {
setError('root.general', {
type: 'requestError',
message: formatMessage('form.genericError'),
});
}
},
[defaultValues, formatMessage, setError],
);
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)} {...formProps}> <form
onSubmit={methods.handleSubmit(async (data, event) => {
try {
return await onSubmit?.(data);
} catch (errors) {
handleErrors(errors);
}
})}
{...formProps}
>
{render ? render(methods) : children} {render ? render(methods) : children}
</form> </form>
</FormProvider> </FormProvider>

View File

@@ -2,11 +2,10 @@ 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'; import Alert from '@mui/material/Alert';
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';
@@ -16,21 +15,41 @@ 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 validationSchema = yup.object().shape({ const getValidationSchema = (formatMessage) => {
fullName: yup.string().trim().required('installationForm.mandatoryInput'), const getMandatoryInputMessage = (inputNameId) =>
email: yup formatMessage('installationForm.mandatoryInput', {
.string() inputName: formatMessage(inputNameId),
.trim() });
.email('installationForm.validateEmail')
.required('installationForm.mandatoryInput'),
password: yup.string().required('installationForm.mandatoryInput'),
confirmPassword: yup
.string()
.required('installationForm.mandatoryInput')
.oneOf([yup.ref('password')], 'installationForm.passwordsMustMatch'),
});
const initialValues = { return yup.object().shape({
fullName: yup
.string()
.trim()
.required(
getMandatoryInputMessage('installationForm.fullNameFieldLabel'),
),
email: yup
.string()
.trim()
.required(getMandatoryInputMessage('installationForm.emailFieldLabel'))
.email(formatMessage('installationForm.validateEmail')),
password: yup
.string()
.required(getMandatoryInputMessage('installationForm.passwordFieldLabel'))
.min(6, formatMessage('installationForm.passwordMinLength')),
confirmPassword: yup
.string()
.required(
getMandatoryInputMessage('installationForm.confirmPasswordFieldLabel'),
)
.oneOf(
[yup.ref('password')],
formatMessage('installationForm.passwordsMustMatch'),
),
});
};
const defaultValues = {
fullName: '', fullName: '',
email: '', email: '',
password: '', password: '',
@@ -39,7 +58,7 @@ const initialValues = {
function InstallationForm() { function InstallationForm() {
const formatMessage = useFormatMessage(); const formatMessage = useFormatMessage();
const install = useInstallation(); const { mutateAsync: install, isSuccess, isPending } = useInstallation();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const handleOnRedirect = () => { const handleOnRedirect = () => {
@@ -48,21 +67,16 @@ function InstallationForm() {
}); });
}; };
const handleSubmit = async (values) => { const handleSubmit = async ({ fullName, email, password }) => {
const { fullName, email, password } = values;
try { try {
await install.mutateAsync({ await install({
fullName, fullName,
email, email,
password, password,
}); });
} catch (error) { } catch (error) {
enqueueSnackbar( const errors = error?.response?.data?.errors;
error?.message || formatMessage('installationForm.error'), throw errors || error;
{
variant: 'error',
},
);
} }
}; };
@@ -82,11 +96,13 @@ function InstallationForm() {
{formatMessage('installationForm.title')} {formatMessage('installationForm.title')}
</Typography> </Typography>
<Form <Form
defaultValues={initialValues} automaticValidation={false}
noValidate
defaultValues={defaultValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
resolver={yupResolver(validationSchema)} resolver={yupResolver(getValidationSchema(formatMessage))}
mode="onChange" mode="onChange"
render={({ formState: { errors, touchedFields } }) => ( render={({ formState: { errors } }) => (
<> <>
<TextField <TextField
label={formatMessage('installationForm.fullNameFieldLabel')} label={formatMessage('installationForm.fullNameFieldLabel')}
@@ -95,19 +111,12 @@ function InstallationForm() {
margin="dense" margin="dense"
autoComplete="fullName" autoComplete="fullName"
data-test="fullName-text-field" data-test="fullName-text-field"
error={touchedFields.fullName && !!errors?.fullName} error={!!errors?.fullName}
helperText={ helperText={errors?.fullName?.message}
touchedFields.fullName && errors?.fullName?.message
? formatMessage(errors?.fullName?.message, {
inputName: formatMessage(
'installationForm.fullNameFieldLabel',
),
})
: ''
}
required required
readOnly={install.isSuccess} readOnly={isSuccess}
/> />
<TextField <TextField
label={formatMessage('installationForm.emailFieldLabel')} label={formatMessage('installationForm.emailFieldLabel')}
name="email" name="email"
@@ -115,19 +124,12 @@ function InstallationForm() {
margin="dense" margin="dense"
autoComplete="email" autoComplete="email"
data-test="email-text-field" data-test="email-text-field"
error={touchedFields.email && !!errors?.email} error={!!errors?.email}
helperText={ helperText={errors?.email?.message}
touchedFields.email && errors?.email?.message
? formatMessage(errors?.email?.message, {
inputName: formatMessage(
'installationForm.emailFieldLabel',
),
})
: ''
}
required required
readOnly={install.isSuccess} readOnly={isSuccess}
/> />
<TextField <TextField
label={formatMessage('installationForm.passwordFieldLabel')} label={formatMessage('installationForm.passwordFieldLabel')}
name="password" name="password"
@@ -135,19 +137,12 @@ function InstallationForm() {
margin="dense" margin="dense"
type="password" type="password"
data-test="password-text-field" data-test="password-text-field"
error={touchedFields.password && !!errors?.password} error={!!errors?.password}
helperText={ helperText={errors?.password?.message}
touchedFields.password && errors?.password?.message
? formatMessage(errors?.password?.message, {
inputName: formatMessage(
'installationForm.passwordFieldLabel',
),
})
: ''
}
required required
readOnly={install.isSuccess} readOnly={isSuccess}
/> />
<TextField <TextField
label={formatMessage( label={formatMessage(
'installationForm.confirmPasswordFieldLabel', 'installationForm.confirmPasswordFieldLabel',
@@ -157,52 +152,53 @@ function InstallationForm() {
margin="dense" margin="dense"
type="password" type="password"
data-test="repeat-password-text-field" data-test="repeat-password-text-field"
error={touchedFields.confirmPassword && !!errors?.confirmPassword} error={!!errors?.confirmPassword}
helperText={ helperText={errors?.confirmPassword?.message}
touchedFields.confirmPassword &&
errors?.confirmPassword?.message
? formatMessage(errors?.confirmPassword?.message, {
inputName: formatMessage(
'installationForm.confirmPasswordFieldLabel',
),
})
: ''
}
required required
readOnly={install.isSuccess} readOnly={isSuccess}
/> />
{errors?.root?.general && (
<Alert data-test="error-alert" severity="error" sx={{ mt: 2 }}>
{errors.root.general.message}
</Alert>
)}
{isSuccess && (
<Alert
data-test="success-alert"
severity="success"
sx={{ mt: 2 }}
>
{formatMessage('installationForm.success', {
link: (str) => (
<Link
component={RouterLink}
to={URLS.LOGIN}
onClick={handleOnRedirect}
replace
>
{str}
</Link>
),
})}
</Alert>
)}
<LoadingButton <LoadingButton
type="submit" type="submit"
variant="contained" variant="contained"
color="primary" color="primary"
sx={{ boxShadow: 2, mt: 3 }} sx={{ boxShadow: 2, mt: 2 }}
loading={install.isPending} loading={isPending}
disabled={install.isSuccess} disabled={isSuccess}
fullWidth fullWidth
data-test="signUp-button" data-test="installation-button"
> >
{formatMessage('installationForm.submit')} {formatMessage('installationForm.submit')}
</LoadingButton> </LoadingButton>
</> </>
)} )}
/> />
{install.isSuccess && (
<Alert data-test="success-alert" severity="success" sx={{ mt: 3 }}>
{formatMessage('installationForm.success', {
link: (str) => (
<Link
component={RouterLink}
to={URLS.LOGIN}
onClick={handleOnRedirect}
replace
>
{str}
</Link>
),
})}
</Alert>
)}
</Paper> </Paper>
); );
} }

View File

@@ -3,6 +3,7 @@ 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';
@@ -12,24 +13,41 @@ 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 validationSchema = yup.object().shape({ const getValidationSchema = (formatMessage) => {
fullName: yup.string().trim().required('signupForm.mandatoryInput'), const getMandatoryInputMessage = (inputNameId) =>
email: yup formatMessage('signupForm.mandatoryInput', {
.string() inputName: formatMessage(inputNameId),
.trim() });
.email('signupForm.validateEmail')
.required('signupForm.mandatoryInput'),
password: yup.string().required('signupForm.mandatoryInput'),
confirmPassword: yup
.string()
.required('signupForm.mandatoryInput')
.oneOf([yup.ref('password')], 'signupForm.passwordsMustMatch'),
});
const initialValues = { return yup.object().shape({
fullName: yup
.string()
.trim()
.required(getMandatoryInputMessage('signupForm.fullNameFieldLabel')),
email: yup
.string()
.trim()
.required(getMandatoryInputMessage('signupForm.emailFieldLabel'))
.email(formatMessage('signupForm.validateEmail')),
password: yup
.string()
.required(getMandatoryInputMessage('signupForm.passwordFieldLabel'))
.min(6, formatMessage('signupForm.passwordMinLength')),
confirmPassword: yup
.string()
.required(
getMandatoryInputMessage('signupForm.confirmPasswordFieldLabel'),
)
.oneOf(
[yup.ref('password')],
formatMessage('signupForm.passwordsMustMatch'),
),
});
};
const defaultValues = {
fullName: '', fullName: '',
email: '', email: '',
password: '', password: '',
@@ -40,7 +58,6 @@ 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 } =
@@ -67,27 +84,8 @@ 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;
? Object.values(error.response.data.errors) throw errors || error;
: [];
if (errors.length) {
for (const [error] of errors) {
enqueueSnackbar(error, {
variant: 'error',
SnackbarProps: {
'data-test': 'snackbar-sign-up-error',
},
});
}
} else {
enqueueSnackbar(error?.message || formatMessage('signupForm.error'), {
variant: 'error',
SnackbarProps: {
'data-test': 'snackbar-sign-up-error',
},
});
}
} }
}; };
@@ -108,11 +106,13 @@ function SignUpForm() {
</Typography> </Typography>
<Form <Form
defaultValues={initialValues} automaticValidation={false}
noValidate
defaultValues={defaultValues}
onSubmit={handleSubmit} onSubmit={handleSubmit}
resolver={yupResolver(validationSchema)} resolver={yupResolver(getValidationSchema(formatMessage))}
mode="onChange" mode="onChange"
render={({ formState: { errors, touchedFields } }) => ( render={({ formState: { errors } }) => (
<> <>
<TextField <TextField
label={formatMessage('signupForm.fullNameFieldLabel')} label={formatMessage('signupForm.fullNameFieldLabel')}
@@ -121,14 +121,9 @@ function SignUpForm() {
margin="dense" margin="dense"
autoComplete="fullName" autoComplete="fullName"
data-test="fullName-text-field" data-test="fullName-text-field"
error={touchedFields.fullName && !!errors?.fullName} error={!!errors?.fullName}
helperText={ helperText={errors?.fullName?.message}
touchedFields.fullName && errors?.fullName?.message required
? formatMessage(errors?.fullName?.message, {
inputName: formatMessage('signupForm.fullNameFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -138,14 +133,9 @@ function SignUpForm() {
margin="dense" margin="dense"
autoComplete="email" autoComplete="email"
data-test="email-text-field" data-test="email-text-field"
error={touchedFields.email && !!errors?.email} error={!!errors?.email}
helperText={ helperText={errors?.email?.message}
touchedFields.email && errors?.email?.message required
? formatMessage(errors?.email?.message, {
inputName: formatMessage('signupForm.emailFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -154,14 +144,9 @@ function SignUpForm() {
fullWidth fullWidth
margin="dense" margin="dense"
type="password" type="password"
error={touchedFields.password && !!errors?.password} error={!!errors?.password}
helperText={ helperText={errors?.password?.message}
touchedFields.password && errors?.password?.message required
? formatMessage(errors?.password?.message, {
inputName: formatMessage('signupForm.passwordFieldLabel'),
})
: ''
}
/> />
<TextField <TextField
@@ -170,19 +155,21 @@ function SignUpForm() {
fullWidth fullWidth
margin="dense" margin="dense"
type="password" type="password"
error={touchedFields.confirmPassword && !!errors?.confirmPassword} error={!!errors?.confirmPassword}
helperText={ helperText={errors?.confirmPassword?.message}
touchedFields.confirmPassword && required
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

@@ -1,5 +1,13 @@
import * as React from 'react';
import { useIntl } from 'react-intl'; import { useIntl } from 'react-intl';
export default function useFormatMessage() { export default function useFormatMessage() {
const { formatMessage } = useIntl(); const { formatMessage } = useIntl();
return (id, values = {}) => formatMessage({ id }, values);
const customFormatMessage = React.useCallback(
(id, values = {}) => formatMessage({ id }, values),
[formatMessage],
);
return customFormatMessage;
} }

View File

@@ -130,6 +130,7 @@
"webhookUrlInfo.description": "You'll need to configure your application with this webhook URL.", "webhookUrlInfo.description": "You'll need to configure your application with this webhook URL.",
"webhookUrlInfo.helperText": "We've generated a custom webhook URL for you to send requests to. <link>Learn more about webhooks</link>.", "webhookUrlInfo.helperText": "We've generated a custom webhook URL for you to send requests to. <link>Learn more about webhooks</link>.",
"webhookUrlInfo.copy": "Copy", "webhookUrlInfo.copy": "Copy",
"form.genericError": "Something went wrong. Please try again.",
"installationForm.title": "Installation", "installationForm.title": "Installation",
"installationForm.fullNameFieldLabel": "Full name", "installationForm.fullNameFieldLabel": "Full name",
"installationForm.emailFieldLabel": "Email", "installationForm.emailFieldLabel": "Email",
@@ -138,9 +139,9 @@
"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.",
"signupForm.title": "Sign up", "signupForm.title": "Sign up",
"signupForm.fullNameFieldLabel": "Full name", "signupForm.fullNameFieldLabel": "Full name",
"signupForm.emailFieldLabel": "Email", "signupForm.emailFieldLabel": "Email",
@@ -149,8 +150,8 @@
"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.",
"loginForm.title": "Login", "loginForm.title": "Login",
"loginForm.emailFieldLabel": "Email", "loginForm.emailFieldLabel": "Email",
"loginForm.passwordFieldLabel": "Password", "loginForm.passwordFieldLabel": "Password",