import React, { memo } from 'react'; import * as Yup from 'yup'; import { useFormik, Form, FormikProvider } from 'formik'; import toast from 'react-hot-toast'; import { AdapterDateFns as DateFnsUtils } from '@mui/x-date-pickers/AdapterDateFns'; import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { Button, Stack, TextField, MenuItem, FormControl, InputLabel, Select, Backdrop, CircularProgress, Box, Divider, Tabs, Tab, FormGroup, Checkbox, FormControlLabel, Dialog, DialogContent, DialogTitle, DialogActions, DialogContentText, } from '@mui/material'; import Autocomplete, { createFilterOptions } from '@mui/material/Autocomplete'; import { Service } from '../../Utils/HTTP'; import { useQuery, useMutation, useQueryClient } from 'react-query'; import { TabPanel } from './TabPanel' import { useSelector } from 'react-redux'; const filter = createFilterOptions(); async function getPuestoSuperior (puesto, auth) { if (puesto.length < 3) return [] let rest = new Service(`/plaza/keypuestosup?keyword=${puesto}`) let result = await rest.get(auth.token) console.log(result) if (result?.data?.length > 0) { result = result.data.map((item) => ({ 'title': item.nombre, year: item.id })) return result; } return []; } function Manual(props) { const auth = useSelector((state) => state.token) const getCategories = async () => { let rest = new Service("/categoria/getAll") return await rest.getQuery(auth.token) } const getTest = async () => { let rest = new Service("/tests/getAll") return await rest.getQuery(auth.token) } const { data } = useQuery('categories', getCategories); const { data: testsCatalog } = useQuery('tests', getTest); const queryClient = useQueryClient(); const NewPlazaSchema = Yup.object().shape({ nombrepuesto: Yup.string().required('El nombre es requerido').min(5, "El nombre del puesto debe ser mayor a 5 caracteres").max(100), puestosuperior: Yup.string().required("El puesto es requerido").min(5, "El nombre del puesto debe ser mayor a 5 caracteres").max(30), aredepto: Yup.number().required('Escoge alguna área'), fecha: Yup.date("Ingresa una fecha válida"), notas: Yup.string("Ingresa una nota válida").min(5, "Ingresa una nota válida").max(150), tests: Yup.array() }) const [departamento, setDepartamento] = React.useState(''); const [open, setOpen] = React.useState(false); const [date, setDate] = React.useState(new Date()); const [tab, setTab] = React.useState(0); const [checklist, setChecklist] = React.useState([]); const [valueDialog, setValueDialog] = React.useState(); const [openDialog, toggleOpenDialog] = React.useState(false); const [openSugg, setOpenSugg] = React.useState(false); const [options, setOptions] = React.useState([]); const [dialogValue, setDialogValue] = React.useState({ title: '', year: '', }); const loading = openSugg && options.length === 0; React.useEffect(() => { console.log('dialogValue', dialogValue) let active = true; console.log('loading', loading) if (!loading) { return undefined; } (async () => { let puestos = await getPuestoSuperior(dialogValue.title, auth) console.log('puestos', puestos) if (active) { setOptions(puestos); } })(); return () => { active = false; }; }, [loading, dialogValue, auth]); const handleClose = () => false const changeDepartamento = (event) => { setDepartamento(event.target.value); }; const handleCloseDialog = () => { setDialogValue({ title: '', year: '', }); toggleOpenDialog(false); }; const handleSubmitDialog = (event) => { event.preventDefault(); setValueDialog({ title: dialogValue.title, year: parseInt(dialogValue.year, 10), }); handleCloseDialog(); }; const AutoCompleteChange = (event, newValue) => { console.log('newValue', newValue) if (typeof newValue === 'string') { // timeout to avoid instant validation of the dialog's form. setTimeout(() => { toggleOpenDialog(true); setDialogValue({ title: newValue, year: '', }); }); } else if (newValue && newValue.inputValue) { toggleOpenDialog(true); setDialogValue({ title: newValue.inputValue, year: '', }); } else { setValueDialog(newValue); } } const agregarPuesto = async (puesto) => { let rest = new Service('/plaza/save'); return await rest.postQuery(puesto, auth.token); } const puestoMutation = useMutation(agregarPuesto) let { visible, onClose } = props const formik = useFormik({ initialValues: { nombrepuesto: "", puestosuperior: "The Godfather", aredepto: 1, fecha: date, notas: "", tests: [] }, onSubmit: (fields, { resetForm }) => { if (fields.tests.length === 0) { toast.error("Recuerda que seleccionar al menos un test") setTab(1) return } setOpen(true) fields['fecha'] = new Date(fields.fecha).toISOString(); fields['areadeptoplz_id'] = 1; fields['id'] = -1; puestoMutation.mutate(fields, { onSuccess: () => { setOpen(false) resetForm(); onClose(); queryClient.invalidateQueries('puestos') toast.success("Puesto Agregado") }, onError: () => { setOpen(false) toast.error("Ups!! Ocurrio un error, inténtalo más tarde") } }) }, validationSchema: NewPlazaSchema, }); const changeTab = (_event, newValue) => { setTab(newValue); }; const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik; const addPrueba = (check, id) => { let { tests } = values let temp; if (check) { temp = [...tests, { id }] } else { temp = tests.filter(test => test.id !== id); } setChecklist(temp.map(test => test.id)) setValues({ ...values, tests: temp }) }; return ( Agregar Puesto
Agrega un nuevo Puesto Agrega la descripcion del puesto setDialogValue({ ...dialogValue, title: event.target.value, }) } label="Puesto" type="text" variant="standard" /> setDialogValue({ ...dialogValue, year: event.target.value, }) } label="Descripción" type="text" variant="standard" />

Selecciona los test a realizar

{ testsCatalog ? testsCatalog.data.map(test => ( addPrueba(event.target.checked, test.id)} /> } label={test.nombre} /> )) : null }
{/* Puesto Superior */} { setOpenSugg(true); }} onClose={() => { setOpenSugg(false); }} isOptionEqualToValue={(option, value) => option.title === value.title} filterOptions={(options, params) => { const filtered = filter(options, params); if (params.inputValue !== '') { filtered.push({ inputValue: params.inputValue, title: `Add "${params.inputValue}"`, }); } return filtered; }} id="puesto_superior_autocomplete" options={options} loading={loading} getOptionLabel={(option) => { if (typeof option === 'string') { return option; } if (option.inputValue) { return option.inputValue; } return option.title; }} selectOnFocus clearOnBlur handleHomeEndKeys renderOption={(props, option) =>
  • {option.title}
  • } freeSolo renderInput={(params) => ( { let title = event.target.value; console.log(title) setOptions([]); setDialogValue({ title: event.target.value, year: '', }); }, endAdornment: ( {loading ? : null} {params.InputProps.endAdornment} ), }} /> )} />
    Departamento } />
    theme.zIndex.drawer + 1 }} open={open} onClick={handleClose} >
    ) } export default memo(Manual);