Browse Source

editar plaza funcionality

amenpunk 2 years ago
parent
commit
cfcdb84cd9

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

@@ -5,7 +5,11 @@ import { Modal } from 'react-bootstrap'
5 5
 
6 6
 import DateFnsUtils from '@date-io/date-fns';
7 7
 import { DesktopDatePicker,LocalizationProvider } from '@mui/lab';
8
-import {  Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select } from '@mui/material';
8
+
9
+import {  
10
+    Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select,
11
+    Backdrop, CircularProgress
12
+} from '@mui/material';
9 13
 
10 14
 import { Service } from '../../Utils/HTTP';
11 15
 import  useAuth from '../../Auth/useAuth';
@@ -17,13 +21,15 @@ export default function Manual ( props ) {
17 21
 
18 22
     const NewPlazaSchema = Yup.object().shape({
19 23
         nombrepuesto : Yup.string().required('El nombre es requerido').min(5, "El nombre del  puesto debe ser mayor a 5 caracteres").max(100),
20
-        puestosuperior : Yup.number("El puesto superior debe ser un número"),
24
+        puestosuperior : Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
21 25
         aredepto : Yup.number().required('Escoge alguna área'),
22 26
         fecha : Yup.date("Ingresa una fecha válida"),
23 27
         notas : Yup.string("Ingresa una nota válida").min(5).max(150),
24 28
     })
25 29
     
26 30
     const [departamento, setDepartamento] = React.useState('');
31
+    const [open, setOpen] = React.useState(false);
32
+    const handleClose = () => false
27 33
 
28 34
     const changeDepartamento = (event) => {
29 35
         setDepartamento(event.target.value);
@@ -46,6 +52,7 @@ export default function Manual ( props ) {
46 52
         },
47 53
         onSubmit: ( fields, { resetForm } ) => {
48 54
 
55
+            setOpen(true)
49 56
             fields['fecha'] =  new Date(fields.fecha).toISOString();
50 57
             fields['areadeptoplz_id'] = 1;
51 58
             fields['id'] = -1;
@@ -56,12 +63,14 @@ export default function Manual ( props ) {
56 63
             .post( fields, token )
57 64
             .then( _ => {
58 65
                 resetForm();
59
-                Complete(true);
66
+                Complete(true, "Puesto agregado exitosamente");
60 67
                 onClose();
68
+                setOpen(false)
61 69
             })
62 70
             .catch(err => {
63 71
                 console.error(err)
64
-                Complete(false);
72
+                Complete(false,"Ocurrio un error intentalo nuevamente");
73
+                setOpen(false)
65 74
             })
66 75
 
67 76
         },
@@ -114,6 +123,7 @@ export default function Manual ( props ) {
114 123
                                         error={Boolean(touched.aredepto && errors.aredepto)} >
115 124
                                         {
116 125
                                         departamentos.map( ( nivel, index ) => {
126
+                                            index = index + 1;
117 127
                                             return (
118 128
                                                 <MenuItem key={nivel} value={index}>{nivel}</MenuItem>
119 129
                                             )
@@ -175,6 +185,13 @@ export default function Manual ( props ) {
175 185
                     </Form>
176 186
                 </FormikProvider>
177 187
             </Modal.Body>
188
+            <Backdrop
189
+                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
190
+                open={open}
191
+                onClick={handleClose} >
192
+            <CircularProgress color="inherit" />
193
+            </Backdrop>
194
+
178 195
         </Modal>
179 196
     )
180 197
 }

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

@@ -1,154 +1,208 @@
1
-import React from 'react';
1
+import React, { useEffect } from 'react';
2 2
 import * as Yup from 'yup';
3
-import { Modal, Row, Col, Button } from 'react-bootstrap'
4
-import { Formik, Field, Form } from 'formik';
5
-
6
-import NotFound from '../../Images/not_found.png';
7
-const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/gif", "image/png"];
8
-
9
-const NewPlazaSchema = Yup.object().shape({
10
-    nombre : Yup.string().required('El nombre es requerido').min(5).max(20),
11
-    description : Yup.string().required('La description es requerida').min(5).max(20),
12
-    salario : Yup.number().required('El salario es requerido'),
13
-    imagen:  Yup.mixed().required('El imagen es requerido').test('fileSize', "El archivo es demasiado grande", value => {
14
-        if(!value || value.length <= 0) return false
15
-        return value[0].size < 200000
16
-    }).test('fileType', "El tipo del archivo no es válido", value => {
17
-        if(!value) return false
18
-        return SUPPORTED_FORMATS.includes(value[0].type)
19
-    })
20
-})
21
-
22
-export default function Edit(props) {
3
+import { useFormik, Form, FormikProvider } from 'formik';
4
+import { Modal } from 'react-bootstrap'
23 5
 
24
-    let { visible, onClose, puesto } = props
6
+import DateFnsUtils from '@date-io/date-fns';
7
+import { DesktopDatePicker,LocalizationProvider } from '@mui/lab';
25 8
 
26
-    let [ filename, setFilename ] = React.useState('');
27
-    let [ file, setFile ] = React.useState(undefined);
28
-    let [ type, setType ] = React.useState(undefined);
29
-    let [ validType, setValidType ] = React.useState(false);
9
+import {  
10
+    Button, Stack, TextField, MenuItem,FormControl, InputLabel, Select,
11
+    Backdrop, CircularProgress
12
+} from '@mui/material';
30 13
 
31
-    const hiddenFileInput = React.useRef(null);
32
-    const PickFile = event => hiddenFileInput.current.click();
14
+import { Service } from '../../Utils/HTTP';
15
+import  useAuth from '../../Auth/useAuth';
33 16
 
34
-    React.useEffect(() => {
35
-        if( SUPPORTED_FORMATS.includes(type) ){
36
-            setValidType(true)
37
-        }else{
38
-            setValidType(false)
39
-        }
17
+import { departamentos } from '../Password/Rows'
40 18
 
41
-    }, [type])
19
+export default function Edit(props) {
42 20
 
43
-    return(
44
-        <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered  show={visible} onHide={onClose}>
21
+    const NewPlazaSchema = Yup.object().shape({
22
+        nombrepuesto : 
23
+        Yup.string().required('El nombre es requerido')
24
+        .min(5, "El nombre del  puesto debe ser mayor a 5 caracteres")
25
+        .max(100),
26
+        puestosuperior : Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
27
+        aredepto : Yup.number().required('Escoge alguna área'),
28
+        fecha : Yup.date("Ingresa una fecha válida"),
29
+        notas : Yup.string("Ingresa una nota válida").min(5).max(150),
30
+    })
31
+    
32
+    const [departamento, setDepartamento] = React.useState('');
33
+    const [open, setOpen] = React.useState(false);
34
+    const handleClose = () => false
35
+
36
+    const changeDepartamento = (event) => {
37
+        setDepartamento(event.target.value);
38
+    };
39
+
40
+
41
+    const [date, setDate] = React.useState(new Date());
42
+    const auth = useAuth();
43
+    const token = auth.getToken();
44
+
45
+    let {onClose, puesto : { data }, Complete, visible  } = props
46
+    
47
+    const formik = useFormik({
48
+        initialValues: {
49
+            nombrepuesto: data ? data.nombrepuesto :"",
50
+            puestosuperior:data ?data.puestosuperior :"",
51
+            aredepto: 1,
52
+            fecha: date,
53
+            notas:data? data.notas :"",
54
+        },
55
+        onSubmit: ( fields, { resetForm } ) => {
56
+            setOpen(true)
57
+            fields['fecha'] =  new Date(fields.fecha).toISOString();
58
+            fields['areadeptoplz_id'] = 1;
59
+            fields['id'] = -1;
60
+            let Rest = new Service('/plaza/edit');
61
+            Rest
62
+            .post( fields, token )
63
+            .then( _ => {
64
+                resetForm();
65
+                Complete(true,"Puesto actualizado exitosamente");
66
+                onClose();
67
+                setOpen(false)
68
+            })
69
+            .catch(err => {
70
+                console.error(err)
71
+                Complete(false,"Ocurrio un error, intentalo nuevamente");
72
+                setOpen(false)
73
+            })
74
+
75
+        },
76
+        validationSchema: NewPlazaSchema,
77
+    });
78
+
79
+    const { errors, touched, handleSubmit, getFieldProps, setValues} = formik;
80
+    
81
+    useEffect(() => {
82
+        console.log(data); 
83
+        setValues({
84
+            nombrepuesto: data.nombrepuesto,
85
+            notas:data.notas,
86
+            puestosuperior:data ?data.puestosuperior :"",
87
+            aredepto: 1,
88
+            fecha:new Date(data.create_day),
89
+        })
90
+
91
+    },[data,setValues])
92
+
93
+
94
+    return (
95
+
96
+        <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered show={visible} onHide={onClose}>
45 97
             <Modal.Header>
46
-                <button onClick={onClose} type="button" className="close" data-dismiss="modal">&times;</button>
47
-                <h4 className="modal-title">Editar plaza</h4>
98
+                <button onClick={onClose}  type="button" className="close" data-dismiss="modal">&times;</button>
99
+                <h4 className="modal-title" style={{color : '#252525'}}>Agregar plaza</h4>
48 100
             </Modal.Header>
49
-
50
-           <Modal.Body className="modal-body">
51
-                <Formik
52
-
53
-                    initialValues={{
54
-                        nombre: puesto.id +" - "+  puesto.nombre,
55
-                        description: puesto.description,
56
-                        salario: puesto.salario,
57
-                        imagen: '',
58
-                    }}
59
-
60
-                    validationSchema={NewPlazaSchema}
61
-                    onSubmit={ (values) => {
62
-                        // console.log('VALUES >> ',values)
63
-                        props.setManual(false)
64
-                    }} >
65
-
66
-
67
-                    { ({  errors, touched, validateField, validateForm, setFieldValue  }) => (
68
-                        <Form>
69
-                            <Row>
70
-
71
-                                <Col md="4">
72
-                                    <div className="img-container">
73
-                                        <img alt="agregar plaza manual" src={ validType ? file : NotFound}/>
74
-                                    </div>
75
-                                </Col>
76
-
77
-                                <Col md="8">
78
-
79
-                                    <input 
80
-                                        value={filename} 
81
-                                        type="text" 
82
-                                        className="file-upload-input" 
83
-                                        disabled="" 
84
-                                        placeholder="Ningún archivo seleccionado" readOnly
101
+            <Modal.Body className="modal-body">
102
+
103
+                <FormikProvider style={{ padding : 25 }} value={formik}>
104
+                    <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
105
+                        <Stack spacing={3}>
106
+
107
+                            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
108
+
109
+                                <TextField
110
+                                    label="Nombre"
111
+                                    fullWidth
112
+                                    {...getFieldProps('nombrepuesto')}
113
+                                    error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
114
+                                    helperText={touched.nombrepuesto && errors.nombrepuesto}
115
+                                />
116
+
117
+                                <TextField
118
+                                    label="Puesto Superior"
119
+                                    fullWidth
120
+                                    {...getFieldProps('puestosuperior')}
121
+                                    error={Boolean(touched.puestosuperior && errors.puestosuperior)}
122
+                                    helperText={touched.puestosuperior && errors.puestosuperior}
123
+                                />
124
+
125
+                            </Stack>
126
+                            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
127
+                                <FormControl fullWidth>
128
+                                    <InputLabel id="demo-simple-select-label">Departamento</InputLabel>
129
+                                    <Select
130
+                                        labelId="demo-simple-select-label"
131
+                                        value={departamento}
132
+                                        label="Departamento"
133
+                                        onChange={changeDepartamento}
134
+                                        {...getFieldProps('aredepto')}
135
+                                        error={Boolean(touched.aredepto && errors.aredepto)} >
136
+                                        {
137
+                                        departamentos.map( ( nivel, index ) => {
138
+                                            return (
139
+                                                <MenuItem key={index} value={index}>{nivel}</MenuItem>
140
+                                            )
141
+                                        })
142
+                                    }
143
+                                    </Select>
144
+                                </FormControl>
145
+
146
+
147
+                                <LocalizationProvider 
148
+                                    dateAdapter={DateFnsUtils}>
149
+                                    <DesktopDatePicker
150
+                                        label="Fecha Creación"
151
+                                        fullWidth
152
+                                        inputFormat="dd/MM/yyyy"
153
+                                        {...getFieldProps('fecha')}
154
+                                        value={date}
155
+                                        onChange={setDate}
156
+                                        renderInput={(params) => 
157
+                                            <TextField 
158
+                                                disabled={true}
159
+                                                label="Fecha Creación"
160
+                                                fullWidth
161
+                                                {...params} 
162
+                                            />}
85 163
                                     />
86
-
87
-                                    <Button className="btn_add_producto_confirm" style={{ marginLeft : 15 }} onClick={PickFile}>
88
-                                        SUBIR FOTO
89
-                                    </Button>
90
-
91
-                                    {errors.imagen && touched.imagen && <div className="error_feedback">{errors.imagen}</div>}
92
-                                    <input
93
-                                        multiple={false}
94
-                                        type="file"
95
-                                        ref={hiddenFileInput}
96
-                                        onChange={(event) => {
97
-                                            const files = event.target.files;
98
-                                            console.log('files crud ', files[0])
99
-                                            let myFiles =Array.from(files);
100
-                                            setFieldValue("imagen", myFiles);
101
-                                            setFilename(myFiles[0].name)
102
-                                            setType(myFiles[0].type)
103
-                                            const objectUrl = URL.createObjectURL(files[0])
104
-                                            setFile(objectUrl)
105
-                                        }}
106
-                                        style={{display: 'none'}}
164
+                                </LocalizationProvider>
165
+
166
+                            </Stack>
167
+
168
+                            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
169
+                                <TextField
170
+                                    id="filled-multiline-static"
171
+                                    multiline
172
+                                    rows={4}
173
+                                    defaultValue="Default Value"
174
+                                    variant="filled"
175
+                                    label="Notas"
176
+                                    fullWidth
177
+                                    type="text"
178
+                                    {...getFieldProps('notas')}
179
+                                    error={Boolean(touched.notas && errors.notas)}
180
+                                    helperText={touched.notas && errors.notas}
107 181
                                     />
108
-
109
-                                </Col>
110
-
111
-                            </Row>
112
-                            <div className="data_product">
113
-                                <Row>
114
-                                    <Col md="12">
115
-
116
-                                        {errors.nombre && touched.nombre && <div className="error_feedback">{errors.nombre}</div>}
117
-                                        <Field  name="nombre" placeholder="Nombre de la plaza"/>
118
-
119
-                                        {errors.description && touched.description && <div className="error_feedback">{errors.description}</div>}
120
-                                        <Field name="description">
121
-                                            {({ field, form, meta }) => {
122
-                                                return(
123
-                                                    <textarea id="description" name="description" value={field.value} onChange={field.onChange} placeholder="Descripción general de la plaza"></textarea>
124
-                                                )
125
-                                            }}
126
-                                        </Field>
127
-
128
-                                        {errors.salario && touched.salario && <div className="error_feedback">{errors.salario}</div>}
129
-                                        <Field name="salario" type="text" placeholder="Salario"/>
130
-
131
-
132
-                                    </Col>
133
-
134
-
135
-                                    <div className="add_producto_confirm">
136
-                                        <div className="btn_add_producto_confirm">
137
-                                            <span href="/" type="submit">Actualizar plaza</span>
138
-                                        </div>
139
-                                    </div>
140
-
141
-                                </Row>
142
-                            </div>
143
-                        </Form>
144
-                    )}
145
-
146
-
147
-
148
-
149
-                </Formik>
150
-
182
+                            </Stack>
183
+                        </Stack>
184
+
185
+
186
+                        <Modal.Footer>
187
+                            <Button
188
+                                type="submit"
189
+                                className="registerBtn" 
190
+                                variant="contained"
191
+                                sx={{ mt: 1, mr: 1 }} >
192
+                                {'Actualizar'}
193
+                            </Button>
194
+                        </Modal.Footer>
195
+
196
+                    </Form>
197
+                </FormikProvider>
151 198
             </Modal.Body>
199
+            <Backdrop
200
+                sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
201
+                open={open}
202
+                onClick={handleClose} >
203
+            <CircularProgress color="inherit" />
204
+            </Backdrop>
205
+
152 206
         </Modal>
153 207
     )
154 208
 }

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

@@ -70,7 +70,9 @@ export const niveles_educativos = [
70 70
 
71 71
 
72 72
 export const departamentos = [
73
-    "Jutiapa",
74 73
     "Guatemala",
75
-    "Santa Rosa",
74
+    "Guatemala",
75
+    "Guatemala",
76
+    "Guatemala",
77
+    "Guatemala",
76 78
 ]

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

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

+ 3 - 2
src/Pages/Login.jsx

@@ -57,17 +57,18 @@ export function Login() {
57 57
             request
58 58
             .post({})
59 59
             .then( response => {
60
-                // console.log("Service Response :: ", response)
60
+                console.log("Service Response :: ", response)
61 61
                 let { token, nombre, apelidos } = response;
62 62
                 toast.success(`Bienvenido ${nombre} ${apelidos}!!`)
63 63
                 token = token.replace("Bearer ", "")
64 64
                 let user_permissions = jwt_decode(token);
65 65
                 Object.keys(user_permissions);
66
-                console.log("Bearer ", token)
66
+                // console.log("Bearer ", token)
67 67
                 setTimeout( () => {
68 68
                     setOpen(false)
69 69
                     auth.login(token)
70 70
                 }, 2000)
71
+
71 72
             }) 
72 73
             .catch( err => {
73 74
                 setOpen(false)

+ 5 - 6
src/Pages/Puestos.jsx

@@ -27,7 +27,7 @@ import { GridMode } from '../Components/Puestos/GridMode'
27 27
 import { Add as AddIcon, } from '@mui/icons-material/'
28 28
 
29 29
 function Divide(arregloOriginal){
30
-    const LONGITUD_PEDAZOS = 7;
30
+    const LONGITUD_PEDAZOS = 9;
31 31
     let arregloDeArreglos = [];
32 32
     for (let i = 0; i < arregloOriginal.length; i += LONGITUD_PEDAZOS) {
33 33
         let pedazo = arregloOriginal.slice(i, i + LONGITUD_PEDAZOS);
@@ -38,10 +38,10 @@ function Divide(arregloOriginal){
38 38
 
39 39
 export function Puestos() {
40 40
 
41
-    const Complete =  (status) => {
41
+    const Complete =  (status, message) => {
42 42
 
43 43
         if(!status){
44
-            toast.error('Ups creo que ocurrio un error, intentalo nuevamente')
44
+            toast.error(message)
45 45
         }
46 46
 
47 47
         let rest = new Service("/plaza/getall")
@@ -63,7 +63,7 @@ export function Puestos() {
63 63
                 console.log('error fetching data  ', error );
64 64
             })
65 65
 
66
-        toast.success('Puesto agregado exitosamente')
66
+        toast.success(message)
67 67
     } 
68 68
 
69 69
     const auth = useAuth();
@@ -203,10 +203,9 @@ export function Puestos() {
203 203
             </div>
204 204
 
205 205
             <Express setExpress={setExpress} visible={expres} onClose={() => setExpress(false) } />
206
-
207 206
             <Manual Complete={Complete} visible={manual} onClose={() => setManual(false)}/>
208 207
 
209
-            <Editar   puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
208
+            <Editar  Complete={Complete} puesto={puesto} visible={edit} onClose={() => setEdit(false)} />
210 209
             <Eliminar puesto={puesto} visible={del} onClose={() => setDelete(false)} />
211 210
             <Mostrar  puesto={puesto} visible={show} onClose={() => setShow(false)} />
212 211