Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
7156 stevensc 1
import React, { useEffect, useRef, useState } from 'react'
2
import { useDispatch, useSelector } from 'react-redux'
3
import { Col, Container, Row } from 'react-bootstrap'
4
import { axios, debounce, jsonToParams } from '../../utils'
5
import { addNotification } from '../../redux/notification/notification.actions'
6
import styled from 'styled-components'
7
 
8
import SearchInput from '../../components/UI/SearchInput'
9
import EmptySection from '../../components/UI/EmptySection'
10
import WidgetLayout from '../../components/widgets/WidgetLayout'
11
import PaginationComponent from '../../components/UI/PaginationComponent'
12
 
13
import ConfirmModal from '../../components/modals/ConfirmModal'
7160 stevensc 14
import QuestionCard from '../../components/my-coach/QuestionCard'
7156 stevensc 15
 
16
const CoachCategories = styled(WidgetLayout)`
17
  padding: 1rem;
18
  ul {
19
    display: flex;
20
    flex-direction: column;
21
    gap: 1rem;
22
    li,
23
    label {
24
      cursor: pointer;
25
    }
26
    .selected label {
27
      font-weight: 600;
28
    }
29
  }
30
`
31
 
7157 stevensc 32
const QuestionsGrid = styled.div`
7156 stevensc 33
  display: grid;
7165 stevensc 34
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
7156 stevensc 35
  gap: 1rem;
36
`
37
 
38
const KnowledgeSearch = styled(SearchInput)`
39
  background-color: var(--bg-color);
40
`
41
 
