import { Button, DialogActions, DialogContent, FormControl, FormHelperText, InputLabel, MenuItem, Select, Stack, TextField } from "@mui/material"; import {useTranslations} from "next-intl"; import useRequest from "@/lib/app/hooks/useRequest"; import * as Yup from "yup"; import {useFormik} from "formik"; import {ADD_USER_MANAGEMENT} from "@/core/data/apiRoutes"; const CreateContent = ({mutate, fetchUrl, setOpenConfirmDialog}) => { const t = useTranslations(); const requestServer = useRequest({auth: true}) const validationSchema = Yup.object().shape({ phone_number: Yup.mixed().test("is-number", `${t("AddDialog.phone_number_number")}`, (value) => !isNaN(value)).test("positive", `${t("AddDialog.phone_number_positive")}`, (value) => value >= 0) .test("max", `${t("AddDialog.phone_number_max")}`, (value) => value.length <= 11) .required(t("AddDialog.phone_number_error")), national_id: Yup.mixed().test("is-number", `${t("AddDialog.national_id_number")}`, (value) => !isNaN(value)).test("positive", `${t("AddDialog.national_id_positive")}`, (value) => value >= 0) .test("max", `${t("AddDialog.national_id_max")}`, (value) => value.length <= 10) .required(t("AddDialog.national_id_error")), type_id: Yup.number().required(t("AddDialog.type_id_error")), navgan_id: Yup.number().when('type_id', { is: 1, // Condition: Check if type_id is equal to 1 then: (schema) => schema.required(t("AddDialog.navgan_id_error")), otherwise: (schema) => schema, // No validation for navgan_id when type_id is not 1 }) }); const formik = useFormik({ initialValues: { phone_number: "", national_id: "", type_id: "", navgan_id: "", }, validationSchema, onSubmit: (values, {setSubmitting}) => { const formData = new FormData(); formData.append("phone_number", values.phone_number); formData.append("national_id", values.national_id); formData.append("type_id", values.type_id); if (formik.values.type_id === 1) formData.append("navgan_id", values.navgan_id); requestServer(ADD_USER_MANAGEMENT, 'post', { data: formData, }).then((response) => { setOpenConfirmDialog(false) mutate(fetchUrl) update_notification() }).catch(() => { }).finally(() => { setSubmitting(false); }); }, }); return ( <> { if (event.target.value.length <= 11) return formik.handleChange(event) }} fullWidth variant="outlined" onBlur={formik.handleBlur("phone_number")} error={formik.touched.phone_number && Boolean(formik.errors.phone_number)} helperText={formik.touched.phone_number && formik.errors.phone_number} sx={{mt: 1}} /> { if (event.target.value.length <= 10) return formik.handleChange(event) }} fullWidth variant="outlined" onBlur={formik.handleBlur("national_id")} error={formik.touched.national_id && Boolean(formik.errors.national_id)} helperText={formik.touched.national_id && formik.errors.national_id} sx={{mt: 1}} /> {t("AddDialog.type_id")} {formik.touched.type_id && formik.errors.type_id} {formik.values.type_id === 1 ? () : null} ) } export default CreateContent