🗂Better folder structure on frontend

This commit is contained in:
canove
2020-07-25 10:49:39 -03:00
parent a543dd31ae
commit 660458a8ab
29 changed files with 38 additions and 41 deletions

View File

@@ -0,0 +1,260 @@
import React, { useState, useEffect } from "react";
import { Formik, FieldArray } from "formik";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import DeleteOutlineIcon from "@material-ui/icons/DeleteOutline";
import CircularProgress from "@material-ui/core/CircularProgress";
import { green } from "@material-ui/core/colors";
import { makeStyles } from "@material-ui/core/styles";
import api from "../../services/api";
const useStyles = makeStyles(theme => ({
root: {
display: "flex",
flexWrap: "wrap",
},
textField: {
// marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
// width: "25ch",
flex: 1,
},
extraAttr: {
display: "flex",
justifyContent: "center",
alignItems: "center",
},
btnWrapper: {
// margin: theme.spacing(1),
position: "relative",
},
buttonProgress: {
color: green[500],
position: "absolute",
top: "50%",
left: "50%",
marginTop: -12,
marginLeft: -12,
},
}));
const ContactModal = ({ modalOpen, onClose, contactId }) => {
const classes = useStyles();
const initialState = {
name: "",
number: "",
email: "",
extraInfo: [
{
name: "",
value: "",
},
],
};
const [contact, setContact] = useState(initialState);
useEffect(() => {
const fetchContact = async () => {
if (!contactId) return;
const res = await api.get(`/contacts/${contactId}`);
setContact(res.data);
};
fetchContact();
}, [contactId]);
const handleClose = () => {
onClose();
setContact(initialState);
};
const handleSaveContact = async values => {
try {
if (contactId) {
await api.put(`/contacts/${contactId}`, values);
} else {
await api.post("/contacts", values);
}
} catch (err) {
alert(err);
}
handleClose();
};
return (
<div className={classes.root}>
<Dialog
open={modalOpen}
onClose={handleClose}
maxWidth="lg"
scroll="paper"
className={classes.modal}
>
<Formik
initialValues={contact}
enableReinitialize={true}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
handleSaveContact(values);
setSubmitting(false);
}, 400);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
}) => (
<>
<DialogTitle id="form-dialog-title">
{contactId ? "Editar contato" : "Adicionar contato"}
</DialogTitle>
<DialogContent dividers>
<Typography variant="subtitle1" gutterBottom>
Dados do contato
</Typography>
<TextField
label="Nome"
name="name"
value={values.name || ""}
onChange={handleChange}
variant="outlined"
margin="dense"
required
className={classes.textField}
/>
<TextField
label="Número do Whatsapp"
name="number"
value={values.number || ""}
onChange={handleChange}
placeholder="Ex: 13912344321"
variant="outlined"
margin="dense"
required
/>
<div>
<TextField
label="Email"
name="email"
value={values.email || ""}
onChange={handleChange}
placeholder="Endereço de Email"
fullWidth
margin="dense"
variant="outlined"
/>
</div>
<Typography
style={{ marginBottom: 8, marginTop: 12 }}
variant="subtitle1"
>
Informações adicionais
</Typography>
<FieldArray name="extraInfo">
{({ push, remove }) => (
<>
{values.extraInfo &&
values.extraInfo.length > 0 &&
values.extraInfo.map((info, index) => (
<div
className={classes.extraAttr}
key={`${index}-info`}
>
<TextField
label="Nome do campo"
name={`extraInfo[${index}].name`}
value={info.name || ""}
onChange={handleChange}
variant="outlined"
margin="dense"
required
className={classes.textField}
/>
<TextField
label="Valor"
name={`extraInfo[${index}].value`}
value={info.value || ""}
onChange={handleChange}
variant="outlined"
margin="dense"
className={classes.textField}
required
/>
<IconButton
size="small"
onClick={() => remove(index)}
>
<DeleteOutlineIcon />
</IconButton>
</div>
))}
<div className={classes.extraAttr}>
<Button
style={{ flex: 1, marginTop: 8 }}
variant="outlined"
color="primary"
onClick={() => push({ name: "", value: "" })}
>
+ Adicionar atributo
</Button>
</div>
</>
)}
</FieldArray>
</DialogContent>
<DialogActions>
<Button
onClick={handleClose}
color="secondary"
disabled={isSubmitting}
variant="outlined"
>
Cancelar
</Button>
<Button
onClick={handleSubmit}
color="primary"
disabled={isSubmitting}
variant="contained"
className={classes.btnWrapper}
>
{contactId ? "Salvar" : "Adicionar"}
{isSubmitting && (
<CircularProgress
size={24}
className={classes.buttonProgress}
/>
)}
</Button>
</DialogActions>
</>
)}
</Formik>
</Dialog>
</div>
);
};
export default ContactModal;

View File

@@ -0,0 +1,163 @@
import React from "react";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import Skeleton from "@material-ui/lab/Skeleton";
const ContactsSekeleton = () => {
return (
<>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={80} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={70} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={90} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={55} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={60} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={100} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={80} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={70} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={90} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={55} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={60} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={100} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={80} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={70} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={90} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={55} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={60} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={100} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={80} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={70} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={90} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={55} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={60} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={100} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={80} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={70} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={90} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingRight: 0 }}>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={55} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={60} />
</TableCell>
<TableCell>
<Skeleton animation="wave" height={20} width={100} />
</TableCell>
<TableCell align="right"></TableCell>
</TableRow>
</>
);
};
export default ContactsSekeleton;

