Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3719 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React, { useState } from 'react';
2
import { useForm } from 'react-hook-form';
3
import { useDispatch } from 'react-redux';
4
import { Button, styled, Tab, Tabs } from '@mui/material';
5
 
6
import { useFetch } from '@hooks';
7
import { getTemplate } from '@services/habits/habits';
8
import { INTELLIGENCES, WEEK_DAYS } from '@constants/habits';
9
import { addNotification } from '@store/notification/notification.actions';
10
 
11
import Row from '@components/common/Row';
12
import Form from '@components/common/form';
13
import Input from '@components/UI/inputs/Input';
14
import Widget from '@components/UI/Widget';
15
import TabPanel from '@components/common/tab-panel';
16
import Ckeditor from '@components/common/ckeditor/Ckeditor';
17
import Select from '@components/UI/inputs/Select';
18
import CheckboxInput from '@components/UI/inputs/Checkbox';
19
import LoadingWrapper from '@components/common/loading-wrapper';
20
 
21
const FormTabPanel = styled(TabPanel)(({ theme }) => ({
22
  display: 'flex',
23
  flexDirection: 'column',
24
  width: '100%',
25
  gap: theme.spacing(0.5)
26
}));
27
 
28
export default function HabitForm({
29
  onSubmit = () => {},
30
  defaultValues = {
31
    name: '',
32
    description: '',
33
    monday_active: false,
34
    tuesday_active: false,
35
    wednesday_active: false,
36
    thursday_active: false,
37
    friday_active: false,
38
    saturday_active: false,
39
    sunday_active: false,
40
    monday_time: undefined,
41
    tuesday_time: undefined,
42
    wednesday_time: undefined,
43
    thursday_time: undefined,
44
    friday_time: undefined,
45
    saturday_time: undefined,
46
    sunday_time: undefined,
47
    quantitative_value: false,
48
    qualitative_description: '',
49
    notification_10min_before: false,
50
    notification_30min_before: false,
51
    intelligence: ''
52
  },
53
  values = {}
54
}) {
55
  const { data: templates } = useFetch('/helpers/habits-and-skills', []);
56
  const [currentTemplate, setCurrentTemplate] = useState(null);
57
  const [currentTab, setCurrentTab] = useState(0);
58
  const dispatch = useDispatch();
59
 
60
  const {
61
    handleSubmit,
62
    control,
63
    formState: { errors, isSubmitting },
64
    trigger
65
  } = useForm({
66
    defaultValues,
67
    values: currentTemplate ?? values
68
  });
69
 
3747 stevensc 70
  console.log({ errors });
71
 
3719 stevensc 72
  const getHabitTemplate = async (url) => {
73
    try {
74
      const response = await getTemplate(url);
75
      setCurrentTemplate(response);
76
    } catch (error) {
77
      dispatch(addNotification({ style: 'danger', msg: error.message }));
78
    }
79
  };
80
 
81
  const handleChange = async (event, newValue) => {
82
    const valid = await trigger();
83
    if (valid) setCurrentTab(newValue);
84
  };
85
 
86
  const nextStep = async () => {
87
    const valid = await trigger();
88
    if (valid) setCurrentTab(currentTab + 1);
89
  };
90
 
91
  const formatHabit = (habit) => {
3747 stevensc 92
    console.log({ habit });
3719 stevensc 93
    const dataArray = Object.entries(habit);
94
    const formatedData = dataArray.map(([key, value]) => {
95
      if (key.includes('active')) return [key, value ? 1 : 0];
3747 stevensc 96
      if (key.includes('time')) {
97
        return value ? [key, value.padEnd(8, ':00')] : [key, '00:00:00'];
98
      }
3719 stevensc 99
      return [key, value];
100
    });
101
    return Object.fromEntries(formatedData);
102
  };
103
 
104
  const dataAdapter = (habit) => {
105
    const formatedHabit = formatHabit(habit);
106
    onSubmit(formatedHabit);
107
  };
108
 
109
  return (
110
    <Widget>
111
      <Tabs value={currentTab} onChange={handleChange}>
112
        <Tab label='Detalles' />
113
        <Tab label='Frecuencia' />
114
        <Tab label='Valor' />
115
        <Tab label='Notificaciones' />
116
      </Tabs>
117
      <Widget.Body>
118
        <Form onSubmit={handleSubmit(dataAdapter)}>
119
          <LoadingWrapper loading={isSubmitting} displayChildren>
120
            {/* Detalles */}
121
            <FormTabPanel value={0} index={currentTab}>
122
              <Select
123
                label='Plantilla:'
124
                options={templates.map((template) => ({
125
                  label: template.name,
126
                  value: template.link
127
                }))}
128
                onChange={(e) => getHabitTemplate(e.target.value)}
129
              />
130
 
131
              <Input
132
                label='Nombre del hábito o competencia:'
133
                name='name'
134
                placeholder='Escribe el nombre del hábito o competencia'
135
                control={control}
136
                rules={{ required: 'El nombre es requerido' }}
137
                error={errors.name?.message}
138
              />
139
 
140
              <Select
141
                label='Inteligencias:'
142
                name='intelligence'
143
                options={INTELLIGENCES}
144
                control={control}
145
                rules={{ required: 'Este campo es requerido' }}
146
                error={errors.intelligence?.message}
147
              />
148
 
149
              <Ckeditor
150
                control={control}
151
                name='description'
152
                error={errors.description?.message}
153
                rules={{ required: 'La descripción es requerida' }}
154
                label='Descripción:'
155
              />
156
 
157
              <Button color='primary' onClick={nextStep}>
158
                Continuar
159
              </Button>
160
            </FormTabPanel>
161
 
162
            {/* Frecuencia */}
163
            <FormTabPanel value={1} index={currentTab}>
164
              {WEEK_DAYS.map(({ label, value, time }) => {
165
                return (
166
                  <Row
167
                    key={value}
168
                    styles={{
169
                      flexFlow: 'nowrap',
170
                      justifyContent: 'space-between'
171
                    }}
172
                  >
173
                    {/* Campos de días activos */}
174
                    <CheckboxInput label={label} control={control} name={value} />
175
                    {/* Puedes repetir los campos de días activos y sus horas para cada día de la semana */}
176
                    <Input
177
                      type='time'
178
                      control={control}
179
                      name={time}
180
                      rules={{
181
                        validate: (time, formValues) => {
182
                          if (!formValues[value]) return true;
183
                          if (formValues[value] && time) return true;
184
                          return 'La hora es requerida si el día está activo';
185
                        }
186
                      }}
187
                      style={{ width: 'auto' }}
188
                      error={errors[time]?.message}
189
                    />
190
                  </Row>
191
                );
192
              })}
193
 
194
              <Button color='primary' onClick={nextStep}>
195
                Continuar
196
              </Button>
197
            </FormTabPanel>
198
 
199
            {/* Valor */}
200
            <FormTabPanel value={2} index={currentTab}>
201
              <Input
202
                control={control}
203
                label='Valor cuantitativo:'
204
                name='quantitative_value'
205
                type='number'
206
                rules={{ required: 'El valor es requerido' }}
207
                error={errors.quantitative_value?.message}
208
              />
209
 
210
              <Ckeditor
211
                control={control}
212
                name='qualitative_description'
213
                error={errors.qualitative_description?.message}
214
                rules={{ required: 'La descripción es requerida' }}
215
                label='Descripción cualitativa:'
216
              />
217
 
218
              <Button color='primary' onClick={nextStep}>
219
                Continuar
220
              </Button>
221
            </FormTabPanel>
222
 
223
            {/* Notificaciones */}
224
            <FormTabPanel value={3} index={currentTab}>
225
              <CheckboxInput
226
                label='Notificación 10 min antes'
227
                name='notification_10min_before'
228
                control={control}
229
              />
230
              <CheckboxInput
231
                label='Notificación 30 min antes'
232
                name='notification_30min_before'
233
                control={control}
234
                rules={{
235
                  validate: (value, formValues) => {
236
                    if (!value && !formValues.notification_10min_before) {
237
                      return 'Debe seleccionar al menos una opción';
238
                    }
239
                    if (value && formValues.notification_10min_before) {
240
                      return 'No se puede seleccionar ambas opciones simultáneamente';
241
                    }
242
                    return true;
243
                  }
244
                }}
245
              />
246
              <Button color='primary' type='submit' disabled={isSubmitting}>
247
                Crear
248
              </Button>
249
            </FormTabPanel>
250
          </LoadingWrapper>
251
        </Form>
252
      </Widget.Body>
253
    </Widget>
254
  );
255
}