Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
3719 stevensc 1
import React, { useEffect, useRef, useState } from 'react';
2
import { useNavigate, useLocation } from 'react-router-dom';
3
import { useDispatch, useSelector } from 'react-redux';
4
import { Grid } from '@mui/material';
5
 
6
import { axios } from '../../utils';
7
import { addNotification } from '../../redux/notification/notification.actions';
8
 
9
import QuestionCard from '../../components/my-coach/QuestionCard';
10
import AnswerCard from '../../components/my-coach/AnswerCard';
11
import AnswerModal from '../../components/my-coach/AnswerModal';
12
import ConfirmModal from '../../components/modals/ConfirmModal';
13
import GoBackLayout from '@layouts/go-back';
14
 
15
const MyCoachViewPage = () => {
16
  const [question, setQuestion] = useState({});
17
  const [answers, setAnswers] = useState([]);
18
  const [modalShow, setModalShow] = useState(null);
19
  const [currentAnswer, setCurrentAnswer] = useState('');
20
  const addUrl = useRef('');
21
  const actionUrl = useRef('');
22
  const labels = useSelector(({ intl }) => intl.labels);
23
  const dispatch = useDispatch();
24
  const { pathname } = useLocation();
25
  const navigate = useNavigate();
26
 
27
  const getQuestion = () => {
28
    axios
29
      .get(pathname, {
30
        headers: {
31
          'Content-Type': 'application/json'
32
        }
33
      })
34
      .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
        addUrl.current = data.link_answers_add;
48
        setQuestion(data);
49
      })
50
      .catch((error) => {
51
        dispatch(addNotification({ style: 'danger', msg: error.message }));
52
      });
53
  };
54
 
55
  const confirmDelete = () => {
56
    axios
57
      .post(actionUrl.current)
58
      .then((response) => {
59
        const { data, success } = response.data;
60
 
61
        if (!success) {
62
          const errorMessage =
63
            typeof data === 'string' ? data : 'Ha ocurrido un error, por favor intente más tarde.';
64
 
65
          dispatch(addNotification({ style: 'danger', msg: errorMessage }));
66
          return;
67
        }
68
 
69
        closeModal();
70
        dispatch(addNotification({ style: 'success', msg: data }));
71
        navigate('/my-coach');
72
      })
73
      .catch((error) => {
74
        dispatch(addNotification({ style: 'danger', msg: error.message }));
75
      });
76
  };
77
 
78
  const confirmDeleteAnswer = () => {
79
    axios
80
      .post(actionUrl.current)
81
      .then((response) => {
82
        const { data, success } = response.data;
83
 
84
        if (!success) {
85
          const errorMessage =
86
            typeof data === 'string' ? data : 'Ha ocurrido un error, por favor intente más tarde.';
87
 
88
          dispatch(addNotification({ style: 'danger', msg: errorMessage }));
89
          return;
90
        }
91
 
92
        setQuestion((prevQuestion) => ({
93
          ...prevQuestion,
94
          comments: data.total_comments,
95
          answers: data.total_answers,
96
          reactions: data.total_reactions
97
        }));
98
        closeModal();
99
      })
100
      .catch((error) => {
101
        dispatch(addNotification({ style: 'danger', msg: error.message }));
102
      });
103
  };
104
 
105
  const deleteQuestion = (url) => {
106
    actionUrl.current = url;
107
    setModalShow('delete');
108
  };
109
 
110
  const editQuestion = (url) => {
111
    actionUrl.current = url;
112
    setModalShow('edit');
113
  };
114
 
115
  const closeModal = () => {
116
    actionUrl.current = '';
117
    setModalShow(null);
118
    setCurrentAnswer('');
119
  };
120
 
121
  const addAnswer = () => {
122
    setModalShow('addAnswer');
123
  };
124
 
125
  const editAnswer = (url, text) => {
126
    setModalShow('editAnswer');
127
    actionUrl.current = url;
128
    setCurrentAnswer(text);
129
  };
130
 
131
  const deleteAnswer = (url) => {
132
    setModalShow('deleteAnswer');
133
    actionUrl.current = url;
134
  };
135
 
136
  const onAddAnswer = ({ answers, item }) => {
137
    setQuestion((prevQuestion) => ({ ...prevQuestion, answers }));
138
    setAnswers((prevAnswers) => [item, ...prevAnswers]);
139
  };
140
 
141
  const onEditAnswer = ({ description }) => {
142
    const newAnswers = answers.map((answer) => {
143
      if (answer.link_edit === actionUrl.current) {
144
        return { ...answer, text: description };
145
      }
146
 
147
      return answer;
148
    });
149
 
150
    setAnswers(newAnswers);
151
  };
152
 
153
  const updateTotalComments = (total) => {
154
    setQuestion({
155
      ...question,
156
      comments: total
157
    });
158
  };
159
 
160
  const updateTotalReactions = (total) => {
161
    setQuestion({
162
      ...question,
163
      reactions: total
164
    });
165
  };
166
 
167
  useEffect(() => {
168
    getQuestion();
169
  }, []);
170
 
171
  useEffect(() => {
172
    if (question.link_answers) {
173
      axios
174
        .get(question.link_answers)
175
        .then((response) => {
176
          const { data, success } = response.data;
177
 
178
          if (!success) {
179
            const errorMessage =
180
              typeof data === 'string'
181
                ? data
182
                : 'Error interno. Por favor, inténtelo de nuevo más tarde.';
183
 
184
            dispatch(addNotification({ style: 'danger', msg: errorMessage }));
185
            return;
186
          }
187
 
188
          setAnswers(data.items);
189
        })
190
        .catch((error) => {
191
          dispatch(addNotification({ style: 'danger', msg: error.message }));
192
        });
193
    }
194
  }, [question]);
195
 
196
  return (
197
    <GoBackLayout title={labels.my_coach}>
198
      <Grid container>
199
        <Grid size={{ xs: 12, md: 8 }} sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
200
          <QuestionCard
201
            key={question.uuid}
202
            onEdit={editQuestion}
203
            onDelete={deleteQuestion}
204
            onReply={addAnswer}
205
            {...question}
206
          />
207
 
208
          {answers.map((answer) => (
209
            <AnswerCard
210
              key={answer.unique}
211
              {...answer}
212
              onEdit={editAnswer}
213
              onDelete={deleteAnswer}
214
              updateComments={updateTotalComments}
215
              updateReactions={updateTotalReactions}
216
            />
217
          ))}
218
        </Grid>
219
      </Grid>
220
 
221
      <AnswerModal
222
        url={currentAnswer ? actionUrl.current : addUrl.current}
223
        show={['addAnswer', 'editAnswer'].includes(modalShow)}
224
        currentAnswer={currentAnswer}
225
        onClose={closeModal}
226
        onComplete={currentAnswer ? onEditAnswer : onAddAnswer}
227
      />
228
      <ConfirmModal
229
        show={modalShow === 'deleteAnswer'}
230
        onClose={closeModal}
231
        onAccept={confirmDeleteAnswer}
232
      />
233
      <ConfirmModal show={modalShow === 'delete'} onClose={closeModal} onAccept={confirmDelete} />
234
    </GoBackLayout>
235
  );
236
};
237
 
238
export default MyCoachViewPage;