Browse Source

retirando logs

pull/4/head
guilherme guia 2 years ago
parent
commit
016242bf0d
  1. 65
      public/js/main.js
  2. 16
      public/js/requests.js
  3. 238
      public/js/util.js

65
public/js/main.js

@ -5,7 +5,6 @@ $(function () {
connect(ws);
notifications();
// waveSurferStart();
/**
* VOICE RECORDER
*/
@ -13,37 +12,29 @@ $(function () {
$("#msgRecorder").text("Paramos de gravar sua voz!");
mediaRecorder.stop();
});
// Chama fila de atendimento
// $("#btnFila").on("click", () => {
// notifications();
// });
// $("#btnAtendimento").on("click", () => {
// notifications();
// });
$("#exitChat").on("click", () => {
abrirMensagem = false;
abrirTela();
// removeMensagemBody();
});
$(".box-event-buttons button").on("click", (e) => {
click_btn(e);
});
$("#voicerecorder").on("click", () => {
recorderVoice();
});
/** FIM VOICE RECORDER */
/** EVENTOS DE CLICK NO BODY */
$("body").mouseup(function () {
$("#uploadfiles").fadeOut("slow");
$("#uploadfiles").fadeOut(200);
});
/** INICIO DAS FUNCIONALIDADES */
startSendImage();
startSendFile();
@ -54,58 +45,48 @@ $(function () {
startFooter();
/** INICIA COM O HEADER DO CONTATO VAZIO */
startChannelMessage();
/** INICIA O CHAT NO FINAL DA CONVERSA */
$(".chats").on("click", function () {
scrollDown();
});
$(".checkbox-switch").on("change", ({ target }) => {
changeInterfaceTheme(target);
});
/** ENVIA AS MSG PELO ENTER */
$("#fieldsendmessage").bind("keyup", function (ev) {
if (ev.keyCode == 13 && $(this).val().trim().length > 0) {
sendMessage();
}
});
$("#fieldsendmessage").on("keyup", () => {
if ($(this).val().trim().length == 0) {
$(this).val("");
}
resizeSendMsg();
});
$(".type-message-bar-right").on("click", () => {
sendMessage();
});
/** abre modal de configurações*/
$("#configs").on("click", () => {
openConfigs();
});
$("#imgclip").on("click", function () {
modalStart();
$("#uploadimage").val("");
$("#uploadfile").val("");
if ($("#uploadfiles").is(":hidden")) {
$("#uploadfiles").fadeIn("slow");
$("#uploadfiles").fadeIn(200);
} else {
$("#uploadfiles").fadeOut("slow");
$("#uploadfiles").fadeOut(200);
}
});
$("#footer-content-right").on("click", "#footersend", () => {
sendMedia(mediaRecorder);
// $("#modalselect").css({ display: "none" });
});
supervisorAgente();
});
/**
* EVENTOS DE CLICK PARA SELECIONAR A SESSAO DE MENSAGEM/CONVERSA E RECUPERAR AS MENSAGENS JA TROCADAS NO ATENDIMENTO
* @param {*} id
@ -118,7 +99,6 @@ const selectNotification = (id) => {
let name;
let dataContact;
let protocolo;
const dataRequest = JSON.parse(localStorage.getItem("obj_contact"));
listarAtendimentoAgente(
localStorage.getItem("id_empresa"),
@ -127,7 +107,6 @@ const selectNotification = (id) => {
const allNotifications = JSON.parse(
localStorage.getItem("obj_notification")
);
hideButtons(false);
allNotifications.data.forEach((e) => {
$("#" + e.uniqueid.replace(".", `\\.`)).removeClass(
@ -138,7 +117,6 @@ const selectNotification = (id) => {
}
});
$("#" + id.replace(".", `\\.`)).addClass("select-notification");
allNotifications.data.forEach((e) => {
if (e.uniqueid == id && e.status == 0) {
hideButtons(true);
@ -151,7 +129,6 @@ const selectNotification = (id) => {
}
});
}
allNotifications.data.forEach((e) => {
if (id === e.uniqueid) {
uniqueid = e.uniqueid;
@ -160,28 +137,23 @@ const selectNotification = (id) => {
protocolo = e.protocolo;
}
});
localStorage.removeItem("session_window");
localStorage.removeItem("session_uniqueid");
localStorage.setItem("session_uniqueid", uniqueid);
localStorage.setItem("session_window", number);
$(".chat-window-contact-name").text(name);
$(".chat-window-contact-status").text("Protocolo: " + protocolo);
/** REMOVE AS MSG NA E CONSTRIO A TELA NOVAMENTE (EVITAR DUPLICAR) */
$(".chat-window .sender").remove();
$(".chat-window .receiver").remove();
$(".chat-window .events").remove();
alertNotification(localStorage.getItem("session_uniqueid"), "remove");
dataContact.forEach((e) => {
const datesend = e.msg_date
? converdata(new Date(e.msg_date).getTime())
: "algumas horas";
let typesend =
localStorage.getItem("my_uniqueid") == e.dst ? "receiver" : "sender";
if (e.type == "text") {
$(".chat-window").append(`
<div class="${typesend}">
@ -193,14 +165,12 @@ const selectNotification = (id) => {
<span class="message-time">${datesend}</span>
</div>`);
}
if (e.type == "finish" || e.type == "re_start") {
$(".chat-window").append(`
<div class="events">
<span class="events-message">${e.content}</span>
</div>`);
}
if (e.type != "text") {
const sendobj = {
filename: e.file_name,
@ -211,7 +181,6 @@ const selectNotification = (id) => {
};
messageTypeMedia(sendobj);
}
if (e.de == localStorage.getItem("my_uniqueid")) {
const datereceived = e.datetime
? converdata(e.datetime)
@ -233,7 +202,6 @@ const selectNotification = (id) => {
// <br/>
// <span class="message-time">${datereceived}</span>
// </div>`);
const audio = `<audio controls>
<source src="data:audio/mpeg;base64,${e.msg}"></source>
</audio>`;
@ -274,10 +242,9 @@ const selectNotification = (id) => {
});
scrollDown();
});
// abrirMensagem = true;
abrirMensagem = true;
startNotification();
};
/**
* REALIZA O ENVIO DE MENSAGEM ATRAVEZ DA API
* @param {*} obj
@ -287,7 +254,6 @@ const sendMessage = (obj = {}) => {
const sendNumber = localStorage.getItem("session_window");
const myUniqueid = localStorage.getItem("my_uniqueid");
const agent = JSON.parse(localStorage.getItem("obj_status"));
let sendContent =
typeof obj.fileContent === "undefined"
? $("#fieldsendmessage").val()
@ -298,11 +264,9 @@ const sendMessage = (obj = {}) => {
let type = obj.type ? obj.type : "text";
let mimetype = obj.mimetype ? obj.mimetype : "text";
let filename = obj.filename ? obj.filename : Date.now();
if (!sendContent) {
return;
}
let dataSend = {
event: {
type: "mensagem",
@ -323,13 +287,10 @@ const sendMessage = (obj = {}) => {
},
},
};
if (type != "audio") {
dataSend.event.mensagem.file_name = filename;
}
enviarMensagem(dataSend);
let msgContent = type == "text" ? sendContent : obj.fileContent;
$(".chat-window").append(`
<div class="sender">
@ -341,14 +302,12 @@ const sendMessage = (obj = {}) => {
<span class="message-time">${converdata(Date.now())}</span>
</div>`);
scrollDown();
/** LIMPA O CAMPO DE ENVIO DE MENSAGEM */
$("#fieldsendmessage").val("");
};
/**
* ATUALIZA AS MENSAGEM QUE SAO RECEBIDAS NA TELA DO ATENDIMENTO
* Os dados s<EFBFBD>o transmitidos pelo evento de WS
* Os dados s<EFBFBD>o transmitidos pelo evento de WS
* @param {*} ev
*/
const viewMessage = (ev) => {
@ -356,7 +315,6 @@ const viewMessage = (ev) => {
const datesend = ev.event?.mensagem.datetime
? converdata(ev.event?.mensagem.datetime, true)
: "algumas horas";
if (ev.event?.mensagem.uniqueid == sessionOpen) {
marcarMensagemVista(sessionOpen);
switch (ev.event?.mensagem.type) {
@ -376,7 +334,6 @@ const viewMessage = (ev) => {
</div>`);
break;
}
const mediaDownload = [
"image",
"voice",
@ -398,7 +355,6 @@ const viewMessage = (ev) => {
scrollDown();
}
};
/**
* APRESENTA AS NOVAS NOTIFICACOES DE ATENDIMENTO NA TELA DO ATENDENTE
* -> CADA ATENDIMENTO DEVE POSSUIR APENAS UMA NOTIFICACAO
@ -406,7 +362,6 @@ const viewMessage = (ev) => {
*/
const receiveNotification = (data) => {
let validate = null;
switch (data.event?.type) {
case "mensagem":
if (
@ -419,24 +374,20 @@ const receiveNotification = (data) => {
});
soundNotification(`${path}/sound/notification.mp3`);
}
/** VALIDA O NUMERO, VERIFICA SE O TEM ALGMA MSG INICIAL, SE JA TEVE UM NUMERO NA VERIFICACAO */
listarAtendimentoAgente(
localStorage.getItem("id_empresa"),
localStorage.getItem("my_uniqueid")
);
validate = JSON.parse(localStorage.getItem("obj_notification"));
const vald = validate.data.filter((e) => {
return data.event?.mensagem.uniqueid == e.uniqueid;
});
if (
data.event?.contact.number != localStorage.getItem("session_window")
) {
alertNotification(data.event.mensagem.uniqueid);
}
if (
data.event?.mensagem.uniqueid &&
data.event?.contact.number &&
@ -473,7 +424,6 @@ const receiveNotification = (data) => {
break;
}
};
/**
* MANTEM TODAS AS MENSAGENS ARMAZENADAS NO LOCALSTORAGE, SEMPRE QUE ENVIA E RECEBE SERA GUARDADO
* @param {*} ev
@ -483,14 +433,12 @@ const keepMensage = (ev) => {
if (!msg) {
msg = { data: [] };
}
if (ev.event?.contact && ev.event?.mensagem.content) {
msg.data.push(ev);
localStorage.removeItem("keep_msg");
localStorage.setItem("keep_msg", JSON.stringify(msg));
}
};
/**
* FUNCAO PARA CAPTURAR O ARQUIVO A SER ENVIADO
*/
@ -527,7 +475,6 @@ const sendMedia = (media = null) => {
fileContent = filesent.css({ "max-width": "350px" })[0].outerHTML;
$("#myImg").empty();
}
const file = new FileReader();
file.onload = function () {
const typefile =
@ -543,4 +490,4 @@ const sendMedia = (media = null) => {
});
};
file.readAsDataURL(rec);
};
};

16
public/js/requests.js

@ -11,7 +11,6 @@ const enviarMensagem = (dataSend) => {
}
});
}
const listaMensagem = (uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/messages/${uniqueid}`,
@ -26,8 +25,6 @@ const listaMensagem = (uniqueid) => new Promise((resolve) => {
}
})
})
const listarAgentesDisponivel = (id_empresa) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/supervisor/agentes/status/${id_empresa}/livre`,
@ -40,7 +37,6 @@ const listarAgentesDisponivel = (id_empresa) => new Promise((resolve) => {
}
});
})
const listarAtendimentoAgente = (id_empresa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/atendimentos/${id_empresa}/${matricula}`,
@ -51,11 +47,9 @@ const listarAtendimentoAgente = (id_empresa, matricula) => new Promise((resolve)
resolve(res)
},
error: function (res) {
}
});
})
const listarPausasAgente = (id_empresa) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/pausas/${id_empresa}`,
@ -68,7 +62,6 @@ const listarPausasAgente = (id_empresa) => new Promise((resolve) => {
}
});
})
const entrarPausa = (id_pausa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/supervisor/entrarPausa`,
@ -90,7 +83,6 @@ const entrarPausa = (id_pausa, matricula) => new Promise((resolve) => {
}
});
})
const sairPausa = (matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/supervisor/sairPausa`,
@ -107,7 +99,6 @@ const sairPausa = (matricula) => new Promise((resolve) => {
}
});
})
const entrar = (matricula, id_fila, id_number) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/auth/conectar-chat`,
@ -125,7 +116,6 @@ const entrar = (matricula, id_fila, id_number) => new Promise((resolve) => {
}
});
})
const sair = (matricula) => {
$.ajax({
url: `${server_api}/auth/desconectar-chat`,
@ -146,7 +136,6 @@ const sair = (matricula) => {
}
});
}
const finalizarAtendimento = (matricula, uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/atendimentos/finalizar`,
@ -176,7 +165,6 @@ const finalizarAtendimento = (matricula, uniqueid) => new Promise((resolve) => {
}
});
})
const statusAgente = (id_empresa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/supervisor/agentes/${id_empresa}/${matricula}`,
@ -194,7 +182,6 @@ const statusAgente = (id_empresa, matricula) => new Promise((resolve) => {
}
});
})
const transferirAtendimento = (origem, destino, uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/atendimentos/transferir`,
@ -222,7 +209,6 @@ const transferirAtendimento = (origem, destino, uniqueid) => new Promise((resolv
}
});
})
const marcarMensagemVista = (uniqueid) => {
$.ajax({
url: `${server_api}/messages/markMessageRead`,
@ -238,7 +224,6 @@ const marcarMensagemVista = (uniqueid) => {
}
});
}
const buscarAtendimento = async (uniqueid) => {
return $.ajax({
url: `${server_api}/atendimentos/buscar`,
@ -254,7 +239,6 @@ const buscarAtendimento = async (uniqueid) => {
}
});
}
const buscarUsuario = (matricula) => new Promise((resolve) =>{
$.ajax({
url: `${server_api}/usuario/buscar`,

238
public/js/util.js

@ -1,8 +1,7 @@
/** ROLAGEM DO SCROLL AT<EFBFBD> NO FINAL DO CHAT */
/** ROLAGEM DO SCROLL AT<EFBFBD> NO FINAL DO CHAT */
const scrollDown = () => {
$(".chat-window").animate({ scrollTop: 99999 * $(this).height() }, 1);
};
const startFooter = () => {
let contador = 1;
let atendimentos = 8;
@ -10,32 +9,25 @@ const startFooter = () => {
`<span class="total-calls">Total Atendimentos - ${atendimentos}</span><span class="time-login">Tempo em Acesso - ${contador}s</span>`
);
};
const click_btn = (btn) => {
const target = btn.target;
const parent = target.parentElement || target.parentNode;
$(parent)
.children()
.each(function () {
$(this)[0].classList.remove("button-selected");
});
target.classList.add("button-selected");
};
/** LIMPA O CONTEUDO DO MODAL */
const modalStart = () => {
$("#footer-content-left").empty();
$("#footer-content-right").empty();
$(".modal-content-body").empty();
$(".modal-content-body").removeClass("d-flex");
$(".modal-content-body").removeClass("align-items-center");
$(".modal-content-body").removeClass("d-flex")
$(".modal-content-body").removeClass("align-items-center")
$(".modal-header-title").empty();
};
/** INICIA COM O HEADER DO CONTATO VAZIO */
const startChannelMessage = () => {
$("#typemessagebar").hide();
@ -44,27 +36,23 @@ const startChannelMessage = () => {
$("#chatwindowagent").css({ overflow: "hidden" });
$("#uploadfiles").hide();
};
/** CARREGA OS ELEMENTOS DA SESSAO DA CONVERSA */
const startNotification = () => {
$("#typemessagebar").show();
$("#headerbuttonsagent").show();
$("#headermediaagent").show();
$("#welcometomessage").hide();
abrirTela();
$("#chatwindowagent").css({ overflow: "scroll" });
};
const removeMensagemBody = () => {
$(".chat-window .sender").remove();
$(".chat-window .receiver").remove();
$(".chat-window .events").remove();
$(".chat-window").remove();
$(".chat-window-header").remove();
};
const hideButtons = (type) => {
if (type) {
$("#voicerecorder").css({ "pointer-events": "none" });
@ -82,7 +70,6 @@ const hideButtons = (type) => {
$("#finalizaratendimento").show();
}
};
const alertModal = (title, message) => {
modalStart();
$(this).css({ "align-items": "center" });
@ -90,7 +77,6 @@ const alertModal = (title, message) => {
$(".modal-header-title").append(`${message}`);
$("#modalselect").show();
};
/**
* HABILITA O ENVIO DE ARQUIVO DE IMAGENS E APRESENTA UMA MODAL PARA APRESENTACAO DA IMAGEM SELECIONADA
*/
@ -100,12 +86,10 @@ const startSendImage = () => {
const file = new FileReader();
file.readAsDataURL(this.files[0]);
const imgName = this.files[0].name;
file.onload = function (e) {
$("#myImg").remove();
$("#footername").remove();
$("#footersend").remove();
$(".modal-content-body").append(
`<img id="myImg" src="${e.target.result}" >`
);
@ -119,11 +103,9 @@ const startSendImage = () => {
$("#modalselect").show();
});
};
/**
* GERENCIA A RESPONSIVIDADE DO LAYOUT
*/
const abrirTela = () => {
let sidebar = document.querySelector(".sidebar");
let main = document.querySelector(".main");
@ -131,56 +113,44 @@ const abrirTela = () => {
main.classList.toggle("chatAtivo", abrirMensagem);
sidebar.classList.toggle("chatAtivo", abrirMensagem);
};
const fecharTela = () => {
abrirMensagem = false;
};
/**
* GERENCIA A TROCA DO MODO DA INTERFACE
*/
const changeInterfaceTheme = (element) => {
let switch_ball = document.querySelector(".switch-ball");
let change = element.checked
? '<span><i class="fas fa-moon"></i></span>'
: '<span><i class="fas fa-sun"></i></span>';
switch_ball.innerHTML = change;
element.checked
? changeColors(darkMode, html)
: changeColors(initialColors, html);
};
const changeColors = (colors, raiz) => {
console.log(colors);
Object.keys(colors).map((key) => {
raiz.style.setProperty(transformKey(key), colors[key]);
});
};
const transformKey = (key) =>
"--" + key.replace(/([A-Z])/g, "-$1").toLowerCase();
const getStyle = (element, style) =>
window.getComputedStyle(element).getPropertyValue(style);
const darkMode = {
textPrimary: "#EEEEEE",
bg: "#41444d",
bgLightDark: "#2b303b",
chatHoverColor: "#5b5e66",
chatActiveColor: "#1e2129",
chatActiveColor: '#1e2129',
senderMessage: "#268d61",
receiveMessage: "#35373b",
colorMoon: "#fff",
eventsMessage: "#222",
eventsMessage: "#222"
};
const initialColors = {
const initialColors = {
bg: getStyle(html, "--bg"),
textPrimary: getStyle(html, "--text-primary"),
bgLightDark: getStyle(html, "--bg-light-dark"),
@ -191,14 +161,11 @@ const initialColors = {
colorMoon: getStyle(html, "--color-moon"),
eventsMessage: getStyle(html, "--events-message"),
};
/**
* HABILITA O MODAL PARA AJUSTAR CONFIGURAÇÕES
*/
const openConfigs = () => {
modalStart();
$(".modal-content").css({ width: "70%" });
$(".modal-content-body").append(`<div class="config-list">
<div class="config config-selected">
@ -226,11 +193,9 @@ const openConfigs = () => {
</label>
</div>
</div>`);
$(".modal-header-title2");
$("#modalselect").show();
};
/**
* HABILITA O ENVIO DE ARQUIVO DE IMAGENS E APRESENTA UMA MODAL PARA APRESENTACAO DA IMAGEM SELECIONADA
*/
@ -242,18 +207,15 @@ const openImgModal = (link) => {
);
$("#modalselect").show();
};
const resizeSendMsg = () => {
let tamField = $("#fieldsendmessage")[0].clientWidth;
let qtdField = $("#fieldsendmessage").val().length;
if (qtdField * 8 >= tamField) {
$("#fieldsendmessage").attr("rows", 4);
} else {
$("#fieldsendmessage").attr("rows", 1);
}
};
const startSendFile = () => {
modalStart();
$("#uploadfile").on("change", function () {
@ -261,7 +223,6 @@ const startSendFile = () => {
file.readAsDataURL(this.files[0]);
const filename = this.files[0].name;
const typefile = this.files[0].name.split(".")[1];
$("#myImg").remove();
icontypes.forEach((e) => {
if (typefile.indexOf(e) >= 0) {
@ -271,13 +232,11 @@ const startSendFile = () => {
return;
}
});
if (!$("#myImg")[0]) {
$(".modal-content-body").append(
`<img id="myImg" src="${path}/images/icons/notfound-file.png" style="max-width: 100px">`
);
}
file.onload = function (e) {
$("#footername").remove();
$("#footersend").remove();
@ -291,7 +250,6 @@ const startSendFile = () => {
$("#modalselect").show();
});
};
const startPause = () => {
$("#btnsPause").on("click", "#entrePause", function () {
listarPausasAgente(localStorage.getItem("id_empresa")).then((pausas) => {
@ -315,7 +273,6 @@ const startPause = () => {
}
return selectPause;
});
$(".modal-header-title").append(
`<span class="fz-14">Selecione uma Pausa:</span>`
);
@ -325,13 +282,11 @@ const startPause = () => {
$("#modalselect").show();
});
});
$("#btnsPause").on("click", "#exitPause", () => {
sairPausa(localStorage.getItem("my_uniqueid")).then(() => {
monitorPausaAgente();
});
});
$("#footer-content-right").on("click", "#pausesend", () => {
entrarPausa(
$("#selectpause").val(),
@ -342,7 +297,6 @@ const startPause = () => {
});
});
};
const startTransfer = () => {
$("#tranferagent").on("click", function () {
modalStart();
@ -355,7 +309,6 @@ const startTransfer = () => {
optAgent += `<option value="${e.matricula}">${e.nome} - ${e.fila}</option>`;
}
});
if (optAgent) {
return `<select id="selectranfer">${optAgent}</select>`;
}
@ -364,7 +317,6 @@ const startTransfer = () => {
});
}
);
$(".modal-header-title").append(
`<span class="fz-14">Selecione um agente para transferir:</span>`
);
@ -373,7 +325,6 @@ const startTransfer = () => {
);
$("#modalselect").show();
});
$("#footer-content-right").on("click", "#transfersend", () => {
transferirAtendimento(
localStorage.getItem("my_uniqueid"),
@ -392,7 +343,6 @@ const startTransfer = () => {
});
});
};
const exitSystem = () => {
$("#exitSystem").on("click", function () {
if (confirm("Deseja realmente desconectar do sistema?")) {
@ -400,7 +350,6 @@ const exitSystem = () => {
}
});
};
const startFinalizar = () => {
$("#finalizaratendimento").on("click", function () {
if (confirm("Deseja realmente finalizar o atendimento?")) {
@ -411,7 +360,6 @@ const startFinalizar = () => {
}
});
};
/**
* FUNCAO PARA RECUPERAR O AUDIO DO MICROFONE
*/
@ -419,9 +367,8 @@ function recorderVoice() {
$("#modalselect").show();
modalStart();
$(".modal-content").css({ width: "30%" });
$(".modal-content-body").addClass("d-flex");
$(".modal-content-body").addClass("align-items-center");
$(".modal-content-body").addClass("d-flex")
$(".modal-content-body").addClass("align-items-center")
$(".modal-content-body")
.append(`<img src="${path}/images/stop.svg" class="cursor-pointer" id="stoprecorder"/>
<div class="modal-content-body-item ">
@ -432,24 +379,19 @@ function recorderVoice() {
<span id="msgRecorder">Estamos gravando sua linda voz ...</span>
</div>
</div>`);
$("#footer-content-right").append(
`<a href="#" class="btn-send" id="footersend"><img src="${path}/images/enter.svg" /></a>`
);
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(
(stream) => {
let option = {
type: "audio/mpeg",
};
mediaRecorder = new MediaRecorder(stream);
let chunks = [];
mediaRecorder.ondataavailable = (data) => {
chunks.push(data.data);
};
mediaRecorder.onstop = () => {
const blob = new Blob(chunks, option);
const reader = new FileReader();
@ -468,7 +410,6 @@ function recorderVoice() {
}
);
}
/**
* ENVIA AS MENSAGEM DO TIPO MIDIA (RECEPTIVO)
* @param {*} id_provedor
@ -482,13 +423,11 @@ const messageTypeMedia = (obj) => {
server_api + "/link/" + obj.id_provedor + "/" + window.btoa(obj.mimetype);
if (obj.type == "voice" || obj.type == "audio") {
// console.log(obj)
// let wavesurfer = WaveSurfer.create({
// container: '#waveform',
// waveColor: 'violet',
// progressColor: 'purple'
// });
// $('.chat-window').append(`
// <div class="${obj.from}">
// <span class="${obj.from}-message">
@ -509,9 +448,7 @@ const messageTypeMedia = (obj) => {
<br/>
<span class="message-time">${converdata(Date.now())}</span>
</div>`);
// const audio = `<div id="waveform"></div>`
// // $('.chat-window').append(`
// // <div class="${typesend}">
// // <span class="${typesend}-message">${audio}</span>
@ -519,10 +456,8 @@ const messageTypeMedia = (obj) => {
// // <span class="message-time">${datereceived}</span>
// // </div>`)
// wavesurfer.load(e.msg);
return;
}
if (obj.type == "video") {
$(".chat-window").append(`
<div class="${obj.from}">
@ -536,7 +471,6 @@ const messageTypeMedia = (obj) => {
</div>`);
return;
}
if (obj.type == "document") {
const typefile = obj.filename.split(".")[1];
let icon;
@ -545,7 +479,6 @@ const messageTypeMedia = (obj) => {
} else {
icon = `<img src="${path}/images/icons/notfound-file.png" style="max-width: 60px"></img>`;
}
$(".chat-window").append(`
<div class="${obj.from}">
<span class="${obj.from}-message message-column">
@ -559,7 +492,6 @@ const messageTypeMedia = (obj) => {
</div>`);
return;
}
if (obj.type == "image" || obj.type == "sticker") {
$(".chat-window").append(`
<div class="${obj.from}">
@ -571,7 +503,6 @@ const messageTypeMedia = (obj) => {
return;
}
};
/**
* data = { number, media, name, datetime }
*
@ -579,17 +510,12 @@ const messageTypeMedia = (obj) => {
* @returns
*/
const buildNotification = (data = {}) => {
if (
data.length == "undefined" ||
(data.media == undefined && data.media == undefined)
) {
if (data.length == "undefined") {
return;
}
const datesend = converdata(data.datetime);
const status = data.status == 0 ? "opacity-3" : "";
return `<div class="chat ${status}" id="${data.uniqueid}" onclick="selectNotification(this.id)">
const status = data.status == 0 ? "opacity-8" : "";
return `<div class="chat ${status}" id="${data.uniqueid}" onclick="selectNotification(this.id)">
<div class="chat-left">
<img src="${path}/images/${data.media}.png"/>
</div>
@ -641,10 +567,9 @@ const buildNotification = (data = {}) => {
// </div>
// </div>
// </div>
// `;
};
const alertNotification = (uniqueid, type = "add") => {
$("#" + uniqueid.replace(".", `\\.`) + " .chat-right-bottom-right").empty();
if (type != "remove") {
@ -654,7 +579,6 @@ const alertNotification = (uniqueid, type = "add") => {
return true;
}
});
let notf = countMsg.length;
$(
"#" + uniqueid.replace(".", `\\.`) + " .chat-right-bottom-right"
@ -662,12 +586,10 @@ const alertNotification = (uniqueid, type = "add") => {
});
}
};
function soundNotification(url) {
const audio = new Audio(url);
audio.play();
}
const notifyMe = (title, content) => {
if (!("Notification" in window)) {
console.log("This browser does not support desktop notification");
@ -692,25 +614,21 @@ const notifyMe = (title, content) => {
});
}
};
/**
* CRIA AS NOTIFICACOES DE TODOS OS ATENDIMENTOS NA INICIALIZACAO DO SISTEMA OU ATUALIZACAO
*/
const notifications = (obj = {}) => {
/** STATUS DO AGENTE */
monitorPausaAgente();
listarAtendimentoAgente(
localStorage.getItem("id_empresa"),
localStorage.getItem("my_uniqueid")
).then((notification) => {
let chatList = "";
$("#chats").empty();
if (!notification.data) {
return;
}
if (Object.values(obj).length > 0) {
if (obj.action == "mensagem") {
notification.data.push(obj);
@ -728,16 +646,8 @@ const notifications = (obj = {}) => {
});
}
}
let chat = notification.data.filter(function (a) {
return (
!this[JSON.stringify(a.uniqueid)] &&
(this[JSON.stringify(a.uniqueid)] = true)
);
}, Object.create(null));
chat.sort((a, b) => b.status - a.status);
chat.forEach((e) => {
notification.data.sort((a, b) => b.status - a.status);
notification.data.forEach((e) => {
chatList += buildNotification({
uniqueid: e.uniqueid,
number: e.cliente_id,
@ -752,14 +662,12 @@ const notifications = (obj = {}) => {
$("#chats").append(chatList);
});
};
const monitorPausaAgente = () => {
statusAgente(
localStorage.getItem("id_empresa"),
localStorage.getItem("my_uniqueid")
).then((agente) => {
let statusagent = agente.data[0]?.status;
let statusagent = agente.data[0].status;
const status = [
{
status: "LIVRE",
@ -771,7 +679,7 @@ const monitorPausaAgente = () => {
status: "PAUSA",
class: "status-desconnect",
html: `id="exitPause" src="${path}/images/play.svg" title="Remover a pausa"`,
descricao: `${statusagent} - ${agente.data[0]?.motivo_pausa}`,
descricao: `${statusagent} - ${agente.data[0].motivo_pausa}`,
},
{
status: "OCUPADO",
@ -786,7 +694,6 @@ const monitorPausaAgente = () => {
descricao: statusagent,
},
];
if (statusagent) {
status.forEach((el) => {
if (el.status == statusagent) {
@ -796,7 +703,6 @@ const monitorPausaAgente = () => {
$("#btnsPause").html(`<img ${el.html} >`);
}
});
$("#myuniqueid").text(localStorage.getItem("my_uniqueid"));
/** CONFIGURACAO NOME */
$("#nameagent").text(agente.data[0].nome);
@ -804,14 +710,7 @@ const monitorPausaAgente = () => {
$("#queueagente").text(agente.data[0].fila);
}
});
$("#myuniqueid").text(localStorage.getItem("my_uniqueid"));
/** CONFIGURACAO NOME */
$("#nameagent").text(agente.data[0].nome);
/** CONFIGURACAO FILA */
$("#queueagente").text(agente.data[0].fila);
};
const supervisorAgente = () => {
/** MONITORA AS CONFIGURACOES */
setInterval(() => {
@ -825,18 +724,15 @@ const supervisorAgente = () => {
});
}, 30000);
};
/** CONNECT TO WS */
const connect = (wsserver) => {
const ws = new WebSocket(wsserver);
ws.onmessage = function (e) {};
ws.onclose = function (e) {
setTimeout(function () {
connect(wsserver);
}, 3000);
};
ws.onerror = function (err) {
alertModal(
`<h2>CONECTANDO NO SISTEMA! POR FAVOR AGUARDE.</h2>`,
@ -845,7 +741,6 @@ const connect = (wsserver) => {
$("#status_agent").addClass("status-desconnect").text("DESCONECTADO");
ws.close();
};
ws.onopen = function wsconnect() {
$("#status_agent").addClass("status-reconnect").text("RECONECTANDO ...");
entrar(
@ -864,71 +759,44 @@ const connect = (wsserver) => {
notifications();
} else if (login.status == "error") {
alertModal(
`<h3>CONECTANDO NO SISTEMA! POR FAVOR AGUARDE.</h3>`,
`<img id="imgReconnect" width="20px" src="${path}/images/loading.gif">`
`<h2>OPSS!! ${login.message} &nbsp</h2>`,
`<img width="20px" src="${path}/images/alerta.png">`
);
$("#status_agent").addClass("status-desconnect").text("DESCONECTADO");
ws.close();
$("#status_agent").addClass("status-desconnect").text("OFF");
} else {
wsconnect();
}
ws.onopen = function wsconnect() {
$("#status_agent")
.addClass("status-reconnect")
.text("RECONECTANDO ...");
entrar(
localStorage.getItem("my_uniqueid"),
localStorage.getItem("obj_queue")
).then((login) => {
console.log(login);
if (
login.status == "success" ||
login.message.indexOf("autenticado") >= 0
) {
$("#modalselect").css({ display: "none" });
monitorPausaAgente();
ws.send(
JSON.stringify({ matricula: localStorage.getItem("my_uniqueid") })
);
notifications();
} else if (login.status == "error") {
alertModal(
`<h3>OPSS!! ${login.message} &nbsp</h3>`,
`<img width="20px" src="${path}/images/alerta.png">`
);
$("#status_agent").addClass("status-desconnect").text("OFF");
} else {
wsconnect();
}
});
};
ws.addEventListener("open", () => {
ws.addEventListener("message", (e) => {
/** att: atualizacao do websocket */
if (e.data != "att") {
const data = JSON.parse(e?.data);
if (localStorage.getItem("session_uniqueid") == null) {
localStorage.setItem(
"session_uniqueid",
data.event.mensagem.uniqueid
);
}
if ($("#welcometomessage").is(":hidden") == false) {
localStorage.setItem("session_window", null);
}
/** ATUALIZACAO DA SESSAO CORRENTE (VALIDA PARA NAO ENVIAR PARA TELA INICIAL)*/
if (localStorage.getItem("session_window") !== "null") {
viewMessage(data);
}
/** RECEBE AS PRIMEIRAS MENSAGENS */
receiveNotification(data);
}
});
});
});
};
ws.addEventListener("open", () => {
const storage = [
"my_uniqueid",
"keep_msg",
"obj_contact",
"session_uniqueid",
"session_window",
];
ws.addEventListener("message", (e) => {
/** att: atualizacao do websocket */
if (e.data != "att") {
const data = JSON.parse(e?.data);
if (localStorage.getItem("session_uniqueid") == null) {
localStorage.setItem(
"session_uniqueid",
data.event.mensagem.uniqueid
);
}
if ($("#welcometomessage").is(":hidden") == false) {
localStorage.setItem("session_window", null);
}
/** ATUALIZACAO DA SESSAO CORRENTE (VALIDA PARA NAO ENVIAR PARA TELA INICIAL)*/
if (localStorage.getItem("session_window") !== "null") {
viewMessage(data);
}
/** RECEBE AS PRIMEIRAS MENSAGENS */
receiveNotification(data);
}
});
});
};

Loading…
Cancel
Save