View File

@@ -21,7 +21,7 @@ import AccountCircle from "@material-ui/icons/AccountCircle";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import { AuthContext } from "../../Context/Auth/AuthContext";
import { AuthContext } from "../../context/Auth/AuthContext";
const drawerWidth = 240;

View File

@@ -0,0 +1,48 @@
import React, { useState, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
timerBox: {
display: "flex",
marginLeft: 10,
marginRight: 10,
alignItems: "center",
},
}));
const RecordingTimer = () => {
const classes = useStyles();
const initialState = {
minutes: 0,
seconds: 0,
};
const [timer, setTimer] = useState(initialState);
useEffect(() => {
const interval = setInterval(
() =>
setTimer(prevState => {
if (prevState.seconds === 59) {
return { ...prevState, minutes: prevState.minutes + 1, seconds: 0 };
}
return { ...prevState, seconds: prevState.seconds + 1 };
}),
1000
);
return () => {
clearInterval(interval);
};
}, []);
const addZero = n => {
return n < 10 ? "0" + n : n;
};
return (
<div className={classes.timerBox}>
<span>{`${addZero(timer.minutes)}:${addZero(timer.seconds)}`}</span>
</div>
);
};
export default RecordingTimer;

View File

@@ -0,0 +1,381 @@
import React, { useState, useEffect } from "react";
import "emoji-mart/css/emoji-mart.css";
import { useParams } from "react-router-dom";
import { Picker } from "emoji-mart";
import MicRecorder from "mic-recorder-to-mp3";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import InputBase from "@material-ui/core/InputBase";
import CircularProgress from "@material-ui/core/CircularProgress";
import { green } from "@material-ui/core/colors";
import AttachFileIcon from "@material-ui/icons/AttachFile";
import IconButton from "@material-ui/core/IconButton";
import MoodIcon from "@material-ui/icons/Mood";
import SendIcon from "@material-ui/icons/Send";
import CancelIcon from "@material-ui/icons/Cancel";
import MicIcon from "@material-ui/icons/Mic";
import CheckCircleOutlineIcon from "@material-ui/icons/CheckCircleOutline";
import HighlightOffIcon from "@material-ui/icons/HighlightOff";
import api from "../../services/api";
import RecordingTimer from "./RecordingTimer";
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
const useStyles = makeStyles(theme => ({
newMessageBox: {
background: "#eee",
display: "flex",
padding: "7px",
alignItems: "center",
borderTop: "1px solid rgba(0, 0, 0, 0.12)",
},
messageInputWrapper: {
padding: 6,
background: "#fff",
display: "flex",
borderRadius: 20,
flex: 1,
},
messageInput: {
paddingLeft: 10,
flex: 1,
border: "none",
},
sendMessageIcons: {
color: "grey",
},
uploadInput: {
display: "none",
},
viewMediaInputWrapper: {
display: "flex",
padding: "10px 13px",
position: "relative",
justifyContent: "space-between",
alignItems: "center",
backgroundColor: "#eee",
borderTop: "1px solid rgba(0, 0, 0, 0.12)",
},
emojiBox: {
position: "absolute",
bottom: 63,
width: 40,
borderTop: "1px solid #e8e8e8",
},
circleLoading: {
color: green[500],
opacity: "70%",
position: "absolute",
top: "20%",
left: "50%",
// marginTop: 8,
// marginBottom: 6,
marginLeft: -12,
},
audioLoading: {
color: green[500],
opacity: "70%",
},
recorderWrapper: {
display: "flex",
alignItems: "center",
alignContent: "middle",
},
cancelAudioIcon: {
color: "red",
},
sendAudioIcon: {
color: "green",
},
}));
const MessageInput = ({ searchParam }) => {
const classes = useStyles();
const { ticketId } = useParams();
const userId = localStorage.getItem("userId");
const username = localStorage.getItem("username");
const mediaInitialState = { preview: "", raw: "", name: "" };
const [media, setMedia] = useState(mediaInitialState);
const [inputMessage, setInputMessage] = useState("");
const [showEmoji, setShowEmoji] = useState(false);
const [loading, setLoading] = useState(false);
const [recording, setRecording] = useState(false);
useEffect(() => {
return () => {
setInputMessage("");
setShowEmoji(false);
setMedia({});
};
}, [ticketId]);
const handleChangeInput = e => {
setInputMessage(e.target.value);
};
const handleAddEmoji = e => {
let emoji = e.native;
setInputMessage(prevState => prevState + emoji);
};
const handleChangeMedia = e => {
if (e.target.files.length) {
setMedia({
preview: URL.createObjectURL(e.target.files[0]),
raw: e.target.files[0],
name: e.target.files[0].name,
});
}
};
const handleInputPaste = e => {
if (e.clipboardData.files[0]) {
setMedia({
preview: URL.createObjectURL(e.clipboardData.files[0]),
raw: e.clipboardData.files[0],
name: e.clipboardData.files[0].name,
});
}
};
const handleUploadMedia = async e => {
setLoading(true);
e.preventDefault();
const formData = new FormData();
formData.append("media", media.raw);
formData.append("userId", userId);
formData.append("body", media.name);
try {
await api.post(`/messages/${ticketId}`, formData);
} catch (err) {
console.log(err);
alert(err);
}
setLoading(false);
setMedia(mediaInitialState);
};
const handleSendMessage = async () => {
if (inputMessage.trim() === "") return;
setLoading(true);
const message = {
read: 1,
userId: userId,
mediaUrl: "",
body: `${username}: ${inputMessage.trim()}`,
};
try {
await api.post(`/messages/${ticketId}`, message);
} catch (err) {
alert(err);
}
setInputMessage("");
setShowEmoji(false);
setLoading(false);
};
const handleStartRecording = () => {
navigator.getUserMedia(
{ audio: true },
() => {
Mp3Recorder.start()
.then(() => {
setRecording(true);
})
.catch(e => console.error(e));
},
() => {
console.log("Permission Denied");
}
);
};
const handleUploadAudio = () => {
setLoading(true);
Mp3Recorder.stop()
.getMp3()
.then(async ([buffer, blob]) => {
if (blob.size < 10000) {
setLoading(false);
setRecording(false);
return;
}
const formData = new FormData();
const filename = `${new Date().getTime()}.mp3`;
console.log(blob);
formData.append("media", blob, filename);
formData.append("body", filename);
formData.append("userId", userId);
try {
await api.post(`/messages/${ticketId}`, formData);
} catch (err) {
console.log(err);
alert(err);
}
setRecording(false);
setLoading(false);
})
.catch(e => console.log(e));
};
const handleCancelAudio = () => {
Mp3Recorder.stop()
.getMp3()
.then(() => setRecording(false));
};
if (media.preview)
return (
<Paper elevation={0} square className={classes.viewMediaInputWrapper}>
<IconButton
aria-label="cancel-upload"
component="span"
onClick={e => setMedia(mediaInitialState)}
>
<CancelIcon className={classes.sendMessageIcons} />
</IconButton>
{loading ? (
<div>
<CircularProgress className={classes.circleLoading} />
</div>
) : (
<span>
{media.name}
{/* <img src={media.preview} alt=""></img> */}
</span>
)}
<IconButton
aria-label="send-upload"
component="span"
onClick={handleUploadMedia}
>
<SendIcon className={classes.sendMessageIcons} />
</IconButton>
</Paper>
);
else {
return (
<Paper square elevation={0} className={classes.newMessageBox}>
<IconButton
aria-label="emojiPicker"
component="span"
disabled={loading || recording}
onClick={e => setShowEmoji(prevState => !prevState)}
>
<MoodIcon className={classes.sendMessageIcons} />
</IconButton>
{showEmoji ? (
<div className={classes.emojiBox}>
<Picker
perLine={16}
showPreview={false}
showSkinTones={false}
onSelect={handleAddEmoji}
/>
</div>
) : null}
<input
type="file"
id="upload-button"
disabled={loading || recording}
className={classes.uploadInput}
onChange={handleChangeMedia}
/>
<label htmlFor="upload-button">
<IconButton
aria-label="upload"
component="span"
disabled={loading || recording}
>
<AttachFileIcon className={classes.sendMessageIcons} />
</IconButton>
</label>
<div className={classes.messageInputWrapper}>
<InputBase
inputRef={input => input && !searchParam && input.focus()}
className={classes.messageInput}
placeholder="Escreva uma mensagem"
multiline
rowsMax={5}
value={inputMessage}
onChange={handleChangeInput}
disabled={recording || loading}
onPaste={handleInputPaste}
onKeyPress={e => {
if (loading) return;
else if (e.key === "Enter") {
handleSendMessage();
}
}}
/>
</div>
{inputMessage ? (
<IconButton
aria-label="sendMessage"
component="span"
onClick={handleSendMessage}
disabled={loading}
>
<SendIcon className={classes.sendMessageIcons} />
</IconButton>
) : recording ? (
<div className={classes.recorderWrapper}>
<IconButton
aria-label="cancelRecording"
component="span"
fontSize="large"
disabled={loading}
onClick={handleCancelAudio}
>
<HighlightOffIcon className={classes.cancelAudioIcon} />
</IconButton>
{loading ? (
<div>
<CircularProgress className={classes.audioLoading} />
</div>
) : (
<RecordingTimer />
)}
<IconButton
aria-label="sendRecordedAudio"
component="span"
onClick={handleUploadAudio}
disabled={loading}
>
<CheckCircleOutlineIcon className={classes.sendAudioIcon} />
</IconButton>
</div>
) : (
<IconButton
aria-label="showRecorder"
component="span"
disabled={loading}
onClick={handleStartRecording}
>
<MicIcon className={classes.sendMessageIcons} />
</IconButton>
)}
</Paper>
);
}
};
export default MessageInput;

