Rev 7165 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Col, Container, Row } from 'react-bootstrap'
import { axios, debounce, jsonToParams } from '../../utils'
import { addNotification } from '../../redux/notification/notification.actions'
import styled from 'styled-components'
import SearchInput from '../../components/UI/SearchInput'
import EmptySection from '../../components/UI/EmptySection'
import WidgetLayout from '../../components/widgets/WidgetLayout'
import PaginationComponent from '../../components/UI/PaginationComponent'
import ConfirmModal from '../../components/modals/ConfirmModal'
import QuestionCard from '../../components/my-coach/QuestionCard'
import QuestionModal from '../../components/my-coach/QuestionModal'
const CoachCategories = styled(WidgetLayout)`
padding: 1rem;
ul {
display: flex;
flex-direction: column;
gap: 1rem;
li,
label {
cursor: pointer;
}
.selected label {
font-weight: 600;
}
}
`
const QuestionsGrid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
`
const KnowledgeSearch = styled(SearchInput)`
background-color: var(--bg-color);
`
const MyCoachPage = () => {
const [questions, setQuestions] = useState([])
const [questionsCategories, setQuestionsCategories] = useState([])
const [search, setSearch] = useState('')
const [category, setCategory] = useState('')
const [currentPage, setCurrentPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [modalShow, setModalShow] = useState(null)
const addUrl = useRef('/my-coach/questions/add')
const actionUrl = useRef('')
const labels = useSelector(({ intl }) => intl.labels)
const dispatch = useDispatch()
const getCategories = () => {
axios
.get('/my-coach', {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
const { data, success } = response.data
if (!success) {
const errorMessage =
typeof data === 'string' ? data : labels.error_there_was_an_error
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
return
}
const categories = Object.entries(data.categories).map((values) => ({
name: values[1],
uuid: values[0],
}))
setQuestionsCategories(categories)
})
.catch((error) => {
dispatch(
addNotification({
style: 'danger',
msg: labels.error_there_was_an_error,
})
)
throw new Error(error)
})
}
const getQuestions = (search = '', page = 1, category_id = '') => {
const urlParams = { search, page, category_id }
axios
.get(`/my-coach/questions?${jsonToParams(urlParams)}`, {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
const { data, success } = response.data
if (!success) {
const errorMessage =
typeof data === 'string' ? data : labels.error_there_was_an_error
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
return
}
setQuestions(data.items)
setCurrentPage(data.page)
setTotalPages(data.total_pages)
})
.catch((error) => {
dispatch(
addNotification({
style: 'danger',
msg: labels.error_there_was_an_error,
})
)
throw new Error(error)
})
}
const confirmDelete = () => {
axios
.post(actionUrl.current)
.then((response) => {
const { data, success } = response.data
if (!success) {
const errorMessage =
typeof data === 'string'
? data
: 'Ha ocurrido un error, por favor intente más tarde.'
dispatch(addNotification({ style: 'danger', msg: errorMessage }))
return
}
dispatch(addNotification({ style: 'success', msg: data }))
getQuestions(search, currentPage, category)
closeModal()
})
.catch((error) => {
dispatch(
addNotification({
style: 'danger',
msg: 'Ha ocurrido un error, por favor intente más tarde.',
})
)
throw new Error(error)
})
}
const addQuestion = (url) => {
actionUrl.current = url
setModalShow('add')
}
const editQuestion = (url) => {
actionUrl.current = url
setModalShow('edit')
}
const deleteQuestion = (url) => {
actionUrl.current = url
setModalShow('delete')
}
const closeModal = () => {
actionUrl.current = ''
setModalShow(null)
}
const handleInputChange = debounce((e) => setSearch(e.target.value), 500)
useEffect(() => {
getCategories()
}, [])
useEffect(() => {
getQuestions(search, currentPage, category)
}, [search, currentPage, category])
return (
<>
<Container as="section" className="companies-info">
<div className="company-title">
<h1 className="title mx-auto">{labels.my_coach}</h1>
<h2
className="title cursor-pointer"
onClick={() => addQuestion(addUrl.current)}
>
{labels.my_coach_question_add}
</h2>
</div>
<Row className="gap-3">
<Col md="3">
<CoachCategories>
<ul>
<li className={!category && 'selected'}>
<input
type="radio"
id="category-all"
value=""
name="category"
onChange={(e) => setCategory(e.target.value)}
hidden
/>
<label htmlFor="category-all">
{labels.knowledge_area_category_all}
</label>
</li>
{questionsCategories.map(({ uuid, name }) => (
<li className={category === uuid && 'selected'} key={uuid}>
<input
type="radio"
id={`category-${name}`}
name="category"
value={uuid}
onChange={(e) => setCategory(e.target.value)}
hidden
/>
<label htmlFor={`category-${name}`}>{name}</label>
</li>
))}
</ul>
</CoachCategories>
</Col>
<Col className="px-md-0">
<KnowledgeSearch
onChange={handleInputChange}
placeholder={labels.search}
/>
<QuestionsGrid className="mt-3">
{questions.length ? (
questions.map((question) => (
<QuestionCard
key={question.uuid}
onEdit={editQuestion}
onDelete={deleteQuestion}
{...question}
/>
))
) : (
<EmptySection
message={labels.error_no_record_matched_your_query}
/>
)}
</QuestionsGrid>
<PaginationComponent
onChangePage={(newPage) => setCurrentPage(newPage)}
currentActivePage={currentPage}
pages={totalPages}
isRow
/>
</Col>
</Row>
</Container>
<QuestionModal
show={['add', 'edit'].includes(modalShow)}
onClose={closeModal}
onComplete={getQuestions}
url={actionUrl.current}
isEdit={modalShow === 'edit'}
/>
<ConfirmModal
show={modalShow === 'delete'}
onClose={closeModal}
onAccept={confirmDelete}
/>
</>
)
}
export default MyCoachPage