Rev 7243 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef, useState } from 'react'
import { axios } from '../../../utils'
import { Modal } from 'react-bootstrap'
import { useForm } from 'react-hook-form'
import { useDispatch } from 'react-redux'
import { addNotification } from '../../../redux/notification/notification.actions'
import styled from 'styled-components'
import Datetime from 'react-datetime'
import SearchIcon from '@mui/icons-material/Search'
import TextBox from '../../../components/chat/TextBox'
import ChatList from '../../../components/chat/ChatList'
import ConfirmModal from '../../../shared/confirm-modal/ConfirmModal'
import EmptySection from '../../../shared/empty-section/EmptySection'
import FormErrorFeedback from '../../../shared/form-error-feedback/FormErrorFeedback'
import 'react-datetime/css/react-datetime.css'
const StyledShowOptions = styled.div`
height: 342px;
flex-direction: column;
gap: 0.5rem;
overflow-y: auto;
position: relative;
&.show {
display: flex;
}
&.hide {
display: none;
}
.optionBack {
margin: 1rem 0 0.5rem 1rem;
cursor: pointer;
}
.optionsTab {
&__option {
padding: 0.5rem;
border-bottom: 1px solid #e2e2e2;
cursor: pointer;
&:hover {
background-color: #e2e2e2;
}
&__icon {
margin-right: 0.3rem;
}
}
}
.addPersonToGroupTab {
display: flex;
flex-direction: column;
&__person {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.2rem 0.5rem;
border-bottom: 1px solid #e2e2e2;
}
}
`
const OPTIONS = {
GROUP: 'group',
CONFERENCE: 'conference',
ADD_CONTACTS: 'addContacts',
LIST_CONTACTS: 'listContacts',
INITIAL: null,
}
const PersonalChat = ({
entity,
onClose,
onMinimize,
onRead,
not_seen_messages,
minimized,
timezones,
}) => {
const {
// id,
image,
name,
online,
type,
url_get_all_messages,
url_send,
url_upload,
profile,
url_leave,
url_delete,
url_add_user_to_group,
url_get_contact_group_list,
url_get_contacts_availables_for_group,
url_zoom,
} = entity
const [optionTab, setOptionTab] = useState(OPTIONS.INITIAL)
const [availableContactsToAdd, setAvailableContactsToAdd] = useState([])
const [groupContactsList, setGroupContactsList] = useState([])
const [confirmModalShow, setConfirmModalShow] = useState(false)
const [showConferenceModal, setShowConferenceModal] = useState(false)
const [search, setSearch] = useState('')
const [messages, setMessages] = useState([])
const [oldMessages, setOldMessages] = useState([])
const [currentPage, setCurrentPage] = useState(1)
const [lastPage, setLastPage] = useState(1)
const [loading, setLoading] = useState(false)
const filtredGroupList = groupContactsList.filter((conversation) =>
conversation.name.toLowerCase().includes(search.toLowerCase())
)
// refs
const conversationListEl = useRef(null)
const loader = useRef(null)
const modalActionUrl = useRef('')
const handleActive = () => {
onRead(entity)
onMinimize(entity)
}
const handleGetMessages = async () => {
setLoading(true)
const response = await axios.get(url_get_all_messages)
const resData = response.data
if (!resData.success) {
return 'ha ocurrido un error'
}
const updatedMessages = [...resData.data.items].reverse()
const newMessages = updatedMessages.reduce((acum, updatedMessage) => {
if (
messages.findIndex((message) => message.id === updatedMessage.id) === -1
) {
acum = [...acum, updatedMessage]
}
return acum
}, [])
if (newMessages.length > 0) {
setMessages([...messages, ...newMessages])
setLoading(false)
setLastPage(resData.data.pages)
scrollToBottom()
} else {
setLoading(false)
}
}
const handleLoadMore = async () => {
await axios
.get(`${url_get_all_messages}?page=${currentPage}`)
.then((response) => {
const resData = response.data
if (resData.success) {
if (resData.data.page > 1) {
const updatedOldMessages = [...resData.data.items].reverse()
setOldMessages([...updatedOldMessages, ...oldMessages])
/* scrollDownBy(100); */
}
}
})
}
const handleCloseChat = () => onClose(entity)
const sendMessage = async (message) => {
const formData = new FormData()
formData.append('message', emojione.toShort(message))
await axios.post(url_send, formData).then((response) => {
const resData = response.data
if (resData.success) {
let newMessage = resData.data
online
? (newMessage = { ...newMessage, not_received: false })
: (newMessage = { ...newMessage, not_received: true })
setMessages([...messages, newMessage])
}
})
// await handleGetMessages()
// setResponseMessage(null)
}
const showOptions = (tab = OPTIONS.INITIAL) => {
onMinimize(entity, false)
setOptionTab(tab)
}
const handleAddPersonToGroup = async (id) => {
const formData = new FormData()
formData.append('uid', id)
await axios.post(url_add_user_to_group, formData).then((response) => {
const resData = response.data
if (resData.success) {
loadPersonsAvailable()
}
})
}
const handleConfirmModalAction = async () => {
try {
const { data } = await axios.post(modalActionUrl.current)
if (!data.success) console.log('Error in confirm modal action')
handleConfirmModalShow()
onClose(entity)
return
} catch (error) {
console.log(error)
}
}
const handleObserver = (entities) => {
const target = entities[0]
if (target.isIntersecting) {
setCurrentPage((prevState) => prevState + 1)
}
}
const scrollToBottom = () => {
if (conversationListEl.current) {
conversationListEl.current.scrollTop =
conversationListEl.current.scrollHeight * 9
}
}
const handleConfirmModalShow = () => setConfirmModalShow(!confirmModalShow)
const handleConfirmModalAccept = () => handleConfirmModalAction()
/* const handleResponseMessage = (element) => {
element.mtype === 'text'
? setResponseMessage(element)
: setResponseMessage({ ...element, m: 'Archivo adjunto' })
textAreaEl.current && textAreaEl.current.focus()
} */
const displayConferenceModal = () =>
setShowConferenceModal(!showConferenceModal)
const loadPersonsAvailable = async () => {
await axios.get(url_get_contacts_availables_for_group).then((response) => {
const resData = response.data
if (resData.success) {
setAvailableContactsToAdd(resData.data)
}
})
}
const loadGroupContacts = async () => {
await axios.get(url_get_contact_group_list).then((response) => {
const resData = response.data
if (resData.success) {
setGroupContactsList(resData.data)
}
})
}
const handleDeletePersonFromGroup = async (urlDeletePersonFromGroup) => {
await axios.post(urlDeletePersonFromGroup).then((response) => {
const resData = response.data
if (resData.success) {
loadGroupContacts()
}
})
}
const tabsOptions = {
group: (
<ul>
{url_get_contact_group_list && (
<li
className="optionsTab__option"
onClick={() => showOptions(OPTIONS.LIST_CONTACTS)}
>
<span className="optionsTab__option__icon">
<i className="fa fa-group" />
Integrantes
</span>
</li>
)}
{url_add_user_to_group && (
<li
className="optionsTab__option"
onClick={() => showOptions(OPTIONS.ADD_CONTACTS)}
>
<span className="optionsTab__option__icon">
<i className="fa fa-user-plus"></i>
</span>
{CHAT_LABELS.ADD_CONTACTS}
</li>
)}
{url_zoom && (
<li className="optionsTab__option" onClick={displayConferenceModal}>
<span className="optionsTab__option__icon">
<i className="fa fa-user-plus" />
</span>
{CHAT_LABELS.CREATE_CONFERENCE}
</li>
)}
{url_delete && (
<li
className="optionsTab__option"
style={{ color: 'red' }}
onClick={() => {
handleConfirmModalShow()
modalActionUrl.current = url_delete
}}
>
<span className="optionsTab__option__icon">
<i className="fa fa-trash"></i>
</span>
Eliminar grupo
</li>
)}
{!!url_leave && (
<li
className="optionsTab__option"
style={{ color: 'red' }}
onClick={() => {
handleConfirmModalShow()
modalActionUrl.current = url_leave
}}
>
<span className="optionsTab__option__icon">
<i className="fa fa-user-times"></i>
</span>
Dejar grupo
</li>
)}
</ul>
),
conference: (
<ul>
<li className="optionsTab__option" onClick={displayConferenceModal}>
<span className="optionsTab__option__icon">
<i className="fa fa-user-plus" />
</span>
{CHAT_LABELS.CREATE_CONFERENCE}
</li>
</ul>
),
addContacts: (
<>
{!availableContactsToAdd.length ? (
<EmptySection message={CHAT_LABELS.NOT_CONTACTS} align="left" />
) : (
availableContactsToAdd.map(({ image, name, id }) => (
<div className="addPersonToGroupTab__person" key={id}>
<div className="d-inline-flex" style={{ gap: '5px' }}>
<img
className="chat-image img-circle pull-left"
height="36"
width="36"
src={image}
alt="image-image"
/>
<div className="name">{name}</div>
</div>
<span
className="cursor-pointer"
onClick={() => handleAddPersonToGroup(id)}
>
<i className="fa fa-plus-circle" />
</span>
</div>
))
)}
</>
),
listContacts: (
<>
<div className="group__search">
<SearchIcon />
<input
type="text"
placeholder={CHAT_LABELS.SEARCH}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{filtredGroupList.length ? (
filtredGroupList.map(({ image, name, url_remove_from_group, id }) => {
return (
<div className="addPersonToGroupTab__person" key={id}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<img
className="chat-image img-circle pull-left"
height="36"
width="36"
src={image}
alt="image-image"
/>
<div className="name">{name}</div>
</div>
{url_remove_from_group && (
<span
className="cursor-pointer"
onClick={() =>
handleDeletePersonFromGroup(url_remove_from_group)
}
>
<i className="fa fa-user-times" />
</span>
)}
</div>
)
})
) : (
<div className="addPersonToGroupTab__person">
{CHAT_LABELS.NOT_CONTACTS}
</div>
)}
</>
),
}
// getMessageOnMaximize and subscribe to infinite Loader
useEffect(async () => {
const options = {
root: null,
rootMargin: '20px',
treshold: 1.0,
}
const observer = new IntersectionObserver(handleObserver, options)
if (!minimized) {
await handleGetMessages()
// loader observer
if (loader.current) {
observer.observe(loader.current)
}
}
return () => {
if (loader.current) {
observer.unobserve(loader.current)
}
}
}, [minimized])
// LoadMore on change page
useEffect(() => {
let loadMore = () => handleLoadMore()
loadMore()
return () => {
loadMore = null
}
}, [currentPage])
// getMessagesInterval
useEffect(() => {
if (window.location.pathname === '/group/my-groups') {
const items = document.getElementsByClassName('sc-jSgupP')
if (items && items.length > 0) {
items[0].style.display = 'none'
}
}
}, [minimized])
useEffect(() => {
let timer
if (!minimized && !loading) {
timer = setTimeout(() => handleGetMessages(), 1000)
}
return () => {
clearTimeout(timer)
}
}, [minimized, loading])
// useEffect for tabs changing
useEffect(() => {
if (optionTab === 'addContacts') loadPersonsAvailable()
if (optionTab === 'listContacts') loadGroupContacts()
}, [optionTab])
return (
<>
<div className="personal-chat">
<div className={`chat-header ${not_seen_messages ? 'notify' : ''}`}>
<img src={image} alt="avatar-image" />
<div className="info-content">
<a href={profile} target="_blank" rel="noreferrer">
{name}
</a>
{type === 'user' && (
<small className={online ? 'online' : 'offline'}>
{online ? 'En línea' : 'Desconectado'}
</small>
)}
</div>
<div className="options ml-auto">
<i
className="cursor-pointer fa fa-gear"
onClick={() =>
showOptions(
type === 'user' ? OPTIONS.CONFERENCE : OPTIONS.GROUP
)
}
/>
<i
className={'cursor-pointer fa fa-minus-circle'}
onClick={handleActive}
/>
<i
className="cursor-pointer fa fa-times-circle"
onClick={handleCloseChat}
/>
</div>
</div>
<div
className="panel-body"
style={{ display: !minimized ? 'block' : 'none' }}
>
{optionTab ? (
<StyledShowOptions>
<span className="optionBack" onClick={() => showOptions()}>
<i className="fa icon-arrow-left" />
</span>
<div className="optionsTab">{tabsOptions[optionTab]}</div>
</StyledShowOptions>
) : (
<>
<ChatList
messages={[...oldMessages, ...messages]}
currentPage={currentPage}
lastPage={lastPage}
conversationList={conversationListEl}
loader={loader}
/>
<TextBox
uploadUrl={url_upload}
isNotSeen={not_seen_messages}
markRead={() => onRead(entity)}
onSend={sendMessage}
/>
</>
)}
</div>
</div>
<ConfirmModal
show={confirmModalShow}
onClose={handleConfirmModalShow}
onAccept={handleConfirmModalAccept}
/>
<ConferenceModal
show={showConferenceModal}
timezones={timezones}
zoomUrl={url_zoom}
onCreate={() => {
showOptions()
displayConferenceModal()
}}
/>
</>
)
}
const StyleModal = ({
title = 'Crea una conferencia',
size = 'md',
show = false,
children,
}) => {
const [isShow, setIsShow] = useState(show)
useEffect(() => {
setIsShow(show)
}, [show])
const closeModal = () => setIsShow(false)
return (
<Modal show={isShow} onHide={closeModal} style={{ overflowY: 'scroll' }}>
<Modal.Header closeButton>
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>{children}</Modal.Body>
</Modal>
)
}
export const ConferenceModal = ({
show = false,
timezones = {},
zoomUrl = '',
onCreate = () => null,
}) => {
const dt = new Date()
const { handleSubmit, register, errors, reset } = useForm({ mode: 'all' })
const [date, setDate] = useState({
year: dt.toLocaleString('default', { year: 'numeric' }),
month: dt.toLocaleString('default', { month: '2-digit' }),
day: dt.toLocaleString('default', { day: '2-digit' }),
})
const [time, setTime] = useState(
dt.toLocaleString('es', {
hour: 'numeric',
minute: '2-digit',
second: '2-digit',
})
)
const [coferenceType, setConferenceType] = useState(1)
const dispatch = useDispatch()
const handleChange = (value) => setConferenceType(value)
const handleDateTime = (value) => {
setDate({
...date,
year: new Intl.DateTimeFormat('es', { year: 'numeric' }).format(value),
month: new Intl.DateTimeFormat('es', { month: '2-digit' }).format(value),
day: new Intl.DateTimeFormat('es', { day: '2-digit' }).format(value),
})
setTime(
new Intl.DateTimeFormat('es', {
hour: 'numeric',
minute: '2-digit',
second: 'numeric',
}).format(value)
)
}
const onSubmit = async (data) => {
try {
const formData = new FormData()
Object.entries(data).forEach(([key, value]) =>
formData.append(key, value)
)
formData.append('date', `${date.year}-${date.month}-${date.day}`)
formData.append('time', time)
const { data: response } = await axios.post(zoomUrl, formData)
if (!response.success && typeof response.data === 'string') {
dispatch(addNotification({ msg: response.data, style: 'danger' }))
return
}
if (!response.success && typeof response.data === 'object') {
Object.entries(response.data).forEach(([key, value]) => {
dispatch(
addNotification({ msg: `${key}: ${value[0]}`, style: 'danger' })
)
})
return
}
dispatch(addNotification({ msg: response.data, style: 'success' }))
onCreate()
reset()
} catch (error) {
console.log(`Error: ${error}`)
return dispatch(
addNotification({ msg: 'Ha ocurrido un error', style: 'danger' })
)
}
}
return (
<StyleModal title="Crea una conferencia" show={show}>
<form onSubmit={handleSubmit(onSubmit)} autoComplete="new-password">
<div className="form-group">
<label htmlFor="first_name">Título</label>
<input
type="text"
name="title"
className="form-control"
maxLength={128}
ref={register({ required: 'Por favor ingrese un título' })}
/>
{errors.title && (
<FormErrorFeedback>{errors.title.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<label htmlFor="first_name">Descripción</label>
<input
type="text"
name="description"
className="form-control"
ref={register({ required: 'Por favor ingrese una descripción' })}
/>
{errors.description && (
<FormErrorFeedback>{errors.description.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<label htmlFor="timezone">Tipo de conferencia</label>
<select
name="type"
className="form-control"
onChange={({ target }) => handleChange(target.value)}
ref={register}
>
<option value="i">Inmediata</option>
<option value="s">Programada</option>
</select>
</div>
{coferenceType === 's' && (
<div className="form-group">
<label htmlFor="timezone">Horario</label>
<Datetime
dateFormat="DD-MM-YYYY"
onChange={(e) => {
if (e.toDate) {
handleDateTime(e.toDate())
}
}}
inputProps={{ className: 'form-control' }}
initialValue={Date.parse(new Date())}
closeOnSelect
/>
</div>
)}
<div className="form-group">
<label htmlFor="timezone">Zona horaria</label>
<select
className="form-control"
name="timezone"
ref={register({ required: 'Por favor elige una Zona horaria' })}
>
<option value="" hidden>
Zona horaria
</option>
{Object.entries(timezones).map(([key, value]) => (
<option value={key} key={key}>
{value}
</option>
))}
</select>
{errors.timezone && (
<FormErrorFeedback>{errors.timezone.message}</FormErrorFeedback>
)}
</div>
<div className="form-group">
<label htmlFor="timezone">Duración</label>
<select className="form-control" name="duration" ref={register}>
<option value={5}>5-min</option>
<option value={10}>10-min</option>
<option value={15}>15-min</option>
<option value={20}>20-min</option>
<option value={25}>25-min</option>
<option value={30}>30-min</option>
<option value={35}>35-min</option>
<option value={40}>40-min</option>
<option value={45}>45-min</option>
</select>
</div>
<div className="form-group">
<label htmlFor="first_name">Contraseña de ingreso</label>
<input
type="password"
name="password"
className="form-control"
ref={register({
required: 'Por favor ingrese una contraseña',
maxLength: {
value: 6,
message: 'La contraseña debe tener al menos 6 digitos',
},
})}
/>
{errors.password && (
<FormErrorFeedback>{errors.password.message}</FormErrorFeedback>
)}
</div>
<button className="btn btn-primary" type="submit">
Crear
</button>
</form>
</StyleModal>
)
}
export default React.memo(PersonalChat)