Merge branch 'master' into _dialogflow_omnihit_hit

pull/20/head
adriano 2023-07-20 17:40:33 -03:00
commit 280c006d02
16 changed files with 2022 additions and 1917 deletions

View File

@ -7,9 +7,9 @@ import UpdateSettingService from "../services/SettingServices/UpdateSettingServi
import ListSettingsService from "../services/SettingServices/ListSettingsService"; import ListSettingsService from "../services/SettingServices/ListSettingsService";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
if (req.user.profile !== "master") { // if (req.user.profile !== "master") {
throw new AppError("ERR_NO_PERMISSION", 403); // throw new AppError("ERR_NO_PERMISSION", 403);
} // }
const settings = await ListSettingsService(); 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(); const settingRoutes = Router();
settingRoutes.get("/settings", SettingController.index);
settingRoutes.get("/settings", isAuth, SettingController.index);
// routes.get("/settings/:settingKey", isAuth, SettingsController.show); // routes.get("/settings/:settingKey", isAuth, SettingsController.show);

View File

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

View File

@ -4,21 +4,18 @@ import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import ShowContactService from "../ContactServices/ShowContactService"; import ShowContactService from "../ContactServices/ShowContactService";
import { getIO } from "../../libs/socket"; import { getIO } from "../../libs/socket";
import ShowUserServiceReport from "../UserServices/ShowUserServiceReport"; import ShowUserServiceReport from "../UserServices/ShowUserServiceReport";
import format from 'date-fns/format'; import format from "date-fns/format";
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from "date-fns/locale/pt-BR";
import { splitDateTime } from "../../helpers/SplitDateTime"; import { splitDateTime } from "../../helpers/SplitDateTime";
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser"; import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache' import { createOrUpdateTicketCache } from "../../helpers/TicketCache";
import User from "../../models/User"; import User from "../../models/User";
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue"; import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
let flatten = require('flat') let flatten = require("flat");
interface Request { interface Request {
contactId: number; contactId: number;
@ -33,17 +30,19 @@ const CreateTicketService = async ({
userId, userId,
queueId = undefined queueId = undefined
}: Request): Promise<Ticket> => { }: Request): Promise<Ticket> => {
console.log("========> queueId: ", queueId);
try { try {
const defaultWhatsapp = await GetDefaultWhatsApp(userId); const defaultWhatsapp = await GetDefaultWhatsApp(userId);
if (!queueId) { if (!queueId) {
const user = await User.findByPk(userId, { raw: true, }) const user = await User.findByPk(userId, { raw: true });
const matchingQueue = await whatsappQueueMatchingUserQueue(userId, defaultWhatsapp, user?.profile); const matchingQueue = await whatsappQueueMatchingUserQueue(
queueId = matchingQueue ? matchingQueue.queueId : undefined userId,
defaultWhatsapp,
user?.profile
);
queueId = matchingQueue ? matchingQueue.queueId : undefined;
} }
await CheckContactOpenTickets(contactId); await CheckContactOpenTickets(contactId);
@ -66,27 +65,32 @@ const CreateTicketService = async ({
// console.log('CONTACT ticket.id: ', ticket.id) // console.log('CONTACT ticket.id: ', ticket.id)
// TEST DEL
// TEST DEL
try { try {
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
let ticket_obj = JSON.parse(jsonString); //to make plain json let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo'] delete ticket_obj["contact"]["extraInfo"];
ticket_obj = flatten(ticket_obj) ticket_obj = flatten(ticket_obj);
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
} catch (error) { } catch (error) {
console.log('There was an error on UpdateTicketService.ts on createTicketCache from user: ', error) console.log(
"There was an error on UpdateTicketService.ts on createTicketCache from user: ",
error
);
} }
// //
const dateToday = splitDateTime(
new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
);
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) TicketEmiterSumOpenClosedByUser(
userId.toString(),
TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate) dateToday.fullDate,
dateToday.fullDate
);
const io = getIO(); const io = getIO();
io.emit("ticketStatus", { io.emit("ticketStatus", {
@ -94,14 +98,11 @@ const CreateTicketService = async ({
ticketStatus: { ticketId: ticket.id, status: ticket.status } ticketStatus: { ticketId: ticket.id, status: ticket.status }
}); });
return ticket; return ticket;
} catch (error: any) { } catch (error: any) {
console.error('===> Error on CreateTicketService.ts file: \n', error) console.error("===> Error on CreateTicketService.ts file: \n", error);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };
export default CreateTicketService; export default CreateTicketService;

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -302,4 +302,4 @@ const QueueModal = ({ open, onClose, queueId }) => {
); );
}; };
export default QueueModal; export default QueueModal;

View File

@ -1,290 +1,300 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, 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 { 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'
import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can'
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogTitle, DialogTitle,
Button, Button,
DialogActions, DialogActions,
CircularProgress, CircularProgress,
TextField, TextField,
Switch, Switch,
FormControlLabel, FormControlLabel,
} from "@material-ui/core"; } from '@material-ui/core'
import api from "../../services/api"; import api from '../../services/api'
import { i18n } from "../../translate/i18n"; import { i18n } from '../../translate/i18n'
import toastError from "../../errors/toastError"; import toastError from '../../errors/toastError'
import QueueSelect from "../QueueSelect"; import QueueSelect from '../QueueSelect'
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
display: "flex", display: 'flex',
flexWrap: "wrap", flexWrap: 'wrap',
}, },
multFieldLine: { multFieldLine: {
display: "flex", display: 'flex',
"& > *:not(:last-child)": { '& > *:not(:last-child)': {
marginRight: theme.spacing(1), marginRight: theme.spacing(1),
}, },
}, },
btnWrapper: { btnWrapper: {
position: "relative", position: 'relative',
}, },
buttonProgress: { buttonProgress: {
color: green[500], color: green[500],
position: "absolute", position: 'absolute',
top: "50%", top: '50%',
left: "50%", left: '50%',
marginTop: -12, marginTop: -12,
marginLeft: -12, marginLeft: -12,
}, },
})); }))
const SessionSchema = Yup.object().shape({ const SessionSchema = Yup.object().shape({
name: Yup.string() name: Yup.string()
.min(2, "Too Short!") .min(2, 'Too Short!')
.max(100, "Too Long!") .max(100, 'Too Long!')
.required("Required"), .required('Required'),
}); })
const WhatsAppModal = ({ open, onClose, whatsAppId }) => { const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
const classes = useStyles(); const classes = useStyles()
const initialState = { const initialState = {
name: "", name: '',
urlApi: "", urlApi: '',
url: "", url: '',
greetingMessage: "", greetingMessage: '',
farewellMessage: "", farewellMessage: '',
isDefault: false, isDefault: false,
}; }
const [whatsApp, setWhatsApp] = useState(initialState);
const [selectedQueueIds, setSelectedQueueIds] = useState([]);
useEffect(() => { const { user } = useContext(AuthContext)
const fetchSession = async () => {
if (!whatsAppId) return;
try { const [whatsApp, setWhatsApp] = useState(initialState)
const { data } = await api.get(`whatsapp/${whatsAppId}`); const [selectedQueueIds, setSelectedQueueIds] = useState([])
setWhatsApp(data);
const whatsQueueIds = data.queues?.map(queue => queue.id); useEffect(() => {
setSelectedQueueIds(whatsQueueIds); const fetchSession = async () => {
} catch (err) { if (!whatsAppId) return
toastError(err);
}
};
fetchSession();
}, [whatsAppId]);
const handleSaveWhatsApp = async values => { try {
const whatsappData = { ...values, queueIds: selectedQueueIds }; const { data } = await api.get(`whatsapp/${whatsAppId}`)
setWhatsApp(data)
let response = null const whatsQueueIds = data.queues?.map((queue) => queue.id)
setSelectedQueueIds(whatsQueueIds)
} catch (err) {
toastError(err)
}
}
fetchSession()
}, [whatsAppId])
try { const handleSaveWhatsApp = async (values) => {
if (whatsAppId) { const whatsappData = { ...values, queueIds: selectedQueueIds }
response = await api.put(`/whatsapp/${whatsAppId}`, whatsappData);
} else {
response = await api.post("/whatsapp", whatsappData);
}
console.log('response: ', response.data.message) let response = null
if(response && response.data.message === 'wrong_number_start'){ try {
alert('O numero contido no nome da conexão deve iniciar com o código do país!') if (whatsAppId) {
} response = await api.put(`/whatsapp/${whatsAppId}`, whatsappData)
else if(response && response.data.message === 'invalid_phone_number'){ } else {
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!') response = await api.post('/whatsapp', whatsappData)
} }
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);
}
};
const handleClose = () => { console.log('response: ', response.data.message)
onClose();
setWhatsApp(initialState);
};
return ( if (response && response.data.message === 'wrong_number_start') {
<div className={classes.root}> alert(
<Dialog 'O numero contido no nome da conexão deve iniciar com o código do país!'
open={open} )
onClose={handleClose} } else if (response && response.data.message === 'invalid_phone_number') {
maxWidth="sm" alert(
fullWidth '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!'
scroll="paper" )
> } else if (response && response.data.message === 'no_phone_number') {
<DialogTitle> alert(
{whatsAppId '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!'
? i18n.t("whatsappModal.title.edit") )
: i18n.t("whatsappModal.title.add")} } else {
</DialogTitle> toast.success(i18n.t('whatsappModal.success'))
<Formik handleClose()
initialValues={whatsApp} }
enableReinitialize={true} } catch (err) {
validationSchema={SessionSchema} toastError(err)
onSubmit={(values, actions) => { }
setTimeout(() => { }
handleSaveWhatsApp(values);
actions.setSubmitting(false);
}, 400);
}}
>
{({ values, touched, errors, isSubmitting }) => (
<Form>
<DialogContent dividers>
<div className={classes.multFieldLine}>
<Field
as={TextField}
label={i18n.t("whatsappModal.form.name")}
autoFocus
name="name"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
<FormControlLabel
control={
<Field
as={Switch}
color="primary"
name="isDefault"
checked={values.isDefault}
/>
}
label={i18n.t("whatsappModal.form.default")}
/>
</div>
const handleClose = () => {
onClose()
setWhatsApp(initialState)
}
return (
<div className={classes.root}>
<Dialog
open={open}
onClose={handleClose}
maxWidth="sm"
fullWidth
scroll="paper"
>
<DialogTitle>
{whatsAppId
? i18n.t('whatsappModal.title.edit')
: i18n.t('whatsappModal.title.add')}
</DialogTitle>
<Formik
initialValues={whatsApp}
enableReinitialize={true}
validationSchema={SessionSchema}
onSubmit={(values, actions) => {
setTimeout(() => {
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')}
autoFocus
name="name"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
<FormControlLabel
control={
<Field
as={Switch}
color="primary"
name="isDefault"
checked={values.isDefault}
/>
}
label={i18n.t('whatsappModal.form.default')}
/>
</div>
<div className={classes.multFieldLine}>
<Field
as={TextField}
label="url API"
autoFocus
name="urlApi"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
<Field
as={TextField}
label="url session"
autoFocus
name="url"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
</div>
</>
)}
/>
<div className={classes.multFieldLine}> <div>
<Field <Field
as={TextField} as={TextField}
label='url API' label={i18n.t('queueModal.form.greetingMessage')}
autoFocus type="greetingMessage"
name="urlApi" multiline
error={touched.name && Boolean(errors.name)} rows={5}
helperText={touched.name && errors.name} fullWidth
variant="outlined" name="greetingMessage"
margin="dense" error={
className={classes.textField} touched.greetingMessage && Boolean(errors.greetingMessage)
/> }
<Field helperText={
as={TextField} touched.greetingMessage && errors.greetingMessage
label='url session' }
autoFocus variant="outlined"
name="url" margin="dense"
error={touched.name && Boolean(errors.name)} />
helperText={touched.name && errors.name} </div>
variant="outlined"
margin="dense"
className={classes.textField}
/>
</div>
<div>
<Field
as={TextField}
label={i18n.t('whatsappModal.form.farewellMessage')}
type="farewellMessage"
multiline
rows={5}
fullWidth
name="farewellMessage"
error={
touched.farewellMessage && Boolean(errors.farewellMessage)
}
helperText={
touched.farewellMessage && errors.farewellMessage
}
variant="outlined"
margin="dense"
/>
</div>
<QueueSelect
selectedQueueIds={selectedQueueIds}
onChange={(selectedIds) => setSelectedQueueIds(selectedIds)}
/>
</DialogContent>
<DialogActions>
<Button
onClick={handleClose}
color="secondary"
disabled={isSubmitting}
variant="outlined"
>
{i18n.t('whatsappModal.buttons.cancel')}
</Button>
<Button
type="submit"
color="primary"
disabled={isSubmitting}
variant="contained"
className={classes.btnWrapper}
>
{whatsAppId
? i18n.t('whatsappModal.buttons.okEdit')
: i18n.t('whatsappModal.buttons.okAdd')}
{isSubmitting && (
<CircularProgress
size={24}
className={classes.buttonProgress}
/>
)}
</Button>
</DialogActions>
</Form>
)}
</Formik>
</Dialog>
</div>
)
}
<div> export default React.memo(WhatsAppModal)
<Field
as={TextField}
label={i18n.t("queueModal.form.greetingMessage")}
type="greetingMessage"
multiline
rows={5}
fullWidth
name="greetingMessage"
error={
touched.greetingMessage && Boolean(errors.greetingMessage)
}
helperText={
touched.greetingMessage && errors.greetingMessage
}
variant="outlined"
margin="dense"
/>
</div>
<div>
<Field
as={TextField}
label={i18n.t("whatsappModal.form.farewellMessage")}
type="farewellMessage"
multiline
rows={5}
fullWidth
name="farewellMessage"
error={
touched.farewellMessage && Boolean(errors.farewellMessage)
}
helperText={
touched.farewellMessage && errors.farewellMessage
}
variant="outlined"
margin="dense"
/>
</div>
<QueueSelect
selectedQueueIds={selectedQueueIds}
onChange={selectedIds => setSelectedQueueIds(selectedIds)}
/>
</DialogContent>
<DialogActions>
<Button
onClick={handleClose}
color="secondary"
disabled={isSubmitting}
variant="outlined"
>
{i18n.t("whatsappModal.buttons.cancel")}
</Button>
<Button
type="submit"
color="primary"
disabled={isSubmitting}
variant="contained"
className={classes.btnWrapper}
>
{whatsAppId
? i18n.t("whatsappModal.buttons.okEdit")
: i18n.t("whatsappModal.buttons.okAdd")}
{isSubmitting && (
<CircularProgress
size={24}
className={classes.buttonProgress}
/>
)}
</Button>
</DialogActions>
</Form>
)}
</Formik>
</Dialog>
</div>
);
};
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 AuthProvider = ({ children }) => {
const { loading, user, isAuth, handleLogin, handleLogout } = useAuth(); const { loading, user, isAuth, handleLogin, handleLogout, setSetting } =
useAuth()
//{ //{
return ( return (
<AuthContext.Provider <AuthContext.Provider
value={{ loading, user, isAuth, handleLogin, handleLogout }} value={{ loading, user, isAuth, handleLogin, handleLogout, setSetting }}
> >
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
); )
}; }
export { AuthContext, AuthProvider }; export { AuthContext, AuthProvider }

