| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235 |
- import React, { memo, useCallback, useMemo, useEffect } from 'react';
- import * as Yup from 'yup';
- import { useFormik, Form, FormikProvider } from 'formik';
- import { Modal } from 'react-bootstrap'
- import toast, { Toaster } from 'react-hot-toast';
- import DateFnsUtils from '@date-io/date-fns';
- import { DesktopDatePicker, LocalizationProvider } from '@mui/lab';
- import {
- Button, Stack, TextField, MenuItem, FormControl, InputLabel, Select,
- Backdrop, CircularProgress
- } from '@mui/material';
- import { Service } from '../../Utils/HTTP';
- import useAuth from '../../Auth/useAuth';
- import { useQuery, useMutation, useQueryClient } from 'react-query'
- const NewPlazaSchema = Yup.object().shape({
- id: Yup.number(),
- 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("El puesto superior debe ser un número").required("El puesto 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).max(150),
- })
- function Edit(props) {
- const now = useMemo(() => new Date(), [])
- const auth = useAuth();
- const token = auth.getToken();
- const queryClient = useQueryClient()
- let { visible, toggle, puesto } = props
- const [departamento, setDepartamento] = React.useState('');
- const [open, setOpen] = React.useState(false);
- const changeDepartamento = useCallback((event) => {
- setDepartamento(event.target.value);
- }, []);
- const [date, setDate] = React.useState(now);
- const getCategories = async () => {
- let rest = new Service("/categoria/getAll")
- return await rest.getQuery(token)
- }
- const updatePuesto = async (fields) => {
- let rest = new Service('/plaza/edit');
- return rest.putQuery(fields, token)
- }
- const puestoMutation = useMutation(updatePuesto)
- const close = () => toggle("EDIT");
- const { data } = useQuery('categories', getCategories);
- const formik = useFormik({
- initialValues: {
- id: 1,
- nombrepuesto: "",
- puestosuperior: 1,
- aredepto: 1,
- fecha: now,
- notas: ""
- },
- onSubmit: (fields, { resetForm }) => {
- setOpen(true);
- fields['fecha'] = new Date(fields.fecha).toISOString();
- puestoMutation.mutate(fields, {
- onSuccess: () => {
- close();
- setOpen(false)
- toast.success("Puesto Actualizado!!")
- queryClient.invalidateQueries('puestos')
- },
- onError:() => {
- close();
- setOpen(false)
- toast.error("Lo sentimos ocurrió error inténtalo más tarde")
- }
- })
- resetForm();
- },
- validationSchema: NewPlazaSchema,
- });
- const { errors, touched, handleSubmit, getFieldProps, setValues } = formik;
- useEffect(() => {
- console.log("PUESTO :: ", puesto)
- if (puesto) {
- setValues({
- id: puesto.id,
- nombrepuesto: puesto.nombrepuesto,
- puestosuperior: puesto.puestosuperior,
- aredepto: puesto.areadeptoplz_id,
- fecha: new Date(puesto.create_day),
- notas: puesto.notas
- })
- }
- }, [puesto, now, setValues])
- return (
- <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered show={visible} onHide={close}>
- <Modal.Header>
- <button onClick={close} type="button" className="close" data-dismiss="modal">×</button>
- <h4 className="modal-title" style={{ color: '#252525' }}>Editar puesto</h4>
- </Modal.Header>
- <Modal.Body className="modal-body">
- <FormikProvider style={{ padding: 25 }} value={formik}>
- <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
- <Stack spacing={3}>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
- <TextField
- label="Nombre"
- fullWidth
- {...getFieldProps('nombrepuesto')}
- error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
- helperText={touched.nombrepuesto && errors.nombrepuesto}
- />
- <TextField
- label="Puesto Superior"
- fullWidth
- {...getFieldProps('puestosuperior')}
- error={Boolean(touched.puestosuperior && errors.puestosuperior)}
- helperText={touched.puestosuperior && errors.puestosuperior}
- />
- </Stack>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
- <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')}
- xd
- value={date}
- onChange={setDate}
- renderInput={(params) =>
- <TextField
- disabled={true}
- label="Fecha Creación"
- fullWidth
- {...params}
- />}
- />
- </LocalizationProvider>
- </Stack>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
- <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>
- <Modal.Footer>
- <Button
- type="submit"
- className="registerBtn"
- variant="contained"
- sx={{ mt: 1, mr: 1 }} >
- {'Actualizar'}
- </Button>
- </Modal.Footer>
- </Form>
- </FormikProvider>
- </Modal.Body>
- <Backdrop
- sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
- open={open}
- onClick={() => console.log('backdrop')} >
- <CircularProgress color="inherit" />
- </Backdrop>
- <Toaster position="top-right" />
- </Modal>
- )
- }
- export default memo(Edit);
|