Browse Source

update pwd form

amenpunk 2 years ago
parent
commit
2931109646
1 changed files with 212 additions and 201 deletions
  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'
12 12
 
13 13
 import toast, { Toaster } from 'react-hot-toast';
14 14
 import * as Yup from 'yup';
15
-
15
+import { yupResolver } from '@hookform/resolvers/yup';
16 16
 import { useQueryClient } from 'react-query'
17
+import { useForm, Controller } from "react-hook-form";
17 18
 import { Service } from '../../Utils/HTTP.js'
18 19
 import { useSelector } from 'react-redux'
19 20
 
@@ -29,17 +30,21 @@ function Candidatos(props) {
29 30
     nombres:
30 31
       Yup.string()
31 32
         .min(2, 'Demasiado corto!')
32
-        .max(50, 'Demasiado largo!'),
33
+        .max(50, 'Demasiado largo!')
34
+        .required('Ingresa un nombre válido'),
33 35
     apellidos:
34 36
       Yup.string()
35
-        .min(2, 'Demasiado corto!').max(50, 'Demasiado Largo!'),
37
+        .min(2, 'Demasiado corto!')
38
+        .max(50, 'Demasiado Largo!')
39
+        .required('Ingresa un apellido válido'),
36 40
     mail:
37 41
       Yup.string()
42
+        .required('Ingresa un email válido')
38 43
         .email("Correo no valido")
39 44
   });
40 45
 
41 46
 
42
-  let { candidatos, add , remove } = props
47
+  let { candidatos, add, remove } = props
43 48
 
44 49
   const formik = useFormik({
45 50
     initialValues: {
@@ -48,32 +53,29 @@ function Candidatos(props) {
48 53
       mail: "",
49 54
     },
50 55
     onSubmit: () => {
51
-      console.log('submited')
52
-    },
53
-    validationSchema: CandidatoSchema,
54
-  });
55 56
 
56
-  var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
57
+      if (!values.nombres || !values.apellidos || !values.mail) {
58
+        return toast.error("Completa la informacion del candidato")
59
+      }
57 60
 
58
-  const addToList = () => {
61
+      if (!isValid) {
62
+        return toast.error("Completa la informacion del candidato")
63
+      }
59 64
 
60
-    if (!values.nombres || !values.apellidos || !values.mail) {
61
-      return toast.error("Completa la informacion del candidato")
62
-    }
65
+      let user = {
66
+        'nombres': values.nombres,
67
+        'apellidos': values.apellidos,
68
+        'mail': values.mail,
69
+      }
63 70
 
64
-    if (!isValid) {
65
-      return toast.error("Completa la informacion del candidato")
66
-    }
71
+      add(user)
72
+      resetForm();
67 73
 
68
-    let user = {
69
-      'nombres': values.nombres,
70
-      'apellidos': values.apellidos,
71
-      'mail': values.mail,
72
-    }
73
-    add(user)
74
-    resetForm();
74
+    },
75
+    validationSchema: CandidatoSchema,
76
+  });
75 77
 
76
-  }
78
+  var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
77 79
 
