customização para editar ura e filas

pull/21/head
adriano 2023-07-20 12:30:26 -03:00
parent 92f7d8b4db
commit 21ce9e1825
13 changed files with 1563 additions and 1407 deletions

View File

@ -7,9 +7,9 @@ import UpdateSettingService from "../services/SettingServices/UpdateSettingServi
import ListSettingsService from "../services/SettingServices/ListSettingsService";
export const index = async (req: Request, res: Response): Promise<Response> => {
if (req.user.profile !== "master") {
throw new AppError("ERR_NO_PERMISSION", 403);
}
// if (req.user.profile !== "master") {
// throw new AppError("ERR_NO_PERMISSION", 403);
// }
const settings = await ListSettingsService();

View File

@ -0,0 +1,22 @@
import { QueryInterface } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.bulkInsert(
"Settings",
[
{
key: "editURA",
value: "enabled",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface: QueryInterface) => {
return queryInterface.bulkDelete("Settings", {});
}
};

View File

@ -0,0 +1,22 @@
import { QueryInterface } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.bulkInsert(
"Settings",
[
{
key: "editQueue",
value: "enabled",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface: QueryInterface) => {
return queryInterface.bulkDelete("Settings", {});
}
};

View File

@ -5,9 +5,7 @@ import * as SettingController from "../controllers/SettingController";
const settingRoutes = Router();
settingRoutes.get("/settings", isAuth, SettingController.index);
settingRoutes.get("/settings", SettingController.index);
// routes.get("/settings/:settingKey", isAuth, SettingsController.show);

View File

@ -1,8 +1,14 @@
import StatusChatEnd from "../../models/StatusChatEnd";
import AppError from "../../errors/AppError";
const ShowStatusChatEndService = async (id: string | number): Promise<StatusChatEnd> => {
const status = await StatusChatEnd.findByPk(id, { attributes: ['id', 'name'], });
const ShowStatusChatEndService = async (
id: string | number
): Promise<StatusChatEnd> => {
const status = await StatusChatEnd.findByPk(id, {
attributes: ["id", "name"]
});
console.log(`---------------> statusChatEnd id: ${id}`);
if (!status) {
throw new AppError("ERR_NO_STATUS_FOUND", 404);

View File

@ -1,57 +1,54 @@
import React, { useState, useEffect } from "react";
import Routes from "./routes";
import "react-toastify/dist/ReactToastify.css";
import React, { useState, useEffect } from 'react'
import Routes from './routes'
import 'react-toastify/dist/ReactToastify.css'
import { createTheme, ThemeProvider } from "@material-ui/core/styles";
import { ptBR } from "@material-ui/core/locale";
import { createTheme, ThemeProvider } from '@material-ui/core/styles'
import { ptBR } from '@material-ui/core/locale'
import { TabTicketProvider } from "../src/context/TabTicketHeaderOption/TabTicketHeaderOption";
import { TabTicketProvider } from '../src/context/TabTicketHeaderOption/TabTicketHeaderOption'
const App = () => {
const [locale, setLocale] = useState();
const [locale, setLocale] = useState()
const theme = createTheme(
{
scrollbarStyles: {
"&::-webkit-scrollbar": {
width: "8px",
height: "8px",
'&::-webkit-scrollbar': {
width: '8px',
height: '8px',
},
"&::-webkit-scrollbar-thumb": {
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
'&::-webkit-scrollbar-thumb': {
boxShadow: 'inset 0 0 6px rgba(0, 0, 0, 0.3)',
backgroundColor: "#e8e8e8",
backgroundColor: '#e8e8e8',
},
},
palette: {
//primary: { main: "#2576d2" },
primary: { main: "#ec5114" },
primary: { main: '#ec5114' },
},
},
locale
);
)
useEffect(() => {
const i18nlocale = localStorage.getItem("i18nextLng");
const i18nlocale = localStorage.getItem('i18nextLng')
const browserLocale =
i18nlocale.substring(0, 2) + i18nlocale.substring(3, 5);
i18nlocale.substring(0, 2) + i18nlocale.substring(3, 5)
if (browserLocale === "ptBR") {
setLocale(ptBR);
if (browserLocale === 'ptBR') {
setLocale(ptBR)
}
}, []);
}, [])
return (
<ThemeProvider theme={theme}>
{/*TabTicketProvider Context to manipulate the entire state of selected option from user click on tickets options header */}
<TabTicketProvider>
<Routes />
</TabTicketProvider>
</ThemeProvider>
);
};
)
}
export default App;
export default App

View File

@ -1,10 +1,13 @@
import React, { useState, useEffect } from "react";
import * as Yup from "yup";
import { Formik, Form, Field } from "formik";
import { toast } from "react-toastify";
import React, { useState, useEffect, useContext } from 'react'
import * as Yup from 'yup'
import { Formik, Form, Field } from 'formik'
import { toast } from 'react-toastify'
import { makeStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import { makeStyles } from '@material-ui/core/styles'
import { green } from '@material-ui/core/colors'
import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can'
import {
Dialog,
@ -16,114 +19,119 @@ import {
TextField,
Switch,
FormControlLabel,
} from "@material-ui/core";
} from '@material-ui/core'
import api from "../../services/api";
import { i18n } from "../../translate/i18n";
import toastError from "../../errors/toastError";
import QueueSelect from "../QueueSelect";
import api from '../../services/api'
import { i18n } from '../../translate/i18n'
import toastError from '../../errors/toastError'
import QueueSelect from '../QueueSelect'
const useStyles = makeStyles(theme => ({
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
flexWrap: "wrap",
display: 'flex',
flexWrap: 'wrap',
},
multFieldLine: {
display: "flex",
"& > *:not(:last-child)": {
display: 'flex',
'& > *:not(:last-child)': {
marginRight: theme.spacing(1),
},
},
btnWrapper: {
position: "relative",
position: 'relative',
},
buttonProgress: {
color: green[500],
position: "absolute",
top: "50%",
left: "50%",
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
},
}));
}))
const SessionSchema = Yup.object().shape({
name: Yup.string()
.min(2, "Too Short!")
.max(100, "Too Long!")
.required("Required"),
});
.min(2, 'Too Short!')
.max(100, 'Too Long!')
.required('Required'),
})
const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
const classes = useStyles();
const classes = useStyles()
const initialState = {
name: "",
urlApi: "",
url: "",
greetingMessage: "",
farewellMessage: "",
name: '',
urlApi: '',
url: '',
greetingMessage: '',
farewellMessage: '',
isDefault: false,
};
const [whatsApp, setWhatsApp] = useState(initialState);
const [selectedQueueIds, setSelectedQueueIds] = useState([]);
}
const { user } = useContext(AuthContext)
const [whatsApp, setWhatsApp] = useState(initialState)
const [selectedQueueIds, setSelectedQueueIds] = useState([])
useEffect(() => {
const fetchSession = async () => {
if (!whatsAppId) return;
if (!whatsAppId) return
try {
const { data } = await api.get(`whatsapp/${whatsAppId}`);
setWhatsApp(data);
const { data } = await api.get(`whatsapp/${whatsAppId}`)
setWhatsApp(data)
const whatsQueueIds = data.queues?.map(queue => queue.id);
setSelectedQueueIds(whatsQueueIds);
const whatsQueueIds = data.queues?.map((queue) => queue.id)
setSelectedQueueIds(whatsQueueIds)
} catch (err) {
toastError(err);
toastError(err)
}
};
fetchSession();
}, [whatsAppId]);
}
fetchSession()
}, [whatsAppId])
const handleSaveWhatsApp = async values => {
const whatsappData = { ...values, queueIds: selectedQueueIds };
const handleSaveWhatsApp = async (values) => {
const whatsappData = { ...values, queueIds: selectedQueueIds }
let response = null
try {
if (whatsAppId) {
response = await api.put(`/whatsapp/${whatsAppId}`, whatsappData);
response = await api.put(`/whatsapp/${whatsAppId}`, whatsappData)
} else {
response = await api.post("/whatsapp", whatsappData);
response = await api.post('/whatsapp', whatsappData)
}
console.log('response: ', response.data.message)
if (response && response.data.message === 'wrong_number_start') {
alert('O numero contido no nome da conexão deve iniciar com o código do país!')
alert(
'O numero contido no nome da conexão deve iniciar com o código do país!'
)
} else if (response && response.data.message === 'invalid_phone_number') {
alert(
'A quantidade de numeros digitados no nome do contato é invalida! Certifique-se de que você digitou o numero correto acompanhado pelo código do país!'
)
} else if (response && response.data.message === 'no_phone_number') {
alert(
'Para criar/editar uma sessão de Whatsapp é necessário que o numero do Whatsapp acompanhado pelo código do país esteja presente no nome da sessão!'
)
} else {
toast.success(i18n.t('whatsappModal.success'))
handleClose()
}
else if(response && response.data.message === 'invalid_phone_number'){
alert('A quantidade de numeros digitados no nome do contato é invalida! Certifique-se de que você digitou o numero correto acompanhado pelo código do país!')
}
else if( response && response.data.message === 'no_phone_number'){
alert('Para criar/editar uma sessão de Whatsapp é necessário que o numero do Whatsapp acompanhado pelo código do país esteja presente no nome da sessão!')
}
else{
toast.success(i18n.t("whatsappModal.success"));
handleClose();
}
} catch (err) {
toastError(err);
toastError(err)
}
}
};
const handleClose = () => {
onClose();
setWhatsApp(initialState);
};
onClose()
setWhatsApp(initialState)
}
return (
<div className={classes.root}>
@ -136,8 +144,8 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
>
<DialogTitle>
{whatsAppId
? i18n.t("whatsappModal.title.edit")
: i18n.t("whatsappModal.title.add")}
? i18n.t('whatsappModal.title.edit')
: i18n.t('whatsappModal.title.add')}
</DialogTitle>
<Formik
initialValues={whatsApp}
@ -145,19 +153,23 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
validationSchema={SessionSchema}
onSubmit={(values, actions) => {
setTimeout(() => {
handleSaveWhatsApp(values);
actions.setSubmitting(false);
}, 400);
handleSaveWhatsApp(values)
actions.setSubmitting(false)
}, 400)
}}
>
{({ values, touched, errors, isSubmitting }) => (
<Form>
<DialogContent dividers>
<Can
role={user.profile}
perform="url-remote-session:show"
yes={() => (
<>
<div className={classes.multFieldLine}>
<Field
as={TextField}
label={i18n.t("whatsappModal.form.name")}
label={i18n.t('whatsappModal.form.name')}
autoFocus
name="name"
error={touched.name && Boolean(errors.name)}
@ -175,16 +187,13 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
checked={values.isDefault}
/>
}
label={i18n.t("whatsappModal.form.default")}
label={i18n.t('whatsappModal.form.default')}
/>
</div>
<div className={classes.multFieldLine}>
<Field
as={TextField}
label='url API'
label="url API"
autoFocus
name="urlApi"
error={touched.name && Boolean(errors.name)}
@ -195,7 +204,7 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
/>
<Field
as={TextField}
label='url session'
label="url session"
autoFocus
name="url"
error={touched.name && Boolean(errors.name)}
@ -205,12 +214,14 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
className={classes.textField}
/>
</div>
</>
)}
/>
<div>
<Field
as={TextField}
label={i18n.t("queueModal.form.greetingMessage")}
label={i18n.t('queueModal.form.greetingMessage')}
type="greetingMessage"
multiline
rows={5}
@ -227,11 +238,10 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
/>
</div>
<div>
<Field
as={TextField}
label={i18n.t("whatsappModal.form.farewellMessage")}
label={i18n.t('whatsappModal.form.farewellMessage')}
type="farewellMessage"
multiline
rows={5}
@ -249,7 +259,7 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
</div>
<QueueSelect
selectedQueueIds={selectedQueueIds}
onChange={selectedIds => setSelectedQueueIds(selectedIds)}
onChange={(selectedIds) => setSelectedQueueIds(selectedIds)}
/>
</DialogContent>
<DialogActions>
@ -259,7 +269,7 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
disabled={isSubmitting}
variant="outlined"
>
{i18n.t("whatsappModal.buttons.cancel")}
{i18n.t('whatsappModal.buttons.cancel')}
</Button>
<Button
type="submit"
@ -269,8 +279,8 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
className={classes.btnWrapper}
>
{whatsAppId
? i18n.t("whatsappModal.buttons.okEdit")
: i18n.t("whatsappModal.buttons.okAdd")}
? i18n.t('whatsappModal.buttons.okEdit')
: i18n.t('whatsappModal.buttons.okAdd')}
{isSubmitting && (
<CircularProgress
size={24}
@ -284,7 +294,7 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
</Formik>
</Dialog>
</div>
);
};
)
}
export default React.memo(WhatsAppModal);
export default React.memo(WhatsAppModal)

