Alteração do endpoint de api externa

pull/20/head
adriano 2022-11-10 13:31:03 -03:00
parent 6a5fb13560
commit 5cf6878e8c
3 changed files with 180 additions and 61 deletions

View File

@ -1,33 +1,51 @@
const fsPromises = require("fs/promises");
const fs = require('fs')
const fs = require('fs')
import axios from 'axios';
import * as https from "https";
const endPointQuery = async (url: string) => {
const endPointQuery = async (url: string, method: string, param: string = '') => {
let response:any = null
let response: any = null
try {
const httpsAgent = new https.Agent({ rejectUnauthorized: false, });
try {
// const url = 'https://sos.espacolaser.com.br/api/whatsapp/ticket/R32656'
const httpsAgent = new https.Agent({ rejectUnauthorized: false, });
response = await axios.get(url, {
httpsAgent,
headers: {
'x-access-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOnsiaWQiOjEsInJvbGUiOiJjbGllbnQiLCJob3N0Ijoic29zLmVzcGFjb2xhc2VyLmNvbS5iciIsInRlbmFudCI6ImVzcGFjb2xhc2VyIiwibmFtZSI6IlNFTlNSLklUIiwiY29tcGFueSI6eyJpZCI6NDR9fSwiZGF0ZSI6MTY2MTI2MjY0MywiaWF0IjoxNjYxMjYyNjQzLCJleHAiOjE3NDc2NjI2NDN9.zf91OmRs4_C7B8OlVpLLrQMiRBYc7edP4qAdH_hqxpk',
'Origin': 'espacolaser'
}
});
console.log(`TEST URL CLIENT GET ROUTE: ${url} | STATUS CODE: ${response.status}`);
if (method == 'get') {
// const url = 'https://sos.espacolaser.com.br/api/whatsapp/ticket/R32656'
response = await axios.get(url, {
httpsAgent,
headers: {
'x-access-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOnsiaWQiOjEsInJvbGUiOiJjbGllbnQiLCJob3N0Ijoic29zLmVzcGFjb2xhc2VyLmNvbS5iciIsInRlbmFudCI6ImVzcGFjb2xhc2VyIiwibmFtZSI6IlNFTlNSLklUIiwiY29tcGFueSI6eyJpZCI6NDR9fSwiZGF0ZSI6MTY2MTI2MjY0MywiaWF0IjoxNjYxMjYyNjQzLCJleHAiOjE3NDc2NjI2NDN9.zf91OmRs4_C7B8OlVpLLrQMiRBYc7edP4qAdH_hqxpk',
'Origin': 'espacolaser'
}
});
console.log(`TEST URL CLIENT GET ROUTE: ${url} | STATUS CODE: ${response.status}`);
}
else if (method == 'post') {
} catch (error) {
console.error(error);
}
return response
// const url = 'http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php'
response = await axios.post(url, {
'auth': '0424bd59b807674191e7d77572075f33',
'jsonrpc': '2.0',
'method': 'chamado.ematendimento',
'params[ccusto]': param,
id: '101'
}, {
httpsAgent,
headers: { 'Content-Type': 'multipart/form-data' },
});
console.log(`TEST URL CLIENT POST ROUTE: ${url} | STATUS CODE: ${response.status}`);
}
} catch (error) {
console.error(error);
}
export default endPointQuery;
return response
}
export default endPointQuery;

View File

@ -55,7 +55,7 @@ async function queryDialogFlow(
}
} catch (error) {
Sentry.captureException(error);
logger.error(`Error handling whatsapp message: Err: ${error}`);
logger.error(`Error handling whatsapp message: Err 2: ${error}`);
}
return null;

View File

