feat: Update application to receive vecard from the client

feat-scaling-ticket-remote-creation
adriano 2024-02-26 11:18:01 -03:00
parent 1d3a6178ba
commit 237fa8124e
10 changed files with 528 additions and 45 deletions

View File

@ -20,12 +20,18 @@ import {
} from "../helpers/ContactsCache";
import { off } from "process";
import GetContactService from "../services/ContactServices/GetContactService"
type IndexQuery = {
searchParam: string;
pageNumber: string;
};
type IndexGetContactQuery = {
name: string;
number: string;
};
interface ExtraInfo {
name: string;
value: string;
@ -84,6 +90,20 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
return res.json({ contacts, count, hasMore });
};
export const getContact = async (
req: Request,
res: Response
): Promise<Response> => {
const { name, number } = req.body as IndexGetContactQuery;
const contact = await GetContactService({
name,
number
});
return res.status(200).json(contact);
};
export const store = async (req: Request, res: Response): Promise<Response> => {
const newContact: ContactData = req.body;
newContact.number = newContact.number.replace("-", "").replace(" ", "");

View File

@ -15,9 +15,9 @@ const CheckContactOpenTickets = async (
if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
let whats = await ListWhatsAppsNumber(whatsappId);
console.log("contactId: ", contactId, " | whatsappId: ", whatsappId);
// console.log("contactId: ", contactId, " | whatsappId: ", whatsappId);
console.log("WHATS: ", JSON.stringify(whats, null, 6));
// console.log("WHATS: ", JSON.stringify(whats, null, 6));
ticket = await Ticket.findOne({
where: {

View File

@ -16,6 +16,8 @@ contactRoutes.get("/contacts/:contactId", isAuth, ContactController.show);
contactRoutes.post("/contacts", isAuth, ContactController.store);
contactRoutes.post("/contact", isAuth, ContactController.getContact);
contactRoutes.put("/contacts/:contactId", isAuth, ContactController.update);
contactRoutes.delete("/contacts/:contactId", isAuth, ContactController.remove);

View File

@ -0,0 +1,38 @@
import AppError from "../../errors/AppError";
import Contact from "../../models/Contact";
import CreateContactService from "./CreateContactService";
interface ExtraInfo {
name: string;
value: string;
}
interface Request {
name: string;
number: string;
email?: string;
profilePicUrl?: string;
extraInfo?: ExtraInfo[];
}
const GetContactService = async ({ name, number }: Request): Promise<Contact> => {
const numberExists = await Contact.findOne({
where: { number }
});
if (!numberExists) {
const contact = await CreateContactService({
name,
number,
})
if (contact == null)
throw new AppError("CONTACT_NOT_FIND")
else
return contact
}
return numberExists
};
export default GetContactService;

View File

@ -98,6 +98,7 @@ import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketSe
import ShowTicketService from "../TicketServices/ShowTicketService";
import ShowQueuesByUser from "../UserServices/ShowQueuesByUser";
import ListWhatsappQueuesByUserQueue from "../UserServices/ListWhatsappQueuesByUserQueue";
import CreateContactService from "../ContactServices/CreateContactService"
var lst: any[] = getWhatsappIds();
@ -479,6 +480,7 @@ const isValidMsg = (msg: any): boolean => {
msg.type === "image" ||
msg.type === "document" ||
msg.type === "vcard" ||
// msg.type === "multi_vcard" ||
msg.type === "sticker"
)
return true;
@ -608,7 +610,7 @@ const handleMessage = async (
return;
}
}
}
if (!isValidMsg(msg)) {
return;
@ -643,7 +645,13 @@ const handleMessage = async (
// media messages sent from me from cell phone, first comes with "hasMedia = false" and type = "image/ptt/etc"
// in this case, return and let this message be handled by "media_uploaded" event, when it will have "hasMedia = true"
if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard") return;
if (
!msg.hasMedia &&
msg.type !== "chat" &&
msg.type !== "vcard" &&
msg.type !== "multi_vcard"
)
return;
} else {
console.log(`\n <<<<<<<<<< RECEIVING MESSAGE:
Parcial msg and msgContact info:
@ -772,6 +780,34 @@ const handleMessage = async (
await verifyQueue(wbot, msg, ticket, contact);
}
if (msg.type === "vcard") {
try {
const array = msg.body.split("\n");
const obj = [];
let contact = "";
for (let index = 0; index < array.length; index++) {
const v = array[index];
const values = v.split(":");
for (let ind = 0; ind < values.length; ind++) {
if (values[ind].indexOf("+") !== -1) {
obj.push({ number: values[ind] });
}
if (values[ind].indexOf("FN") !== -1) {
contact = values[ind + 1];
}
}
}
for await (const ob of obj) {
const cont = await CreateContactService({
name: contact,
number: ob.number.replace(/\D/g, "")
});
}
} catch (error) {
console.log(error);
}
}
const botInfo = await BotIsOnQueue("botqueue");
// Transfer to agent
@ -784,9 +820,7 @@ const handleMessage = async (
ticket.status == "pending" ||
ticket.status == "queueChoice")
) {
const filteredUsers = await findByContain("user:*", "name", msg?.body);
console.log("######## filteredUsers: ", filteredUsers);
const filteredUsers = await findByContain("user:*", "name", msg?.body);
if (filteredUsers && filteredUsers.length > 0) {
if (botInfo.isOnQueue) {

View File

@ -0,0 +1,62 @@
import { Button } from "@material-ui/core";
import React, { useRef } from "react";
import { useEffect } from "react";
import { useState } from "react";
const LS_NAME = 'audioMessageRate';
export default function({url}) {
const audioRef = useRef(null);
const [audioRate, setAudioRate] = useState( parseFloat(localStorage.getItem(LS_NAME) || "1") );
const [showButtonRate, setShowButtonRate] = useState(false);
useEffect(() => {
audioRef.current.playbackRate = audioRate;
localStorage.setItem(LS_NAME, audioRate);
}, [audioRate]);
useEffect(() => {
audioRef.current.onplaying = () => {
setShowButtonRate(true);
};
audioRef.current.onpause = () => {
setShowButtonRate(false);
};
audioRef.current.onended = () => {
setShowButtonRate(false);
};
}, []);
const toogleRate = () => {
let newRate = null;
switch(audioRate) {
case 0.5:
newRate = 1;
break;
case 1:
newRate = 1.5;
break;
case 1.5:
newRate = 2;
break;
case 2:
newRate = 0.5;
break;
default:
newRate = 1;
break;
}
setAudioRate(newRate);
};
return (
<>
<audio ref={audioRef} controls>
<source src={url} type="audio/ogg"></source>
</audio>
{showButtonRate && <Button style={{marginLeft: "5px", marginTop: "-45px"}} onClick={toogleRate}>{audioRate}x</Button>}
</>
);
}

View File

@ -0,0 +1,53 @@
import React, { useEffect } from 'react';
import toastError from "../../errors/toastError";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import { Button, Divider, } from "@material-ui/core";
const LocationPreview = ({ image, link, description }) => {
useEffect(() => {}, [image, link, description]);
const handleLocation = async() => {
try {
window.open(link);
} catch (err) {
toastError(err);
}
}
return (
<>
<div style={{
minWidth: "250px",
}}>
<div>
<div style={{ float: "left" }}>
<img src={image} onClick={handleLocation} style={{ width: "100px" }} />
</div>
{ description && (
<div style={{ display: "flex", flexWrap: "wrap" }}>
<Typography style={{ marginTop: "12px", marginLeft: "15px", marginRight: "15px", float: "left" }} variant="subtitle1" color="primary" gutterBottom>
<div dangerouslySetInnerHTML={{ __html: description.replace('\\n', '<br />') }}></div>
</Typography>
</div>
)}
<div style={{ display: "block", content: "", clear: "both" }}></div>
<div>
<Divider />
<Button
fullWidth
color="primary"
onClick={handleLocation}
disabled={!link}
>Visualizar</Button>
</div>
</div>
</div>
</>
);
};
export default LocationPreview;

View File

@ -1,5 +1,5 @@
import React from "react";
import Markdown from "markdown-to-jsx";
import React from "react"
import Markdown from "markdown-to-jsx"
const elements = [
"a",
@ -139,25 +139,32 @@ const elements = [
"svg",
"text",
"tspan",
];
]
const allowedElements = ["a", "b", "strong", "em", "u", "code", "del"];
const allowedElements = ["a", "b", "strong", "em", "u", "code", "del"]
const CustomLink = ({ children, ...props }) => (
<a {...props} target="_blank" rel="noopener noreferrer">
{children}
</a>
);
)
const MarkdownWrapper = ({ children }) => {
const boldRegex = /\*(.*?)\*/g;
const tildaRegex = /~(.*?)~/g;
const boldRegex = /\*(.*?)\*/g
const tildaRegex = /~(.*?)~/g
if (children && children.includes('BEGIN:VCARD'))
//children = "Diga olá ao seu novo contato clicando em *conversar*!";
children = null
if (children && children.includes('data:image/'))
children = null
if (children && boldRegex.test(children)) {
children = children.replace(boldRegex, "**$1**");
children = children.replace(boldRegex, "**$1**")
}
if (children && tildaRegex.test(children)) {
children = children.replace(tildaRegex, "~~$1~~");
children = children.replace(tildaRegex, "~~$1~~")
}
const options = React.useMemo(() => {
@ -167,20 +174,20 @@ const MarkdownWrapper = ({ children }) => {
overrides: {
a: { component: CustomLink },
},
};
}
elements.forEach(element => {
if (!allowedElements.includes(element)) {
markdownOptions.overrides[element] = el => el.children || null;
markdownOptions.overrides[element] = el => el.children || null
}
});
})
return markdownOptions;
}, []);
return markdownOptions
}, [])
if (!children) return null;
if (!children) return null
return <Markdown options={options}>{children}</Markdown>;
};
return <Markdown options={options}>{children}</Markdown>
}
export default MarkdownWrapper;
export default MarkdownWrapper

View File

@ -23,6 +23,11 @@ import {
} from "@material-ui/icons";
import MarkdownWrapper from "../MarkdownWrapper";
import VcardPreview from "../VcardPreview";
import LocationPreview from "../LocationPreview";
import Audio from "../Audio";
import ModalImageCors from "../ModalImageCors";
import MessageOptionsMenu from "../MessageOptionsMenu";
import whatsBackground from "../../assets/wa-background.png";
@ -488,27 +493,109 @@ const MessagesList = ({ ticketId, isGroup }) => {
setAnchorEl(null);
};
// const checkMessageMedia = (message) => {
// if (message.mediaType === "image") {
// return <ModalImageCors imageUrl={message.mediaUrl} />;
// }
// 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 (
// <>
// <div className={classes.downloadMedia}>
// <Button
// startIcon={<GetApp />}
// color="primary"
// variant="outlined"
// target="_blank"
// href={message.mediaUrl}
// >
// Download
// </Button>
// </div>
// <Divider />
// </>
// );
// }
// };
const checkMessageMedia = (message) => {
if (message.mediaType === "image") {
return <ModalImageCors imageUrl={message.mediaUrl} />;
}
if (message.mediaType === "audio") {
if (message.mediaType === "location" && message.body.split('|').length >= 2) {
let locationParts = message.body.split('|')
let imageLocation = locationParts[0]
let linkLocation = locationParts[1]
return (
<audio controls>
<source src={message.mediaUrl} type="audio/ogg"></source>
</audio>
);
}
let descriptionLocation = null
if (message.mediaType === "video") {
if (locationParts.length > 2)
descriptionLocation = message.body.split('|')[2]
return <LocationPreview image={imageLocation} link={linkLocation} description={descriptionLocation} />
}
else if (message.mediaType === "vcard") {
//console.log("vcard")
//console.log(message)
let array = message.body.split("\n")
let obj = []
let contact = ""
for (let index = 0; index < array.length; index++) {
const v = array[index]
let values = v.split(":")
for (let ind = 0; ind < values.length; ind++) {
if (values[ind].indexOf("+") !== -1) {
obj.push({ number: values[ind] })
}
if (values[ind].indexOf("FN") !== -1) {
contact = values[ind + 1]
}
}
}
return <VcardPreview contact={contact} numbers={obj[0]?.number} />
}
/*else if (message.mediaType === "multi_vcard") {
console.log("multi_vcard")
console.log(message)
if(message.body !== null && message.body !== "") {
let newBody = JSON.parse(message.body)
return (
<>
{
newBody.map(v => (
<VcardPreview contact={v.name} numbers={v.number} />
))
}
</>
)
} else return (<></>)
}*/
else if (/^.*\.(jpe?g|png|gif)?$/i.exec(message.mediaUrl) && message.mediaType === "image") {
return <ModalImageCors imageUrl={message.mediaUrl} />
} else if (message.mediaType === "audio") {
return <Audio url={message.mediaUrl} />
} else if (message.mediaType === "video") {
return (
<video
className={classes.messageMedia}
src={message.mediaUrl}
controls
/>
);
)
} else {
return (
<>
@ -525,7 +612,7 @@ const MessagesList = ({ ticketId, isGroup }) => {
</div>
<Divider />
</>
);
)
}
};
@ -643,6 +730,88 @@ const MessagesList = ({ ticketId, isGroup }) => {
);
};
// const renderMessages = () => {
// if (messagesList.length > 0) {
// const viewMessagesList = messagesList.map((message, index) => {
// if (!message.fromMe) {
// return (
// <React.Fragment key={message.id}>
// {renderDailyTimestamps(message, index)}
// {renderMessageDivider(message, index)}
// <div className={classes.messageLeft}>
// <IconButton
// variant="contained"
// size="small"
// id="messageActionsButton"
// disabled={message.isDeleted}
// className={classes.messageActionsButton}
// onClick={(e) => handleOpenMessageOptionsMenu(e, message)}
// >
// <ExpandMore />
// </IconButton>
// {isGroup && (
// <span className={classes.messageContactName}>
// {message.contact?.name}
// </span>
// )}
// {message.mediaUrl && checkMessageMedia(message)}
// <div className={classes.textContentItem}>
// {message.quotedMsg && renderQuotedMessage(message)}
// <MarkdownWrapper>{message.body}</MarkdownWrapper>
// <span className={classes.timestamp}>
// {format(parseISO(message.createdAt), "HH:mm")}
// </span>
// </div>
// </div>
// </React.Fragment>
// );
// } else {
// return (
// <React.Fragment key={message.id}>
// {renderDailyTimestamps(message, index)}
// {renderMessageDivider(message, index)}
// <div className={classes.messageRight}>
// <IconButton
// variant="contained"
// size="small"
// id="messageActionsButton"
// disabled={message.isDeleted}
// className={classes.messageActionsButton}
// onClick={(e) => handleOpenMessageOptionsMenu(e, message)}
// >
// <ExpandMore />
// </IconButton>
// {message.mediaUrl && checkMessageMedia(message)}
// <div
// className={clsx(classes.textContentItem, {
// [classes.textContentItemDeleted]: message.isDeleted,
// })}
// >
// {message.isDeleted && (
// <Block
// color="disabled"
// fontSize="small"
// className={classes.deletedIcon}
// />
// )}
// {message.quotedMsg && renderQuotedMessage(message)}
// <MarkdownWrapper>{message.body}</MarkdownWrapper>
// <span className={classes.timestamp}>
// {format(parseISO(message.createdAt), "HH:mm")}
// {renderMessageAck(message)}
// </span>
// </div>
// </div>
// </React.Fragment>
// );
// }
// });
// return viewMessagesList;
// } else {
// return <div>Say hello to your new contact!</div>;
// }
// };
const renderMessages = () => {
if (messagesList.length > 0) {
const viewMessagesList = messagesList.map((message, index) => {
@ -667,7 +836,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
{message.contact?.name}
</span>
)}
{message.mediaUrl && checkMessageMedia(message)}
{(message.mediaUrl || message.mediaType === "location" || message.mediaType === "vcard"
//|| message.mediaType === "multi_vcard"
) && checkMessageMedia(message)}
<div className={classes.textContentItem}>
{message.quotedMsg && renderQuotedMessage(message)}
<MarkdownWrapper>{message.body}</MarkdownWrapper>
@ -677,7 +848,7 @@ const MessagesList = ({ ticketId, isGroup }) => {
</div>
</div>
</React.Fragment>
);
)
} else {
return (
<React.Fragment key={message.id}>
@ -694,7 +865,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
>
<ExpandMore />
</IconButton>
{message.mediaUrl && checkMessageMedia(message)}
{(message.mediaUrl || message.mediaType === "location" || message.mediaType === "vcard"
//|| message.mediaType === "multi_vcard"
) && checkMessageMedia(message)}
<div
className={clsx(classes.textContentItem, {
[classes.textContentItemDeleted]: message.isDeleted,
@ -716,12 +889,12 @@ const MessagesList = ({ ticketId, isGroup }) => {
</div>
</div>
</React.Fragment>
);
)
}
});
return viewMessagesList;
})
return viewMessagesList
} else {
return <div>Say hello to your new contact!</div>;
return <div>Say hello to your new contact!</div>
}
};

View File

@ -0,0 +1,94 @@
import React, { useEffect, useState, useContext } from 'react';
import { useHistory } from "react-router-dom";
import toastError from "../../errors/toastError";
import api from "../../services/api";
import Avatar from "@material-ui/core/Avatar";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import { AuthContext } from "../../context/Auth/AuthContext";
import { Button, Divider, } from "@material-ui/core";
const VcardPreview = ({ contact, numbers }) => {
const history = useHistory();
const { user } = useContext(AuthContext);
const [selectedContact, setContact] = useState({
name: "",
number: 0,
profilePicUrl: ""
});
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchContacts = async () => {
try {
let contactObj = {
name: contact,
// number: numbers.replace(/\D/g, ""),
number: numbers !== undefined && numbers.replace(/\D/g, ""),
email: ""
}
console.log('contactObj: ', contactObj)
// return
const { data } = await api.post("/contact", contactObj);
setContact(data)
} catch (err) {
console.log(err)
toastError(err);
}
};
fetchContacts();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [contact, numbers]);
const handleNewChat = async () => {
try {
const { data: ticket } = await api.post("/tickets", {
contactId: selectedContact.id,
userId: user.id,
status: "open",
});
history.push(`/tickets/${ticket.id}`);
} catch (err) {
toastError(err);
}
}
return (
<>
<div style={{
minWidth: "250px",
}}>
<Grid container spacing={1}>
<Grid item xs={2}>
<Avatar src={selectedContact.profilePicUrl} />
</Grid>
<Grid item xs={9}>
<Typography style={{ marginTop: "12px", marginLeft: "10px" }} variant="subtitle1" color="primary" gutterBottom>
{selectedContact.name}
</Typography>
</Grid>
<Grid item xs={12}>
<Divider />
<Button
fullWidth
color="primary"
onClick={handleNewChat}
disabled={!selectedContact.number}
>Conversar</Button>
</Grid>
</Grid>
</div>
</>
);
};
export default VcardPreview;