improvement: moved user data from localstorage to context

This commit is contained in:
canove
2021-01-13 08:08:25 -03:00
parent 2bec877e4f
commit 3aa287d394
23 changed files with 231 additions and 134 deletions

View File

@@ -0,0 +1,39 @@
import rules from "../../accessRules";
const check = (rules, role, action, data) => {
const permissions = rules[role];
if (!permissions) {
// role is not present in the rules
return false;
}
const staticPermissions = permissions.static;
if (staticPermissions && staticPermissions.includes(action)) {
// static rule not provided for action
return true;
}
const dynamicPermissions = permissions.dynamic;
if (dynamicPermissions) {
const permissionCondition = dynamicPermissions[action];
if (!permissionCondition) {
// dynamic rule not provided for action
return false;
}
return permissionCondition(data);
}
return false;
};
const Can = ({ role, perform, data, yes, no }) =>
check(rules, role, perform, data) ? yes() : no();
Can.defaultProps = {
yes: () => null,
no: () => null,
};
export default Can;

View File

@@ -25,6 +25,8 @@ import { i18n } from "../../translate/i18n";
import api from "../../services/api";
import RecordingTimer from "./RecordingTimer";
import { ReplyMessageContext } from "../../context/ReplyingMessage/ReplyingMessageContext";
import { AuthContext } from "../../context/Auth/AuthContext";
import { useLocalStorage } from "../../hooks/useLocalStorage";
import toastError from "../../errors/toastError";
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
@@ -164,7 +166,6 @@ const useStyles = makeStyles(theme => ({
const MessageInput = ({ ticketStatus }) => {
const classes = useStyles();
const { ticketId } = useParams();
const username = localStorage.getItem("username");
const [medias, setMedias] = useState([]);
const [inputMessage, setInputMessage] = useState("");
@@ -175,17 +176,9 @@ const MessageInput = ({ ticketStatus }) => {
const { setReplyingMessage, replyingMessage } = useContext(
ReplyMessageContext
);
const { user } = useContext(AuthContext);
const [signMessage, setSignMessage] = useState(false);
useEffect(() => {
const storedSignOption = localStorage.getItem("signOption");
if (storedSignOption === "true") setSignMessage(true);
}, []);
useEffect(() => {
localStorage.setItem("signOption", signMessage);
}, [signMessage]);
const [signMessage, setSignMessage] = useLocalStorage("signOption", true);
useEffect(() => {
inputRef.current.focus();
@@ -255,7 +248,7 @@ const MessageInput = ({ ticketStatus }) => {
fromMe: true,
mediaUrl: "",
body: signMessage
? `*${username}:*\n${inputMessage.trim()}`
? `*${user?.name}:*\n${inputMessage.trim()}`
: inputMessage.trim(),
quotedMsg: replyingMessage,
};
@@ -279,7 +272,7 @@ const MessageInput = ({ ticketStatus }) => {
setRecording(true);
setLoading(false);
} catch (err) {
console.log(err);
toastError(err);
setLoading(false);
}
};
@@ -314,7 +307,7 @@ const MessageInput = ({ ticketStatus }) => {
await Mp3Recorder.stop().getMp3();
setRecording(false);
} catch (err) {
console.log(err);
toastError(err);
}
};
@@ -428,8 +421,8 @@ const MessageInput = ({ ticketStatus }) => {
<Switch
size="small"
checked={signMessage}
onChange={() => {
setSignMessage(prevState => !prevState);
onChange={e => {
setSignMessage(e.target.checked);
}}
name="showAllTickets"
color="primary"

View File

@@ -301,7 +301,7 @@ const reducer = (state, action) => {
}
};
const MessagesList = ({ ticketId, isGroup, setReplyingMessage }) => {
const MessagesList = ({ ticketId, isGroup }) => {
const classes = useStyles();
const [messagesList, dispatch] = useReducer(reducer, []);

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useContext } from "react";
import { useHistory } from "react-router-dom";
import Button from "@material-ui/core/Button";
@@ -18,6 +18,7 @@ import api from "../../services/api";
import ButtonWithSpinner from "../ButtonWithSpinner";
import ContactModal from "../ContactModal";
import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext";
const filter = createFilterOptions({
trim: true,
@@ -25,7 +26,6 @@ const filter = createFilterOptions({
const NewTicketModal = ({ modalOpen, onClose }) => {
const history = useHistory();
const userId = +localStorage.getItem("userId");
const [options, setOptions] = useState([]);
const [loading, setLoading] = useState(false);
@@ -33,6 +33,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
const [selectedContact, setSelectedContact] = useState(null);
const [newContact, setNewContact] = useState({});
const [contactModalOpen, setContactModalOpen] = useState(false);
const { user } = useContext(AuthContext);
useEffect(() => {
if (!modalOpen || searchParam.length < 3) {
@@ -71,7 +72,7 @@ const NewTicketModal = ({ modalOpen, onClose }) => {
try {
const { data: ticket } = await api.post("/tickets", {
contactId: contactId,
userId: userId,
userId: user.id,
status: "open",
});
history.push(`/tickets/${ticket.id}`);

View File

@@ -1,4 +1,4 @@
import React, { useState, useRef, useEffect } from "react";
import React, { useState, useRef, useEffect, useContext } from "react";
import { useHistory } from "react-router-dom";
import { format } from "date-fns";
@@ -18,6 +18,7 @@ import TicketListItem from "../TicketListItem";
import { i18n } from "../../translate/i18n";
import useTickets from "../../hooks/useTickets";
import alertSound from "../../assets/sound.mp3";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({
tabContainer: {
@@ -43,7 +44,7 @@ const NotificationsPopOver = () => {
const classes = useStyles();
const history = useHistory();
const userId = +localStorage.getItem("userId");
const { user } = useContext(AuthContext);
const ticketIdUrl = +history.location.pathname.split("/")[2];
const ticketIdRef = useRef(ticketIdUrl);
const anchorEl = useRef();
@@ -108,7 +109,7 @@ const NotificationsPopOver = () => {
if (
data.action === "create" &&
!data.message.read &&
(data.ticket.userId === userId || !data.ticket.userId)
(data.ticket.userId === user?.id || !data.ticket.userId)
) {
setNotifications(prevState => {
const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id);
@@ -122,7 +123,7 @@ const NotificationsPopOver = () => {
const shouldNotNotificate =
(data.message.ticketId === ticketIdRef.current &&
document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== userId) ||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup;
if (shouldNotNotificate) return;
@@ -134,7 +135,7 @@ const NotificationsPopOver = () => {
return () => {
socket.disconnect();
};
}, [history, userId]);
}, [history, user]);
const handleNotifications = (data, history) => {
const { message, contact, ticket } = data;

View File

@@ -41,7 +41,7 @@ const QueueSelector = ({ selectedQueueIds, onChange }) => {
return (
<div style={{ marginTop: 6 }}>
<FormControl fullWidth variant="outlined">
<FormControl fullWidth margin="dense" variant="outlined">
<InputLabel>Filas</InputLabel>
<Select
multiple

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useContext, useState } from "react";
import { useHistory } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
@@ -10,6 +10,7 @@ import api from "../../services/api";
import TicketOptionsMenu from "../TicketOptionsMenu";
import ButtonWithSpinner from "../ButtonWithSpinner";
import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({
actionButtons: {
@@ -26,10 +27,10 @@ const useStyles = makeStyles(theme => ({
const TicketActionButtons = ({ ticket }) => {
const classes = useStyles();
const history = useHistory();
const userId = +localStorage.getItem("userId");
const [anchorEl, setAnchorEl] = useState(null);
const [loading, setLoading] = useState(false);
const ticketOptionsMenuOpen = Boolean(anchorEl);
const { user } = useContext(AuthContext);
const handleOpenTicketOptionsMenu = e => {
setAnchorEl(e.currentTarget);
@@ -66,7 +67,7 @@ const TicketActionButtons = ({ ticket }) => {
loading={loading}
startIcon={<Replay />}
size="small"
onClick={e => handleUpdateTicketStatus(e, "open", userId)}
onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
>
{i18n.t("messagesList.header.buttons.reopen")}
</ButtonWithSpinner>
@@ -86,7 +87,7 @@ const TicketActionButtons = ({ ticket }) => {
size="small"
variant="contained"
color="primary"
onClick={e => handleUpdateTicketStatus(e, "closed", userId)}
onClick={e => handleUpdateTicketStatus(e, "closed", user?.id)}
>
{i18n.t("messagesList.header.buttons.resolve")}
</ButtonWithSpinner>
@@ -107,7 +108,7 @@ const TicketActionButtons = ({ ticket }) => {
size="small"
variant="contained"
color="primary"
onClick={e => handleUpdateTicketStatus(e, "open", userId)}
onClick={e => handleUpdateTicketStatus(e, "open", user?.id)}
>
{i18n.t("messagesList.header.buttons.accept")}
</ButtonWithSpinner>

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef } from "react";
import React, { useState, useEffect, useRef, useContext } from "react";
import { useHistory, useParams } from "react-router-dom";
import { parseISO, format, isSameDay } from "date-fns";
@@ -20,6 +20,7 @@ import api from "../../services/api";
import ButtonWithSpinner from "../ButtonWithSpinner";
import MarkdownWrapper from "../MarkdownWrapper";
import { Tooltip } from "@material-ui/core";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({
ticket: {
@@ -102,10 +103,10 @@ const useStyles = makeStyles(theme => ({
const TicketListItem = ({ ticket }) => {
const classes = useStyles();
const history = useHistory();
const userId = +localStorage.getItem("userId");
const [loading, setLoading] = useState(false);
const { ticketId } = useParams();
const isMounted = useRef(true);
const { user } = useContext(AuthContext);
useEffect(() => {
return () => {
@@ -118,7 +119,7 @@ const TicketListItem = ({ ticket }) => {
try {
await api.put(`/tickets/${ticketId}`, {
status: "open",
userId: userId,
userId: user?.id,
});
} catch (err) {
setLoading(false);

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useReducer } from "react";
import React, { useState, useEffect, useReducer, useContext } from "react";
import openSocket from "socket.io-client";
import { makeStyles } from "@material-ui/core/styles";
@@ -10,6 +10,7 @@ import TicketsListSkeleton from "../TicketsListSkeleton";
import useTickets from "../../hooks/useTickets";
import { i18n } from "../../translate/i18n";
import { ListSubheader } from "@material-ui/core";
import { AuthContext } from "../../context/Auth/AuthContext";
const useStyles = makeStyles(theme => ({
ticketsListWrapper: {
@@ -149,10 +150,10 @@ const reducer = (state, action) => {
};
const TicketsList = ({ status, searchParam, showAll }) => {
const userId = +localStorage.getItem("userId");
const classes = useStyles();
const [pageNumber, setPageNumber] = useState(1);
const [ticketsList, dispatch] = useReducer(reducer, []);
const { user } = useContext(AuthContext);
useEffect(() => {
dispatch({ type: "RESET" });
@@ -194,7 +195,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
if (
(data.action === "updateStatus" || data.action === "create") &&
(!data.ticket.userId || data.ticket.userId === userId || showAll)
(!data.ticket.userId || data.ticket.userId === user?.id || showAll)
) {
dispatch({
type: "UPDATE_TICKET",
@@ -210,7 +211,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
socket.on("appMessage", data => {
if (
data.action === "create" &&
(!data.ticket.userId || data.ticket.userId === userId || showAll)
(!data.ticket.userId || data.ticket.userId === user?.id || showAll)
) {
dispatch({
type: "UPDATE_TICKET_MESSAGES_COUNT",
@@ -234,7 +235,7 @@ const TicketsList = ({ status, searchParam, showAll }) => {
return () => {
socket.disconnect();
};
}, [status, showAll, userId, searchParam]);
}, [status, showAll, user, searchParam]);
const loadMore = () => {
setPageNumber(prevState => prevState + 1);

View File

@@ -175,13 +175,13 @@ const TicketsManager = () => {
</Paper>
<TabPanel value={tab} name="open" className={classes.ticketsWrapper}>
<TicketsList status="open" showAll={showAllTickets} />
<TicketsList status="pending" showAll={true} />
<TicketsList status="pending" />
</TabPanel>
<TabPanel value={tab} name="closed" className={classes.ticketsWrapper}>
<TicketsList status="closed" showAll={true} />
<TicketsList status="closed" showAll={showAllTickets} />
</TabPanel>
<TabPanel value={tab} name="search" className={classes.ticketsWrapper}>
<TicketsList searchParam={searchParam} showAll={true} />
<TicketsList searchParam={searchParam} showAll={showAllTickets} />
</TabPanel>
</Paper>
);