feat: starting appbar notifications

This commit is contained in:
canove
2020-08-24 17:16:26 -03:00
parent 3fe436fd34
commit ea4ff654ff
17 changed files with 1113 additions and 305 deletions

15
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}"
}
]
}

View File

@@ -4,4 +4,5 @@ module.exports = {
config: resolve(__dirname, "src", "config", "database.js"),
"modules-path": resolve(__dirname, "src", "models"),
"migrations-path": resolve(__dirname, "src", "database", "migrations"),
"seeders-path": resolve(__dirname, "src", "database", "seeds"),
};

View File

@@ -126,7 +126,6 @@ exports.store = async (req, res, next) => {
});
if (media) {
console.log(media);
const newMedia = MessageMedia.fromFilePath(req.file.path);
message.mediaUrl = req.file.filename;

View File

@@ -27,14 +27,16 @@ exports.index = async (req, res) => {
},
];
if (status === "open") {
if (status) {
whereCondition = {
...whereCondition,
status: { [Sequelize.Op.or]: ["pending", "open"] },
status: status,
};
} else if (status === "closed") {
whereCondition = { ...whereCondition, status: "closed" };
} else if (searchParam) {
}
// else if (status === "closed") {
// whereCondition = { ...whereCondition, status: "closed" };
// }
else if (searchParam) {
includeCondition = [
...includeCondition,
{

View File

@@ -0,0 +1,48 @@
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert(
"Contacts",
[
{
name: "Joana Doe",
profilePicUrl:
"https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1834&q=80",
number: 5512345678,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: "John Rulles",
profilePicUrl:
"https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80",
number: 5512345679,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: "Jonas Jhones",
profilePicUrl:
"https://images.unsplash.com/photo-1531427186611-ecfd6d936c79?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80",
number: 5512345680,
createdAt: new Date(),
updatedAt: new Date(),
},
{
name: "Julie June",
profilePicUrl:
"https://images.unsplash.com/photo-1493666438817-866a91353ca9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1049&q=80",
number: 5512345681,
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("Contacts", null, {});
},
};

View File

@@ -0,0 +1,261 @@
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert(
"Tickets",
[
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 3,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 4,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 2,
createdAt: new Date(),
updatedAt: new Date(),
},
{
status: "pending",
lastMessage: "hello!",
contactId: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("Tickets", null, {});
},
};

View File

@@ -0,0 +1,148 @@
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert(
"Messages",
[
{
id: "12312321342",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 1,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321313",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 1,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321314",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 1,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321315",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 1,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321316",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 5,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321355",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 5,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321318",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 5,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321319",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 5,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321399",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 11,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321391",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 11,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321392",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 3,
ticketId: 11,
fromMe: true,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: "12312321393",
body:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
ack: 0,
ticketId: 11,
fromMe: false,
read: 1,
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("Messages", null, {});
},
};

View File

@@ -0,0 +1,183 @@
import React from "react";
import { parseISO, format, isSameDay } from "date-fns";
import { makeStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import Typography from "@material-ui/core/Typography";
import Avatar from "@material-ui/core/Avatar";
import Divider from "@material-ui/core/Divider";
import Badge from "@material-ui/core/Badge";
import Button from "@material-ui/core/Button";
import { i18n } from "../../translate/i18n";
const useStyles = makeStyles(theme => ({
ticket: {
position: "relative",
"& .hidden-button": {
display: "none",
},
"&:hover .hidden-button": {
display: "flex",
position: "absolute",
left: "50%",
},
},
noTicketsDiv: {
display: "flex",
height: "100px",
margin: 40,
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
},
noTicketsText: {
textAlign: "center",
color: "rgb(104, 121, 146)",
fontSize: "14px",
lineHeight: "1.4",
},
noTicketsTitle: {
textAlign: "center",
fontSize: "16px",
fontWeight: "600",
margin: "0px",
},
contactNameWrapper: {
display: "flex",
justifyContent: "space-between",
},
lastMessageTime: {
justifySelf: "flex-end",
},
closedBadge: {
alignSelf: "center",
justifySelf: "flex-end",
marginRight: 32,
marginLeft: "auto",
},
contactLastMessage: {
paddingRight: 20,
},
newMessagesCount: {
alignSelf: "center",
marginRight: 8,
marginLeft: "auto",
},
badgeStyle: {
color: "white",
backgroundColor: green[500],
},
}));
const TicketListItem = ({
ticket,
handleAcepptTicket,
handleSelectTicket,
ticketId,
}) => {
const classes = useStyles();
return (
<React.Fragment key={ticket.id}>
<ListItem
dense
button
onClick={e => {
if (ticket.status === "pending" && handleAcepptTicket) return;
handleSelectTicket(e, ticket);
}}
selected={ticketId && +ticketId === ticket.id}
className={classes.ticket}
>
<ListItemAvatar>
<Avatar
src={ticket.contact.profilePicUrl && ticket.contact.profilePicUrl}
></Avatar>
</ListItemAvatar>
<ListItemText
primary={
<span className={classes.contactNameWrapper}>
<Typography
noWrap
component="span"
variant="body2"
color="textPrimary"
>
{ticket.contact.name}
</Typography>
{ticket.status === "closed" && (
<Badge
className={classes.closedBadge}
badgeContent={"closed"}
color="primary"
/>
)}
{ticket.lastMessage && (
<Typography
className={classes.lastMessageTime}
component="span"
variant="body2"
color="textSecondary"
>
{isSameDay(parseISO(ticket.updatedAt), new Date()) ? (
<>{format(parseISO(ticket.updatedAt), "HH:mm")}</>
) : (
<>{format(parseISO(ticket.updatedAt), "dd/MM/yyyy")}</>
)}
</Typography>
)}
</span>
}
secondary={
<span className={classes.contactNameWrapper}>
<Typography
className={classes.contactLastMessage}
noWrap
component="span"
variant="body2"
color="textSecondary"
>
{ticket.lastMessage || <br />}
</Typography>
<Badge
className={classes.newMessagesCount}
badgeContent={ticket.unreadMessages}
classes={{
badge: classes.badgeStyle,
}}
/>
</span>
}
/>
{ticket.status === "pending" && handleAcepptTicket ? (
<Button
variant="contained"
size="small"
color="primary"
className="hidden-button"
onClick={e => handleAcepptTicket(ticket.id)}
>
{i18n.t("ticketsList.buttons.accept")}
</Button>
) : null}
</ListItem>
<Divider variant="inset" component="li" />
</React.Fragment>
);
};
export default TicketListItem;

View File

@@ -1,7 +1,5 @@
import React, { useState, useEffect, useReducer } from "react";
import React, { useState, useEffect } from "react";
import { useHistory, useParams } from "react-router-dom";
import openSocket from "socket.io-client";
import { toast } from "react-toastify";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
@@ -16,14 +14,19 @@ import IconButton from "@material-ui/core/IconButton";
import AddIcon from "@material-ui/icons/Add";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Switch from "@material-ui/core/Switch";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import TicketsSkeleton from "../TicketsSkeleton";
import NewTicketModal from "../NewTicketModal";
import TicketsList from "../TicketsList";
// import TicketsList from "../TicketsList";
import TicketListItem from "../TicketListItem";
import TabPanel from "../TabPanel";
import { i18n } from "../../translate/i18n";
import api from "../../services/api";
import useTickets from "../../hooks/useTickets";
const useStyles = makeStyles(theme => ({
ticketsWrapper: {
@@ -154,140 +157,45 @@ const useStyles = makeStyles(theme => ({
},
}));
const reducer = (state, action) => {
if (action.type === "LOAD_TICKETS") {
const newTickets = action.payload;
newTickets.forEach(ticket => {
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
if (ticket.unreadMessages > 0) {
state.unshift(state.splice(ticketIndex, 1)[0]);
}
} else {
state.push(ticket);
}
});
return [...state];
}
if (action.type === "UPDATE_TICKETS") {
const ticket = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
state.unshift(state.splice(ticketIndex, 1)[0]);
} else {
state.unshift(ticket);
}
return [...state];
}
if (action.type === "DELETE_TICKET") {
const ticketId = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticketId);
if (ticketIndex !== -1) {
state.splice(ticketIndex, 1);
}
return [...state];
}
if (action.type === "RESET_UNREAD") {
const ticketId = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticketId);
if (ticketIndex !== -1) {
state[ticketIndex].unreadMessages = 0;
}
return [...state];
}
if (action.type === "RESET") {
return [];
}
};
const Tickets = () => {
const classes = useStyles();
const history = useHistory();
const token = localStorage.getItem("token");
const userId = +localStorage.getItem("userId");
const { ticketId } = useParams();
const [loading, setLoading] = useState(false);
const [searchParam, setSearchParam] = useState("");
const [tab, setTab] = useState("open");
const [newTicketModalOpen, setNewTicketModalOpen] = useState(false);
const [showAllTickets, setShowAllTickets] = useState(false);
const [pageNumber, setPageNumber] = useState(1);
const [hasMore, setHasMore] = useState(false);
const [tickets, dispatch] = useReducer(reducer, []);
const {
tickets: ticketsOpen,
hasMore: hasMoreOpen,
loading: loadingOpen,
dispatch: dispatchOpen,
} = useTickets({
pageNumber,
searchParam,
status: "open",
});
const {
tickets: ticketsPending,
hasMore: hasMorePending,
loading: loadingPending,
dispatch: dispatchPending,
} = useTickets({
pageNumber,
searchParam,
status: "pending",
});
useEffect(() => {
dispatch({ type: "RESET" });
dispatchOpen({ type: "RESET" });
dispatchPending({ type: "RESET" });
setPageNumber(1);
}, [searchParam, tab]);
useEffect(() => {
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchTickets = async () => {
try {
const { data } = await api.get("/tickets", {
params: { searchParam, pageNumber, status: tab },
});
dispatch({
type: "LOAD_TICKETS",
payload: data.tickets,
});
setHasMore(data.hasMore);
setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchTickets();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber, token, tab]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinNotification");
socket.on("ticket", data => {
if (data.action === "updateUnread") {
dispatch({ type: "RESET_UNREAD", payload: data.ticketId });
}
if (data.action === "updateStatus" || data.action === "create") {
dispatch({ type: "UPDATE_TICKETS", payload: data.ticket });
}
if (data.action === "delete") {
dispatch({ type: "DELETE_TICKET", payload: data.ticketId });
if (ticketId && data.ticketId === +ticketId) {
toast.warn(i18n.t("tickets.toasts.deleted"));
history.push("/chat");
}
}
});
socket.on("appMessage", data => {
if (data.action === "create") {
dispatch({ type: "UPDATE_TICKETS", payload: data.ticket });
}
});
return () => {
socket.disconnect();
};
}, [history, ticketId, userId]);
}, [searchParam, tab, dispatchOpen, dispatchPending]);
const loadMore = () => {
setPageNumber(prevState => prevState + 1);
@@ -297,9 +205,12 @@ const Tickets = () => {
history.push(`/chat/${ticket.id}`);
};
// console.log(tickets);
const handleSearchContact = e => {
if (e.target.value === "") {
setSearchParam(e.target.value.toLowerCase());
setTab("open");
return;
}
setSearchParam(e.target.value.toLowerCase());
@@ -307,7 +218,7 @@ const Tickets = () => {
};
const handleScroll = e => {
if (!hasMore || loading) return;
if (!hasMoreOpen || loadingOpen) return;
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
if (scrollHeight - (scrollTop + 100) < clientHeight) {
@@ -331,16 +242,16 @@ const Tickets = () => {
history.push(`/chat/${ticketId}`);
};
const countTickets = (status, userId) => {
const ticketsFound = tickets.filter(
t =>
(t.status === status && t.userId === userId) ||
(t.status === status && showAllTickets)
).length;
// const countTickets = (status, userId) => {
// const ticketsFound = tickets.filter(
// t =>
// (t.status === status && t.userId === userId) ||
// (t.status === status && showAllTickets)
// ).length;
if (ticketsFound === 0) return "";
return ticketsFound;
};
// if (ticketsFound === 0) return "";
// return ticketsFound;
// };
return (
<Paper elevation={0} variant="outlined" className={classes.ticketsWrapper}>
@@ -397,9 +308,7 @@ const Tickets = () => {
>
<div className={classes.ticketsListHeader}>
{i18n.t("tickets.tabs.open.assignedHeader")}
<span className={classes.ticketsCount}>
{countTickets("open", userId)}
</span>
<span className={classes.ticketsCount}>{ticketsOpen.length}</span>
<div className={classes.ticketsListActions}>
<FormControlLabel
label={i18n.t("tickets.buttons.showAll")}
@@ -424,21 +333,25 @@ const Tickets = () => {
</div>
</div>
<List style={{ paddingTop: 0 }}>
<TicketsList
tickets={tickets}
loading={loading}
handleSelectTicket={handleSelectTicket}
showAllTickets={showAllTickets}
ticketId={ticketId}
handleAcepptTicket={handleAcepptTicket}
noTicketsTitle={i18n.t("tickets.tabs.open.openNoTicketsTitle")}
noTicketsMessage={i18n.t(
"tickets.tabs.open.openNoTicketsMessage"
)}
status="open"
userId={userId}
/>
{loading && <TicketsSkeleton />}
{ticketsOpen.length === 0 ? (
<ListItem>
<ListItemText>
You haven&apos;t received any messages yet.
</ListItemText>
</ListItem>
) : (
ticketsOpen.map(ticket => (
<TicketListItem
ticket={ticket}
key={ticket.id}
// loading={loading}
handleSelectTicket={handleSelectTicket}
handleAcepptTicket={handleAcepptTicket}
ticketId={ticketId}
/>
))
)}
{loadingOpen && <TicketsSkeleton />}
</List>
</Paper>
<Paper
@@ -450,25 +363,29 @@ const Tickets = () => {
<div className={classes.ticketsListHeader}>
{i18n.t("tickets.tabs.open.pendingHeader")}
<span className={classes.ticketsCount}>
{countTickets("pending", null)}
{ticketsPending.length}
</span>
</div>
<List style={{ paddingTop: 0 }}>
<TicketsList
tickets={tickets}
loading={loading}
handleSelectTicket={handleSelectTicket}
showAllTickets={showAllTickets}
ticketId={ticketId}
handleAcepptTicket={handleAcepptTicket}
noTicketsTitle={i18n.t("tickets.tabs.open.pendingNoTicketsTitle")}
noTicketsMessage={i18n.t(
"tickets.tabs.open.pendingNoTicketsMessage"
)}
status="pending"
userId={null}
/>
{loading && <TicketsSkeleton />}
{ticketsPending.length === 0 ? (
<ListItem>
<ListItemText>
You haven&apos;t received any messages yet.
</ListItemText>
</ListItem>
) : (
ticketsPending.map(ticket => (
<TicketListItem
ticket={ticket}
key={ticket.id}
// loading={loading}
handleSelectTicket={handleSelectTicket}
handleAcepptTicket={handleAcepptTicket}
ticketId={ticketId}
/>
))
)}
{loadingPending && <TicketsSkeleton />}
</List>
</Paper>
</TabPanel>
@@ -480,7 +397,7 @@ const Tickets = () => {
onScroll={handleScroll}
>
<List style={{ paddingTop: 0 }}>
<TicketsList
{/* <TicketsList
tickets={tickets}
loading={loading}
handleSelectTicket={handleSelectTicket}
@@ -490,7 +407,7 @@ const Tickets = () => {
status="closed"
userId={null}
/>
{loading && <TicketsSkeleton />}
{loading && <TicketsSkeleton />} */}
</List>
</Paper>
</TabPanel>
@@ -502,7 +419,7 @@ const Tickets = () => {
onScroll={handleScroll}
>
<List style={{ paddingTop: 0 }}>
<TicketsList
{/* <TicketsList
tickets={tickets}
loading={loading}
handleSelectTicket={handleSelectTicket}
@@ -513,7 +430,7 @@ const Tickets = () => {
noTicketsMessage={i18n.t("tickets.tabs.search.noTicketsMessage")}
status="all"
/>
{loading && <TicketsSkeleton />}
{loading && <TicketsSkeleton />} */}
</List>
</Paper>
</TabPanel>

View File

@@ -110,7 +110,7 @@ const TicketsList = ({
dense
button
onClick={e => {
if (ticket.status === "pending") return;
if (ticket.status === "pending" && handleAcepptTicket) return;
handleSelectTicket(e, ticket);
}}
selected={ticketId && +ticketId === ticket.id}
@@ -179,7 +179,7 @@ const TicketsList = ({
</span>
}
/>
{ticket.status === "pending" ? (
{ticket.status === "pending" && handleAcepptTicket ? (
<Button
variant="contained"
size="small"

View File

@@ -0,0 +1,179 @@
import React, { useState, useRef, useCallback, useEffect } from "react";
import { format } from "date-fns";
import openSocket from "socket.io-client";
import Popover from "@material-ui/core/Popover";
import IconButton from "@material-ui/core/IconButton";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import { makeStyles } from "@material-ui/core/styles";
import Badge from "@material-ui/core/Badge";
import ChatIcon from "@material-ui/icons/Chat";
import TicketListItem from "../TicketListItem";
// import { toast } from "react-toastify";
import { useHistory } from "react-router-dom";
import { i18n } from "../../translate/i18n";
import useTickets from "../../hooks/useTickets";
const useStyles = makeStyles(theme => ({
tabContainer: {
overflowY: "auto",
maxHeight: 350,
"&::-webkit-scrollbar": {
width: "8px",
height: "8px",
},
"&::-webkit-scrollbar-thumb": {
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
backgroundColor: "#e8e8e8",
},
},
popoverPaper: {
width: "100%",
maxWidth: 350,
marginLeft: theme.spacing(2),
marginRight: theme.spacing(1),
[theme.breakpoints.down("sm")]: {
maxWidth: 270,
},
},
noShadow: {
boxShadow: "none !important",
},
}));
const NotificationsPopOver = () => {
const classes = useStyles();
const history = useHistory();
const userId = +localStorage.getItem("userId");
const soundAlert = useRef(new Audio(require("../../assets/sound.mp3")));
const ticketId = +history.location.pathname.split("/")[2];
const anchorEl = useRef();
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
if (!("Notification" in window)) {
console.log("This browser doesn't support notifications");
} else {
Notification.requestPermission();
}
}, []);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinNotification");
socket.on("appMessage", data => {
if (data.action === "create") {
if (
(ticketId &&
data.message.ticketId === +ticketId &&
document.visibilityState === "visible") ||
(data.ticket.userId !== userId && data.ticket.userId)
)
return;
showDesktopNotification(data);
}
});
return () => {
socket.disconnect();
};
}, [history, ticketId, userId]);
const { tickets } = useTickets({ status: "open" });
const showDesktopNotification = ({ message, contact, ticket }) => {
const options = {
body: `${message.body} - ${format(new Date(), "HH:mm")}`,
icon: contact.profilePicUrl,
tag: ticket.id,
};
let notification = new Notification(
`${i18n.t("tickets.notification.message")} ${contact.name}`,
options
);
notification.onclick = function (event) {
event.preventDefault(); //
window.open(`/chat/${ticket.id}`, "_self");
};
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
notification.close();
}
});
soundAlert.current.play();
};
const handleClick = useCallback(() => {
setIsOpen(!isOpen);
}, [isOpen, setIsOpen]);
const handleClickAway = useCallback(() => {
setIsOpen(false);
}, [setIsOpen]);
const handleSelectTicket = (e, ticket) => {
history.push(`/chat/${ticket.id}`);
handleClickAway();
};
return (
<>
<IconButton
onClick={handleClick}
buttonRef={anchorEl}
aria-label="Open Notifications"
color="inherit"
>
<Badge badgeContent={tickets.length} color="secondary">
<ChatIcon />
</Badge>
</IconButton>
<Popover
disableScrollLock
open={isOpen}
anchorEl={anchorEl.current}
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
classes={{ paper: classes.popoverPaper }}
onClose={handleClickAway}
>
<List dense className={classes.tabContainer}>
{tickets.length === 0 ? (
<ListItem>
<ListItemText>
You haven&apos;t received any messages yet.
</ListItemText>
</ListItem>
) : (
tickets.map(ticket => (
<TicketListItem
key={ticket.id}
ticket={ticket}
handleSelectTicket={handleSelectTicket}
/>
))
)}
</List>
</Popover>
</>
);
};
export default NotificationsPopOver;

View File

@@ -1,32 +1,22 @@
import React, { useState, useContext, useEffect, useRef } from "react";
import React, { useState, useContext, useEffect } from "react";
import clsx from "clsx";
import { makeStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import Badge from "@material-ui/core/Badge";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import NotificationsIcon from "@material-ui/icons/Notifications";
import MainListItems from "./MainListItems";
import AccountCircle from "@material-ui/icons/AccountCircle";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import IconButton from "@material-ui/core/IconButton";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import AccountCircle from "@material-ui/icons/AccountCircle";
import openSocket from "socket.io-client";
import { format } from "date-fns";
// import { toast } from "react-toastify";
import { useHistory } from "react-router-dom";
import { i18n } from "../../translate/i18n";
import MainListItems from "./MainListItems";
import NotificationsPopOver from "./NotificationsPopOver";
import { AuthContext } from "../../context/Auth/AuthContext";
const drawerWidth = 240;
@@ -115,80 +105,20 @@ const MainDrawer = ({ appTitle, children }) => {
const classes = useStyles();
const [open, setOpen] = useState(true);
const [anchorEl, setAnchorEl] = React.useState(null);
const menuOpen = Boolean(anchorEl);
const [menuOpen, setMenuOpen] = useState(false);
const drawerState = localStorage.getItem("drawerOpen");
const history = useHistory();
const ticketId = +history.location.pathname.split("/")[2];
const soundAlert = useRef(new Audio(require("../../assets/sound.mp3")));
const userId = +localStorage.getItem("userId");
// const [notifications, setNotifications] = useState([]);
useEffect(() => {
if (!("Notification" in window)) {
console.log("This browser doesn't support notifications");
} else {
Notification.requestPermission();
}
}, []);
useEffect(() => {
if (drawerState === "0") {
setOpen(false);
}
}, [drawerState]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinNotification");
socket.on("appMessage", data => {
if (data.action === "create") {
if (
(ticketId &&
data.message.ticketId === +ticketId &&
document.visibilityState === "visible") ||
(data.ticket.userId !== userId && data.ticket.userId)
)
return;
showDesktopNotification(data);
}
});
return () => {
socket.disconnect();
};
}, [history, ticketId, userId]);
const showDesktopNotification = ({ message, contact, ticket }) => {
const options = {
body: `${message.body} - ${format(new Date(), "HH:mm")}`,
icon: contact.profilePicUrl,
tag: ticket.id,
};
let notification = new Notification(
`${i18n.t("tickets.notification.message")} ${contact.name}`,
options
);
notification.onclick = function (event) {
event.preventDefault(); //
window.open(`/chat/${ticket.id}`, "_self");
};
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
notification.close();
}
});
soundAlert.current.play();
};
const handleDrawerOpen = () => {
setOpen(true);
localStorage.setItem("drawerOpen", 1);
};
const handleDrawerClose = () => {
setOpen(false);
localStorage.setItem("drawerOpen", 0);
@@ -196,10 +126,12 @@ const MainDrawer = ({ appTitle, children }) => {
const handleMenu = event => {
setAnchorEl(event.currentTarget);
setMenuOpen(true);
};
const handleClose = () => {
const handleCloseMenu = () => {
setAnchorEl(null);
setMenuOpen(false);
};
return (
@@ -225,7 +157,7 @@ const MainDrawer = ({ appTitle, children }) => {
<AppBar
position="absolute"
className={clsx(classes.appBar, open && classes.appBarShift)}
color={process.env.NODE_ENV === "development" ? "secondary" : "primary"}
color={process.env.NODE_ENV === "development" ? "inherit" : "primary"}
>
<Toolbar variant="dense" className={classes.toolbar}>
<IconButton
@@ -249,11 +181,7 @@ const MainDrawer = ({ appTitle, children }) => {
>
{appTitle}
</Typography>
<IconButton color="inherit">
<Badge badgeContent={0} color="secondary">
<NotificationsIcon />
</Badge>
</IconButton>
<NotificationsPopOver />
<div>
<IconButton
@@ -278,9 +206,9 @@ const MainDrawer = ({ appTitle, children }) => {
horizontal: "right",
}}
open={menuOpen}
onClose={handleClose}
onClose={handleCloseMenu}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleCloseMenu}>Profile</MenuItem>
<MenuItem onClick={handleLogout}>Logout</MenuItem>
</Menu>
</div>

View File

@@ -0,0 +1,140 @@
import { useState, useEffect, useReducer } from "react";
import openSocket from "socket.io-client";
import { useHistory } from "react-router-dom";
import api from "../../services/api";
const reducer = (state, action) => {
if (action.type === "LOAD_TICKETS") {
const newTickets = action.payload;
newTickets.forEach(ticket => {
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
if (ticket.unreadMessages > 0) {
state.unshift(state.splice(ticketIndex, 1)[0]);
}
} else {
state.push(ticket);
}
});
return [...state];
}
if (action.type === "UPDATE_TICKETS") {
const ticket = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
if (ticket.status !== state[ticketIndex]) {
state.splice(ticketIndex, 1);
} else {
state[ticketIndex] = ticket;
state.unshift(state.splice(ticketIndex, 1)[0]);
}
} else {
state.unshift(ticket);
}
return [...state];
}
if (action.type === "DELETE_TICKET") {
const ticketId = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticketId);
if (ticketIndex !== -1) {
state.splice(ticketIndex, 1);
}
return [...state];
}
if (action.type === "RESET_UNREAD") {
const ticketId = action.payload;
const ticketIndex = state.findIndex(t => t.id === ticketId);
if (ticketIndex !== -1) {
state[ticketIndex].unreadMessages = 0;
}
return [...state];
}
if (action.type === "RESET") {
return [];
}
};
const useTickets = ({ searchParam, pageNumber, status, date }) => {
const history = useHistory();
const [loading, setLoading] = useState(true);
const [hasMore, setHasMore] = useState(false);
const [tickets, dispatch] = useReducer(reducer, []);
useEffect(() => {
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchTickets = async () => {
try {
const { data } = await api.get("/tickets", {
params: {
searchParam,
pageNumber,
status,
date,
},
});
dispatch({
type: "LOAD_TICKETS",
payload: data.tickets,
});
setHasMore(data.hasMore);
setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchTickets();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber, status, date]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinNotification");
socket.on("ticket", data => {
if (data.action === "updateUnread") {
dispatch({ type: "RESET_UNREAD", payload: data.ticketId });
}
if (data.action === "updateStatus" || data.action === "create") {
console.log("to aqui", status, data.ticket);
dispatch({
type: "UPDATE_TICKETS",
payload: data.ticket,
status: status,
});
}
if (data.action === "delete") {
dispatch({ type: "DELETE_TICKET", payload: data.ticketId });
}
});
socket.on("appMessage", data => {
if (data.action === "create") {
dispatch({ type: "UPDATE_TICKETS", payload: data.ticket });
}
});
return () => {
socket.disconnect();
};
}, [status]);
return { loading, tickets, hasMore, dispatch };
};
export default useTickets;

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { useTheme } from "@material-ui/core/styles";
import {
BarChart,
@@ -14,12 +14,14 @@ import { startOfHour, parseISO, format } from "date-fns";
import { i18n } from "../../translate/i18n";
import Title from "./Title";
import api from "../../services/api";
import useTickets from "../../hooks/useTickets";
const Chart = () => {
const theme = useTheme();
const [tickets, setTickets] = useState([]);
const date = useRef(new Date().toISOString());
const { tickets } = useTickets({ date: date.current });
const [chartData, setChartData] = useState([
{ time: "08:00", amount: 0 },
{ time: "09:00", amount: 0 },
@@ -36,38 +38,25 @@ const Chart = () => {
]);
useEffect(() => {
const feathTickets = async () => {
try {
const { data } = await api.get("/tickets", {
params: { date: new Date().toISOString() },
});
const ticketsData = data.tickets;
setTickets(ticketsData);
setChartData(prevState => {
let aux = [...prevState];
setChartData(prevState => {
let aux = [...prevState];
aux.map(a => {
ticketsData.forEach(ticket => {
if (
format(startOfHour(parseISO(ticket.createdAt)), "HH:mm") ===
a.time
) {
return a.amount++;
} else {
return a;
}
});
aux.map(a => {
tickets.forEach(ticket => {
if (
format(startOfHour(parseISO(ticket.createdAt)), "HH:mm") === a.time
) {
return a.amount++;
} else {
return a;
});
return aux;
}
});
} catch (err) {
console.log(err);
}
};
feathTickets();
}, []);
return a;
});
return aux;
});
}, [tickets]);
return (
<React.Fragment>

View File

@@ -20,8 +20,8 @@ import { AuthContext } from "../../context/Auth/AuthContext";
const Copyright = () => {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://economicros.com.br/">
{"Copyleft "}
<Link color="inherit" href="https://github.com/canove">
Canove
</Link>{" "}
{new Date().getFullYear()}

View File

@@ -23,8 +23,8 @@ import api from "../../services/api";
const Copyright = () => {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://economicros.com.br/">
{"Copyleft "}
<Link color="inherit" href="https://github.com/canove">
Canove
</Link>{" "}
{new Date().getFullYear()}

View File

@@ -51,8 +51,6 @@ const WhatsAuth = () => {
fetchSession();
}, []);
console.log("session", session);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);