Sfoglia il codice sorgente

add and remove user candilist

amenpunk 3 anni fa
parent
commit
c29b698948
1 ha cambiato i file con 60 aggiunte e 71 eliminazioni
  1. 60 71
      src/Components/Password/Operation.jsx

+ 60 - 71
src/Components/Password/Operation.jsx

@@ -1,8 +1,8 @@
 import * as React from 'react';
 import {
   Button, Dialog, DialogActions, DialogContent,
-  FormControlLabel, Checkbox, Box, Stack,
-  TextField,CircularProgress
+  FormControlLabel, Checkbox, Stack,
+  TextField, CircularProgress, Divider, Typography
 } from '@mui/material'
 
 import { AddCircle } from '@mui/icons-material/';
@@ -23,7 +23,7 @@ import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker';
 import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
 
 
-function Candidatos(props){
+function Candidatos(props) {
 
   const CandidatoSchema = Yup.object().shape({
     nombres:
@@ -38,10 +38,8 @@ function Candidatos(props){
         .email("Correo no valido")
   });
 
-  let [password, setPassword] = React.useState([]);
 
-  let { candidatos } = props
-  console.log('operation props candidatos', candidatos)
+  let { candidatos, add , remove } = props
 
   const formik = useFormik({
     initialValues: {
@@ -50,24 +48,20 @@ function Candidatos(props){
       mail: "",
     },
     onSubmit: () => {
-      if(password.length <= 0){
-        toast.error("Seleciona almenos un destino")
-        return;
-      }
       console.log('submited')
     },
     validationSchema: CandidatoSchema,
   });
 
-  const { errors, touched, handleSubmit, getFieldProps, values, resetForm,isValid } = formik;
+  var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
 
   const addToList = () => {
 
-    if(!values.nombres || !values.apellidos || !values.mail){
+    if (!values.nombres || !values.apellidos || !values.mail) {
       return toast.error("Completa la informacion del candidato")
     }
 
-    if(!isValid) {
+    if (!isValid) {
       return toast.error("Completa la informacion del candidato")
     }
 
@@ -76,23 +70,18 @@ function Candidatos(props){
       'apellidos': values.apellidos,
       'mail': values.mail,
     }
-    let new_users = [...password.candidatos, user ]
-
-    setPassword({...candidatos, candidatos: new_users })
+    add(user)
     resetForm();
 
   }
 
-  const removeFromList = (umail) => {
-    let without = password.candidatos.filter( user => user.mail !== umail )
-    setPassword({...password, candidatos: without })
-  }
-
   return (
     <FormikProvider style={{ padding: 25 }} value={formik}>
+      <Typography style={{ padding: 5, marginBottom: 15 }}>Ingresa la informacion del candidato</Typography>
+      <Divider />
       <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
         <Stack spacing={3}>
-          <Stack style={{paddingTop: 15}} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
+          <Stack style={{ paddingTop: 15 }} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
             <TextField
               label="Nombre"
               fullWidth
@@ -121,35 +110,15 @@ function Candidatos(props){
             />
 
             <Button onClick={addToList}>
-              <AddCircle style={{color:'var(--main)'}}/>
+              <AddCircle style={{ color: 'var(--main)' }} />
             </Button>
 
           </Stack>
 
-          <MailTable 
-            remove={removeFromList} 
+          <MailTable
+            remove={remove}
             users={candidatos}
-            />
-
-          <Box sx={{ mb: 2 }}>
-            <div style={{ paddingTop: 15 }}>
-              <Button
-                type="submit"
-                className="registerBtn"
-                variant="contained"
-                sx={{ mt: 1, mr: 1 }}
-              >
-                {'Siguiente'}
-              </Button>
-              <Button
-                disabled={false}
-                onClick={() => console.log('regresar')}
-                sx={{ mt: 1, mr: 1 }}
-              >
-                Regresar
-              </Button>
-            </div>
-          </Box>
+          />
 
         </Stack>
         <Toaster position="top-right" />
@@ -160,6 +129,10 @@ function Candidatos(props){
 
 export function ModalEdit(props) {
 
+  //TODO:
+  //se debe crear un objeto de estado que almacena los nuevos cambios de la password
+  //enviar por props las utilizades de edicion y eliminar
+
   const auth = useSelector((state) => state.token)
   let [data, setData] = React.useState(null)
   let { password, open, handleOpen } = props
@@ -167,14 +140,11 @@ export function ModalEdit(props) {
 
   React.useEffect(() => {
 
-    const getPassword = async () => {
-      let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
-      return await rest.getQuery(auth.token)
-    }
-
-    getPassword()
+    let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
+    rest.getQuery(auth.token)
       .then(resp => setData(resp.data))
       .catch(error => console.log(error))
+
   }, [auth.token, pwd, plz])
 
   return (
@@ -208,6 +178,7 @@ function Loading() {
 
 function ModalForm(props) {
 
+  let [candidatos,setCandidatos] = React.useState(null);
   const pwdSchema = Yup.object().shape({
     id: Yup.number(),
     pwd: Yup.string().required("Escoge un nombre valido"),
@@ -218,12 +189,24 @@ function ModalForm(props) {
 
   const queryClient = useQueryClient();
   let { password } = props
-  console.log("227 PWD: ", password)
 
-  let candidatos = password.candidatospwds.map( pwd => {
-    let { apellidos, nombre,mail} = pwd.candi
-    return { nombres: nombre, apellidos, mail }
-  })
+  React.useEffect(() => {
+    let mapCandi = password.candidatospwds.map(pwd => {
+      let { apellidos, nombre, mail } = pwd.candi
+      return { nombres: nombre, apellidos, mail }
+    })
+    setCandidatos(mapCandi)
+  },[password.candidatospwds])
+
+  function removeCandidato (umail) {
+    console.log('remove:', umail)
+    let without = candidatos.filter( user => user.mail !== umail )
+    setCandidatos(without)
+  }
+
+  function addCandidato (candidato) {
+    setCandidatos([...candidatos, candidato ])
+  }
 
   const formik = useFormik({
     initialValues: {
@@ -246,7 +229,6 @@ function ModalForm(props) {
       rest.put(fields, props.token)
         .then(result => {
           queryClient.invalidateQueries('passwords')
-          console.log(result)
           setTimeout(() => {
             props.handleOpen(false)
           }, 1000)
@@ -264,6 +246,7 @@ function ModalForm(props) {
 
   return (
     <Row>
+
       <Col>
         <FormikProvider value={formik}>
           <Form style={{ padding: 20, maxWidth: 950 }} autoComplete="off" noValidate onSubmit={handleSubmit}>
@@ -347,18 +330,7 @@ function ModalForm(props) {
                     />}
                 />
               </LocalizationProvider>
-              <DialogActions>
-                <Button onClick={() => props.handleOpen(false)}>
-                  Cerrar
-                </Button>
-                <Button
-                  type="submit"
-                  className="registerBtn"
-                  style={{ color: 'white' }}
-                >
-                  Guardar
-                </Button>
-              </DialogActions>
+
 
             </Stack>
           </Form>
@@ -366,8 +338,25 @@ function ModalForm(props) {
         </FormikProvider >
       </Col>
       <Col>
-        <Candidatos candidatos={candidatos} />
+        <Candidatos
+          add={addCandidato} 
+          remove={removeCandidato} 
+          candidatos={candidatos} 
+        />
       </Col>
+
+      <DialogActions>
+        <Button onClick={() => props.handleOpen(false)}>
+          Cerrar
+        </Button>
+        <Button
+          type="submit"
+          className="registerBtn"
+          style={{ color: 'white' }}
+        >
+          Guardar
+        </Button>
+      </DialogActions>
     </Row>
   )
 }