View File

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

File diff suppressed because it is too large Load Diff

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

View File

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

View File

@ -1,59 +1,58 @@
const rules = { const rules = {
user: { user: {
static: [], static: [],
}, },
admin: { admin: {
static: [ static: [
//"show-icon-edit-whatsapp", 'show-icon-edit-whatsapp',
'show-icon-edit-queue',
"drawer-admin-items:view", 'drawer-admin-items:view',
"tickets-manager:showall", 'tickets-manager:showall',
"user-modal:editProfile", 'user-modal:editProfile',
"user-modal:editQueues", 'user-modal:editQueues',
"ticket-options:deleteTicket", 'ticket-options:deleteTicket',
"contacts-page:deleteContact", 'contacts-page:deleteContact',
"contacts-page:import-csv-contacts", 'contacts-page:import-csv-contacts',
"connections-view:show", 'connections-view:show',
"dashboard-view:show", 'dashboard-view:show',
"queues-view:show", 'queues-view:show',
"user-view:show", 'user-view:show',
"ticket-report:show", 'ticket-report:show',
],
], },
},
master: { master: {
static: [ 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", 'drawer-admin-items:view',
"show-icon-add-queue", 'tickets-manager:showall',
"show-icon-edit-queue", 'user-modal:editProfile',
"show-icon-delete-queue", 'user-modal:editQueues',
"space-disk-info:show", '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", export default rules
"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;