Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 655 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
5 stevensc 1
import React, { useEffect, useState } from "react";
2
import { Button, Form, Modal } from "react-bootstrap";
3
import { useDispatch, useSelector } from "react-redux";
4
import { CKEditor } from "ckeditor4-react";
5
import { CKEDITOR_OPTIONS, axios } from "../../utils";
6
import { useForm } from "react-hook-form";
7
import { addNotification } from "../../redux/notification/notification.actions";
8
 
9
import Spinner from "../UI/Spinner";
10
import TagsInput from "../UI/TagsInput";
11
import FormErrorFeedback from "../UI/FormErrorFeedback";
12
import { styled } from "styled-components";
13
 
14
const TagsContainer = styled.div`
15
  padding: 0.5rem;
16
  border: 1px solid var(--border-primary);
17
  border-radius: var(--border-radius);
18
  margin-top: 1rem;
19
`;
20
 
21
const QuestionModal = ({ show, url, isEdit, onClose, onComplete }) => {
22
  const [loading, setLoading] = useState(false);
23
  const [questionsCategories, setQuestionsCategories] = useState([]);
24
  const [currentCategories, setCurrentCategories] = useState([]);
25
  const labels = useSelector(({ intl }) => intl.labels);
26
  const dispatch = useDispatch();
27
 
28
  const { register, handleSubmit, getValues, setValue, errors } = useForm();
29
 
30
  const onSubmit = handleSubmit((data) => {
31
    setLoading(true);
32
    const formData = new FormData();
33
 
34
    Object.entries(data).map(([key, value]) => formData.append(key, value));
35
 
36
    axios
37
      .post(url, formData)
38
      .then((response) => {
39
        const { data, success } = response.data;
40
 
41
        if (!success) {
42
          const errorMessage =
43
            typeof data === "string"
44
              ? data
45
              : "Error interno. Por favor, inténtelo de nuevo más tarde.";
46
 
47
          dispatch(addNotification({ style: "danger", msg: errorMessage }));
48
          return;
49
        }
50
 
51
        onComplete();
52
        onClose();
53
      })
54
      .finally(() => setLoading(false));
55
  });
56
 
57
  const getCategories = () => {
58
    axios
59
      .get("/my-coach", {
60
        headers: {
61
          "Content-Type": "application/json",
62
        },
63
      })
64
      .then((response) => {
65
        const { data, success } = response.data;
66
 
67
        if (!success) {
68
          const errorMessage =
69
            typeof data === "string"
70
              ? data
71
              : "Error interno. Por favor, inténtelo de nuevo más tarde.";
72
 
73
          dispatch(addNotification({ style: "danger", msg: errorMessage }));
74
          return;
75
        }
76
 
77
        const categories = Object.entries(data.categories).map((values) => ({
78
          name: values[1],
79
          value: values[0],
80
        }));
81
 
82
        setQuestionsCategories(categories);
83
      })
84
      .catch((error) => {
85
        dispatch(
86
          addNotification({
87
            style: "danger",
88
            msg: "Error interno. Por favor, inténtelo de nuevo más tarde.",
89
          })
90
        );
91
        throw new Error(error);
92
      });
93
  };
94
 
95
  const onTagsChange = (tags) => {
96
    const categories = tags.map((tag) => tag.value);
97
    setValue("category_id", categories);
98
  };
99
 
100
  useEffect(() => {
101
    getCategories();
102
 
103
    register("description", { required: true });
104
    register("category_id", { required: true });
105
  }, []);
106
 
107
  useEffect(() => {
108
    if (!url || !show || !isEdit || !questionsCategories.length) return;
109
 
110
    axios.get(url).then((response) => {
111
      const { data, success } = response.data;
112
 
113
      if (!success) {
114
        const errorMessage =
115
          typeof data === "string"
116
            ? data
117
            : "Error interno. Por favor, inténtelo de nuevo más tarde.";
118
 
119
        dispatch(
120
          addNotification({
121
            style: "danger",
122
            msg: errorMessage,
123
          })
124
        );
125
        return;
126
      }
127
 
128
      const categories = data.category_id.map((uuid) =>
129
        questionsCategories.find((c) => c.value === uuid)
130
      );
131
 
132
      setCurrentCategories(categories);
133
 
134
      setValue("title", data.title);
135
      setValue("description", data.description);
136
    });
137
  }, [url, show, isEdit, questionsCategories]);
138
 
139
  useEffect(() => {
140
    if (!show) {
141
      setCurrentCategories([]);
142
      setValue("category_id", []);
143
      setValue("description", "");
144
      setValue("title", "");
145
    }
146
  }, [show]);
147
 
148
  return (
149
    <Modal show={show}>
150
      <Modal.Header className="pb-0">
151
        <Modal.Title>
152
          {isEdit ? labels.edit : labels.add} {labels.question}
153
        </Modal.Title>
154
      </Modal.Header>
155
      <Modal.Body>
156
        {loading ? (
157
          <Spinner />
158
        ) : (
159
          <Form onSubmit={onSubmit}>
160
            <Form.Group>
161
              <Form.Label>{labels.title}</Form.Label>
162
              <Form.Control
163
                type="text"
164
                name="title"
165
                ref={register({ required: true })}
166
              />
167
              {errors.title && (
168
                <FormErrorFeedback>
169
                  {labels.error_field_empty}
170
                </FormErrorFeedback>
171
              )}
172
            </Form.Group>
173
 
174
            <CKEditor
175
              onChange={(e) => setValue("description", e.editor.getData())}
176
              onInstanceReady={(e) =>
177
                e.editor.setData(getValues("description"))
178
              }
179
              config={CKEDITOR_OPTIONS}
180
            />
181
            {errors.description && (
182
              <FormErrorFeedback>{labels.error_field_empty}</FormErrorFeedback>
183
            )}
184
 
185
            <TagsContainer>
186
              <TagsInput
187
                suggestions={questionsCategories}
188
                settedTags={currentCategories}
189
                onChange={onTagsChange}
190
              />
191
            </TagsContainer>
192
 
193
            <Button className="mt-3 mr-2" variant="primary" type="submit">
194
              {labels.accept}
195
            </Button>
196
            <Button className="btn-secondary mt-3" onClick={onClose}>
197
              {labels.cancel}
198
            </Button>
199
          </Form>
200
        )}
201
      </Modal.Body>
202
    </Modal>
203
  );
204
};
205
 
206
export default QuestionModal;