Bladeren bron

update pwd form

amenpunk 3 jaren geleden
bovenliggende
commit
2931109646
1 gewijzigde bestanden met toevoegingen van 212 en 201 verwijderingen
  1. 212 201
      src/Components/Password/Operation.jsx

+ 212 - 201
src/Components/Password/Operation.jsx

@@ -12,8 +12,9 @@ import { Col, Row } from 'react-bootstrap'
 
 import toast, { Toaster } from 'react-hot-toast';
 import * as Yup from 'yup';
-
+import { yupResolver } from '@hookform/resolvers/yup';
 import { useQueryClient } from 'react-query'
+import { useForm, Controller } from "react-hook-form";
 import { Service } from '../../Utils/HTTP.js'
 import { useSelector } from 'react-redux'
 
@@ -29,17 +30,21 @@ function Candidatos(props) {
     nombres:
       Yup.string()
         .min(2, 'Demasiado corto!')
-        .max(50, 'Demasiado largo!'),
+        .max(50, 'Demasiado largo!')
+        .required('Ingresa un nombre válido'),
     apellidos:
       Yup.string()
-        .min(2, 'Demasiado corto!').max(50, 'Demasiado Largo!'),
+        .min(2, 'Demasiado corto!')
+        .max(50, 'Demasiado Largo!')
+        .required('Ingresa un apellido válido'),
     mail:
       Yup.string()
+        .required('Ingresa un email válido')
         .email("Correo no valido")
   });
 
 
-  let { candidatos, add , remove } = props
+  let { candidatos, add, remove } = props
 
   const formik = useFormik({
     initialValues: {
@@ -48,32 +53,29 @@ function Candidatos(props) {
       mail: "",
     },
     onSubmit: () => {
-      console.log('submited')
-    },
-    validationSchema: CandidatoSchema,
-  });
 
-  var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
+      if (!values.nombres || !values.apellidos || !values.mail) {
+        return toast.error("Completa la informacion del candidato")
+      }
 
-  const addToList = () => {
+      if (!isValid) {
+        return toast.error("Completa la informacion del candidato")
+      }
 
-    if (!values.nombres || !values.apellidos || !values.mail) {
-      return toast.error("Completa la informacion del candidato")
-    }
+      let user = {
+        'nombres': values.nombres,
+        'apellidos': values.apellidos,
+        'mail': values.mail,
+      }
 
-    if (!isValid) {
-      return toast.error("Completa la informacion del candidato")
-    }
+      add(user)
+      resetForm();
 
-    let user = {
-      'nombres': values.nombres,
-      'apellidos': values.apellidos,
-      'mail': values.mail,
-    }
-    add(user)
-    resetForm();
+    },
+    validationSchema: CandidatoSchema,
+  });
 
