|
| 1 | +import { FormControl, FormHelperText, FormLabel } from '@mui/material'; |
| 2 | +import ReactHookTextField from '../../../components/ReactHookTextField'; |
| 3 | +import { useForm } from 'react-hook-form'; |
| 4 | +import { useToast } from '../../../hooks/toasts.hooks'; |
| 5 | +import * as yup from 'yup'; |
| 6 | +import { yupResolver } from '@hookform/resolvers/yup'; |
| 7 | +import { IndexCode } from 'shared'; |
| 8 | +import NERFormModal from '../../../components/NERFormModal'; |
| 9 | +import { IndexCodePayload } from '../../../hooks/finance.hooks'; |
| 10 | + |
| 11 | +const schema = yup.object().shape({ |
| 12 | + name: yup.string().required('Name is required'), |
| 13 | + code: yup.string().required('Code is required') |
| 14 | +}); |
| 15 | + |
| 16 | +interface IndexCodeFormModalProps { |
| 17 | + showModal: boolean; |
| 18 | + handleClose: () => void; |
| 19 | + defaultValues?: IndexCode; |
| 20 | + mutateAsync: (data: IndexCodePayload) => Promise<IndexCode>; |
| 21 | +} |
| 22 | + |
| 23 | +const IndexCodeFormModal: React.FC<IndexCodeFormModalProps> = ({ showModal, handleClose, defaultValues, mutateAsync }) => { |
| 24 | + const toast = useToast(); |
| 25 | + |
| 26 | + const onSubmit = async (data: IndexCodePayload) => { |
| 27 | + try { |
| 28 | + await mutateAsync(data); |
| 29 | + toast.success(`Index Code: ${data.name} ${defaultValues ? 'edited' : 'created'} successfully!`); |
| 30 | + } catch (error: unknown) { |
| 31 | + if (error instanceof Error) { |
| 32 | + toast.error(error.message); |
| 33 | + } |
| 34 | + } |
| 35 | + handleClose(); |
| 36 | + }; |
| 37 | + |
| 38 | + const { |
| 39 | + handleSubmit, |
| 40 | + control, |
| 41 | + reset, |
| 42 | + formState: { errors } |
| 43 | + } = useForm({ |
| 44 | + resolver: yupResolver(schema), |
| 45 | + defaultValues: { |
| 46 | + name: defaultValues?.name ?? '', |
| 47 | + code: defaultValues?.code ?? '' |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + return ( |
| 52 | + <NERFormModal |
| 53 | + open={showModal} |
| 54 | + onHide={handleClose} |
| 55 | + title={`${defaultValues ? 'Edit' : 'Create'} Index Code`} |
| 56 | + reset={() => reset({ name: '', code: '' })} |
| 57 | + handleUseFormSubmit={handleSubmit} |
| 58 | + onFormSubmit={onSubmit} |
| 59 | + formId="edit-index-code-form" |
| 60 | + showCloseButton |
| 61 | + > |
| 62 | + <FormControl> |
| 63 | + <FormLabel>Name</FormLabel> |
| 64 | + <ReactHookTextField name="name" control={control} sx={{ width: 1 }} /> |
| 65 | + <FormHelperText error>{errors.name?.message}</FormHelperText> |
| 66 | + <FormLabel>Code</FormLabel> |
| 67 | + <ReactHookTextField name="code" control={control} sx={{ width: 1 }} /> |
| 68 | + <FormHelperText error>{errors.code?.message}</FormHelperText> |
| 69 | + </FormControl> |
| 70 | + </NERFormModal> |
| 71 | + ); |
| 72 | +}; |
| 73 | + |
| 74 | +export default IndexCodeFormModal; |
0 commit comments