Ver código fonte

editar plaza funcionality

amenpunk 3 anos atrás
pai
commit
cfcdb84cd9

+ 21 - 4
src/Components/Modal/AgregarManual.js

@@ -5,7 +5,11 @@ import { Modal } from 'react-bootstrap'
 
 import DateFnsUtils from '@date-io/date-fns';
 import { DesktopDatePicker,LocalizationProvider } from '@mui/lab';
-import {  Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select } from '@mui/material';
+
+import {  
+    Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select,
+    Backdrop, CircularProgress
+} from '@mui/material';
 
 import { Service } from '../../Utils/HTTP';
 import  useAuth from '../../Auth/useAuth';
@@ -17,13 +21,15 @@ export default function Manual ( props ) {
 
     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("El puesto superior debe ser un número"),
+        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),
     })
     
     const [departamento, setDepartamento] = React.useState('');
+    const [open, setOpen] = React.useState(false);
+    const handleClose = () => false
 
     const changeDepartamento = (event) => {
         setDepartamento(event.target.value);
@@ -46,6 +52,7 @@ export default function Manual ( props ) {
         },
         onSubmit: ( fields, { resetForm } ) => {
 
+            setOpen(true)
             fields['fecha'] =  new Date(fields.fecha).toISOString();
             fields['areadeptoplz_id'] = 1;
             fields['id'] = -1;
@@ -56,12 +63,14 @@ export default function Manual ( props ) {
             .post( fields, token )
             .then( _ => {
                 resetForm();
-                Complete(true);
+                Complete(true, "Puesto agregado exitosamente");
                 onClose();
+                setOpen(false)
             })
             .catch(err => {
                 console.error(err)
-                Complete(false);
+                Complete(false,"Ocurrio un error intentalo nuevamente");
+                setOpen(false)
             })
 
         },
@@ -114,6 +123,7 @@ export default function Manual ( props ) {
                                         error={Boolean(touched.aredepto && errors.aredepto)} >
                                         {
                                         departamentos.map( ( nivel, index ) => {
+                                            index = index + 1;
                                             return (
                                                 <MenuItem key={nivel} value={index}>{nivel}</MenuItem>
                                             )
@@ -175,6 +185,13 @@ export default function Manual ( props ) {
                     </Form>
                 </FormikProvider>
             </Modal.Body>
+            <Backdrop
+                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
+                open={open}
+                onClick={handleClose} >
+            <CircularProgress color="inherit" />
+            </Backdrop>
+
         </Modal>
     )
 }

+ 193 - 139
src/Components/Modal/EditPlaza.js

@@ -1,154 +1,208 @@
-import React from 'react';
+import React, { useEffect } from 'react';
 import * as Yup from 'yup';
-import { Modal, Row, Col, Button } from 'react-bootstrap'
-import { Formik, Field, Form } from 'formik';
-
-import NotFound from '../../Images/not_found.png';
-const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/gif", "image/png"];
-
-const NewPlazaSchema = Yup.object().shape({
-    nombre : Yup.string().required('El nombre es requerido').min(5).max(20),
-    description : Yup.string().required('La description es requerida').min(5).max(20),
-    salario : Yup.number().required('El salario es requerido'),
-    imagen:  Yup.mixed().required('El imagen es requerido').test('fileSize', "El archivo es demasiado grande", value => {
-        if(!value || value.length <= 0) return false
-        return value[0].size < 200000
-    }).test('fileType', "El tipo del archivo no es válido", value => {
-        if(!value) return false
-        return SUPPORTED_FORMATS.includes(value[0].type)
-    })
-})
-
-export default function Edit(props) {
+import { useFormik, Form, FormikProvider } from 'formik';
+import { Modal } from 'react-bootstrap'
 
-    let { visible, onClose, puesto } = props
+import DateFnsUtils from '@date-io/date-fns';
+import { DesktopDatePicker,LocalizationProvider } from '@mui/lab';
 
-    let [ filename, setFilename ] = React.useState('');
-    let [ file, setFile ] = React.useState(undefined);
-    let [ type, setType ] = React.useState(undefined);
-    let [ validType, setValidType ] = React.useState(false);
+import {  
+    Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select,
+    Backdrop, CircularProgress
+} from '@mui/material';
 
-    const hiddenFileInput = React.useRef(null);
-    const PickFile = event => hiddenFileInput.current.click();
+import { Service } from '../../Utils/HTTP';
+import  useAuth from '../../Auth/useAuth';
 
-    React.useEffect(() => {
-        if( SUPPORTED_FORMATS.includes(type) ){
-            setValidType(true)
-        }else{
-            setValidType(false)
-        }
+import { departamentos } from '../Password/Rows'
 
-    }, [type])
+export default function Edit(props) {
 
-    return(
-        <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered  show={visible} onHide={onClose}>
+    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("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),
+    })
+    
+    const [departamento, setDepartamento] = React.useState('');
+    const [open, setOpen] = React.useState(false);
+    const handleClose = () => false
+
+    const changeDepartamento = (event) => {
+        setDepartamento(event.target.value);
+    };
+
+
+    const [date, setDate] = React.useState(new Date());
+    const auth = useAuth();
+    const token = auth.getToken();
+
+    let {onClose, puesto : { data }, Complete, visible  } = props
+    
+    const formik = useFormik({
+        initialValues: {
+            nombrepuesto: data ? data.nombrepuesto :"",
+            puestosuperior:data ?data.puestosuperior :"",
+            aredepto: 1,
+            fecha: date,
+            notas:data? data.notas :"",
+        },
+        onSubmit: ( fields, { resetForm } ) => {
+            setOpen(true)
+            fields['fecha'] =  new Date(fields.fecha).toISOString();
+            fields['areadeptoplz_id'] = 1;
+            fields['id'] = -1;
+            let Rest = new Service('/plaza/edit');
+            Rest
+            .post( fields, token )
+            .then( _ => {
+                resetForm();
+                Complete(true,"Puesto actualizado exitosamente");
+                onClose();
+                setOpen(false)
+            })
+            .catch(err => {
+                console.error(err)
+                Complete(false,"Ocurrio un error, intentalo nuevamente");
+                setOpen(false)
+            })
+
+        },
+        validationSchema: NewPlazaSchema,
+    });
+
+    const { errors, touched, handleSubmit, getFieldProps, setValues} = formik;
+    
+    useEffect(() => {
+        console.log(data); 
+        setValues({
+            nombrepuesto: data.nombrepuesto,
+            notas:data.notas,
+            puestosuperior:data ?data.puestosuperior :"",
+            aredepto: 1,
+            fecha:new Date(data.create_day),
+        })
+
+    },[data,setValues])
+
+
+    return (
+
+        <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered show={visible} onHide={onClose}>
             <Modal.Header>
-                <button onClick={onClose} type="button" className="close" data-dismiss="modal">&times;</button>
-                <h4 className="modal-title">Editar plaza</h4>
+                <button onClick={onClose}  type="button" className="close" data-dismiss="modal">&times;</button>
+                <h4 className="modal-title" style={{color : '#252525'}}>Agregar plaza</h4>
             </Modal.Header>
-
-           <Modal.Body className="modal-body">
-                <Formik
-
-                    initialValues={{
-                        nombre: puesto.id +" - "+  puesto.nombre,
-                        description: puesto.description,
-                        salario: puesto.salario,
-                        imagen: '',
-                    }}
-
-                    validationSchema={NewPlazaSchema}
-                    onSubmit={ (values) => {
-                        // console.log('VALUES >> ',values)
-                        props.setManual(false)
-                    }} >
-
-
-                    { ({  errors, touched, validateField, validateForm, setFieldValue  }) => (
-                        <Form>
-                            <Row>
-
-                                <Col md="4">
-                                    <div className="img-container">
-                                        <img alt="agregar plaza manual" src={ validType ? file : NotFound}/>
-                                    </div>
-                                </Col>
-
-                                <Col md="8">
-
-                                    <input 
-                                        value={filename} 
-                                        type="text" 
-                                        className="file-upload-input" 
-                                        disabled="" 
-                                        placeholder="Ningún archivo seleccionado" readOnly
+            <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)} >
+                                        {
+                                        departamentos.map( ( nivel, index ) => {
+                                            return (
+                                                <MenuItem key={index} value={index}>{nivel}</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} 
+                                            />}
                                     />
-
-                                    <Button className="btn_add_producto_confirm" style={{ marginLeft : 15 }} onClick={PickFile}>
-                                        SUBIR FOTO
-                                    </Button>
-
-                                    {errors.imagen && touched.imagen && <div className="error_feedback">{errors.imagen}</div>}
-                                    <input
-                                        multiple={false}
-                                        type="file"
-                                        ref={hiddenFileInput}
-                                        onChange={(event) => {
-                                            const files = event.target.files;
-                                            console.log('files crud ', files[0])
-                                            let myFiles =Array.from(files);
-                                            setFieldValue("imagen", myFiles);
-                                            setFilename(myFiles[0].name)
-                                            setType(myFiles[0].type)
-                                            const objectUrl = URL.createObjectURL(files[0])
-                                            setFile(objectUrl)
-                                        }}
-                                        style={{display: 'none'}}
+                                </LocalizationProvider>
+
+                            </Stack>
+
+                            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
+                                <TextField
+                                    id="filled-multiline-static"
+                                    multiline
+                                    rows={4}
+                                    defaultValue="Default Value"
+                                    variant="filled"
+                                    label="Notas"
+                                    fullWidth
+                                    type="text"
+                                    {...getFieldProps('notas')}
+                                    error={Boolean(touched.notas && errors.notas)}
+                                    helperText={touched.notas && errors.notas}
                                     />
-
-                                </Col>
-
-                            </Row>
-                            <div className="data_product">
-                                <Row>
-                                    <Col md="12">
-
-                                        {errors.nombre && touched.nombre && <div className="error_feedback">{errors.nombre}</div>}
-                                        <Field  name="nombre" placeholder="Nombre de la plaza"/>
-
-                                        {errors.description && touched.description && <div className="error_feedback">{errors.description}</div>}
-                                        <Field name="description">
-                                            {({ field, form, meta }) => {
-                                                return(
-                                                    <textarea id="description" name="description" value={field.value} onChange={field.onChange} placeholder="Descripción general de la plaza"></textarea>
-                                                )
-                                            }}
-                                        </Field>
-
-                                        {errors.salario && touched.salario && <div className="error_feedback">{errors.salario}</div>}
-                                        <Field name="salario" type="text" placeholder="Salario"/>
-
-
-                                    </Col>
-
-
-                                    <div className="add_producto_confirm">
-                                        <div className="btn_add_producto_confirm">
-                                            <span href="/" type="submit">Actualizar plaza</span>
-                                        </div>
-                                    </div>
-
-                                </Row>
-                            </div>
-                        </Form>
-                    )}
-
-
-
-
-                </Formik>
-
+                            </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={handleClose} >
+            <CircularProgress color="inherit" />
+            </Backdrop>
+
         </Modal>
     )
 }

+ 4 - 2
src/Components/Password/Rows.js

@@ -70,7 +70,9 @@ export const niveles_educativos = [
 
 
 export const departamentos = [
-    "Jutiapa",
     "Guatemala",
-    "Santa Rosa",
+    "Guatemala",
+    "Guatemala",
+    "Guatemala",
+    "Guatemala",
 ]

+ 0 - 1
src/Components/Puestos/ListMode.jsx

@@ -11,7 +11,6 @@ export function ListMode(props) {
     let { setEdit, setDelete, setShow, setPuesto, data, index, showing } = props;
 
     const isMovil = Size('(min-width:770px)');
-    console.log("IS MOV:: ", isMovil)
 
     return(
         <Col md="12">

+ 3 - 2
src/Pages/Login.jsx

@@ -57,17 +57,18 @@ export function Login() {
             request
             .post({})
             .then( response => {
-                // console.log("Service Response :: ", response)
+                console.log("Service Response :: ", response)
                 let { token, nombre, apelidos } = response;
                 toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
                 token = token.replace("Bearer ", "")
                 let user_permissions = jwt_decode(token);
                 Object.keys(user_permissions);
-                console.log("Bearer ", token)
+                // console.log("Bearer ", token)
                 setTimeout( () => {
                     setOpen(false)
                     auth.login(token)
                 }, 2000)
+
             }) 
             .catch( err => {
                 setOpen(false)

+ 5 - 6
src/Pages/Puestos.jsx

@@ -27,7 +27,7 @@ import { GridMode } from '../Components/Puestos/GridMode'
 import { Add as AddIcon, } from '@mui/icons-material/'
 
 function Divide(arregloOriginal){
-    const LONGITUD_PEDAZOS = 7;
+    const LONGITUD_PEDAZOS = 9;
     let arregloDeArreglos = [];
     for (let i = 0; i < arregloOriginal.length; i += LONGITUD_PEDAZOS) {
         let pedazo = arregloOriginal.slice(i, i + LONGITUD_PEDAZOS);
@@ -38,10 +38,10 @@ function Divide(arregloOriginal){
 
 export function Puestos() {
 
-    const Complete =  (status) => {
+    const Complete =  (status, message) => {
 
         if(!status){
-            toast.error('Ups creo que ocurrio un error, intentalo nuevamente')
+            toast.error(message)
         }
 
         let rest = new Service("/plaza/getall")
@@ -63,7 +63,7 @@ export function Puestos() {
                 console.log('error fetching data  ', error );
             })
 
-        toast.success('Puesto agregado exitosamente')
+        toast.success(message)
     } 
 
     const auth = useAuth();
@@ -203,10 +203,9 @@ export function Puestos() {
             </div>
 
             <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false) } />
-
             <Manual Complete={Complete} visible={manual} onClose={() => setManual(false)}/>
 
-            <Editar   puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
+            <Editar  Complete={Complete} puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
             <Mostrar  puesto={puesto} visible={show} onClose={() => setShow(false)} />