View File

@ -1,21 +1,22 @@
import React, { createContext } from "react";
import React, { createContext } from 'react'
import useAuth from "../../hooks/useAuth.js";
import useAuth from '../../hooks/useAuth.js'
const AuthContext = createContext();
const AuthContext = createContext()
const AuthProvider = ({ children }) => {
const { loading, user, isAuth, handleLogin, handleLogout } = useAuth();
const { loading, user, isAuth, handleLogin, handleLogout, setSetting } =
useAuth()
//{
return (
<AuthContext.Provider
value={{ loading, user, isAuth, handleLogin, handleLogout }}
value={{ loading, user, isAuth, handleLogin, handleLogout, setSetting }}
>
{children}
</AuthContext.Provider>
);
};
)
}
export { AuthContext, AuthProvider };
export { AuthContext, AuthProvider }

View File

@ -1,125 +1,158 @@
import { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import openSocket from "socket.io-client";
import { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import openSocket from 'socket.io-client'
import { toast } from "react-toastify";
import { toast } from 'react-toastify'
import { i18n } from "../../translate/i18n";
import api from "../../services/api";
import toastError from "../../errors/toastError";
import { i18n } from '../../translate/i18n'
import api from '../../services/api'
import toastError from '../../errors/toastError'
const useAuth = () => {
const history = useHistory();
const [isAuth, setIsAuth] = useState(false);
const [loading, setLoading] = useState(true);
const [user, setUser] = useState({});
const history = useHistory()
const [isAuth, setIsAuth] = useState(false)
const [loading, setLoading] = useState(true)
const [user, setUser] = useState({})
const [setting, setSetting] = useState({})
api.interceptors.request.use(
config => {
const token = localStorage.getItem("token");
(config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers["Authorization"] = `Bearer ${JSON.parse(token)}`;
setIsAuth(true);
config.headers['Authorization'] = `Bearer ${JSON.parse(token)}`
setIsAuth(true)
}
return config;
return config
},
error => {
Promise.reject(error);
(error) => {
Promise.reject(error)
}
);
)
api.interceptors.response.use(
response => {
return response;
(response) => {
return response
},
async error => {
const originalRequest = error.config;
async (error) => {
const originalRequest = error.config
if (error?.response?.status === 403 && !originalRequest._retry) {
originalRequest._retry = true;
originalRequest._retry = true
const { data } = await api.post("/auth/refresh_token");
const { data } = await api.post('/auth/refresh_token')
if (data) {
localStorage.setItem("token", JSON.stringify(data.token));
api.defaults.headers.Authorization = `Bearer ${data.token}`;
localStorage.setItem('token', JSON.stringify(data.token))
api.defaults.headers.Authorization = `Bearer ${data.token}`
}
return api(originalRequest);
return api(originalRequest)
}
if (error?.response?.status === 401) {
localStorage.removeItem("token");
api.defaults.headers.Authorization = undefined;
setIsAuth(false);
localStorage.removeItem('token')
api.defaults.headers.Authorization = undefined
setIsAuth(false)
}
return Promise.reject(error);
return Promise.reject(error)
}
);
)
useEffect(() => {
const token = localStorage.getItem("token");
(async () => {
const token = localStorage.getItem('token')
;(async () => {
if (token) {
try {
const { data } = await api.post("/auth/refresh_token");
api.defaults.headers.Authorization = `Bearer ${data.token}`;
setIsAuth(true);
setUser(data.user);
const { data } = await api.post('/auth/refresh_token')
api.defaults.headers.Authorization = `Bearer ${data.token}`
setIsAuth(true)
setUser(data.user)
} catch (err) {
toastError(err);
toastError(err)
}
}
setLoading(false);
})();
}, []);
setLoading(false)
})()
}, [])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("user", data => {
if (data.action === "update" && data.user.id === user.id) {
setUser(data.user);
const fetchSession = async () => {
try {
const { data } = await api.get('/settings')
setSetting(data)
} catch (err) {
toastError(err)
}
});
}
fetchSession()
}, [])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('user', (data) => {
if (data.action === 'update' && data.user.id === user.id) {
setUser(data.user)
}
})
socket.on('settings', (data) => {
if (data.action === 'update') {
setSetting((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
})
return () => {
socket.disconnect();
};
}, [user]);
socket.disconnect()
}
}, [user])
const handleLogin = async userData => {
setLoading(true);
const handleLogin = async (userData) => {
setLoading(true)
try {
const { data } = await api.post("/auth/login", userData);
localStorage.setItem("token", JSON.stringify(data.token));
api.defaults.headers.Authorization = `Bearer ${data.token}`;
setUser(data.user);
setIsAuth(true);
toast.success(i18n.t("auth.toasts.success"));
history.push("/tickets");
setLoading(false);
const { data } = await api.post('/auth/login', userData)
localStorage.setItem('token', JSON.stringify(data.token))
api.defaults.headers.Authorization = `Bearer ${data.token}`
setUser(data.user)
setIsAuth(true)
toast.success(i18n.t('auth.toasts.success'))
history.push('/tickets')
setLoading(false)
} catch (err) {
toastError(err);
setLoading(false);
toastError(err)
setLoading(false)
}
}
};
const handleLogout = async () => {
setLoading(true);
setLoading(true)
try {
await api.delete("/auth/logout");
setIsAuth(false);
setUser({});
localStorage.removeItem("token");
api.defaults.headers.Authorization = undefined;
setLoading(false);
history.push("/login");
await api.delete('/auth/logout')
setIsAuth(false)
setUser({})
localStorage.removeItem('token')
api.defaults.headers.Authorization = undefined
setLoading(false)
history.push('/login')
} catch (err) {
toastError(err);
setLoading(false);
toastError(err)
setLoading(false)
}
}
};
return { isAuth, user, loading, handleLogin, handleLogout };
};
return {
isAuth,
user,
loading,
handleLogin,
handleLogout,
setting,
setSetting,
}
}
export default useAuth;
export default useAuth

