/** 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(`${message}`) $('#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(``) $('#footer-content-left').append(``) $('#footer-content-right').append(``) } $('#modalselect').show() }) } 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(``) return } }) if(!$('#myImg')[0]){ $('.modal-content-body').append(``) } file.onload = function(e) { $('#footername').remove() $('#footersend').remove() $('#footer-content-left').append(``) $('#footer-content-right').append(``) } $('#modalselect').show() }) } const startPause = () => { $("#entrePause").on('click', 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 += `` } }) if(selectPause.length > 0){ selectPause = `` } else { selectPause = '

Nenhuma pausa foi encontrado!

' } return selectPause }); $('.modal-header-title').append(`Selecione uma Pausa:`) $('#footer-content-right').append(``) $('#modalselect').show() }) }) $("#exitPause").on('click', () => { 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 += `` } }) if(optAgent){ return `` } $('#transfersend').hide() return `

Nenhum agente disponível no momento!

` }); }) $('.modal-header-title').append(`Selecione um agente para transferir:`) $('#footer-content-right').append(``) $('#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(` `) $('#footer-content-right').append(``) 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(`

${converdata(Date.now())}
`) return } if(obj.type == 'video'){ $('.chat-window').append(`

${converdata(Date.now())}
`) return } if(obj.type == 'document'){ const typefile = obj.filename.split('.')[1] let icon if(icontypes.indexOf(typefile) >= 0){ icon = `` } else { icon = `` } $('.chat-window').append(`
${icon} ${obj.filename}
${converdata(Date.now())}
`) return } if(obj.type == 'image' || obj.type == 'sticker'){ $('.chat-window').append(`

${converdata(Date.now())}
`) 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 `
${data.name} ${datesend}
${data.media}
` } const alertNotification = (uniqueid, type = 'add') => { $('#' + uniqueid.replace('.', `\\.`) + " .chat-right-bottom-right").empty() if(type != 'remove'){ listaMensagem(uniqueid) const mensagens = JSON.parse(localStorage.getItem('obj_contact')) const countMsg = mensagens.data.filter(e => { if(e.event.mensagem.status != 'read'){ return true } }) let notf = countMsg.length + 1 $('#' + uniqueid.replace('.', `\\.`) + " .chat-right-bottom-right").append(`${notf}`) } } 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(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 if(agente.data.status){ statusagent = agente.data.status if(agente.data.status == 'LIVRE'){ $('#exitPause').hide() $('#entrePause').show() $('#status_agent').attr('class','status-connect') } else if(agente.data.status == 'PAUSA') { $('#entrePause').hide() $('#exitPause').show() $('#status_agent').attr('class','status-desconnect') statusagent = agente.data.status + " - " + agente.data.motivo_pausa } else if (agente.data.status == 'OCUPADO'){ $('#exitPause').hide() $('#status_agent').attr('class','status-reconnect') } else { $('#entrePause').hide() $('#exitPause').show() $('#status_agent').attr('class','status-reconnect') statusagent = agente.data.status } $('#status_agent').text(statusagent) $('#myuniqueid').text(localStorage.getItem('my_uniqueid')) /** CONFIGURACAO NOME */ $('#nameagent').text(agente.data.nome) /** CONFIGURACAO FILA */ $('#queueagente').text(agente.data.fila) } }) } const supervisorAgente = () => { /** MONITORA AS CONFIGURACOES */ setTimeout(() => { 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() } }) supervisorAgente() }, 40000); } /** 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( `

DESCONECTADO, TENTANTO RECONECTAR  

`, '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.status.indexOf('autenticado') === -1){ $('#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) console.log(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) } }) }) }