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

@ -3,31 +3,49 @@ const fs = require('fs')
import axios from 'axios'; import axios from 'axios';
import * as https from "https"; 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 { try {
const httpsAgent = new https.Agent({ rejectUnauthorized: false, }); const httpsAgent = new https.Agent({ rejectUnauthorized: false, });
// const url = 'https://sos.espacolaser.com.br/api/whatsapp/ticket/R32656' 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') {
response = await axios.get(url, { // const url = 'http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php'
httpsAgent,
headers: {
'x-access-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOnsiaWQiOjEsInJvbGUiOiJjbGllbnQiLCJob3N0Ijoic29zLmVzcGFjb2xhc2VyLmNvbS5iciIsInRlbmFudCI6ImVzcGFjb2xhc2VyIiwibmFtZSI6IlNFTlNSLklUIiwiY29tcGFueSI6eyJpZCI6NDR9fSwiZGF0ZSI6MTY2MTI2MjY0MywiaWF0IjoxNjYxMjYyNjQzLCJleHAiOjE3NDc2NjI2NDN9.zf91OmRs4_C7B8OlVpLLrQMiRBYc7edP4qAdH_hqxpk',
'Origin': 'espacolaser'
}
});
console.log(`TEST URL CLIENT GET ROUTE: ${url} | STATUS CODE: ${response.status}`);
} catch (error) {
console.error(error);
}
return response 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) { } catch (error) {
Sentry.captureException(error); Sentry.captureException(error);
logger.error(`Error handling whatsapp message: Err: ${error}`); logger.error(`Error handling whatsapp message: Err 2: ${error}`);
} }
return null; return null;

View File

@ -37,7 +37,7 @@ import { date } from "faker";
import ShowQueueService from "../QueueService/ShowQueueService"; import ShowQueueService from "../QueueService/ShowQueueService";
import ShowTicketMessage from "../TicketServices/ShowTicketMessage" import ShowTicketMessage from "../TicketServices/ShowTicketMessage"
import BotIsOnQueue from "../../helpers/BotIsOnQueue" import BotIsOnQueue from "../../helpers/BotIsOnQueue"
import Queue from "../../models/Queue"; import Queue from "../../models/Queue";
import fs from 'fs'; import fs from 'fs';
@ -179,6 +179,9 @@ const verifyMessage = async (
}; };
async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Contact, message: string) { async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Contact, message: string) {
const body = message.replace(/\\n/g, '\n'); 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)); await new Promise(f => setTimeout(f, 1000));
// const url = 'https://sos.espacolaser.com.br/api/whatsapps/ticket/R32656' // 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) { if (endPointResponse) {
const response = Object.entries(endPointResponse.data); const response = Object.entries(endPointResponse.data);
let msg_endpoint_response = '' let msg_endpoint_response = ''
let msg_endpoint2: any = []
let centro_de_custo = ''
for (let i = 0; i < response.length; i++) { for (let i = 0; i < response.length; i++) {
msg_endpoint_response += `*${response[i][0]}*: ${response[i][1]}\n` 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 centro_de_custo = endPointResponse.data.centro_custo_departamento
// Verificar pelo “ID do solicitante” se existe chamado na HIT -> Se houver, informar status (Vamos alinhar os detalhes)`);
// 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 verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000)); 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')) { 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._`); await itsm_response('Vi que está com um problema no ELOS', `\nSe seu caso for urgente para concluir uma venda, digite “URGENTE”\n`)
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 monitoramento_response(msg_endpoint2)
await new Promise(f => setTimeout(f, 1000));
} }
else if ((endPointResponse.data.categoria == 'INFRAESTRUTURA' || endPointResponse.data.subcategoria == 'INTERNET' || 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 == 'QUEDA TOTAL' || endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO') ||
(endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO' || endPointResponse.data.terceiro_nivel == 'ABERTO')) { (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) await transferTicket(0, wbot, ticket, contact)
} }
else { 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._`); await itsm_response('', `\n Por favor, aguarde atendimento e acompanhe sua solicitação no SOS.`)
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 monitoramento_response(msg_endpoint2)
await new Promise(f => setTimeout(f, 1000));
} }
} }
@ -260,15 +361,15 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
await transferTicket(+msgAction.actions[1], wbot, ticket, contact) 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); const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
await verifyMessage(msg, ticket, contact); await verifyMessage(msg, ticket, contact);
await new Promise(f => setTimeout(f, 1000)); 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])
} }
@ -550,7 +651,7 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, med
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' });