Adaptação para abrir links de whasapp wa pelo brower usando plugin de terceiro no chrome

adriano 2023-06-06 14:59:06 -03:00
parent bec2d612b3
commit 48834af7de
8 changed files with 195 additions and 95 deletions

View File

@ -41,6 +41,7 @@ interface TicketData {
status: string; status: string;
queueId: number; queueId: number;
userId: number; userId: number;
msg?: string,
} }
@ -51,6 +52,7 @@ import TicketEmiterSumOpenClosedByUser from "../helpers/OnlineReporEmiterInfoByU
import CountTicketService from "../services/TicketServices/CountTicketService"; import CountTicketService from "../services/TicketServices/CountTicketService";
import CountTicketsByUserQueue from "../services/UserServices/CountTicketsByUserQueue"; import CountTicketsByUserQueue from "../services/UserServices/CountTicketsByUserQueue";
import ShowUserService from "../services/UserServices/ShowUserService"; import ShowUserService from "../services/UserServices/ShowUserService";
import axios from "axios";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
@ -90,7 +92,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
}; };
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { contactId, status, userId }: TicketData = req.body; const { contactId, status, userId, msg }: TicketData = req.body;
console.log('TICKET CREATE: ', 'contactId: ', contactId, ' | status: ', status, ' | userId: ', userId) console.log('TICKET CREATE: ', 'contactId: ', contactId, ' | status: ', status, ' | userId: ', userId)
@ -98,11 +100,11 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } }); let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } });
if (ticket) { if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open', userId: userId, }, ticketId: ticket.id }); await UpdateTicketService({ ticketData: { status: 'open', userId: userId,}, ticketId: ticket.id, msg });
} }
else { else {
ticket = await CreateTicketService({ contactId, status, userId }); ticket = await CreateTicketService({ contactId, status, userId, msg });
} }
const io = getIO(); const io = getIO();
@ -140,7 +142,6 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json({ contact, statusChatEnd, schedulesContact }); return res.status(200).json({ contact, statusChatEnd, schedulesContact });
}; };
export const count = async (req: Request, res: Response): Promise<Response> => { export const count = async (req: Request, res: Response): Promise<Response> => {
// type indexQ = { status: string; date?: string; }; // type indexQ = { status: string; date?: string; };
@ -152,8 +153,6 @@ export const count = async (req: Request, res: Response): Promise<Response> => {
}; };
export const update = async (req: Request, res: Response): Promise<Response> => { export const update = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;

View File

@ -221,6 +221,10 @@ export const initIO = (httpServer: Server): SocketIO => {
socket.on("joinChatBox", (ticketId: string) => { socket.on("joinChatBox", (ticketId: string) => {
logger.info("A client joined a ticket channel"); logger.info("A client joined a ticket channel");
const regex = /^[0-9\b]+$/; // Regular expression to match only numbers
if (ticketId && !ticketId.match(regex)) return
socket.join(ticketId); socket.join(ticketId);
}); });

View File

@ -19,6 +19,17 @@ const ListMessagesService = async ({
pageNumber = "1", pageNumber = "1",
ticketId ticketId
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
if (ticketId && ticketId.includes("&&text=")) {
return {
messages: [],
ticket: new Ticket,
count: 0,
hasMore: false
};
}
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
if (!ticket) { if (!ticket) {

View File

@ -19,6 +19,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import Whatsapp from "../../models/Whatsapp"; import Whatsapp from "../../models/Whatsapp";
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue"; import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
import User from "../../models/User"; import User from "../../models/User";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
let flatten = require('flat') let flatten = require('flat')
@ -27,12 +28,14 @@ interface Request {
contactId: number; contactId: number;
status: string; status: string;
userId: number; userId: number;
msg?: string
} }
const CreateTicketService = async ({ const CreateTicketService = async ({
contactId, contactId,
status, status,
userId userId,
msg = ''
}: Request): Promise<Ticket> => { }: Request): Promise<Ticket> => {
try { try {
@ -72,6 +75,12 @@ const CreateTicketService = async ({
// console.log('CONTACT ticket.id: ', ticket.id) // console.log('CONTACT ticket.id: ', ticket.id)
// console.log('>>>>>>>>>>>>>>>>> msg: ', msg)
if (msg.length > 0) {
sendWhatsAppMessageSocket(ticket, msg)
}
try { try {

View File

@ -8,6 +8,7 @@ import ShowTicketService from "./ShowTicketService";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache' import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
var flatten = require('flat') var flatten = require('flat')
@ -16,12 +17,13 @@ interface TicketData {
status?: string; status?: string;
userId?: number; userId?: number;
queueId?: number; queueId?: number;
statusChatEnd?: string statusChatEnd?: string;
} }
interface Request { interface Request {
ticketData: TicketData; ticketData: TicketData;
ticketId: string | number; ticketId: string | number;
msg?: string
} }
interface Response { interface Response {
@ -32,77 +34,82 @@ interface Response {
const UpdateTicketService = async ({ const UpdateTicketService = async ({
ticketData, ticketData,
ticketId ticketId,
msg=''
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
try { try {
const { status, userId, queueId, statusChatEnd } = ticketData; const { status, userId, queueId, statusChatEnd } = ticketData;
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
// await SetTicketMessagesAsRead(ticket); // await SetTicketMessagesAsRead(ticket);
const oldStatus = ticket.status; const oldStatus = ticket.status;
const oldUserId = ticket.user?.id; const oldUserId = ticket.user?.id;
if (oldStatus === "closed") { if (oldStatus === "closed") {
await CheckContactOpenTickets(ticket.contact.id); await CheckContactOpenTickets(ticket.contact.id);
} }
await ticket.update({ await ticket.update({
status, status,
queueId, queueId,
userId, userId,
statusChatEnd statusChatEnd
});
await ticket.reload();
// TEST DEL
try {
// const { name, number } = await ShowContactService(ticket.contactId)
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo']
delete ticket_obj['user']
ticket_obj = flatten(ticket_obj)
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
} catch (error) {
console.log('There was an error on UpdateTicketService.ts on createTicketCache: ', error)
}
//
let io = getIO();
if (ticket.status !== oldStatus || ticket.user?.id !== oldUserId) {
io.to(oldStatus).emit("ticket", {
action: "delete",
ticketId: ticket.id
}); });
}
await ticket.reload();
if (msg.length > 0) {
sendWhatsAppMessageSocket(ticket, msg)
}
// TEST DEL
try {
// const { name, number } = await ShowContactService(ticket.contactId)
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo']
delete ticket_obj['user']
ticket_obj = flatten(ticket_obj)
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
} catch (error) {
console.log('There was an error on UpdateTicketService.ts on createTicketCache: ', error)
}
//
let io = getIO();
if (ticket.status !== oldStatus || ticket.user?.id !== oldUserId) {
io.to(oldStatus).emit("ticket", {
action: "delete",
ticketId: ticket.id
});
}
io.to(ticket.status) io.to(ticket.status)
.to("notification") .to("notification")
.to(ticketId.toString()) .to(ticketId.toString())
.emit("ticket", { .emit("ticket", {
action: "update",
ticket
});
io.emit("ticketStatus", {
action: "update", action: "update",
ticket ticketStatus: { ticketId: ticket.id, status: ticket.status }
}); });
io.emit("ticketStatus", { return { ticket, oldStatus, oldUserId };
action: "update",
ticketStatus: { ticketId: ticket.id, status: ticket.status }
});
return { ticket, oldStatus, oldUserId };
} catch (error: any) { } catch (error: any) {
console.error('===> Error on UpdateTicketService.ts file: \n', error) console.error('===> Error on UpdateTicketService.ts file: \n', error)

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, useContext } from "react";
import { useParams, useHistory } from "react-router-dom"; import { useParams, useHistory } from "react-router-dom";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
@ -17,6 +17,8 @@ import api from "../../services/api";
import { ReplyMessageProvider } from "../../context/ReplyingMessage/ReplyingMessageContext"; import { ReplyMessageProvider } from "../../context/ReplyingMessage/ReplyingMessageContext";
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError";
import { AuthContext } from "../../context/Auth/AuthContext"
const drawerWidth = 320; const drawerWidth = 320;
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
@ -74,6 +76,10 @@ const useStyles = makeStyles((theme) => ({
})); }));
const Ticket = () => { const Ticket = () => {
const { user } = useContext(AuthContext);
const { ticketId } = useParams(); const { ticketId } = useParams();
const history = useHistory(); const history = useHistory();
const classes = useStyles(); const classes = useStyles();
@ -89,32 +95,92 @@ const Ticket = () => {
setLoading(true); setLoading(true);
const delayDebounceFn = setTimeout(() => { const delayDebounceFn = setTimeout(() => {
const fetchTicket = async () => { const fetchTicket = async () => {
try { try {
// maria julia let number
let msg
let contactId
const { data } = await api.get("/tickets/" + ticketId); if (ticketId && ticketId.includes("&&text=")) {
// setContact(data.contact); number = ticketId.split('&&text=')[0]
// setTicket(data); msg = ticketId.split('&&text=')[1]
setContact(data.contact.contact); msg = decodeURIComponent(msg);
setTicket(data.contact);
console.log('NUMBER: ', number)
const { data: data0 } = await api.get("/contacts/", { params: { searchParam: number, pageNumber: "1" }, });
if (data0 && data0.contacts.length > 0) {
console.log('-----> data: ', data0.contacts[0].id)
contactId = data0.contacts[0].id
}
else {
console.log('NO CONTACT whith this NUMBER: ', number)
const values = {
name: number,
number: number,
};
const { data: data1 } = await api.post("/contacts", values);
console.log('data1: ', data1)
contactId = data1.id
}
const { data: ticket } = await api.post("/tickets", {
contactId: contactId,
userId: user.id,
status: "open",
msg
});
window.location.reload();
history.push(`/tickets/${ticket.id}`);
window.location.reload();
}
else {
console.log('>>>>>>>>>>>>>>>>>>>>>>>>> ticketId: ', ticketId)
const { data } = await api.get("/tickets/" + ticketId);
// setContact(data.contact);
// setTicket(data);
setContact(data.contact.contact);
setTicket(data.contact);
setStatusChatEnd(data.statusChatEnd)
setLoading(false);
}
setStatusChatEnd(data.statusChatEnd)
setLoading(false);
} catch (err) { } catch (err) {
setLoading(false); setLoading(false);
console.log('ERROR: ', err)
toastError(err); toastError(err);
} }
}; };
fetchTicket(); fetchTicket();
}, 500); }, 500);
return () => clearTimeout(delayDebounceFn); return () => clearTimeout(delayDebounceFn);
}, [ticketId, history]); }, [ticketId, history, user.id]);
useEffect(() => { useEffect(() => {
const regex = /^[0-9\b]+$/; // Regular expression to match only numbers
if (ticketId && !ticketId.match(regex)) return
const socket = openSocket(process.env.REACT_APP_BACKEND_URL); const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("connect", () => socket.emit("joinChatBox", ticketId)); socket.on("connect", () => socket.emit("joinChatBox", ticketId));
@ -172,7 +238,7 @@ const Ticket = () => {
/> />
</div> </div>
<div className={classes.ticketActionButtons}> <div className={classes.ticketActionButtons}>
<TicketActionButtons ticket={ticket} statusChatEnd={statusChatEnd}/> <TicketActionButtons ticket={ticket} statusChatEnd={statusChatEnd} />
</div> </div>
</TicketHeader> </TicketHeader>
<ReplyMessageProvider> <ReplyMessageProvider>

View File

@ -1,4 +1,6 @@
import React, { useState, useEffect, useReducer, useContext } from "react"; import React, { useState, useEffect, useReducer, useContext } from "react";
import openSocket from "socket.io-client"; import openSocket from "socket.io-client";
import { makeStyles } from "@material-ui/core/styles"; import { makeStyles } from "@material-ui/core/styles";
@ -183,7 +185,9 @@ const TicketsList = (props) => {
const { searchTicket } = useContext(SearchTicketContext) const { searchTicket } = useContext(SearchTicketContext)
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }); dispatch({ type: "RESET" });
setPageNumber(1); setPageNumber(1);