@ -37,7 +37,7 @@ import { date } from "faker";
import ShowQueueService from "../QueueService/ShowQueueService";
import ShowTicketMessage from "../TicketServices/ShowTicketMessage"
import BotIsOnQueue from "../../helpers/BotIsOnQueue"
import BotIsOnQueue from "../../helpers/BotIsOnQueue"
import Queue from "../../models/Queue";
import fs from 'fs';
@ -46,7 +46,7 @@ import { StartWhatsAppSession } from "../../services/WbotServices/StartWhatsAppS
import { removeWbot } from '../../libs/wbot'
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import data_ura from './ura'
import msg_client_transfer from './ura_msg_transfer'
import final_message from "./ura_final_message";
@ -60,7 +60,7 @@ import bot_actions from './BotActions'
import ShowTicketService from "../TicketServices/ShowTicketService";
import { updateTicketCacheByTicketId } from '../../helpers/TicketCache'
import endPointQuery from "../../helpers/EndpointQuery";
@ -179,6 +179,9 @@ const verifyMessage = async (
};
async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Contact, message: string) {
const body = message.replace(/\\n/g, '\n');
@ -195,13 +198,16 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
await new Promise(f => setTimeout(f, 1000));
// const url = 'https://sos.espacolaser.com.br/api/whatsapps/ticket/R32656'
const endPointResponse = await endPointQuery(msgAction.actions[1])
let endPointResponse = await endPointQuery(msgAction.actions[1], 'get')
if (endPointResponse) {
const response = Object.entries(endPointResponse.data);
let msg_endpoint_response = ''
let msg_endpoint2: any = []
let centro_de_custo = ''
for (let i = 0; i < response.length; i++) {
msg_endpoint_response += `*${response[i][0]}*: ${response[i][1]}\n`
@ -210,39 +216,134 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
if (endPointResponse.data.status == 'EM ATENDIMENTO') {
if (endPointResponse.data.centro_custo_departamento && endPointResponse.data.centro_custo_departamento.trim().length > 0) {
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Seu chamado está em atendimento pelo analista ${endPointResponse.data.tecnico} + Última informação do CHAT
// Verificar pelo “ID do solicitante” se existe chamado na HIT -> Se houver, informar status (Vamos alinhar os detalhes)`);
centro_de_custo = endPointResponse.data.centro_custo_departamento
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n Seu chamado está em atendimento\n\n *Analista:* ${endPointResponse.data.tecnico}\n *Chat:* ${endPointResponse.data.chat ? endPointResponse.data.chat : ""}\n\n_Digite *0* para voltar ao menu principal._`);
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n Seu chamado está em atendimento\n\n${msg_endpoint_response}\n_Digite *0* para voltar ao menu principal._`);
let response2 = await endPointQuery('http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php', 'post', centro_de_custo.trim())
if (response2 && response2.data.result) {
response2 = response2.data.result;
for (let i = 0; i < response2.length; i++) {
let data = ''
let sub_data = '*Atualizações:*\n\n'
const properties: any = Object.entries(response2[i]);
for (let x = 0; x < properties.length; x++) {
if (typeof (properties[x][1]) != 'object') {
data += `*${properties[x][0]}*: ${properties[x][1].replace(/(\r\n|\n|\r)/gm, "")}\n`
}
else if (typeof (properties[x][1]) == 'object') {
const sub_properties = properties[x][1];
for (let k = 0; k < sub_properties.length; k++) {
const inner_properties: any = Object.entries(sub_properties[k]);
for (let y = 0; y < inner_properties.length; y++) {
sub_data += `*${inner_properties[y][0]}*: ${inner_properties[y][1].replace(/(\r\n|\n|\r)/gm, "")}\n`
}
sub_data += '\n'
}
}
}
msg_endpoint2.push({ header: data, body: sub_data })
}
}
else {
msg_endpoint2 = null
}
}
const monitoramento_response = async (response: any | null) => {
if (!response) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Houve um erro ao tentar consultar o monitoramento!\n\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
}
else if (response.length > 0) {
for (let i = 0; i < response.length; i++) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`,
`*Chamado ${extractCallCode(msgAction.msgBody)}*\n*Centro de custo: ${centro_de_custo}*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body} _Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
}
}
else {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Sem incidente!\n\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
}
}
const itsm_response = async (message1: string = '', message2: string = '') => {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n ${message1}\n\n${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
}
if (endPointResponse.data.status == 'EM ATENDIMENTO') {
await itsm_response('Seu chamado está em atendimento')
await monitoramento_response(msg_endpoint2)
}
else if (endPointResponse.data.categoria == 'ELOS' || (endPointResponse.data.subcategoria == 'VENDA' || endPointResponse.data.subcategoria == 'INDISPONIBILIDADE')) {
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n Vi que está com um problema no ELOS\n\n *Status:* ${endPointResponse.data.status}\n\nSe seu caso for urgente para concluir uma venda, digite “URGENTE”\n_Digite *0* para voltar ao menu principal._`);
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n Vi que está com um problema no ELOS\n\n${msg_endpoint_response}\nSe seu caso for urgente para concluir uma venda, digite “URGENTE”\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
await itsm_response('Vi que está com um problema no ELOS', `\nSe seu caso for urgente para concluir uma venda, digite “URGENTE”\n`)
await monitoramento_response(msg_endpoint2)
}
else if ((endPointResponse.data.categoria == 'INFRAESTRUTURA' || endPointResponse.data.subcategoria == 'INTERNET' ||
endPointResponse.data.terceiro_nivel == 'QUEDA TOTAL' || endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO') ||
(endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO' || endPointResponse.data.terceiro_nivel == 'ABERTO')) {
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n${msg_endpoint_response}\n Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!`);
await itsm_response('', `\n Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!`)
await monitoramento_response(msg_endpoint2)
await transferTicket(0, wbot, ticket, contact)
}
else {
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n *Status:* ${endPointResponse.data.status}\n *Data:* ${endPointResponse.data.data_chat ? endPointResponse.data.data_chat : ""}\n *Hora:* ${endPointResponse.data.hora_chat ? endPointResponse.data.hora_chat : ""} \n\n Por favor, aguarde atendimento e acompanhe sua solicitação no SOS.\n_Digite *0* para voltar ao menu principal._`);
const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*\n\n${msg_endpoint_response}\n Por favor, aguarde atendimento e acompanhe sua solicitação no SOS.\n_Digite *0* para voltar ao menu principal._`);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
await itsm_response('', `\n Por favor, aguarde atendimento e acompanhe sua solicitação no SOS.`)
await monitoramento_response(msg_endpoint2)
}
}
@ -260,15 +361,15 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
await transferTicket(+msgAction.actions[1], wbot, ticket, contact)
}
else if (msgAction.actions[0] == 'send_file'){
else if (msgAction.actions[0] == 'send_file') {
const sourcePath = path.join(__dirname,`../../../public/bot`)
const sourcePath = path.join(__dirname, `../../../public/bot`)
const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000));
await botSendMedia(ticket,contact,wbot,sourcePath, msgAction.actions[1])
await botSendMedia(ticket, contact, wbot, sourcePath, msgAction.actions[1])
}
@ -368,7 +469,7 @@ const verifyQueue = async (
let choosenQueue = null
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue')
const botInfo = await BotIsOnQueue('botqueue')
// const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 }
if (botInfo.isOnQueue) {
@ -408,7 +509,7 @@ const verifyQueue = async (
ticketData: { queueId: choosenQueue.id },
ticketId: ticket.id
});
let botOptions = ''
@ -425,7 +526,7 @@ const verifyQueue = async (
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat);
return
}
//
@ -475,7 +576,7 @@ const verifyQueue = async (
}
}
};
@ -548,20 +649,20 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, med
// const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, newMedia, { sendAudioAsVoice: true });
const newMedia = MessageMedia.fromFilePath(`${mediaPath}/${fileNameExtension}`);
const newMedia = MessageMedia.fromFilePath(`${mediaPath}/${fileNameExtension}`);
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, {caption: 'this is my caption'});
const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, { caption: 'this is my caption' });
// client.sendMessage("xxxxxxxx@c.us", media, {caption: "some caption"}); })();
// client.sendMessage(msg.from, attachmentData, { caption: 'Here\'s your requested media.' });
await ticket.update({ lastMessage: fileNameExtension });
verifyMessage(sentMessage, ticket, contact);
},
3000,
ticket.id
@ -650,8 +751,8 @@ const handleMessage = async (
const unreadMessages = msg.fromMe ? 0 : chat.unreadCount;
const contact = await verifyContact(msgContact);
const contact = await verifyContact(msgContact);
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
@ -661,7 +762,7 @@ const handleMessage = async (
wbot.id!,
unreadMessages,
groupContact
);
);
//
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -669,7 +770,7 @@ const handleMessage = async (
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen
if (wbot.id != ticket.whatsappId) {
await ticket.update({ whatsappId: wbot.id });
}
@ -706,7 +807,7 @@ const handleMessage = async (
await sendDialogflowAwswer(wbot, ticket, msg, contact, chat);
}
// if (msg.body.trim() == 'broken') {
// throw new Error('Throw makes it go boom!')
@ -729,7 +830,7 @@ const handleMessage = async (
if (whatsapp.status == 'CONNECTED') {
let timestamp = Math.floor(Date.now() / 1000)
@ -738,7 +839,7 @@ const handleMessage = async (
await restartWhatsSession(whatsapp)
}
}