Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3373 | Ir a la última revisión | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 3373 Rev 3697
Línea 1... Línea 1...
1
import React, { useState } from 'react'
1
import React, { useState } from 'react';
2
import { useForm } from 'react-hook-form'
2
import { useForm } from 'react-hook-form';
3
import { useDispatch } from 'react-redux'
3
import { useDispatch } from 'react-redux';
4
import { Button, styled, Tab, Tabs } from '@mui/material'
4
import { Button, styled, Tab, Tabs } from '@mui/material';
5
 
5
 
6
import { useFetch } from '@hooks'
6
import { useFetch } from '@hooks';
7
import { getTemplate } from '@services/habits/habits'
7
import { getTemplate } from '@services/habits/habits';
8
import { INTELLIGENCES, WEEK_DAYS } from '@constants/habits'
8
import { INTELLIGENCES, WEEK_DAYS } from '@constants/habits';
9
import { addNotification } from '@store/notification/notification.actions'
9
import { addNotification } from '@store/notification/notification.actions';
10
 
10
 
11
import Row from '@components/common/Row'
11
import Row from '@components/common/Row';
12
import Form from '@components/common/form'
12
import Form from '@components/common/form';
13
import Input from '@components/UI/inputs/Input'
13
import Input from '@components/UI/inputs/Input';
14
import Widget from '@components/UI/Widget'
14
import Widget from '@components/UI/Widget';
15
import TabPanel from '@components/common/tab-panel'
15
import TabPanel from '@components/common/tab-panel';
16
import Ckeditor from '@components/common/ckeditor/Ckeditor'
16
import Ckeditor from '@components/common/ckeditor/Ckeditor';
17
import Select from '@components/UI/inputs/Select'
17
import Select from '@components/UI/inputs/Select';
18
import CheckboxInput from '@components/UI/inputs/Checkbox'
18
import CheckboxInput from '@components/UI/inputs/Checkbox';
19
import LoadingWrapper from '@components/common/loading-wrapper'
19
import LoadingWrapper from '@components/common/loading-wrapper';
Línea 20... Línea 20...
20
 
20
 
21
const FormTabPanel = styled(TabPanel)(({ theme }) => ({
21
const FormTabPanel = styled(TabPanel)(({ theme }) => ({
22
  display: 'flex',
22
  display: 'flex',
23
  flexDirection: 'column',
23
  flexDirection: 'column',
24
  width: '100%',
24
  width: '100%',
25
  gap: theme.spacing(0.5)
25
  gap: theme.spacing(0.5)
Línea 26... Línea 26...
26
}))
26
}));
27
 
27
 
28
export default function HabitForm({
28
export default function HabitForm({
29
  onSubmit = () => {},
29
  onSubmit = () => {},
Línea 50... Línea 50...
50
    notification_30min_before: false,
50
    notification_30min_before: false,
51
    intelligence: ''
51
    intelligence: ''
52
  },
52
  },
53
  values = {}
53
  values = {}
54
}) {
54
}) {
55
  const { data: templates } = useFetch('/helpers/habits-and-skills', [])
55
  const { data: templates } = useFetch('/helpers/habits-and-skills', []);
56
  const [currentTemplate, setCurrentTemplate] = useState(null)
56
  const [currentTemplate, setCurrentTemplate] = useState(null);
57
  const [currentTab, setCurrentTab] = useState(0)
57
  const [currentTab, setCurrentTab] = useState(0);
58
  const dispatch = useDispatch()
58
  const dispatch = useDispatch();
Línea 59... Línea 59...
59
 
59
 
60
  const {
60
  const {
61
    handleSubmit,
61
    handleSubmit,
62
    control,
62
    control,
63
    formState: { errors, isSubmitting },
63
    formState: { errors, isSubmitting },
64
    trigger
64
    trigger
65
  } = useForm({
65
  } = useForm({
66
    defaultValues,
66
    defaultValues,
67
    values: currentTemplate ?? values
67
    values: currentTemplate ?? values
Línea 68... Línea 68...
68
  })
68
  });
69
 
69
 
70
  const getHabitTemplate = async (url) => {
70
  const getHabitTemplate = async (url) => {
71
    try {
71
    try {
72
      const response = await getTemplate(url)
72
      const response = await getTemplate(url);
73
      setCurrentTemplate(response)
73
      setCurrentTemplate(response);
74
    } catch (error) {
74
    } catch (error) {
75
      dispatch(addNotification({ style: 'danger', msg: error.message }))
75
      dispatch(addNotification({ style: 'danger', msg: error.message }));
Línea 76... Línea 76...
76
    }
76
    }
77
  }
77
  };
78
 
78
 
79
  const handleChange = async (event, newValue) => {
79
  const handleChange = async (event, newValue) => {
Línea 80... Línea 80...
80
    const valid = await trigger()
80
    const valid = await trigger();
81
    if (valid) setCurrentTab(newValue)
81
    if (valid) setCurrentTab(newValue);
82
  }
82
  };
83
 
83
 
Línea 84... Línea 84...
84
  const nextStep = async () => {
84
  const nextStep = async () => {
85
    const valid = await trigger()
85
    const valid = await trigger();
86
    if (valid) setCurrentTab(currentTab + 1)
86
    if (valid) setCurrentTab(currentTab + 1);
87
  }
87
  };
88
 
88
 
89
  const formatHabit = (habit) => {
89
  const formatHabit = (habit) => {
90
    const dataArray = Object.entries(habit)
90
    const dataArray = Object.entries(habit);
91
    const formatedData = dataArray.map(([key, value]) => {
91
    const formatedData = dataArray.map(([key, value]) => {
92
      if (key.includes('active')) return [key, value ? 1 : 0]
92
      if (key.includes('active')) return [key, value ? 1 : 0];
Línea 93... Línea 93...
93
      if (key.includes('time')) return [key, value.padEnd(8, ':00')]
93
      if (key.includes('time')) return [key, value.padEnd(8, ':00')];
94
      return [key, value]
94
      return [key, value];
95
    })
95
    });
96
    return Object.fromEntries(formatedData)
96
    return Object.fromEntries(formatedData);
Línea 97... Línea 97...
97
  }
97
  };
98
 
98
 
99
  const dataAdapter = (habit) => {
99
  const dataAdapter = (habit) => {
100
    const formatedHabit = formatHabit(habit)
100
    const formatedHabit = formatHabit(habit);
Línea 115... Línea 115...
115
            {/* Detalles */}
115
            {/* Detalles */}
116
            <FormTabPanel value={0} index={currentTab}>
116
            <FormTabPanel value={0} index={currentTab}>
117
              <Select
117
              <Select
118
                label='Plantilla:'
118
                label='Plantilla:'
119
                options={templates.map((template) => ({
119
                options={templates.map((template) => ({
120
                  name: template.name,
120
                  label: template.name,
121
                  value: template.link
121
                  value: template.link
122
                }))}
122
                }))}
123
                onChange={(e) => getHabitTemplate(e.target.value)}
123
                onChange={(e) => getHabitTemplate(e.target.value)}
124
              />
124
              />
Línea 164... Línea 164...
164
                      flexFlow: 'nowrap',
164
                      flexFlow: 'nowrap',
165
                      justifyContent: 'space-between'
165
                      justifyContent: 'space-between'
166
                    }}
166
                    }}