View File

@@ -0,0 +1,635 @@
import React, { useState, useEffect, useRef } from "react";
import { useParams, useHistory } from "react-router-dom";
import { isSameDay, parseISO, format } from "date-fns";
import openSocket from "socket.io-client";
import InfiniteScrollReverse from "react-infinite-scroll-reverse";
import ModalImage from "react-modal-image";
import { makeStyles } from "@material-ui/core/styles";
import clsx from "clsx";
import AccessTimeIcon from "@material-ui/icons/AccessTime";
import CircularProgress from "@material-ui/core/CircularProgress";
import DoneIcon from "@material-ui/icons/Done";
import DoneAllIcon from "@material-ui/icons/DoneAll";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import ReplayIcon from "@material-ui/icons/Replay";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import IconButton from "@material-ui/core/IconButton";
import CloseIcon from "@material-ui/icons/Close";
import Divider from "@material-ui/core/Divider";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import { green } from "@material-ui/core/colors";
import Skeleton from "@material-ui/lab/Skeleton";
import Drawer from "@material-ui/core/Drawer";
import whatsBackground from "../../assets/wa-background.png";
import LinkifyWithTargetBlank from "../LinkifyWithTargetBlank";
import api from "../../services/api";
import MessageInput from "../MessageInput/";
const drawerWidth = 320;
const useStyles = makeStyles(theme => ({
root: {
display: "flex",
height: "100%",
position: "relative",
overflow: "hidden",
},
mainWrapper: {
flex: 1,
height: "100%",
display: "flex",
flexDirection: "column",
overflow: "hidden",
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
borderLeft: "0",
marginRight: -drawerWidth,
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
mainWrapperShift: {
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
transition: theme.transitions.create("margin", {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginRight: 0,
},
messagesHeader: {
display: "flex",
backgroundColor: "#eee",
flex: "none",
borderBottom: "1px solid rgba(0, 0, 0, 0.12)",
},
actionButtons: {
marginRight: 6,
flex: "none",
alignSelf: "center",
marginLeft: "auto",
"& > *": {
margin: theme.spacing(1),
},
},
messagesListWrapper: {
overflow: "hidden",
position: "relative",
display: "flex",
flexDirection: "column",
flexGrow: 1,
},
messagesList: {
backgroundImage: `url(${whatsBackground})`,
display: "flex",
flexDirection: "column",
flexGrow: 1,
padding: "20px 20px 20px 20px",
overflowY: "scroll",
"&::-webkit-scrollbar": {
width: "8px",
},
"&::-webkit-scrollbar-thumb": {
// borderRadius: "2px",
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
backgroundColor: "#e8e8e8",
},
},
circleLoading: {
color: green[500],
position: "absolute",
opacity: "70%",
top: 0,
left: "50%",
marginTop: 12,
// marginLeft: -12,
},
messageLeft: {
marginRight: 20,
marginTop: 2,
minWidth: 100,
maxWidth: 600,
height: "auto",
display: "block",
position: "relative",
backgroundColor: "#ffffff",
alignSelf: "flex-start",
borderTopLeftRadius: 0,
borderTopRightRadius: 8,
borderBottomLeftRadius: 8,
borderBottomRightRadius: 8,
paddingLeft: 5,
paddingRight: 5,
paddingTop: 5,
paddingBottom: 0,
boxShadow: "0 1px 1px #b3b3b3",
},
messageRight: {
marginLeft: 20,
marginTop: 2,
minWidth: 100,
maxWidth: 600,
height: "auto",
display: "block",
position: "relative",
backgroundColor: "#dcf8c6",
alignSelf: "flex-end",
borderTopLeftRadius: 8,
borderTopRightRadius: 8,
borderBottomLeftRadius: 8,
borderBottomRightRadius: 0,
paddingLeft: 5,
paddingRight: 5,
paddingTop: 5,
paddingBottom: 0,
boxShadow: "0 1px 1px #b3b3b3",
},
textContentItem: {
overflowWrap: "break-word",
padding: "3px 80px 6px 6px",
},
messageMedia: {
objectFit: "cover",
width: 250,
height: 200,
borderTopLeftRadius: 8,
borderTopRightRadius: 8,
borderBottomLeftRadius: 8,
borderBottomRightRadius: 8,
},
timestamp: {
fontSize: 11,
position: "absolute",
bottom: 0,
right: 5,
color: "#999",
},
dailyTimestamp: {
alignItems: "center",
textAlign: "center",
alignSelf: "center",
width: "110px",
backgroundColor: "#e1f3fb",
margin: "10px",
borderRadius: "10px",
boxShadow: "0 1px 1px #b3b3b3",
},
dailyTimestampText: {
color: "#808888",
padding: 8,
alignSelf: "center",
marginLeft: "0px",
},
ackIcons: {
fontSize: 18,
verticalAlign: "middle",
marginLeft: 4,
},
ackDoneAllIcon: {
color: green[500],
fontSize: 18,
verticalAlign: "middle",
marginLeft: 4,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
borderTop: "1px solid rgba(0, 0, 0, 0.12)",
borderTopRightRadius: 4,
borderBottomRightRadius: 4,
},
drawerHeader: {
display: "flex",
borderBottom: "1px solid rgba(0, 0, 0, 0.12)",
backgroundColor: "#eee",
alignItems: "center",
padding: theme.spacing(0, 1),
minHeight: "73px",
justifyContent: "flex-start",
},
}));
const MessagesList = () => {
const { ticketId } = useParams();
const history = useHistory();
const classes = useStyles();
const token = localStorage.getItem("token");
const userId = localStorage.getItem("userId");
const [loading, setLoading] = useState(true);
const [contact, setContact] = useState({});
const [ticket, setTicket] = useState({});
const [messagesList, setMessagesList] = useState([]);
const [hasMore, setHasMore] = useState(false);
const [searchParam, setSearchParam] = useState("");
const [pageNumber, setPageNumber] = useState(0);
const lastMessageRef = useRef();
const [open, setOpen] = useState(true);
useEffect(() => {
setMessagesList([]);
}, [searchParam]);
useEffect(() => {
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchMessages = async () => {
try {
const res = await api.get("/messages/" + ticketId, {
params: { searchParam, pageNumber },
});
setContact(res.data.contact);
setTicket(res.data.ticket);
setMessagesList(prevMessages => {
return [...res.data.messages, ...prevMessages];
});
setHasMore(res.data.messages.length > 0);
setLoading(false);
if (pageNumber === 1 && res.data.messages.length > 1) {
scrollToBottom();
}
} catch (err) {
console.log(err);
alert(err);
}
};
fetchMessages();
}, 1000);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber, ticketId, token]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinChatBox", ticketId, () => {});
socket.on("appMessage", data => {
if (data.action === "create") {
addMessage(data.message);
scrollToBottom();
} else if (data.action === "update") {
updateMessageAck(data.message);
}
});
return () => {
socket.disconnect();
setSearchParam("");
setPageNumber(1);
setMessagesList([]);
};
}, [ticketId]);
// const handleSearch = e => {
// setSearchParam(e.target.value);
// setPageNumber(1);
// };
const loadMore = () => {
setPageNumber(prevPageNumber => prevPageNumber + 1);
};
const addMessage = message => {
setMessagesList(prevState => {
if (prevState.length >= 20) {
let aux = [...prevState];
aux.shift();
aux.push(message);
return aux;
} else {
return [...prevState, message];
}
});
};
const updateMessageAck = message => {
let id = message.id;
setMessagesList(prevState => {
let aux = [...prevState];
let messageIndex = aux.findIndex(message => message.id === id);
if (messageIndex !== -1) {
aux[messageIndex].ack = message.ack;
}
return aux;
});
};
const scrollToBottom = () => {
if (lastMessageRef.current) {
lastMessageRef.current.scrollIntoView({});
}
};
const checkMessaageMedia = message => {
if (message.mediaType === "image") {
return (
<ModalImage
className={classes.messageMedia}
smallSrcSet={message.mediaUrl}
medium={message.mediaUrl}
large={message.mediaUrl}
alt="image"
/>
);
}
if (message.mediaType === "audio") {
return (
<audio controls>
<source src={message.mediaUrl} type="audio/ogg"></source>
</audio>
);
}
if (message.mediaType === "video") {
return (
<video
className={classes.messageMedia}
src={message.mediaUrl}
controls
/>
);
} else {
return <a href={message.mediaUrl}>Download</a>;
}
};
const handleUpdateTicketStatus = async (status, userId) => {
try {
await api.put(`/tickets/${ticketId}`, {
status: status,
userId: userId || null,
});
} catch (err) {
console.log(err);
}
history.push("/chat");
};
const renderMessageAck = message => {
if (message.ack === 0) {
return <AccessTimeIcon fontSize="small" className={classes.ackIcons} />;
}
if (message.ack === 1) {
return <DoneIcon fontSize="small" className={classes.ackIcons} />;
}
if (message.ack === 2) {
return <DoneAllIcon fontSize="small" className={classes.ackIcons} />;
}
if (message.ack === 3) {
return (
<DoneAllIcon fontSize="small" className={classes.ackDoneAllIcon} />
);
}
};
const renderDailyTimestamps = (message, index) => {
if (index === 0) {
return (
<span
className={classes.dailyTimestamp}
key={`timestamp-${message.id}`}
>
<div className={classes.dailyTimestampText}>
{format(parseISO(messagesList[index].createdAt), "dd/MM/yyyy")}
</div>
</span>
);
}
if (index < messagesList.length - 1) {
let messageDay = parseISO(messagesList[index].createdAt);
let previousMessageDay = parseISO(messagesList[index - 1].createdAt);
if (!isSameDay(messageDay, previousMessageDay)) {
return (
<span
className={classes.dailyTimestamp}
key={`timestamp-${message.id}`}
>
<div className={classes.dailyTimestampText}>
{format(parseISO(messagesList[index].createdAt), "dd/MM/yyyy")}
</div>
</span>
);
}
}
if (index + 1 === messagesList.length) {
return (
<div
key={`ref-${message.createdAt}`}
ref={lastMessageRef}
style={{ float: "left", clear: "both" }}
/>
);
}
};
const renderMessages = () => {
if (messagesList.length > 0) {
const viewMessagesList = messagesList.map((message, index) => {
if (!message.userId) {
return (
<LinkifyWithTargetBlank key={message.id}>
{renderDailyTimestamps(message, index)}
<div className={classes.messageLeft}>
{message.mediaUrl && checkMessaageMedia(message)}
<div className={classes.textContentItem}>
{message.body}
<span className={classes.timestamp}>
{format(parseISO(message.createdAt), "HH:mm")}
</span>
</div>
</div>
</LinkifyWithTargetBlank>
);
} else {
return (
<LinkifyWithTargetBlank key={message.id}>
{renderDailyTimestamps(message, index)}
<div className={classes.messageRight}>
{message.mediaUrl && checkMessaageMedia(message)}
<div className={classes.textContentItem}>
{message.body}
<span className={classes.timestamp}>
{format(parseISO(message.createdAt), "HH:mm")}
{renderMessageAck(message)}
</span>
</div>
</div>
</LinkifyWithTargetBlank>
);
}
});
return viewMessagesList;
} else {
return <div>Diga olá ao seu novo contato</div>;
}
};
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
return (
<div className={classes.root} id="drawer-container">
<Paper
variant="outlined"
elevation={0}
className={clsx(classes.mainWrapper, {
[classes.mainWrapperShift]: open,
})}
>
<Card square className={classes.messagesHeader}>
<CardHeader
titleTypographyProps={{ noWrap: true }}
subheaderTypographyProps={{ noWrap: true }}
avatar={
loading ? (
<Skeleton animation="wave" variant="circle">
<Avatar alt="contact_image" />
</Skeleton>
) : (
<Avatar src={contact.profilePicUrl} alt="contact_image" />
)
}
title={
loading ? (
<Skeleton animation="wave" width={60} />
) : (
`${contact.name} #${ticket.id}`
)
}
subheader={
loading ? (
<Skeleton animation="wave" width={80} />
) : (
`Atribuído á ${ticket.userId}`
)
}
/>
{!loading && (
<div className={classes.actionButtons}>
{ticket.status === "closed" ? (
<Button
startIcon={<ReplayIcon />}
size="small"
onClick={e => handleUpdateTicketStatus("open", userId)}
>
Reabrir
</Button>
) : (
<>
<Button
startIcon={<ReplayIcon />}
size="small"
onClick={e => handleUpdateTicketStatus("pending", null)}
>
Retornar
</Button>
<Button
startIcon={<ReplayIcon />}
size="small"
onClick={handleDrawerOpen}
>
Drawer
</Button>
<Button
size="small"
variant="contained"
color="primary"
onClick={e => handleUpdateTicketStatus("closed", userId)}
>
Resolver
</Button>
</>
)}
</div>
)}
</Card>
<div className={classes.messagesListWrapper}>
<InfiniteScrollReverse
className={classes.messagesList}
hasMore={hasMore}
isLoading={loading}
loadMore={loadMore}
loadArea={10}
>
{messagesList.length > 0 ? renderMessages() : []}
</InfiniteScrollReverse>
<MessageInput searchParam={searchParam} />
{loading ? (
<div>
<CircularProgress className={classes.circleLoading} />
</div>
) : null}
</div>
</Paper>
<Drawer
className={classes.drawer}
variant="persistent"
anchor="right"
open={open}
PaperProps={{ style: { position: "absolute" } }}
BackdropProps={{ style: { position: "absolute" } }}
ModalProps={{
container: document.getElementById("drawer-container"),
style: { position: "absolute" },
}}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={handleDrawerClose}>
<CloseIcon />
</IconButton>
<Typography style={{ justifySelf: "center" }}>
Dados do contato
</Typography>
</div>
<a href="https://economicros.ddns.com.br:4043/?viewmode=11&gotonode=j@fJRRDC0rsF1pdypERaF4eQbcwntph@aNQrtLIXhES3Q4AZX678gnn4qbPG619C">
Value
</a>
</Drawer>
</div>
);
};
export default MessagesList;