78 80
   return (
79 81
     <FormikProvider style={{ padding: 25 }} value={formik}>
@@ -84,7 +86,6 @@ function Candidatos(props) {
84 86
           <Stack style={{ paddingTop: 15 }} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
85 87
             <TextField
86 88
               label="Nombre"
87
-              fullWidth
88 89
               {...getFieldProps('nombres')}
89 90
               error={Boolean(touched.nombres && errors.nombres)}
90 91
               helperText={touched.nombres && errors.nombres}
@@ -92,7 +93,6 @@ function Candidatos(props) {
92 93
 
93 94
             <TextField
94 95
               label="Apellidos"
95
-              fullWidth
96 96
               {...getFieldProps('apellidos')}
97 97
               error={Boolean(touched.apellidos && errors.apellidos)}
98 98
               helperText={touched.apellidos && errors.apellidos}
@@ -101,7 +101,6 @@ function Candidatos(props) {
101 101
 
102 102
           <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
103 103
             <TextField
104
-              fullWidth
105 104
               type="email"
106 105
               label="Correo Electronico"
107 106
               {...getFieldProps('mail')}
@@ -109,7 +108,7 @@ function Candidatos(props) {
109 108
               helperText={touched.mail && errors.mail}
110 109
             />
111 110
 
112
-            <Button onClick={addToList}>
111
+            <Button type="submit">
113 112
               <AddCircle style={{ color: 'var(--main)' }} />
114 113
             </Button>
115 114
 
@@ -121,7 +120,6 @@ function Candidatos(props) {
121 120
           />
122 121
 
123 122
         </Stack>
124
-        <Toaster position="top-right" />
125 123
       </Form>
126 124
     </FormikProvider>
127 125
   );
@@ -134,19 +132,9 @@ export function ModalEdit(props) {
134 132
   //enviar por props las utilizades de edicion y eliminar
135 133
 
136 134
   const auth = useSelector((state) => state.token)
137
-  let [data, setData] = React.useState(null)
138 135
   let { password, open, handleOpen } = props
139 136
   let { pwd, plz } = password
140 137
 
141
-  React.useEffect(() => {
142
-
143
-    let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
144
-    rest.getQuery(auth.token)
145
-      .then(resp => setData(resp.data))
146
-      .catch(error => console.log(error))
147
-
148
-  }, [auth.token, pwd, plz])
149
-
150 138
   return (
151 139
     <Dialog
152 140
       fullWidth="md"
@@ -157,20 +145,17 @@ export function ModalEdit(props) {
157 145
       aria-describedby="alert-dialog-description"
158 146
     >
159 147
       <DialogContent>
160
-        {
161
-          data ?
162
-            <ModalForm
163
-              password={data}
164
-              handleOpen={handleOpen}
165
-              token={auth.token}
166
-            /> : <Loading />
167
-        }
148
+        <ModalForm
149
+          pwdinfo={{ pwd, plz }}
150
+          closeModal={handleOpen}
151
+          token={auth.token}
152
+        />
168 153
       </DialogContent>
169 154
     </Dialog>
170 155
   )
171 156
 }
172 157
 
173
-function Loading() {
158
+export function Loading() {
174 159
   return (
175 160
     <CircularProgress style={{ color: 'var(--main)' }} />
176 161
   )
@@ -178,185 +163,211 @@ function Loading() {
178 163
 
179 164
 function ModalForm(props) {
180 165
 
181
-  let [candidatos,setCandidatos] = React.useState(null);
166
+  let { pwdinfo, closeModal } = props
167
+  const auth = useSelector((state) => state.token)
168
+  let [candidatos,setCandidatos] = React.useState([]);
169
+  let [password, setPassword] = React.useState();
170
+  const queryClient = useQueryClient()
171
+
182 172
   const pwdSchema = Yup.object().shape({
183
-    id: Yup.number(),
184
-    pwd: Yup.string().required("Escoge un nombre valido"),
185
-    deadpwd: Yup.date().required("Escoge una fecha valida"),
186
-    state: Yup.number(),
173
+    pwd: Yup.string(),
174
+    deadpwd: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
175
+    state: Yup.boolean(),
187 176
     dateToActived: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
188 177
   })
189 178
 
190
-  const queryClient = useQueryClient();
191
-  let { password } = props
179
+  const { reset, control, register, handleSubmit, formState: { errors } } = useForm({
180
+    resolver: yupResolver(pwdSchema),
181
+    defaultValues: {
182
+      pwd: 0,
183
+      deadpwd: 0,
184
+      state: false,
185
+      dateToActived: 0,
186
+    }
187
+  });
192 188
 
193 189
   React.useEffect(() => {
194
-    let mapCandi = password.candidatospwds.map(pwd => {
195
-      let { apellidos, nombre, mail } = pwd.candi
196
-      return { nombres: nombre, apellidos, mail }
197
-    })
198
-    setCandidatos(mapCandi)
199
-  },[password.candidatospwds])
200
-
201
-  function removeCandidato (umail) {
202
-    console.log('remove:', umail)
203
-    let without = candidatos.filter( user => user.mail !== umail )
204
-    setCandidatos(without)
205
-  }
190
+    let { pwd, plz } = pwdinfo;
206 191
 
207
-  function addCandidato (candidato) {
208
-    setCandidatos([...candidatos, candidato ])
209
-  }
192
+    let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
193
+    rest.getQuery(auth.token)
194
+      .then(resp => {
210 195
 
211
-  const formik = useFormik({
212
-    initialValues: {
213
-      state: 1,
214
-      pwd: atob(password.pwd),
215
-      deadpwd: password.deadpwd,
216
-      dateToActived: password.dateToActived,
217
-    },
218
-    onSubmit: (fields) => {
219
-
220
-      let rest = new Service('/contrasenia/create');
221
-      let { deadpwd, dateToActived, pwd } = fields
222
-
223
-      fields['pwd'] = btoa(pwd);
224
-      fields['deadpwd'] = new Date(deadpwd).toISOString();
225
-      fields['dateToActived'] = new Date(dateToActived).toISOString();
226
-      fields['candidato_id'] = props.initialValues.candidato_id
227
-      fields['plaza_id'] = props.initialValues.plaza_id
228
-
229
-      rest.put(fields, props.token)
230
-        .then(result => {
231
-          queryClient.invalidateQueries('passwords')
232
-          setTimeout(() => {
233
-            props.handleOpen(false)
234
-          }, 1000)
235
-          toast.success("Contraseña Actualizada")
196
+        let json_data = resp;
197
+        let mapCandi = resp.data.candidatospwds.map(pwd => {
198
+          let { apellidos, nombre, mail } = pwd.candi
199
+          return { nombres: nombre, apellidos, mail }
236 200
         })
237
-        .catch(bad => {
238
-          console.log('ERROR', bad)
239
-          toast.error("Ocurrio un error")
201
+
202
+        json_data.data['candidatospwds'] = mapCandi;
203
+        let password = json_data.data
204
+        setPassword(password)
205
+        setCandidatos(password.candidatospwds)
206
+
207
+        reset({
208
+          pwd: password.pwd,
209
+          deadpwd: password.deadpwd,
210
+          state: parseInt( password.state ) === 1 ,
211
+          dateToActived: password.dateToActived,
212
+          // id: password.id,
213
+          // link: password.link,
214
+          // plaza_id: password.plaza_id,
240 215
         })
241
-    },
242
-    validationSchema: pwdSchema,
243
-  })
244 216
 
245
-  const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;
217
+      })
218
+      .catch(error => console.log(error))
219
+
220
+  }, [auth.token, pwdinfo, reset])
221
+
222
+
223
+
224
+  function onSubmit(fields) {
225
+    let rest = new Service('/contrasenia/create');
226
+    let { deadpwd, dateToActived, pwd, state } = fields
227
+
228
+    fields['pwd'] = pwd;
229
+    fields['deadpwd'] = new Date(deadpwd).toISOString();
230
+    fields['dateToActived'] = new Date(dateToActived).toISOString();
231
+    fields['link'] = 'www.psicoadmin.ditaca.org'
232
+    fields['state'] = state ? 1: 0
233
+    delete password['candidato_id'];
234
+    delete password['tokensecurity'];
235
+    delete password['candidatospwds'];
236
+
237
+    let body_req = {
238
+      ...password, ...fields
239
+    }
240
+
241
+    rest.putQuery(body_req, auth.token)
242
+      .then(result => {
243
+        console.log('result: ', result)
244
+        queryClient.invalidateQueries('passwords')
245
+        setTimeout(() => {
246
+          closeModal(false)
247
+        }, 1000)
248
+        toast.success("Contraseña Actualizada")
249
+      })
250
+      .catch(bad => {
251
+        console.log('ERROR', bad)
252
+        toast.error("Ocurrio un error")
253
+      })
254
+  }
255
+
256
+
257
+  function removeCandidato(umail) {
258
+    let without = candidatos.filter(user => user.mail !== umail)
259
+    setCandidatos(without)
260
+  }
261
+
262
+  function addCandidato(candidato) {
263
+    let temp = [...candidatos, candidato]
264
+    setCandidatos(temp)
265
+  }
246 266
 
247 267
   return (
248 268
     <Row>
249
-
250 269
       <Col>
251
-        <FormikProvider value={formik}>
252
-          <Form style={{ padding: 20, maxWidth: 950 }} autoComplete="off" noValidate onSubmit={handleSubmit}>
253
-            <Stack spacing={4}>
270
+        <form style={{ padding: 20, maxWidth: 950 }} onSubmit={handleSubmit(onSubmit)}>
271
+          <Stack spacing={4}>
272
+
273
+            <TextField
274
+              {...register('pwd')}
275
+              variant="filled"
276
+              disabled
277
+              type="text"
278
+              label="Contraseña Cifrada"
279
+            />
280
+
281
+            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
282
+
254 283
               <TextField
255
-                value={btoa(values.pwd)}
256
-                variant="filled"
257
-                disabled
258
-                fullWidth
284
+                value={ password ? atob(password.pwd ) : ""}
259 285
                 type="text"
260
-                label="Contraseña Cifrada"
286
+                disabled
261 287
               />
262 288
 
263
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
264
-
265
-                <TextField
266
-                  type="text"
267
-                  label="Contraseña"
268
-                  {...getFieldProps('pwd')}
269
-                  error={Boolean(touched.pwd && errors.pwd)}
270
-                  helperText={touched.pwd && errors.pwd}
271
-                />
272
-
273
-                <FormControlLabel
274
-                  control={
275
-                    <Checkbox
276
-                      checked={values.state === 1}
277
-                      onChange={(event) => {
278
-                        let check = event.target.checked;
279
-                        setValues({
280
-                          ...values,
281
-                          state: check ? 1 : 0
282
-                        })
283
-                      }}
284
-                    />
285
-                  }
286
-                  label="Activa"
287
-                />
288
-              </Stack>
289
-
290
-
291
-              <LocalizationProvider
292
-                dateAdapter={DateFnsUtils}>
293
-                <DesktopDatePicker
294
-                  label="Fecha de Activación"
295
-                  fullWidth
296
-                  inputFormat="dd/MM/yyyy"
297
-                  value={values.dateToActived}
298
-                  onChange={(val) => setValues({ ...values, dateToActived: val })}
299
-                  renderInput={(params) =>
300
-                    <TextField
301
-                      {...getFieldProps('dateToActived')}
302
-                      error={Boolean(touched.dateToActived && errors.dateToActived)}
303
-                      helperText={touched.dateToActived && errors.dateToActived}
304
-                      disabled={true}
305
-                      label="Fecha de Activación"
306
-                      fullWidth
307
-                      {...params}
308
-                    />}
309
-                />
310
-              </LocalizationProvider>
311
-
312
-              <LocalizationProvider
313
-                dateAdapter={DateFnsUtils}>
314
-                <DesktopDatePicker
315
-                  label="Fecha de Vencimiento"
316
-                  fullWidth
317
-                  inputFormat="dd/MM/yyyy"
318
-                  {...getFieldProps('deadpwd')}
319
-                  value={values.deadpwd}
320
-                  onChange={(val) => setValues({ ...values, deadpwd: new Date(val) })
321
-                  }
322
-                  renderInput={(params) =>
323
-                    <TextField
324
-                      error={Boolean(touched.deadpwd && errors.deadpwd)}
325
-                      helperText={touched.deadpwd && errors.deadpwd}
326
-                      disabled={true}
327
-                      label="Fecha de Vencimiento"
328
-                      fullWidth
329
-                      {...params}
330
-                    />}
331
-                />
332
-              </LocalizationProvider>
289
+              <FormControlLabel
290
+                label="Activo?"
291
+                control={
292
+                  <Controller
293
+                    name="state"
294
+                    control={control}
295
+                    render={({field:props}) =>
296
+                      <Checkbox
297
+                        style={{ color: 'var(--main)' }}
298
+                        checked={props.value}
299
+                        onChange={(e) => props.onChange(e.target.checked) }
300
+                      />
301
+                    }
302
+                  />
303
+                }
304
+              />
305
+            </Stack>
333 306
 
307
+            <LocalizationProvider dateAdapter={DateFnsUtils}>
308
+              <Controller
309
+                name="dateToActived"
310
+                control={control}
311
+                render={({ field }) =>
312
+                  <DesktopDatePicker
313
+                    {...field}
314
+                    label="Fecha de Activación"
315
+                    inputFormat="dd/MM/yyyy"
316
+                    fullWidth
317
+                    error={Boolean(errors?.dateToActived)}
318
+                    renderInput={(params) =>
319
+                      <TextField
320
+                        {...params}
321
+                        helperText={errors?.dateToActived?.message}
322
+                      />}
323
+                  />
324
+                }
325
+              >
326
+              </Controller>
327
+            </LocalizationProvider>
328
+
329
+            <LocalizationProvider dateAdapter={DateFnsUtils}>
330
+              <Controller
331
+                name="deadpwd"
332
+                control={control}
333
+                render={({ field }) =>
334
+                  <DesktopDatePicker
335
+                    {...field}
336
+                    label="Fecha de Vencimiento"
337
+                    error={Boolean(errors?.deadpwd)}
338
+                    inputFormat="dd/MM/yyyy"
339
+                    renderInput={(params) =>
340
+                      <TextField
341
+                        {...params}
342
+                        helperText={errors?.deadpwd?.message}
343
+                        label="Fecha de Vencimiento"
344
+                      />}
345
+                  />
346
+                }
347
+              >
348
+              </Controller>
349
+            </LocalizationProvider>
350
+
351
+            <DialogActions style={{ paddingTop: 25, 'justifyContent': "flex-start" }}>
352
+              <Button onClick={() => closeModal(false)}>
353
+                Cerrar
354
+              </Button>
355
+              <Button type="submit" style={{ color: 'white', background: 'var(--main)' }} >
356
+                Guardar
357
+              </Button>
358
+            </DialogActions>
334 359
 
335
-            </Stack>
336
-          </Form>
337
-          <Toaster position="bottom-right" />
338
-        </FormikProvider >
360
+          </Stack>
361
+        </form>
362
+        <Toaster position="bottom-right" />
339 363
       </Col>
340 364
       <Col>
341 365
         <Candidatos
342
-          add={addCandidato} 
343
-          remove={removeCandidato} 
344
-          candidatos={candidatos} 
366
+          add={addCandidato}
367
+          remove={removeCandidato}
368
+          candidatos={candidatos}
345 369
         />
346 370
       </Col>
347
-
348
-      <DialogActions>
349
-        <Button onClick={() => props.handleOpen(false)}>
350
-          Cerrar
351
-        </Button>
352
-        <Button
353
-          type="submit"
354
-          className="registerBtn"
355
-          style={{ color: 'white' }}
356
-        >
357
-          Guardar
358
-        </Button>
359
-      </DialogActions>
360 371
     </Row>
361 372
   )
362 373
 }