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 < 2) 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, id: item.id })) return result; } return []; } async function savePuestoSuperior(input, auth) { let rest = new Service("/plaza/puestosuperior") let body = { "active": 1, "nombre": input.title, "decription": input.id, "modifyday": "2023-02-12T23:55:26.007", "createday": "2023-02-12T23:55:26.007", "id": null, "descripction": input.id, "modify_day": "2023-02-12T23:55:26.007", } let result = await rest.post(body, auth.token); let { id, nombre } = result; return { id, nombre } } 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.number().required("El puesto superior es requerido"), 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 [openDialog, toggleOpenDialog] = React.useState(false); const [openSugg, setOpenSugg] = React.useState(false); const [options, setOptions] = React.useState([]); const [dialogValue, setDialogValueHook] = React.useState({ title: '', id: '', }); let setDialogValue = (value) => { // console.log('llamada', value) // setValues({...values, puestosuperior: value?.title }) setDialogValueHook(value) } const loading = openSugg && options.length === 0; React.useEffect(() => { let active = true; if (!loading) { return undefined; } (async () => { let puestos = await getPuestoSuperior(dialogValue.title, auth) if (active) { setOptions(puestos); } })(); return () => { active = false; }; }, [loading, dialogValue, auth]); const handleClose = () => false const changeDepartamento = (event) => { setDepartamento(event.target.value); }; const handleCloseDialog = () => { setDialogValue({ title: '', id: '', }); toggleOpenDialog(false); }; const handleSubmitDialog = async (event) => { event.preventDefault(); console.log('to save: ', dialogValue) let { id, nombre } = await savePuestoSuperior(dialogValue, auth) if (id) { setDialogValue({ title: nombre, id: id, }); } setDialogValue({ title: dialogValue.title, id: dialogValue.id }); handleCloseDialog(); }; const AutoCompleteChange = (event, newValue) => { console.log('newValue', newValue) setValues({ ...values, puestosuperior: newValue?.id }) if (typeof newValue === 'string') { setTimeout(() => { toggleOpenDialog(true); setDialogValue({ title: newValue, id: '', }); }); } else if (newValue && newValue.inputValue) { toggleOpenDialog(true); setDialogValue({ title: newValue.inputValue, id: '', }); } else { setDialogValue(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: null, 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; // console.log({ values }) 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, id: 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 }
{ 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('titulo',title) setOptions([]); setDialogValue({ title: event.target.value, id: '', }); }, endAdornment: ( {loading ? : null} {params.InputProps.endAdornment} ), }} /> )} />
    Departamento } />
    theme.zIndex.drawer + 1 }} open={open} onClick={handleClose} >
    ) } export default memo(Manual);