Browse Source

Merge pull request 'guilherme' (#8) from guilherme into master

Reviewed-on: awade/simples_client#8
v0.0.1
Lucas Awade 2 years ago
parent
commit
72e1cd3fd3
  1. 4
      Dockerfile
  2. 41
      app/view/content.php
  3. 2
      app/view/header.php
  4. 73
      index copy.php
  5. 76
      index.php
  6. 714
      public/css/styles.css
  7. 68
      public/css/teste
  8. BIN
      public/images/favicon.ico
  9. BIN
      public/images/lua.png
  10. BIN
      public/images/send-message.png
  11. BIN
      public/images/seta-para-baixo.png
  12. BIN
      public/images/settings.png
  13. BIN
      public/images/sol.png
  14. 17
      public/index.html
  15. 8
      public/js/config.js
  16. 4
      public/js/cronometro.js
  17. 852
      public/js/main.js
  18. 146
      public/js/requests.js
  19. 1269
      public/js/util.js
  20. 6095
      public/js/waveSurfer.js
  21. 67
      ws.php

4
Dockerfile

@ -14,7 +14,7 @@ RUN php composer-setup.php --filename=composer --install-dir=/bin
WORKDIR /var/www/html
RUN git clone http://desenvolvimento:SimpleS_G1t34@192.168.115.83:3000/awade/simples_client.git
RUN git clone -b develop http://desenvolvimento:SimpleS_G1t34@192.168.115.233:3000/awade/simples_client.git
WORKDIR /var/www/html/simples_client
@ -26,5 +26,5 @@ ENTRYPOINT [ "php" ]
CMD ["-S", "0.0.0.0:80", "-t", "/var/www/html/simples_client"]
#docker image build -t client_whatsapp .
# docker image build -t client_whatsapp .
# docker run -d --name client_whatsapp -p 8001:80 client_whatsapp

41
app/view/content.php

@ -13,14 +13,35 @@
<div class="sidebar-header-icons">
<div id="btnsPause"></div>
<img src="<?= $files ?>/images/power.svg" id="exitSystem" alt="Desconectar do Chat" title="Sair do sistema" />
<!-- <img src="<?= $files ?>/images/settings.png" title="Configurações" id="configs"/> -->
<input type="checkbox" class="checkbox-switch" id="input-checkbox-switch">
<label for="input-checkbox-switch" class="label-switch">
<!-- <span><i class="fas fa-sun"></i></span>
<span><i class="fas fa-moon"></i></span> -->
<div class="switch-ball light-mode">
<span><i class="fas fa-sun"></i></span>
</div>
</label>
</div>
</div>
<div class="chats" id="chats"></div>
<div class="box-event-buttons">
<button class="btn-atendimento button-selected" id="btnAtendimento">Em atendimento </button>
<button class="btn-fila" id="btnFila">Em espera <span class="qtde-fila">2</span></button>
</div>
<div class="search">
<i class="fas fa-search search-icon"></i>
<input type="text" class="search-form" placeholder="Search" id="search-form">
</div>
<div class="chats" id="chats">
</div>
</div>
<div class="main">
<div class="fade"></div>
<div class="chat-window-header">
<div class="chat-window-header-left" id="headermediaagent">
<span class="btn-exit-chat" id="exitChat"><i class="fas fa-arrow-left"></i></span>
<img class="chat-window-contact-image" src="<?= $files ?>/images/whatsapp.png" />
<div class="contact-name-and-status-container">
<span class="chat-window-contact-name"></span>
@ -37,6 +58,7 @@
<span class="chat-window-menu-span"> Finalizar</span>
</div>
</div>
<span id="chat-window-header-right-icon" class="responsive-icon-header"><i class="fas fa-ellipsis-v"></i></span>
</div>
<div class="chat-window" id="chatwindowagent">
@ -56,24 +78,26 @@
</label>
<input id="uploadimage" accept="image/*,video/mp4,video/3gpp,video/quicktime" type="file" multiple="" style="display: none;">
</div>
<div class="type-message-bar" id="typemessagebar">
<div class="type-message-bar-left">
<img src="<?= $files ?>/images/microphone.svg" id="voicerecorder" title="Enviar mensagem de audio" />
<img src="<?= $files ?>/images/clip.svg" id="imgclip" title="Anexar arquivo ou imagem" />
</div>
<div class="type-message-bar-center">
<textarea rows="1" type="text" id="fieldsendmessage" placeholder="Escreva uma mensagem" style="resize: none;"></textarea>
</div>
<div class="type-message-bar-right flex-center">
<img src="<?= $files ?>/images/paper-plane.svg" title="Enviar mensagem" />
<img src="<?= $files ?>/images/microphone.svg" id="voicerecorder" title="Enviar mensagem de audio" class="icons file"/>
<img src="<?= $files ?>/images/clip.svg" id="imgclip" title="Anexar arquivo ou imagem" class="icons file"/>
<img src="<?= $files ?>/images/send-message.png" title="Enviar mensagem" class="icons send"/>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<div id="modalselect" class="modal">
<div class="modal-content">
<div class="modal-header">
@ -90,6 +114,9 @@
</div>
</div>
<script>
let modal = document.getElementById("modalselect");
let span = document.getElementsByClassName("close")[0];

2
app/view/header.php

@ -8,4 +8,6 @@
<title>Simples IP - Simples Client</title>
<link rel="icon" href="<?= $files ?>/images/favicon.ico" />
<link rel="stylesheet" href="<?= $files ?>/css/styles.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"/>
</head>

73
index copy.php

@ -0,0 +1,73 @@
<?php
include "config/includes.php";
use app\Provider\Crypt;
$files = getconfig('app')['FILES'];
$crypt = new Crypt('aes-256-cbc', getconfig('app')['PASSWORD']);
$geturl = bootstrap();
$connected = false;
$post = is_postback();
$objs = [
'obj_server' => null,
'my_uniqueid' => null,
'obj_queue' => null,
'obj_ws' => null,
'supervisor_api' => null,
'session_uniqueid' => null,
'obj_notification' => null,
'obj_contact' => null,
'obj_status' => null,
'session_window' => null
];
if ($geturl['t'] == 'gerar' && ($_SERVER['SERVER_NAME'] == 'localhost' || $geturl['password'] == 'S1MPL3S1P_CH4T')) {
foreach ($objs as $key => $val) {
$jsStartup[] = "localStorage.removeItem('{$key}')";
}
$dados = true;
}
if ($post) {
$objs['id_empresa'] = $post['empresa'];
$objs['obj_server'] = "http://{$post['servidor']}";
$objs['my_uniqueid'] = $post['matricula'];
$objs['obj_queue'] = $post['fila'];
$objs['obj_ws'] = "ws://{$post['servidor']}:8080/wss";
$objs['supervisor_api'] = "http://{$post['servidor']}";
foreach ($objs as $key => $val) {
$jsStartup[] = "localStorage.removeItem('{$key}')";
if ($val) {
$jsStartup[] = sprintf("localStorage.setItem('{$key}', '%s')", $val);
}
}
$connected = true;
}
?>
<!DOCTYPE html>
<html>
<?php include "app/view/header.php" ?>
<?php if ($dados && !$connected) { ?>
<form method="post">
<p>Informe o id da empresa:</p>
<input type="number" name="empresa" placeholder="Informe o ID a empresa"><br>
<p>Informe o Servidor:</p>
<input type="text" name="servidor" placeholder="Informe o IP/Host do servidor"><br>
<p>Informe a Matricula:</p>
<input type="text" name="matricula" placeholder="Informe matricula do agente"><br>
<p>Informe a fila:</p>
<input type="number" name="fila" placeholder="Informe o numero da fila"><br>
<input type="submit" name="btnSend" value="Gerar Token">
</form>
<?php } ?>
<body>
<?php include "app/view/content.php" ?>
</body>
</html>

76
index.php

@ -7,36 +7,48 @@ use app\Provider\Crypt;
$files = getconfig('app')['FILES'];
$crypt = new Crypt('aes-256-cbc', getconfig('app')['PASSWORD']);
$geturl = bootstrap();
$post = is_postback();
$connected = false;
if($geturl['t'] == 'gerar' && $_SERVER['SERVER_NAME'] == 'localhost'){
$expireToken = strtotime( '+1 days', time());
$json_info = '{"servidor": "http://sipcloud02.simplesip.com.br:8000", "websocket": "ws://sipcloud02.simplesip.com.br:8000/wss", "matricula": "1000", "fila": "102", "expire": "'.$expireToken.'"}';
echo $json_info;
echo "<br/><br/>";
echo "Token: <input type='text' value='{$crypt->encrypt($json_info)}' size='90'>";
if ($geturl['t'] == 'gerar' && $post['passwd'] == 'S1MPL3S1P_CH4T') {
$expireToken = strtotime("+{$post['expire']} days", time());
$info = [
"id_number" => $post['id_number'],
"id_empresa" => $post['id_empresa'],
"servidor" => $post['servidor'],
"websocket" => "ws://{$post['servidor']}:8080",
"matricula" => $post['matricula'],
"fila" => $post['fila'],
"expire" => $expireToken
];
$token = $crypt->encrypt(json_encode($info, true));
echo "Token: <input type='text' value='{$token}' size='90'><br><br>";
// echo "<a href='http://{$post['servidor']}:8001/?t=$token' target='_blank'><b>Ir para</b></a>";
echo "<a href='http://localhost:8001/?t=$token' target='_blank'><b>Ir para</b></a>";
exit;
}
$json = json_decode($crypt->decrypt(str_replace(' ', '+', $geturl['t'])), true);
if($geturl['t'] && $json ){
if ($geturl['t']) {
$json = json_decode($crypt->decrypt(str_replace(' ', '+', $geturl['t'])), true);
$objs = [
'obj_server' => $json['servidor'],
'my_uniqueid' => $json['matricula'],
'obj_queue' => $json['fila'],
'id_number' => $json['id_number'],
'id_empresa' => $json['id_empresa'],
'obj_server' => $json['servidor'],
'my_uniqueid' => $json['matricula'],
'obj_queue' => $json['fila'],
'obj_ws' => $json['websocket'],
'supervisor_api' => $json['api'],
'session_uniqueid' => null,
'obj_notification' => null,
'obj_contact' => null,
'obj_status' => null,
'session_uniqueid' => null,
'obj_notification' => null,
'obj_contact' => null,
'obj_status' => null,
'session_window' => null
];
foreach($objs as $key => $val){
foreach ($objs as $key => $val) {
$jsStartup[] = "localStorage.removeItem('{$key}')";
if($val){
if ($val) {
$jsStartup[] = sprintf("localStorage.setItem('{$key}', '%s')", $val);
}
}
@ -46,8 +58,32 @@ if($geturl['t'] && $json ){
<!DOCTYPE html>
<html>
<?php include "app/view/header.php" ?>
<?php include "app/view/header.php" ?>
<body>
<?php include "app/view/content.php" ?>
<?php if ($geturl['t'] == 'gerar') { ?>
<form method="post">
<p>Informe o id da empresa:</p>
<input type="number" name="id_empresa" placeholder="Informe o ID da empresa"><br>
<p>Informe o id do numero:</p>
<input type="number" name="id_number" placeholder="Informe o ID do numero"><br>
<p>Informe o Servidor:</p>
<input type="text" name="servidor" placeholder="Informe o IP/Host do servidor"><br>
<p>Informe a Matricula:</p>
<input type="text" name="matricula" placeholder="Informe matricula do agente"><br>
<p>Informe a fila:</p>
<input type="number" name="fila" placeholder="Informe o numero da fila"><br>
<p>Token expira dias:</p>
<input type="number" name="expire" value="1" placeholder="Informe o numero da fila"><br>
<p>Password To generate token:</p>
<input type="text" name="passwd" placeholder="Informe a senha para gerar o token"><br>
<input type="submit" name="btnSend" value="Gerar Token">
</form>
<?php } else { ?>
<?php include "app/view/content.php" ?>
<?php } ?>
</body>
</html>

714
public/css/styles.css

File diff suppressed because it is too large Load Diff

68
public/css/teste

@ -0,0 +1,68 @@
@media (max-width: 680px) {
.app {
grid-template-columns: 30em 1fr;
/* grid-template-columns: 1fr; */
}
/* .sidebar {
display: none;
} */
}
@media (max-width: 850px) {
.app {
grid-template-columns: 33em 1fr;
}
}
@media (max-height: 820px) {
#welcometomessage h1,
h2 {
font-size: 30px;
}
#welcometomessage img {
width: 300px;
}
}
@media (max-height: 1380px) {
.chats {
height: 65vh;
padding-bottom: 20px;
}
}
@media (max-height: 700px) {
.type-message-bar {
bottom: 2rem;
}
/* .estatisticas {
display: none;
} */
.chats {
height: 60vh;
padding-bottom: 30px;
}
.type-message-bar {
bottom: 0;
}
}
/* @media (max-height: 650px) {
.chats {
height: 50vh;
padding-bottom: 30px;
}
} */
/*
@media (max-height: 550px) {
.type-message-bar {
bottom: 11rem;
}
}
*/

BIN
public/images/favicon.ico

Binary file not shown.

Before

Width:  |  Height:  |  Size: 438 B

After

Width:  |  Height:  |  Size: 15 KiB

BIN
public/images/lua.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1007 B

BIN
public/images/send-message.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 635 B

BIN
public/images/seta-para-baixo.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

BIN
public/images/settings.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

BIN
public/images/sol.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

17
public/index.html

@ -4,7 +4,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multi Channel | Simples Chat</title>
<title>Simples Chat</title>
<link rel="icon" href="images/favicon.ico" />
<link rel="stylesheet" href="../public/css/styles.css" />
</head>
@ -28,17 +28,7 @@
<div id="btnsPause"></div>
<img src="images/power.svg" title="Sair do sistema"/>
</div>
</div>
<div class="sidebar-notifications">
<img src="images/notifications.svg" />
<div class="sidebar-notifications-message">
<span>Get Notified of New Messages</span>
<a href="#">Turn on desktop notifications <img src="images/gt-arrow.svg" /></a>
</div>
</div>
</div>
<!-- Sidebar search chat -->
@ -97,7 +87,7 @@
<div class="type-message-bar" id="typemessagebar">
<div class="type-message-bar-left">
<!-- <img src="images/icons.svg" /> -->
<img src="images/microphone.svg" id="voicerecorder" title="Gravar mensagem áudio" />
<img src="images/microphone.svg" id="voicerecorder" title="Gravar mensagem <EFBFBD>udio" />
<img src="images/clip.svg" id="imgclip" title="Anexar arquivos ou images"/>
</div>
@ -134,7 +124,6 @@
<script>
let modal = document.getElementById("modalselect");
let span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
}

8
public/js/config.js

@ -1,6 +1,10 @@
const ws = localStorage.getItem('obj_ws')
const server_api = localStorage.getItem('obj_server')
const server_api = `http://${localStorage.getItem('obj_server')}`
const supervisor_api = localStorage.getItem('supervisor_api') ? localStorage.getItem('supervisor_api') : localStorage.getItem('obj_server')
let mediaRecorder
const icontypes = ['csv', 'doc', 'pdf', 'txt', 'xls', 'zip', 'ppt']
const path = 'public'
const path = 'public'
const html = document.querySelector("html");
let abrirMensagem = false;
let inputInterface = document.querySelector('#input-checkbox-switch');
let chatsArray = [];

4
public/js/cronometro.js

@ -47,8 +47,8 @@ function converdata(timestamp, horario_server = false){
}
let date = new Date(timestamp);
let day = addZero(date.getDay())
let month = addZero(date.getMonth())
let day = addZero(date.getDate())
let month = addZero(date.getMonth() + 1)
let hours = date.getHours();
let minutes = date.getMinutes();
let formattedTime = `${day}/${month} ` + addZero(hours) + ':' + addZero(minutes)

852
public/js/main.js

@ -1,452 +1,516 @@
/**
* EVENTOS GERADOS PELO USUÁRIO DA APLICAÇÃO
* EVENTOS GERADOS PELO USUARIO DA APLICACAO
*/
$(function(){
connect(ws)
notifications()
/**
* VOICE RECORDER
*/
$('.modal-content-body').on('click', '#stoprecorder', () => {
$('#msgRecorder').text('Paramos de gravar sua voz!')
mediaRecorder.stop()
})
$('#voicerecorder').on('click', () => {
recorderVoice()
})
/** FIM VOICE RECORDER */
/** EVENTOS DE CLICK NO BODY */
$("body").mouseup(function(){
$('#uploadfiles').fadeOut('slow')
});
/** INICIO DAS FUNCIONALIDADES */
startSendImage()
startSendFile()
startPause()
startTransfer()
startFinalizar()
exitSystem()
/** INICIA COM O HEADER DO CONTATO VAZIO */
startChannelMessage()
/** INICIA O CHAT NO FINAL DA CONVERSA */
$('.chats').on('click', function(){
scrollDown()
})
/** 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()
})
$('#imgclip').on('click', function(){
modalStart()
$("#uploadimage").val('')
$('#uploadfile').val('')
if($('#uploadfiles').is(':hidden')){
$('#uploadfiles').fadeIn('slow')
} else {
$('#uploadfiles').fadeOut('slow')
}
})
$('#footer-content-right').on('click', '#footersend', () => {
sendMedia(mediaRecorder)
$('#modalselect').css({display: 'none'})
})
supervisorAgente()
})
$(function () {
connect(ws);
notifications();
/**
* VOICE RECORDER
*/
$(".modal-content-body").on("click", "#stoprecorder", () => {
$("#msgRecorder").text("Paramos de gravar sua voz!");
mediaRecorder.stop();
});
$("#voicerecorder").on("click", () => {
recorderVoice();
});
$("#search-form").on("keyup", ({ target }) => {
search(target);
});
$("#chat-window-header-right-icon").on("click", () => {
responsivoButtonsHeader();
});
$("#btnFila").on("click", () => {
filaNotifications();
});
$("#btnAtendimento").on("click", () => {
notifications();
});
$("#exitChat").on("click", () => {
abrirMensagem = false;
abrirTela();
// removeMensagemBody();
});
/** FIM VOICE RECORDER */
/** EVENTOS DE CLICK NO BODY */
$("body").mouseup(function () {
$("#uploadfiles").fadeOut(200);
});
$(".fade").mouseup(function () {
$(".chat-window-header-right").removeClass("ativo");
});
/** INICIO DAS FUNCIONALIDADES */
startSendImage();
startSendFile();
startPause();
startTransfer();
startFinalizar();
exitSystem();
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);
});
$(".box-event-buttons button").on("click", ({ target }) => {
click_btn(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();
});
$("#imgclip").on("click", function () {
modalStart();
$("#uploadimage").val("");
$("#uploadfile").val("");
if ($("#uploadfiles").is(":hidden")) {
$("#uploadfiles").fadeIn(200);
} else {
$("#uploadfiles").fadeOut(200);
}
});
$("#footer-content-right").on("click", "#footersend", () => {
sendMedia(mediaRecorder);
$("#modalselect").css({ display: "none" });
});
supervisorAgente();
});
/**
* EVENTOS DE CLICK PARA SELECIONAR A SESSÃO DE MENSAGEM/CONVERSA E RECUPERAR AS MENSAGENS TROCADAS NO ATENDIMENTO
* @param {*} id
* EVENTOS DE CLICK PARA SELECIONAR A SESSAO DE MENSAGEM/CONVERSA E RECUPERAR AS MENSAGENS JA TROCADAS NO ATENDIMENTO
* @param {*} id
*/
const selectNotification = (id) => {
marcarMensagemVista(id)
listaMensagem(id).then(() => {
let uniqueid
let number
let name
let dataContact
let protocolo
const dataRequest = JSON.parse(localStorage.getItem('obj_contact'))
listarAtendimentoAgente(localStorage.getItem('my_uniqueid'))
const allNotifications = JSON.parse(localStorage.getItem('obj_notification'))
hideButtons(false)
allNotifications.data.forEach(e => {
$('#' + e.uniqueid.replace('.', `\\.`)).removeClass('select-notification')
if(e.uniqueid == id && e.status == 0){
hideButtons(true)
}
})
$('#' + id.replace('.', `\\.`)).addClass('select-notification')
allNotifications.data.forEach(e => {
if(e.uniqueid == id && e.status == 0){
hideButtons(true)
}
})
if(dataRequest.data.length > 0){
dataContact = dataRequest.data.filter(e => {
if(id.trim() == e.event?.mensagem.uniqueid){
return true
}
})
marcarMensagemVista(id);
listaMensagem(id).then(async () => {
let uniqueid;
let number;
let name;
let dataContact;
let protocolo;
const dataRequest = JSON.parse(localStorage.getItem("obj_contact"));
listarAtendimentoAgente(
localStorage.getItem("id_empresa"),
localStorage.getItem("my_uniqueid")
);
const allNotifications = JSON.parse(
localStorage.getItem("obj_notification")
);
const atendimentos = await buscarAtendimento(id);
hideButtons(false);
allNotifications.data.forEach((e) => {
$("#" + e.uniqueid.replace(".", `\\.`)).removeClass(
"select-notification"
);
if (e.uniqueid == id && e.status == 0) {
hideButtons(true);
}
});
$("#" + id.replace(".", `\\.`)).addClass("select-notification");
allNotifications.data.forEach((e) => {
if (e.uniqueid == id && e.status == 0) {
hideButtons(true);
}
});
if (dataRequest.data.length > 0) {
dataContact = dataRequest.data.filter((e) => {
if (id.trim() == e.uniqueid) {
return true;
}
allNotifications.data.forEach(e => {
if(id === e.uniqueid){
uniqueid = e.uniqueid
name = e.nome
number = e.cliente_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.event?.mensagem.datetime ? converdata(new Date(e.event?.mensagem.datetime).getTime()) : 'algumas horas';
let typesend = localStorage.getItem('my_uniqueid') == e.event.contact.number ? 'sender': 'receiver'
if(e.event?.mensagem.type == 'text'){
$('.chat-window').append(`
});
}
allNotifications.data.forEach((e) => {
if (id === e.uniqueid) {
uniqueid = e.uniqueid;
name = e.nome;
number = e.cliente_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");
if (typeof dataContact === "undefined") return;
dataContact.forEach((e) => {
const datesend = e.msg_date
? converdata(new Date(e.msg_date).getTime())
: "algumas horas";
let typesend =
atendimentos.data[0].cliente_id == e.dst ? "sender" : "receiver";
if (e.type == "text") {
$(".chat-window").append(`
<div class="${typesend}">
<span class="${typesend}-message">${e.event.mensagem.content}</span>
<span class="${typesend}-message">${e.content.replace(
/\r?\n/g,
"<br>"
)}</span>
<br/>
<span class="message-time">${datesend}</span>
</div>`
)
}
if(e.event?.mensagem.type == 'finish' || e.event?.mensagem.type == 're_start'){
$('.chat-window').append(`
</div>`);
}
if (e.type == "transfer") {
$(".chat-window").append(`
<div class="events">
<span class="events-message">${e.event.mensagem.content}</span>
</div>`
)
}
if(e.event?.mensagem.type != 'text'){
const sendobj = {
filename: e.event?.mensagem.file_name,
id_provedor: e.event?.mensagem.id_provedor,
type: e.event?.mensagem.type,
mimetype: e.event?.mensagem.mimetype,
from: typesend
}
messageTypeMedia(sendobj)
}
if(e.de == localStorage.getItem('my_uniqueid')){
const datereceived = e.datetime ? converdata(e.datetime) : 'algumas horas';
if(e.type == 'text'){
$('.chat-window').append(`
<span class="events-message">${e.content} por ${e.profile_name}, ${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,
id_provedor: e.id_provedor,
type: e.type,
mimetype: e.mimetype,
from: typesend,
};
messageTypeMedia(sendobj);
}
if (e.de == localStorage.getItem("my_uniqueid")) {
const datereceived = e.datetime
? converdata(e.datetime)
: "algumas horas";
if (e.type == "text") {
$(".chat-window").append(`
<div class="${typesend}">
<span class="${typesend}-message">${e.msg}</span>
<br/>
<span class="message-time">${datereceived}</span>
</div>`)
} else if (e.type == 'audio' || e.type == 'voice'){
const audio = `<audio controls>
<source src="data:audio/mpeg;base64,${e.msg}"></source>
</audio>`
$('.chat-window').append(`
</div>`);
} else if (e.type == "audio" || e.type == "voice") {
const audio = `<audio controls><source src="data:audio/mpeg;base64,${e.msg}"></source></audio>`;
$(".chat-window").append(`
<div class="${typesend}">
<span class="${typesend}-message">${audio}</span>
<span class="${typesend}-message audio">${audio}</span>
<br/>
<span class="message-time">${datereceived}</span>
</div>`)
} else if (e.type == 'document'){
icontypes.forEach(l => {
if(e.filename.indexOf(l) >= 0){
$('.chat-window').append(`
</div>`);
} else if (e.type == "document") {
icontypes.forEach((l) => {
if (e.filename.indexOf(l) >= 0) {
$(".chat-window").append(`
<div class="${typesend}">
<span class="${typesend}-message message-column">
<a href="http://${server_api}/integracao/media/link/${e.uniqueid}/${window.btoa('application/' + l)}" target="_blank">
<a href="http://${server_api}/link/${
e.uniqueid
}/${window.btoa("application/" + l)}" target="_blank">
<img src="${path}/images/icons/${l}-file.png" style="max-width: 60px">
</a>
</span>
${e.filename}
<br/>
<span class="message-time">${datereceived}</span>
</div>`)
}
})
} else if (e.type == 'image'){
const fileimg = `data:${e.mimetype};base64,` + e.msg
$('.chat-window').append(`
</div>`);
}
});
} else if (e.type == "image") {
const fileimg = `data:${e.mimetype};base64,` + e.msg;
$(".chat-window").append(`
<div class="${typesend}">
<span class="${typesend}-message"><img src="${fileimg}" style="max-width: 200px; max-height: 150px"></span>
<br/>
<span class="message-time">${datereceived}</span>
</div>`)
}
}
})
scrollDown()
})
startNotification()
}
</div>`);
}
}
});
scrollDown();
});
abrirMensagem = true;
startNotification();
};
/**
* REALIZA O ENVIO DE MENSAGEM ATRAVEZ DA API
* @param {*} obj
* @returns
* @param {*} obj
* @returns
*/
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() : obj.content
let name = agent.data.nome ? agent.data.nome : 'Atendente'
let uniqueid = localStorage.getItem('session_uniqueid')
let media = obj.media ? obj.media : 'whatsapp'
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",
"contact": {
"name": name,
"number": myUniqueid,
"matricula": myUniqueid
},
"mensagem": {
"uniqueid": uniqueid,
"dst": sendNumber,
"id_provedor": `${uniqueid}_${Date.now()}`,
"type": type,
"mimetype": mimetype,
"media": media,
"content": sendContent,
"status": "sended"
}
}
}
if(type != 'audio'){
dataSend.event.mensagem.file_name = filename
}
enviarMensagem(dataSend)
let msgContent = type == 'text' ? sendContent : obj.fileContent
$('.chat-window').append(`
console.log('send')
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()
: obj.content;
let name = agent.data.nome ? agent.data.nome : "Atendente";
let uniqueid = localStorage.getItem("session_uniqueid");
let media = obj.media ? obj.media : "whatsapp";
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",
contact: {
name: name,
number: myUniqueid,
matricula: myUniqueid,
},
mensagem: {
uniqueid: uniqueid,
dst: sendNumber,
id_provedor: `${uniqueid}_${Date.now()}`,
type: type,
mimetype: mimetype,
media: media,
content: sendContent,
status: "sended",
},
},
};
if (type != "audio") {
dataSend.event.mensagem.file_name = filename;
}
enviarMensagem(dataSend);
let msgContent = type == "text" ? sendContent : obj.fileContent;
$(".chat-window").append(`
<div class="sender">
<span class="sender-message">${msgContent}</span>
<span class="sender-message">${msgContent.replace(
/\r?\n/g,
"<br>"
)}</span>
<br/>
<span class="message-time">${converdata(Date.now())}</span>
</div>`)
scrollDown()
/** LIMPA O CAMPO DE ENVIO DE MENSAGEM */
$('#fieldsendmessage').val("")
}
</div>`);
scrollDown();
/** LIMPA O CAMPO DE ENVIO DE MENSAGEM */
$("#fieldsendmessage").val("");
};
/**
* ATUALIZA AS MENSAGEM QUE SÃO RECEBIDAS NA TELA DO ATENDIMENTO
* @param {*} ev
* ATUALIZA AS MENSAGEM QUE SAO RECEBIDAS NA TELA DO ATENDIMENTO
* Os dados s<EFBFBD>o transmitidos pelo evento de WS
* @param {*} ev
*/
const viewMessage = (ev) => {
const sessionOpen = localStorage.getItem('session_uniqueid')
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){
case 'text':
$('.chat-window').append(`
const sessionOpen = localStorage.getItem("session_uniqueid");
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) {
case "text":
$(".chat-window").append(`
<div class="receiver">
<span class="receiver-message">${ev.event.mensagem.content}</span>
<br/>
<span class="message-time">${datesend}</span>
</div>`)
break
case 'finish':
case 're_start':
$('.chat-window').append(`
</div>`);
break;
case "finish":
case "re_start":
$(".chat-window").append(`
<div class="events">
<span class="events-message">${ev.event.mensagem.content}</span>
</div>`)
break
}
const mediaDownload = ["image", "voice", "document", "audio", "video", "sticker"]
if(mediaDownload.indexOf(ev.event?.mensagem.type) >= 0){
const sendobj = {
filename: ev.event?.mensagem.file_name,
id_provedor: ev.event?.mensagem.id_provedor,
type: ev.event?.mensagem.type,
mimetype: ev.event?.mensagem.mimetype,
from: 'receiver'
}
messageTypeMedia(sendobj)
}
scrollDown()
</div>`);
break;
}
}
const mediaDownload = [
"image",
"voice",
"document",
"audio",
"video",
"sticker",
];
if (mediaDownload.indexOf(ev.event?.mensagem.type) >= 0) {
const sendobj = {
filename: ev.event?.mensagem.file_name,
id_provedor: ev.event?.mensagem.id_provedor,
type: ev.event?.mensagem.type,
mimetype: ev.event?.mensagem.mimetype,
from: "receiver",
};
messageTypeMedia(sendobj);
}
scrollDown();
}
};
/**
* APRESENTA AS NOVAS NOTIFICACOES DE ATENDIMENTO NA TELA DO ATENDENTE
* -> CADA ATENDIMENTO DEVE POSSUIR APENAS UMA NOTIFICACAO
* @param {*} data
* @param {*} data
*/
const receiveNotification = (data) => {
let validate = null
switch(data.event?.type){
case "mensagem":
if(data.event.mensagem.uniqueid != localStorage.getItem('session_uniqueid')){
notifyMe(data.event.contact.name, {
body: data.event.mensagem.content,
icon: `images/${data.event.mensagem.media}.png`,
silent: true
})
soundNotification(`${path}/sound/notification.mp3`)
}
/** VALIDA O NUMERO, VERIFICA SE O TEM ALGMA MSG INICIAL, SE JÁ TEVE UM NUMERO NA VERIFICACAO */
listarAtendimentoAgente(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 && vald.length == 0) {
notifications(
{
uniqueid: data.event?.mensagem.uniqueid,
cliente_id: data.event?.contact.number,
context: data.event?.mensagem.media,
profile_name: data.event?.contact.name,
data_reg: data.event?.mensagem.datetime,
status: 1,
action: 'mensagem',
}
)
}
break
case "actions":
let obj
switch(data.event.mensagem.type){
case 'start':
case 'transfer':
case 'att_status':
obj = {}
break
case 'finish':
case 're_start':
obj = {
uniqueid: data.event?.mensagem.uniqueid,
action: data.event.mensagem.type,
}
break
}
notifications(obj)
break
}
}
let validate = null;
switch (data.event?.type) {
case "mensagem":
if (
data.event.mensagem.uniqueid != localStorage.getItem("session_uniqueid")
) {
notifyMe(data.event.contact.name, {
body: data.event.mensagem.content,
icon: `images/${data.event.mensagem.media}.png`,
silent: true,
});
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 &&
vald.length == 0
) {
notifications({
uniqueid: data.event?.mensagem.uniqueid,
cliente_id: data.event?.contact.number,
context: data.event?.mensagem.media,
profile_name: data.event?.contact.name,
data_reg: data.event?.mensagem.datetime,
media: data.event?.mensagem.media,
status: 1,
action: "mensagem",
});
}
break;
case "actions":
let obj;
switch (data.event.mensagem.type) {
case "start":
case "transfer":
case "att_status":
obj = {};
break;
case "finish":
case "re_start":
obj = {
uniqueid: data.event?.mensagem.uniqueid,
action: data.event.mensagem.type,
};
break;
}
notifications(obj);
break;
}
};
/**
* MANTEM TODAS AS MENSAGENS ARMAZENADAS NO LOCALSTORAGE, SEMPRE QUE ENVIA E RECEBE SERÁ GUARDADO
* @param {*} ev
* MANTEM TODAS AS MENSAGENS ARMAZENADAS NO LOCALSTORAGE, SEMPRE QUE ENVIA E RECEBE SERA GUARDADO
* @param {*} ev
*/
const keepMensage = (ev) => {
let msg = JSON.parse(localStorage.getItem('keep_msg'))
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))
}
}
let msg = JSON.parse(localStorage.getItem("keep_msg"));
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));
}
};
/**
* FUNÇÃO PARA CAPTURAR O ARQUIVO A SER ENVIADO
* FUNCAO PARA CAPTURAR O ARQUIVO A SER ENVIADO
*/
const sendMedia = (media = null) => {
let rec
let filename
if($("#footer-content-left audio").length){
if(media.state == 'recording'){
media.stop();
}
let el = $("#footer-content-left audio")[0].src
fileContent = $("#footer-content-left audio")[0].outerHTML
sendMessage({ content: el.replace("data:", "").replace(/^.+,/, ""), type: 'audio', mimetype: 'audio/mpeg', fileContent })
return
} else if($("#uploadfile")[0].files[0]) {
let el = $("#uploadfile")[0].files[0]
rec = new Blob([el], { type : el.type })
let filesent = $("#myImg")
filesent[0].id = Date.now()
imgContent = filesent.css({'max-width': '60px'})[0].outerHTML
fileContent = `<a href="${URL.createObjectURL(rec)}" target="_blank">${imgContent}</a>`
filename = el.name
} else {
rec = $("#uploadimage")[0].files[0]
let filesent = $("#myImg")
filesent[0].id = Date.now()
fileContent = filesent.css({'max-width': '350px'})[0].outerHTML
$("#myImg").empty()
}
const file = new FileReader();
file.onload = function() {
const typefile = rec.type.split("/")[0].indexOf('image') >= 0 ? rec.type.split("/")[0] : 'document'
sendMessage({ content: file.result.replace("data:", "").replace(/^.+,/, ""), type: typefile, mimetype: rec.type, fileContent, filename })
const sendMedia = (media = null) => {
let rec;
let filename;
if ($("#footer-content-left audio").length) {
if (media.state == "recording") {
media.stop();
}
file.readAsDataURL(rec);
}
let el = $("#footer-content-left audio")[0].src;
fileContent = $("#footer-content-left audio")[0].outerHTML;
sendMessage({
content: el.replace("data:", "").replace(/^.+,/, ""),
type: "audio",
mimetype: "audio/mpeg",
fileContent,
});
return;
} else if ($("#uploadfile")[0].files[0]) {
let el = $("#uploadfile")[0].files[0];
rec = new Blob([el], { type: el.type });
let filesent = $("#myImg");
filesent[0].id = Date.now();
imgContent = filesent.css({ "max-width": "60px" })[0].outerHTML;
fileContent = `<a href="${URL.createObjectURL(
rec
)}" target="_blank">${imgContent}</a>`;
filename = el.name;
} else {
rec = $("#uploadimage")[0].files[0];
let filesent = $("#myImg");
filesent[0].id = Date.now();
fileContent = filesent.css({ "max-width": "200px" })[0].outerHTML;
$("#myImg").empty();
}
const file = new FileReader();
file.onload = function () {
const typefile =
rec.type.split("/")[0].indexOf("image") >= 0
? rec.type.split("/")[0]
: "document";
sendMessage({
content: file.result.replace("data:", "").replace(/^.+,/, ""),
type: typefile,
mimetype: rec.type,
fileContent,
filename,
});
};
file.readAsDataURL(rec);
};

146
public/js/requests.js

@ -1,24 +1,20 @@
const enviarMensagem = (dataSend) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/enviarMensagem`,
url: `${server_api}/messages/sendMessage`,
type: "POST",
data: JSON.stringify(dataSend),
success: function (res) {
//console.log(res)
},
error: function (res) {
$('.chat-window').append(`<div class="sender"><span class="sender-message">MENSAGEM NÃO FOI ENVIADA!</span></div>`)
$('.chat-window').append(`<div class="sender"><span class="sender-message">MENSAGEM NÃO FOI ENVIADA!</span></div>`)
}
});
}
const listaMensagem = (uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/listarMensagem`,
type: "POST",
data: JSON.stringify({
uniqueid
}),
url: `${server_api}/messages/${uniqueid}`,
type: "GET",
success: function (res) {
localStorage.removeItem('obj_contact')
localStorage.setItem('obj_contact', JSON.stringify(res))
@ -29,10 +25,9 @@ const listaMensagem = (uniqueid) => new Promise((resolve) => {
}
})
})
const listarAgentesDisponivel = () => new Promise((resolve) => {
const listarAgentesDisponivel = (id_empresa) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/listarAgentesDisponivel`,
url: `${server_api}/supervisor/agentes/status/${id_empresa}/livre`,
type: "GET",
success: function (res) {
resolve(res)
@ -42,44 +37,55 @@ const listarAgentesDisponivel = () => new Promise((resolve) => {
}
});
})
const listarAtendimentoAgente = (matricula) => new Promise((resolve) => {
const listarAtendimentoAgente = (id_empresa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/listarAtendimentoAgente`,
type: "POST",
data: JSON.stringify({
matricula
}),
url: `${server_api}/atendimentos/${id_empresa}/${matricula}`,
type: "GET",
success: function (res) {
localStorage.removeItem('obj_notification')
localStorage.setItem('obj_notification', JSON.stringify(res))
resolve(res)
},
error: function (res) {
}
});
})
const listarPausasAgente = (matricula) => new Promise((resolve) => {
const listarPausasAgente = (id_empresa) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/pausas/${id_empresa}`,
type: "GET",
success: function (res) {
resolve(res)
},
error: function (res) {
alert('Nao foi possivel carregar as listas de pausa.')
}
});
})
const listarAtendimentosFila = (id_queue, status) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/listarPausasAgente`,
url: `${server_api}/atendimentos/buscar/status`,
type: "POST",
data: JSON.stringify({
matricula
id_queue,
status
}),
success: function (res) {
resolve(res)
},
error: function (res) {
alert('Nao foi possivel carregar as listas de pausa.')
alert('erro ao chamar API');
}
});
})
const entrarPausa = (id_pausa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/entrarPausa`,
url: `${server_api}/supervisor/entrarPausa`,
type: "POST",
data: JSON.stringify({
id_pausa,
@ -94,14 +100,13 @@ const entrarPausa = (id_pausa, matricula) => new Promise((resolve) => {
}
},
error: function (res) {
alert('Não foi possível atribuir a pausa no momento!')
alert('Não foi possível atribuir a pausa no momento!')
}
});
})
const sairPausa = (matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/sairPausa`,
url: `${server_api}/supervisor/sairPausa`,
type: "POST",
data: JSON.stringify({
matricula
@ -115,14 +120,14 @@ const sairPausa = (matricula) => new Promise((resolve) => {
}
});
})
const entrar = (matricula, queue) => new Promise((resolve) => {
const entrar = (matricula, id_fila, id_number) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/entrar`,
url: `${server_api}/auth/conectar-chat`,
type: "POST",
data: JSON.stringify({
id_fila: queue,
matricula
matricula,
id_fila,
"id_number_channel": id_number
}),
success: function (res) {
resolve(res)
@ -132,10 +137,9 @@ const entrar = (matricula, queue) => new Promise((resolve) => {
}
});
})
const sair = (matricula) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/sair`,
url: `${server_api}/auth/desconectar-chat`,
type: "POST",
data: JSON.stringify({
matricula
@ -153,10 +157,9 @@ const sair = (matricula) => {
}
});
}
const finalizarAtendimento = (matricula, uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/finalizarAtendimento`,
url: `${server_api}/atendimentos/finalizar`,
type: "POST",
data: JSON.stringify({
matricula,
@ -176,55 +179,38 @@ const finalizarAtendimento = (matricula, uniqueid) => new Promise((resolve) => {
error: function (res) {
alertModal(
`<h2>OPS... HOUVE UM PROBLEMA &nbsp</h2><img id="imgReconnect" width="25px" src="${path}/images/alert.png">
<p>Não foi possível finalizar atendimento!</p>
<p>Não foi possível finalizar atendimento!</p>
<p>Error: ${res}</p>`,
'OPS!!!'
)
}
});
})
const statusAgente = (matricula) => new Promise((resolve) => {
const statusAgente = (id_empresa, matricula) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/statusAgente`,
type: "POST",
data: JSON.stringify({
matricula
}),
success: function(res) {
url: `${server_api}/supervisor/agentes/${id_empresa}/${matricula}`,
type: "GET",
success: function (res) {
localStorage.removeItem('obj_status')
localStorage.setItem('obj_status', JSON.stringify(res))
resolve(res)
},
error: function(res) {
console.log(res)
error: function (res) {
alertModal(
`<h2>RECONECTANDO, AGUARDE &nbsp</h2><img id="imgReconnect" width="25px" src="${path}/images/loading.gif">`,
'[ POR FAVOR AGUARDE ]'
)
console.log('statusAgente: ' + res.responseText)
}
});
})
const atualizaAgente = () => new Promise((resolve) => {
$.ajax({
url: `${supervisor_api}/index.php?idProg=14&idSubProg=3&ajax=1&acao=atualiza`,
type: "GET",
success: function(res){
resolve(res)
}
});
})
const transferirAtendimento = (origem, destino, uniqueid) => new Promise((resolve) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/transferirAtendimento`,
url: `${server_api}/atendimentos/transferir`,
type: "POST",
data: JSON.stringify({
matricula_origem: origem,
matricula_destino: destino,
uniqueid
uniqueid
}),
success: function (res) {
if (res.status == 'success') {
@ -237,18 +223,16 @@ const transferirAtendimento = (origem, destino, uniqueid) => new Promise((resolv
},
error: function (res) {
alertModal(
`<h2>OPS... HOUVE UM PROBLEMA &nbsp</h2><img id="imgReconnect" width="25px" src="${path}/images/alert.png">
<p>Não foi possível carregar as infoemacoes do agente!</p>
<p>Error: ${res}</p>`,
`<h3>OPS... HOUVE UM PROBLEMA &nbsp</h3><img id="imgReconnect" width="25px" src="${path}/images/alerta.png">
<p>Não foi possível carregar as infomacçõs do agente!</p>`,
'OPS!!!'
)
}
});
})
const marcarMensagemVista = (uniqueid) => {
$.ajax({
url: `${server_api}/integracao/media/api/agente/marcarMensagemVista`,
url: `${server_api}/messages/markMessageRead`,
type: "POST",
data: JSON.stringify({
uniqueid
@ -261,3 +245,33 @@ const marcarMensagemVista = (uniqueid) => {
}
});
}
const buscarAtendimento = async (uniqueid) => {
return $.ajax({
url: `${server_api}/atendimentos/buscar`,
type: "POST",
data: JSON.stringify({
uniqueid
}),
success: function (res) {
return res
},
error: function (res) {
alert('Nao foi possivel carregar as informacoes do atendimento.')
}
});
}
const buscarUsuario = (matricula) => new Promise((resolve) =>{
$.ajax({
url: `${server_api}/usuario/buscar`,
type: "POST",
data: JSON.stringify({
matricula
}),
success: function (res) {
resolve(res)
},
error: function (res) {
alert('Nao foi possivel carregar as informacoes do usuario.')
}
});
})

1269
public/js/util.js

File diff suppressed because it is too large Load Diff

6095
public/js/waveSurfer.js

File diff suppressed because it is too large Load Diff

67
ws.php

@ -0,0 +1,67 @@
<!DOCTYPE html>
<head>
<title>WebSocket client test</title>
</head>
<body>
<h1>WebSocket Client Test</h1>
<div id="log"></div>
</body>
<script language="javascript" type="text/javascript">
var wsUri = "ws://192.168.115.244:8080/wss";
var log;
function init() {
log = document.getElementById("log");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onclose = function(evt) {
onClose(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
writeLog("CONNECTED");
sendMessage("Hello world");
}
function onClose(evt) {
writeLog("Websocket DISCONNECTED");
}
function onMessage(evt) {
writeLog('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
websocket.close();
}
function onError(evt) {
writeLog('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function sendMessage(message) {
writeLog("SENT: " + message);
websocket.send(message);
}
function writeLog(message) {
var pre = document.createElement("p");
pre.innerHTML = message;
log.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
Loading…
Cancel
Save