View File

@@ -0,0 +1,71 @@
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import FirstPageIcon from "@material-ui/icons/FirstPage";
import KeyboardArrowLeft from "@material-ui/icons/KeyboardArrowLeft";
import KeyboardArrowRight from "@material-ui/icons/KeyboardArrowRight";
import LastPageIcon from "@material-ui/icons/LastPage";
import IconButton from "@material-ui/core/IconButton";
const useStyles = makeStyles(theme => ({
root: {
flexShrink: 0,
marginLeft: theme.spacing(2.5),
},
}));
const PaginationActions = ({ count, page, rowsPerPage, onChangePage }) => {
const classes = useStyles();
const handleFirstPageButtonClick = event => {
onChangePage(event, 0);
};
const handleBackButtonClick = event => {
onChangePage(event, page - 1);
};
const handleNextButtonClick = event => {
onChangePage(event, page + 1);
};
const handleLastPageButtonClick = event => {
onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
};
return (
<div className={classes.root}>
<IconButton
onClick={handleFirstPageButtonClick}
disabled={page === 0}
aria-label="first page"
>
{<FirstPageIcon />}
</IconButton>
<IconButton
onClick={handleBackButtonClick}
disabled={page === 0}
aria-label="previous page"
>
{<KeyboardArrowLeft />}
</IconButton>
<IconButton
onClick={handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="next page"
>
{<KeyboardArrowRight />}
</IconButton>
<IconButton
onClick={handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="last page"
>
{<LastPageIcon />}
</IconButton>
</div>
);
};
export default PaginationActions;

View File

@@ -0,0 +1,16 @@
import React from "react";
import QRCode from "qrcode.react";
import Typography from "@material-ui/core/Typography";
const Qrcode = ({ qrCode }) => {
return (
<div>
<Typography color="primary" gutterBottom>
Leia o QrCode para iniciar a sessão
</Typography>
<QRCode value={qrCode} size={256} />
</div>
);
};
export default Qrcode;

View File

@@ -0,0 +1,34 @@
import React from "react";
import Link from "@material-ui/core/Link";
import { makeStyles } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
const useStyles = makeStyles({
main: {
flex: 1,
},
});
const SessionInfo = ({ session }) => {
const classes = useStyles();
return (
<React.Fragment>
<Typography component="h2" variant="h6" color="primary" gutterBottom>
Bateria
</Typography>
<Typography component="p" variant="h6">
{(session && session.baterry) || "Não disponível"}
</Typography>
<Typography color="textSecondary" className={classes.main}>
Carregando: {(session && session.plugged) || "Não disponível"}
</Typography>
<div>
<Link color="primary" href="#">
Verificar bateria
</Link>
</div>
</React.Fragment>
);
};
export default SessionInfo;

View File

@@ -0,0 +1,46 @@
import React from "react";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import Divider from "@material-ui/core/Divider";
import Skeleton from "@material-ui/lab/Skeleton";
const TicketSkeleton = () => {
return (
<>
<ListItem dense>
<ListItemAvatar>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</ListItemAvatar>
<ListItemText
primary={<Skeleton animation="wave" height={20} width={60} />}
secondary={<Skeleton animation="wave" height={20} width={90} />}
/>
</ListItem>
<Divider />
<ListItem dense>
<ListItemAvatar>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</ListItemAvatar>
<ListItemText
primary={<Skeleton animation="wave" height={20} width={70} />}
secondary={<Skeleton animation="wave" height={20} width={120} />}
/>
</ListItem>
<Divider />
<ListItem dense>
<ListItemAvatar>
<Skeleton animation="wave" variant="circle" width={40} height={40} />
</ListItemAvatar>
<ListItemText
primary={<Skeleton animation="wave" height={20} width={60} />}
secondary={<Skeleton animation="wave" height={20} width={90} />}
/>
</ListItem>
<Divider />
</>
);
};
export default TicketSkeleton;

View File

@@ -0,0 +1,544 @@
import React, { useState, useEffect } from "react";
import { useHistory, useParams } from "react-router-dom";
import openSocket from "socket.io-client";
import { parseISO, format } from "date-fns";
import { makeStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import Paper from "@material-ui/core/Paper";
import List from "@material-ui/core/List";
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 SearchIcon from "@material-ui/icons/Search";
import InputBase from "@material-ui/core/InputBase";
import Button from "@material-ui/core/Button";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import MoveToInboxIcon from "@material-ui/icons/MoveToInbox";
import CheckCircleOutlineIcon from "@material-ui/icons/CheckCircleOutline";
import TicketSkeleton from "./TicketSkeleton";
import api from "../../services/api";
const useStyles = makeStyles(theme => ({
contactsWrapper: {
position: "relative",
display: "flex",
height: "100%",
flexDirection: "column",
overflow: "hidden",
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
},
tabsHeader: {
// display: "flex",
flex: "none",
backgroundColor: "#eee",
},
settingsIcon: {
alignSelf: "center",
marginLeft: "auto",
padding: 8,
},
openTicketsList: {
height: "50%",
overflowY: "scroll",
"&::-webkit-scrollbar": {
width: "8px",
},
"&::-webkit-scrollbar-thumb": {
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
backgroundColor: "#e8e8e8",
},
borderTop: "1px solid rgba(0, 0, 0, 0.12)",
},
closedTicketsList: {
flex: 1,
overflowY: "scroll",
"&::-webkit-scrollbar": {
width: "8px",
},
"&::-webkit-scrollbar-thumb": {
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
backgroundColor: "#e8e8e8",
},
borderTop: "2px solid rgba(0, 0, 0, 0.12)",
},
ticketsListHeader: {
display: "flex",
// flexShrink: 0,
// -webkitBoxAlign: "center",
alignItems: "center",
fontWeight: 500,
fontSize: "16px",
height: "56px",
// backgroundColor: "#eee",
color: "rgb(67, 83, 105)",
padding: "0px 12px",
borderBottom: "1px solid rgba(0, 0, 0, 0.12)",
},
ticketsCount: {
fontWeight: "normal",
color: "rgb(104, 121, 146)",
marginLeft: "8px",
fontSize: "14px",
},
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",
},
contactsSearchBox: {
position: "relative",
background: "#fafafa",
padding: "10px 13px",
},
serachInputWrapper: {
background: "#fff",
display: "flex",
borderRadius: 40,
padding: 4,
},
searchIcon: {
color: "grey",
marginLeft: 6,
marginRight: 6,
alignSelf: "center",
},
contactsSearchInput: {
flex: 1,
border: "none",
borderRadius: 30,
},
contactNameWrapper: {
display: "flex",
// display: "inline",
},
lastMessageTime: {
marginLeft: "auto",
},
contactLastMessage: {
paddingRight: 20,
},
newMessagesCount: {
alignSelf: "center",
marginRight: 8,
marginLeft: "auto",
},
badgeStyle: {
color: "white",
backgroundColor: green[500],
},
circleLoading: {
color: green[500],
opacity: "70%",
position: "absolute",
top: "50%",
left: "50%",
marginTop: 12,
// marginLeft: -12,
},
}));
const TicketsList = () => {
const classes = useStyles();
const token = localStorage.getItem("token");
const userId = +localStorage.getItem("userId");
const { ticketId } = useParams();
const [tickets, setTickets] = useState([]);
const [loading, setLoading] = useState();
const [searchParam, setSearchParam] = useState("");
const [tab, setTab] = useState("open");
// const [modalOpen, setModalOpen] = useState(false);
const history = useHistory();
useEffect(() => {
if (!("Notification" in window)) {
console.log("This browser doesn't support notifications");
} else {
Notification.requestPermission();
}
}, []);
useEffect(() => {
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchContacts = async () => {
try {
const res = await api.get("/tickets", {
params: { searchParam, status: tab },
});
setTickets(res.data);
setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchContacts();
}, 1000);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, token, tab]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.emit("joinNotification");
socket.on("ticket", data => {
if (data.action === "updateUnread") {
resetUnreadMessages(data.ticketId);
}
if (data.action === "updateStatus") {
updateTicketStatus(data);
}
});
socket.on("appMessage", data => {
console.log(data);
if (data.action === "create") {
updateUnreadMessagesCount(data);
if (
(ticketId &&
data.message.ticketId === +ticketId &&
document.visibilityState === "visible") ||
(data.ticket.userId !== userId && data.ticket.userId)
)
return;
showDesktopNotification(data);
}
});
return () => {
socket.disconnect();
};
}, [ticketId, userId]);
const updateUnreadMessagesCount = data => {
setTickets(prevState => {
const ticketIndex = prevState.findIndex(
ticket => ticket.id === data.message.ticketId
);
if (ticketIndex !== -1) {
let aux = [...prevState];
aux[ticketIndex].unreadMessages++;
aux[ticketIndex].lastMessage = data.message.body;
aux.unshift(aux.splice(ticketIndex, 1)[0]);
return aux;
} else {
return [data.ticket, ...prevState];
}
});
};
const updateTicketStatus = data => {
setTickets(prevState => {
const ticketIndex = prevState.findIndex(
ticket => ticket.id === data.ticket.id
);
if (ticketIndex === -1) {
return [data.ticket, ...prevState];
} else {
let aux = [...prevState];
aux[ticketIndex] = data.ticket;
return aux;
}
});
};
console.log(tickets);
const showDesktopNotification = data => {
const options = {
body: `${data.message.body} - ${format(new Date(), "HH:mm")}`,
icon: data.contact.profilePicUrl,
};
new Notification(`Mensagem de ${data.contact.name}`, options);
document.getElementById("sound").play();
};
const resetUnreadMessages = ticketId => {
setTickets(prevState => {
const ticketIndex = prevState.findIndex(
ticket => ticket.id === +ticketId
);
if (ticketIndex !== -1) {
let aux = [...prevState];
aux[ticketIndex].unreadMessages = 0;
return aux;
} else {
return prevState;
}
});
};
const handleSelectTicket = (e, ticket) => {
history.push(`/chat/${ticket.id}`);
};
const handleSearchContact = e => {
// let searchTerm = e.target.value.toLowerCase();
setSearchParam(e.target.value.toLowerCase());
};
const handleChangeTab = (event, newValue) => {
setTab(newValue);
};
const handleAcepptTicket = async ticketId => {
try {
await api.put(`/tickets/${ticketId}`, {
status: "open",
userId: userId,
});
} catch (err) {
alert(err);
}
history.push(`/chat/${ticketId}`);
};
const countTickets = (status, userId) => {
const ticketsFound = tickets.filter(
t => t.status === status && t.userId === userId
).length;
if (ticketsFound === 0) return "";
return ticketsFound;
};
const renderTickets = (status, userId) => {
const viewTickets = tickets.map(ticket => {
if (
(ticket.status === status && ticket.userId === userId) ||
(ticket.status === "closed" && status === "closed")
)
return (
<React.Fragment key={ticket.id}>
<ListItem
dense
button
onClick={e => {
if (ticket.status === "pending") 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.lastMessage && (
<Typography
className={classes.lastMessageTime}
component="span"
variant="body2"
color="textSecondary"
>
{format(parseISO(ticket.updatedAt), "HH:mm")}
</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" ? (
<Button
variant="contained"
size="small"
color="primary"
className="hidden-button"
onClick={e => handleAcepptTicket(ticket.id)}
>
Aceitar
</Button>
) : null}
</ListItem>
<Divider variant="inset" component="li" />
</React.Fragment>
);
else return null;
});
if (loading) {
return <TicketSkeleton />;
} else if (countTickets(status, userId) === "" && status !== "closed") {
return (
<div className={classes.noTicketsDiv}>
<span className={classes.noTicketsTitle}>
{status === "pending" ? "Tudo resolvido" : "Pronto pra mais?"}
</span>
<p className={classes.noTicketsText}>
{status === "pending"
? "Nenhum ticket pendente por enquanto. Hora do café!"
: "Aceite um ticket da fila para começar."}
</p>
</div>
);
} else {
return viewTickets;
}
};
return (
<Paper elevation={0} variant="outlined" className={classes.contactsWrapper}>
<Paper elevation={0} square className={classes.tabsHeader}>
<Tabs
value={tab}
onChange={handleChangeTab}
variant="fullWidth"
indicatorColor="primary"
textColor="primary"
aria-label="icon label tabs example"
>
<Tab
value="open"
icon={<MoveToInboxIcon />}
label="Caixa de Entrada"
/>
<Tab
value="closed"
icon={<CheckCircleOutlineIcon />}
label="Resolvidos"
/>
</Tabs>
</Paper>
<Paper square elevation={0} className={classes.contactsSearchBox}>
<div className={classes.serachInputWrapper}>
<SearchIcon className={classes.searchIcon} />
<InputBase
className={classes.contactsSearchInput}
placeholder="Buscar contatos"
type="search"
onChange={handleSearchContact}
/>
</div>
</Paper>
{tab === "open" ? (
<>
<Paper square elevation={0} className={classes.openTicketsList}>
<List style={{ paddingTop: 0 }}>
<div className={classes.ticketsListHeader}>
Meus tickets
<span className={classes.ticketsCount}>
{countTickets("open", userId)}
</span>
</div>
{renderTickets("open", userId)}
</List>
</Paper>
<Paper square elevation={0} className={classes.openTicketsList}>
<List style={{ paddingTop: 0 }}>
<div className={classes.ticketsListHeader}>
Aguardando
<span className={classes.ticketsCount}>
{countTickets("pending", null)}
</span>
</div>
{renderTickets("pending", null)}
</List>
</Paper>
</>
) : (
<Paper square elevation={0} className={classes.closedTicketsList}>
<List>{renderTickets("closed", userId)}</List>
</Paper>
)}
<audio id="sound" preload="auto">
<source src={require("../../assets/sound.mp3")} type="audio/mpeg" />
<source src={require("../../assets/sound.ogg")} type="audio/ogg" />
<embed hidden={true} autostart="false" loop={false} src="./sound.mp3" />
</audio>
</Paper>
);
};
export default TicketsList;