42
const MyCoachPage = () => {
7157 stevensc 43
  const [questions, setQuestions] = useState([])
44
  const [questionsCategories, setQuestionsCategories] = useState([])
7156 stevensc 45
  const [search, setSearch] = useState('')
46
  const [category, setCategory] = useState('')
47
  const [currentPage, setCurrentPage] = useState(1)
48
  const [totalPages, setTotalPages] = useState(1)
49
  const [modalShow, setModalShow] = useState(null)
7158 stevensc 50
  const addUrl = useRef('/my-coach/questions/add')
7156 stevensc 51
  const actionUrl = useRef('')
52
  const labels = useSelector(({ intl }) => intl.labels)
53
  const dispatch = useDispatch()
54
 
7157 stevensc 55
  const getCategories = () => {
56
    axios
57
      .get('/my-coach', {
58
        headers: {
59
          'Content-Type': 'application/json',
60
        },
61
      })
62
      .then((response) => {
63
        const { data, success } = response.data
64
 
65
        if (!success) {
66
          const errorMessage =
67
            typeof data === 'string' ? data : labels.error_there_was_an_error
68
 
69
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
70
          return
71
        }
72
 
7158 stevensc 73
        const categories = Object.entries(data.categories).map((values) => ({
74
          name: values[1],
75
          uuid: values[0],
76
        }))
77
 
78
        setQuestionsCategories(categories)
7157 stevensc 79
      })
80
      .catch((error) => {
81
        dispatch(
82
          addNotification({
83
            style: 'danger',
84
            msg: labels.error_there_was_an_error,
85
          })
86
        )
87
        throw new Error(error)
88
      })
89
  }
90
 
91
  const getQuestions = (search = '', page = 1, category_id = '') => {
7156 stevensc 92
    const urlParams = { search, page, category_id }
93
    axios
7158 stevensc 94
      .get(`/my-coach/questions?${jsonToParams(urlParams)}`, {
7156 stevensc 95
        headers: {
96
          'Content-Type': 'application/json',
97
        },
98
      })
99
      .then((response) => {
100
        const { data, success } = response.data
101
 
102
        if (!success) {
103
          const errorMessage =
104
            typeof data === 'string' ? data : labels.error_there_was_an_error
105
 
106
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
107
          return
108
        }
109
 
7158 stevensc 110
        setQuestions(data.items)
111
        setCurrentPage(data.page)
112
        setTotalPages(data.total_pages)
7156 stevensc 113
      })
114
      .catch((error) => {
115
        dispatch(
116
          addNotification({
117
            style: 'danger',
118
            msg: labels.error_there_was_an_error,
119
          })
120
        )
121
        throw new Error(error)
122
      })
123
  }
124
 
125
  const confirmDelete = () => {
126
    axios
127
      .post(actionUrl.current)
128
      .then((response) => {
129
        const { data, success } = response.data
130
 
131
        if (!success) {
132
          const errorMessage =
133
            typeof data === 'string'
134
              ? data
135
              : 'Ha ocurrido un error, por favor intente más tarde.'
136
 
137
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
138
          return
139
        }
140
 
141
        dispatch(addNotification({ style: 'success', msg: data }))
7157 stevensc 142
        getQuestions(search, currentPage, category)
7156 stevensc 143
        closeModal()
144
      })
145
      .catch((error) => {
146
        dispatch(
147
          addNotification({
148
            style: 'danger',
149
            msg: 'Ha ocurrido un error, por favor intente más tarde.',
150
          })
151
        )
152
        throw new Error(error)
153
      })
154
  }
155
 
7157 stevensc 156
  const addQuestion = (url) => {
7156 stevensc 157
    actionUrl.current = url
158
    setModalShow('add')
159
  }
160
 
7157 stevensc 161
  const editQuestion = (url) => {
7156 stevensc 162
    actionUrl.current = url
163
    setModalShow('edit')
164
  }
165
 
7157 stevensc 166
  const deleteQuestion = (url) => {
7156 stevensc 167
    actionUrl.current = url
168
    setModalShow('delete')
169
  }
170
 
171
  const closeModal = () => {
172
    actionUrl.current = ''
173
    setModalShow(null)
174
  }
175
 
176
  const handleInputChange = debounce((e) => setSearch(e.target.value), 500)
177
 
178
  useEffect(() => {
7157 stevensc 179
    getCategories()
180
  }, [])
181
 
182
  useEffect(() => {
183
    getQuestions(search, currentPage, category)
7156 stevensc 184
  }, [search, currentPage, category])
185
 
186
  return (
187
    <>
188
      <Container as="section" className="companies-info">
189
        <div className="company-title">
190
          <h1 className="title mx-auto">{labels.knowledge_area_title}</h1>
7158 stevensc 191
          <h2
192
            className="title cursor-pointer"
193
            onClick={() => addQuestion(addUrl.current)}
194
          >
195
            {labels.knowledge_area_add}
196
          </h2>
7156 stevensc 197
        </div>
198
 
199
        <Row className="gap-3">
200
          <Col md="3">
201
            <CoachCategories>
202
              <ul>
203
                <li className={!category && 'selected'}>
204
                  <input
205
                    type="radio"
206
                    id="category-all"
207
                    value=""
208
                    name="category"
209
                    onChange={(e) => setCategory(e.target.value)}
210
                    hidden
211
                  />
212
                  <label htmlFor="category-all">
213
                    {labels.knowledge_area_category_all}
214
                  </label>
215
                </li>
7157 stevensc 216
                {questionsCategories.map(({ uuid, name }) => (
7156 stevensc 217
                  <li className={category === uuid && 'selected'} key={uuid}>
218
                    <input
219
                      type="radio"
220
                      id={`category-${name}`}
221
                      name="category"
222
                      value={uuid}
223
                      onChange={(e) => setCategory(e.target.value)}
224
                      hidden
225
                    />
226
                    <label htmlFor={`category-${name}`}>{name}</label>
227
                  </li>
228
                ))}
229
              </ul>
230
            </CoachCategories>
231
          </Col>
232
 
7165 stevensc 233
          <Col className="px-md-0">
7156 stevensc 234
            <KnowledgeSearch
235
              onChange={handleInputChange}
236
              placeholder={labels.search}
237
            />
7157 stevensc 238
            <QuestionsGrid className="mt-3">
239
              {questions.length ? (
7160 stevensc 240
                questions.map((question) => (
241
                  <QuestionCard
242
                    key={question.uuid}
7157 stevensc 243
                    onEdit={editQuestion}
244
                    onDelete={deleteQuestion}
7164 stevensc 245
                    {...question}
7156 stevensc 246
                  />
247
                ))
248
              ) : (
249
                <EmptySection
250
                  message={labels.error_no_record_matched_your_query}
251
                />
252
              )}
7157 stevensc 253
            </QuestionsGrid>
7156 stevensc 254
            <PaginationComponent
255
              onChangePage={(newPage) => setCurrentPage(newPage)}
256
              currentActivePage={currentPage}
257
              pages={totalPages}
258
              isRow
259
            />
260
          </Col>
261
        </Row>
262
      </Container>
263
      <ConfirmModal
264
        show={modalShow === 'delete'}
265
        onClose={closeModal}
266
        onAccept={confirmDelete}
267
      />
268
    </>
269
  )
270
}
271
 
272
export default MyCoachPage