Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

Rev Autor Línea Nro. Línea
5064 stevensc 1
/* eslint-disable react/prop-types */
2
import React from "react"
3
import { useState, useEffect } from "react"
4
import { axios } from "../../utils"
5
import { FiMaximize2 } from 'react-icons/fi'
6
import AddIcon from '@mui/icons-material/Add'
7
 
8
// Components
9
import NotificationAlert from "../../shared/notification/NotificationAlert"
10
import PersonalChat from "./personal-chat/PersonalChat"
11
import ContactsModal from "./components/ContactsModal"
12
import ContactsFilters from "./components/contactsFilters"
13
 
14
const notifyAudio = new Audio("/audio/chat.mp3")
15
 
16
const Chat = ({ defaultNetwork, emojiOnePath, timezones }) => {
17
  const [contacts, setContacts] = useState([])
18
  const [activeChats, setActiveChats] = useState([])
19
 
20
  const [isChatOpen, setIsChatOpen] = useState(false)
21
  const [isMuted, setIsMuted] = useState(false)
22
  const [showModal, setShowModal] = useState(false)
23
  const [loading, setLoading] = useState(false)
24
 
25
  const [pendingConversation, setPendingConversation] = useState('')
26
 
27
  const handleEntities = entities => {
28
    entities.map((entity) => {
29
      if (entity.not_received_messages) handleNewMessage(entity)
30
      if (entity.not_seen_messages) handleNotSeenMessage(entity)
31
      if (entity.is_open) handleOpenConversation(entity, false)
32
      if (entity.type === 'user') handleUpdateOnline(entity)
33
    })
34
    setContacts(entities)
35
  }
36
 
37
  const heartBeat = async () => {
38
    try {
39
      const { data } = await axios.get("/chat/heart-beat")
40
      if (data.success) handleEntities(data.data)
41
      return data.data
42
    } catch (error) {
43
      console.log('>>: chat error > ', error)
44
    }
45
  }
46
 
47
  const handleUpdateOnline = (entity) => {
48
    const existingChatId = activeChats.findIndex(
49
      (activeChat) => activeChat.id === entity.id
50
    )
51
    if (existingChatId >= 0) {
52
      if (activeChats[existingChatId].online !== entity.online) {
53
        const newActiveChats = [...activeChats]
54
        newActiveChats[existingChatId].online = entity.online
55
        setActiveChats(newActiveChats)
56
      }
57
    }
58
  }
59
 
60
  const handleNewMessage = async (unseeEntity) => {
61
    await axios.post(unseeEntity.url_mark_received)
62
    if (!activeChats.some((activeChat) => activeChat.id === unseeEntity.id)) {
63
      setActiveChats([...activeChats, { ...unseeEntity, minimized: false }])
64
      playNotifyAudio()
65
    } else {
66
      const existingChatId = activeChats.findIndex(
67
        (activeChat) => activeChat.id === unseeEntity.id
68
      )
69
      if (!activeChats[existingChatId].unsee_messages) {
70
        const newActiveChats = [...activeChats]
71
        newActiveChats[existingChatId].unsee_messages = true
72
        setActiveChats(newActiveChats)
73
        playNotifyAudio(newActiveChats[existingChatId].minimized)
74
      }
75
    }
76
  }
77
 
78
  const handleCloseConversation = async (entity) => {
79
    const { data } = await axios.post(entity.url_close)
80
    if (!data.success) console.log('Error in entity close')
81
    setActiveChats(activeChats.filter(prevActiveChats => prevActiveChats.id !== entity.id))
82
  }
83
 
84
  const handleOpenConversation = async (entity, minimized = false) => {
85
    if (activeChats.some(el => el.id === entity.id)) {
86
      return null
87
    }
88
 
89
    if (activeChats.length >= 3) {
90
      await handleCloseConversation(activeChats[0])
91
      setActiveChats(prevActiveChats => [...prevActiveChats, { ...entity, minimized: minimized }])
92
      return
93
    }
94
 
95
    setActiveChats(prevActiveChats => [...prevActiveChats, { ...entity, minimized: minimized }])
96
  }
97
 
98
  const handleReadConversation = async (entity) => {
99
    try {
100
      const { data } = await axios.post(entity.url_mark_seen)
101
      if (!data.success) console.log('Ha ocurrido un error')
102
      setActiveChats(prevActiveChats => [...prevActiveChats].map(chat => {
103
        if (entity.id === chat.id) return { ...chat, not_seen_messages: false }
104
        return chat
105
      }))
106
    } catch (error) {
107
      console.log(`Error: ${error}`)
108
    }
109
  }
110
 
111
  const handleMinimizeConversation = (entity, minimized = null) => {
112
    return setActiveChats(prevActiveChats => [...prevActiveChats].map(chat => {
113
      if (entity.id === chat.id) return { ...chat, minimized: minimized ?? !chat.minimized }
114
      return chat
115
    }))
116
  }
117
 
118
  const handleNotSeenMessage = (entity) => {
119
    const index = activeChats.findIndex(chat => chat.id === entity.id)
120
 
121
    if (index !== -1) {
122
      setActiveChats(prev => [...prev].map(chat => {
123
        if (chat.id === entity.id) {
124
          return {
125
            ...chat,
126
            not_seen_messages: entity.not_seen_messages
127
          }
128
        }
129
        return chat
130
      }))
131
    }
132
 
133
  }
134
 
135
  const playNotifyAudio = (minimized = true) => {
136
    if (!isMuted && minimized) {
137
      notifyAudio.play()
138
    }
139
  }
140
 
141
  const handleMute = () => {
142
    setIsMuted(!isMuted)
143
    if (isMuted) {
144
      notifyAudio.play()
145
    }
146
  }
147
 
148
  useEffect(() => {
149
    if (!loading) {
150
      const fetchData = async () => {
151
        setLoading(true)
152
        const entities = await heartBeat() || []
153
        setLoading(false)
154
 
155
        return entities
156
      }
157
 
158
      setTimeout(() => {
159
        fetchData()
160
      }, "2000")
161
    }
162
  }, [loading])
163
 
164
  useEffect(() => {
165
    if (pendingConversation) {
166
      const pendingChat = contacts.find(contact => contact.url_send === pendingConversation)
167
 
168
      if (pendingChat) {
169
        handleOpenConversation(pendingChat)
170
        setPendingConversation('')
171
      }
172
 
173
    }
174
  }, [pendingConversation, contacts])
175
 
176
  useEffect(() => {
177
    emojione.imageType = "png"
178
    emojione.sprites = false
179
    emojione.ascii = true
180
    emojione.imagePathPNG = emojiOnePath
181
  }, [])
182
 
183
  if (window.innerWidth < 1000 || window.location.pathname === '/chat') return null
184
 
185
  return (
186
    <>
187
      <div className="chat-helper">
188
        <div className="subpanel_title" onClick={(e) => (e.currentTarget === e.target) && setIsChatOpen(!isChatOpen)}>
189
          <a href="/chat" className="text-chat-title">
190
            Chat
191
            <FiMaximize2 className="ml-3" />
192
          </a>
193
          <div className="subpanel_title-icons">
194
            <i
195
              className={`icon ${isMuted ? "icon-volume-off" : "icon-volume-2"} text-20`}
196
              onClick={handleMute}
197
            />
198
            <i
199
              className={`fa ${isChatOpen ? "fa-angle-down" : "fa-angle-up"} text-20`}
200
              onClick={() => setIsChatOpen(!isChatOpen)}
201
            />
202
          </div>
203
        </div>
204
        {defaultNetwork !== 'y' &&
205
          <button className="action-btn" onClick={() => setShowModal(true)}>
206
            <AddIcon />
207
            Iniciar conversación
208
          </button>
209
        }
210
        {isChatOpen &&
211
          <ContactsFilters
212
            dataset={contacts}
213
            selectConversation={(entity) => handleOpenConversation(entity)}
214
          />
215
        }
216
 
217
      </div>
218
 
219
      <div className="active_chats-list">
220
        {activeChats.map((entity, index) => (
221
          <PersonalChat
222
            index={index}
223
            key={entity.id}
224
            entity={entity}
225
            not_seen_messages={entity.not_seen_messages}
226
            minimized={entity.minimized}
227
            onClose={handleCloseConversation}
228
            onMinimize={handleMinimizeConversation}
229
            onRead={handleReadConversation}
230
            timezones={timezones}
231
          />
232
        ))}
233
      </div>
234
 
235
      <ContactsModal
236
        show={showModal}
237
        setConversation={(url) => setPendingConversation(url)}
238
      />
239
      <NotificationAlert />
240
    </>
241
  )
242
}
243
 
244
export default Chat