PABX da Simples IP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

588 lines
21 KiB

/** ROLAGEM DO SCROLL ATÉ NO FINAL DO CHAT */
const scrollDown = () => {
$(".chat-window").animate({scrollTop: 99999 * $(this).height() }, 1);
}
/** LIMPA O CONTEUDO DO MODAL */
const modalStart = () => {
$('#footer-content-left').empty()
$('#footer-content-right').empty()
$('.modal-content-body').empty()
$('.modal-header-title').empty()
}
/** INICIA COM O HEADER DO CONTATO VAZIO */
const startChannelMessage = () => {
$('#typemessagebar').hide()
$('#headerbuttonsagent').hide()
$("#headermediaagent").hide()
$('#chatwindowagent').css({ overflow: 'hidden' })
$('#uploadfiles').hide()
}
/** CARREGA OS ELEMENTOS DA SESSAO DA CONVERSA */
const startNotification = () => {
$('#typemessagebar').show();
$('#headerbuttonsagent').show()
$("#headermediaagent").show()
$('#welcometomessage').hide()
$('#chatwindowagent').css({ overflow: 'scroll' })
}
const removeMensagemBody = () => {
$('.chat-window .sender').remove()
$('.chat-window .receiver').remove()
$('.chat-window .events').remove()
}
const hideButtons = (type) => {
if(type){
$('#voicerecorder').css({'pointer-events': 'none'})
$('#imgclip').css({'pointer-events': 'none'})
$('#fieldsendmessage').css({'pointer-events': 'none'})
$('#fieldsendmessage').hide()
$('#tranferagent').hide()
$('#finalizaratendimento').hide()
} else {
$('#voicerecorder').css({'pointer-events': 'auto'})
$('#imgclip').css({'pointer-events': 'auto'})
$('#fieldsendmessage').css({'pointer-events': 'auto'})
$('#fieldsendmessage').show()
$('#tranferagent').show()
$('#finalizaratendimento').show()
}
}
const alertModal = (title, message) => {
modalStart()
$(this).css({'align-items': 'center'})
$('.modal-content-body').append(() =>
title
);
$('.modal-header-title').append(`<span class="fz-14">${message}</span>`)
$('#modalselect').show()
}
/**
* HABILITA O ENVIO DE ARQUIVO DE IMAGENS E APRESENTA UMA MODAL PARA APRESENTAÇÃO DA IMAGEM SELECIONADA
*/
const startSendImage = () => {
modalStart()
$("#uploadimage").on('change', function(){
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}" >`)
$('#footer-content-left').append(`<label id="footername"><b>Arquivo:</b> ${imgName}</label>`)
$('#footer-content-right').append(`<a href="#" class="btn-send" id="footersend"><img src="integracao/simpleschat/images/enter.svg" /></a>`)
}
$('#modalselect').show()
})
}
/**
* HABILITA O ENVIO DE ARQUIVO DE IMAGENS E APRESENTA UMA MODAL PARA APRESENTAÇÃO DA IMAGEM SELECIONADA
*/
const openImgModal = (link) => {
modalStart()
$('#myImg').remove()
$('.modal-content-body').append(`<a href="${link}" target="_blank"><img id="myImg" src="${link}"></a>`)
$('#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(){
const file = new FileReader();
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){
$('.modal-content-body').append(`<img id="myImg" src="integracao/simpleschat/images/icons/${e}-file.png" style="max-width: 100px">`)
return
}
})
if(!$('#myImg')[0]){
$('.modal-content-body').append(`<img id="myImg" src="integracao/simpleschat/images/icons/notfound-file.png" style="max-width: 100px">`)
}
file.onload = function(e) {
$('#footername').remove()
$('#footersend').remove()
$('#footer-content-left').append(`<label id="footername"><b>Arquivo:</b> ${filename}</label>`)
$('#footer-content-right').append(`<a href="#" class="btn-send" id="footersend"><img src="integracao/simpleschat/images/enter.svg" /></a>`)
}
$('#modalselect').show()
})
}
const startPause = () => {
$("#btnsPause").on('click', '#entrePause', function(){
listarPausasAgente(localStorage.getItem('my_uniqueid')).then((pausas) => {
modalStart()
$("#modalselect").show()
$('.modal-content-body').append(() => {
let selectPause = ''
pausas.data.forEach(e => {
if(e.matricula != localStorage.getItem('my_uniqueid')){
selectPause += `<option value="${e.id}">${e.motivo}</option>`
}
})
if(selectPause.length > 0){
selectPause = `<select id="selectpause">${selectPause}</select>`
} else {
selectPause = '<h3>Nenhuma pausa foi encontrado!</h3>'
}
return selectPause
});
$('.modal-header-title').append(`<span class="fz-14">Selecione uma Pausa:</span>`)
$('#footer-content-right').append(`<a href="#" class="btn-send" id="pausesend"><img src="integracao/simpleschat/images/enter.svg" /></a>`)
$('#modalselect').show()
})
})
$("#btnsPause").on('click', '#exitPause', () => {
sairPausa(localStorage.getItem('my_uniqueid')).then(() => {
monitorPausaAgente()
})
})
$('#footer-content-right').on('click', '#pausesend', () => {
entrarPausa($("#selectpause").val(), localStorage.getItem('my_uniqueid')).then(() => {
$('#modalselect').css({display: 'none'})
monitorPausaAgente()
})
})
}
const startTransfer = () => {
$("#tranferagent").on('click', function(){
modalStart()
listarAgentesDisponivel().then((agentes) => {
$('.modal-content-body').append(() => {
let optAgent = null
agentes.data.forEach(e => {
if(e.matricula != localStorage.getItem('my_uniqueid')){
optAgent += `<option value="${e.matricula}">${e.nome} - ${e.fila}</option>`
}
})
if(optAgent){
return `<select id="selectranfer">${optAgent}</select>`
}
$('#transfersend').hide()
return `<h3>Nenhum agente disponível no momento!</h3>`
});
})
$('.modal-header-title').append(`<span class="fz-14">Selecione um agente para transferir:</span>`)
$('#footer-content-right').append(`<a href="#" class="btn-send" id="transfersend"><img src="integracao/simpleschat/images/enter.svg" /></a>`)
$('#modalselect').show()
})
$('#footer-content-right').on('click', '#transfersend', () => {
transferirAtendimento(localStorage.getItem('my_uniqueid'), $("#selectranfer").val(), localStorage.getItem('session_uniqueid')).then((res) => {
if(res.status == 'success'){
hideButtons(true)
notifications({ matricula: localStorage.getItem('my_uniqueid'), uniqueid: localStorage.getItem('session_uniqueid'), action: 'finish' })
$('#modalselect').css({display: 'none'})
}
})
})
}
const exitSystem = () => {
$("#exitSystem").on('click', function(){
if(confirm('Deseja realmente desconectar do sistema?')){
sair(localStorage.getItem('my_uniqueid'))
}
})
}
const startFinalizar = () => {
$("#finalizaratendimento").on('click', function(){
if(confirm('Deseja realmente finalizar o atendimento?')){
finalizarAtendimento(localStorage.getItem('my_uniqueid'), localStorage.getItem('session_uniqueid'))
}
})
}
/**
* FUNÇÃO PARA RECUPERAR O AUDIO DO MICROFONE
*/
function recorderVoice () {
$('#modalselect').show()
modalStart()
$('.modal-content-body').append(`<img src="integracao/simpleschat/images/stop.svg" class="cursor-pointer" id="stoprecorder"/>
<div class="modal-content-body-item">
<div class="modal-content-body-itens">
<span class="fz-18"><b><span id="minutes">00</span>:<span id="seconds">00</span></b></span>
</div>
<div class="modal-content-body-itens">
<span id="msgRecorder">Estamos gravando sua linda voz ...</span>
</div>
</div>`)
$('#footer-content-right').append(`<a href="#" class="btn-send" id="footersend"><img src="integracao/simpleschat/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()
reader.readAsDataURL(blob)
reader.onloadend = () => {
const audio = document.createElement('audio')
audio.src = reader.result
audio.controls = true
$('#footer-content-left').append(audio)
}
}
mediaRecorder.start()
}, err => {
// add msg de error
}
)
}
/**
* ENVIA AS MENSAGEM DO TIPO MIDIA (RECEPTIVO)
* @param {*} id_provedor
* @param {*} type
* @param {*} mimetype
* @param {*} delivery
* @returns
*/
const messageTypeMedia = (obj) => {
const fileDownload = server_api + "/integracao/media/link/" + obj.id_provedor + "/" + window.btoa(obj.mimetype)
if(obj.type == 'voice' || obj.type == 'audio'){
$('.chat-window').append(`
<div class="${obj.from}">
<span class="${obj.from}-message">
<audio controls><source src="${fileDownload}" type="${obj.mimetype}"></audio>
<a href="${fileDownload}"><img src="integracao/simpleschat/images/arrow-down.svg" class="btn-default"></a>
</span>
<br/>
<span class="message-time">${converdata(Date.now())}</span>
</div>`)
return
}
if(obj.type == 'video'){
$('.chat-window').append(`
<div class="${obj.from}">
<span class="${obj.from}-message">
<video autoplay controls>
<source src="${fileDownload}" type="${obj.mimetype}">
</video>
</span>
<br/>
<span class="message-time">${converdata(Date.now())}</span>
</div>`)
return
}
if(obj.type == 'document'){
const typefile = obj.filename.split('.')[1]
let icon
if(icontypes.indexOf(typefile) >= 0){
icon = `<img src="integracao/simpleschat/images/icons/${typefile}-file.png" style="max-width: 60px"></img>`
} else {
icon = `<img src="integracao/simpleschat/images/icons/notfound-file.png" style="max-width: 60px"></img>`
}
$('.chat-window').append(`
<div class="${obj.from}">
<span class="${obj.from}-message message-column">
<a href="${fileDownload}" target="_blank">
${icon}
</a>
</span>
<span class="fz-12">${obj.filename}</span>
<br/>
<span class="message-time">${converdata(Date.now())}</span>
</div>`)
return
}
if(obj.type == 'image' || obj.type == 'sticker'){
$('.chat-window').append(`
<div class="${obj.from}">
<span class="${obj.from}-message message-column">
<img src="${fileDownload}" style="max-width: 200px; max-height: 150px" onclick="openImgModal('${fileDownload}')" >
</span>
<span class="message-time">${converdata(Date.now())}</span>
</div>`)
return
}
}
/**
* data = { number, media, name, datetime }
*
* @param {} data
* @returns
*/
const buildNotification = (data = {}) => {
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)">
<div class="chat-left">
<img src="integracao/simpleschat/images/${data.media}.png"/>
</div>
<div class="chat-right ">
<div class="chat-right-top">
<span class="contact-name">${data.name}</span>
<span class="chat-date">${datesend}</span>
</div>
<div class="chat-right-bottom">
<div class="chat-right-bottom-left">
<span class="chat-message-${data.media}">${data.media}</span>
</div>
<div class="chat-right-bottom-right"></div>
</div>
</div>
</div>`
}
const alertNotification = (uniqueid, type = 'add') => {
$('#' + uniqueid.replace('.', `\\.`) + " .chat-right-bottom-right").empty()
if(type != 'remove'){
listaMensagem(uniqueid).then(mensagens => {
const countMsg = mensagens.data.filter(e => {
if(e.event.mensagem.status != 'read'){
return true
}
})
let notf = countMsg.length
$('#' + uniqueid.replace('.', `\\.`) + " .chat-right-bottom-right").append(`<span class="unread-messages-number">${notf}</span>`)
})
}
}
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");
} else if (Notification.permission === "granted") {
let notification = new Notification(title,{
body: content.body,
icon: content.icon,
silent: true
})
} else if (Notification.permission !== 'denied' || Notification.permission === "default") {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
let notification = new Notification(title, {
body: content.body,
icon: content.icon,
silent: true
})
}
})
}
}
/**
* CRIA AS NOTIFICACOES DE TODOS OS ATENDIMENTOS NA INICIALIZACAO DO SISTEMA OU ATUALIZACAO
*/
const notifications = (obj = {}) => {
/** STATUS DO AGENTE */
monitorPausaAgente()
listarAtendimentoAgente(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)
} else if (obj.action == "finish"){
/** RECEBIMENTO DO SOCKET PARA ALTERAR ESTILO DO HTML */
notification.data.forEach(el => {
if(el.uniqueid == obj.uniqueid){
/** MARCA ATENDIMENTO COMO FINALIZADO */
obj.action == "finish" ? el.status = 0 : null
/** REMOVE OS BOTÕES E CAIXA DE TEXTO DEPOIS DA FINALIZACAO */
if(el.uniqueid == localStorage.getItem('session_uniqueid')){
hideButtons(true)
}
}
})
}
}
notification.data.sort((a, b) => b.status - a.status)
notification.data.forEach(e => {
chatList += buildNotification({
uniqueid: e.uniqueid,
number: e.cliente_id,
media: e.context,
name: e.profile_name,
datetime: e.data_reg,
status: e.status,
protocolo: e.protocolo
})
})
$('#chats').append(chatList)
})
}
const monitorPausaAgente = () => {
statusAgente(localStorage.getItem('my_uniqueid')).then((agente) => {
let statusagent = agente.data[0].status
const status = [
{ status: "LIVRE", class: "status-connect", html: `id="entrePause" src="integracao/simpleschat/images/pause.svg" title="Atribuir uma pausa"`, descricao: statusagent },
{ status: "PAUSA", class: "status-desconnect", html: `id="exitPause" src="integracao/simpleschat/images/play.svg" title="Remover a pausa"`, descricao: `${statusagent} - ${agente.data[0].motivo_pausa}` },
{ status: "OCUPADO", class: "status-reconnect", html: `id="entrePause" src="integracao/simpleschat/images/pause.svg" title="Atribuir uma pausa"`, descricao: statusagent },
{ status: "INDISPONIVEL", class: "status-reconnect", html: `id="exitPause" src="integracao/simpleschat/images/play.svg" title="Remover a pausa"`, descricao: statusagent },
]
if(statusagent){
status.forEach(el => {
if(el.status == statusagent){
$('#status_agent').attr('class', el.class)
$('#status_agent').text(el.descricao)
$('#btnsPause').empty()
$('#btnsPause').html(`<img ${el.html} >`)
}
})
$('#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(() => {
atualizaAgente().then((res) => {
if (res.indexOf('close') >= 0) {
window.close()
}
})
statusAgente(localStorage.getItem('my_uniqueid')).then((agente) => {
if (agente.status == 'error' && agente.message == 'Agente não encontrado') {
window.close()
}
})
}, 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(
`<h4>DESCONECTADO, TENTANTO RECONECTAR &nbsp</h4><img id="imgReconnect" width="25px" src="integracao/simpleschat/images/loading.gif">`,
'Estamos tentando restabelecer a conexão com nosso sistema, por favor aguarde!'
)
$("#status_agent").addClass("status-desconnect").text('DESCONECTADO');
ws.close();
};
ws.onopen = function wsconnect() {
$("#status_agent").addClass("status-reconnect").text('CONECTANDO ...');
entrar(localStorage.getItem('my_uniqueid'), localStorage.getItem('obj_queue')).then((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 {
wsconnect()
}
})
};
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)
}
})
})
}