179 lines
5.8 KiB
TypeScript
Executable File
179 lines
5.8 KiB
TypeScript
Executable File
import * as Yup from 'yup';
|
|
import { LoadingButton } from "@mui/lab";
|
|
import { Box, Card, Grid, Stack, Typography } from "@mui/material";
|
|
import { Role, UserAccess, Organization } from "../../../@types/user";
|
|
import { FormProvider, RHFSelect, RHFTextField } from "../../../components/hook-form";
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
import { useForm } from 'react-hook-form';
|
|
import { yupResolver } from '@hookform/resolvers/yup';
|
|
import { useSnackbar } from 'notistack';
|
|
import { useNavigate, useParams } from 'react-router-dom';
|
|
import axios from '../../../utils/axios';
|
|
import palette from '@/theme/palette';
|
|
import { Corporate } from '@/@types/corporates';
|
|
|
|
type Props = {
|
|
isEdit: boolean;
|
|
currentUserAccess?: UserAccess;
|
|
roles: Role;
|
|
organizations: Organization;
|
|
corporate: Corporate;
|
|
};
|
|
|
|
export default function AccessForm({ isEdit, currentUserAccess, roles, organizations, corporate }: Props) {
|
|
|
|
const { enqueueSnackbar } = useSnackbar();
|
|
const navigate = useNavigate();
|
|
const { id } = useParams();
|
|
|
|
const NewCorporatePlanSchema = Yup.object().shape({
|
|
name: Yup.string().required('Name is required'),
|
|
});
|
|
|
|
const defaultValues = useMemo(
|
|
() => ({
|
|
name: currentUserAccess?.person?.name || '',
|
|
username: currentUserAccess?.username || '',
|
|
email: currentUserAccess?.email || '',
|
|
roles: currentUserAccess?.role?.id || '',
|
|
organizations: currentUserAccess?.organization_id || '',
|
|
corporates: currentUserAccess?.corporate_id || '',
|
|
password: '',
|
|
}),
|
|
[currentUserAccess]
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (isEdit && currentUserAccess) {
|
|
reset(defaultValues);
|
|
}
|
|
if (!isEdit) {
|
|
reset(defaultValues);
|
|
}
|
|
}, [isEdit, currentUserAccess]);
|
|
|
|
const methods = useForm({
|
|
resolver: yupResolver(NewCorporatePlanSchema),
|
|
defaultValues,
|
|
});
|
|
|
|
const {
|
|
reset,
|
|
watch,
|
|
handleSubmit,
|
|
setError,
|
|
formState: { isSubmitting },
|
|
} = methods;
|
|
|
|
// Watch 'roles' field to conditionally render other fields
|
|
const selectedRole = watch('roles');
|
|
|
|
const onSubmit = async (data: any) => {
|
|
console.log(data, 'test123');
|
|
if (!isEdit) {
|
|
await axios
|
|
.post('/user/access', data)
|
|
.then((res) => {
|
|
enqueueSnackbar('User created successfully', { variant: 'success' });
|
|
navigate('/user-access', { replace: true });
|
|
})
|
|
.catch(({ response }) => {
|
|
if (response.status === 422) {
|
|
for (const [key, value] of Object.entries(response.data.errors)) {
|
|
setError(key, { message: value[0] });
|
|
enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
|
|
}
|
|
} else {
|
|
enqueueSnackbar('Create Failed : ' + response.data.message, { variant: 'error' });
|
|
}
|
|
});
|
|
} else {
|
|
await axios
|
|
.put('/user/access/' + currentUserAccess?.id, data)
|
|
.then((res) => {
|
|
enqueueSnackbar('User updated successfully', { variant: 'success' });
|
|
navigate('/user-access', { replace: true });
|
|
})
|
|
.catch(({ response }) => {
|
|
enqueueSnackbar('Update Failed : ' + response.data.message, { variant: 'error' });
|
|
});
|
|
}
|
|
};
|
|
|
|
// Map role, organization, and corporate options
|
|
const optionsRoles = roles?.data?.map((item) => ({
|
|
value: item.id,
|
|
label: item.name,
|
|
})) ?? [];
|
|
|
|
const optionsOrganization = organizations?.data?.map((item) => ({
|
|
value: item.id,
|
|
label: item.name,
|
|
})) ?? [];
|
|
|
|
const optionsCorporate = corporate?.data?.map((item) => ({
|
|
value: item.id,
|
|
label: item.name,
|
|
})) ?? [];
|
|
|
|
return (
|
|
<FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
|
|
<Box sx={{ px: 2 }}>
|
|
<Grid container spacing={2}>
|
|
<Grid item xs={12} sm={12}>
|
|
<Card sx={{ px: 3, py: 4 }}>
|
|
<Stack spacing={2}>
|
|
<Typography variant="h6" color={palette.light.primary.main}>
|
|
User Access
|
|
</Typography>
|
|
<RHFTextField name="name" label="Name" />
|
|
<RHFTextField name="username" label="Username" />
|
|
<RHFTextField type="email" name="email" label="Email" />
|
|
<RHFTextField type="password" name="password" label="Password" />
|
|
|
|
{/* Select for roles */}
|
|
<RHFSelect name="roles" label="Roles">
|
|
{optionsRoles.map((option, index) => (
|
|
<option key={index} value={option.value}>
|
|
{option.label}
|
|
</option>
|
|
))}
|
|
</RHFSelect>
|
|
|
|
{/* Conditional rendering based on selectedRole */}
|
|
{selectedRole && (['8'].includes(selectedRole) ? (
|
|
<RHFSelect name="organizations" label="Organizations">
|
|
{optionsOrganization.map((option, index) => (
|
|
<option key={index} value={option.value}>
|
|
{option.label}
|
|
</option>
|
|
))}
|
|
</RHFSelect>
|
|
) : ['2'].includes(selectedRole) ? (
|
|
<RHFSelect name="corporates" label="Corporates">
|
|
{optionsCorporate.map((option, index) => (
|
|
<option key={index} value={option.value}>
|
|
{option.label}
|
|
</option>
|
|
))}
|
|
</RHFSelect>
|
|
) : null)}
|
|
|
|
<LoadingButton
|
|
type="submit"
|
|
variant="contained"
|
|
size="large"
|
|
fullWidth={true}
|
|
loading={isSubmitting}
|
|
>
|
|
{isEdit ? 'Update' : 'Create'}
|
|
</LoadingButton>
|
|
</Stack>
|
|
</Card>
|
|
</Grid>
|
|
</Grid>
|
|
</Box>
|
|
</FormProvider>
|
|
);
|
|
}
|