167
                  >
167
                  >
168
                    {/* Campos de días activos */}
168
                    {/* Campos de días activos */}
169
                    <CheckboxInput
-
 
170
                      label={label}
-
 
171
                      control={control}
169
                    <CheckboxInput label={label} control={control} name={value} />
172
                      name={value}
-
 
173
                    />
-
 
174
                    {/* Puedes repetir los campos de días activos y sus horas para cada día de la semana */}
170
                    {/* Puedes repetir los campos de días activos y sus horas para cada día de la semana */}
175
                    <Input
171
                    <Input
176
                      type='time'
172
                      type='time'
177
                      control={control}
173
                      control={control}
178
                      name={time}
174
                      name={time}
179
                      rules={{
175
                      rules={{
180
                        validate: (time, formValues) => {
176
                        validate: (time, formValues) => {
181
                          if (!formValues[value]) return true
177
                          if (!formValues[value]) return true;
182
                          if (formValues[value] && time) return true
178
                          if (formValues[value] && time) return true;
183
                          return 'La hora es requerida si el día está activo'
179
                          return 'La hora es requerida si el día está activo';
184
                        }
180
                        }
185
                      }}
181
                      }}
186
                      style={{ width: 'auto' }}
182
                      style={{ width: 'auto' }}
187
                      error={errors[time]?.message}
183
                      error={errors[time]?.message}
188
                    />
184
                    />
189
                  </Row>
185
                  </Row>
190
                )
186
                );
191
              })}
187
              })}
Línea 192... Línea 188...
192
 
188
 
193
              <Button color='primary' onClick={nextStep}>
189
              <Button color='primary' onClick={nextStep}>
194
                Continuar
190
                Continuar
Línea 231... Línea 227...
231
                name='notification_30min_before'
227
                name='notification_30min_before'
232
                control={control}
228
                control={control}
233
                rules={{
229
                rules={{
234
                  validate: (value, formValues) => {
230
                  validate: (value, formValues) => {
235
                    if (!value && !formValues.notification_10min_before) {
231
                    if (!value && !formValues.notification_10min_before) {
236
                      return 'Debe seleccionar al menos una opción'
232
                      return 'Debe seleccionar al menos una opción';
237
                    }
233
                    }
238
                    if (value && formValues.notification_10min_before) {
234
                    if (value && formValues.notification_10min_before) {
239
                      return 'No se puede seleccionar ambas opciones simultáneamente'
235
                      return 'No se puede seleccionar ambas opciones simultáneamente';
240
                    }
236
                    }
241
                    return true
237
                    return true;
242
                  }
238
                  }
243
                }}
239
                }}
244
              />
240
              />
245
              <Button color='primary' type='submit' disabled={isSubmitting}>
241
              <Button color='primary' type='submit' disabled={isSubmitting}>
246
                Crear
242
                Crear
Línea 248... Línea 244...
248
            </FormTabPanel>
244
            </FormTabPanel>
249
          </LoadingWrapper>
245
          </LoadingWrapper>
250
        </Form>
246
        </Form>
251
      </Widget.Body>
247
      </Widget.Body>
252
    </Widget>
248
    </Widget>
253
  )
249
  );
254
}
250
}