refactor: mais 7 conexoes movidas para conexao ws global

websocket
willian-pessoa 2024-05-09 15:31:30 -03:00
parent 4d3cab5333
commit 5981f9dd5e
7 changed files with 109 additions and 85 deletions

View File

@ -3,8 +3,8 @@ import React, { useState, useEffect, useRef, useContext } from "react"
import * as Yup from "yup" import * as Yup from "yup"
import { Formik, Form, Field } from "formik" import { Formik, Form, Field } from "formik"
import { toast } from "react-toastify" import { toast } from "react-toastify"
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from "../../services/socket"
import { import {
makeStyles, makeStyles,
@ -51,8 +51,8 @@ const useStyles = makeStyles((theme) => ({
})) }))
const PositionSchema = Yup.object().shape({ const PositionSchema = Yup.object().shape({
name: Yup.string() name: Yup.string()
.required("Required"), .required("Required"),
}) })
const PositionModal = ({ const PositionModal = ({
@ -66,14 +66,14 @@ const PositionModal = ({
const isMounted = useRef(true) const isMounted = useRef(true)
const initialState = { const initialState = {
name: "", name: "",
} }
const [position, setPosition] = useState(initialState) const [position, setPosition] = useState(initialState)
// const [selectedQueueIds, setSelectedQueueIds] = useState([]) // const [selectedQueueIds, setSelectedQueueIds] = useState([])
const { setting } = useContext(AuthContext) const { setting } = useContext(AuthContext)
const [settings, setSettings] = useState(setting) const [settings, setSettings] = useState(setting)
useEffect(() => { useEffect(() => {
return () => { return () => {
@ -87,9 +87,9 @@ const PositionModal = ({
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('settings', (data) => { const onSettingsPosition = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -98,10 +98,12 @@ const PositionModal = ({
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsPosition)
return () => { return () => {
socket.disconnect() socket.off("settings", onSettingsPosition)
} }
}, []) }, [])
@ -141,7 +143,7 @@ const PositionModal = ({
const handleSavePosition = async (values) => { const handleSavePosition = async (values) => {
try { try {
if (positionId) { if (positionId) {
await api.put(`/positions/${positionId}`, values) await api.put(`/positions/${positionId}`, values)
handleClose() handleClose()
@ -154,7 +156,7 @@ const PositionModal = ({
handleClose() handleClose()
toast.success("Cargo salvo com sucesso") toast.success("Cargo salvo com sucesso")
} }
} catch (err) { } catch (err) {
toastError(err) toastError(err)
} }
@ -201,7 +203,7 @@ const PositionModal = ({
className={classes.textField} className={classes.textField}
fullWidth fullWidth
/> />
</div> </div>
{/* <div> {/* <div>
{ {
((settings && getSettingValue('quickAnswerByQueue') === 'enabled')) && ( ((settings && getSettingValue('quickAnswerByQueue') === 'enabled')) && (

View File

@ -1,6 +1,8 @@
import React, { useEffect, useState, useContext } from "react"; import React, { useEffect, useState, useContext } from "react";
import QRCode from "qrcode.react"; import QRCode from "qrcode.react";
import openSocket from "socket.io-client"; //import openSocket from "socket.io-client";
import { socket } from "../../services/socket";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
import { Dialog, DialogContent, Paper, Typography } from "@material-ui/core"; import { Dialog, DialogContent, Paper, Typography } from "@material-ui/core";
@ -31,9 +33,9 @@ const QrcodeModal = ({ open, onClose, whatsAppId }) => {
useEffect(() => { useEffect(() => {
if (!whatsAppId) return; if (!whatsAppId) return;
const socket = openSocket(process.env.REACT_APP_BACKEND_URL); //const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("whatsappSession", data => { const onWhatsAppSessionQrCode = data => {
if (data.action === "update" && data.session.id === whatsAppId) { if (data.action === "update" && data.session.id === whatsAppId) {
setQrCode(data.session.qrcode); setQrCode(data.session.qrcode);
} }
@ -42,21 +44,23 @@ const QrcodeModal = ({ open, onClose, whatsAppId }) => {
onClose(); onClose();
} }
if (data.action === "error") { if (data.action === "error") {
console.log('user.profile: ', user.profile) console.log('user.profile: ', user.profile)
if(user.profile === 'master'){ if (user.profile === 'master') {
alert(data.msg) alert(data.msg)
} }
} }
}); }
socket.on("whatsappSession", onWhatsAppSessionQrCode);
return () => { return () => {
socket.disconnect(); socket.off("whatsappSession", onWhatsAppSessionQrCode);
}; };
}, [whatsAppId, onClose, user.profile]); }, [whatsAppId, onClose, user.profile]);

View File

@ -23,8 +23,8 @@ import { IconButton, InputAdornment } from "@material-ui/core"
import { Colorize } from "@material-ui/icons" import { Colorize } from "@material-ui/icons"
import { AuthContext } from '../../context/Auth/AuthContext' import { AuthContext } from '../../context/Auth/AuthContext'
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from "../../services/socket"
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
@ -92,9 +92,9 @@ const QueueModal = ({ open, onClose, queueId }) => {
}, [setting]) }, [setting])
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('settings', (data) => { const onSettingsQueueModal = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -103,10 +103,12 @@ const QueueModal = ({ open, onClose, queueId }) => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsQueueModal)
return () => { return () => {
socket.disconnect() socket.off("settings", onSettingsQueueModal)
} }
}, []) }, [])

View File

@ -3,8 +3,8 @@ import React, { useState, useEffect, useRef, useContext } from "react"
import * as Yup from "yup" import * as Yup from "yup"
import { Formik, Form, Field } from "formik" import { Formik, Form, Field } from "formik"
import { toast } from "react-toastify" import { toast } from "react-toastify"
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from "../../services/socket"
import { import {
makeStyles, makeStyles,
@ -79,7 +79,7 @@ const QuickAnswersModal = ({
const [quickAnswer, setQuickAnswer] = useState(initialState) const [quickAnswer, setQuickAnswer] = useState(initialState)
const [selectedQueueIds, setSelectedQueueIds] = useState([]) const [selectedQueueIds, setSelectedQueueIds] = useState([])
const { user, setting, getSettingValue } = useContext(AuthContext) const { user, setting, getSettingValue } = useContext(AuthContext)
const [settings, setSettings] = useState(setting) const [settings, setSettings] = useState(setting)
useEffect(() => { useEffect(() => {
return () => { return () => {
@ -92,18 +92,18 @@ const QuickAnswersModal = ({
}, [setting]) }, [setting])
useEffect(() => { useEffect(() => {
setSelectedQueueIds([]) setSelectedQueueIds([])
if (open && selectedQueueIds.length === 0 && !quickAnswerId) { if (open && selectedQueueIds.length === 0 && !quickAnswerId) {
setSelectedQueueIds(user.queues.map(q => q.id)) setSelectedQueueIds(user.queues.map(q => q.id))
} }
}, [open,]) }, [open,])
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('settings', (data) => { const onSettingsQuickAnswersModal = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -112,14 +112,16 @@ const QuickAnswersModal = ({
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsQuickAnswersModal)
return () => { return () => {
socket.disconnect() socket.off("settings", onSettingsQuickAnswersModal)
} }
}, []) }, [])
useEffect(() => { useEffect(() => {
// setSelectedQueueIds([]) // setSelectedQueueIds([])
@ -139,7 +141,7 @@ const QuickAnswersModal = ({
if (isMounted.current) { if (isMounted.current) {
setQuickAnswer(data) setQuickAnswer(data)
if (data?.queues) { if (data?.queues) {
const quickQueueIds = data.queues?.map((queue) => queue.id) const quickQueueIds = data.queues?.map((queue) => queue.id)
setSelectedQueueIds(quickQueueIds) setSelectedQueueIds(quickQueueIds)
} }

View File

@ -1,6 +1,7 @@
import React, { useState, useContext, useMemo, useEffect } from "react" import React, { useState, useContext, useMemo, useEffect } from "react"
import { useHistory } from "react-router-dom" import { useHistory } from "react-router-dom"
import openSocket from "socket.io-client" //import openSocket from "socket.io-client"
import { socket } from "../../services/socket"
import Button from "@material-ui/core/Button" import Button from "@material-ui/core/Button"
import Dialog from "@material-ui/core/Dialog" import Dialog from "@material-ui/core/Dialog"
@ -110,9 +111,9 @@ const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('settings', (data) => { const onSettingsTransferTicketModal = (data) => {
console.log('settings updated ----------------------------xxxxxxxxxxxx') console.log('settings updated ----------------------------xxxxxxxxxxxx')
if (data.action === 'update') { if (data.action === 'update') {
@ -123,10 +124,12 @@ const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsTransferTicketModal)
return () => { return () => {
socket.disconnect() socket.off("settings", onSettingsTransferTicketModal)
} }
}, []) }, [])
@ -194,7 +197,7 @@ const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
const { data } = await api.get(`/users/all`, { const { data } = await api.get(`/users/all`, {
params: { userId: user.id }, params: { userId: user.id },
}) })
setUsers(data.users) setUsers(data.users)
setQueuesByWhats(data.queues) setQueuesByWhats(data.queues)
setQueues(data.queues) setQueues(data.queues)
@ -228,7 +231,7 @@ const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
{i18n.t("transferTicketModal.title")} {i18n.t("transferTicketModal.title")}
</DialogTitle> </DialogTitle>
<DialogContent dividers > <DialogContent dividers >
<FormControl variant="outlined" className={classes.maxWidth} style={{marginBottom: '8px'}}> <FormControl variant="outlined" className={classes.maxWidth} style={{ marginBottom: '8px' }}>
{/* <InputLabel>{i18n.t("transferTicketModal.fieldQueueLabel")}</InputLabel> */} {/* <InputLabel>{i18n.t("transferTicketModal.fieldQueueLabel")}</InputLabel> */}
<InputLabel>{'Usuário'}</InputLabel> <InputLabel>{'Usuário'}</InputLabel>
@ -247,7 +250,7 @@ const TransferTicketModal = ({ modalOpen, onClose, ticketid }) => {
</MenuItem> </MenuItem>
))} ))}
</Select> </Select>
</FormControl> </FormControl>
<FormControl variant="outlined" className={classes.maxWidth}> <FormControl variant="outlined" className={classes.maxWidth}>
<InputLabel>{i18n.t("transferTicketModal.fieldQueuePlaceholder")}</InputLabel> <InputLabel>{i18n.t("transferTicketModal.fieldQueuePlaceholder")}</InputLabel>

View File

@ -1,7 +1,8 @@
import React, { useState, useCallback, useEffect, useReducer, useContext } from 'react' import React, { useState, useCallback, useEffect, useReducer, useContext } from 'react'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from '../../services/socket'
import { makeStyles } from '@material-ui/core/styles' import { makeStyles } from '@material-ui/core/styles'
import { green } from '@material-ui/core/colors' import { green } from '@material-ui/core/colors'
@ -13,11 +14,11 @@ import {
IconButton, IconButton,
Table, Table,
TableHead, TableHead,
Paper, Paper,
} from '@material-ui/core' } from '@material-ui/core'
import { import {
Edit, Edit,
DeleteOutline, DeleteOutline,
// Restore // Restore
} from '@material-ui/icons' } from '@material-ui/icons'
@ -26,7 +27,7 @@ import MainHeader from '../../components/MainHeader'
import MainHeaderButtonsWrapper from '../../components/MainHeaderButtonsWrapper' import MainHeaderButtonsWrapper from '../../components/MainHeaderButtonsWrapper'
import Title from '../../components/Title' import Title from '../../components/Title'
import TableRowSkeleton from '../../components/TableRowSkeleton' import TableRowSkeleton from '../../components/TableRowSkeleton'
import CampaignModal from '../../components/CampaignModal' import CampaignModal from '../../components/CampaignModal'
import ConfirmationModal from '../../components/ConfirmationModal' import ConfirmationModal from '../../components/ConfirmationModal'
import QrcodeModal from '../../components/QrcodeModal' import QrcodeModal from '../../components/QrcodeModal'
@ -51,7 +52,7 @@ const reducer = (state, action) => {
const campaigns = action.payload const campaigns = action.payload
return [...state, ...campaigns] return [...state, ...campaigns]
} }
if (action.type === "UPDATE_CAMPAIGNS") { if (action.type === "UPDATE_CAMPAIGNS") {
const campaign = action.payload const campaign = action.payload
const campaignIndex = state.findIndex((c) => c.id === campaign.id) const campaignIndex = state.findIndex((c) => c.id === campaign.id)
@ -109,7 +110,7 @@ const useStyles = makeStyles((theme) => ({
buttonProgress: { buttonProgress: {
color: green[500], color: green[500],
}, },
})) }))
const Campaign = () => { const Campaign = () => {
//-------- //--------
@ -124,7 +125,7 @@ const Campaign = () => {
const [qrModalOpen, setQrModalOpen] = useState(false) const [qrModalOpen, setQrModalOpen] = useState(false)
const [selectedCampaign, setSelectedCampaign] = useState(null) const [selectedCampaign, setSelectedCampaign] = useState(null)
const [confirmModalOpen, setConfirmModalOpen] = useState(false) const [confirmModalOpen, setConfirmModalOpen] = useState(false)
const [campaigns, dispatch] = useReducer(reducer, []) const [campaigns, dispatch] = useReducer(reducer, [])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
@ -152,7 +153,7 @@ const Campaign = () => {
const delayDebounceFn = setTimeout(() => { const delayDebounceFn = setTimeout(() => {
const fetchContacts = async () => { const fetchContacts = async () => {
try { try {
const { data } = await apiBroker.get('/campaign', { const { data } = await apiBroker.get('/campaign', {
params: { params: {
@ -160,7 +161,7 @@ const Campaign = () => {
baseURL: process.env.REACT_APP_BACKEND_URL_PRIVATE, baseURL: process.env.REACT_APP_BACKEND_URL_PRIVATE,
identifier: 'campaign' identifier: 'campaign'
} }
}) })
dispatch({ type: "LOAD_CAMPAIGNS", payload: data.campaign }) dispatch({ type: "LOAD_CAMPAIGNS", payload: data.campaign })
setLoading(false) setLoading(false)
@ -174,7 +175,7 @@ const Campaign = () => {
}, 500) }, 500)
return () => clearTimeout(delayDebounceFn) return () => clearTimeout(delayDebounceFn)
}, [user.id]) }, [user.id])
const handleOpenCampaignModal = () => { const handleOpenCampaignModal = () => {
setSelectedCampaign(null) setSelectedCampaign(null)
@ -184,12 +185,12 @@ const Campaign = () => {
const handleCloseCampaignModal = useCallback(() => { const handleCloseCampaignModal = useCallback(() => {
setCampaignModalOpen(false) setCampaignModalOpen(false)
setSelectedCampaign(null) setSelectedCampaign(null)
}, [setSelectedCampaign, setCampaignModalOpen]) }, [setSelectedCampaign, setCampaignModalOpen])
const handleStart = async (campaign) => { const handleStart = async (campaign) => {
try { try {
const { data } = await apiBroker.post(`/campaign/start/${campaign.id}`) const { data } = await apiBroker.post(`/campaign/start/${campaign.id}`)
dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign }) dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign })
@ -200,10 +201,10 @@ const Campaign = () => {
} }
} }
const handleStop = async (campaign) => { const handleStop = async (campaign) => {
try { try {
const { data } = await apiBroker.post(`/campaign/stop/${campaign.id}`) const { data } = await apiBroker.post(`/campaign/stop/${campaign.id}`)
dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign }) dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign })
@ -245,7 +246,7 @@ const Campaign = () => {
setConfirmModalOpen(true) setConfirmModalOpen(true)
} }
const handleSubmitConfirmationModal = async () => { const handleSubmitConfirmationModal = async () => {
if (confirmModalInfo.action === 'delete') { if (confirmModalInfo.action === 'delete') {
try { try {
@ -293,13 +294,12 @@ const Campaign = () => {
)} )}
</> </>
) )
} }
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
const onContactsBulkCampaing = (data) => {
socket.on("contactsBulkInsertOnQueueStatus", (data) => {
if (data.action === 'update') { if (data.action === 'update') {
if (String(data.insertOnQueue.adminId) === String(user.id)) { if (String(data.insertOnQueue.adminId) === String(user.id)) {
@ -312,19 +312,24 @@ const Campaign = () => {
} }
} }
}) }
socket.on('campaign', (data) => { socket.on("contactsBulkInsertOnQueueStatus", onContactsBulkCampaing)
const onCampaignCampaign = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign }) dispatch({ type: "UPDATE_CAMPAIGNS", payload: data.campaign })
} }
}) }
socket.on('campaign', onCampaignCampaign)
return () => { return () => {
socket.disconnect() socket.off("campaign", onCampaignCampaign)
socket.off("contactsBulkInsertOnQueueStatus", onContactsBulkCampaing)
} }
}, [user.id]) }, [user.id])

View File

@ -2,7 +2,8 @@ import React, { useState, useCallback, useEffect, useContext } from 'react'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { format, parseISO } from 'date-fns' import { format, parseISO } from 'date-fns'
import openSocket from 'socket.io-client' //import openSocket from 'socket.io-client'
import { socket } from '../../services/socket'
import { makeStyles } from '@material-ui/core/styles' import { makeStyles } from '@material-ui/core/styles'
import { green, red, yellow, grey } from '@material-ui/core/colors' import { green, red, yellow, grey } from '@material-ui/core/colors'
@ -144,7 +145,7 @@ const Connections = () => {
const [selectedWhatsApp, setSelectedWhatsApp] = useState(null) const [selectedWhatsApp, setSelectedWhatsApp] = useState(null)
const [confirmModalOpen, setConfirmModalOpen] = useState(false) const [confirmModalOpen, setConfirmModalOpen] = useState(false)
const [diskSpaceInfo, setDiskSpaceInfo] = useState({}) const [diskSpaceInfo, setDiskSpaceInfo] = useState({})
const [settings, setSettings] = useState([]) const [settings, setSettings] = useState([])
@ -388,7 +389,7 @@ const Connections = () => {
getSettingValue('whatsaAppCloudApi') === 'disabled') && ( getSettingValue('whatsaAppCloudApi') === 'disabled') && (
<CustomToolTip title={'Whatsapp Cloud API está desativado'}> <CustomToolTip title={'Whatsapp Cloud API está desativado'}>
<FiberManualRecord style={{ color: grey[500] }} /> <FiberManualRecord style={{ color: grey[500] }} />
</CustomToolTip> </CustomToolTip>
)} )}
{whatsApp.status === 'OPENING' && !whatsApp.isOfficial && ( {whatsApp.status === 'OPENING' && !whatsApp.isOfficial && (
<CircularProgress size={24} className={classes.buttonProgress} /> <CircularProgress size={24} className={classes.buttonProgress} />
@ -433,7 +434,7 @@ const Connections = () => {
try { try {
await api.post(`/restartwhatsappsession/0`, { await api.post(`/restartwhatsappsession/0`, {
params: { status: 'status' }, params: { status: 'status' },
}) })
setClicks((buttons) => setClicks((buttons) =>
buttons.map((e) => { buttons.map((e) => {
@ -451,15 +452,17 @@ const Connections = () => {
}, []) }, [])
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) //const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('diskSpaceMonit', (data) => { const onDiskSpaceMonitConnections = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setDiskSpaceInfo(data.diskSpace) setDiskSpaceInfo(data.diskSpace)
} }
}) }
socket.on('settings', (data) => { socket.on('diskSpaceMonit', onDiskSpaceMonitConnections)
const onSettingsConnections = (data) => {
if (data.action === 'update') { if (data.action === 'update') {
setSettings((prevState) => { setSettings((prevState) => {
const aux = [...prevState] const aux = [...prevState]
@ -468,10 +471,13 @@ const Connections = () => {
return aux return aux
}) })
} }
}) }
socket.on('settings', onSettingsConnections)
return () => { return () => {
socket.disconnect() socket.off("settings", onSettingsConnections)
socket.off("diskSpaceMonit", onDiskSpaceMonitConnections)
} }
}, []) }, [])