Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3304 | Rev 3306 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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