Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React, { useEffect, useState } from 'react';
2
import { useDispatch, useSelector } from 'react-redux';
3
import { useForm } from 'react-hook-form';
4
 
5
import { axios } from '@utils';
6
import { addNotification } from '@store/notification/notification.actions';
7
 
8
import Modal from '@components/UI/modal/Modal';
9
import Input from '@components/UI/inputs/Input';
10
import Ckeditor from '@components/common/ckeditor/Ckeditor';
11
import TagsInput from '@components/UI/TagsInput';
12
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback';
13
 
14
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
15
  const [questionsCategories, setQuestionsCategories] = useState([]);
16
  const [currentCategories, setCurrentCategories] = useState([]);
17
  const labels = useSelector(({ intl }) => intl.labels);
18
  const dispatch = useDispatch();
19
 
20
  const {
21
    register,
22
    control,
23
    handleSubmit,
24
    setValue,
25
    formState: { errors }
26
  } = useForm();
27
 
28
  const onSubmit = handleSubmit(({ category_id, ...data }) => {
29
    const formData = new FormData();
30
 
31
    category_id.map((value) => formData.append('category_id[]', value));
32
    Object.entries(data).map(([key, value]) => formData.append(key, value));
33
 
34
    axios.post(url, formData).then((response) => {
35
      const { data, success } = response.data;
36
 
37
      if (!success) {
38
        const errorMessage =
39
          typeof data === 'string'
40
            ? data
41
            : 'Error interno. Por favor, inténtelo de nuevo más tarde.';
42
 
43
        dispatch(addNotification({ style: 'danger', msg: errorMessage }));
44
        return;
45
      }
46
 
47
      onComplete();
48
      onClose();
49
    });
50
  });
51
 
52
  const getCategories = () => {
53
    axios
54
      .get('/my-coach')
55
      .then((response) => {
56
        const { data, success } = response.data;
57
 
58
        if (!success) {
59
          const errorMessage =
60
            typeof data === 'string'
61
              ? data
62
              : 'Error interno. Por favor, inténtelo de nuevo más tarde.';
63
 
64
          dispatch(addNotification({ style: 'danger', msg: errorMessage }));
65
          return;
66
        }
67
 
68
        const categories = Object.entries(data.categories).map((values) => ({
69
          label: values[1],
70
          value: values[0]
71
        }));
72
 
73
        setQuestionsCategories(categories);
74
      })
75
      .catch((err) => {
76
        dispatch(addNotification({ style: 'danger', msg: err.message }));
77
      });
78
  };
79
 
80
  const onTagsChange = (tags) => {
81
    const categories = tags.map((tag) => tag.value);
82
    setValue('category_id', categories);
83
  };
84
 
85
  useEffect(() => {
86
    getCategories();
87
 
88
    register('description', { required: 'Este campo es requerido.' });
89
    register('category_id', {
90
      required: 'Este campo es requerido.',
91
      validate: (val) => val.length > 0 || 'Por favor, seleccione una categoria.'
92
    });
93
  }, []);
94
 
95
  useEffect(() => {
96
    if (!url || !show || !isEdit || !questionsCategories.length) return;
97
 
98
    axios.get(url).then((response) => {
99
      const { data, success } = response.data;
100
 
101
      if (!success) {
102
        const errorMessage =
103
          typeof data === 'string'
104
            ? data
105
            : 'Error interno. Por favor, inténtelo de nuevo más tarde.';
106
 
107
        dispatch(
108
          addNotification({
109
            style: 'danger',
110
            msg: errorMessage
111
          })
112
        );
113
        return;
114
      }
115
 
116
      const categories = data.category_id.map((uuid) =>
117
        questionsCategories.find((c) => c.value === uuid)
118
      );
119
 
120
      setCurrentCategories(categories);
121
 
122
      setValue('title', data.title);
123
      setValue('description', data.description);
124
    });
125
  }, [url, show, isEdit, questionsCategories]);
126
 
127
  useEffect(() => {
128
    if (!show) {
129
      setCurrentCategories([]);
130
      setValue('category_id', []);
131
      setValue('description', '');
132
      setValue('title', '');
133
    }
134
  }, [show]);
135
 
136
  return (
137
    <Modal
138
      title={`${isEdit ? labels.edit : labels.add} ${labels.question}`}
139
      show={show}
140
      onClose={onClose}
141
      onAccept={onSubmit}
142
    >
143
      <Input
144
        name='title'
145
        control={control}
146
        rules={{ required: labels.error_field_empty }}
147
        error={errors.title?.message}
148
      />
149
 
150
      <TagsInput
151
        label='Categorías'
152
        name='category_id'
153
        onChange={onTagsChange}
154
        suggestions={questionsCategories}
155
        defaultValue={currentCategories}
156
      />
157
      {errors.category_id && <FormErrorFeedback>{errors.category_id?.message}</FormErrorFeedback>}
158
 
159
      <Ckeditor
160
        name='description'
161
        control={control}
162
        rules={{ required: labels.error_field_empty }}
163
        error={errors.description?.message}
164
      />
165
    </Modal>
166
  );
167
};
168
 
169
export default QuestionModal;