Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
5 stevensc 1
import React, { useEffect, useRef, useState } from 'react'
2
import { axios } from '../../utils'
3
import { useHistory, useLocation } from 'react-router-dom'
4
import { addNotification } from '../../redux/notification/notification.actions'
5
import { useDispatch, useSelector } from 'react-redux'
6
import { Col, Container, Row } from 'react-bootstrap'
7
import styled from 'styled-components'
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'
535 stevensc 12
import ConfirmModal from '../../components/modals/ConfirmModal'
409 stevensc 13
import TitleSection from '../../components/UI/TitleSection'
5 stevensc 14
 
15
const StyledSection = styled(Col)`
16
  display: flex;
17
  flex-direction: column;
18
  gap: 0.5rem;
19
  margin: auto;
20
`
21
 
22
const MyCoachViewPage = () => {
23
  const [question, setQuestion] = useState({})
24
  const [answers, setAnswers] = useState([])
25
  const [modalShow, setModalShow] = useState(null)
26
  const [currentAnswer, setCurrentAnswer] = useState('')
27
  const addUrl = useRef('')
28
  const actionUrl = useRef('')
29
  const labels = useSelector(({ intl }) => intl.labels)
30
  const dispatch = useDispatch()
31
  const { pathname } = useLocation()
32
  const history = useHistory()
33
 
34
  const getQuestion = () => {
35
    axios
36
      .get(pathname, {
37
        headers: {
38
          'Content-Type': 'application/json',
39
        },
40
      })
41
      .then((response) => {
42
        const { data, success } = response.data
43
 
44
        if (!success) {
45
          const errorMessage =
46
            typeof data === 'string'
47
              ? data
48
              : 'Error interno. Por favor, inténtelo de nuevo más tarde.'
49
 
50
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
51
          return
52
        }
53
 
54
        addUrl.current = data.link_answers_add
55
        setQuestion(data)
56
      })
57
      .catch((error) => {
58
        dispatch(
59
          addNotification({
60
            style: 'danger',
61
            msg: 'Error interno. Por favor, inténtelo de nuevo más tarde.',
62
          })
63
        )
64
        throw new Error(error)
65
      })
66
  }
67
 
68
  const confirmDelete = () => {
69
    axios
70
      .post(actionUrl.current)
71
      .then((response) => {
72
        const { data, success } = response.data
73
 
74
        if (!success) {
75
          const errorMessage =
76
            typeof data === 'string'
77
              ? data
78
              : 'Ha ocurrido un error, por favor intente más tarde.'
79
 
80
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
81
          return
82
        }
83
 
84
        closeModal()
85
        dispatch(addNotification({ style: 'success', msg: data }))
86
        history.replace('/my-coach')
87
      })
88
      .catch((error) => {
89
        dispatch(
90
          addNotification({
91
            style: 'danger',
92
            msg: 'Ha ocurrido un error, por favor intente más tarde.',
93
          })
94
        )
95
        throw new Error(error)
96
      })
97
  }
98
 
99
  const confirmDeleteAnswer = () => {
100
    axios
101
      .post(actionUrl.current)
102
      .then((response) => {
103
        const { data, success } = response.data
104
 
105
        if (!success) {
106
          const errorMessage =
107
            typeof data === 'string'
108
              ? data
109
              : 'Ha ocurrido un error, por favor intente más tarde.'
110
 
111
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
112
          return
113
        }
114
 
115
        setQuestion((prevQuestion) => ({
116
          ...prevQuestion,
117
          comments: data.total_comments,
118
          answers: data.total_answers,
119
          reactions: data.total_reactions,
120
        }))
121
        closeModal()
122
      })
123
      .catch((error) => {
124
        dispatch(
125
          addNotification({
126
            style: 'danger',
127
            msg: 'Ha ocurrido un error, por favor intente más tarde.',
128
          })
129
        )
130
        throw new Error(error)
131
      })
132
  }
133
 
134
  const deleteQuestion = (url) => {
135
    actionUrl.current = url
136
    setModalShow('delete')
137
  }
138
 
139
  const editQuestion = (url) => {
140
    actionUrl.current = url
141
    setModalShow('edit')
142
  }
143
 
144
  const closeModal = () => {
145
    actionUrl.current = ''
146
    setModalShow(null)
147
    setCurrentAnswer('')
148
  }
149
 
150
  const addAnswer = () => {
151
    setModalShow('addAnswer')
152
  }
153
 
154
  const editAnswer = (url, text) => {
155
    setModalShow('editAnswer')
156
    actionUrl.current = url
157
    setCurrentAnswer(text)
158
  }
159
 
160
  const deleteAnswer = (url) => {
161
    setModalShow('deleteAnswer')
162
    actionUrl.current = url
163
  }
164
 
165
  const onAddAnswer = ({ answers, item }) => {
166
    setQuestion((prevQuestion) => ({ ...prevQuestion, answers }))
167
    setAnswers((prevAnswers) => [item, ...prevAnswers])
168
  }
169
 
170
  const onEditAnswer = ({ description }) => {
171
    const newAnswers = answers.map((answer) => {
172
      if (answer.link_edit === actionUrl.current) {
173
        return { ...answer, text: description }
174
      }
175
 
176
      return answer
177
    })
178
 
179
    setAnswers(newAnswers)
180
  }
181
 
182
  const updateTotalComments = (total) => {
183
    setQuestion({
184
      ...question,
185
      comments: total,
186
    })
187
  }
188
 
189
  const updateTotalReactions = (total) => {
190
    setQuestion({
191
      ...question,
192
      reactions: total,
193
    })
194
  }
195
 
196
  useEffect(() => {
197
    getQuestion()
198
  }, [])
199
 
200
  useEffect(() => {
201
    if (question.link_answers) {
202
      axios
203
        .get(question.link_answers)
204
        .then((response) => {
205
          const { data, success } = response.data
206
 
207
          if (!success) {
208
            const errorMessage =
209
              typeof data === 'string'
210
                ? data
211
                : 'Error interno. Por favor, inténtelo de nuevo más tarde.'
212
 
213
            dispatch(addNotification({ style: 'danger', msg: errorMessage }))
214
            return
215
          }
216
 
217
          setAnswers(data.items)
218
        })
219
        .catch((error) => {
220
          dispatch(
221
            addNotification({
222
              style: 'danger',
223
              msg: 'Error interno. Por favor, inténtelo de nuevo más tarde.',
224
            })
225
          )
226
          throw new Error(error)
227
        })
228
    }
229
  }, [question])
230
 
231
  return (
232
    <>
535 stevensc 233
      <Container as="section" className="px-0">
409 stevensc 234
        <TitleSection title={labels.my_coach} />
5 stevensc 235
        <Row>
236
          <StyledSection md="8">
237
            <QuestionCard
238
              key={question.uuid}
239
              onEdit={editQuestion}
240
              onDelete={deleteQuestion}
241
              onReply={addAnswer}
242
              {...question}
243
            />
244
            {answers.map((answer) => (
245
              <AnswerCard
246
                key={answer.unique}
247
                {...answer}
248
                onEdit={editAnswer}
249
                onDelete={deleteAnswer}
250
                updateComments={updateTotalComments}
251
                updateReactions={updateTotalReactions}
252
              />
253
            ))}
254
          </StyledSection>
255
        </Row>
256
      </Container>
257
      <AnswerModal
258
        url={currentAnswer ? actionUrl.current : addUrl.current}
259
        show={['addAnswer', 'editAnswer'].includes(modalShow)}
260
        currentAnswer={currentAnswer}
261
        onClose={closeModal}
262
        onComplete={currentAnswer ? onEditAnswer : onAddAnswer}
263
      />
264
      <ConfirmModal
265
        show={modalShow === 'deleteAnswer'}
266
        onClose={closeModal}
267
        onAccept={confirmDeleteAnswer}
268
      />
269
      <ConfirmModal
270
        show={modalShow === 'delete'}
271
        onClose={closeModal}
272
        onAccept={confirmDelete}
273
      />
274
    </>
275
  )
276
}
277
 
278
export default MyCoachViewPage