amenpunk преди 2 години
родител
ревизия
8e82fdff73
променени са 1 файла, в които са добавени 237 реда и са изтрити 224 реда
  1. 237 224
      src/Components/Modal/EditPlaza.js

+ 237 - 224
src/Components/Modal/EditPlaza.js

@@ -1,8 +1,7 @@
-import React, { memo, useEffect, useCallback } from 'react';
+import React, { memo, useEffect, useCallback, useRef } from 'react';
 import { Modal } from 'react-bootstrap'
-import { useForm, Controller } from "react-hook-form";
-import { yupResolver } from '@hookform/resolvers/yup';
 import * as Yup from 'yup';
+import { useFormik, Form, FormikProvider } from 'formik';
 
 
 import { TabPanel } from './TabPanel'
@@ -55,7 +54,6 @@ async function savePuestoSuperior(input, auth) {
   return { id, nombre }
 }
 
-
 const plazeSchema = Yup.object({
   id: Yup.number(),
   nombrepuesto:
@@ -72,24 +70,44 @@ const plazeSchema = Yup.object({
 
 function Edit(props) {
 
-  const {setValue, getValues, reset, control, register, handleSubmit, formState: { errors } } = useForm({
-    resolver: yupResolver(plazeSchema),
-    defaultValues: {
+  // const { resetField, setFocus, setValue, getValues, reset, control, register, handleSubmit, formState: { errors } } = useForm({
+  //   resolver: yupResolver(plazeSchema),
+  //   defaultValues: {
+  //     id: 0,
+  //     nombrepuesto: 'mingtest',
+  //     puestosuperior: 0,
+  //     fecha: '01/01/2019',
+  //     notas: 'esto es un ejemplod e una nota',
+  //     aredepto: 1,
+  //     tests: []
+  //   }
+  // });
+
+  const formik = useFormik({
+    initialValues: {
       id: 0,
-      nombrepuesto: 'mingtest',
+      nombrepuesto: "",
       puestosuperior: 0,
-      fecha: '01/01/2019',
-      notas: 'esto es un ejemplod e una nota',
       aredepto: 1,
+      fecha: '01/01/2019',
+      notas: "",
       tests: []
-    }
+    },
+    onSubmit: (fields, { resetForm }) => {
+      console.log('submit values', fields)
+      saveEditPlaza(fields)
+    },
+    validationSchema: plazeSchema,
   });
 
-  const onSubmit = data => {
+
+  const { errors, touched, handleSubmit, getFieldProps, values, setValues } = formik;
+
+  const saveEditPlaza = data => {
 
     let body = {
       ...data,
-      fecha: new Date(data.fecha).toISOString()
+      fecha: new Date(data.fecha).toISOString(),
     }
 
     puestoMutation.mutate(body, {
@@ -113,6 +131,8 @@ function Edit(props) {
   let { visible, toggle } = props
 
   const [open, setOpen] = React.useState(false);
+  const [departamento, setDepartamento] = React.useState('');
+  const puestoref = useRef(null);
   const [tab, setTab] = React.useState(0);
   const [checklist, setChecklist] = React.useState([]);
   const [openSugg, setOpenSugg] = React.useState(false);
@@ -154,34 +174,46 @@ function Edit(props) {
       // let temp = getValues();
       // temp['puestosuperior'] = id
       // temp['puestosuperior_id'] = id
-      // reset({ ...temp, puestosuperior: id })
+      // reset({ ...temp, puestosuperior: id }, { keepDefaultValues: false, })
       // setDialogValueHook(value)
-      // reset({ ...temp, puestosuperior_id: id,puestosuperior:value.title })
-      // reset()
-      setValue('puestosuperior', parseInt( id ))
-      // setFocus("notas", { shouldSelect: true })
-      // // resetField('puestosuperior',{keepError:false})
-      //
+      // setValue('puestosuperior', parseInt(id))
+      // resetField('puestosuperior')
+      // let a = puestoref.current;
+      // a.focus();
+      // console.log(a)
+      // setValue('puestosuperior', id)
+      // reset({ ...temp, puestosuperior_id: id, puestosuperior: id }, {
+      //   keepErrors: true ,
+      //   keepDirty: true,
+      //   keepIsSubmitted: true,
+      //   keepTouched: true,
+      // })
 
-      // setDialogValueHook(value)
     }
+    // setFocus("puestosuperior_id",{shouldSelect:true})
     // console.log('SETTING:', value)
+    // console.log("final", getValues())
     setDialogValueHook(value)
-    console.log("final", getValues())
 
-  }, [setValue, getValues])
+  }, [])
+
+  const changeDepartamento = (event) => {
+    setDepartamento(event.target.value);
+  };
 
   const loading = openSugg && options.length === 0;
 
   const AutoCompleteChange = (event, newValue) => {
-    let temp = getValues();
-    console.log('newValue', temp, newValue)
-    temp['puestosuperior'] = newValue?.id;
+    // let temp = getValues();
+    // console.log('newValue', temp, newValue)
+    // temp['puestosuperior'] = newValue?.id;
     // reset(temp)
     // setDialogValue(newValue);
     // return;
     //this should be change
-    setValue('puestosuperior', newValue?.id)
+    // setValue('puestosuperior', newValue?.id)
+    setValues({ ...values, puestosuperior: newValue?.id })
+
     if (typeof newValue === 'string') {
       console.log('if1')
       setTimeout(() => {
@@ -205,8 +237,7 @@ function Edit(props) {
   }
 
   const addPrueba = (check, id) => {
-    let tests = getValues("tests")
-    console.log(tests)
+    let { tests } = values
     let temp;
     if (check) {
       temp = [...tests, { id }]
@@ -214,7 +245,8 @@ function Edit(props) {
       temp = tests.filter(test => test.id !== id);
     }
     setChecklist(temp.map(test => test.id))
-    setValue('tests', temp)
+    // setValue('tests', temp)
+    setValues({ ...values, tests: temp })
   };
 
   const getCategories = async () => {
@@ -240,7 +272,7 @@ function Edit(props) {
 
   useEffect(() => {
 
-    let current_id = getValues('id')
+    let current_id = values.id; // getValues('id')
 
     if (visible == null) return;
 
@@ -257,7 +289,7 @@ function Edit(props) {
             title: puestosuperior.nombre,
             id: puestosuperior.id
           })
-          reset({
+          setValues({
             ...response.data,
             aredepto: areadeptoplz_id,
             fecha: new Date(fecha),
@@ -286,7 +318,7 @@ function Edit(props) {
       active = false;
     };
 
-  }, [visible, auth, reset, loading, dialogValue, getValues, setDialogValue])
+  }, [visible, auth, loading, dialogValue, setDialogValue,setValues,values.id])
 
   const changeTab = (_event, newValue) => setTab(newValue);
 
@@ -354,203 +386,184 @@ function Edit(props) {
           </form>
         </Dialog>
 
-
-
-
-        <form onSubmit={handleSubmit(onSubmit)}>
-          <TabPanel value={tab} index={1}>
-            <Stack spacing={1}>
-              <Box style={{ paddingTop: 5, paddingLeft: 15 }}>
-                <Divider />
-                <h4 style={{ paddingTop: 10, paddingBottom: 10 }}>Seleciona los test a realizar</h4>
-                <Divider />
-                <FormGroup>
-                  {
-                    testsCatalog ?
-                      testsCatalog.data.map(test => (
-                        <FormControlLabel
-                          label={test.nombre}
-                          key={test.id}
-                          control={
-                            <Checkbox
-                              checked={checklist.includes((test.id))}
-                              onChange={(event) => addPrueba(event.target.checked, test.id)} />}
-                        />
-                      )) : null
-                  }
-                </FormGroup>
-              </Box>
-            </Stack>
-          </TabPanel>
-
-          <TabPanel value={tab} index={0} >
-            <Stack spacing={3}>
-
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
-
-                <TextField
-                  name="nombrepuesto"
-                  label="Nombre"
-                  fullWidth
-                  helperText={errors.nombrepuesto?.message}
-                  error={Boolean(errors?.nombrepuesto)}
-                  {...register("nombrepuesto")} />
-
-
-                <FormControl fullWidth>
-                  <Controller
-                    helperText={errors.puestosuperior?.message}
-                    error={errors?.puestosuperior}
-                    name="puestosuperior"
-                    control={control}
-                    render={({ field }) =>
-                      <Autocomplete
-                        fullWidth
-                        value={dialogValue}
-                        onChange={AutoCompleteChange}
-                        open={openSugg}
-                        onOpen={() => {
-                          setOpenSugg(true);
-                        }}
-                        onClose={() => {
-                          setOpenSugg(false);
-                        }}
-                        isOptionEqualToValue={(option, value) => option.title === value.title}
-                        filterOptions={(options, params) => {
-                          const filtered = filter(options, params);
-
-                          if (params.inputValue !== '') {
-                            filtered.push({
-                              inputValue: params.inputValue,
-                              title: `Agregar "${params.inputValue}"`,
-                            });
-                          }
-
-                          return filtered;
-                        }}
-                        id="puesto_superior_autocomplete"
-                        options={options}
-                        loading={loading}
-                        getOptionLabel={(option) => {
-                          if (typeof option === 'string') {
-                            return option;
-                          }
-                          if (option.inputValue) {
-                            return option.inputValue;
-                          }
-                          return option.title;
-                        }}
-                        selectOnFocus
-                        clearOnBlur
-                        handleHomeEndKeys
-                        renderOption={(props, option) => <li key={option.id} {...props}>{option.title}</li>}
-                        freeSolo
-                        renderInput={(params) => (
-                          <TextField
-                            {...params}
-                            {...register('puestosuperior')}
-                            error={Boolean(errors.puestosuperior)}
-                            label="Puesto Superior"
-                            InputProps={{
-                              ...params.InputProps,
-                              onChange: (event) => {
-                                let title = event.target.value;
-                                console.log('titulo',title)
-                                setOptions([]);
-                                setDialogValue({
-                                  title: event.target.value,
-                                  id: '',
-                                });
-                              },
-                              endAdornment: (
-                                <React.Fragment>
-                                  {loading ? <CircularProgress color="inherit" size={20} /> : null}
-                                  {params.InputProps.endAdornment}
-                                </React.Fragment>
-                              ),
-                            }}
+        <FormikProvider style={{ paddingTop: 25 }} value={formik}>
+          <Form onSubmit={handleSubmit}>
+            <TabPanel value={tab} index={1}>
+              <Stack spacing={1}>
+                <Box style={{ paddingTop: 5, paddingLeft: 15 }}>
+                  <Divider />
+                  <h4 style={{ paddingTop: 10, paddingBottom: 10 }}>Seleciona los test a realizar</h4>
+                  <Divider />
+                  <FormGroup>
+                    {
+                      testsCatalog ?
+                        testsCatalog.data.map(test => (
+                          <FormControlLabel
+                            label={test.nombre}
+                            key={test.id}
+                            control={
+                              <Checkbox
+                                checked={checklist.includes((test.id))}
+                                onChange={(event) => addPrueba(event.target.checked, test.id)} />}
                           />
-                        )}
-
-                      />
-
+                        )) : null
                     }
-                  >
-                  </Controller>
-                </FormControl>
-
+                  </FormGroup>
+                </Box>
               </Stack>
-
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
-
-                <FormControl fullWidth>
-                  <InputLabel id="demo-simple-select-label2">Departamento</InputLabel>
-                  <Controller
-                    helperText={errors.aredepto?.message}
-                    error={Boolean(errors?.aredepto)}
-                    name="aredepto"
-                    control={control}
-                    render={({ field }) =>
-                      <Select {...field}>
-                        {
-                          categories ?
-                            categories.data.map(cate => {
-                              return (
-                                <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
-                              )
-                            })
-                            : <MenuItem value={1}>hola</MenuItem>
+            </TabPanel>
+
+            <TabPanel value={tab} index={0} >
+              <Stack spacing={3}>
+
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
+
+                  <TextField
+                    name="nombrepuesto"
+                    label="Nombre"
+                    fullWidth
+                    helperText={errors.nombrepuesto?.message}
+                    error={Boolean(errors?.nombrepuesto)}
+                    {...getFieldProps("nombrepuesto")} />
+
+
+                  <FormControl fullWidth>
+                    <Autocomplete
+                      fullWidth
+                      value={dialogValue}
+                      onChange={AutoCompleteChange}
+                      open={openSugg}
+                      onOpen={() => {
+                        setOpenSugg(true);
+                      }}
+                      onClose={() => {
+                        setOpenSugg(false);
+                      }}
+                      isOptionEqualToValue={(option, value) => option.title === value.title}
+                      filterOptions={(options, params) => {
+                        const filtered = filter(options, params);
+
+                        if (params.inputValue !== '') {
+                          filtered.push({
+                            inputValue: params.inputValue,
+                            title: `Agregar "${params.inputValue}"`,
+                          });
                         }
-                      </Select>
-                    }>
-                  </Controller>
-                </FormControl>
-
-                <LocalizationProvider dateAdapter={DateFnsUtils}>
-                  <Controller
-                    name="fecha"
-                    control={control}
-                    render={({ field }) =>
-                      <DesktopDatePicker
-                        {...field}
-                        helperText={errors.fecha?.message}
-                        error={Boolean(errors?.fecha)}
-                        label="Fecha Creación"
-                        fullWidth
-                        inputFormat="dd/MM/yyyy"
-                        renderInput={(params) => <TextField {...params} helperText={errors.fecha?.message} />} />}
-                  >
-                  </Controller>
-                </LocalizationProvider>
-              </Stack>
 
-              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
-                <TextField
-                  helperText={errors.notas?.message}
-                  error={Boolean(errors?.notas)}
-                  name="notas"
-                  multiline
-                  rows={4}
-                  label="Notas"
-                  fullWidth
-                  type="text"
-                  {...register("notas")}
-                />
+                        return filtered;
+                      }}
+                      id="puesto_superior_autocomplete"
+                      options={options}
+                      loading={loading}
+                      getOptionLabel={(option) => {
+                        if (typeof option === 'string') {
+                          return option;
+                        }
+                        if (option.inputValue) {
+                          return option.inputValue;
+                        }
+                        return option.title;
+                      }}
+                      selectOnFocus
+                      // clearOnBlur
+                      // handleHomeEndKeys
+                      renderOption={(props, option) => <li key={option.id} {...props}>{option.title}</li>}
+                      freeSolo
+                      renderInput={(params) => (
+                        <TextField
+                          {...params}
+                          {...getFieldProps('puestosuperior')}
+                          error={Boolean(errors.puestosuperior)}
+                          label="Puesto Superior"
+                          InputProps={{
+                            ...params.InputProps,
+                            onChange: (event) => {
+                              let title = event.target.value;
+                              console.log('titulo', title)
+                              setOptions([]);
+                              setDialogValue({
+                                title: title,
+                                id: '',
+                              });
+                            },
+                            endAdornment: (
+                              <React.Fragment>
+                                {loading ? <CircularProgress color="inherit" size={20} /> : null}
+                                {params.InputProps.endAdornment}
+                              </React.Fragment>
+                            ),
+                          }}
+                        />
+                      )}
+
+                    />
+                  </FormControl>
+
+                </Stack>
+
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
+
+                  <FormControl fullWidth>
+                    <InputLabel id="demo-simple-select-label2">Departamento</InputLabel>
+                    <Select
+                      value={departamento}
+                      label="Departamento"
+                      onChange={changeDepartamento}
+                      {...getFieldProps('aredepto')}
+                      error={Boolean(touched.aredepto && errors.aredepto)}>
+                      {
+                        categories ?
+                          categories.data.map(cate => {
+                            return (
+                              <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
+                            )
+                          })
+                          : <MenuItem value={1}>hola</MenuItem>
+                      }
+                    </Select>
+                  </FormControl>
+
+                  <LocalizationProvider dateAdapter={DateFnsUtils}>
+                    <DesktopDatePicker
+                      helperText={errors.fecha?.message}
+                      error={Boolean(errors?.fecha)}
+                      label="Fecha Creación"
+                      fullWidth
+                      inputFormat="dd/MM/yyyy"
+                      renderInput={(params) => <TextField {...params} helperText={errors.fecha?.message} />}
+                    />
+                  </LocalizationProvider>
+                </Stack>
+
+                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
+                  <TextField
+                    helperText={errors.notas?.message}
+                    error={Boolean(errors?.notas)}
+                    name="notas"
+                    multiline
+                    rows={4}
+                    label="Notas"
+                    fullWidth
+                    type="text"
+                    {...getFieldProps("notas")}
+                  />
+                </Stack>
               </Stack>
-            </Stack>
-          </TabPanel>
-
-          <Modal.Footer>
-            <Button
-              type="submit"
-              className="registerBtn"
-              variant="contained"
-              sx={{ mt: 1, mr: 1 }} >
-              {'Actualizar'}
-            </Button>
-          </Modal.Footer>
-
-        </form>
+            </TabPanel>
+
+            <Modal.Footer>
+              <Button
+                ref={puestoref}
+                type="submit"
+                className="registerBtn"
+                variant="contained"
+                sx={{ mt: 1, mr: 1 }} >
+                {'Actualizar'}
+              </Button>
+            </Modal.Footer>
+
+          </Form>
+        </FormikProvider>
 
       </Modal.Body>
       <Backdrop