Merge pull request #2143 from automatisch/AUT-1325

feat: introduce uniqueness validation for remote role name
This commit is contained in:
Ali BARIN
2024-11-12 13:18:07 +01:00
committed by GitHub
5 changed files with 79 additions and 13 deletions

View File

@@ -5,6 +5,8 @@ import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import useEnqueueSnackbar from 'hooks/useEnqueueSnackbar';
import { useMemo } from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import Form from 'components/Form';
import useFormatMessage from 'hooks/useFormatMessage';
@@ -23,6 +25,42 @@ function generateFormRoleMappings(roleMappings) {
}));
}
const uniqueRemoteRoleName = (array, context, formatMessage) => {
const seen = new Set();
for (const [index, value] of array.entries()) {
if (seen.has(value.remoteRoleName)) {
const path = `${context.path}[${index}].remoteRoleName`;
return context.createError({
message: `${formatMessage('roleMappingsForm.remoteRoleName')} must be unique`,
path,
});
}
seen.add(value.remoteRoleName);
}
return true;
};
const getValidationSchema = (formatMessage) =>
yup.object({
roleMappings: yup
.array()
.of(
yup.object({
roleId: yup
.string()
.required(`${formatMessage('roleMappingsForm.role')} is required`),
remoteRoleName: yup
.string()
.required(
`${formatMessage('roleMappingsForm.remoteRoleName')} is required`,
),
}),
)
.test('unique-remoteRoleName', '', (value, ctx) => {
return uniqueRemoteRoleName(value, ctx, formatMessage);
}),
});
function RoleMappings({ provider, providerLoading }) {
const formatMessage = useFormatMessage();
const enqueueSnackbar = useEnqueueSnackbar();
@@ -94,7 +132,15 @@ function RoleMappings({ provider, providerLoading }) {
<Typography variant="h3">
{formatMessage('roleMappingsForm.title')}
</Typography>
<Form defaultValues={defaultValues} onSubmit={handleRoleMappingsUpdate}>
<Form
defaultValues={defaultValues}
onSubmit={handleRoleMappingsUpdate}
resolver={yupResolver(getValidationSchema(formatMessage))}
mode="onSubmit"
reValidateMode="onChange"
noValidate
automaticValidation={false}
>
<Stack direction="column" spacing={2}>
<RoleMappingsFieldArray />
<LoadingButton

View File

@@ -55,6 +55,7 @@ function RoleMappingsFieldArray() {
label={formatMessage('roleMappingsForm.remoteRoleName')}
fullWidth
required
showError
/>
<ControlledAutocomplete
name={`roleMappings.${index}.roleId`}
@@ -62,14 +63,17 @@ function RoleMappingsFieldArray() {
disablePortal
disableClearable
options={generateRoleOptions(roles)}
renderInput={(params) => (
renderInput={(params, { error }) => (
<MuiTextField
{...params}
label={formatMessage('roleMappingsForm.role')}
required
error={!!error}
helperText={error?.message}
/>
)}
loading={isRolesLoading}
showHelperText={false}
/>
</Stack>
<IconButton