-  }
+  var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
 
   return (
     <FormikProvider style={{ padding: 25 }} value={formik}>
@@ -84,7 +86,6 @@ function Candidatos(props) {
           <Stack style={{ paddingTop: 15 }} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
             <TextField
               label="Nombre"
-              fullWidth
               {...getFieldProps('nombres')}
               error={Boolean(touched.nombres && errors.nombres)}
               helperText={touched.nombres && errors.nombres}
@@ -92,7 +93,6 @@ function Candidatos(props) {
 
             <TextField
               label="Apellidos"
-              fullWidth
               {...getFieldProps('apellidos')}
               error={Boolean(touched.apellidos && errors.apellidos)}
               helperText={touched.apellidos && errors.apellidos}
@@ -101,7 +101,6 @@ function Candidatos(props) {
 
           <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
             <TextField
-              fullWidth
               type="email"
               label="Correo Electronico"
               {...getFieldProps('mail')}
@@ -109,7 +108,7 @@ function Candidatos(props) {
               helperText={touched.mail && errors.mail}
             />
 
-            <Button onClick={addToList}>
+            <Button type="submit">
               <AddCircle style={{ color: 'var(--main)' }} />
             </Button>
 
@@ -121,7 +120,6 @@ function Candidatos(props) {
           />
 
         </Stack>
-        <Toaster position="top-right" />
       </Form>
     </FormikProvider>
   );
@@ -134,19 +132,9 @@ export function ModalEdit(props) {
   //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
   let { pwd, plz } = password
 
-  React.useEffect(() => {
-
-    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 (
     <Dialog
       fullWidth="md"
@@ -157,20 +145,17 @@ export function ModalEdit(props) {
       aria-describedby="alert-dialog-description"
     >
       <DialogContent>
-        {
-          data ?
-            <ModalForm
-              password={data}
-              handleOpen={handleOpen}
-              token={auth.token}
-            /> : <Loading />
-        }
+        <ModalForm
+          pwdinfo={{ pwd, plz }}
+          closeModal={handleOpen}
+          token={auth.token}
+        />
       </DialogContent>
     </Dialog>
   )
 }
 
-function Loading() {
+export function Loading() {
   return (
     <CircularProgress style={{ color: 'var(--main)' }} />
   )
@@ -178,185 +163,211 @@ function Loading() {
 
 function ModalForm(props) {
 
-  let [candidatos,setCandidatos] = React.useState(null);
+  let { pwdinfo, closeModal } = props
+  const auth = useSelector((state) => state.token)
+  let [candidatos,setCandidatos] = React.useState([]);
+  let [password, setPassword] = React.useState();
+  const queryClient = useQueryClient()
+
   const pwdSchema = Yup.object().shape({
-    id: Yup.number(),
-    pwd: Yup.string().required("Escoge un nombre valido"),
-    deadpwd: Yup.date().required("Escoge una fecha valida"),
-    state: Yup.number(),
+    pwd: Yup.string(),
+    deadpwd: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
+    state: Yup.boolean(),
     dateToActived: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
   })
 
-  const queryClient = useQueryClient();
-  let { password } = props
+  const { reset, control, register, handleSubmit, formState: { errors } } = useForm({
+    resolver: yupResolver(pwdSchema),
+    defaultValues: {
+      pwd: 0,
+      deadpwd: 0,
+      state: false,
+      dateToActived: 0,
+    }
+  });
 
   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)
-  }
+    let { pwd, plz } = pwdinfo;
 
-  function addCandidato (candidato) {
-    setCandidatos([...candidatos, candidato ])
-  }
+    let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
+    rest.getQuery(auth.token)
+      .then(resp => {
 
-  const formik = useFormik({
-    initialValues: {
-      state: 1,
-      pwd: atob(password.pwd),
-      deadpwd: password.deadpwd,
-      dateToActived: password.dateToActived,
-    },
-    onSubmit: (fields) => {
-
-      let rest = new Service('/contrasenia/create');
-      let { deadpwd, dateToActived, pwd } = fields
-
-      fields['pwd'] = btoa(pwd);
-      fields['deadpwd'] = new Date(deadpwd).toISOString();
-      fields['dateToActived'] = new Date(dateToActived).toISOString();
-      fields['candidato_id'] = props.initialValues.candidato_id
-      fields['plaza_id'] = props.initialValues.plaza_id
-
-      rest.put(fields, props.token)
-        .then(result => {
-          queryClient.invalidateQueries('passwords')
-          setTimeout(() => {
-            props.handleOpen(false)
-          }, 1000)
-          toast.success("Contraseña Actualizada")
+        let json_data = resp;
+        let mapCandi = resp.data.candidatospwds.map(pwd => {
+          let { apellidos, nombre, mail } = pwd.candi
+          return { nombres: nombre, apellidos, mail }
         })
-        .catch(bad => {
-          console.log('ERROR', bad)
-          toast.error("Ocurrio un error")
+
+        json_data.data['candidatospwds'] = mapCandi;
+        let password = json_data.data
+        setPassword(password)
+        setCandidatos(password.candidatospwds)
+
+        reset({
+          pwd: password.pwd,
+          deadpwd: password.deadpwd,
+          state: parseInt( password.state ) === 1 ,
+          dateToActived: password.dateToActived,
+          // id: password.id,
+          // link: password.link,
+          // plaza_id: password.plaza_id,
         })
-    },
-    validationSchema: pwdSchema,
-  })
 
-  const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;
+      })
+      .catch(error => console.log(error))
+
+  }, [auth.token, pwdinfo, reset])
+
+
+
+  function onSubmit(fields) {
+    let rest = new Service('/contrasenia/create');
+    let { deadpwd, dateToActived, pwd, state } = fields
+
+    fields['pwd'] = pwd;
+    fields['deadpwd'] = new Date(deadpwd).toISOString();
+    fields['dateToActived'] = new Date(dateToActived).toISOString();
+    fields['link'] = 'www.psicoadmin.ditaca.org'
+    fields['state'] = state ? 1: 0
+    delete password['candidato_id'];
+    delete password['tokensecurity'];
+    delete password['candidatospwds'];
+
+    let body_req = {
+      ...password, ...fields
+    }
+
+    rest.putQuery(body_req, auth.token)
+      .then(result => {
+        console.log('result: ', result)
+        queryClient.invalidateQueries('passwords')
+        setTimeout(() => {
+          closeModal(false)
+        }, 1000)
+        toast.success("Contraseña Actualizada")
+      })
+      .catch(bad => {
+        console.log('ERROR', bad)
+        toast.error("Ocurrio un error")
+      })
+  }
+
+
+  function removeCandidato(umail) {
+    let without = candidatos.filter(user => user.mail !== umail)
+    setCandidatos(without)
+  }
+
+  function addCandidato(candidato) {
+    let temp = [...candidatos, candidato]
+    setCandidatos(temp)
+  }
 
   return (
     <Row>
-
       <Col>
-        <FormikProvider value={formik}>
-          <Form style={{ padding: 20, maxWidth: 950 }} autoComplete="off" noValidate onSubmit={handleSubmit}>
-            <Stack spacing={4}>
+        <form style={{ padding: 20, maxWidth: 950 }} onSubmit={handleSubmit(onSubmit)}>
+          <Stack spacing={4}>
+
+            <TextField
+              {...register('pwd')}
+              variant="filled"
+              disabled
+              type="text"
+              label="Contraseña Cifrada"
+            />
+
+            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
+
               <TextField
-                value={btoa(values.pwd)}
-                variant="filled"
-                disabled
-                fullWidth
+                value={ password ? atob(password.pwd ) : ""}
                 type="text"
-                label="Contraseña Cifrada"
+                disabled
               />
 
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
-
-                <TextField
-                  type="text"
-                  label="Contraseña"
-                  {...getFieldProps('pwd')}
-                  error={Boolean(touched.pwd && errors.pwd)}
-                  helperText={touched.pwd && errors.pwd}
-                />
-
-                <FormControlLabel
-                  control={
-                    <Checkbox
-                      checked={values.state === 1}
-                      onChange={(event) => {
-                        let check = event.target.checked;
-                        setValues({
-                          ...values,
-                          state: check ? 1 : 0
-                        })
-                      }}
-                    />
-                  }
-                  label="Activa"
-                />
-              </Stack>
-
-
-              <LocalizationProvider
-                dateAdapter={DateFnsUtils}>
-                <DesktopDatePicker
-                  label="Fecha de Activación"
-                  fullWidth
-                  inputFormat="dd/MM/yyyy"
-                  value={values.dateToActived}
-                  onChange={(val) => setValues({ ...values, dateToActived: val })}
-                  renderInput={(params) =>
-                    <TextField
-                      {...getFieldProps('dateToActived')}
-                      error={Boolean(touched.dateToActived && errors.dateToActived)}
-                      helperText={touched.dateToActived && errors.dateToActived}
-                      disabled={true}
-                      label="Fecha de Activación"
-                      fullWidth
-                      {...params}
-                    />}
-                />
-              </LocalizationProvider>
-
-              <LocalizationProvider
-                dateAdapter={DateFnsUtils}>
-                <DesktopDatePicker
-                  label="Fecha de Vencimiento"
-                  fullWidth
-                  inputFormat="dd/MM/yyyy"
-                  {...getFieldProps('deadpwd')}
-                  value={values.deadpwd}
-                  onChange={(val) => setValues({ ...values, deadpwd: new Date(val) })
-                  }
-                  renderInput={(params) =>
-                    <TextField
-                      error={Boolean(touched.deadpwd && errors.deadpwd)}
-                      helperText={touched.deadpwd && errors.deadpwd}
-                      disabled={true}
-                      label="Fecha de Vencimiento"
-                      fullWidth
-                      {...params}
-                    />}
-                />
-              </LocalizationProvider>
+              <FormControlLabel
+                label="Activo?"
+                control={
+                  <Controller
+                    name="state"
+                    control={control}
+                    render={({field:props}) =>
+                      <Checkbox
+                        style={{ color: 'var(--main)' }}
+                        checked={props.value}
+                        onChange={(e) => props.onChange(e.target.checked) }
+                      />
+                    }
+                  />
+                }
+              />
+            </Stack>
 
+            <LocalizationProvider dateAdapter={DateFnsUtils}>
+              <Controller
+                name="dateToActived"
+                control={control}
+                render={({ field }) =>
+                  <DesktopDatePicker
+                    {...field}
+                    label="Fecha de Activación"
+                    inputFormat="dd/MM/yyyy"
+                    fullWidth
+                    error={Boolean(errors?.dateToActived)}
+                    renderInput={(params) =>
+                      <TextField
+                        {...params}
+                        helperText={errors?.dateToActived?.message}
+                      />}
+                  />
+                }
+              >
+              </Controller>
+            </LocalizationProvider>
+
+            <LocalizationProvider dateAdapter={DateFnsUtils}>
+              <Controller
+                name="deadpwd"
+                control={control}
+                render={({ field }) =>
+                  <DesktopDatePicker
+                    {...field}
+                    label="Fecha de Vencimiento"
+                    error={Boolean(errors?.deadpwd)}
+                    inputFormat="dd/MM/yyyy"
+                    renderInput={(params) =>
+                      <TextField
+                        {...params}
+                        helperText={errors?.deadpwd?.message}
+                        label="Fecha de Vencimiento"
+                      />}
+                  />
+                }
+              >
+              </Controller>
+            </LocalizationProvider>
+
+            <DialogActions style={{ paddingTop: 25, 'justifyContent': "flex-start" }}>
+              <Button onClick={() => closeModal(false)}>
+                Cerrar
+              </Button>
+              <Button type="submit" style={{ color: 'white', background: 'var(--main)' }} >
+                Guardar
+              </Button>
+            </DialogActions>
 
-            </Stack>
-          </Form>
-          <Toaster position="bottom-right" />
-        </FormikProvider >
+          </Stack>
+        </form>
+        <Toaster position="bottom-right" />
       </Col>
       <Col>
         <Candidatos
-          add={addCandidato} 
-          remove={removeCandidato} 
-          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>
   )
 }