import { Grid } from '@mui/material'; import { FC, ReactNode, useCallback, useMemo, useRef } from 'react'; import { v4 as uuidv4 } from 'uuid'; import ActionGroup from '../ActionGroup'; import api from '../../lib/api'; import handleAPIError from '../../lib/handleAPIError'; import MessageGroup, { MessageGroupForwardedRefContent } from '../MessageGroup'; import OutlinedInputWithLabel from '../OutlinedInputWithLabel'; import mailServerListSchema from './schema'; import SelectWithLabel from '../SelectWithLabel'; import useFormikUtils from '../../hooks/useFormikUtils'; import UncontrolledInput from '../UncontrolledInput'; const AddMailServerForm: FC = (props) => { const { localhostDomain = '', mailServerUuid, onSubmit, previousFormikValues, } = props; const msUuid = useMemo( () => mailServerUuid ?? uuidv4(), [mailServerUuid], ); const messageGroupRef = useRef({}); const setApiMessage = useCallback( (message?: Message) => messageGroupRef.current.setMessage?.call(null, 'api', message), [], ); const { disableAutocomplete, disabledSubmit, formik, formikErrors, handleChange, } = useFormikUtils({ initialValues: previousFormikValues ?? { [msUuid]: { address: '', authentication: 'none', heloDomain: localhostDomain, port: 587, security: 'none', uuid: msUuid, }, }, onSubmit: (...args) => { onSubmit( { mailServer: args[0][msUuid], onConfirmCancel: (values, { setSubmitting }) => setSubmitting(false), onConfirmProceed: (values, { setSubmitting }) => { let errorMessage: ReactNode = <>Failed to add mail server.; let method: 'post' | 'put' = 'post'; let successMessage = <>Mail server added.; let url = '/mail-server'; if (previousFormikValues) { errorMessage = <>Failed to update mail server.; method = 'put'; successMessage = <>Mail server updated.; url += `/${msUuid}`; } api[method](url, values[msUuid]) .then(() => { setApiMessage({ children: successMessage }); }) .catch((error) => { const emsg = handleAPIError(error); emsg.children = ( <> {errorMessage} {emsg.children} ); setApiMessage(emsg); }) .finally(() => { setSubmitting(false); }); }, }, ...args, ); }, validationSchema: mailServerListSchema, }); const addressChain = useMemo(() => `${msUuid}.address`, [msUuid]); const authenticationChain = useMemo( () => `${msUuid}.authentication`, [msUuid], ); const confirmPasswordChain = useMemo( () => `${msUuid}.confirmPassword`, [msUuid], ); const heloDomainChain = useMemo( () => `${msUuid}.heloDomain`, [msUuid], ); const passwordChain = useMemo(() => `${msUuid}.password`, [msUuid]); const portChain = useMemo(() => `${msUuid}.port`, [msUuid]); const securityChain = useMemo(() => `${msUuid}.security`, [msUuid]); const usernameChain = useMemo(() => `${msUuid}.username`, [msUuid]); return ( { event.preventDefault(); formik.submitForm(); }} container columns={{ xs: 1, sm: 2 }} spacing="1em" > } /> } /> } /> } /> } /> } /> } /> } /> ); }; export default AddMailServerForm;