Proyectos de Subversion LeadersLinked - SPA

Rev

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

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