123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520 |
- 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 (
- <Dialog
- open={visible}
- fullWidth={true}
- maxWidth="md"
- aria-labelledby="contained-modal-title-vcenter"
- onClose={onClose}>
- <DialogTitle className="modal-title" style={{ color: '#252525' }}>
- <button onClick={onClose} type="button" className="close" data-dismiss="modal">×</button>
- Agregar Puesto
- </DialogTitle>
- <DialogContent className="modal-body">
- <Tabs value={tab} onChange={changeTab} aria-label="basic tabs example">
- <Tab label="Información" />
- <Tab label="Pruebas" />
- </Tabs>
- <Dialog open={openDialog} onClose={handleCloseDialog}>
- <form onSubmit={handleSubmitDialog}>
- <DialogTitle>Agrega un nuevo Puesto</DialogTitle>
- <DialogContent>
- <DialogContentText>
- Agrega la descripcion del puesto
- </DialogContentText>
- <TextField
- autoFocus
- margin="dense"
- id="name"
- value={dialogValue.title}
- onChange={(event) =>
- setDialogValue({
- ...dialogValue,
- title: event.target.value,
- })
- }
- label="Puesto"
- type="text"
- variant="standard"
- />
- <TextField
- margin="dense"
- id="name"
- value={dialogValue.year}
- onChange={(event) =>
- setDialogValue({
- ...dialogValue,
- year: event.target.value,
- })
- }
- label="Descripción"
- type="text"
- variant="standard"
- />
- </DialogContent>
- <DialogActions>
- <Button onClick={handleCloseDialog}>Cancelar</Button>
- <Button type="submit">Agregar</Button>
- </DialogActions>
- </form>
- </Dialog>
- <FormikProvider style={{ paddingTop: 25 }} value={formik}>
- <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
- <TabPanel value={tab} index={1}>
- <Stack spacing={1}>
- <Box style={{ paddingTop: 5, paddingLeft: 15 }}>
- <Divider />
- <h4 style={{ paddingTop: 10, paddingBottom: 10 }}>Selecciona los test a realizar</h4>
- <Divider />
- <FormGroup>
- {
- testsCatalog ?
- testsCatalog.data.map(test => (
- <FormControlLabel
- key={test.id}
- control={
- <Checkbox
- checked={checklist.includes((test.id))}
- onChange={(event) => addPrueba(event.target.checked, test.id)}
- />
- }
- label={test.nombre}
- />
- )) : null
- }
- </FormGroup>
- </Box>
- </Stack>
- </TabPanel>
- <TabPanel value={tab} index={0}>
- <Stack spacing={3}>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={4}>
- <TextField
- label="Nombre"
- fullWidth
- {...getFieldProps('nombrepuesto')}
- helperText={touched.nombrepuesto && errors.nombrepuesto}
- error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
- />
- <FormControl fullWidth>
- {/*
- <InputLabel id="demo-simple-select-label">Puesto Superior</InputLabel>
- <Select
- labelId="demo-simple-select-label"
- value={puestoSup}
- label="Puesto Superior"
- onChange={changePuestoSup}
- {...getFieldProps('puestosuperior')}
- error={Boolean(touched.puestosuperior && errors.puestosuperior)} >
- {
- data ?
- data.data.map(cate => {
- return (
- <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
- )
- })
- : <MenuItem>Null</MenuItem>
- }
- </Select>
- */}
- <Autocomplete
- fullWidth
- value={valueDialog}
- onChange={AutoCompleteChange}
- open={openSugg}
- onOpen={() => {
- 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) => <li {...props}>{option.title}</li>}
- freeSolo
- renderInput={(params) => (
- <TextField
- {...params}
- {...getFieldProps('puestosuperior')}
- error={Boolean(touched.puestosuperior && errors.puestosuperior)}
- label="Puesto Superior"
- InputProps={{
- ...params.InputProps,
- onChange: (event) => {
- let title = event.target.value;
- console.log(title)
- setOptions([]);
- setDialogValue({
- title: event.target.value,
- year: '',
- });
- },
- endAdornment: (
- <React.Fragment>
- {loading ? <CircularProgress color="inherit" size={20} /> : null}
- {params.InputProps.endAdornment}
- </React.Fragment>
- ),
- }}
- />
- )}
- />
- </FormControl>
- </Stack>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={4}>
- <FormControl fullWidth>
- <InputLabel id="demo-simple-select-label">Departamento</InputLabel>
- <Select
- labelId="demo-simple-select-label"
- value={departamento}
- label="Departamento"
- onChange={changeDepartamento}
- {...getFieldProps('aredepto')}
- error={Boolean(touched.aredepto && errors.aredepto)} >
- {
- data ?
- data.data.map(cate => {
- return (
- <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
- )
- })
- : <MenuItem>Null</MenuItem>
- }
- </Select>
- </FormControl>
- <LocalizationProvider
- dateAdapter={DateFnsUtils}>
- <DesktopDatePicker
- label="Fecha Creación"
- fullWidth
- inputFormat="dd/MM/yyyy"
- {...getFieldProps('fecha')}
- value={date}
- onChange={setDate}
- renderInput={(params) =>
- <TextField
- disabled={true}
- label="Fecha Creación"
- fullWidth
- {...params}
- />}
- />
- </LocalizationProvider>
- </Stack>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={4}>
- <TextField
- id="filled-multiline-static"
- multiline
- rows={4}
- variant="filled"
- label="Notas"
- fullWidth
- type="text"
- {...getFieldProps('notas')}
- error={Boolean(touched.notas && errors.notas)}
- helperText={touched.notas && errors.notas}
- />
- </Stack>
- </Stack>
- </TabPanel>
- <DialogActions>
- <Button
- type="submit"
- className="registerBtn"
- variant="contained"
- sx={{ mt: 1, mr: 1 }} >
- {'Guardar'}
- </Button>
- </DialogActions>
- </Form>
- </FormikProvider>
- </DialogContent>
- <Backdrop
- sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
- open={open}
- onClick={handleClose} >
- <CircularProgress color="inherit" />
- </Backdrop>
- </Dialog>
- )
- }
- export default memo(Manual);
|