View File

@ -1,11 +1,11 @@
import React, { useState, useCallback, useEffect, useContext } from "react";
import { toast } from "react-toastify";
import { format, parseISO } from "date-fns";
import React, { useState, useCallback, useEffect, useContext } from 'react'
import { toast } from 'react-toastify'
import { format, parseISO } from 'date-fns'
import openSocket from "socket.io-client";
import openSocket from 'socket.io-client'
import { makeStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import { makeStyles } from '@material-ui/core/styles'
import { green } from '@material-ui/core/colors'
import {
Button,
TableBody,
@ -18,7 +18,7 @@ import {
Tooltip,
Typography,
CircularProgress,
} from "@material-ui/core";
} from '@material-ui/core'
import {
Edit,
CheckCircle,
@ -28,56 +28,55 @@ import {
CropFree,
DeleteOutline,
// Restore
} from "@material-ui/icons";
} from '@material-ui/icons'
import MainContainer from "../../components/MainContainer";
import MainHeader from "../../components/MainHeader";
import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper";
import Title from "../../components/Title";
import TableRowSkeleton from "../../components/TableRowSkeleton";
import MainContainer from '../../components/MainContainer'
import MainHeader from '../../components/MainHeader'
import MainHeaderButtonsWrapper from '../../components/MainHeaderButtonsWrapper'
import Title from '../../components/Title'
import TableRowSkeleton from '../../components/TableRowSkeleton'
import api from "../../services/api";
import WhatsAppModal from "../../components/WhatsAppModal";
import ConfirmationModal from "../../components/ConfirmationModal";
import QrcodeModal from "../../components/QrcodeModal";
import { i18n } from "../../translate/i18n";
import { WhatsAppsContext } from "../../context/WhatsApp/WhatsAppsContext";
import toastError from "../../errors/toastError";
import api from '../../services/api'
import WhatsAppModal from '../../components/WhatsAppModal'
import ConfirmationModal from '../../components/ConfirmationModal'
import QrcodeModal from '../../components/QrcodeModal'
import { i18n } from '../../translate/i18n'
import { WhatsAppsContext } from '../../context/WhatsApp/WhatsAppsContext'
import toastError from '../../errors/toastError'
//--------
import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can'
const useStyles = makeStyles(theme => ({
const useStyles = makeStyles((theme) => ({
mainPaper: {
flex: 1,
padding: theme.spacing(1),
overflowY: "scroll",
overflowY: 'scroll',
...theme.scrollbarStyles,
},
customTableCell: {
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
tooltip: {
backgroundColor: "#f5f5f9",
color: "rgba(0, 0, 0, 0.87)",
backgroundColor: '#f5f5f9',
color: 'rgba(0, 0, 0, 0.87)',
fontSize: theme.typography.pxToRem(14),
border: "1px solid #dadde9",
border: '1px solid #dadde9',
maxWidth: 450,
},
tooltipPopper: {
textAlign: "center",
textAlign: 'center',
},
buttonProgress: {
color: green[500],
},
}));
}))
const CustomToolTip = ({ title, content, children }) => {
const classes = useStyles();
const classes = useStyles()
return (
<Tooltip
@ -97,189 +96,195 @@ const CustomToolTip = ({ title, content, children }) => {
>
{children}
</Tooltip>
);
};
)
}
const Connections = () => {
//--------
const { user } = useContext(AuthContext);
const { user } = useContext(AuthContext)
const classes = useStyles()
const classes = useStyles();
const { whatsApps, loading } = useContext(WhatsAppsContext)
const [whatsAppModalOpen, setWhatsAppModalOpen] = useState(false)
const [qrModalOpen, setQrModalOpen] = useState(false)
const [selectedWhatsApp, setSelectedWhatsApp] = useState(null)
const [confirmModalOpen, setConfirmModalOpen] = useState(false)
const { whatsApps, loading } = useContext(WhatsAppsContext);
const [whatsAppModalOpen, setWhatsAppModalOpen] = useState(false);
const [qrModalOpen, setQrModalOpen] = useState(false);
const [selectedWhatsApp, setSelectedWhatsApp] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [diskSpaceInfo, setDiskSpaceInfo] = useState({})
const [diskSpaceInfo, setDiskSpaceInfo] = useState({});
const [disabled, setDisabled] = useState(true)
const [disabled, setDisabled] = useState(true);
const [settings, setSettings] = useState([])
const [buttons, setClicks] = useState([])
const confirmationModalInitialState = {
action: "",
title: "",
message: "",
whatsAppId: "",
action: '',
title: '',
message: '',
whatsAppId: '',
open: false,
};
}
const [confirmModalInfo, setConfirmModalInfo] = useState(
confirmationModalInitialState
);
)
const handleStartWhatsAppSession = async whatsAppId => {
useEffect(() => {
const fetchSession = async () => {
try {
await api.post(`/whatsappsession/${whatsAppId}`);
const { data } = await api.get('/settings')
setSettings(data)
} catch (err) {
toastError(err);
toastError(err)
}
};
}
fetchSession()
}, [])
const getSettingValue = (key) => {
const { value } = settings.find((s) => s.key === key)
return value
}
const handleRestartWhatsAppSession = async whatsapp => {
const handleStartWhatsAppSession = async (whatsAppId) => {
try {
await api.post(`/whatsappsession/${whatsAppId}`)
} catch (err) {
toastError(err)
}
}
const handleRestartWhatsAppSession = async (whatsapp) => {
try {
whatsapp.disabled = true
setClicks([...buttons, whatsapp.id])
function enable_button(whatsappId) {
setClicks(buttons => buttons.filter(id => { return +id !== +whatsappId }),);
setClicks((buttons) =>
buttons.filter((id) => {
return +id !== +whatsappId
})
)
}
setTimeout(enable_button, 25000, whatsapp.id)
await api.post(`/restartwhatsappsession/${whatsapp.id}`);
await api.post(`/restartwhatsappsession/${whatsapp.id}`)
} catch (err) {
toastError(err);
toastError(err)
}
}
};
useEffect(() => {
// whatsApps.map((e) => {
// if (buttons.includes(e.id)) {
// e.disabled = true
// }
// })
for (let i = 0; i < whatsApps.length; i++) {
if (buttons.includes(whatsApps[i].id)) {
whatsApps[i].disabled = true
}
}
}, [whatsApps, buttons])
const handleRequestNewQrCode = async whatsAppId => {
const handleRequestNewQrCode = async (whatsAppId) => {
try {
await api.put(`/whatsappsession/${whatsAppId}`);
await api.put(`/whatsappsession/${whatsAppId}`)
} catch (err) {
toastError(err);
toastError(err)
}
}
};
const handleOpenWhatsAppModal = () => {
setSelectedWhatsApp(null);
setWhatsAppModalOpen(true);
};
setSelectedWhatsApp(null)
setWhatsAppModalOpen(true)
}
const handleCloseWhatsAppModal = useCallback(() => {
setWhatsAppModalOpen(false);
setSelectedWhatsApp(null);
}, [setSelectedWhatsApp, setWhatsAppModalOpen]);
setWhatsAppModalOpen(false)
setSelectedWhatsApp(null)
}, [setSelectedWhatsApp, setWhatsAppModalOpen])
const handleOpenQrModal = whatsApp => {
setSelectedWhatsApp(whatsApp);
setQrModalOpen(true);
};
const handleOpenQrModal = (whatsApp) => {
setSelectedWhatsApp(whatsApp)
setQrModalOpen(true)
}
const handleCloseQrModal = useCallback(() => {
setSelectedWhatsApp(null);
setQrModalOpen(false);
}, [setQrModalOpen, setSelectedWhatsApp]);
setSelectedWhatsApp(null)
setQrModalOpen(false)
}, [setQrModalOpen, setSelectedWhatsApp])
const handleEditWhatsApp = whatsApp => {
setSelectedWhatsApp(whatsApp);
setWhatsAppModalOpen(true);
};
const handleEditWhatsApp = (whatsApp) => {
setSelectedWhatsApp(whatsApp)
setWhatsAppModalOpen(true)
}
const handleOpenConfirmationModal = (action, whatsAppId) => {
if (action === "disconnect") {
if (action === 'disconnect') {
setConfirmModalInfo({
action: action,
title: i18n.t("connections.confirmationModal.disconnectTitle"),
message: i18n.t("connections.confirmationModal.disconnectMessage"),
title: i18n.t('connections.confirmationModal.disconnectTitle'),
message: i18n.t('connections.confirmationModal.disconnectMessage'),
whatsAppId: whatsAppId,
});
})
}
if (action === "delete") {
if (action === 'delete') {
setConfirmModalInfo({
action: action,
title: i18n.t("connections.confirmationModal.deleteTitle"),
message: i18n.t("connections.confirmationModal.deleteMessage"),
title: i18n.t('connections.confirmationModal.deleteTitle'),
message: i18n.t('connections.confirmationModal.deleteMessage'),
whatsAppId: whatsAppId,
});
})
}
setConfirmModalOpen(true)
}
setConfirmModalOpen(true);
};
const handleSubmitConfirmationModal = async () => {
if (confirmModalInfo.action === "disconnect") {
if (confirmModalInfo.action === 'disconnect') {
try {
await api.delete(`/whatsappsession/${confirmModalInfo.whatsAppId}`);
await api.delete(`/whatsappsession/${confirmModalInfo.whatsAppId}`)
} catch (err) {
toastError(err);
toastError(err)
}
}
if (confirmModalInfo.action === "delete") {
if (confirmModalInfo.action === 'delete') {
try {
await api.delete(`/whatsapp/${confirmModalInfo.whatsAppId}`);
toast.success(i18n.t("connections.toasts.deleted"));
await api.delete(`/whatsapp/${confirmModalInfo.whatsAppId}`)
toast.success(i18n.t('connections.toasts.deleted'))
} catch (err) {
toastError(err);
toastError(err)
}
}
setConfirmModalInfo(confirmationModalInitialState);
};
setConfirmModalInfo(confirmationModalInitialState)
}
const renderActionButtons = whatsApp => {
const renderActionButtons = (whatsApp) => {
return (
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<>
{whatsApp.status === "qrcode" && (
{whatsApp.status === 'qrcode' && (
<Button
size="small"
variant="contained"
color="primary"
onClick={() => handleOpenQrModal(whatsApp)}
>
{i18n.t("connections.buttons.qrcode")}
{i18n.t('connections.buttons.qrcode')}
</Button>
)}
{whatsApp.status === "DISCONNECTED" && (
{whatsApp.status === 'DISCONNECTED' && (
<>
<Button
size="small"
@ -287,76 +292,74 @@ const Connections = () => {
color="primary"
onClick={() => handleStartWhatsAppSession(whatsApp.id)}
>
{i18n.t("connections.buttons.tryAgain")}
</Button>{" "}
{i18n.t('connections.buttons.tryAgain')}
</Button>{' '}
<Button
size="small"
variant="outlined"
color="secondary"
onClick={() => handleRequestNewQrCode(whatsApp.id)}
>
{i18n.t("connections.buttons.newQr")}
{i18n.t('connections.buttons.newQr')}
</Button>
</>
)}
{(whatsApp.status === "CONNECTED" ||
whatsApp.status === "PAIRING" ||
whatsApp.status === "TIMEOUT") && (
{(whatsApp.status === 'CONNECTED' ||
whatsApp.status === 'PAIRING' ||
whatsApp.status === 'TIMEOUT') && (
<Button
size="small"
variant="outlined"
color="secondary"
onClick={() => {
handleOpenConfirmationModal("disconnect", whatsApp.id);
handleOpenConfirmationModal('disconnect', whatsApp.id)
}}
>
{i18n.t("connections.buttons.disconnect")}
{i18n.t('connections.buttons.disconnect')}
</Button>
)}
{whatsApp.status === "OPENING" && (
{whatsApp.status === 'OPENING' && (
<Button size="small" variant="outlined" disabled color="default">
{i18n.t("connections.buttons.connecting")}
{i18n.t('connections.buttons.connecting')}
</Button>
)}
</>
)}
/>
)
}
);
};
const renderStatusToolTips = whatsApp => {
const renderStatusToolTips = (whatsApp) => {
return (
<div className={classes.customTableCell}>
{whatsApp.status === "DISCONNECTED" && (
{whatsApp.status === 'DISCONNECTED' && (
<CustomToolTip
title={i18n.t("connections.toolTips.disconnected.title")}
content={i18n.t("connections.toolTips.disconnected.content")}
title={i18n.t('connections.toolTips.disconnected.title')}
content={i18n.t('connections.toolTips.disconnected.content')}
>
<SignalCellularConnectedNoInternet0Bar color="secondary" />
</CustomToolTip>
)}
{whatsApp.status === "OPENING" && (
{whatsApp.status === 'OPENING' && (
<CircularProgress size={24} className={classes.buttonProgress} />
)}
{whatsApp.status === "qrcode" && (
{whatsApp.status === 'qrcode' && (
<CustomToolTip
title={i18n.t("connections.toolTips.qrcode.title")}
content={i18n.t("connections.toolTips.qrcode.content")}
title={i18n.t('connections.toolTips.qrcode.title')}
content={i18n.t('connections.toolTips.qrcode.content')}
>
<CropFree />
</CustomToolTip>
)}
{whatsApp.status === "CONNECTED" && (
<CustomToolTip title={i18n.t("connections.toolTips.connected.title")}>
{whatsApp.status === 'CONNECTED' && (
<CustomToolTip title={i18n.t('connections.toolTips.connected.title')}>
<SignalCellular4Bar style={{ color: green[500] }} />
</CustomToolTip>
)}
{(whatsApp.status === "TIMEOUT" || whatsApp.status === "PAIRING") && (
{(whatsApp.status === 'TIMEOUT' || whatsApp.status === 'PAIRING') && (
<CustomToolTip
title={i18n.t("connections.toolTips.timeout.title")}
content={i18n.t("connections.toolTips.timeout.content")}
title={i18n.t('connections.toolTips.timeout.title')}
content={i18n.t('connections.toolTips.timeout.content')}
>
<SignalCellularConnectedNoInternet2Bar color="secondary" />
</CustomToolTip>
@ -371,62 +374,65 @@ const Connections = () => {
</CustomToolTip>
)} */}
</div>
);
};
)
}
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
await api.post(`/restartwhatsappsession/0`, { params: { status: 'status' }, });
await api.post(`/restartwhatsappsession/0`, {
params: { status: 'status' },
})
setDisabled(false)
setClicks(buttons => buttons.map((e) => { return { id: e.id, disabled: false } }))
setClicks((buttons) =>
buttons.map((e) => {
return { id: e.id, disabled: false }
})
)
} catch (err) {
console.log(err);
console.log(err)
}
}
};
fetchQueries();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, []);
fetchQueries()
}, 500)
return () => clearTimeout(delayDebounceFn)
}, [])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("diskSpaceMonit", data => {
if (data.action === "update") {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('diskSpaceMonit', (data) => {
if (data.action === 'update') {
setDiskSpaceInfo(data.diskSpace)
}
});
})
socket.on('settings', (data) => {
if (data.action === 'update') {
setSettings((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
})
return () => {
socket.disconnect();
};
}, []);
socket.disconnect()
}
}, [])
return (
<Can
role={user.profile}
perform="connections-view:show"
yes={() => (
<MainContainer>
<ConfirmationModal
title={confirmModalInfo.title}
open={confirmModalOpen}
@ -436,7 +442,6 @@ const Connections = () => {
{confirmModalInfo.message}
</ConfirmationModal>
<QrcodeModal
open={qrModalOpen}
onClose={handleCloseQrModal}
@ -450,32 +455,28 @@ const Connections = () => {
/>
<MainHeader>
<Title>{i18n.t("connections.title")}</Title>
<Title>{i18n.t('connections.title')}</Title>
<MainHeaderButtonsWrapper>
<Can
role={user.profile}
perform="btn-add-whatsapp" updatedAt
perform="btn-add-whatsapp"
updatedAt
yes={() => (
<Button
variant="contained"
color="primary"
onClick={handleOpenWhatsAppModal}>
{i18n.t("connections.buttons.add")}
onClick={handleOpenWhatsAppModal}
>
{i18n.t('connections.buttons.add')}
</Button>
)}
/>
</MainHeaderButtonsWrapper>
</MainHeader>
<Paper className={classes.mainPaper} variant="outlined">
<>
<Can
role={user.profile}
perform="space-disk-info:show"
@ -484,27 +485,27 @@ const Connections = () => {
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
Size
</TableCell>
<TableCell align="center">
Used
</TableCell>
<TableCell align="center">
Available
</TableCell>
<TableCell align="center">
Use%
</TableCell>
<TableCell align="center">Size</TableCell>
<TableCell align="center">Used</TableCell>
<TableCell align="center">Available</TableCell>
<TableCell align="center">Use%</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell align="center">{diskSpaceInfo.size}</TableCell>
<TableCell align="center">{diskSpaceInfo.used}</TableCell>
<TableCell align="center">{diskSpaceInfo.available}</TableCell>
<TableCell align="center">{diskSpaceInfo.use}</TableCell>
<TableCell align="center">
{diskSpaceInfo.size}
</TableCell>
<TableCell align="center">
{diskSpaceInfo.used}
</TableCell>
<TableCell align="center">
{diskSpaceInfo.available}
</TableCell>
<TableCell align="center">
{diskSpaceInfo.use}
</TableCell>
</TableRow>
</TableBody>
</Table>
@ -516,13 +517,12 @@ const Connections = () => {
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
{i18n.t("connections.table.name")}
{i18n.t('connections.table.name')}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.status")}
{i18n.t('connections.table.status')}
</TableCell>
<Can
@ -530,47 +530,33 @@ const Connections = () => {
perform="connection-button:show"
yes={() => (
<TableCell align="center">
{i18n.t("connections.table.session")}
{i18n.t('connections.table.session')}
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => <TableCell align="center">Restore</TableCell>}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Restore
</TableCell>
<TableCell align="center">Session MB</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Session MB
</TableCell>
)}
/>
<TableCell align="center">
{i18n.t("connections.table.lastUpdate")}
{i18n.t('connections.table.lastUpdate')}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.default")}
{i18n.t('connections.table.default')}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.actions")}
{i18n.t('connections.table.actions')}
</TableCell>
</TableRow>
</TableHead>
@ -580,9 +566,11 @@ const Connections = () => {
) : (
<>
{whatsApps?.length > 0 &&
whatsApps.map(whatsApp => (
whatsApps.map((whatsApp) => (
<TableRow key={whatsApp.id}>
<TableCell align="center">{whatsApp.name}</TableCell>
<TableCell align="center">
{whatsApp.name}
</TableCell>
<TableCell align="center">
{renderStatusToolTips(whatsApp)}
@ -598,36 +586,30 @@ const Connections = () => {
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<Button
disabled={whatsApp.disabled || disabled ? true : false}
disabled={
whatsApp.disabled || disabled
? true
: false
}
size="small"
variant="contained"
color="primary"
onClick={() => handleRestartWhatsAppSession(whatsApp)}
onClick={() =>
handleRestartWhatsAppSession(whatsApp)
}
>
Restore
</Button>
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
@ -635,7 +617,9 @@ const Connections = () => {
<TableCell align="center">
<CustomToolTip
title={'Informação da sessão em Megabytes'}
content={'Tamanho do diretorio da sessão atualizado a cada 5 segundos'}
content={
'Tamanho do diretorio da sessão atualizado a cada 5 segundos'
}
>
<div>{whatsApp.sessionSize}</div>
</CustomToolTip>
@ -643,15 +627,13 @@ const Connections = () => {
)}
/>
<TableCell align="center">
{format(parseISO(whatsApp.updatedAt), "dd/MM/yy HH:mm")}
{format(
parseISO(whatsApp.updatedAt),
'dd/MM/yy HH:mm'
)}
</TableCell>
<TableCell align="center">
{whatsApp.isDefault && (
<div className={classes.customTableCell}>
@ -660,38 +642,62 @@ const Connections = () => {
)}
</TableCell>
<TableCell align="center">
<Can
role={user.profile}
perform="show-icon-edit-whatsapp"
yes={() => (
// disabled={
// whatsApp.disabled || disabled
// ? true
// : false
// }
<div
style={{
margin: 0,
padding: 0,
border: 'none',
display: 'inline',
}}
>
{(settings &&
settings.length > 0 &&
getSettingValue('editURA') &&
getSettingValue('editURA') ===
'enabled') |
(user.profile === 'master') ? (
<IconButton
size="small"
onClick={() => handleEditWhatsApp(whatsApp)}
onClick={() =>
handleEditWhatsApp(whatsApp)
}
>
<Edit />
</IconButton>
) : (
<div></div>
)}
</div>
)}
/>
<Can
role={user.profile}
perform="btn-remove-whatsapp"
yes={() => (
<IconButton
size="small"
onClick={e => {
handleOpenConfirmationModal("delete", whatsApp.id);
onClick={(e) => {
handleOpenConfirmationModal(
'delete',
whatsApp.id
)
}}
>
<DeleteOutline />
</IconButton>
)}
/>
</TableCell>
</TableRow>
))}
@ -699,14 +705,12 @@ const Connections = () => {
)}
</TableBody>
</Table>
</>
</Paper>
</MainContainer>
)}
/>
)
}
);
};
export default Connections;
export default Connections

View File

@ -1,6 +1,6 @@
import React, { useEffect, useReducer, useState, useContext } from "react";
import React, { useEffect, useReducer, useState, useContext } from 'react'
import openSocket from "socket.io-client";
import openSocket from 'socket.io-client'
import {
Button,
@ -13,155 +13,186 @@ import {
TableHead,
TableRow,
Typography,
} from "@material-ui/core";
} from '@material-ui/core'
import MainContainer from "../../components/MainContainer";
import MainHeader from "../../components/MainHeader";
import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper";
import TableRowSkeleton from "../../components/TableRowSkeleton";
import Title from "../../components/Title";
import { i18n } from "../../translate/i18n";
import toastError from "../../errors/toastError";
import api from "../../services/api";
import { DeleteOutline, Edit } from "@material-ui/icons";
import QueueModal from "../../components/QueueModal";
import { toast } from "react-toastify";
import ConfirmationModal from "../../components/ConfirmationModal";
import MainContainer from '../../components/MainContainer'
import MainHeader from '../../components/MainHeader'
import MainHeaderButtonsWrapper from '../../components/MainHeaderButtonsWrapper'
import TableRowSkeleton from '../../components/TableRowSkeleton'
import Title from '../../components/Title'
import { i18n } from '../../translate/i18n'
import toastError from '../../errors/toastError'
import api from '../../services/api'
import { DeleteOutline, Edit } from '@material-ui/icons'
import QueueModal from '../../components/QueueModal'
import { toast } from 'react-toastify'
import ConfirmationModal from '../../components/ConfirmationModal'
import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can'
const useStyles = makeStyles((theme) => ({
mainPaper: {
flex: 1,
padding: theme.spacing(1),
overflowY: "scroll",
overflowY: 'scroll',
...theme.scrollbarStyles,
},
customTableCell: {
display: "flex",
alignItems: "center",
justifyContent: "center",
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
}));
}))
const reducer = (state, action) => {
if (action.type === "LOAD_QUEUES") {
const queues = action.payload;
const newQueues = [];
if (action.type === 'LOAD_QUEUES') {
const queues = action.payload
const newQueues = []
queues.forEach((queue) => {
const queueIndex = state.findIndex((q) => q.id === queue.id);
const queueIndex = state.findIndex((q) => q.id === queue.id)
if (queueIndex !== -1) {
state[queueIndex] = queue;
state[queueIndex] = queue
} else {
newQueues.push(queue);
newQueues.push(queue)
}
});
})
return [...state, ...newQueues];
return [...state, ...newQueues]
}
if (action.type === "UPDATE_QUEUES") {
const queue = action.payload;
const queueIndex = state.findIndex((u) => u.id === queue.id);
if (action.type === 'UPDATE_QUEUES') {
const queue = action.payload
const queueIndex = state.findIndex((u) => u.id === queue.id)
if (queueIndex !== -1) {
state[queueIndex] = queue;
return [...state];
state[queueIndex] = queue
return [...state]
} else {
return [queue, ...state];
return [queue, ...state]
}
}
if (action.type === "DELETE_QUEUE") {
const queueId = action.payload;
const queueIndex = state.findIndex((q) => q.id === queueId);
if (action.type === 'DELETE_QUEUE') {
const queueId = action.payload
const queueIndex = state.findIndex((q) => q.id === queueId)
if (queueIndex !== -1) {
state.splice(queueIndex, 1);
state.splice(queueIndex, 1)
}
return [...state];
return [...state]
}
if (action.type === "RESET") {
return [];
if (action.type === 'RESET') {
return []
}
}
};
const Queues = () => {
const classes = useStyles();
const classes = useStyles()
const { user } = useContext(AuthContext);
const { user } = useContext(AuthContext)
const [queues, dispatch] = useReducer(reducer, []);
const [loading, setLoading] = useState(false);
const [queues, dispatch] = useReducer(reducer, [])
const [loading, setLoading] = useState(false)
const [queueModalOpen, setQueueModalOpen] = useState(false);
const [selectedQueue, setSelectedQueue] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [queueModalOpen, setQueueModalOpen] = useState(false)
const [selectedQueue, setSelectedQueue] = useState(null)
const [confirmModalOpen, setConfirmModalOpen] = useState(false)
const [settings, setSettings] = useState([])
useEffect(() => {
(async () => {
setLoading(true);
;(async () => {
setLoading(true)
try {
const { data } = await api.get("/queue");
dispatch({ type: "LOAD_QUEUES", payload: data });
const { data } = await api.get('/queue')
dispatch({ type: 'LOAD_QUEUES', payload: data })
setLoading(false);
setLoading(false)
} catch (err) {
toastError(err);
setLoading(false);
toastError(err)
setLoading(false)
}
})();
}, []);
})()
}, [])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
const fetchSession = async () => {
try {
const { data } = await api.get('/settings')
setSettings(data)
} catch (err) {
toastError(err)
}
}
fetchSession()
}, [])
socket.on("queue", (data) => {
if (data.action === "update" || data.action === "create") {
dispatch({ type: "UPDATE_QUEUES", payload: data.queue });
const getSettingValue = (key) => {
const { value } = settings.find((s) => s.key === key)
return value
}
if (data.action === "delete") {
dispatch({ type: "DELETE_QUEUE", payload: data.queueId });
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('queue', (data) => {
if (data.action === 'update' || data.action === 'create') {
dispatch({ type: 'UPDATE_QUEUES', payload: data.queue })
}
});
if (data.action === 'delete') {
dispatch({ type: 'DELETE_QUEUE', payload: data.queueId })
}
})
socket.on('settings', (data) => {
if (data.action === 'update') {
setSettings((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
})
return () => {
socket.disconnect();
};
}, []);
socket.disconnect()
}
}, [])
const handleOpenQueueModal = () => {
setQueueModalOpen(true);
setSelectedQueue(null);
};
setQueueModalOpen(true)
setSelectedQueue(null)
}
const handleCloseQueueModal = () => {
setQueueModalOpen(false);
setSelectedQueue(null);
};
setQueueModalOpen(false)
setSelectedQueue(null)
}
const handleEditQueue = (queue) => {
setSelectedQueue(queue);
setQueueModalOpen(true);
};
setSelectedQueue(queue)
setQueueModalOpen(true)
}
const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false);
setSelectedQueue(null);
};
setConfirmModalOpen(false)
setSelectedQueue(null)
}
const handleDeleteQueue = async (queueId) => {
try {
await api.delete(`/queue/${queueId}`);
toast.success(i18n.t("Queue deleted successfully!"));
await api.delete(`/queue/${queueId}`)
toast.success(i18n.t('Queue deleted successfully!'))
} catch (err) {
toastError(err);
toastError(err)
}
setSelectedQueue(null)
}
setSelectedQueue(null);
};
return (
<Can
@ -172,14 +203,15 @@ const Queues = () => {
<ConfirmationModal
title={
selectedQueue &&
`${i18n.t("queues.confirmationModal.deleteTitle")} ${selectedQueue.name
`${i18n.t('queues.confirmationModal.deleteTitle')} ${
selectedQueue.name
}?`
}
open={confirmModalOpen}
onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteQueue(selectedQueue.id)}
>
{i18n.t("queues.confirmationModal.deleteMessage")}
{i18n.t('queues.confirmationModal.deleteMessage')}
</ConfirmationModal>
<QueueModal
open={queueModalOpen}
@ -187,8 +219,7 @@ const Queues = () => {
queueId={selectedQueue?.id}
/>
<MainHeader>
<Title>{i18n.t("queues.title")}</Title>
<Title>{i18n.t('queues.title')}</Title>
<Can
role={user.profile}
@ -200,29 +231,27 @@ const Queues = () => {
color="primary"
onClick={handleOpenQueueModal}
>
{i18n.t("queues.buttons.add")}
{i18n.t('queues.buttons.add')}
</Button>
</MainHeaderButtonsWrapper>
)}
/>
</MainHeader>
<Paper className={classes.mainPaper} variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
{i18n.t("queues.table.name")}
{i18n.t('queues.table.name')}
</TableCell>
<TableCell align="center">
{i18n.t("queues.table.color")}
{i18n.t('queues.table.color')}
</TableCell>
<TableCell align="center">
{i18n.t("queues.table.greeting")}
{i18n.t('queues.table.greeting')}
</TableCell>
<TableCell align="center">
{i18n.t("queues.table.actions")}
{i18n.t('queues.table.actions')}
</TableCell>
</TableRow>
</TableHead>
@ -238,7 +267,7 @@ const Queues = () => {
backgroundColor: queue.color,
width: 60,
height: 20,
alignSelf: "center",
alignSelf: 'center',
}}
/>
</div>
@ -246,7 +275,7 @@ const Queues = () => {
<TableCell align="center">
<div className={classes.customTableCell}>
<Typography
style={{ width: 300, align: "center" }}
style={{ width: 300, align: 'center' }}
noWrap
variant="body2"
>
@ -255,25 +284,44 @@ const Queues = () => {
</div>
</TableCell>
<TableCell align="center">
<Can
role={user.profile}
perform="show-icon-edit-queue"
yes={() => (
<div
style={{
margin: 0,
padding: 0,
border: 'none',
display: 'inline',
}}
>
{(settings &&
settings.length > 0 &&
getSettingValue('editQueue') &&
getSettingValue('editQueue') === 'enabled') |
(user.profile === 'master') ? (
<IconButton
size="small"
onClick={() => handleEditQueue(queue)}
>
<Edit />
</IconButton>
) : (
<div></div>
)}
</div>
// <IconButton
// size="small"
// onClick={() => handleEditQueue(queue)}
// >
// <Edit />
// </IconButton>
)}
/>
<Can
role={user.profile}
perform="show-icon-delete-queue"
@ -281,15 +329,14 @@ const Queues = () => {
<IconButton
size="small"
onClick={() => {
setSelectedQueue(queue);
setConfirmModalOpen(true);
setSelectedQueue(queue)
setConfirmModalOpen(true)
}}
>
<DeleteOutline />
</IconButton>
)}
/>
</TableCell>
</TableRow>
))}
@ -301,7 +348,7 @@ const Queues = () => {
</MainContainer>
)}
/>
);
};
)
}
export default Queues;
export default Queues

View File

@ -1,128 +1,125 @@
import React, { useState, useEffect, useContext} from "react";
import openSocket from "socket.io-client";
import React, { useState, useEffect, useContext } from 'react'
import openSocket from 'socket.io-client'
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Container from "@material-ui/core/Container";
import Select from "@material-ui/core/Select";
import { toast } from "react-toastify";
import { makeStyles } from '@material-ui/core/styles'
import Paper from '@material-ui/core/Paper'
import Typography from '@material-ui/core/Typography'
import Container from '@material-ui/core/Container'
import Select from '@material-ui/core/Select'
import { toast } from 'react-toastify'
import api from "../../services/api";
import { i18n } from "../../translate/i18n.js";
import toastError from "../../errors/toastError";
import api from '../../services/api'
import { i18n } from '../../translate/i18n.js'
import toastError from '../../errors/toastError'
//--------
import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can'
// import Button from "@material-ui/core/Button";
const useStyles = makeStyles(theme => ({
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
alignItems: "center",
display: 'flex',
alignItems: 'center',
padding: theme.spacing(4),
},
paper: {
padding: theme.spacing(2),
display: "flex",
alignItems: "center",
display: 'flex',
alignItems: 'center',
},
settingOption: {
marginLeft: "auto",
marginLeft: 'auto',
},
margin: {
margin: theme.spacing(1),
},
}));
}))
const Settings = () => {
const classes = useStyles();
const classes = useStyles()
//--------
const { user } = useContext(AuthContext);
const { user } = useContext(AuthContext)
const [settings, setSettings] = useState([]);
const [settings, setSettings] = useState([])
useEffect(() => {
const fetchSession = async () => {
try {
const { data } = await api.get("/settings");
setSettings(data);
const { data } = await api.get('/settings')
setSettings(data)
} catch (err) {
toastError(err);
toastError(err)
}
};
fetchSession();
}, []);
}
fetchSession()
}, [])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on("settings", data => {
if (data.action === "update") {
setSettings(prevState => {
const aux = [...prevState];
const settingIndex = aux.findIndex(s => s.key === data.setting.key);
aux[settingIndex].value = data.setting.value;
return aux;
});
socket.on('settings', (data) => {
console.log('settings updated ----------------------------')
if (data.action === 'update') {
setSettings((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
});
})
return () => {
socket.disconnect();
};
}, []);
socket.disconnect()
}
}, [])
const handleChangeSetting = async e => {
const selectedValue = e.target.value;
const settingKey = e.target.name;
useEffect(() => {
console.log('------> settings: ', settings)
}, [settings])
const handleChangeSetting = async (e) => {
const selectedValue = e.target.value
const settingKey = e.target.name
try {
await api.put(`/settings/${settingKey}`, {
value: selectedValue,
});
toast.success(i18n.t("settings.success"));
})
toast.success(i18n.t('settings.success'))
} catch (err) {
toastError(err);
toastError(err)
}
}
};
const getSettingValue = key => {
const { value } = settings.find(s => s.key === key);
return value;
};
const getSettingValue = (key) => {
const { value } = settings.find((s) => s.key === key)
// const handleEdit = () => {
//
// }
return value
}
return (
<Can
role={user.profile}
perform="settings-view:show"
yes={() => (
<div>
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Typography variant="body2" gutterBottom>
{i18n.t("settings.title")}
{i18n.t('settings.title')}
</Typography>
<Paper className={classes.paper}>
<Typography variant="body1">
{i18n.t("settings.settings.userCreation.name")}
{i18n.t('settings.settings.userCreation.name')}
</Typography>
<Select
@ -132,59 +129,79 @@ const Settings = () => {
id="userCreation-setting"
name="userCreation"
value={
settings && settings.length > 0 && getSettingValue("userCreation")
settings &&
settings.length > 0 &&
getSettingValue('userCreation')
}
className={classes.settingOption}
onChange={handleChangeSetting}
>
<option value="enabled">
{i18n.t("settings.settings.userCreation.options.enabled")}
{i18n.t('settings.settings.userCreation.options.enabled')}
</option>
<option value="disabled">
{i18n.t("settings.settings.userCreation.options.disabled")}
{i18n.t('settings.settings.userCreation.options.disabled')}
</option>
</Select>
</Paper>
</Container>
</div>
{/* <div className={classes.root}>
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Typography variant="body2" gutterBottom>
Application name
</Typography>
<Paper className={classes.paper}>
<Typography variant="body1">Editar ura</Typography>
<Typography variant="body1">
Estudio Face
</Typography>
<Button
<Select
margin="dense"
variant="outlined"
id="applicationName-setting"
name="applicationName"
color="primary"
onClick={(e) => handleEdit()}
native
id="editURA-setting"
name="editURA"
value={
settings &&
settings.length > 0 &&
getSettingValue('editURA')
}
className={classes.settingOption}
onChange={handleChangeSetting}
>
{"EDIT"}
</Button>
<option value="enabled">Ativado</option>
<option value="disabled">Desativado</option>
</Select>
</Paper>
</Container>
</div> */}
</div>
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Paper className={classes.paper}>
<Typography variant="body1">Editar fila</Typography>
<Select
margin="dense"
variant="outlined"
native
id="editQueue-setting"
name="editQueue"
value={
settings &&
settings.length > 0 &&
getSettingValue('editQueue')
}
className={classes.settingOption}
onChange={handleChangeSetting}
>
<option value="enabled">Ativado</option>
<option value="disabled">Desativado</option>
</Select>
</Paper>
</Container>
</div>
</div>
)}
/>
)
}
);
};
export default Settings;
export default Settings

View File

@ -5,55 +5,54 @@ const rules = {
admin: {
static: [
//"show-icon-edit-whatsapp",
"drawer-admin-items:view",
"tickets-manager:showall",
"user-modal:editProfile",
"user-modal:editQueues",
"ticket-options:deleteTicket",
"contacts-page:deleteContact",
"contacts-page:import-csv-contacts",
"connections-view:show",
"dashboard-view:show",
"queues-view:show",
"user-view:show",
"ticket-report:show",
'show-icon-edit-whatsapp',
'show-icon-edit-queue',
'drawer-admin-items:view',
'tickets-manager:showall',
'user-modal:editProfile',
'user-modal:editQueues',
'ticket-options:deleteTicket',
'contacts-page:deleteContact',
'contacts-page:import-csv-contacts',
'connections-view:show',
'dashboard-view:show',
'queues-view:show',
'user-view:show',
'ticket-report:show',
],
},
master: {
static: [
'url-remote-session:show',
'show-icon-edit-whatsapp',
'show-icon-add-queue',
'show-icon-edit-queue',
'show-icon-delete-queue',
'space-disk-info:show',
"show-icon-edit-whatsapp",
"show-icon-add-queue",
"show-icon-edit-queue",
"show-icon-delete-queue",
"space-disk-info:show",
"drawer-admin-items:view",
"tickets-manager:showall",
"user-modal:editProfile",
"user-modal:editQueues",
"ticket-options:deleteTicket",
"contacts-page:deleteContact",
"contacts-page:import-contacts",
"contacts-page:import-csv-contacts",
"connections-view:show",
"dashboard-view:show",
"queues-view:show",
"user-view:show",
"settings-view:show",
"btn-add-user",
"icon-remove-user",
"btn-add-whatsapp",
"btn-remove-whatsapp",
"ticket-report:show",
"connection-button:show"
'drawer-admin-items:view',
'tickets-manager:showall',
'user-modal:editProfile',
'user-modal:editQueues',
'ticket-options:deleteTicket',
'contacts-page:deleteContact',
'contacts-page:import-contacts',
'contacts-page:import-csv-contacts',
'connections-view:show',
'dashboard-view:show',
'queues-view:show',
'user-view:show',
'settings-view:show',
'btn-add-user',
'icon-remove-user',
'btn-add-whatsapp',
'btn-remove-whatsapp',
'ticket-report:show',
'connection-button:show',
],
},
};
}
export default rules;
export default rules