Proyectos de Subversion LeadersLinked - SPA

Rev

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