Browse Source

Arquivos que faltavam na separação do PABX e o monitor

master
Rodgger 4 months ago
parent
commit
b116ebbfea
  1. 1106
      include/funcoes/shared.php
  2. 198
      include/util/constantes.php
  3. 2
      include/util/display_errors.php
  4. 952
      include/util/funcoesAmi.php
  5. 100
      integracao/bdApi.php
  6. BIN
      integracao/download/layouteBaseDiscador.pdf
  7. 76
      integracao/enviaCampanha.html
  8. 6700
      integracao/funcoesApi.php
  9. 97
      integracao/funcoesCustom.php
  10. BIN
      integracao/imgIntegra/delphiIco.png
  11. BIN
      integracao/imgIntegra/dotNetIco.png
  12. BIN
      integracao/imgIntegra/javaIco.png
  13. BIN
      integracao/imgIntegra/logoPrincipal.gif
  14. BIN
      integracao/imgIntegra/pdf16.png
  15. BIN
      integracao/imgIntegra/phpIco.png
  16. BIN
      integracao/imgIntegra/textoApi.png
  17. 139
      integracao/importaCampanha.php
  18. 76
      integracao/index.php
  19. 274
      integracao/infoAtende.php
  20. 68
      integracao/integracao.hmtl
  21. 140
      integracao/integracao.tpl
  22. 76
      integracao/ligueGratis.php
  23. 33
      integracao/liguemeGratis/liguemeGratis.php
  24. 20
      integracao/media/.gitignore
  25. 6
      integracao/media/.htaccess
  26. 29
      integracao/media/Dockerfile
  27. 232
      integracao/media/apache2.conf
  28. 385
      integracao/media/app/Controllers/AgentController.php
  29. 88
      integracao/media/app/Controllers/BilheteController.php
  30. 151
      integracao/media/app/Controllers/ClassificacaoController.php
  31. 45
      integracao/media/app/Controllers/ClientController.php
  32. 55
      integracao/media/app/Controllers/MessageController.php
  33. 173
      integracao/media/app/Controllers/QueueController.php
  34. 53
      integracao/media/app/Controllers/SupervisorQueueController.php
  35. 49
      integracao/media/app/Controllers/SystemMessageController.php
  36. 170
      integracao/media/app/Core/Commands.php
  37. 69
      integracao/media/app/Core/Connect.php
  38. 24
      integracao/media/app/Core/Controller.php
  39. 326
      integracao/media/app/Core/CoreMedia.php
  40. 120
      integracao/media/app/Core/Model.php
  41. 9
      integracao/media/app/Interfaces/IApi.php
  42. 29
      integracao/media/app/Interfaces/IApiMedia.php
  43. 743
      integracao/media/app/Middleware/ApiAgente.php
  44. 39
      integracao/media/app/Middleware/ApiInfo.php
  45. 129
      integracao/media/app/Middleware/ApiSupervisor.php
  46. 39
      integracao/media/app/Middleware/Http.php
  47. 155
      integracao/media/app/Middleware/Middleware.php
  48. 222
      integracao/media/app/Models/Agent.php
  49. 182
      integracao/media/app/Models/Atendimento.php
  50. 103
      integracao/media/app/Models/Bilhete.php
  51. 49
      integracao/media/app/Models/Classificacao.php
  52. 63
      integracao/media/app/Models/EventQueue.php
  53. 50
      integracao/media/app/Models/Evento.php
  54. 21
      integracao/media/app/Models/ListaNegraPalavras.php
  55. 85
      integracao/media/app/Models/Message.php
  56. 46
      integracao/media/app/Models/NotificaMedia.php
  57. 22
      integracao/media/app/Models/Parametros.php
  58. 112
      integracao/media/app/Models/Pause.php
  59. 29
      integracao/media/app/Models/Protocol.php
  60. 53
      integracao/media/app/Models/Queue.php
  61. 22
      integracao/media/app/Models/Ramal.php
  62. 408
      integracao/media/app/Models/SupervisorModel.php
  63. 26
      integracao/media/app/Models/SupervisorQueue.php
  64. 34
      integracao/media/app/Models/SystemMessage.php
  65. 527
      integracao/media/app/Providers/ApiTelegram.php
  66. 231
      integracao/media/app/Providers/ApiTwilio.php
  67. 78
      integracao/media/app/Providers/Crypt.php
  68. 177
      integracao/media/app/Providers/Logger.php
  69. 343
      integracao/media/app/Providers/Positus.php
  70. 103
      integracao/media/app/Providers/RequestURL.php
  71. 144
      integracao/media/app/Providers/Requests.php
  72. 259
      integracao/media/app/Providers/WebHeader.php
  73. 9
      integracao/media/app/Providers/whatsapp.php
  74. 9
      integracao/media/bd
  75. 146
      integracao/media/client.php
  76. 22
      integracao/media/composer.json
  77. BIN
      integracao/media/composer.phar
  78. 15
      integracao/media/config/agent.php
  79. 78
      integracao/media/config/app.php
  80. 15
      integracao/media/config/display_errors.php
  81. 23
      integracao/media/config/event.php
  82. 74
      integracao/media/config/helpers.php
  83. 32
      integracao/media/config/log.php
  84. 25
      integracao/media/config/middleware.php
  85. 18
      integracao/media/config/moments.php
  86. 60
      integracao/media/config/telegram.php
  87. 60
      integracao/media/config/whatsapp.php
  88. 282
      integracao/media/database/att-v2.sql
  89. 515
      integracao/media/database/att-v3.sql
  90. 45
      integracao/media/database/database.sql
  91. 21
      integracao/media/database/modelo_mensagem.json
  92. 17
      integracao/media/database/msg-text-positus.json
  93. 10
      integracao/media/docker-compose.yml
  94. 32
      integracao/media/docker/README
  95. 31
      integracao/media/docker/aplicativo/Dockerfile
  96. 16
      integracao/media/docker/asterisk/Dockerfile
  97. 96
      integracao/media/docker/asterisk/build-asterisk.sh
  98. 27
      integracao/media/docker/asterisk/docker-entrypoint.sh
  99. 15
      integracao/media/docker/asterisk/hooks/post_push
  100. 90
      integracao/media/docker/asterisk13/Dockerfile
  101. Some files were not shown because too many files have changed in this diff Show More

1106
include/funcoes/shared.php

File diff suppressed because it is too large Load Diff

198
include/util/constantes.php

@ -9,12 +9,73 @@ define('SS_OPERACAO_SUPERVISOR', "SSoperacaoSupervisor");
define("VERSAO_API", '1.0');
//
//Define status de atendimento para o agente
//
define("MAX_QUEBRA", 70); //Usada para formatar url em GetMetodos
define("AGENTE_EM_ATENDIMENTO", 'OCUPADO');
define("AGENTE_LIVRE", 'LIVRE');
define("AGENTE_EM_PAUSA", 'PAUSA');
define("AGENTE_LOGOFF", 'LOGOFF');
define("AGENTE_DISCANDO", 'ORIGINANDO');
define("MAX_TENTATIVA_RETORNO", 50);
//combo meses
$meses = array('Todos', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
$mesesAbr = array('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez');
$diasDaSemana = array('dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab');
//constantes para interagir com asterisk
define("AST_LOGIN_AGENTE", 1);
define("AST_LOGOFF_AGENTE", 2);
define("AST_ADD_FILA", 3); //Adiciona agente agente a fila
define("AST_REM_FILA", 4); //remove agente da fila
define("AST_ADD_PAUSA", 5); //colaca agente em pausa
define("AST_REM_PAUSA", 6); //retira o agente de pausa
define("AST_DISCAR", 7);
define("AST_TRANSFERIR", 8);
define("AST_INCLUI_AGENTE", 9);
define("AST_TESTE_URL", 10);
define("MONITOR_AGENTS", 11);
define("AST_INTERCALAR", 12);
define("AST_MONITORAR", 13);
define("AST_INICIA_GRAVACAO", 14);
define("AST_FINALISA_GRAVACAO", 15);
define("AST_INICIA_PAUSA_GRAVACAO", 16);
define("AST_FINALISA_PAUSA_GRAVACAO", 17);
define("AST_DESLIGAR_LIGACAO", 18);
define("AST_RELOAD_URA", 19);
define("AST_RELOAD_FILA", 20);
define("AST_MUTE_SET_VAR", 21);
define("AST_MUTE_ADD_CANAIS", 22);
define("AST_MUTE_GET_SALA_CONFERENCIA", 23);
define("AST_MUTE_ADD_AGENTE", 24);
define("AST_MUTE_REM_AGENTE", 25);
define("AST_PENDULO_SET_VAR", 26);
define("AST_PENDULO_ADD_CANAIS", 27);
define("AST_PENDULO_GET_SALA", 28);
define("AST_PENDULO_ADD_MUTE", 29);
define("AST_PENDULO_REM_MUTE", 30);
define("AST_TRCONSULTA_SET_VAR", 31);
define("AST_TRCONSULTA_ESPERA", 32);
define("AST_TRCONSULTA_TRANSFERE", 33);
define("AST_TRCONSULTA_TRANSFERE_ABORTA", 34);
define("AST_TRCONSULTA_LIBERA_AGENTE", 35);
define("AST_TRCONSULTA_CONFERENCIA", 36);
define("AST_DISCAR_DIRETO", 37);
define("AST_TRANSF_PESQUISA", 38);
define("AST_PENDULO_REM_CANAIS", 39);
define("AST_MUTE_CLIENTE", 40);
define("AST_MUTE_ATENDENTE", 41);
define("AST_REM_MUTE", 42);
define("AST_ALARME", 43);
define("AST_SET_VAR", 44);
define("AST_EXEC_AMI", 45);
define("AST_CALLBACK", 46);
define("AST_ALERTA_AGENTE", 47);
define("AST_SMS_SEND", 48);
define("AST_DESLIGAR_TODOS", 49);
define("AST_LIGUE_GRATIS", 50);
//Sess<EFBFBD>o para mute
@ -38,8 +99,25 @@ define("AGT_SUBID", "subIdCorrente");
define("AGT_ID_LOGIN", "idTabLogin");
define("AGT_ID_PAUSA", "idTabPausa");
//constates para secao do modulo de agente
//ramal do atendente
//conexao do agente com asterisk
define("AGT_CONECT", "AgenteOnLine");
define("AGT_ULT_EVENTO", "AgenteUltimoEvento");
define("AGT_DESCONECTA_SUPER", "AgenteDesconectaSuper");
//mode de atendimento
define("AGT_TP_ATEND", "TipoAtend");
define("AGT_TP_ATEND_COD", "ModoAtendimento");
define("AGT_MODU_MANUAL", '**50');
define("AGT_MODU_AUTOMATICO", '**60');
define("AGT_DAC_CONECT", "AgenteConctDac");
define("AGT_DAC_CONECT_DESC", "AgenteConctDacNome");
define("SS_NOME_DAC", "AgenteConctDacNome");
define("SS_AUT", "SSaut");
define("SS_USER_AUT", "SSuserAut");
define("AGT_MATRICULA", "SSmatriculaAgente");
/*
@ -52,6 +130,10 @@ define("AGT_RAMAL_CONF", "SSramalConf");
*/
define("AGT_RECEPTIVO_CALLBACK", "SSorigemCallback");
//pausa do agente
define("AGT_EM_PAUSA", "AgenteEmPausa");
define("AGT_PAUSA_MOTIVO", "MotivoPausa");
define("AGT_RELACIONA_EVENTO", "RelacionaEvento");
//Tempo de atuliza<EFBFBD><EFBFBD>o da tela de agente, se nao informado nos parametros
define("AGT_TEMPO_ATUALIZA", 5);
//CALL
@ -118,6 +200,29 @@ define("SS_DESTINO_INTERCALAR", "SSdestinoIntercalar");
define("SS_TIPO_FILA", "SS_tipoFilaLogin"); //
/*
* Valore usados para registrar ramais usados em monitoria e intercala<EFBFBD><EFBFBD>o de <EFBFBD>udios.
*/
define("SS_MONITOR_ALVO", "SSramalMonitorAlvo");
define("SS_MONITOR_ALVO_SIP", "SSramalMonitorAlvoSip");
define("RAMAL_MONITOR_AGENTE", "ramalMonitorAgente");
define("CANAL_MONITOR_AGENTE", "canalMonitorAgente");
define("RAMAL_MONITOR_AUDIO", "ramalMonitorAudio");
define("CANAL_MONITOR_AUDIO", "canalMonitorAudio");
define("RAMAL_MONITOR_SUPERVISOR", "ramalMonitorSupervisor");
define("CANAL_MONITOR_SUPERVISOR", "canalMonitorSupervisor");
//RELATORIO
define("REL_HEAD_NIVEL1", 1);
define("REL_HEAD_NIVEL2", 2);
define("REL_HEAD_NIVEL3", 3);
//base do c<EFBFBD>lculo para o desvio padr<EFBFBD>o
define("NUMERO_SEMANAS", 52);
define("SS_DESVIO_PADRAO", "desvioPadrao");
@ -200,7 +305,12 @@ define("DDD_EMPRESA", 65);
define("PATH_ABSOLUTO", 'SSabsPath');
define("PATH_BAR", 'SSbarPath');
//Relatorios
define("REL_TITULO_PAGE", "SSrelTituloPage");
define("REL_TITULO_HEAD", "SSrelTituloHead");
define("REL_COMPLEMENTO_FILTRO", "SSrelComplFiltro");
define("REL_HEAD", "SSrelHead");
define("REL_LINHAS_IMPRIME", "SSrelLinhasImprime");
define("TEMPO_TENTATIVA_URL", 300000);
define("MAX_TENTATIVA_URL", 5);
@ -214,7 +324,30 @@ define("CONF_PADRAO_URL_ASTERISK", 'url_asterisk');
define("COMP_SVN", 1);
//Define um codigo de acordo com o status do agente
define("AGT_STATUS_OFF", 0);
define("AGT_STATUS_PAUSA", 1);
define("AGT_STATUS_LIVRE", 2);
define("AGT_STATUS_CHAMANDO", 3);
define("AGT_STATUS_ORIGNANDO", 4);
define("AGT_STATUS_OCUPADO", 5);
//Indentificadores de formulario
define("REL_TOTALIZADOR_CENTRO_CUSTO", 159);
define("REL_SAINTES_RAMAL", 37);
define("REL_TOTALIZADOR_CHAMADAS", 41);
define("REL_SAINTES_CENTRO_CUSTO", 67);
define("REL_SAINTES_TIPO_LIGACAO", 70);
define("REL_SAINTES_MAIS_DISCADOS", 74);
define("REL_TOTALIZADOR_TIPO_LA", 87);
define("REL_CHAMADAS_ENCAMINHADAS_CAIXAPOSTAL", 76);
define("REL_ENTRANTES_NAO_ATENDIDA", 78);
define("REL_ENTRANTES_RAMAL", 59);
define("REL_ENTRANTES_TIPO_LIGACAO", 72);
define("REL_TOTALIZADOR_CHAMADAS_ENTRANTES", 63);
define("REL_CHAMADAS_RAMAL_RAMAL", 43);
define("REL_LISTA_SIGAME_EXTERNO", 80);
define("REL_LISTA_USUARIO", 65);
//AgenteRT
define("SS_DAC_CODIGO", "AgenteConctDac"); //Id do Dac conectado
@ -237,31 +370,18 @@ define("DEFAULT_MASC_PASSWORD", '****');
define("CONF_CRYPT_IV", '4928e5d91dea39d0755b110cad0abe45');
define("CONF_CRYPT_KEY", 'b4adfe9e896ad2791967382a55532148');
/*
* Conversao de arquivos, CNVRTD
* Tipos de ramal
*/
define("CNVRT_CONVERT_AUDIO", '/var/www/html/aplicativo/cnvrtd/cnvrtAudio.php'); // milhonesimo of second.
define("CNVRT_FILE", '/var/www/html/aplicativo/cnvrtd/cnvrtFile.php');
define("CNVRT_BASE", '/var/www/html/aplicativo/audio/');
define("CNVRT_TEMPO_CICLO", 100000); // milhonesimo of second.
define("CNVRT_TIMEOUT", 10); // Scond.
define("CNVRT_WAV_MP3", 1);
define("CNVRT_WAV_ULAW", 2);
define("CNVRT_MP3_ULAW", 3);
define("CNVRT_FILE_EXISTS", 4);
define("CNVRT_FILE_MV", 5);
define("CNVRT_FILE_RM", 6);
define("CNVRT_FILE_CP", 7);
define("CNVRT_FILE_TAR_GZ", 8);
define("CNVRT_FILE_TAR_BZ2", 9);
define("CNVRT_FILE_CMD", 10);
define("CNVRT_FILE_SIZE", 11);
define("CNVRT_EXEC", 12);
define("RAMAL_SIP", 'SIP');
define("RAMAL_IAX", 'IAX');
define("RAMAL_IAX2", 'IAX2');
define("RAMAL_PBX", 'PBX');
define("RAMAL_DGV", 'DGV');
define("RAMAL_KHOMP", 'KHOMP');
define("RAMAL_DAHDI", 'DAHDI');
define("ROTA_ENTRADA", 'E');
define("ROTA_SAIDA", 'S');
/*
* Perfil do sistema.
@ -299,7 +419,27 @@ define("MEDIA_PRINT_PDF", 3);
define("MEDIA_PRINT_EXCEL", 4);
define("MEDIA_PRINT_CSV", 5);
/*
* Conversao de arquivos, CNVRTD
*/
define("CNVRT_CONVERT_AUDIO", '/var/lib/asterisk/scripts/cnvrtd/cnvrtAudio.php'); // milhonesimo of second.
define("CNVRT_FILE", '/var/lib/asterisk/scripts/cnvrtd/cnvrtFile.php');
define("CNVRT_BASE", '/var/www/html/aplicativo/audio/');
define("CNVRT_TEMPO_CICLO", 100000); // milhonesimo of second.
define("CNVRT_TIMEOUT", 10); // Scond.
define("CNVRT_WAV_MP3", 1);
define("CNVRT_WAV_ULAW", 2);
define("CNVRT_MP3_ULAW", 3);
define("CNVRT_FILE_EXISTS", 4);
define("CNVRT_FILE_MV", 5);
define("CNVRT_FILE_RM", 6);
define("CNVRT_FILE_CP", 7);
define("CNVRT_FILE_TAR_GZ", 8);
define("CNVRT_FILE_TAR_BZ2", 9);
define("CNVRT_FILE_CMD", 10);
define("CNVRT_FILE_SIZE", 11);
define("CNVRT_EXEC", 12);
/*
* Servidor de central de Atualizacoes
@ -311,3 +451,11 @@ define('IP_CENTRAL_ATUALIZACAO', '192.168.115.12');
*/
define('MASCARA_PASSWORD', '*******');
/*
* Define o comportamento dos relatorios de servico.
*/
define("RELATORIO_SERVICOS_DESABILITA", 0);
define("RELATORIO_SERVICOS_HABILITA", 1);
define("RELATORIO_SERVICOS_FILTROS", 2);

2
include/util/display_errors.php

@ -1,7 +1,7 @@
<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('display_errors', 1);
ini_set("memory_limit", "512M");

952
include/util/funcoesAmi.php

@ -0,0 +1,952 @@
<?php
function ConectaAmi($host = '', $porta = '', $usuario = '', $senha = '', $events = 0) {
$host = $host ? trim($host) : '127.0.0.1';
$porta = $porta ? trim($porta) : '5038';
$usuario = $usuario ? trim($usuario) : 'manager';
$senha = $senha ? trim($senha) : 'manager007';
$errno = '';
$errstr = '';
$timeout = 10;
$socket = fsockopen($host, $porta, $errno, $errstr, $timeout);
if ($socket) {
$actionid = rand(000000000, 9999999999);
__fwrite($socket, "action: login\r\n", "ConectaAmi");
__fwrite($socket, "username: $usuario\r\n");
__fwrite($socket, "secret: $senha\r\n");
__fwrite($socket, sprintf("events: %s\r\n", $events ? "on" : "off"));
__fwrite($socket, "ActionID: " . $actionid . "\r\n\r\n");
$i = 0;
while (!feof($socket)) {
$bufer = fgets($socket);
if (stristr($bufer, "Authentication accepted")) {
return $socket;
} else if (stristr($bufer, "Authentication failed")) {
fclose($socket);
return false;
}
if ($i++ > MAX_TENTATIVA_RETORNO) {
return false;
}
}
}
return false;
}
function ExecutaAmi($socket, $params) {
$rand = rand(000000000, 9999999999);
$start = 0;
foreach ($params as $key => $value) {
__fwrite($socket, "$key: $value\r\n", ($start++ ? '' : 'ExecutaAmi'));
}
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'ExecutaAmi');
}
function LoginAgenteAmi($socket, $channel, $modoAtende, $ramal, $dac, $matricula, $penalidade) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'LoginAgenteAmi');
__fwrite($socket, "Channel: $channel\r\n");
__fwrite($socket, "context: app-login\r\n");
__fwrite($socket, "exten: $modoAtende\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "callerid: $ramal\r\n");
__fwrite($socket, "variable: DAC=$dac,AGENT=$matricula,RAMAL=$ramal,PENALIDADE=$penalidade\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'LoginAgenteAmi');
}
/* ASTERISK 1.4
function LogoffAgenteAmi($socket, $matricula)
{
$rand = rand(000000000,9999999999);
__fwrite($socket, "Action: agentlogoff\r\n", 'LogoffAgenteAmi');
__fwrite($socket, "agent: $matricula\r\n");
__fwrite($socket, "soft: false\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'LogoffAgenteAmi');
}
*/
function LogoffAgenteAmi($socket, $matricula, $ramal, $dac) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: agentlogoff\r\n", 'LogoffAgenteAmi');
__fwrite($socket, "agent: $matricula\r\n");
__fwrite($socket, "soft: false\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'LogoffAgenteAmi');
}
function AddFilaAmi($socket, $dac, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: queueadd\r\n", 'AddFilaAmi');
__fwrite($socket, "queue: $dac\r\n");
__fwrite($socket, "interface: Agent/$matricula\r\n");
__fwrite($socket, "penaly: 1\r\n");
__fwrite($socket, "paused: true\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'AddFilaAmi');
}
function RemFilaAmi($socket, $dac, $matricula, $ramal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: queueremove\r\n", 'LogoffAgenteAmi');
__fwrite($socket, "queue: $dac\r\n");
__fwrite($socket, "interface: Local/$ramal@app-callcenter/n\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'RemFilaAmi');
}
function AddPausaAmi($socket, $matricula, $ramal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: queuepause\r\n", 'AddPausaAmi');
// __fwrite($socket, "interface: Agent/$matricula\r\n");
__fwrite($socket, "interface: Local/$ramal@app-callcenter/n\r\n");
__fwrite($socket, "paused: true\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'AddPausaAmi');
return $ret;
}
function RemPausaAmi($socket, $matricula, $ramal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: queuepause\r\n", 'RemPausaAmi');
// __fwrite($socket, "interface: Agent/$matricula\r\n");
__fwrite($socket, "interface: Local/$ramal@app-callcenter/n\r\n");
__fwrite($socket, "paused: false\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'RemPausaAmi');
}
function DesligarAmi($socket, $channelAgente) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: hangup\r\n", 'DesligarAmi');
__fwrite($socket, "Channel: $channelAgente\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'DesligarAmi');
return $ret;
}
function DiscarCallAmi($socket, $channelAgente, $matricula, $numDisc, $ramal, $contextoRamal = "padrao", $codigo = null) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'DiscarCallAmi');
__fwrite($socket, "Channel: $channelAgente\r\n");
__fwrite($socket, "Context: $contextoRamal\r\n");
__fwrite($socket, "Exten: $numDisc\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "Callerid: $ramal\r\n");
//__fwrite($socket, "variable: MATRICULA=$matricula,TIPO-DISCAGEM=APLICACAO,CONTEXTORAMAL=$contextoRamal,PERMISSAO=OK\r\n");
if ($codigo) {
__fwrite($socket, "variable: RAMAL=$ramal,CONTEXTORAMAL=$contextoRamal,TIPODISCAGEM=AGENTE,CODIGOPARAM=$codigo\r\n");
} else {
__fwrite($socket, "variable: RAMAL=$ramal,CONTEXTORAMAL=$contextoRamal,TIPODISCAGEM=AGENTE\r\n");
}
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'DiscarCallAmi');
}
function DiscarDiretoAmi($socket, $channel, $numDisc, $ramal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'DiscarDiretoAmi');
__fwrite($socket, "Channel: $channel\r\n"); //Ramal local sip/1001
__fwrite($socket, "Context: padrao\r\n");
__fwrite($socket, "Exten: $numDisc\r\n"); //numero a discar
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "Callerid: $ramal\r\n"); //Ramal local 1001
__fwrite($socket, "Timeout: 30000\r\n");
__fwrite($socket, "Variable: TIPO-DISCAGEM=APLICACAO,PERMISSAO=OK\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'DiscarDiretoAmi');
}
function AlarmeAmi($socket, $channel, $numDisc, $ramal, $audio = 'appsounds/alarmeapi') {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'AlarmeAmi');
__fwrite($socket, "Channel: Local/$numDisc@padrao\r\n"); //Ramal local sip/1001
__fwrite($socket, "Application: Playback\r\n");
__fwrite($socket, "Data: $audio\r\n");
__fwrite($socket, "Context: default\r\n");
__fwrite($socket, "Exten: s\r\n"); //numero a discar
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "Callerid: $ramal\r\n"); //Ramal local 1001
__fwrite($socket, "Timeout: 30000\r\n");
__fwrite($socket, "Variable: TIPO-DISCAGEM=APLICACAO,PERMISSAO=OK\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'AlarmeAmi');
}
function CallbackAmi($socket, $destino, $numDisc, $ramal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'CallbackAmi');
__fwrite($socket, "Channel: Local/$numDisc@padrao\r\n"); //Nro a discar
__fwrite($socket, "Context: padrao\r\n");
__fwrite($socket, "Exten: $destino\r\n"); // ( fila )
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "Callerid: $numDisc\r\n"); //Ramal local 1001
__fwrite($socket, "Timeout: 30000\r\n");
__fwrite($socket, "Variable: RAMAL=$ramal\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'CallbackAmi');
}
function LigueGratisAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'CallbackAmi');
__fwrite($socket, sprintf("Channel: Local/%s@padrao\r\n", GetNumeroLigueGratis())); //Nro a discar
__fwrite($socket, "Context: ext-anuncios\r\n");
__fwrite($socket, sprintf("Exten: %s\r\n", GetAnuncioLigueGratis())); // ( fila )
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, sprintf("Callerid: %s\r\n", GetNumeroLigueGratis())); //Ramal local 1001
__fwrite($socket, "Timeout: 30000\r\n");
__fwrite($socket, sprintf("Variable: RAMAL=%s,LIGUE-ME=%s\r\n", GetRamalLigueGratis(), GetNumeroLigueGratis()));
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'CallbackAmi');
}
function TransferirAmi($socket, $channelTransf, $numDisc) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: redirect\r\n", 'TransferirAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "Context: ext-transferencia\r\n");
__fwrite($socket, "Exten: $numDisc\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TransferirAmi');
}
function TransferirPesquisaAmi($socket, $channelTransf, $idPesqisa, $matricula = '') {
if ($matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Setvar\r\n", 'SetVarPesquisa');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "variable: PESQUISA_MATRICULA\r\n");
__fwrite($socket, "value: $matricula\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
VerificaRetornoSocket($socket, "Success", "Error", 'SetVarPesquisa');
}
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: redirect\r\n", 'TransferirPesquisaAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "Context: $idPesqisa\r\n");
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TransferirPesquisaAmi');
}
function IncluiAgenteAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: command\r\n", 'IncluiAgenteAmi');
__fwrite($socket, "command: module reload app_agent_pool.so\r\n");
__fwrite($socket, "Context: ext-transferencia\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'IncluiAgenteAmi');
}
function TesteUrlAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: ping\r\n", 'TesteUrlAmi');
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "pong", "Error", 'TesteUrlAmi');
}
function MonitorAgentsAmi() {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action:agents\r\n", 'MonitorAgentsAmi');
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'MonitorAgentsAmi');
}
function IntercalarAmi($socket, $canalIntercalar, $ramalIntercalar, $rmalDestinoIntercalar) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'IntercalarAmi');
__fwrite($socket, "Channel: $canalIntercalar\r\n");
__fwrite($socket, "Context: call-intercala\r\n");
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "CallerID: $ramalIntercalar\r\n");
__fwrite($socket, "variable: RAMAL=$ramalIntercalar,DESTINO=$rmalDestinoIntercalar\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'IntercalarAmi');
return $ret;
}
//function MonitorarAmi($socket, $canalIntercalar, $ramalIntercalar, $rmalDestinoIntercalar)
function MonitorarAmi($socket, $params) {
//
// Chaves array params:
// "matricula_supervisor", "matricula_monitorado", "dac_monitorado", "setido_chamada", "nivel_lgpd_supevisor", "nivel_lgpd_monitorado", "uniqueid_monitorado",
// "ramal_supervisor", "ramal_monitorado", "canal_monitorado", "canal_agente", "canal_supervisor" , "ramal_supervisor"
//
$rand = rand(000000000, 9999999999);
$varLgpd = $params["var_lgpd"];
if ((int)$varLgpd === 0) {
$canalIntercalar = $params['canal_supervisor'];
$ramalIntercalar = $params['ramal_supervisor'];
$rmalDestinoIntercalar = $params['ramal_monitorado'];
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'MonitorarAmi');
__fwrite($socket, "Channel: $canalIntercalar\r\n");
__fwrite($socket, "Context: call-monitora\r\n");
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "CallerID: $ramalIntercalar\r\n");
__fwrite($socket, "variable: RAMAL=$ramalIntercalar,DESTINO=$rmalDestinoIntercalar,LGPD_VAR=0\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'MonitorarAmi');
return $ret;
}
$sentidoChamada = (strtoupper($params['setido_chamada']) == 'E' ? 'recebida' : 'originada' );
$canalAgente = ($params['setido_chamada'] == 'E') ? $params['canal_monitorado'] : $params['canal_agente'];
$paramLgpd = GetParamLgpd($varLgpd);
$paramLgpdContent = $paramLgpd['lgpdm_content'];
$nvSuper = isset($paramLgpdContent['nivel_lgpd_supevisor']) ? $paramLgpdContent['nivel_lgpd_supevisor'] : 0;
$nvMonitorado = isset($paramLgpdContent['nivel_lgpd_monitorado']) ? $paramLgpdContent['nivel_lgpd_monitorado'] : 0;
$permiteSupervisao = $nvSuper > 0 ? 'SIM' : 'NAO';
$enviaAviso = ($nvSuper >= $nvMonitorado) ? 'SIM' : 'NAO';
__fwrite($socket, "Action: originate\r\n", 'MonitorarAmi');
__fwrite($socket, sprintf("Channel: %s\r\n", $params['canal_supervisor']));
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Context: call-intercala-lgpd-verifica\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, sprintf("CallerID: %s\r\n", $params['ramal_supervisor']));
//__fwrite($socket, sprintf("variable: RAMAL=%s|DESTINO=%s|LGPD_VAR=%s\r\n", $params['ramal_supervisor'], $params['ramal_monitorado'], $varLgpd));
__fwrite($socket, sprintf("Variable: RAMAL_AGENTE=%s,CANAL_AGENTE=%s,LGPD=%s,FEATURES=%s,ENVIA_AVISO_MONITORADO=%s,LGPD_VAR=%s\r\n", $params['ramal_monitorado'], $canalAgente, $permiteSupervisao, $sentidoChamada, $enviaAviso, $varLgpd));
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'MonitorarAmi');
return $ret;
/*
;CHAMADA ORIGINADA - UTILIZAR O CANAL DO AGENTE (campo: canal_agente da pbx_supervisor_agentes)
Action: Originate
Channel: SIP/8517
Exten: s
Context: call-intercala-lgpd-verifica
Priority: 1
Callerid: 8517
Variable: RAMAL_AGENTE=8511|CANAL_AGENTE=SIP/8511-000000a3|LGPD=SIM|FEATURES=originada
;CHAMADA RECEBIDA - UTILIZAR O CANAL DO CLIENTE (campo: canal da pbx_supervisor_agentes)
Action: Originate
Channel: SIP/8517 ;ramal intercala - supervisor
Exten: s
Context: call-intercala-lgpd-verifica
Priority: 1
Callerid: 8517 ; ramal intercala - supervisor
Variable: RAMAL_AGENTE=8515|CANAL_AGENTE=SIP/LINHA_E1-00000098|LGPD=SIM|FEATURES=recebida
*/
}
function __MonitorarAmi($socket, $canalIntercalar, $ramalIntercalar, $rmalDestinoIntercalar) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'MonitorarAmi');
__fwrite($socket, "Channel: $canalIntercalar\r\n");
__fwrite($socket, "Context: call-monitora\r\n");
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "CallerID: $ramalIntercalar\r\n");
__fwrite($socket, "variable: RAMAL=$ramalIntercalar|DESTINO=$rmalDestinoIntercalar\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'MonitorarAmi');
return $ret;
}
function ReloadUraAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: command\r\n", 'ReloadUraAmi');
__fwrite($socket, "command: dialplan reload\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'ReloadUraAmi');
return $ret;
}
function ReloadFilaAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: command\r\n", 'ReloadFilaAmi');
__fwrite($socket, "command: module reload app_queue.so\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'ReloadFilaAmi');
}
function IniciaGravacaoAmi($socket, $channelTransf, $fileAudio, $fileAudioTipo) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: monitor\r\n", 'IniciaGravacaoAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "file: $fileAudio\r\n");
__fwrite($socket, "format: $fileAudioTipo\r\n");
__fwrite($socket, "mix: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'IniciaGravacaoAmi');
}
function FinalizaGravacaoAmi($socket, $channelTransf) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: stopmonitor\r\n", 'FinalizaGravacaoAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'FinalizaGravacaoAmi');
}
function IniciaPausaGravacaoAmi($socket, $channelTransf) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: pausemonitor\r\n", 'IniciaPausaGravacaoAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'IniciaPausaGravacaoAmi');
}
function FinalizaPausaGravacaoAmi($socket, $channelTransf) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: unpausemonitor\r\n", 'FinalizaPausaGravacaoAmi');
__fwrite($socket, "Channel: $channelTransf\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'FinalizaPausaGravacaoAmi');
}
function MuteSetVarAmi($socket, $channelAgente) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Setvar\r\n", 'MuteSetVarAmi');
__fwrite($socket, "Channel: $channelAgente\r\n");
__fwrite($socket, "variable: MUTE\r\n");
__fwrite($socket, "value: V\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'MuteSetVarAmi');
}
function MuteAddCanaisAmi($socket, $ramal, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'MuteAddCanaisAmi');
__fwrite($socket, "Channel: Local/s@app-atende\r\n");
__fwrite($socket, "context: app-mute\r\n");
__fwrite($socket, "exten: s\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "variable: RAMAL=$ramal,AGENTE=$matricula\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'MuteAddCanaisAmi');
}
function MuteAddAgenteAmi($socket, $salaConferencia) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: meetmemute\r\n", 'MuteAddAgenteAmi');
__fwrite($socket, "meetme: $salaConferencia\r\n");
__fwrite($socket, "usernum: 2\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'MuteAddAgenteAmi');
}
function MuteRemAgenteAmi($socket, $salaConferencia) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: meetmeunmute\r\n", 'MuteRemAgenteAmi');
__fwrite($socket, "meetme: $salaConferencia\r\n");
__fwrite($socket, "usernum: 2\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'MuteRemAgenteAmi');
}
function PenduloSetVarAmi($socket, $channelAgente) {
return true;
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Setvar\r\n", 'PenduloSetVarAmi');
__fwrite($socket, "channel: $channelAgente\r\n");
__fwrite($socket, "variable: ESPERA\r\n");
__fwrite($socket, "value: V\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'PenduloSetVarAmi');
}
//function PenduloAddCanaisAmi($socket, $ramal, $matricula, $channelTransf, $numDisc, $channelAgente, $automatico = false) {
// $rand = rand(000000000, 9999999999);
// __fwrite($socket, "Action: redirect\r\n", 'PenduloAddCanaisAmi');
// __fwrite($socket, "channel: $channelTransf\r\n");
// if (!$automatico) {
// __fwrite($socket, "extrachannel: $channelAgente\r\n");
// }
// __fwrite($socket, "context: app-espera\r\n");
// __fwrite($socket, "exten: $matricula$numDisc\r\n");
// __fwrite($socket, "priority: 1\r\n");
// __fwrite($socket, "ActionID: $rand\r\n\r\n");
// $ret = VerificaRetornoSocket($socket, "Success", "Error", 'PenduloAddCanaisAmi');
// return $ret;
//}
function PenduloAddCanaisAmi($socket, $ramal, $matricula, $channelTransf, $numDisc, $channelAgente, $automatico = false) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Atxfer\r\n", 'PenduloAddCanaisAmi');
__fwrite($socket, "channel: $channelAgente\r\n");
__fwrite($socket, "context: app-consulta\r\n");
__fwrite($socket, "exten: $numDisc\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'PenduloAddCanaisAmi');
return $ret;
}
function PenduloRemCanaisAmi($socket, $ramal, $matricula, $channelTransf) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: redirect\r\n", 'PenduloRemCanaisAmi');
__fwrite($socket, "channel: $channelTransf\r\n");
__fwrite($socket, "context: app-atendentes\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'PenduloRemCanaisAmi');
}
function PenduloAddMuteAmi($socket, $channelMute, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'PenduloAddMuteAmi');
__fwrite($socket, "channel: $channelMute\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "context: ext-app-espera\r\n");
__fwrite($socket, "priority: agente\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'PenduloAddMuteAmi');
}
function PenduloRemMuteAmi($socket, $channelMute, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'PenduloRemMuteAmi');
__fwrite($socket, "channel: $channelMute\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "context: ext-app-espera\r\n");
__fwrite($socket, "priority: cliente\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'PenduloRemMuteAmi');
}
function TrConsultaSetVarAmi($socket, $channelAgente) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Setvar\r\n", 'TrConsultaSetVarAmi');
__fwrite($socket, "channel: $channelAgente\r\n");
__fwrite($socket, "variable: TRANSFER\r\n");
__fwrite($socket, "value: V\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaSetVarAmi');
}
function TrConsultaEsperaAmi($socket, $ramal, $matricula, $numDisc, $contextoRamal) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'TrConsultaEsperaAmi');
__fwrite($socket, "channel: Local/$ramal@app-callcenter/n\r\n");
__fwrite($socket, "context: app-transfere\r\n");
__fwrite($socket, "exten: $matricula$numDisc\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "callerid: $ramal\r\n");
__fwrite($socket, "variable: CONSULTA=OK\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaEsperaAmi');
return $ret;
}
function TrConsultaTransfereAmi($socket, $channelTransfConsulta, $matricula, $channelAgente) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'TrConsultaTransfereAmi');
__fwrite($socket, "channel: $channelTransfConsulta\r\n");
__fwrite($socket, "context: app-transfere\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "priority: transfere\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaTransfereAmi');
return $ret;
}
//function TrConsultaTransfereAbortaAmi($socket, $channelAgente, $matricula) {
// $rand = rand(000000000, 9999999999);
// __fwrite($socket, "Action: Redirect\r\n", 'TrConsultaTransfereAbortaAmi');
// __fwrite($socket, "channel: $channelAgente\r\n");
// __fwrite($socket, "context: app-transfere\r\n");
// __fwrite($socket, "exten: $matricula\r\n");
// __fwrite($socket, "priority: transfere\r\n");
// __fwrite($socket, "ActionID: $rand\r\n\r\n");
// $ret = VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaTransfereAbortaAmi');
// return $ret;
//}
function TrConsultaTransfereAbortaAmi($socket, $channelAgente, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: CancelAtxfer\r\n", 'TrConsultaTransfereAbortaAmi');
__fwrite($socket, "channel: $channelAgente\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaTransfereAbortaAmi');
return $ret;
}
function TrConsultaLiberaAgenteAmi($socket, $channelTransf) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'TrConsultaLiberaAgenteAmi');
__fwrite($socket, "channel: $channelTransf\r\n");
__fwrite($socket, "exten: transfer\r\n");
__fwrite($socket, "context: ext-app-transfer\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaLiberaAgenteAmi');
}
function TrConsultaConferenciaAmi($socket, $channelTransfConsulta, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'TrConsultaConferenciaAmi');
__fwrite($socket, "channel: $channelTransfConsulta\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "context: ext-app-transfer\r\n");
__fwrite($socket, "priority: conferencia\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrConsultaConferenciaAmi');
}
function SetVarAmi($socket, $channelTransf, $ramal, $channelAgente, $matricula) {
// $rand = rand(000000000, 9999999999);
// __fwrite($socket, "Action: Setvar\r\n", 'SetVarAmi');
// __fwrite($socket, "channel: $channelTransf\r\n");
// __fwrite($socket, "variable: CONSULTANDO\r\n");
// __fwrite($socket, "value: SIM\r\n");
// __fwrite($socket, "ActionID: $rand\r\n\r\n");
// $ret = VerificaRetornoSocket($socket, "Success", "Error", 'SetVarAmi-1');
// $ret = ($ret == "ok");
// if ($ret) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Setvar\r\n");
__fwrite($socket, "channel: $channelTransf\r\n");
__fwrite($socket, "variable: CALLERID(NUM)\r\n");
__fwrite($socket, "value: $ramal\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
// $ret = VerificaRetornoSocket($socket, "Success", "Error", 'SetVarAmi-2');
// }
//
// if ($ret) {
// $rand = rand(000000000, 9999999999);
// __fwrite($socket, "Action: Setvar\r\n", 'SetVarAmi');
// __fwrite($socket, "channel: $channelAgente\r\n");
// __fwrite($socket, "variable: MATRICULA-DESTINO\r\n");
// __fwrite($socket, "value: $matricula\r\n");
// __fwrite($socket, "ActionID: $rand\r\n\r\n");
// $ret = VerificaRetornoSocket($socket, "Success", "Error", 'SetVarAmi-2');
// }
return $ret;
}
function ExecutaAgtAmi($socket, $cmdAmi) {
$rand = rand(000000000, 9999999999);
$var = '';
$start = 0;
foreach ($cmdAmi as $value) {
$var = trim($value);
$var = "$var\r\n";
__fwrite($socket, $var, ($start++ ? '' : 'ExecutaAgtAmi'));
}
__fwrite($socket, "ActionID: $rand\r\n\r\n");
$ret = VerificaRetornoSocket($socket, "Success", "Error", 'ExecutaAgtAmi');
return $ret;
}
function TrMuteClienteAmi($socket, $channelTransf, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'TrMuteClienteAmi');
__fwrite($socket, "channel: $channelTransf\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "context: app-mute\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrMuteClienteAmi');
}
function AlertaAgtAmi($socket, $channel, $ramalLogado, $audio = 'appsounds/chamada_nao_classificada') {
/*
* Se atendimento manual use channel do ramal do agente(SIP/8285), atumatico
* use o canal do agente(Agent/1000).
*/
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Originate\r\n", 'AlertaAgtAmi');
__fwrite($socket, "channel: $channel\r\n");
__fwrite($socket, "Application: Playback\r\n");
__fwrite($socket, "Data: $audio\r\n");
__fwrite($socket, "Callerid: $ramalLogado\r\n");
__fwrite($socket, "Variable: AVISO=OK\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'AlertaAgtAmi');
}
function TrMuteAtendenteAmi($socket, $ramal, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: originate\r\n", 'TrMuteAtendenteAmi');
__fwrite($socket, "channel: Agent/$matricula\r\n");
__fwrite($socket, "context: app-mute\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "priority: sala\r\n");
__fwrite($socket, "callerid: $ramal\r\n");
__fwrite($socket, "variable: MATRICULA=$matricula,OPTS=m\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrMuteAtendenteAmi');
}
function TrRemMuteAmi($socket, $channelTransf, $matricula) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "Action: Redirect\r\n", 'TrRemMuteAmi');
__fwrite($socket, "channel: $channelTransf\r\n");
__fwrite($socket, "exten: $matricula\r\n");
__fwrite($socket, "context: app-atendentes\r\n");
__fwrite($socket, "priority: 1\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'TrRemMuteAmi');
}
function VerificaRetornoSocket($socket, $sucess, $erro, $function = '') {
__fwrite(null, '', "VerificaRetornoSocket: $function", true);
$i = 0;
while (!feof($socket)) {
$bufer = trim(@fgets($socket));
/*
* Envia para o log.
*/
if ($bufer) {
__fwrite(null, $bufer . "\n", '', true);
}
if (stristr($bufer, $sucess)) {
return "ok";
} else if (stristr($bufer, $erro)) {
return 'Error';
} else if (stristr($bufer, "--END COMMAND--")) {
return "ok";
}
if ($i++ > MAX_TENTATIVA_RETORNO)
break;
}
return 'Error';
}
function AnalisaRetornoSocket($socket) {
$i = 0;
while (!feof($socket)) {
$bufer = @fgets($socket);
echo $bufer;
flush();
$i++;
}
}
function DesconectaAmi($socket) {
$rand = rand(000000000, 9999999999);
__fwrite($socket, "action: logoff\r\n", 'DesconectaAmi');
__fwrite($socket, "ActionID: $rand\r\n\r\n");
fclose($socket);
}
function InfoRamalAmi($socket, $ramal) {
$infoRamal = array('direcao' => '', 'status' => 'LIVRE', 'duracao' => '00:00:00', 'numero' => '');
$params = array('action' => 'command', 'command' => 'core show channels verbose');
$result = GetAmi($socket, $params);
$map = array('channel' => array(0, 21), 'context' => array(21, 21), 'extension' => array(42, 17), 'prio' => array(59, 5), 'state' => array(64, 8), 'application' => array(72, 13), 'data' => array(85, 26), 'callerid' => array(111, 16), 'duration' => array(127, 9), 'accountcode' => array(136, 12), 'bridgedto' => array(148, 16));
$linhas = array();
$start = 0;
foreach ($result as $line) {
if ($start) {
if (stripos($line, "active channels") !== false) {
break;
}
$linha = array();
foreach ($map as $key => $pos) {
$linha[$key] = trim(substr($line, $pos[0], $pos[1]));
}
$linhas[] = $linha;
}
$start = $start || ((stripos($line, "Channel") !== false) && (stripos($line, "Extension") !== false));
}
if (!count($linhas)) {
return $infoRamal;
}
$info = false;
$ocupado = false;
/*
* Identificando o ramal;
*/
foreach ($linhas as $linha) {
if ($ramal == $linha['callerid']) {
$status = strtoupper(trim($linha['state']));
$infoRamal['direcao'] = $linha['application'] == 'Dial' ? 'S' : 'E';
$infoRamal['status'] = $status == 'UP' ? 'OCUPADO' : 'CHAMANDO';
$infoRamal['duracao'] = $linha['duration'];
$infoRamal['ponte'] = $linha['bridgedto'];
$infoRamal['dados'] = $linha['data'];
$ocupado = $status == 'UP';
$info = true;
break;
}
}
/*
* Ramal não esta setado retorna default;
*/
if ($info === false) {
return $infoRamal;
}
/*
* Identificando o ramal;
*/
foreach ($linhas as $linha) {
/*
* Informacoes do ramal
*/
$entrada = $infoRamal['direcao'] == 'E';
$ponte = trim($infoRamal['ponte']);
$dataRamal = trim($infoRamal['dados']);
/*
* Informações do canal corrente;
*/
$canal = trim($linha['channel']);
$data = trim($linha['data']);
$numero = trim($linha['callerid']);
if ($ocupado && ($ponte == $canal)) {
$infoRamal['numero'] = $numero;
break;
} else if (!$entrada && (strpos($dataRamal, $numero) !== false)) {
$infoRamal['numero'] = $numero;
} else if ($entrada && (strpos($data, $ramal) !== false)) {
$infoRamal['numero'] = $numero;
}
}
return array_slice($infoRamal, 0, 4, true);
}
function EnviaSmsAmi($socket, $channel, $destino, $texto) {
/*
Action: Originate
Channel: Local/100@app-envia-sms
Async: true
Variable: SMS_TRONCO_ENVIO=b1c0|SMS_DESTINO=6599893984|SMS_MENSAGEM=TESTE API SIMPLES IP SMS|SMS_SIP_ID=09876
ActionID:09876
*/
//$rand = rand(000000000,9999999999);
$rand = time();
$GLOBALS["SSrand"] = $rand;
__fwrite($socket, "Action: Originate\r\n", 'EnviaSmsAmi');
__fwrite($socket, "Channel: Local/100@app-envia-sms\r\n");
__fwrite($socket, "Exten: s\r\n");
__fwrite($socket, "Context: app-atende-sms\r\n");
__fwrite($socket, "Priority: 1\r\n");
__fwrite($socket, "Timeout: 60000\r\n");
__fwrite($socket, "Variable: SMS_TRONCO_ENVIO=$channel,SMS_DESTINO=$destino,SMS_MENSAGEM=$texto,SMS_SIP_ID=$rand\r\n");
__fwrite($socket, "ActionID: $rand\r\n\r\n");
return VerificaRetornoSocket($socket, "Success", "Error", 'EnviaSmsAmi');
}
function GetAmi($socket, $params, $end = '--END COMMAND--') {
$rand = rand(000000000, 9999999999);
$start = 0;
$write = 0;
foreach ($params as $key => $value) {
$write = fwrite($socket, "$key: $value\r\n");
if (!$write)
return false;
}
fwrite($socket, "ActionID: $rand\r\n\r\n");
if (!$write)
return false;
$result = array();
while (!feof($socket)) {
$line = trim(fgets($socket));
if ($line)
$result[] = $line;
if (stripos($line, $end) !== false)
break;
}
return $result;
}
function __fwrite($socket, $value, $function = '', $logOnly = false) {
global $debugAmi, $errorMode;
if (!$logOnly) {
$wSck = fwrite($socket, $value);
if ($errorMode && !$wSck) {
GeraExcept("Não foi possível gravar no socket!");
}
}
if ($debugAmi) {
$login = "anonimo";
if (function_exists('IsUserConnect')) {
$login = IsUserConnect() ? $_SESSION["SSlogin"] : "anonimo";
}
$path = "/var/log/asterisk/log_ami_$login.log";
if ($function) {
GravaLog(sprintf("\n[%s-%s]\n", $function, date('Y-m-d H:i:s')), $path);
}
if ($value) {
GravaLog($value, $path);
}
}
}
function DesligaTodasAmi($socket, $ramal) {
$params = array('action' => 'command', 'command' => 'core show channels verbose');
$result = GetAmi($socket, $params);
// $map = array('channel' => array(0,21),'context' => array(21,21),'extension' => array(42,17),'prio' => array(59,5),'state' => array(64,8),'application' => array(72,13),'data' => array(85,26),'callerid' => array(111,16),'duration' => array(127,9),'accountcode' => array(136,12),'bridgedto' => array(148,16));
$map = array('channel' => array(0, 21), 'context' => array(21, 21));
$linhas = array();
$start = 0;
foreach ($result as $line) {
if ($start) {
/*
* Active channels indica o final do arquivo.
*/
if (stripos($line, "active channels") !== false) {
break;
}
$linha = array();
foreach ($map as $key => $pos) {
$linha[$key] = trim(substr($line, $pos[0], $pos[1]));
}
/*
* Verifica se o contexto é de monitoria ou itercalação.
*/
$context = trim($linha['context']);
if ((stripos($context, 'call-monitora') !== false) || (stripos($context, 'call-intercala') !== false)) {
/*
* Se o channel corresponder ao ramal
*/
$channel = trim($linha['channel']);
if (stripos($channel, $ramal) !== false) {
DesligarAmi($socket, $channel);
}
}
}
/*
* Identifica a linha de cabeçalio, após esta linha deve començar a ler os dados,
* start é modificado para true.
*/
$start = $start || ((stripos($line, "Channel") !== false) && (stripos($line, "Extension") !== false));
}
}
?>

100
integracao/bdApi.php

@ -0,0 +1,100 @@
<?php
//conecta ao banco de dados
$dbcon = @pg_connect(GetConectString());
$_SESSION["Db_conf_ok"] = "0";
function GetConectString() {
if (!$_SESSION["Db_conf_ok"]) {
include_once "configBd.php";
//$ini = parse_ini_file($dir . "configs" . $bar . "db.ini", true);
}
$dbPort = $_SESSION["Db_conf_ok"] ? $_SESSION["dbPort"] : $dbPort;
$dbHost = $_SESSION["Db_conf_ok"] ? $_SESSION["dbHost"] : $dbHost;
$dbName = $_SESSION["Db_conf_ok"] ? $_SESSION["dbName"] : $dbName;
$dbUser = $_SESSION["Db_conf_ok"] ? $_SESSION["dbUser"] : $dbUser;
$dbPassword = $_SESSION["Db_conf_ok"] ? $_SESSION["dbPassword"] : $dbPassword;
$_SESSION["dbPort"] = $dbPort;
$_SESSION["dbHost"] = $dbHost;
$_SESSION["dbName"] = $dbName;
$_SESSION["dbUser"] = $dbUser;
$_SESSION["dbPassword"] = $dbPassword;
//$_SESSION["Db_conf_ok"] = "1";
return "host='$dbHost' port='$dbPort' dbname='$dbName' user='$dbUser' password='$dbPassword'";
}
function GetAvisoErroDB() {
$_SESSION["Db_conf_ok"] = "0";
return "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">
<html>
<head>
<title>Simples IP</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">
<style type=\"text/css\">
<!--
.style1 {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
font-weight: bold;
color: #CC0033;
}
.style2 {
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
}
body {
background-color: #CCCCCC;
}
-->
</style>
</head>
<body>
<table width=\"60%\" style=\"border: 2px solid #CC0033;\" border=\"0\" align=\"center\" cellpadding=\"2\" cellspacing=\"0\" bordercolor=\"#FFFFFF\" bgcolor=\"#FFFFFF\">
<tr>
<td><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"10\">
<tr>
<td align=\"left\"><img src=\"".LOGO_HEADER_SITE."\" width=\"160\" height=\"69\"></td>
</tr>
<tr align=\"center\">
<td nowrap><span class=\"style1\"> N&atilde;o foi poss&iacute;vel estabelecer uma conex&atilde;o com o banco de dados! </span></td>
</tr>
<tr>
<td align=\"center\" class=\"style1\">Se o problema persistir entre em contado com o suporte t&eacute;cnico </td>
</tr>
<tr align=\"center\">
<td><a href=\"index.php\" class=\"style2\">Tentar Novamente </a></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
";
}
function SetAbsPath() {
if (!$_SESSION["SSaut"]) {
$bar = (strtoupper(substr(PHP_OS, 0, 3)) == "WIN") && (trim(getenv("OS")) != '') ? "\\" : "/";
$path = GetPathApi(dirname(__FILE__), $bar);
$_SESSION[PATH_BAR] = $bar;
$_SESSION[PATH_ABSOLUTO] = substr($path, -1) != $bar ? $path . $bar : $path;
}
}
function GetPathApi($path, $bar) {
$dirs = explode($bar, $path);
$numDir = count($dirs);
$newPath = '';
for ($i = 0; $i < ($numDir - 1); $i++)
$newPath .= $dirs[$i] . $bar;
return $newPath;
}
?>

BIN
integracao/download/layouteBaseDiscador.pdf

Binary file not shown.

76
integracao/enviaCampanha.html

@ -0,0 +1,76 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Texte envio Campanha</title>
</head>
<body>
<form action="http://127.0.0.1/integracao/index.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<!-- <form action="http://10.254.253.63/simplesip/integracao/index.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> -->
<table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td>
<input type="hidden" name="method" value="EnviarDadosCampanha"/>
<input type="hidden" name="login" value="admin"/>
<input type="hidden" name="senha" value="OitoDois80_SiP"/>
<input type="hidden" name="tipoRetorno" value="XML"/>
</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Arquivo:</td>
<td>
<input type="file" name="arquivoCampanha" id="arquivoCampanha" />
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>
<input type="submit" name="button" id="button" value="Submit" />
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>

6700
integracao/funcoesApi.php

File diff suppressed because it is too large Load Diff

97
integracao/funcoesCustom.php

@ -0,0 +1,97 @@
<?php
// *************************************************************************
// * Funcoes de customizacao de protocolo VENDA *
// * Lucas Awade *
// * 24/06/2019 *
// * *
// * Descricao: Este script foi criado para desenvolver funcoes para valida*
// * cao dos protocolos de modulo de venda. Com a presenca de clientes soli*
// * citantes foi iniciado o desenvolvimento, cada funcao é destinado a um *
// * cliente diferente de acordo com sua operacao! *
// *************************************************************************
/*
* CADASTRA AS FUNCOES PARA SER APRESENTADAS NAS CONFIGURACOES
*/
$_SESSION['SSValidaFuncoesProtocolo'] = array(
"ValidaProtocoloAlgar",
"ValidaTamanhoProtocolo",
"ValidaProtocoloClickTelecom",
"ValidaProtocoloSevenProtecao"
);
function ___GetValidacaoProtocolo($protocolo, $validacao) {
$resp = ___GetValidaFuncao($validacao);
if (!$resp) {
$validacao = "ValidaTamanhoProtocolo";
}
switch ($validacao) {
case "ValidaProtocoloAlgar" :
return ValidaProtocoloAlgar($protocolo);
case "ValidaTamanhoProtocolo" :
return ValidaTamanhoProtocolo($protocolo);
case "ValidaProtocoloClickTelecom" :
return ValidaProtocoloClickTelecom($protocolo);
case "ValidaProtocoloSevenProtecao" :
return ValidaProtocoloSevenProtecao($protocolo);
}
}
function ValidaProtocoloAlgar($protocolo, $silent = false) {
$ano = date('Y');
$at = strtotime("+90days $ano-01-01");
$string = str_split($protocolo, 4);
if (($at > time() && $string[0] == ($ano - 1)) || ($string[0] == $ano)) {
if (strlen(soNumero($protocolo)) == 12) {
return true;
}
}
if ($silent) {
return false;
}
GeraExcept("ERRO; Para o protocolo informe 12 dígitos com as iniciais do ano vigente!");
}
function ValidaTamanhoProtocolo($protocolo) {
if (strlen(soNumero($protocolo)) == 12) {
return true;
} else {
GeraExcept("ERRO; Para o protocolo informe 12 dígitos!");
}
}
function ValidaProtocoloClickTelecom($protocolo) {
if (strlen(soNumero($protocolo)) > 0) {
return true;
} else {
GeraExcept("ERRO; O número de protocolo deve possuir no minimo 1 digito!");
}
}
function ValidaProtocoloSevenProtecao($protocolo) {
if (strlen(soNumero($protocolo)) > 0 && strlen(soNumero($protocolo)) <= 30) {
return true;
} else {
GeraExcept("ERRO; O número de protocolo deve possuir no minimo 1 digito e no máximo 30 digitos!");
}
}
/*
* VALIDA SE A FUNCAO ESTÁ CADASTRADA
*/
function ___GetValidaFuncao($funcao) {
foreach ($_SESSION['SSValidaFuncoesProtocolo'] as $fnc) {
if ($fnc == $funcao) {
return true;
}
}
return false;
}

BIN
integracao/imgIntegra/delphiIco.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 689 B

BIN
integracao/imgIntegra/dotNetIco.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

BIN
integracao/imgIntegra/javaIco.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

BIN
integracao/imgIntegra/logoPrincipal.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
integracao/imgIntegra/pdf16.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
integracao/imgIntegra/phpIco.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
integracao/imgIntegra/textoApi.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

139
integracao/importaCampanha.php

@ -0,0 +1,139 @@
<?php
$gmtDate = gmdate("D, d M Y H:i:s");
header("Expires: {$gmtDate} GMT");
header("Last-Modified: {$gmtDate} GMT");
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
header("X-XSS-Protection: 0");
header('Content-Type: text/html; charset=ISO-8859-1', true);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Importa Discador</title>
<link rel="shortcut icon" href="../img/logo_ip.png"/>
<style type="text/css">
body{
height: auto;
background: #D8D5C2 url(../img/background_main.jpg) repeat-x top;
text-align: center;
position: absolute; top: 0; bottom:0; right:0; left:0;
font-family: helvetica, arial, sans-serif;
}
.titulo_pagina{
text-align: center;
}
input{
width: 300px;
padding: 15px;
font-size: 14px;
border: 1px solid #CCC;
margin: 5px;
}
input[type=submit]{
width: 150px;
padding: 15px;
font-size: 14px;
border: 1px solid #CCC;
border-radius: 5%;
}
input[type=submit]:hover{
color: black;
box-shadow: #000 5px 5px 5px;
transition: ease-in;
transition-duration: 0.10s;
transition-timing-function: linear;
background-color: #DCDCDC;
}
.form{
margin-left: auto;
margin-right: auto;
width: 400px;
height: 425px;
border-radius: 5px;
background-color: #FFA54F;
padding-top: 15px;
margin-bottom: 10%;
box-shadow: 0.1em 0.1em 0.2em black;
}
footer{
position: absolute;
bottom: 0;
width: 100%;
height: auto;
background-color: #FFA54F;
text-shadow: 0.1em 0.1em 0.5em black;
}
header{
width: 100%;
height: 10%;
background-color: #FFA54F;
color: black;
}
.box-shadow{
box-shadow: 0 2px 4px 0 rgba(0,0,0,.10),
0 2px 4px 0 rgba(0,0,0,.10);
}
</style>
</head>
<body>
<header class="box-shadow">
<img src="../img/LOGO_SIMPLES_IP.png" alt="Logo Simples IP"/>
</header>
<h2 class="titulo_pagina">Upload Discador</h2>
<div class="contorno_form">
<div class="form">
<form action="http://127.0.0.1/integracao/index.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input type="hidden" name="method" value="EnviarDadosCampanha"/>
<input type="hidden" name="tipoRetorno" value="XML"/>
</div>
<div class="row">
<div class="column-3 column label">
<label for="usuario">Usuário</label>
</div>
<div class="column-9 column input">
<input type="text" id="txtUsuario" name="login" placeholder="Nome de Usuário" value="aplicativos"/>
</div>
</div>
<div class="row">
<div class="column-3 column label">
<label for="senha">Senha</label>
</div>
<div class="column-9 column input">
<input type="password" id="txtSenha" name="senha" value="1234" />
</div>
</div>
<div class="row">
<div class="column-3 column label">
<label for="arquivo">Arquivo</label>
</div>
<div>
<input type="file" name="arquivoCampanha" id="arquivoCampanha"/>
</div>
</div>
<div>
<input type="submit" name="btnUpload" id="btnUpload" value="Upload"/>
</div>
</form>
<div class="alerta">
<strong><?= $msg; ?></strong>
</div>
</div>
</div>
</body>
<footer class="footer">
Simples IP ® - Comércio e Serviços de Tecnologia da Informação ltda. 2019
</footer>
</html>

76
integracao/index.php

@ -0,0 +1,76 @@
<?php
error_reporting(E_ERROR);
ini_set('display_errors', 0 );
ini_set("session.name", "SIPID");
ini_set('session.use_cookies', 0);
if (isset($_REQUEST["SIPID"])) {
session_id($_REQUEST["SIPID"]);
}
session_start();
require("util/constantes.php");
require("util/funcoesAmi.php");
require("util/util.php");
include("funcoes/shared.php");
include("funcoesCustom.php");
require("util/funcoesApl.php");
include('bdApi.php');
include("util/cnvrtFunctions.php");
include("configs/config.php");
header('Content-Type: text/html; charset=ISO-8859-1');
/*
*
* Usado para debug
*/
$log = array();
$ativaDebug = 0; // 1 envia url astman/chamada socket para o cliente
$useLog = 0; // 1 para gravar log de erros
/*
* habilita/desabilita a gravação de log.
*/
$gravaLog = 1;
$debugAmi = 1;
/*
* Metodos disponiveis
*/
$metodosParam = array();
$metodosRetorno = array();
$metodos = array();
$encoding = 'ISO-8859-1';
require("ligueGratis.php");
require('funcoesApi.php');
/*
* Captura os parametros passados pelo cliente por GET/POST.
*/
$paraUrl = array();
$paramUrl = $_REQUEST;
$metodoRequest = getRequestMethod($paramUrl);
$methodReturn = getReturnMethod($paramUrl);
if (strtoupper($metodoRequest) == strtoupper("InformacoesAtendimentoRT")) {
InformacoesAtendimentoRT();
} else if (ValidaMetodos($paramUrl) != 'OK') {
try {
throw new Exception(ValidaMetodos($paramUrl));
} catch (Exception $ex) {
echo GetErro($metodoRequest, $ex, 0, $methodReturn);
}
} else if (!UserAut() && ($metodoRequest != "AutenticaUsuario")) {
try {
$errrror = error_get_last();
$log[] = "Metodo: $metodoRequest Mensagem: " . $errrror["message"];
throw new Exception( strstr($errrror["message"],'padrão') === false ? "Usuário não autenticado!" : $errrror["message"]);
} catch (Exception $ex) {
echo GetErro($metodoRequest, $ex, 0, $methodReturn);
}
} else {
Display($paramUrl);
}
GravaLogItgr();
?>

274
integracao/infoAtende.php

@ -0,0 +1,274 @@
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbPort = "5432";
$dbHost = "127.0.0.1"; // "192.168.80.210";
$dbName = "pbx";
$dbUser = "contacte";
$dbPassword = "ctepgSQL";
$str = "host='$dbHost' port='$dbPort' dbname='$dbName' user='$dbUser' password='$dbPassword'";
$dbcon = @pg_connect($str);
InformacoesAtendimentoRT();
function InformacoesAtendimentoRT() {
$dbcon = $GLOBALS['dbcon'];
$nomeDac = 'Api'; //$_SESSION[SS_NOME_DAC];
$matricula = '1067'; // $_SESSION[AGT_MATRICULA];
$infoChamada = array(
"ramal" => '-', "matricula" => '-', "nome" => '-', "tempo_login" => '00:00:00', "modo_atendimento" => '-',
"origem_destino" => '-', "status" => 'LOGOFF', "duracao" => '00:00:00'
);
$infoFila = array(
"fila" => '-', "abandonadas" => '0', "atendidas_pa" => '0', "espera" => '0', "tme" => '00:00:00',
"tma" => '00:00:00', "qt_fila" => '0'
);
$infoFilaOld = array(
"fila" => '-', "abandonadas" => '0', "atendidas_pa" => '0', "espera" => '0', "tme" => '00:00:00',
"tma" => '00:00:00', "qt_fila" => '0'
);
/*
* Informações da chamada corrente
*/
$queryAgente = "select ramal, matricula, nome, (LOCALTIMESTAMP(0) - tempo_login) as tempo_login, modo_atendimento, origem_destino, status, (LOCALTIMESTAMP(0) - duracao) as duracao
from pbx_supervisor_agentes
where matricula = '$matricula' ";
$queryFila = GetQueryInfoFila($nomeDac, $matricula);
echo $queryFila;
try {
//Indica o tempo entre as requisições para verifica o status do agente no banco de dados
define("TEMPO_DORME", 10);
define("MAX_ERROS", 10);
//Variavel armazena o status do agente na sessao atual
// if(!$_SESSION[AGT_CONECT])
// throw new Exception ('O agente não esta logado!');
//Tolerancia de tentavias de acesso ao banco de dados
$numErros = 0;
//Id do bloco de informacoes retornado
$idBloco = 1;
//Buffer necessário para o browser comecar a receber atualizações
echo(str_repeat(' ', 256));
_flush();
//Contera blocos de informações sobre filas e agentes
/* $encode = $GLOBALS['server']->getEncoding();
$info = "\n<?xml version=\"1.0\" encoding=\"$encode\" ?>\n";
$info .= "<root>\n";
$info .= "<status>ok</status>\n";
*
*/
$info = "<message>Inicializando monitoramento de agente! Aguarde...</message>\n";
DisplayInfo($info); //simplexml_load_string($info)->asXml();
$info = "";
//Flag que indica se ha dados a enviar ao processo chamador
$display = 0;
//Variavel define o status atual do agente
//$statusAgente = $_SESSION[SS_STATUS_AGENTE];
$start = 0;
//Indica que houve mudança na fila
$statusFila = 0;
//Display das informações para o chamador
while (true) {
$info = "";
$display = 0;
$result = pg_query($dbcon, $queryAgente);
$ret = array();
if (!$result) {
$numErros++;
} else {
//Se o agente foi desconectado, gera uma excessão informando o processo chamador
if (!pg_num_rows($result))
throw new Exception('O agente foi desconectado!');
// Recupera informações do banco de dados sobre o agente logado
$row = @pg_fetch_array($result);
GetValoresInfo($row, $infoChamada);
if ((!$start) || ($statusAgente != $infoChamada["status"])) {
// $ret[] = $infoChamada;
$statusAgente = $infoChamada["status"];
$info = "<agente id=\"$idBloco\">\n";
$info .= ArrToStrXml($infoChamada);
$info .= "</agente>\n";
DisplayInfo($info);
$display++;
}
if ($display) {
$idBloco++;
$display = 0;
}
//Recupera informações sobre a fila de atendimento
$result = pg_query($dbcon, $queryFila);
if (!$result) {
$numErros++;
} else {
$row = @pg_fetch_array($result);
if (!empty($row["fila"])) {
GetValoresInfo($row, $infoFila);
if (!$start)
GetValoresInfo($row, $infoFilaOld);
$statusFila = GetStatusFila($infoFila, $infoFilaOld);
if (!$start || $statusFila) {
$ret = array();
// $ret[] = $infoFila;
$info = "<dac id=\"$idBloco\">\n";
$info .= $info .= ArrToStrXml($infoFila);
$info .= "</dac>\n";
$display++;
DisplayInfo($info);
GetValoresInfo($row, $infoFilaOld);
}
}
}
if ($display) {
$idBloco++;
$display = 0;
}
}
if ($numErros > MAX_ERROS)
throw new Exception('A aplicação foi encerrada porque atingiu o limite máximo de erros ao tentar acessar o banco de dados!');
$start++;
sleep(TEMPO_DORME);
}
} catch (Exception $ex) {
echo GetErroSimples("InformacoesAtendimentoRT", $ex);
}
}
function GetErroSimples($method, $ex) {
$xml = "<erro>\n";
$xml .= "<status>erro</status>\n";
$xml .= "<SIPID>%s</SIPID>\n";
$xml .= "<method>%s</method>\n";
$xml .= "<code>%s</code>\n";
$xml .= "<message>%s</message>\n";
$xml .= "<line>%s</line>\n";
$xml .= "<file>%s</file>\n";
$xml .= "</erro>\n";
$xml = sprintf($xml, session_id(), $method, $ex->getCode(), $ex->getMessage(), $ex->getLine(), $ex->getFile());
return $xml;
}
function DisplayInfo($info) {
echo $info; //simplexml_load_string($info)->asXml();
_flush();
}
function _flush() {
echo(str_repeat(' ', 256));
// check that buffer is actually set before flushing
if (ob_get_length()) {
@ob_flush();
@flush();
}
}
function GetStatusFila($infoFila, $infoFilaOld) {
$count = count($infoFila);
for ($i = 0; $i < $count; $i++) {
if ($infoFila[$i] != $infoFilaOld[$i])
return true;
}
return false;
}
function GetValoresInfo($row, &$infoArray) {
foreach ($row as $key => $value) {
if (array_key_exists($key, $infoArray)) {
$infoArray[$key] = $value;
}
}
}
function GetQueryInfoFila($nomeDac, $matricula) {
return "SELECT fila
,ABANDONADAS
,ATENDIDAS_PA
,ESPERA
,round( CASE WHEN(ESPERA = 0)THEN 0 ELSE (TEMPO_ESPERA / ESPERA) END ) * INTERVAL '1 SECOND' AS TME
,round( CASE WHEN(ATENDIDAS_PA = 0)THEN 0 ELSE (TEMPO_ATENDIMENTO / ATENDIDAS_PA)END) * INTERVAL '1 SECOND' AS TMA,
coalesce((select espera from pbx_supervisor_dacs where dac = DADOS.fila), '0') as qt_fila
FROM
(
SELECT fila
,SUM (CASE WHEN EVENTO = 'ABANDON' THEN 1 ELSE 0 END) AS ABANDONADAS
,SUM (CASE WHEN EVENTO IN ('CONNECT') THEN 1 ELSE 0 END) AS ATENDIDAS_PA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND to_number(param1,'999999999') > '3' THEN 1 ELSE 0 END) AS ESPERA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND to_number(param1,'999999999') > '1' THEN to_number(param1,'999999999') ELSE 0 END) AS TEMPO_ESPERA
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER') AND to_number(param2,'999999999') > '1' THEN to_number(param2,'999999999') ELSE 0 END) AS TEMPO_ATENDIMENTO
FROM
( SELECT a.calldate,b.fila,b.evento,b.param1,b.param2
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b on b.uid2 = a.uniqueid
WHERE b.evento in ('ABANDON','COMPLETEAGENT','COMPLETECALLER','CONNECT','ENTERQUEUE')
AND a.calldate IS NOT NULL
AND a.lastapp <> 'Transferred Call'
AND cast(a.calldate as date) = cast(now() as date)
AND substring(b.agente, 7,4) = '$matricula'
AND b.fila = '$nomeDac'
) AS DADOS
GROUP BY FILA
) AS DADOS
";
}
function UpdatePausa($db) {
$idPausa = $_SESSION[AGT_ID_PAUSA];
$query = "update pbx_eventos_agentes
set saida_pausa = now(),
flag = 1
where id = $idPausa ";
pg_query($db, $query);
}
function UpdateLogoff($db) {
$idLogoff = $_SESSION[AGT_ID_LOGIN];
$matricula = GetMatriculaAgente();
$query = "update pbx_supervisor_agentes
set logado = now()
where matricula = '$matricula'";
$result = pg_query($db, $query);
$query = "update pbx_eventos_agentes
set logoff = now(),
flag = 1
where id = $idLogoff";
pg_query($db, $query);
}
?>

68
integracao/integracao.hmtl

@ -0,0 +1,68 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-family: Arial, Helvetica, sans-serif;
font-size: x-large;
font-weight: bold;
}
body {
background-image: url(Backgroung.png);
background-repeat: repeat-x;
}
-->
</style>
</head>
<body>
<table width="760" border="0" align="center" cellpadding="2" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="2"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center"><span class="style1">Simples API</span></td>
<td width="200" align="right"><img src="Logo.png" width="200" height="61" /></td>
</tr>
</table></td>
</tr>
<tr>
<td colspan="2" align="center">Lista de M&eacute;todos</td>
</tr>
<tr>
<td width="200">Nome</td>
<td>Descri&ccedil;&atilde;o</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</body>
</html>

140
integracao/integracao.tpl

@ -0,0 +1,140 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Simples IP - Documentação API</title>
<style type="text/css" >
<!--
body {
background-image: url();
background-repeat: repeat-x;
background-color: #F8F9FA;
text-align: left;
font-family: helvetica, arial;
}
.style1 {
font-size: x-large;
font-weight: bold;
}
#tableStyle {
border-color: #FFF;
border-radius: 7px;
box-shadow: 0 0.25rem 0.75rem rgb(0 0 0 / 5%);
}
#DisplayMetodos
{
border: 0;
padding: 2px;
border-collapse: collapse;
border-color: #FFF;
}
#DisplayMetodos td
{
border-right: 0;
border: 1px solid #FFF;
padding: 6px;
}
#DisplayMetodos th
{
border-right: 0;
border: 1px solid #FFF;
padding: 6px;
color: #fff;
}
#TipoRetorno{
padding: 3px 10px 3px;
border-radius: 5px;
background-color: #FF8D00;
font-family: inherit;
font-size: 10px;
color: #FFF;
margin-left: 40px;
}
#TipoParam{
padding: 3px 10px 3px;
border-radius: 5px;
background-color: #e4e4e4;
font-family: inherit;
font-size: 10px;
color: #FF8D00;
}
#TipoResponse{
font-size: 14px;
color: #888;
}
#isRequire{
padding: 3px 10px 3px;
border-radius: 5px;
background-color: red;
font-family: inherit;
font-size: 10px;
color: #FFF;
margin-left: 40px;
}
#isNoRequire{
padding: 3px 10px 3px;
background-color: #029ef3;
border-radius: 5px;
font-family: inherit;
font-size: 10px;
color: #FFF;
margin-left: 40px;
}
#url{
padding: 3px 10px 3px;
border-radius: 2px;
background-color: #f5f5f5;
font-family: inherit;
font-size: 13px;
}
hr.separate {
border-top: 1px solid #f1f1f2;
}
hr.new {
border: 0;
height: 1px;
background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0));
}
-->
</style>
</head>
<body>
<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" >
<tr>
<td align="center">
<div style="width: 90%; margin:0; border: 0; padding:0;">
<table id="tableStyle" width="100%" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td colspan="2">
<table width="100%" border="0" align="center" cellspacing="10" cellpadding="5">
<tr>
<td width="20%" align="left">
<img src={LOGO} />
<p style="font-family: inherit; color: #CCCCCC">[v1.0] Documentação API - <i>Developers</i></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
{LINHAS}
</div>
</td>
</tr>
</table>
</body>
</html>

76
integracao/ligueGratis.php

@ -0,0 +1,76 @@
<?php
/*
* Ligue gratis.
*/
define('ANUNCIO_LIGUE_GRATIS_RECEBE', 'LIGUE_GRATIS_RECEBE');
define('HORARIO_LIGUE_GRATIS_VERIFICA', 'LIGUE_GRATIS_VERIFICA');
define('ANUNCIO_LIGUE_GRATIS_AVISO', 'LIGUE_GRATIS_AVISO');
define('ANUNCIO_LIGUE_GRATIS_RETORNA', 'LIGUE_GRATIS_RETORNA');
define('RAMAL_LIGUE_GRATIS', 'LIGUE_GRATIS_RAMAL');
$numLigueGratis = '';
$ramlLigueGratis = '';
$anuncioRecebe = '';
function GetAnuncioLigueGratis() {
global $anuncioRecebe;
/*
* Garante a consulta ao banco apenas uma vez por requisicao.
*/
if (!empty($anuncioRecebe)) {
return $anuncioRecebe;
}
/*
* Consulta o banco na primeira chamada.
*/
$query = sprintf("select '_a' || id::text as anuncio from pbx_anuncios where nome = %s", QuotedStr(ANUNCIO_LIGUE_GRATIS_RECEBE));
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$dados = pg_fetch_row($result);
$anuncioRecebe = $dados[0];
return $dados[0];
}
function GetRamalLigueGratis() {
global $ramlLigueGratis;
/*
* Garante a consulta ao banco apenas uma vez por requisicao.
*/
if (!empty($ramlLigueGratis)) {
return $ramlLigueGratis;
}
/*
* Consulta o banco na primeira chamada.
*/
$query = sprintf("select nome from pbx_sip_ramais where callerid = %s", QuotedStr(RAMAL_LIGUE_GRATIS));
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$dados = pg_fetch_row($result);
$ramlLigueGratis = $dados[0];
return $dados[0];
}
function SetNumeroLigueGratis($numeroDiscar) {
global $numLigueGratis;
$numLigueGratis = $numeroDiscar;
}
function GetNumeroLigueGratis() {
global $numLigueGratis;
return $numLigueGratis;
}
function GetSIPIDCall(){
global $numLigueGratis;
$query = "SELECT sipid_contato FROM pbx_ligueme_gratis WHERE telefone_contato = $numLigueGratis ORDER BY 1 DESC LIMIT 1";
$result = pg_query($query);
return pg_fetch_assoc($result);
}

33
integracao/liguemeGratis/liguemeGratis.php

@ -0,0 +1,33 @@
<?php
include("util/util.php");
$nome = isset($_POST['lg_nome']) ? $_POST['lg_nome'] : '';
$ddd = isset($_POST['lg_ddd']) ? $_POST['lg_ddd'] : '';
$tel = isset($_POST['lg_telefone']) ? $_POST['lg_telefone'] : '';
$pagina = isset($_GET['pag']) ? $_GET['pag'] : '';
$url = sprintf("http://localhost/integracao?method=LigueGratis&numeroDiscar=%s&login=sinccontasenha&senha=s3ncC0nt@S2nh@&SIPID=hv615jnr8pc68guovgl1s61326&tipoRetorno=XML", $ddd . $tel);
$ret = file_get_contents($url);
$xml = simplexml_load_string($ret);
if (strval($xml->status) == 'OK' && strval($xml->result) == true) {
echo 'OK';
} else {
echo 'FAIL';
}
GetQuery($nome, $ddd . $tel, $xml->status . '|' . $xml->result, $xml->message, $xml->SIPID);
function GetQuery($nome, $telefone, $result, $mensagem, $sipid) {
$query = "INSERT INTO pbx_ligueme_gratis (nome_contato,telefone_contato,result_contato,mensagem_contato,sipid_contato) VALUES('$nome','$telefone','$result','$mensagem','$sipid')";
pg_query($query);
if (pg_last_error()) {
$path = "/var/log/asterisk/liguemegratis.log";
$log = date('Y-m-d H:i:s')." [ ERROR ] ".pg_last_error() ."\n";
@WriteLog($log, $path);
}
}

20
integracao/media/.gitignore vendored

@ -0,0 +1,20 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
docker-compose.override.yml
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
/.idea
/stubs
/public/node_modules
/public/vendor
/banco
/websocket/vendor
composer.lock

6
integracao/media/.htaccess

@ -0,0 +1,6 @@
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
AddType application/json json php
php_value default_mimetype application/json

29
integracao/media/Dockerfile

@ -0,0 +1,29 @@
FROM php:8.0-apache
RUN apt-get update && apt-get install -y \
vim git
ADD https://raw.githubusercontent.com/mlocati/docker-php-extension-installer/master/install-php-extensions /usr/local/bin/
RUN chmod uga+x /usr/local/bin/install-php-extensions && sync && \
install-php-extensions pdo_pgsql
RUN echo "ServerName 192.168.115.65" >> /etc/apache2/apache2.conf &&\
a2enmod rewrite &&\
a2dissite 000-default
COPY apache2.conf /etc/apache2/
COPY ports.conf /etc/apache2/
COPY . .
RUN a2enmod headers
RUN service apache2 restart
WORKDIR /var/www/html
COPY index.php index.php
RUN chmod -R 777 /var/www/html/
RUN chmod -R 777 /tmp
RUN chown -R www-data:www-data /var/www/html
EXPOSE 8081
EXPOSE 8090
EXPOSE 5432
ENTRYPOINT ["./inicia.sh"]

232
integracao/media/apache2.conf

@ -0,0 +1,232 @@
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
# together by including all remaining configuration files when starting up the
# web server.
#
# * ports.conf is always included from the main configuration file. It is
# supposed to determine listening ports for incoming connections which can be
# customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
# directories contain particular configuration snippets which manage modules,
# global configuration fragments, or virtual host configurations,
# respectively.
#
# They are activated by symlinking available configuration files from their
# respective *-available/ counterparts. These should be managed by using our
# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
# their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
# the default configuration, apache2 needs to be started/stopped with
# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
# work with the default configuration.
# Global configuration
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default
#
# The directory where shm and other runtime files will be stored.
#
DefaultRuntimeDir ${APACHE_RUN_DIR}
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn
# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
# Include list of ports to listen on
Include ports.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
Options FollowSymLinks
Header set Access-Control-Allow-Origin "*"
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
Header set Access-Control-Allow-Origin "*"
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Header set Access-Control-Allow-Origin "*"
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
#<Directory /srv/>
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#</Directory>
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
Header set Access-Control-Allow-Origin "*"
Require all denied
</FilesMatch>
#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
ServerName 192.168.115.65

385
integracao/media/app/Controllers/AgentController.php

@ -0,0 +1,385 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Queue;
use app\Models\Ramal;
use app\Models\Pause;
use app\Models\Bilhete;
use app\Models\EventQueue;
use app\Models\Atendimento;
use app\Models\Evento;
use app\Models\Message;
use app\Models\SupervisorModel;
use Exception;
use websocket\WsInterface;
/**
* Description of AgentController
*
* @author root
*/
class AgentController extends Controller
{
/** @var SupervisorModel $agent model de supervisor */
protected $agent;
/** @var Queue $queue model de queue */
protected $queue;
/** @var Ramal $ramal model de Ramal */
protected $ramal;
/** @var Pause $pause model de Pause */
protected $pause;
/** @var Bilhete $bilhete model de Bilhete */
protected $bilhete;
/** @var EventQueue $eventqueue model de EventQueue */
protected $eventqueue;
/** @var Atendimento $atendModel model de Atendimento */
protected $atendModel;
public function __construct()
{
$this->agent = new SupervisorModel();
$this->queue = new Queue();
$this->ramal = new Ramal();
$this->pause = new Pause();
$this->bilhete = new Bilhete();
$this->eventqueue = new EventQueue();
$this->atendModel = new Atendimento();
}
public function login($fila, $matricula)
{
try {
$this->agent->begin();
$queue = $this->queue->findQueueByName(strtoupper($fila));
$agent = $this->agent->findByAgent(strtolower($matricula));
if ($queue->midiafila == 'N') {
return 'Fila não relacionada como WhatsApp!';
}
if (!$queue) {
return 'Fila não encontrada ou não relacionada como WhatsApp!';
}
if (!$agent) {
return 'Usuário não encontrado!';
}
if ($this->agent->findByMatricula($matricula)) {
return 'Agente já autenticado!';
}
/**
* VERIFICA CLASSIFICACAO ATENDIMENTO
*/
// $classificacao = new ClassificacaoController();
// $chamadaSemClassificacao = $classificacao->agentClassificacaoPending($agent->matricula, $fila);
if (!$this->agent->addAgent($agent->matricula, $fila, $agent->nome)) {
return 'Não foi possével inserir o agente!';
}
if (!$this->agent->addEventoLoginAgent($agent->matricula, $queue->id, 1, '0')) {
return 'Não foi possível inserir as informações de autenticação do login!';
}
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function logoff($matricula, $valida = true)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByMatricula($matricula);
if (!$agent) {
throw new Exception('Agente não encontrado!');
}
$queue = $this->queue->findQueueByName($agent->fila);
if (!$queue) {
throw new Exception('Agente não conectado!');
}
if ($agent->status != CONF_AGENT_STATUS_LIVRE && $valida) {
throw new Exception('Saia da pausa para fazer logoff');
}
$this->agent->updateEventoLogoffAgent($agent->matricula, '0', $queue->id);
$this->agent->deleteAgent($agent->matricula);
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function indisponivelAtendimento($matricula, $pausa)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByMatricula($matricula);
$queue = $this->queue->findQueueByName($agent->fila);
$pause = $this->pause->findPauseByName($pausa);
if (!$this->agent->updateAgent($agent->matricula, CONF_AGENT_STATUS_INDISPONIVEL, $pause->motivo)) {
throw new Exception('Não foi possível atualizar o status do agente!');
}
if (!$this->pause->addEventoIndisponivelAgent($agent->matricula, '0', $pause->id, $queue->id)) {
throw new Exception('Não foi possível atualizar informações complementares do agente!');
}
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function enterPause($matricula, $pausa)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByMatricula($matricula);
$queue = $this->queue->findQueueByName($agent->fila);
$pause = $this->pause->findPauseByName($pausa);
if (!$agent) {
throw new Exception('Telefone não identificado!');
}
if (!$pause) {
throw new Exception('Pausa não encontrada!');
}
if (!$queue) {
throw new Exception('Usuário não conectado em uma fila!');
}
if ($agent->status == 'PAUSA') {
throw new Exception('Agente precisa estar livre para entrar em pausa!');
}
if (!$this->agent->updateAgent($agent->matricula, CONF_AGENT_STATUS_PAUSA, $pause->motivo)) {
throw new Exception('Não foi possível atualizar o status do agente!');
}
if (!$this->pause->addEventoPauseAgent($agent->matricula, '0', $pause->id, $queue->id, $pause->produtiva)) {
throw new Exception('Não foi possível atualizar informações complementares do agente!');
}
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function exitPause($matricula)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByMatricula($matricula);
$queue = $this->queue->findQueueByName($agent->fila);
if (!$agent) {
throw new Exception('Telefone não identificado!');
}
if (!$queue) {
throw new Exception('Agente não está conectado!');
}
if ($agent->status != CONF_AGENT_STATUS_PAUSA && $agent->status != CONF_AGENT_STATUS_INDISPONIVEL) {
throw new Exception('Agente não está em pausa!');
}
$atendimentos = $this->atendModel->getAtendimentoAbertoByAgente($matricula);
$param = $this->atendModel->getQuantiAtendimentSimultaneos();
if (count($atendimentos) < $param->prm_media_simultaneo) {
$this->agent->updateAgent($agent->matricula, CONF_AGENT_STATUS_LIVRE);
} else {
$this->agent->updateAgent($agent->matricula, CONF_AGENT_STATUS_OCUPADO);
}
$this->pause->updateEventoOutPause($agent->matricula, $queue->id);
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function transfer($matOrigem, $matDestino, $uniqueid)
{
try {
$this->agent->begin();
$atendimento = new Atendimento();
$eventModel = new Evento();
$agent = $this->agent->findAgentByMatricula($matOrigem);
if (!$agent) {
throw new Exception('Agente não conectado!');
}
$agentTransf = $this->agent->findAgentByMatricula($matDestino);
if (!$agentTransf || $agentTransf->status != CONF_AGENT_STATUS_LIVRE) {
throw new Exception('Agente indisponível para atendimento!');
}
$atendAtual = $atendimento->findAtendId($uniqueid);
if (!$atendAtual) {
throw new Exception('Atendimento não encontrado');
}
$atendimento->updAtendimento($uniqueid, $agentTransf->matricula);
$eventModel->createEvento(
$uniqueid,
CONF_EVENT_TRANSFER,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendAtual->fila,
$agent->matricula
);
$eventModel->createEvento(
$uniqueid,
CONF_EVENT_START,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendAtual->fila,
$agentTransf->matricula
);
//$ws->enviaMsg($ws->enviaActions('Atendimento transferido', 'transfer', $agent->matricula, $uniqueid));
$provedor = returnChannel($atendAtual->context);
$provedor->enviarMsg($atendAtual->cliente_id, CONF_NAME_REPONSE . ": Atendimento transferido");
$messegeModel = new Message();
$messegeModel->addMessage(
$uniqueid,
$agent->matricula,
$agentTransf->matricula,
'transfer',
'Atendimento transferido',
$agent->nome,
$atendAtual->context,
'read'
);
$this->agent->commit();
$this->atualizaStatusAgente($agentTransf);
$this->atualizaStatusAgente($agent);
$ws = new WsInterface();
$ws->enviaMsg($ws->enviaActions('Atendimento transferido', 'transfer', $agentTransf->matricula, $uniqueid));
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
return $ex->getMessage();
}
return false;
}
public function atualizaStatusAgente($agente)
{
$atendimentosAbertos = $this->atendModel->getAtendimentoAbertoByAgente($agente->matricula);
$param = $this->atendModel->getQuantiAtendimentSimultaneos();
if ($agente->status == CONF_AGENT_STATUS_LIVRE || $agente->status == CONF_AGENT_STATUS_OCUPADO) {
if (count($atendimentosAbertos) < $param->prm_media_simultaneo) {
$this->agent->updateAgent($agente->matricula, CONF_AGENT_STATUS_LIVRE);
} else {
$this->agent->updateAgent($agente->matricula, CONF_AGENT_STATUS_OCUPADO);
}
}
if ($agente->status == CONF_AGENT_STATUS_INDISPONIVEL) {
if (empty($atendimentosAbertos)) {
$this->enterPause($agente->matricula, $agente->motivo_pausa);
}
}
}
public function infoAgentes($media, $queue = null)
{
try {
$agent = $this->agent->findAllAgentes($media, $queue);
return $agent;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
}
return false;
}
public function status($ramal, $status, $origemDestino = null)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByRamal($ramal);
if (!$agent) {
throw new Exception('Agente não conectado!');
}
$this->agent->updateAgent($agent->matricula, $ramal, strtoupper($status), $origemDestino, null, 1);
$this->agent->commit();
return true;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
}
return false;
}
public function getAgente($ramal)
{
try {
$this->agent->begin();
$agent = $this->agent->findAgentByRamal($ramal);
$agent->nome = ucwords(explode(' ', str_replace('.', ' ', $agent->nome))[0]);
if (!$agent) {
throw new Exception('Telefone não identificado!');
}
$this->agent->commit();
return $agent;
} catch (Exception $ex) {
$this->agent->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
}
return false;
}
public function findRamal($ramal)
{
try {
return $this->ramal->findRamal($ramal);
} catch (Exception $ex) {
logger()->error($ex->getMessage());
}
return false;
}
}

88
integracao/media/app/Controllers/BilheteController.php

@ -0,0 +1,88 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Parametros;
use app\Models\Protocol;
use Exception;
class BilheteController extends Controller
{
/** @var Parametros $parametros model de Parametros */
protected $parametros;
/** @var Protocol $protocol model de Protocol */
protected $protocol;
public function __construct()
{
$this->parametros = new Parametros();
$this->protocol = new Protocol();
}
public function generateProtocol($uniqueid)
{
/*
* Função retorna numero de Protocolo de Atendimento para o agente
*/
$tentativa = 0;
while (true) {
$proto = $this->geraProtocolo($uniqueid);
if ($proto == '99') {
$proto = '0000-000000';
break;
}
if (!empty($proto) || $tentativa >= CONF_PROTOCOL_TENTATIVAS_GERAR) {
break;
}
$tentativa++;
}
return $proto;
}
private function geraProtocolo($uniqueid, $protocoloParceiro = '')
{
try {
$this->protocol->begin();
$param = $this->parametros->findProtocolByParams($uniqueid);
$useProtocolo = $param->prm_agente_proto;
$useProtoParceiro = $param->prm_use_proto_parceiro;
if (!$useProtocolo) {
$this->protocol->rollback();
return '99';
}
$numProto = $this->protocol->findProtocol($uniqueid);
if ($numProto) {
$numProtoParceiro = trim($numProto->protoparceiro);
$this->protocol->rollback();
if ($useProtoParceiro && $numProtoParceiro) {
return $numProtoParceiro;
}
return $numProto->protocolo;
}
$protoParceiro = $useProtoParceiro ? trim($protocoloParceiro) : '';
$year = date('Y');
$result = $this->protocol->findMaxProtocol($year);
if ($result) {
$numProto = $result->protocolo;
$numProto = $numProto ? $numProto + 1 : 1;
$proto = $year . str_pad($numProto, 6, '0', STR_PAD_LEFT);
$protoAgt = $year . '-' . str_pad($numProto, 6, '0', STR_PAD_LEFT);
$protoParceiro = $protoParceiro && $useProtoParceiro ? $protoParceiro : 'null';
$this->protocol->insert($uniqueid, $year, $numProto, $proto, 'null');
$this->protocol->commit();
return $protoParceiro !== 'null' ? $protoParceiro : $protoAgt;
}
$this->protocol->commit();
} catch (Exception $ex) {
$this->protocol->rollback();
logger()->error($ex->getMessage());
}
return false;
}
}

151
integracao/media/app/Controllers/ClassificacaoController.php

@ -0,0 +1,151 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\EventQueue;
use app\Models\Agent;
use app\Models\Classificacao;
use Exception;
class ClassificacaoController extends Controller
{
/** @var Agent $agent model de Agent */
protected $agent;
/** @var EventQueue $eventqueue model de EventQueue */
protected $eventqueue;
/** @var Classificacao $classificacao model de Classificacao */
protected $classificacao;
public function __construct()
{
$this->agent = new Agent();
$this->eventqueue = new EventQueue();
$this->classificacao = new Classificacao();
}
public function classificacaoList($queue)
{
try {
$classificacao = $this->classificacao->findClassificacaoByQueue($queue);
return $classificacao;
} catch (Exception $ex) {
$this->message($ex->getMessage());
}
return false;
}
public function classificacaoRegister($matricula, $clas_id, $clit_id, $id_bilhetes, $id_dac)
{
try {
$this->classificacao->begin();
$this->classificacao->addClassificacaoReg($matricula, $clas_id, $clit_id, $id_bilhetes, $id_dac);
$agentData = $this->agent->findAgentByMatricula($matricula);
$this->agent->updateAgent($matricula, $agentData->ramal, CONF_AGENT_STATUS_LIVRE, null, null, 1, null, 1);
$this->classificacao->commit();
return true;
} catch (Exception $ex) {
$this->classificacao->rollback();
$this->message($ex->getMessage());
}
return false;
}
public function classificacaoRegList($uniqueid)
{
try {
$classificacaoReg = $this->classificacao->findClassificacaoRegByUniqueid($uniqueid);
return $classificacaoReg;
} catch (Exception $ex) {
$this->message($ex->getMessage());
}
return false;
}
/*
* Listar classificacoes disponiveis
*/
public function agentClassificacaoList($queue)
{
try {
$classificacaoLista = $this->classificacaoList($queue);
if ($classificacaoLista) {
$strmsg = "Informe o número da classificação para o atendimento: \n";
$count = 1;
foreach ($classificacaoLista as $classificacao) {
$strmsg .= "{$count}. *{$classificacao->clas_descricao}* - _{$classificacao->clit_descricao}_ \n";
$count++;
}
$this->message($strmsg);
return $strmsg;
}
return false;
} catch (Exception $ex) {
$this->message($ex->getMessage());
}
return false;
}
/*
* Registrar uma classificacao
*/
public function agentClassificacaoRegister($matricula, $queue, $uniqueid, $option)
{
try {
$classificacaoLista = $this->classificacaoList($queue);
if ($classificacaoLista) {
$count = 1;
foreach ($classificacaoLista as $classificacao) {
if ($option == $count || $option == $classificacao->clas_descricao . '-' . $classificacao->clit_descricao) {
$registro = $this->classificacaoRegister($matricula, $classificacao->clas_id, $classificacao->clit_id, $uniqueid, $classificacao->id_dac);
if (!$registro) {
throw new Exception("Não foi possível classificar o atendimento. " . $this->message());
}
$this->message("Atendimento classificado com sucesso!");
return true;
}
$count++;
}
throw new Exception("Informe uma classificação válida!");
}
return true;
} catch (Exception $ex) {
$this->classificacao->rollback();
$this->message($ex->getMessage());
}
return false;
}
/**
* Verificar se o agente esta pendente de classificacao
* @return string uniqueid
*/
public function agentClassificacaoPending($matricula, $queue)
{
$pendenteClassificacao = null;
$classificacaoLista = $this->classificacaoList($queue); //SE NAO EXISTIR CLASSIFICACAO NAO PRECISA CLASSIFICAR
if ($classificacaoLista) {
$eventQueue = $this->eventqueue->findEventQueueByAgent($matricula, $queue);
$uniqueid = null;
if ($eventQueue) {
$uniqueid = $eventQueue->uid2;
$classificacaoReg = $this->classificacao->findClassificacaoRegByUniqueid($uniqueid);
if (!$classificacaoReg) {
$pendenteClassificacao = $uniqueid;
}
}
}
return $pendenteClassificacao;
}
}

45
integracao/media/app/Controllers/ClientController.php

@ -0,0 +1,45 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Atendimento;
/**
* Description of ClientController
*
* @author root
*/
class ClientController extends Controller
{
public function getClientQueueData($number, $fila)
{
$atendimento = new Atendimento();
$atendimentoFila = $atendimento->getAtendimentoByEvento($fila);
$clientInQueue = false;
$queuePosition = 0;
$clientQueue = '';
foreach ($atendimentoFila as $clientes) {
if ($clientes->cliente_id == $number) {
$clientInQueue = true;
$clientQueue = $clientes->fila;
break;
}
}
$queueClientData = array_filter($atendimentoFila, function ($data) use ($clientQueue) {
return $data->fila == $clientQueue;
});
foreach ($queueClientData as $clientes) {
$queuePosition += 1;
if ($clientes->cliente_id == $number) {
break;
}
}
return ["IN_QUEUE" => $clientInQueue, "QUEUE_POSITION" => $queuePosition, "CLIENT_QUEUE" => $clientQueue];
}
}

55
integracao/media/app/Controllers/MessageController.php

@ -0,0 +1,55 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Message;
use Exception;
/**
* Description of MessageController
*
* @author root
*/
class MessageController extends Controller
{
/** @var Message $message model de Message */
protected $message;
public function __construct()
{
$this->message = new Message();
}
/**
* Calcula o timeout para o encerramento da chamada
* @param type $matricula
* @param type $ramal
* @param type $timer
* @return boolean
*/
public function timeoutTalk($uniqueid, $cliente)
{
try {
$message = $this->message->findLastMessage($uniqueid);
if ($cliente == $message->dst) {
if (strtotime($message->msg_date . '+' . CONF_WHATSAPP_TIMEOUT_CLIENT_RESPOSTA . ' seconds') < time()) {
print('FINISH');
return "FINISH";
}
$timealert = strtotime($message->msg_date . '+' . (CONF_WHATSAPP_TIMEOUT_CLIENT_RESPOSTA - 60) . ' seconds');
if ($timealert < strtotime(date('Y-m-d H:i:s'))) {
print('alerta');
return "ALERT";
}
}
return false;
} catch (Exception $ex) {
$this->message->rollback();
$this->message($ex->getMessage());
logger()->error($ex->getMessage());
}
return false;
}
}

173
integracao/media/app/Controllers/QueueController.php

@ -0,0 +1,173 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Queue;
use app\Models\Agent;
use app\Models\Bilhete;
use app\Controllers\ClientController;
use Exception;
/**
* ringall -> 'Simultaneo'
* leastrecent -> 'Tempo Livre'
* fewesrcalls -> 'Numero de Atendimento'
* random -> 'Randomico'
* rrordered -> 'Sequencial'
*/
/**
* Description of QueueController
*
* @author Lucas Awade
*/
class QueueController extends Controller
{
/** @var Queue $queue model de Queue */
protected $queue;
/** @var Agent $agent model de Agent */
protected $agent;
/** @var Bilhete $bilhete model de Bilhete */
protected $bilhete;
public function __construct()
{
$this->queue = new Queue();
$this->agent = new Agent();
$this->bilhete = new Bilhete();
}
public function strategy($queue)
{
$search = $this->queue->findQueueByName($queue);
$strategy = $search->strategy;
if (method_exists(__CLASS__, $strategy)) {
return $this->$strategy($queue);
}
return false;
}
public function listAllQueueWhatsApp($option = null)
{
try {
$response = ['QUEUE' => '', 'LIST' => ''];
$search = $this->queue->findAllQueue();
$strmsg = "Informe o numero do setor para o atendimento: \n";
$count = 1;
if (count($search) == 1) {
$response['QUEUE'] = $search[0]->nome;
return $response;
}
foreach ($search as $q) {
if ($option == $count || $option == $q->nome) {
$response['QUEUE'] = $q->nome;
return $response;
}
$strmsg .= "{$count}. *{$q->nome}* \n";
$count++;
}
$response['LIST'] = $strmsg;
return $response;
} catch (Exception $ex) {
logger()->error($ex->getMessage());
}
return false;
}
public function listaAllFilas()
{
return $this->queue->findAllQueue();
}
public function clientQueueVerify($number, $fila)
{
$client = new ClientController();
$clienteFila = $client->getClientQueueData($number, $fila);
$clienteEmFila = $clienteFila['IN_QUEUE'];
$posicaoFila = $clienteFila['QUEUE_POSITION'];
if ($clienteEmFila) {
$msg = 'Você está na posição ' . $posicaoFila . ' da fila ' . $clienteFila['CLIENT_QUEUE'] . '. Aguarde ser atendido!';
$response['MESSAGE'] = $msg;
return $response;
}
return false;
}
/**
* Busca o agente com o menor tempo de atendimento.
*/
private function leastrecent($queue)
{
$agents = $this->agent->findAgentByQueue($queue, CONF_AGENT_STATUS_LIVRE);
if (!$agents) {
return null;
}
$timer = ['RAMAL' => '', 'TIMER' => (9999999 * 9999999)];
foreach ($agents as $agent) {
$livre = strtotime('1970-01-01 ' . $agent->tempo_livre . 'UTC');
if ($livre < $timer['TIMER']) {
$timer['RAMAL'] = $agent->ramal;
$timer['TIMER'] = $livre;
}
}
return $timer['RAMAL'];
}
private function fewestcalls($queue)
{
$agents = $this->agent->findAgentByQueue($queue, CONF_AGENT_STATUS_LIVRE);
if (!$agents) {
return null;
}
$atendimentos = ['RAMAL' => '', 'ATENDIMENTOS' => (9999999 * 9999999)];
foreach ($agents as $agent) {
if ($agent->atendimentos <= $atendimentos['ATENDIMENTOS']) {
$atendimentos['RAMAL'] = $agent->ramal;
$atendimentos['ATENDIMENTOS'] = $agent->atendimentos;
}
}
return $atendimentos['RAMAL'];
}
private function random($queue)
{
$agents = $this->agent->findAgentByQueue($queue);
if (!$agents) {
return null;
}
$rand = rand(0, (count($agents) - 1));
return $agents[$rand]->ramal;
}
/** Busca o ultima matricula que foi atendida e pega a maior */
private function rrordered($queue, $media)
{
$calls = $this->bilhete->findBilheteByEventosDacs($queue, 'now', ['COMPLETEAGENT', 'COMPLETECALLER', 'COMPLETAAGENT', 'COMPLETACALLER', 'ABANDON', 'ATENDIDA'], null, $media);
$atendimento = end($calls);
$agents = $this->agent->findAgentByQueue($queue, CONF_AGENT_STATUS_LIVRE, 'matricula', 'DESC');
if (!$agents) {
return null;
}
if (!$calls) {
return $agents[0]->ramal;
}
foreach ($agents as $agent) {
if ($atendimento->agente > $agent->matricula) {
return $agent->ramal;
}
}
return $agents[0]->ramal;
}
}

53
integracao/media/app/Controllers/SupervisorQueueController.php

@ -0,0 +1,53 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Models\Queue;
use app\Models\EventQueue;
use app\Models\SupervisorQueue;
use Exception;
/**
* Description of SupervisorController
*
* @author root
*/
class SupervisorQueueController extends Controller
{
private $queue;
private $eventqueue;
private $supervisorqueue;
public function __construct()
{
$this->queue = new Queue();
$this->eventqueue = new EventQueue();
$this->supervisorqueue = new SupervisorQueue();
}
public function calcTimeAwait()
{
try {
$this->supervisorqueue->begin();
$queue = $this->queue->findAllQueue();
foreach ($queue as $q) {
$timewait = 0;
$count = 0;
$waits = $this->eventqueue->findAllEventByAwait($q->nome);
foreach ($waits as $w) {
$timewait += time() - $w->uid1;
$count++;
}
$this->supervisorqueue->updateEsperaByQueue($q->nome, $timewait, $count);
}
$this->supervisorqueue->commit();
return true;
} catch (Exception $ex) {
$this->supervisorqueue->rollback();
logger()->error($ex->getMessage());
}
return false;
}
}

49
integracao/media/app/Controllers/SystemMessageController.php

@ -0,0 +1,49 @@
<?php
namespace app\Controllers;
use app\Core\Controller;
use app\Interfaces\IApiMedia;
use app\Models\SystemMessage;
use Exception;
/**
* Description of SupervisorController
*
* @author root
*/
class SystemMessageController extends Controller
{
/** @var SystemMessage $sysMessage model de mensagens do sistema */
protected $sysMessage;
public function __construct()
{
$this->sysMessage = new SystemMessage();
}
public function sendMessageSystem($momento, $variavels, IApiMedia $api, $numero, $fila = null)
{ //$variavels = [["nome" => '@cliente', "valor" => 'afonso']]
try {
$msgs = $this->sysMessage->findMessage($momento, $fila);
if (empty($msgs)) {
$msgs = $this->sysMessage->findMessage($momento);
}
foreach ($msgs as $key => $msg) {
$msg->texto = str_replace('\n', "\n", $msg->texto);
if ($variavels) {
foreach ($variavels as $key => $variavel) {
$vari = $variavel['nome'];
$pattern = "/$vari/i";
$msg->texto = preg_replace($pattern, utf8_decode($variavel['valor']), $msg->texto);
}
}
$api->enviarMsg($numero, $msg->texto);
}
return $msgs;
} catch (Exception $ex) {
logger()->error($ex->getMessage());
return false;
}
}
}

170
integracao/media/app/Core/Commands.php

@ -0,0 +1,170 @@
<?php
namespace app\Core;
use app\Controllers\AgentController;
use app\Controllers\BilheteController;
use app\Controllers\QueueController;
use app\Controllers\SystemMessageController;
use app\Interfaces\IApiMedia;
use app\Models\Atendimento;
use app\Models\Evento;
use app\Models\Message;
use app\Models\SupervisorModel;
use websocket\WsInterface;
/**
*
* @author Lucas Awade
*/
class Commands
{
/** @var IApiMedia $api provider de mensagens */
protected $api;
/** @var SystemMessageController $systemController controller de mensagens de sistemas */
protected $systemController;
/** @var BilheteController $bilheteController controller de billhete */
protected $bilheteController;
/** @var Atendimento $atendimentoModel model de atendimento*/
protected $atendimentoModel;
/** @var Evento $eventosModel model de eventos */
protected $eventosModel;
/** @var QueueController $queue controller da queue*/
protected $queue;
public function __construct()
{
$this->queue = new QueueController();
$this->eventosModel = new Evento();
$this->atendimentoModel = new Atendimento();
$this->agente = new AgentController();
$this->bilheteController = new BilheteController();
$this->systemController = new SystemMessageController();
}
public function setApi(IApiMedia $api)
{
$this->api = $api;
}
public function isCommand(IApiMedia $api)
{
$this->api = $api;
$messageParams = explode(" ", $api->getMessage());
$command = $messageParams[0];
switch (strtoupper($command)) {
case '/FINALIZAR':
return $this->finalizar($api->getPhone());
case '/CANCELAR':
return $this->cancelar($api->getPhone());
default:
return false;
}
}
public function finalizar($numero)
{
try {
$this->atendimentoModel->begin();
$supervisorModel = new SupervisorModel();
$atendimento = $this->atendimentoModel->getAtendimentoByCliente($numero, CONF_EVENT_START);
//verifica se existe atendimento
if (empty($atendimento)) {
$this->atendimentoModel->rollback();
$this->api->enviarMsg($numero, CONF_NAME_REPONSE . " : Não foi encontrado atendimento em aberto");
return true;
}
//cria o evento pra finalizar
$ret = $this->eventosModel->createEvento(
$atendimento->uniqueid,
CONF_EVENT_TIMERMINO_CLIENTE,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendimento->fila
);
if ($ret) {
$ws = new WsInterface();
$agente = $supervisorModel->findAgentByMatricula($atendimento->matricula);
$messegeModel = new Message();
$mensagemW = 'Atendimento finalizado pelo cliente';
$messegeModel->addMessage(
$atendimento->uniqueid,
$numero,
$agente->matricula,
'finish',
$mensagemW,
$atendimento->nome,
$atendimento->context,
'read'
);
//verifica se está como indisponivel e caso não tenha atendimento ele entra em pausa
if ($agente->status == CONF_AGENT_STATUS_INDISPONIVEL) {
$atends = $this->atendimentoModel->getAtendimentoAbertoByAgente($atendimento->matricula);
if (empty($atends)) {
$agente->enterPause($atendimento->matricula, $agente->motivo_pausa);
}
}
//coloca o agente como livre caso esteja ocupado e com menos atendimento que o maximo de atendimento
if ($agente->status == CONF_AGENT_STATUS_OCUPADO) {
$param = $this->atendimentoModel->getQuantiAtendimentSimultaneos();
$atendimentosAbertos = $this->atendimentoModel->getAtendimentoAbertoByAgente($agente->matricula);
if (count($atendimentosAbertos) < $param->prm_media_simultaneo) {
$supervisorModel->updateAgent($agente->matricula, CONF_AGENT_STATUS_LIVRE);
}
}
//envia as mensagens do sistema do momento atual para o cliente
$this->systemController->sendMessageSystem(
CONF_MOMENT_FINALIZAR_ATENDIMENTO,
[["nome" => "@autor_name", "valor" => $atendimento->nome]],
$this->api,
$numero
);
$this->atendimentoModel->commit();
//notifica o agente da mudança
$ws->enviaMsg($ws->enviaActions($mensagemW, 'finish', $agente->matricula, $atendimento->uniqueid));
return true;
} else {
$this->atendimentoModel->rollback();
$this->api->enviarMsg($numero, CONF_NAME_REPONSE . " : Erro ao finalizar!");
return true;
}
} catch (\Exception $th) {
$this->atendimentoModel->rollback();
$this->api->enviarMsg($numero, CONF_NAME_REPONSE . " : " . $th->getMessage());
return true;
}
}
private function cancelar($numero)
{
$atendimento = $this->atendimentoModel->getAtendimentoByCliente($numero, CONF_EVENT_ESPERA);
$ret = $this->eventosModel->createEvento(
$atendimento->uniqueid,
CONF_EVENT_ABANDONADA,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendimento->fila
);
if ($ret) {
//envia as mensagens do sistema do momento atual para o cliente
$this->systemController->sendMessageSystem(
CONF_MOMENT_CANCELAR_FILA,
[],
$this->api,
$numero
);
$filas = $this->queue->listAllQueueWhatsApp($this->api->getMessage());
if ($filas['LIST']) {
$this->api->enviarMsg($this->api->getPhone(), $filas['LIST']);
}
return true;
} else {
$this->api->enviarMsg($numero, CONF_NAME_REPONSE . " : Não foi possível cancelar o atendimento! " . $this->bilheteController->message());
return true;
}
}
}

69
integracao/media/app/Core/Connect.php

@ -0,0 +1,69 @@
<?php
namespace app\Core;
use PDO;
use PDOException;
/**
* Classe de Conexao com banco de dados.
*
* - Criar uma conexao de forma mais r<EFBFBD>pida.
* - Gerar logs da conexao.
* - Fazer consultas mais r<EFBFBD>pidas.
*
* @author Lucas Awade
*/
class Connect
{
/** @conexao */
private static $instance;
const FILE_DB = __DIR__ . "/../../bd";
public static function setInstance($val)
{
self::$instance = $val;
}
public static function getInstance()
{
$cd = [];
if (empty(self::$instance)) {
$cd = self::filedb();
self::$instance = new PDO(
"pgsql:host={$cd['host_db']};port={$cd['porta_db']};dbname={$cd['base_db']}",
$cd['usuario'],
$cd['senha'],
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_CASE => PDO::CASE_NATURAL
]
);
}
if (self::$instance) {
return self::$instance;
}
return null;
}
/**
* Pega as informacoes das credenciais no arquivos padrao "bd";
*/
private static function filedb()
{
if (file_exists(self::FILE_DB)) {
$credentials = array();
$contents = fopen(self::FILE_DB, 'r');
while (!feof($contents) && $contents) {
$str = fgets($contents);
$dados = explode('=', $str);
$credentials[strtolower($dados[0])] = trim(str_replace('"', '', $dados[1]));
}
fclose($contents);
$credentials = array_filter($credentials);
return $credentials;
}
}
}

24
integracao/media/app/Core/Controller.php

@ -0,0 +1,24 @@
<?php
namespace app\Core;
/**
* Description of Controller
*
* @author Lucas Awade
*/
abstract class Controller
{
const LOGGER_ACTIVE = true;
private $message;
public function message($message = null)
{
if (!$message) {
return $this->message;
}
$this->message = $message;
}
}

326
integracao/media/app/Core/CoreMedia.php

@ -0,0 +1,326 @@
<?php
namespace app\Core;
use app\Core\Commands;
use app\Models\Message;
use app\Providers\Crypt;
use app\Controllers\QueueController;
use app\Controllers\AgentController;
use app\Controllers\BilheteController;
use app\Controllers\SystemMessageController;
use app\Interfaces\IApiMedia;
use app\Models\Atendimento;
use app\Models\Evento;
use app\Models\ListaNegraPalavras;
use app\Models\SupervisorModel;
use websocket\WsInterface;
/**
* Description of WhatsApp
*
* @author Lucas Awade
*/
class CoreMedia
{
/** @var IApiMedia $api api do provedor de mensagens */
protected $api;
/** @var Commands $commands classe de comandos do sistema*/
protected $commands;
/** @var QueueController $queue controller da queue*/
protected $queue;
/** @var AgentController $agente controller do agente*/
protected $agente;
/** @var ListaNegraPalavras $palavroes model de palavras banida*/
protected $palavroes;
/** @var WsInterface $ws classe de comandos do sistema*/
protected $ws;
/** @var Atendimento $atendimento model de atendimentos*/
protected $atendimento;
/** @var SupervisorModel $supervisor model de supervisor*/
protected $supervisor;
/** @var Evento $eventos model de eventos*/
protected $eventos;
/** @var BilheteController $eventos controller dos bilhetess*/
protected $bilheteController;
/** @var Message $message model de mensagens*/
protected $message;
/** @var SystemMessageController $systemController controller de mensagens de sistema*/
protected $systemController;
/** @var Crypt $crypt core de criptografia*/
protected $crypt;
public function __construct()
{
$this->ws = new WsInterface();
$this->queue = new QueueController();
$this->commands = new Commands();
$this->agente = new AgentController();
$this->crypt = new Crypt();
$this->atendimento = new Atendimento();
$this->message = new Message();
$this->palavroes = new ListaNegraPalavras();
$this->supervisor = new SupervisorModel();
$this->eventos = new Evento();
$this->bilheteController = new BilheteController;
$this->systemController = new SystemMessageController();
}
public function setApi(IApiMedia $api)
{
$this->api = $api;
}
/**
* Send the file to the active contact
*
* @return null
*/
public function inicia($data, IApiMedia $providere)
{
/** Validate $data */
$this->api = $providere;
$this->build($data);
if (!$this->api->getIsValidMessage()) {
return null;
}
if (!$this->api->baixarMidia()) {
$this->api->enviarMsg($this->api->getPhone(), "Não foi possivel entregar o aquivo para o agente. Envie novamente!");
}
// VERIFICA SE ? UM COMANDO
if ($this->commands->isCommand($this->api)) {
return null;
}
//verifica se tem atendimento em aberto, se tiver ja manda msg para o agente via ws
$atendiment = $this->atendimento->findAtenEmAberto($this->api->getPhone());
if ($atendiment) {
$this->enviaMensagemAgente($atendiment);
return null;
}
//verifica se tem atendimento em espera, se tiver ja mostra a sua posi��o na fila
$atende = $this->atendimento->getAtendimentoByCliente($this->api->getPhone());
if (empty($atende)) {
$atende = $this->atendimento->getAtendimentoByCliente($this->api->getPhone(), CONF_EVENT_ERRO_ATEND);
}
if ($atende) {
$this->mostraPosiscaoNaFila($this->api->getPhone(), $atende->fila);
return null;
}
//verifica se o cliente escolheu uma fila caso não escolheu manda as filas
$filas = $this->queue->listAllQueueWhatsApp($this->api->getMessage());
if ($filas['LIST']) {
//manda as mensagens personalizada do moment CONF_MOMENT_SAUDACAO
$this->systemController->sendMessageSystem(
CONF_MOMENT_SAUDACAO,
[["nome" => "@cliente_name", "valor" => $this->api->getProfile()]],
$this->api,
$this->api->getPhone()
);
$this->api->enviarMsg($this->api->getPhone(), $filas['LIST']);
return null;
}
// cria a atendimento
$this->criaAtendimento($filas['QUEUE'], $this->api->getPhone());
}
/**
* Set variables class
* @param array $data
* @return boolean
*/
public function build($data)
{
$this->api->setHook($data);
$this->validaPalavroes();
}
public function validaPalavroes()
{
try {
$msg = $this->api->getMessage();
$palavras = $this->palavroes->getAll();
foreach ($palavras as $key => $value) {
$pattern = "/\b($value->palavra)\b/i";
$msg = preg_replace($pattern, '*' . str_repeat('*', strlen($value->palavra)) . '*', $msg);
}
$this->api->setMessage($msg);
} catch (\Exception $th) {
}
return;
}
public function criaAtendimento($fila, $numero, $uniqueid = null)
{
try {
if (empty($uniqueid)) {
$uniqueid = $this->atendimento->createAtendimento(null, $numero, 'E', $this->api->getchannel(), $this->api->getProfile());
if ($uniqueid) {
$this->eventos->createEvento($uniqueid, 'EMESPERA', date('Y-m-d H:i:s'), date('Y-m-d H:i:s'), $fila);
}
}
$agentes = $this->agente->infoAgentes($fila);
if (empty($agentes)) {
$this->systemController->sendMessageSystem(
CONF_MOMENT_ENTRAR_FILA_SEM,
[],
$this->api,
$numero,
$fila
);
return null;
}
$agent = $this->supervisor->findAgentByQueue($fila, 'LIVRE');
if (empty($agent)) {
$this->systemController->sendMessageSystem(
CONF_MOMENT_ENTRAR_FILA_COM,
[],
$this->api,
$numero,
$fila
);
$this->mostraPosiscaoNaFila($numero, $fila);
return null;
}
$retServe = $this->atendimento->updAtendimento($uniqueid, $agent[0]->matricula);
if (empty($retServe)) {
$this->api->enviarMsg(
$numero,
'Erro ao gerar atendimento!'
);
return null;
}
$protocol = $this->bilheteController->generateProtocol($uniqueid);
//cria o evento de inicio de atendimento e criar o protocolo
if ($protocol) {
$event = $this->eventos->getStatusAtendimento($uniqueid);
$retCria = $this->eventos->createEvento(
$uniqueid,
CONF_EVENT_START,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$fila,
$agent[0]->matricula
);
if (!empty($retCria) && $event->evento != CONF_EVENT_START) {
$atendimentosAbertos = $this->atendimento->getAtendimentoAbertoByAgente($agent[0]->matricula);
$sup = new SupervisorModel();
$param = $this->atendimento->getQuantiAtendimentSimultaneos();
$ws = new WsInterface();
if ((count($atendimentosAbertos)) >= $param->prm_media_simultaneo) {
$sup->updateAgent($agent[0]->matricula, CONF_AGENT_STATUS_OCUPADO);
}
$this->systemController->sendMessageSystem(
CONF_MOMENT_INICIAR_ATENDIMENTO,
[["nome" => "@agente_name", "valor" => utf8_encode($agent[0]->nome)]],
$this->api,
$numero,
$fila
);
$this->api->enviarMsg(
$numero,
"Número do protocolo do atendimento é $protocol\n"
);
try {
if ($event->evento == CONF_EVENT_ERRO_ATEND) {
$ws->enviaMsg($ws->enviaActions(
'Este atendimento foi realocado para sua responsabilidade.',
're_start',
$agent[0]->matricula,
$uniqueid
));
$this->message->addMessage(
$uniqueid,
$agent[0]->matricula,
$agent[0]->matricula,
're_start',
'Este atendimento foi realocado para sua responsabilidade.',
$agent[0]->nome,
$this->api->getchannel(),
'read'
);
} else {
$ws->enviaMsg($ws->enviaActions('Atendimento iniciado!', 'start', $agent[0]->matricula, $uniqueid));
}
} catch (\Exception $th) {
return $ws->enviaActions('Atendimento iniciado!', 'start', $agent[0]->matricula, $uniqueid);
}
}
}
return;
} catch (\Exception $th) {
logger('criaAtendimento')->info($th->getMessage());
return;
}
}
public function mostraPosiscaoNaFila($numero, $fila)
{
$clientfila = $this->queue->clientQueueVerify($numero, $fila);
if ($clientfila['MESSAGE']) {
$this->api->enviarMsg($numero, $clientfila['MESSAGE']);
return null;
}
}
public function retornaConteudo()
{
switch ($this->api->getType()) {
case 'text':
return $this->api->getMessage();
case 'image':
case 'sticker':
case 'video':
case 'voice':
case 'audio':
case 'document':
return $this->api->getId();
case 'contacts':
return null;
case 'location':
return null;
}
}
function enviaMensagemAgente($atendiment)
{
$this->message->addMessage(
$atendiment->uniqueid,
$this->api->getPhone(),
$atendiment->matricula,
$this->api->getType(),
$this->retornaConteudo(),
empty($this->api->getProfile()) ? '' : $this->api->getProfile(),
$this->api->getchannel(),
"sended",
$this->api->getMimetype(),
$this->api->retornaTituloDocument(),
$this->api->getId()
);
$this->ws->enviaMsg(
$this->ws->convertToWebsocket(
$this->retornaConteudo(),
$atendiment->matricula,
$atendiment->uniqueid,
$this->api->getType(),
$this->api->getProfile(),
$this->api->getPhone(),
time(),
$this->api->getId(),
$this->api->getMimetype(),
$this->api->retornaTituloDocument(),
$this->api->getchannel()
)
);
}
}

120
integracao/media/app/Core/Model.php

@ -0,0 +1,120 @@
<?php
namespace app\Core;
use app\Core\Connect;
use PDO;
use PDOException;
/**
* Description of WppModel
*
* @author Lucas Awade
*/
abstract class Model
{
protected $query;
protected function strquery($stmt, $params)
{
foreach ($params as $key => $value) {
if (is_null($value) || (is_string($value) && $value == '')) {
$value = null;
}
$stmt->bindValue(":{$key}", $value, (is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR));
}
}
public function begin()
{
try {
Connect::getInstance()->beginTransaction();
return 1;
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
public function commit()
{
try {
Connect::getInstance()->commit();
return 1;
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
public function rollback()
{
try {
Connect::getInstance()->rollBack();
return 1;
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
protected function create($query, $data)
{
try {
$stmt = Connect::getInstance()->prepare($query);
$this->strquery($stmt, $data);
$stmt->execute();
return Connect::getInstance()->lastInsertId();
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
protected function read($query, $data = null)
{
try {
$stmt = Connect::getInstance()->prepare($query);
$this->strquery($stmt, $data);
$stmt->execute();
return $stmt;
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
protected function delete($query, $data)
{
try {
$stmt = Connect::getInstance()->prepare($query);
$this->strquery($stmt, $data);
$stmt->execute();
return ($stmt->rowCount() ? 1 : 0);
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
protected function update($query, $data)
{
try {
$stmt = Connect::getInstance()->prepare($query);
$this->strquery($stmt, $data);
$stmt->execute();
return ($stmt->rowCount() ? 1 : 0);
} catch (PDOException $ex) {
Connect::setInstance(null);
logger('PDOExcep')->error('PDOException: ' . $ex->getMessage(), debug_backtrace());
return null;
}
}
}

9
integracao/media/app/Interfaces/IApi.php

@ -0,0 +1,9 @@
<?php
namespace app\Interfaces;
interface IApi
{
function router($rota, $request);
function retorno($mensagem, $status = null, $dados = null);
}

29
integracao/media/app/Interfaces/IApiMedia.php

@ -0,0 +1,29 @@
<?php
namespace app\Interfaces;
interface IApiMedia
{
function getchannel();
function getContentType();
function enviarMedia($whatsapp, $link, $type, $titulo = null);
function enviarMsg($whatsapp, $mensagem, $encode = true);
function enviarMsgIterativaLista($whatsapp, $mensagem, $nomeButton, $sections);
function enviarMsgIterativaBotao($whatsapp, $mensagem, $buttons);
function enviarContato($whatsapp, $nome, $contato);
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null);
function baixarMidia();
function getProfile();
function getPhone();
function getType();
function getMimetype();
function getId();
function getIsValidMessage();
function getMessage();
function setMessage($msg);
function getContactFormatted();
function getContactPhone();
function getGeolocation($type);
function setHook($hook);
function retornaTituloDocument();
}

743
integracao/media/app/Middleware/ApiAgente.php

@ -0,0 +1,743 @@
<?php
namespace app\Middleware;
use app\Controllers\AgentController;
use app\Controllers\ClassificacaoController;
use app\Controllers\QueueController;
use app\Controllers\SystemMessageController;
use app\Interfaces\IApi;
use app\Models\Atendimento;
use app\Models\Evento;
use app\Models\ListaNegraPalavras;
use app\Models\Message;
use app\Models\Parametros;
use app\Models\Pause;
use app\Models\Queue;
use app\Models\SupervisorModel;
use websocket\WsInterface;
class ApiAgente implements IApi
{
/** @var AgentController $agentController Controller do agente */
protected $agentController;
/** @var ClassificacaoController $classificacao Controller do classificacao */
protected $classificacao;
/** @var SupervisorModel $supervisor model do supervisor */
protected $supervisor;
/** @var Atendimento $atendimento model do atendimento */
protected $atendimento;
/** @var Evento $eventos model do Evento */
protected $eventos;
/** @var Parametros $parametros model do Parametros */
protected $parametros;
/** @var Pause $pausasModel model do Pause */
protected $pausasModel;
public function __construct()
{
$this->classificacao = new ClassificacaoController();
$this->agentController = new AgentController();
$this->supervisor = new SupervisorModel();
$this->atendimento = new Atendimento();
$this->eventos = new Evento();
$this->pausasModel = new Pause();
$this->parametros = new Parametros();
}
function router($rota, $request)
{
$request = json_decode($request, true);
switch ($rota) {
case 'entrar':
$this->login($request);
break;
case 'listarFilas':
$this->listaFilas($request);
break;
case 'classificarAtendimento':
$this->classificarAtendimento($request);
break;
case 'enviarMensagem':
$this->enviaMsg($request);
break;
case 'sair':
$this->logoff($request);
break;
case 'listarAgentesDisponivel':
$this->listaAgentesDisponivel();
break;
case 'finalizarAtendimento':
$this->finalizaAtendimento($request);
break;
case 'listarAtendimentoAgente':
$this->listaAtendimentoAgent($request);
break;
case 'listarMensagem':
$this->listaMensagem($request);
break;
case 'listarPausasAgente':
$this->listaPausasAgente($request);
break;
case 'sairPausa':
$this->saiPausa($request);
break;
case 'entrarPausa':
$this->entrarPausa($request);
break;
case 'transferirAtendimento':
$this->transfAtendimento($request);
break;
case 'marcarMensagemVista':
$this->markMessegeRead($request);
break;
case 'statusAgente':
$this->statusAgente($request);
break;
case 'listarAtendimentosFilas':
$this->listarAtendimentosFilas($request);
break;
case 'listarAtendimentosAbandonado':
$this->listarAtendimentosAbandonado($request);
break;
default:
echo json_encode(['status' => '404']);
break;
}
}
function login($request)
{
try {
$agente = $this->supervisor->findByAgent($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$filaModel = new Queue();
$fila = $filaModel->findQueueById($request['id_fila']);
if (empty($fila)) {
$this->retorno("Fila não encontrada");
return;
}
$ret = $this->agentController->login(
$fila->nome,
$request['matricula']
);
if (is_string($ret)) {
$this->retorno($ret);
return;
}
$this->retorno(
$ret ? "Logado com sucesso" : "Erro",
$ret ? $ret : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function logoff($request, $valida = true)
{
try {
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
$atends = $this->atendimento->getAtendimentoAbertoByAgente($request['matricula']);
if (!$valida) {
foreach ($atends as $key => $atendimento) {
$this->sinalisaErroAtendimento(
$request['matricula'],
$atendimento->uniqueid,
$agente->fila,
$atendimento->cliente_id
);
}
}
if (!empty($atends) && $valida) {
$this->retorno("Atendimentos em aberto, finalize os atendimentos para fazer logoff");
return;
}
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$ret = $this->agentController->logoff(
$request['matricula'],
$valida
);
if (is_string($ret)) {
$this->retorno($ret);
return;
}
$this->retorno(
$ret ? "Deslogado com sucesso" : "Erro",
$ret ? $ret : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function listaAgentesDisponivel()
{;
try {
$param = $this->atendimento->getQuantiAtendimentSimultaneos();
$ret = $this->supervisor->listaAgentesDisponivel('LIVRE');
$agentes = [];
foreach ($ret as $key => $value) {
if ($value->countAtendimentos < $param->prm_media_simultaneo) {
array_push($agentes, $value);
}
}
$this->retorno(
$agentes ? "Sucesso" : "Nenhum agente disponivel",
$agentes ? $agentes : null,
$agentes ? $agentes : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function finalizaAtendimento($request)
{
try {
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
logger('debug')->info(var_export($agente, true));
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$atendimento = $this->atendimento->findAtendId($request['uniqueid']);
//verifica se existe atendimento
if (empty($atendimento)) {
$this->retorno("Atendimento não encontrado");
return;
}
$event = $this->eventos->findEventFinish($request['uniqueid']);
//verifica se o atendimento ja foi finalizado
if (!empty($event)) {
$this->retorno("Atendimento já foi finalizado");
return;
}
$ret = $this->eventos->createEvento(
$request['uniqueid'],
CONF_EVENT_TIMERMINO_AGENTE,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendimento->fila,
$request['matricula']
);
$ws = new WsInterface();
$mesg = "Atendimento finalizado pelo agente {$agente->nome}";
$ws->enviaMsg($this->enviaActions($mesg, 'finish', $agente->matricula, $request['uniqueid']));
$systemController = new SystemMessageController();
$provedor = returnChannel($atendimento->context);
$systemController->sendMessageSystem(
CONF_MOMENT_FINALIZAR_ATENDIMENTO,
[["nome" => "@autor_name", "valor" => $agente->nome]],
$provedor,
$atendimento->cliente_id
);
$messegeModel = new Message();
$messegeModel->addMessage(
$request['uniqueid'],
$agente->matricula,
$agente->matricula,
'finish',
$mesg,
$agente->nome,
$atendimento->context,
'read'
);
if ($agente->status == CONF_AGENT_STATUS_INDISPONIVEL) {
$atends = $this->atendimento->getAtendimentoAbertoByAgente($request['matricula']);
if (empty($atends)) {
$this->agentController->enterPause($request['matricula'], $agente->motivo_pausa);
$ws->enviaMsg($this->enviaActions('Agente em pausa', 'att_status', $agente->matricula, $request['uniqueid']));
}
}
if ($agente->status == CONF_AGENT_STATUS_OCUPADO) {
$atendimentosAbertos = $this->atendimento->getAtendimentoAbertoByAgente($agente->matricula);
$param = $this->atendimento->getQuantiAtendimentSimultaneos();
if (count($atendimentosAbertos) < $param->prm_media_simultaneo) {
$this->supervisor->updateAgent($agente->matricula, CONF_AGENT_STATUS_LIVRE);
}
}
$this->retorno(
$ret ? "Finalizado com sucesso" : "Erro",
$ret ? $ret : null,
$ret ? [$ret] : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function sinalisaErroAtendimento($matricula, $uniqueid, $fila, $client_id)
{
try {
$ret = $this->eventos->createEvento(
$uniqueid,
CONF_EVENT_ERRO_ATEND,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$fila,
$matricula
);
$atendimento = $this->atendimento->findAtendId($uniqueid);
$systemController = new SystemMessageController();
$provedor = returnChannel($atendimento->context);
$systemController->sendMessageSystem(
CONF_MOMENT_ERRO_ATEND,
[],
$provedor,
$client_id,
$fila
);
$this->retorno(
$ret ? "Finalizado com sucesso" : "Erro",
$ret ? $ret : null,
$ret ? ["id" => $ret] : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
public function listaFilas()
{
$queue = new QueueController();
$search = $queue->listaAllFilas();
$this->retorno(
$search ? "Sucesso" : "Erro",
$search ? $search : null,
$search ? $search : null
);
return null;
}
public function classificarAtendimento($request)
{
$agent = $this->agentController->getAgente($request['ramal']);
if (!$agent) {
$msg = "Faça o login para iniciar o atendimento!\n";
echo json_encode(['message' => $msg]);
return null;
}
/**
* VERIFICA CLASSIFICACAO DE ATENDIMENTO
*/
$chamadaSemClassificacao = $this->classificacao->agentClassificacaoPending($agent->matricula, $agent->dac);
if ($chamadaSemClassificacao) {
$classificacaoRegisterReturn = $this->classificacao->agentClassificacaoRegister(
$agent->matricula,
$agent->dac,
$chamadaSemClassificacao,
$request['option']
);
if ($classificacaoRegisterReturn) {
echo json_encode(['message' => CONF_NAME_REPONSE . " : " . $this->classificacao->message()]);
return null;
}
$classificacaoList = $this->classificacao->agentClassificacaoList($agent->dac);
echo json_encode(['message' => CONF_NAME_REPONSE . " : " . $classificacaoList]);
return null;
}
echo json_encode(['status' => "false"]);
return null;
}
public function enviaMsg($request)
{
try {
$mensagem = $request['event']['mensagem'];
$contact = $request['event']['contact'];
$status = $this->atendimento->getStatusAtendimento($mensagem['uniqueid']);
if ($status->evento == CONF_EVENT_START) {
$provider = returnChannel($mensagem['media']);
$modelMensagem = new Message();
$msgTexto = $contact['name'] . ': ' . $this->validaPalavroes($mensagem['content']);
if ($mensagem['type'] == 'text') {
$retuno = $provider->enviarMsg(
$mensagem['dst'],
$msgTexto,
false
);
} else {
$anmeArquivo = CONF_PATH_FILES . $mensagem['id_provedor'];
$texto = base64_decode($mensagem['content']);
file_put_contents($anmeArquivo, $texto);
ConvertWavToMp3($anmeArquivo);
$retuno = $provider->enviarMedia(
$mensagem['dst'],
CONF_MIDDLEWARE_LINKUPLOAD .
$mensagem['id_provedor'] . '/' .
base64_encode($mensagem['mimetype']),
$mensagem['type'],
$mensagem['file_name']
);
}
$modelMensagem->addMessage(
$mensagem['uniqueid'],
$contact['number'],
$mensagem['dst'],
$mensagem['type'],
$mensagem['type'] == 'text' ? $msgTexto : $mensagem['id_provedor'],
$contact['name'],
$mensagem['media'],
$mensagem['status'],
$mensagem['mimetype'],
$mensagem['file_name'],
$mensagem['id_provedor']
);
$this->retorno(
$retuno ? "Sucesso" : "Erro",
$retuno ? $retuno : null,
$retuno ? [["message" => $retuno]] : null
);
} else {
$this->retorno('Atendimento já foi finalizado');
}
return;
} catch (\Exception $th) {
$this->retorno($th->getMessage());
return;
}
}
function retorno($mensagem, $status = null, $dados = null)
{
//{ "status": "success", "message": "register created!", "data": [ "id": 20 ] }
$data = [];
$data['message'] = utf8_encode($mensagem);
if (!empty($status)) {
$data['status'] = "success";
} else {
$data['status'] = "error";
}
if (!empty($dados)) {
$data['data'] = $dados;
}
echo json_encode($data);
}
function listaAtendimentoAgent($request)
{
try {
if ($request['matricula']) {
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
}
$ret = $this->atendimento->findAtendAgent($request['matricula'], $request['quantidade']);
$data = [];
$data['message'] = utf8_encode("Sucesso");
$data['status'] = "success";
$data['data'] = $ret;
echo json_encode($data);
return null;
} catch (\Exception $th) {
$this->retorno($th->getMessage());
return;
}
}
function listaMensagem($request)
{
try {
$atend = $this->atendimento->findAtendId($request['uniqueid']);
//verifica se existe agente
if (empty($atend)) {
$this->retorno("Não existe atendimento para esse uniqueid");
return;
}
$messageModel = new Message();
$retunr = $messageModel->findMessageByUniqueid($request['uniqueid']);
$mensagenss = [];
foreach ($retunr as $key => $value) {
$mensagem = [];
$mensagem["event"] = [
"type" => $value->type == 'finish' ? 'actions' : "mensagem",
"contact" => [
"name" => utf8_encode($value->profile_name),
"number" => $value->src,
],
"mensagem" => [
"type" => $value->type,
"content" => $value->content,
"id_provedor" => $value->id_provedor,
"dst" => $value->dst,
"uniqueid" => $value->uniqueid,
"media" => $value->media,
"file_name" => utf8_encode($value->file_name),
"datetime" => $value->msg_date,
"status" => $value->status,
'mimetype' => $value->mimetype
]
];
array_push($mensagenss, $mensagem);
}
$data = [];
$data['message'] = utf8_encode("Sucesso");
$data['status'] = "success";
$data['data'] = $mensagenss;
echo json_encode($data);
return;
} catch (\Exception $th) {
$this->retorno($th->getMessage());
return;
}
}
function listaPausasAgente($request)
{
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return null;
}
$param = $this->parametros->findProtocolByParams();
if (false) {
$ret = $this->pausasModel->findPauseByGroupUser($request['matricula']);
} else {
$ret = $this->pausasModel->findAllPause();
}
foreach ($ret as $key => $value) {
$ret[$key] = removeAcentosArray((array) $value);
}
$this->retorno(
$ret ? "Sucesso" : "Erro",
$ret ? $ret : null,
$ret ? $ret : null
);
return null;
}
function entrarPausa($request)
{
$ws = new WsInterface();
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$pausa = $this->pausasModel->findPauseById($request['id_pausa']);
if (empty($pausa)) {
$this->retorno("Pausa não encontrado");
return;
}
if ($agente->status == CONF_AGENT_STATUS_PAUSA || $agente->status == CONF_AGENT_STATUS_INDISPONIVEL) {
$this->retorno('Agente precisa estar livre para entrar em pausa!');
return;
}
$atends = $this->atendimento->getAtendimentoAbertoByAgente($request['matricula']);
if (!empty($atends)) {
$ret = $this->agentController->indisponivelAtendimento($request['matricula'], $pausa->motivo);
if (is_string($ret)) {
$this->retorno($ret);
} else {
$ws->enviaMsg($this->enviaActions('Agente em pausa', 'att_status', $agente->matricula));
$this->retorno(
"Agente em 'indisponivel'",
$ret
);
}
return;
}
$ret = $this->agentController->enterPause($request['matricula'], $pausa->motivo);
$ws->enviaMsg($this->enviaActions('Agente em pausa', 'att_status', $agente->matricula));
$this->retorno(
$ret ? "Agente em 'pausa'" : "Erro",
$ret ? $ret : null
);
return null;
}
function saiPausa($request)
{
$ws = new WsInterface();
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$ret = $this->agentController->exitPause($request['matricula']);
if (is_string($ret)) {
$this->retorno($ret);
} else {
$ws->enviaMsg($this->enviaActions('Agente em pausa', 'att_status', $agente->matricula));
$this->retorno(
"Agente 'livre'",
$ret
);
}
return;
}
function transfAtendimento($request)
{
$retunr = $this->agentController->transfer(
$request['matricula_origem'],
$request['matricula_destino'],
$request['uniqueid']
);
if (is_string($retunr)) {
$this->retorno($retunr);
} else {
$this->retorno(
$retunr ? "Sucesso" : "Erro",
$retunr ? $retunr : null
);
}
return null;
}
function markMessegeRead($request)
{
$atend = $this->atendimento->findAtendId($request['uniqueid']);
//verifica se existe agente
if (empty($atend)) {
$this->retorno("Não existe atendimento para esse uniqueid");
return;
}
$modelMensagem = new Message();
$ret = $modelMensagem->markMessege($request['uniqueid'], 'read');
$this->retorno(
$ret ? "Sucesso" : "Erro",
$ret ? $ret : null
);
return null;
}
function statusAgente($request)
{
try {
$agente = $this->supervisor->findAgentByMatricula($request['matricula']);
//verifica se existe agente
if (empty($agente)) {
$this->retorno("Agente não encontrado");
return;
}
$this->supervisor->updateAgent($agente->matricula, $agente->status, $agente->motivo_pausa);
$ret = $this->supervisor->statusAgente($request['matricula']);
$ret = removeAcentosArray((array) $ret);
$this->retorno(
$ret ? "Sucesso" : "Erro",
$ret ? $ret : null,
$ret ? [$ret] : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
}
function enviaActions($msg, $tipo, $destino, $uniqueid = null)
{
try {
$mensagem = [];
$mensagem["event"] = [
"type" => 'actions',
"contact" => [
"name" => 'Sistema',
"number" => '0'
],
"mensagem" => [
"type" => $tipo,
"dst" => $destino,
"uniqueid" => $uniqueid,
"content" => utf8_encode($msg)
],
];
return json_encode($mensagem);
} catch (\Exception $th) {
logger('monitora')->info($th->getMessage());
}
}
public function validaPalavroes($msg)
{
try {
$palavroes = new ListaNegraPalavras();
$palavras = $palavroes->getAll();
foreach ($palavras as $key => $value) {
$pattern = "/\b($value->palavra)\b/i";
$msg = preg_replace($pattern, '*' . str_repeat('*', strlen($value->palavra)) . '*', $msg);
}
} catch (\Exception $th) {
logger('telegram')->info(print_r($th, true), true);
}
return $msg;
}
public function listarAtendimentosFilas($request)
{
try {
$filaModel = new Queue();
$fila = $filaModel->findQueueById($request['id_fila']);
if (empty($fila)) {
$this->retorno("Fila não encontrada");
return;
}
$retunr = $this->atendimento->getAtendFila($fila->nome);
$data = [];
$data['message'] = utf8_encode("Sucesso");
$data['status'] = "success";
$data['data'] = $retunr;
echo json_encode($data);
return null;
} catch (\Exception $th) {
return $this->retorno($th->getMessage());
}
}
public function listarAtendimentosAbandonado($request)
{
try {
$filaModel = new Queue();
if ($request['id_fila']) {
$fila = $filaModel->findQueueById($request['id_fila']);
if (empty($fila)) {
$this->retorno("Fila não encontrada");
return;
}
}
$retunr = $this->atendimento->getAtendAbandonado($fila->nome);
$data = [];
$data['message'] = utf8_encode("Sucesso");
$data['status'] = "success";
$data['data'] = $retunr;
echo json_encode($data);
return null;
} catch (\Exception $th) {
return $this->retorno($th->getMessage());
}
}
}

39
integracao/media/app/Middleware/ApiInfo.php

@ -0,0 +1,39 @@
<?php
namespace app\Middleware;
use app\Interfaces\IApi;
class ApiInfo implements IApi
{
function router($rota, $request)
{
$this->showConf();
}
function retorno($mensagem, $status = null, $dados = null)
{
//{ "status": "success", "message": "register created!", "data": [ "id": 20 ] }
$data = [];
$data['message'] = utf8_encode($mensagem);
if (!empty($status)) {
$data['status'] = "success";
} else {
$data['status'] = "error";
}
if (!empty($dados)) {
$data['data'] = $dados;
}
echo json_encode($data);
}
function showConf()
{
$dados['version_system'] = INFO_VERSION_SYSTEM;
$dados['conf_db_host'] = CONF_DB_HOST;
$dados['conf_db_port'] = CONF_DB_PORT;
$dados['conf_middleware_redirect'] = CONF_MIDDLEWARE_REDIRECT;
$this->retorno('Sucesso', "success", [$dados]);
}
}

129
integracao/media/app/Middleware/ApiSupervisor.php

@ -0,0 +1,129 @@
<?php
namespace app\Middleware;
use app\Controllers\QueueController;
use app\Controllers\SystemMessageController;
use app\Interfaces\IApi;
use app\Interfaces\IApiMedia;
use app\Models\Atendimento;
use app\Models\Evento;
use app\Models\SupervisorModel;
class ApiSupervisor implements IApi
{
/** @var SupervisorModel $supervisor model de supervisor */
protected $supervisor;
/** @var Atendimento $atendimentoModel model de supervisor */
protected $atendimentoModel;
/** @var Evento $eventosModel model de evento */
protected $eventosModel;
/** @var QueueController $queue controller da queue*/
protected $queue;
/** @var SystemMessageController $systemController controller da queue*/
protected $systemController;
/** @var IApiMedia $api provider de mensagens */
protected $api;
public function __construct()
{
$this->eventosModel = new Evento();
$this->atendimentoModel = new Atendimento();
$this->supervisor = new SupervisorModel();
$this->queue = new QueueController();
$this->systemController = new SystemMessageController();
}
function router($rota, $request)
{
$request = json_decode($request, true);
switch ($rota) {
case 'listarAgentesDisponivel':
$this->listaAgentesDisponivel();
break;
case 'removerAtendimentoFila':
$this->removerAtendimentoFila($request);
break;
default:
echo json_encode(['status' => '404']);
break;
}
}
function listaAgentesDisponivel()
{
try {
$ret = $this->supervisor->listaAgentesDisponivel();
$agentes = [];
foreach ($ret as $key => $value) {
array_push($agentes, $value);
}
$this->retorno(
$agentes ? "Sucesso" : "Nenhum agente disponivel",
$agentes ? $agentes : null,
$agentes ? $agentes : null
);
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function removerAtendimentoFila($request)
{
try {
$atendimento = $this->atendimentoModel->findAtendId($request['uniqueid']);
logger()->error(print_r($request, true));
$this->api = returnChannel($atendimento->context);
$ret = $this->eventosModel->createEvento(
$atendimento->uniqueid,
CONF_EVENT_ABANDONADA,
date('Y-m-d H:i:s'),
date('Y-m-d H:i:s'),
$atendimento->fila
);
if ($ret) {
//envia as mensagens do sistema do momento atual para o cliente
$this->systemController->sendMessageSystem(
CONF_MOMENT_CANCELAR_FILA,
[],
$this->api,
$atendimento->cliente_id
);
$filas = $this->queue->listAllQueueWhatsApp($this->api->getMessage());
if ($filas['LIST']) {
$this->api->enviarMsg($atendimento->cliente_id, $filas['LIST']);
}
$this->retorno(
$ret ? "Sucesso" : "Erro",
$ret ? $ret : null,
);
} else {
$this->retorno("Não foi possível cancelar o atendimento!");
}
} catch (\Exception $th) {
$this->retorno($th->getMessage());
}
return null;
}
function retorno($mensagem, $status = null, $dados = null)
{
//{ "status": "success", "message": "register created!", "data": [ "id": 20 ] }
$data = [];
$data['message'] = utf8_encode($mensagem);
if (!empty($status)) {
$data['status'] = "success";
} else {
$data['status'] = "error";
}
if (!empty($dados)) {
$data['data'] = $dados;
}
echo json_encode($data);
}
}

39
integracao/media/app/Middleware/Http.php

@ -0,0 +1,39 @@
<?php
namespace app\Middleware;
/**
* Description of Http
*
* @author Lucas Awade
*/
class Http
{
private $url;
private $param;
const CONF_PAGE = 'index.php';
public function __construct()
{
$this->baseUri();
}
public function param()
{
return $this->param;
}
public function baseUri()
{
$this->url = explode(self::CONF_PAGE, $_SERVER['PHP_SELF']);
$this->url = end($this->url);
if ($this->url) {
$this->url = explode("/", $this->url);
if (isset($this->url[0])) {
$this->param = array_filter($this->url);
}
}
}
}

155
integracao/media/app/Middleware/Middleware.php

@ -0,0 +1,155 @@
<?php
namespace app\Middleware;
use app\Core\CoreMedia;
use app\Middleware\Http;
use app\Middleware\ApiAgente;
use app\Providers\Positus;
use app\Providers\WebHeader;
use app\Providers\Whatsapp;
/**
* Description of WppController
*
* @author Lucas Awade
*/
class Middleware extends Http
{
/** @var array request */
private $request;
/** @class WebHeader */
private $header;
/** @var String local downloads image|document|video|sticker|audio */
private $link;
public function __construct($config = null)
{
$this->link = $config['LINK_UPLOAD'];
$this->header = new WebHeader($config);
$this->api();
$this->hook();
}
/**
* Start API headers
* @param array $config
*/
public function api($contentType = "application/json; charset=UTF-8")
{
$this->header->API($contentType);
}
/**
* Redirect request to media Social
* @return null
*/
private function router()
{
$coremedia = new CoreMedia();
$this->baseUri();
switch (strtolower($this->param()[1])) {
case 'whatsapp':
$provedor = returnChannel('whatsapp');
$coremedia->inicia($this->request, $provedor);
$this->api($provedor->getContentType());
echo '';
return null;
case 'api':
$this->api();
switch ($this->param()[2]) {
case 'agente':
$apiAgente = new ApiAgente();
$apiAgente->router($this->param()[3], $this->request);
return null;
case 'supervisor':
$apiSupervisor = new ApiSupervisor();
$apiSupervisor->router($this->param()[3], $this->request);
return null;
default:
echo 'erro';
}
case 'link':
$this->api();
$this->header->fileTransfer($this->param()[2], CONF_PATH_FILES . $this->param()[2], base64_decode($this->param()[3]));
exit(0);
case 'info':
$this->api();
$apiInfo = new ApiInfo();
$apiInfo->router($this->param()[3], $this->request);
exit(0);
default:
$this->header->redirect();
exit(0);
}
}
/**
* Read input requests
*/
private function hook()
{
$this->request = file_get_contents('php://input');
$this->router();
}
/**
* Create file and download in browser
*/
private function download($file = null)
{
if ($file) {
$this->header->fileTransfer($this->param()[3], $file, base64_decode($this->param()[4]));
exit(0);
}
if ($this->param()[3] && $this->param()[4]) {
return ["FILE" => strtolower($this->param()[3]), "MIMETYPE" => $this->param()[4]];
} else {
return null;
}
}
########################################################################
##### FUNCTION UTIL #####
########################################################################
private function formatLink()
{
$link = str_split($this->link);
if (strpos($this->link, 'http://') === false && strpos($this->link, 'http://') === false) {
$this->link = "http://" . $this->link;
}
if (end($link) != "/") {
$this->link .= "/";
}
}
########################################################################
##### FUNCTION CLASS #####
########################################################################
/**
* Set new link download
* @param string $link
*/
public function setLink($link)
{
$this->link = $link;
$this->formatLink();
}
/**
* Get link download
* @return string
*/
public function getLink()
{
$this->formatLink();
return $this->link;
}
}

222
integracao/media/app/Models/Agent.php

@ -0,0 +1,222 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Clase para criacao de Querys no banco de dados.
*
* Todas as querys desta classe esta especificada para o uso do WhatsApp.
*
* @author Lucas Awade
*/
class Agent extends Model
{
const USUARIOS = "pbx_usuarios";
const SUPERVISOR_AGENTE = "pbx_supervisor_agentes";
const EVENTO_AGENTE = 'pbx_eventos_agentes';
const BILHETE = 'pbx_bilhetes';
const EVENTOS_DACS = 'pbx_eventos_dacs';
public function findByNumber($number)
{
$this->query = "SELECT CASE WHEN(origem_destino = '$number') THEN 'CLIENT' ELSE 'AGENT' END AS phone, * "
. "FROM " . self::SUPERVISOR_AGENTE . " WHERE (origem_destino = :number OR ramal = :number)";
return $this->read($this->query, ['number' => $number])->fetch();
}
public function findAllAgentes($media = ['TELEGRAM', 'whatsapp'], $queue = null)
{
$data = [];
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE 1=1 ";
$this->query .= sprintf(" AND sala_1 in(%s) ", whereIn($media));
if ($queue) {
$this->query .= " AND dac = :queue ";
$data['queue'] = $queue;
}
$ret = $this->read($this->query, $data);
if ($ret) {
return $ret->fetchAll();
} else {
return [];
}
}
public function findByAgent($user)
{
$this->query = "SELECT * FROM " . self::USUARIOS . " WHERE apelido = :apelido;";
return $this->read($this->query, ['apelido' => $user])->fetch();
}
public function findAgentByRamal($ramal)
{
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE ramal = :ramal;";
return $this->read($this->query, ['ramal' => $ramal])->fetch();
}
public function findAgentByMatricula($matricula)
{
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE matricula = :matricula;";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findAgentByQueue($queue, $status = 'LIVRE', $orderBy = null, $orderByType = 'ASC')
{
$data = [];
$this->query = "SELECT ramal, b.matricula, b.nome, b.apelido, penalidade, (logado - duracao) as tempo_livre,
(SELECT count(*) AS atendimentos
FROM " . self::BILHETE . " ab
INNER JOIN " . self::EVENTOS_DACS . " bc ON ab.uniqueid = bc.uid2
WHERE bc.fila = a.dac
AND bc.agente = a.matricula
AND bc.evento IN(:evento)
AND ab.data_bilhete = 'now')
FROM " . self::SUPERVISOR_AGENTE . " a
INNER JOIN " . self::USUARIOS . " b ON a.matricula = b.matricula
WHERE upper(a.dac) = upper(:queue)
AND a.status = upper(:status) ";
$data['queue'] = $queue;
$data['status'] = $status;
$data['evento'] = implode(',', [
CONF_EVENT_TIMERMINO_CLIENTE,
CONF_EVENT_TIMERMINO_AGENTE
]);
if ($orderBy && $orderByType) {
$this->query .= " ORDER BY $orderBy $orderByType;";
}
return $this->read($this->query, $data)->fetchAll();
}
########################################
### SUPERVISOR AGENTE ###
########################################
public function addAgent($matricula, $ramal, $login, $queue, $media, $chamada_classificado = 1)
{
$this->query = "INSERT INTO " . self::SUPERVISOR_AGENTE . "
(ramal, matricula, nome, tempo_login, modo_atendimento, dac, status, duracao, logado, status_time, disponivel_atendimento, sala_1, chamada_classificado)
VALUES(:ramal, :matricula, :login, :tempo_login, :modo_atendimento, :queue, :status, :duracao, :logado, :status_time, :disponivel_atendimento, :media, :chamada_classificado);";
return $this->create($this->query, [
'matricula' => $matricula,
'ramal' => $ramal,
'login' => $login,
'tempo_login' => 'now()',
'modo_atendimento' => 'Manual',
'queue' => $queue,
'status' => 'LIVRE',
'duracao' => 'now()',
'logado' => 'now()',
'status_time' => 'now()',
'disponivel_atendimento' => 1,
'media' => $media,
'chamada_classificado' => $chamada_classificado
]);
}
public function updateAgent($matricula, $ramal, $status = 'LIVRE', $origemDestino = null, $motivoPausa = null, $duracao = null, $uniqueid = null, $chamada_classificado = 1)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET logado = :logado, origem_destino = :origem_destino, status = :status, motivo_pausa = :motivo_pausa, uniqueid = :uniqueid, chamada_classificado = :chamada_classificado";
if ($duracao) {
$this->query .= ", duracao = :duracao ";
}
$this->query .= " WHERE matricula = :matricula AND ramal = :ramal;";
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
$data['logado'] = 'now()';
$data['duracao'] = 'now()';
$data['origem_destino'] = $origemDestino;
$data['status'] = $status;
$data['motivo_pausa'] = $motivoPausa;
$data['uniqueid'] = $uniqueid;
$data['chamada_classificado'] = ($chamada_classificado ? '1' : '0');
return $this->update($this->query, $data);
}
public function updateRefreshAgent($matricula, $ramal, $duracao = false)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET logado = :logado ";
if ($duracao) {
$this->query .= ", duracao = :duracao ";
$data['duracao'] = 'now()';
}
$this->query .= " WHERE matricula = :matricula AND ramal = :ramal;";
$data['logado'] = 'now()';
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
public function updateSala2Agent($matricula, $ramal, $sala2 = null)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET sala_2 = :sala_2 WHERE matricula = :matricula AND ramal = :ramal;";
$data['sala_2'] = $sala2;
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
public function deleteAgent($matricula, $ramal)
{
$data = [];
$this->query = "DELETE FROM " . self::SUPERVISOR_AGENTE . " WHERE matricula = :matricula AND ramal = :ramal;";
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
return $this->delete($this->query, $data);
}
public function updateLogadoAll($media = null)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET logado = :logado ";
if ($media) {
$this->query .= " WHERE sala_1 = :sala_1; ";
}
$data['logado'] = 'now()';
$data['sala_1'] = $media;
return $this->update($this->query, $data);
}
########################################
### EVENTOS ###
########################################
public function addEventoLoginAgent($matricula, $ramal, $idDac, $flag = 1)
{
$data = [];
$this->query = "INSERT INTO " . self::EVENTO_AGENTE . "(matricula, ramal, login, logoff, id_dac, flag) VALUES(:matricula, :ramal, :login, :logoff, :id_dac, :flag) ";
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
$data['login'] = 'now()';
$data['logoff'] = 'now()';
$data['id_dac'] = $idDac;
$data['flag'] = $flag;
return $this->create($this->query, $data);
}
public function updateEventoLogoffAgent($matricula, $ramal, $dac, $flag = 2)
{
$data = [];
$this->query = "UPDATE " . self::EVENTO_AGENTE . " SET logoff = :logoff, flag = :flag "
. "WHERE matricula = :matricula AND id_dac = :id_dac AND ramal = :ramal "
. "AND login = (SELECT MAX(login) FROM pbx_eventos_agentes WHERE matricula = :matricula AND id_dac = :id_dac AND ramal= :ramal);";
$data['logoff'] = 'now()';
$data['flag'] = $flag;
$data['matricula'] = $matricula;
$data['id_dac'] = $dac;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
}

182
integracao/media/app/Models/Atendimento.php

@ -0,0 +1,182 @@
<?php
namespace app\Models;
use app\Core\Connect;
use app\Core\Model;
class Atendimento extends Model
{
private $evento = 'md_evento';
private $atendimento = 'md_atendimento';
public function getAtendimentoByCliente($cliente_id, $evento = 'EMESPERA')
{
$this->query = "SELECT ma.*, me.fila as fila FROM {$this->atendimento} ma
INNER JOIN {$this->evento} me
ON ma.uniqueid = me.uniqueid
WHERE ma.cliente_id = :cliente_id
AND (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = :evento";
return $this->read($this->query, ['cliente_id' => $cliente_id, 'evento' => $evento])->fetch();
}
public function getStatusAtendimento($uniqueid)
{
$this->query = "SELECT evento FROM md_evento WHERE uniqueid = :uniqueid ORDER BY id DESC LIMIT 1";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function findAtendId($uniqueid)
{
$this->query = "SELECT ma.*, me.fila as fila FROM {$this->atendimento} ma
INNER JOIN {$this->evento} me
ON ma.uniqueid = me.uniqueid
WHERE ma.uniqueid = :uniqueid ";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function getAtendimentoByEvento($fila, $evento = 'EMESPERA')
{
$this->query = "SELECT ma.* FROM {$this->atendimento} ma
INNER JOIN {$this->evento} me
ON ma.uniqueid = me.uniqueid
WHERE (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = :evento
AND me.fila = :fila";
return $this->read($this->query, ['evento' => $evento, 'fila' => $fila])->fetchAll();
}
public function findAtendAgent($matricula, $quantidade = 10)
{
$data = [];
$this->query = "SELECT ma.*,
ma.nome AS profile_name,
ppr.protocolo as protocolo,
(SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) AS evento,
CASE
WHEN (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = 'START' THEN 1
ELSE 0
END AS status
FROM {$this->atendimento} ma
INNER JOIN pbx_protocolo_reg ppr ON ma.uniqueid = ppr.uniqueid ";
if ($matricula) {
$this->query .= " WHERE ma.matricula = :matricula ";
$data['matricula'] = $matricula;
}
if (empty($quantidade)) {
$data['quantidade'] = 10;
} else {
$data['quantidade'] = $quantidade;
}
$this->query .= " ORDER BY status DESC, data_reg DESC
LIMIT :quantidade ";
return $this->read($this->query, $data)->fetchAll();
}
public function findAtenEmAberto($cliente_id = null)
{
$this->query = "SELECT ma.* FROM {$this->atendimento} ma
WHERE (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = 'START'
AND ma.matricula notnull ";
$data = [];
if ($cliente_id) {
$data['cliente_id'] = $cliente_id;
$this->query .= 'AND ma.cliente_id = :cliente_id';
return $this->read($this->query, $data)->fetch();
}
return $this->read($this->query, $data)->fetchAll();
}
public function getAtendimentoAbertoByAgente($matricula)
{
$this->query = "SELECT ma.* FROM {$this->atendimento} ma
WHERE (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = 'START'
AND ma.matricula = :matricula ";
return $this->read($this->query, ['matricula' => $matricula])->fetchAll();
}
// public function getAtendFila($fila, $evento = 'LOST_CONNECTION')
// {
// $this->query = "SELECT ma.*, me.fila as fila FROM {$this->atendimento} ma
// INNER JOIN {$this->evento} me
// ON ma.uniqueid = me.uniqueid
// WHERE me.evento = :evento
// AND me.fila = :fila
// AND (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = 'LOST_CONNECTION' ";
// return $this->read($this->query, ['evento' => $evento, 'fila' => $fila])->fetchAll();
// }
public function getAtendFila($fila)
{
$this->query = "SELECT ma.*, me.fila as fila FROM {$this->atendimento} ma
INNER JOIN {$this->evento} me
ON ma.uniqueid = me.uniqueid
AND me.evento IN('EMESPERA', 'LOST_CONNECTION')
WHERE me.fila = :fila
AND (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) IN('EMESPERA', 'LOST_CONNECTION') ";
return $this->read($this->query, ['fila' => $fila])->fetchAll();
}
public function getAtendAbandonado($fila = null)
{
$data = [];
$this->query = "SELECT ma.*, me.fila as fila FROM {$this->atendimento} ma
INNER JOIN {$this->evento} me
ON ma.uniqueid = me.uniqueid
AND me.evento = 'ABANDON'
WHERE (SELECT m2.evento FROM md_evento m2 WHERE ma.uniqueid = m2.uniqueid ORDER BY id DESC LIMIT 1) = 'ABANDON'
AND ma.data_reg >= CURRENT_DATE ";
if ($fila) {
$this->query .= ' AND me.fila = :fila';
$data['fila'] = $fila;
}
return $this->read($this->query, $data)->fetchAll();
}
public function createAtendimento($matricula, $cliente_id, $direcao, $context, $nome)
{
$unique = uniqid('', true);
$this->query = "INSERT INTO {$this->atendimento} (
matricula,
cliente_id,
direcao,
uniqueid,
context,
nome)
VALUES(
:matricula,
:cliente_id,
:direcao,
:uniqueid,
:context,
:nome);";
$data['uniqueid'] = $unique;
$data['matricula'] = $matricula;
$data['cliente_id'] = $cliente_id;
$data['direcao'] = $direcao;
$data['context'] = $context;
$data['nome'] = $nome;
$return = $this->create($this->query, $data);
if ($return) {
return $unique;
}
return $return;
}
public function updAtendimento($uniqueid, $matricula)
{
$this->query = "UPDATE {$this->atendimento} SET matricula = :matricula WHERE uniqueid = :uniqueid;";
$data['matricula'] = $matricula;
$data['uniqueid'] = $uniqueid;
return $this->update($this->query, $data);
}
public function getQuantiAtendimentSimultaneos()
{
$this->query = "SELECT prm_media_simultaneo FROM pbx_parametros LIMIT 1";
return $this->read($this->query)->fetch();
}
}

103
integracao/media/app/Models/Bilhete.php

@ -0,0 +1,103 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Bilhete
*
* @author root
*/
class Bilhete extends Model
{
const TABLE = "pbx_bilhetes";
const EVENTOS_DACS = 'pbx_eventos_dacs';
public function addBilhete($calldate, $src, $dst, $duration, $billsec, $disposition, $unique = null, $forahorario = 0)
{
if ($unique == null) {
$unique = uniqid('', true);
}
$this->query = "INSERT INTO " . self::TABLE . " (uniqueid, calldate, src, dst, duration, billsec, disposition, fora_horario, data_bilhete) VALUES(:uniqueid, :calldate, :src, :dst, :duration, :billsec, :disposition, :fora_horario, :data_bilhete);";
$data['uniqueid'] = $unique;
$data['calldate'] = $calldate;
$data['src'] = $src;
$data['dst'] = $dst;
$data['duration'] = $duration;
$data['billsec'] = abs($billsec);
$data['disposition'] = $disposition;
$data['fora_horario'] = $forahorario;
$data['data_bilhete'] = date('Y-m-d H:i:s');
$return = $this->create($this->query, $data);
if ($return) {
return $unique;
}
return $return;
}
public function findByUniqueid($uniqueid)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE uniqueid = :uniqueid";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function findBilheteByEventosDacs($queue = null, $dataBilhete = 'now', $eventos = ['COMPLETEAGENT', 'COMPLETECALLER', 'COMPLETAAGENT', 'COMPLETACALLER', 'TRANSFER', 'ABANDON'], $agente = null, $media)
{
$this->query = "SELECT * FROM " . self::TABLE . " a
INNER JOIN " . self::EVENTOS_DACS . " b ON a.uniqueid = b.uid2
WHERE 1=1 AND evento IN(:evento) ";
$data['evento'] = is_array($eventos) ? implode(",", $eventos) : $eventos;
if ($queue) {
$this->query .= " AND b.fila = :queue ";
$data['queue'] = $queue;
}
if ($dataBilhete) {
$this->query .= " AND data_bilhete = :data_bilhete ";
$data['data_bilhete'] = $dataBilhete;
}
if ($media) {
$this->query .= " AND param2 = :param2 ";
$data['param2'] = $media;
}
if ($agente) {
$this->query .= " AND b.agente = :agente ";
$data['agente'] = $agente;
}
$this->query .= " ORDER BY calldate";
return $this->read($this->query, $data)->fetchAll();
}
public function findBilheteBySrc($src, $eventos = ['COMPLETEAGENT', 'COMPLETECALLER', 'COMPLETAAGENT', 'COMPLETACALLER', 'TRANSFER', 'ABANDON'])
{
$this->query = "SELECT * FROM " . self::TABLE . " a
INNER JOIN " . self::EVENTOS_DACS . " b ON a.uniqueid = b.uid2
WHERE 1=1 ";
$this->query .= " AND a.src = :src ";
$this->query .= " AND evento IN(:evento) ";
$this->query .= " ORDER BY calldate";
$data['src'] = $src;
$data['evento'] = is_array($eventos) ? implode(",", $eventos) : $eventos;
return $this->read($this->query, $data)->fetch();
}
public function updateBilheteForaHorario($uniqueid, $ramalorigem, $forahorario, $disposition)
{
$this->query = "UPDATE " . self::TABLE . " SET disposition = :disposition, fora_horario = :fora_horario, ramal_origem = :ramal_origem WHERE uniqueid = :uniqueid;";
$data['disposition'] = $disposition;
$data['fora_horario'] = $forahorario;
$data['ramal_origem'] = $ramalorigem;
$data['uniqueid'] = $uniqueid;
return $this->update($this->query, $data);
}
}

49
integracao/media/app/Models/Classificacao.php

@ -0,0 +1,49 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Classificacao
*
* @author root
*/
class Classificacao extends Model
{
const CLASSIFICACAO_ATT = "pbx_classifica_atendimento";
const CLASSIFICACAO_ITEM = "pbx_classifica_item";
const CLASSIFICACAO_DACS = "pbx_classifica_dacs";
const CLASSIFICACAO_REG = "pbx_classifica_reg";
const QUEUE_GROUPOS = "pbx_queues_grupos";
public function findClassificacaoRegByUniqueid($uniqueid)
{
$this->query = "SELECT * FROM " . self::CLASSIFICACAO_REG . " WHERE id_bilhetes = :id_bilhetes;";
return $this->read($this->query, ['id_bilhetes' => $uniqueid])->fetch();
}
public function findClassificacaoByQueue($queue)
{
$this->query = "SELECT pca.clas_descricao, pca.clas_id, pci2.clit_id, pci2.clit_descricao, pcd.id_dac FROM " . self::CLASSIFICACAO_ATT . " pca
INNER JOIN " . self::CLASSIFICACAO_ITEM . " pci2 ON pci2.clas_id = pca.clas_id
INNER JOIN " . self::CLASSIFICACAO_DACS . " pcd ON pcd.clas_id = pca.clas_id
INNER JOIN " . self::QUEUE_GROUPOS . " pqg ON pcd.id_dac = pqg.id
WHERE pqg.nome = :queue ;";
return $this->read($this->query, ['queue' => $queue])->fetchAll();
}
public function addClassificacaoReg($matricula, $clas_id, $clit_id, $id_bilhetes, $id_dac)
{
$this->query = "INSERT INTO " . self::CLASSIFICACAO_REG . "
(matricula, clas_id, clit_id, id_bilhetes, id_dac)
VALUES(:matricula, :clas_id, :clit_id, :id_bilhetes, :id_dac)";
$data['matricula'] = $matricula;
$data['clas_id'] = $clas_id;
$data['clit_id'] = $clit_id;
$data['id_bilhetes'] = $id_bilhetes;
$data['id_dac'] = $id_dac;
return $this->create($this->query, $data);
}
}

63
integracao/media/app/Models/EventQueue.php

@ -0,0 +1,63 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of EventQueue
*
* @author root
*/
class EventQueue extends Model
{
const TABLE = 'pbx_eventos_dacs';
public function findEventQueueByAgent($agente, $queue = false)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE agente = :agente ";
if ($queue) {
$this->query .= " AND fila = :queue ";
$data['queue'] = $queue;
}
$this->query .= " ORDER BY uid1 DESC LIMIT 1 ";
$data['agente'] = $agente;
return $this->read($this->query, $data)->fetch();
}
public function findEventQueueByParam2($uniqueid)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE param2 = :param2 ";
return $this->read($this->query, ['param2' => $uniqueid])->fetch();
}
public function addEventQueue($uniqueid, $queue, $agent, $event, $media)
{
$this->query = "INSERT INTO " . self::TABLE . " (uid1, uid2, fila, agente, evento, param2) VALUES(:uid1, :uid2, :fila, :agente, :evento, :param2);";
$data['uid1'] = time();
$data['uid2'] = $uniqueid;
$data['fila'] = $queue;
$data['agente'] = $agent;
$data['evento'] = $event;
$data['param2'] = $media;
return $this->create($this->query, $data);
}
public function updateEventQueue($uniqueid, $queue, $agent, $event, $param1 = null, $param2 = null)
{
$this->query = "UPDATE " . self::TABLE . " SET fila = :fila, agente = :agente, evento = :evento, param1 = :param1, param2 = :param2 WHERE uid2 = :uid2;";
return $this->update($this->query, ['fila' => $queue, 'agente' => $agent, 'evento' => $event, 'param1' => $param1, 'param2' => $param2, 'uid2' => $uniqueid]);
}
public function findAllEventByAwait($queue)
{
$this->query = "SELECT * FROM " . self::TABLE . "
WHERE evento = :evento
AND fila = :fila ";
return $this->read($this->query, ['fila' => $queue, 'evento' => CONF_EVENT_ESPERA]);
}
}

50
integracao/media/app/Models/Evento.php

@ -0,0 +1,50 @@
<?php
namespace app\Models;
use app\Core\Model;
class Evento extends Model
{
private $evento = 'md_evento';
public function createEvento($uniqueid, $evento, $data_evento, $data_reg, $fila = null, $matricula = null)
{
$this->query = "INSERT INTO {$this->evento} (uniqueid,
evento,
data_evento,
data_reg,
fila,
matricula )
VALUES(:uniqueid,
:evento,
:data_evento,
:data_reg,
:fila,
:matricula );";
$data['uniqueid'] = $uniqueid;
$data['evento'] = $evento;
$data['data_evento'] = $data_evento;
$data['data_reg'] = $data_reg;
$data['fila'] = $fila;
$data['matricula'] = $matricula;
$return = $this->create($this->query, $data);
return $return;
}
public function findEventFinish($uniqueid)
{
$this->query = "SELECT * FROM {$this->evento}
WHERE uniqueid = :uniqueid
AND evento in ('COMPLETE_AGENT', 'COMPLETE_AGENT');";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function getStatusAtendimento($uniqueid)
{
$this->query = "SELECT evento FROM {$this->evento} WHERE uniqueid = :uniqueid ORDER BY id DESC LIMIT 1";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
}

21
integracao/media/app/Models/ListaNegraPalavras.php

@ -0,0 +1,21 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of NotificaMedia
*
* @author root
*/
class ListaNegraPalavras extends Model
{
const table = "pbx_lista_negra_palavras";
public function getAll()
{
$this->query = "SELECT * FROM " . self::table;
return $this->read($this->query)->fetchAll();
}
}

85
integracao/media/app/Models/Message.php

@ -0,0 +1,85 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Message
*
* @author root
*/
class Message extends Model
{
const MESSAGE = "md_message";
public function addMessage($uniqueid, $src, $dst, $tipo, $content, $profile_name, $media, $status, $mimetype = null, $file_name = null, $id_provedor = null)
{
if ($uniqueid) {
$this->query = "INSERT INTO " . self::MESSAGE . " (uniqueid, src, dst, type, content, profile_name, media, status, mimetype, file_name, id_provedor)
VALUES(:uniqueid, :src, :dst, :type, :content, :profile_name, :media, :status, :mimetype, :file_name, :id_provedor);";
return $this->create($this->query, [
'uniqueid' => $uniqueid,
'src' => $src,
'dst' => $dst,
'type' => $tipo,
'content' => $content,
'profile_name' => utf8_decode($profile_name),
'media' => $media,
'status' => $status,
'id_provedor' => $id_provedor,
'file_name' => $file_name,
'mimetype' => $mimetype
]);
} else {
logger('debug')->info(print_r([
'uniqueid' => $uniqueid,
'src' => $src,
'dst' => $dst,
'type' => $tipo,
'content' => $content,
'profile_name' => utf8_decode($profile_name),
'media' => $media,
'status' => $status,
'id_provedor' => $id_provedor,
'file_name' => $file_name,
'mimetype' => $mimetype
], true));
return null;
}
}
public function findMessageByUniqueid($uniqueid)
{
$this->query = "SELECT * FROM " . self::MESSAGE . " WHERE uniqueid = :uniqueid ORDER BY id";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetchAll();
}
public function findMessageByNumber($number)
{
$this->query = "SELECT * FROM " . self::MESSAGE . " WHERE (src = :number OR dst = :number) ORDER BY msg_date ASC, uniqueid ";
return $this->read($this->query, ['number' => $number])->fetchAll();
}
public function findLastMessage($uniqueid)
{
$this->query = "SELECT * FROM " . self::MESSAGE . " WHERE uniqueid = :uniqueid ";
$this->query .= " ORDER BY msg_date DESC LIMIT 1";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function markMessege($uniqueid, $status)
{
$this->query = "UPDATE " . self::MESSAGE . " SET status = :status WHERE uniqueid = :uniqueid;";
$data['uniqueid'] = $uniqueid;
$data['status'] = $status;
return $this->update($this->query, $data);
}
public function getNameCliente($uniqueid, $cliente_id)
{
$this->query = "SELECT profile_name FROM md_message mm WHERE uniqueid = :uniqueid AND src = :cliente_id LIMIT 1";
return $this->read($this->query, ['uniqueid' => $uniqueid, 'cliente_id' => $cliente_id])->fetch();
}
}

46
integracao/media/app/Models/NotificaMedia.php

@ -0,0 +1,46 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of NotificaMedia
*
* @author root
*/
class NotificaMedia extends Model
{
const table = "pbx_notifica_media";
public function verificaNotifica($uniqueid, $src, $msg)
{
$this->query = "SELECT count(*) as quant FROM " .
self::table .
" WHERE uniqueid = :uniqueid and src = :src and msg = :msg";
return $this->read(
$this->query,
[
'uniqueid' => $uniqueid,
'src' => $src,
'msg' => $msg
]
)->fetch();
}
public function addNotifica($uniqueid, $src, $msg)
{
$data = [
'uniqueid' => $uniqueid,
'src' => $src,
'msg' => $msg,
];
$this->query = "INSERT INTO " . self::table . " (uniqueid, src, msg) VALUES(:uniqueid, :src, :msg);";
logger('notificacao')->error(print_r($data, true));
return $this->create(
$this->query,
$data
);
}
}

22
integracao/media/app/Models/Parametros.php

@ -0,0 +1,22 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of EventQueue
*
* @author root
*/
class Parametros extends Model
{
const TABLE = 'pbx_parametros';
public function findProtocolByParams()
{
$this->query = "SELECT prm_agente_proto, prm_use_proto_parceiro, prm_pausa_grupo, prm_media_simultaneo FROM " . self::TABLE . " WHERE id = :id;";
return $this->read($this->query, ['id' => 1])->fetch();
}
}

112
integracao/media/app/Models/Pause.php

@ -0,0 +1,112 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Pause
*
* @author Lucas Awade
*/
class Pause extends Model
{
const TABLE = "pbx_motivos_pausas";
const EVENTO_AGENTE = 'pbx_eventos_agentes';
public function findPauseByName($name)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE upper(motivo) = :name ";
return $this->read($this->query, ['name' => strtoupper($name)])->fetch();
}
public function findPauseById($id)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE id = :id";
return $this->read($this->query, ['id' => strtoupper($id)])->fetch();
}
public function addEventoPauseAgent($matricula, $ramal, $idMotivo, $idDac, $produtiva, $flag = 1)
{
$this->query = "INSERT INTO " . self::EVENTO_AGENTE . " (matricula, ramal, id_dac, id_motivo_pausa, flag, pausa_produtiva, entrada_pausa, saida_pausa)
VALUES(:matricula, :ramal, :id_dac, :id_motivo_pausa, :flag, :pausa_produtiva, :entrada_pausa, :saida_pausa);";
return $this->create(
$this->query,
[
'matricula' => $matricula,
'ramal' => $ramal,
'id_dac' => $idDac,
'id_motivo_pausa' => $idMotivo,
'flag' => $flag,
'pausa_produtiva' => $produtiva,
'entrada_pausa' => 'now()',
'saida_pausa' => 'now()'
]
);
}
public function addEventoIndisponivelAgent($matricula, $ramal, $idDac)
{
$this->query = "INSERT INTO " . self::EVENTO_AGENTE . " (matricula, ramal, id_dac, entrada_indisponivel, saida_indisponivel)
VALUES(:matricula, :ramal, :id_dac, :entrada_indisponivel, :saida_indisponivel);";
return $this->create(
$this->query,
[
'matricula' => $matricula,
'ramal' => $ramal,
'id_dac' => $idDac,
'entrada_indisponivel' => 'now()',
'saida_indisponivel' => 'now()'
]
);
}
public function updateEventoOutPause($matricula, $dac, $flag = 2)
{
$this->query = "UPDATE " . self::EVENTO_AGENTE . " SET saida_pausa = :saida_pausa, flag = :flag WHERE matricula = :matricula AND id_dac = :id_dac
AND entrada_pausa = (SELECT MAX(entrada_pausa) FROM " . self::EVENTO_AGENTE . " WHERE matricula = :matricula AND id_dac = :id_dac);";
return $this->update($this->query, ['saida_pausa' => 'now()', 'flag' => $flag, 'matricula' => $matricula, 'id_dac' => $dac]);
}
public function findGroupPause()
{
$this->query = "SELECT prm_pausa_grupo FROM pbx_parametros";
return $this->read($this->query)->fetchAll();
}
public function findPauseByGroupUser($matricula, $active = true)
{
$this->query = "SELECT DISTINCT d.id, d.motivo, d.produtiva, d.flag, d.tempo_alerta
FROM pbx_usuarios a
INNER JOIN pbx_grupo_usuario b ON a.id = b.user_id
INNER JOIN pbx_pausa_grupo_usuario c ON c.gp_id = b.gp_id
INNER JOIN pbx_motivos_pausas d ON d.id = c.id
WHERE matricula = :matricula
AND d.motivo NOT IN('login','ausente','RECUSADA') ";
if ($active) {
$this->query .= " AND d.flag = :flag";
$data['flag'] = 1;
}
$data['matricula'] = $matricula;
return $this->read($this->query, $data)->fetchAll();
}
public function findAllPause($active = true)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE 1=1 ";
if ($active) {
$this->query .= " AND flag = :flag ";
$data['flag'] = 1;
}
$this->query .= " AND motivo NOT IN('login','ausente','RECUSADA') LIMIT 10 ";
return $this->read($this->query, $data)->fetchAll();
}
public function findAgentPause($matricula)
{
$this->query = "SELECT status, motivo_pausa FROM pbx_supervisor_agentes WHERE matricula = :matricula;";
return $this->read($this->query, ['matricula' => $matricula])->fetchAll();
}
}

29
integracao/media/app/Models/Protocol.php

@ -0,0 +1,29 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of EventQueue
*
* @author root
*/
class Protocol extends Model {
const TABLE = 'pbx_protocolo_reg';
public function findProtocol($uniqueid){
$this->query = "SELECT ano::text || '-' || lpad(numproto::text,6,'0') as protocolo, protoparceiro FROM " . self::TABLE . " WHERE uniqueid = :uniqueid;";
return $this->read($this->query, ['uniqueid' => $uniqueid])->fetch();
}
public function findMaxProtocol($year){
$this->query = "SELECT MAX(numProto) AS protocolo FROM " . self::TABLE . " WHERE ano = :ano";
return $this->read($this->query, ['ano' => $year])->fetch();
}
public function insert($uniqueId, $year, $numProto, $proto, $protoParceiro){
$this->query = "INSERT INTO " . self::TABLE . "(uniqueid, ano, numProto, protocolo, protoparceiro) VALUES(:uniqueid, :ano, :numProto, :protocolo, :protoparceiro);";
return $this->create($this->query, ['uniqueid' => $uniqueId , 'ano' => $year, 'numProto' => $numProto, 'protocolo' => $proto, 'protoparceiro' => $protoParceiro]);
}
}

53
integracao/media/app/Models/Queue.php

@ -0,0 +1,53 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Clase para criacao de Querys no banco de dados.
*
* Todas as querys desta classe esta especificada para o uso do WhatsApp.
*
* @author Lucas Awade
*/
class Queue extends Model
{
const TABLE = "pbx_queues_grupos";
public function findAllQueue($active = true)
{
$this->query = "SELECT id, nome FROM " . self::TABLE . " WHERE 1=1 AND midiafila = :midiafila ";
if ($active) {
$this->query .= " AND status = :status ";
$data['status'] = 'A';
}
$data['midiafila'] = "S";
$this->query .= " ORDER BY nome LIMIT 10 ";
return $this->read($this->query, $data)->fetchAll();
}
public function findQueueByName($nome, $active = true)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE nome = :nome ";
if ($active) {
$this->query .= " AND status = :status ";
$data['status'] = 'A';
}
$data['nome'] = $nome;
return $this->read($this->query, $data)->fetch();
}
public function findQueueById($id, $active = true)
{
$this->query = "SELECT * FROM " . self::TABLE . " WHERE id = :id ";
if ($active) {
$this->query .= " AND status = :status ";
$data['status'] = 'A';
}
$data['id'] = $id;
return $this->read($this->query, $data)->fetch();
}
}

22
integracao/media/app/Models/Ramal.php

@ -0,0 +1,22 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Ramal
*
* @author Lucas Awade
*/
class Ramal extends Model
{
const TABLE = 'pbx_sip_ramais';
public function findRamal($ramal)
{
$this->query = "SELECT * FROM " . self::TABLE . " pr WHERE pr.nome = :ramal;";
return $this->read($this->query, ['ramal' => $ramal])->fetch();
}
}

408
integracao/media/app/Models/SupervisorModel.php

@ -0,0 +1,408 @@
<?php
namespace app\Models;
use app\Core\Model;
class SupervisorModel extends Model
{
const USUARIOS = "pbx_usuarios";
const SUPERVISOR_AGENTE = "md_supervisor";
const EVENTO_AGENTE = 'pbx_eventos_agentes';
const BILHETE = 'pbx_bilhetes';
const EVENTOS_DACS = 'pbx_eventos_dacs';
private $supervisor = 'md_supervisor';
private $atendimento = 'md_atendimento';
public function listaAgentesDisponivel($status = null, $somenteLivre = true)
{
$data = [];
$this->query = " SELECT *,
(
SELECT
count(*)
FROM
md_atendimento ma
WHERE 'START' = (SELECT m2.evento FROM md_evento m2
WHERE ma.uniqueid = m2.uniqueid
ORDER BY m2.id DESC LIMIT 1)
AND ma.matricula = ms.matricula
) AS countAtendimentos,
(
SELECT
count(*)
FROM
md_atendimento ma
WHERE ma.data_reg >= current_date
AND ma.matricula = ms.matricula
) AS numero_atendimento_dia
FROM md_supervisor ms
WHERE 1=1
";
if ($somenteLivre) {
$this->query .= " AND (
SELECT
count(*)
FROM
md_atendimento ma
WHERE 'START' = (SELECT m2.evento FROM md_evento m2
WHERE ma.uniqueid = m2.uniqueid
ORDER BY m2.id DESC LIMIT 1)
AND ma.matricula = ms.matricula
) < (SELECT prm_media_simultaneo FROM pbx_parametros pp LIMIT 1 )";
}
if ($status) {
$this->query .= " AND ms.status = :status ";
$data['status'] = $status;
}
$this->query .= " ORDER BY countAtendimentos ";
return $this->read($this->query, $data)->fetchAll();
}
public function statusAgente($matricula)
{
$this->query = "SELECT
*,
(
SELECT
count(*)
FROM
md_atendimento ma
WHERE 'START' = (SELECT m2.evento FROM md_evento m2
WHERE ma.uniqueid = m2.uniqueid
ORDER BY m2.id DESC LIMIT 1)
AND ma.matricula = ms.matricula
) AS numero_atendimento
FROM
md_supervisor ms
WHERE ms.matricula = :matricula ";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findByMatricula($matricula)
{
//Codigo acrescentado para não permitir logar o agente no chat e pabx simultaneamente.
$this->query = "SELECT matricula from ( SELECT matricula FROM " . self::SUPERVISOR_AGENTE
. " UNION "
. " SELECT matricula FROM pbx_supervisor_agentes ) AS agt WHERE (matricula = :matricula)";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findAllAgentes($queue = null)
{
$data = [];
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE 1=1 ";
if ($queue) {
$this->query .= " AND fila = :queue ";
$data['queue'] = $queue;
}
return $this->read($this->query, $data)->fetchAll();
}
public function findAllAgentesPBX($queue = null, $media = null)
{
$data = [];
$this->query = "SELECT * FROM pbx_supervisor_agentes WHERE 1=1 ";
if ($queue) {
$this->query .= " AND fila = :queue ";
$data['queue'] = $queue;
}
if($media){
$this->query .= " AND media <> :media";
$data['media'] = $media;
}
return $this->read($this->query, $data)->fetchAll();
}
public function findByAgent($matricula)
{
$this->query = "SELECT * FROM " . self::USUARIOS . " WHERE matricula = :matricula;";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findAgentByRamal($ramal)
{
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE ramal = :ramal;";
return $this->read($this->query, ['ramal' => $ramal])->fetch();
}
public function findAgentByMatricula($matricula)
{
$this->query = "SELECT * FROM " . self::SUPERVISOR_AGENTE . " WHERE matricula = :matricula;";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findAgentByMatriculaPbx($matricula)
{
$this->query = "SELECT * FROM pbx_supervisor_agentes WHERE matricula = :matricula;";
return $this->read($this->query, ['matricula' => $matricula])->fetch();
}
public function findAgentByQueue($queue, $status)
{
$data = [];
$this->query = "SELECT *
FROM md_supervisor ms
WHERE ms.fila = :queue
AND ms.status = :status
ORDER BY (
SELECT
count(*)
FROM
md_atendimento ma
WHERE 'START' = (SELECT m2.evento FROM md_evento m2
WHERE ma.uniqueid = m2.uniqueid
ORDER BY m2.id DESC LIMIT 1)
AND ma.matricula = ms.matricula
)
";
$data['queue'] = $queue;
$data['status'] = $status;
return $this->read($this->query, $data)->fetchAll();
}
########################################
### SUPERVISOR AGENTE ###
########################################
public function addAgent($matricula, $fila, $nome, $chamada_classificado = 1)
{
$this->query = "INSERT INTO " . self::SUPERVISOR_AGENTE . "
(
matricula,
tempo_login,
fila,
status,
duracao,
chamada_classificado,
nome
)
VALUES(
:matricula,
:tempo_login,
:fila,
:status,
:duracao,
:chamada_classificado,
:nome
);";
return $this->create($this->query, [
'matricula' => $matricula,
'tempo_login' => 'now()',
'fila' => $fila,
'status' => 'LIVRE',
'duracao' => 'now()',
'nome' => $nome,
'chamada_classificado' => $chamada_classificado
]);
}
public function addAgent2(
$nome,
$matricula,
$ramal,
$dac,
$tempo_login,
$status = 'LIVRE',
$motivoPausa = null,
$origemDestino = null,
$media = 1,
$modo_atendimento = 'Automatico',
$chamada_classificado = 1
) {
$data = [];
$this->query = "INSERT INTO pbx_supervisor_agentes (
tempo_login,
nome,
ramal,
matricula,
origem_destino,
status,
motivo_pausa,
chamada_classificado,
modo_atendimento,
dac,
duracao,
logado,
media) VALUES(
:tempo_login,
:nome,
:ramal,
:matricula,
:origem_destino,
:status,
:motivo_pausa,
:chamada_classificado,
:modo_atendimento,
:dac,
:duracao,
:logado,
:media) ";
$data['tempo_login'] = $tempo_login;
$data['nome'] = $nome;
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
$data['duracao'] = 'now()';
$data['logado'] = 'now()';
$data['dac'] = $dac;
$data['origem_destino'] = $origemDestino;
$data['status'] = $status;
$data['motivo_pausa'] = $motivoPausa;
$data['media'] = $media;
$data['modo_atendimento'] = $modo_atendimento;
$data['chamada_classificado'] = ($chamada_classificado ? '1' : '0');
return $this->create($this->query, $data);
}
public function updateAgent(
$matricula,
$status = 'LIVRE',
$motivo_pausa = null
) {
$this->query = "UPDATE {$this->supervisor} SET status = :status, motivo_pausa = :motivo_pausa, duracao = :duracao";
$this->query .= " WHERE matricula = :matricula";
$data = [];
$data['status'] = $status;
$data['motivo_pausa'] = $motivo_pausa;
$data['matricula'] = $matricula;
$data['duracao'] = 'now()';
// logger('teste')->debug(print_r($data, true), true);
return $this->update($this->query, $data);
}
public function updateAgent2(
$matricula,
$ramal,
$dac,
$status = 'LIVRE',
$atualizaDuracao = false,
$motivoPausa = null,
$origemDestino = null,
$disponivel_atendimento = 1
) {
$data = [];
$this->query = "UPDATE pbx_supervisor_agentes SET
origem_destino = :origem_destino,
status = :status,
motivo_pausa = :motivo_pausa,
dac = :dac,
ramal = :ramal,
logado = :logado,
disponivel_atendimento = :disponivel_atendimento ";
if ($atualizaDuracao) {
$data['duracao'] = 'now()';
$this->query .= " , duracao = :duracao";
}
$this->query .= " WHERE matricula = :matricula";
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
$data['dac'] = $dac;
$data['origem_destino'] = $origemDestino;
$data['status'] = $status;
$data['logado'] = 'now()';
$data['motivo_pausa'] = $motivoPausa;
$data['disponivel_atendimento'] = $disponivel_atendimento;
return $this->update($this->query, $data);
}
public function updateRefreshAgent($matricula, $ramal, $duracao = false)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET logado = :logado ";
if ($duracao) {
$this->query .= ", duracao = :duracao ";
$data['duracao'] = 'now()';
}
$this->query .= " WHERE matricula = :matricula AND ramal = :ramal;";
$data['logado'] = 'now()';
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
public function updateSala2Agent($matricula, $ramal, $sala2 = null)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET sala_2 = :sala_2 WHERE matricula = :matricula AND ramal = :ramal;";
$data['sala_2'] = $sala2;
$data['matricula'] = $matricula;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
public function deleteAgentPbx($matricula, $media = null, $oper = '=')
{
$data = [];
$this->query = "DELETE FROM pbx_supervisor_agentes WHERE matricula = :matricula ";
if($media){
$this->query .= "AND media {$oper} :media ";
$data['media'] = $media;
}
$data['matricula'] = $matricula;
return $this->delete($this->query, $data);
}
public function deleteAgent($matricula)
{
$data = [];
$this->query = "DELETE FROM " . self::SUPERVISOR_AGENTE . " WHERE matricula = :matricula";
$data['matricula'] = $matricula;
return $this->delete($this->query, $data);
}
public function updateLogadoAll($media = null)
{
$data = [];
$this->query = "UPDATE " . self::SUPERVISOR_AGENTE . " SET logado = :logado ";
if ($media) {
$this->query .= " WHERE sala_1 = :sala_1; ";
}
$data['logado'] = 'now()';
$data['sala_1'] = $media;
return $this->update($this->query, $data);
}
########################################
### EVENTOS ###
########################################
public function addEventoLoginAgent($matricula, $idDac, $flag = 1, $ramal)
{
$data = [];
$this->query = "INSERT INTO " . self::EVENTO_AGENTE . "(matricula, login, logoff, id_dac, flag, ramal) VALUES(:matricula, :login, :logoff, :id_dac, :flag, :ramal) ";
$data['matricula'] = $matricula;
$data['login'] = 'now()';
$data['logoff'] = 'now()';
$data['id_dac'] = $idDac;
$data['flag'] = $flag;
$data['ramal'] = $ramal;
return $this->create($this->query, $data);
}
public function updateEventoLogoffAgent($matricula, $ramal, $dac, $flag = 2)
{
$data = [];
$this->query = "UPDATE " . self::EVENTO_AGENTE . " SET logoff = :logoff, flag = :flag "
. "WHERE matricula = :matricula AND id_dac = :id_dac AND ramal = :ramal "
. "AND login = (SELECT MAX(login) FROM pbx_eventos_agentes WHERE matricula = :matricula AND id_dac = :id_dac AND ramal= :ramal);";
$data['logoff'] = 'now()';
$data['flag'] = $flag;
$data['matricula'] = $matricula;
$data['id_dac'] = $dac;
$data['ramal'] = $ramal;
return $this->update($this->query, $data);
}
}

26
integracao/media/app/Models/SupervisorQueue.php

@ -0,0 +1,26 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of EventQueue
*
* @author root
*/
class SupervisorQueue extends Model {
const TABLE = 'pbx_supervisor_dacs';
public function updateEsperaSupervisorQueue($name, $time){
$this->query = "UPDATE " . self::TABLE . " SET espera = (b.espera::int + :time)
FROM (SELECT espera FROM " . self::TABLE . " b WHERE b.dac = :dac) AS b
WHERE dac = :dac;";
return $this->update($this->query, ['espera' => $time , 'dac' => $name]);
}
public function updateEsperaByQueue($queue, $time, $numberwait){
$this->query = "UPDATE " . self::TABLE . " SET tempo_espera = :tempo_espera, espera = :espera WHERE dac = :dac;";
return $this->update($this->query, ['tempo_espera' => $time , 'espera' => $numberwait, 'dac' => $queue]);
}
}

34
integracao/media/app/Models/SystemMessage.php

@ -0,0 +1,34 @@
<?php
namespace app\Models;
use app\Core\Model;
/**
* Description of Ramal
*
* @author Lucas Awade
*/
class SystemMessage extends Model
{
private $table = 'md_system_message';
public function findMessage($momento, $fila = null)
{
$data = [];
$data['momento'] = $momento;
$this->query = "SELECT * FROM {$this->table} m WHERE 1=1";
if (!empty($fila)) {
$data['fila'] = $fila;
$this->query .= " AND (m.fila = :fila OR m.fila IS null)";
} else {
$this->query .= " AND m.fila IS null";
}
$this->query .= " AND m.momento = :momento ORDER BY ordem";
return $this->read($this->query, $data)->fetchAll();
}
}

527
integracao/media/app/Providers/ApiTelegram.php

@ -0,0 +1,527 @@
<?php
namespace app\Providers;
use app\Interfaces\IApiMedia;
use app\Providers\RequestURL;
class ApiTelegram implements IApiMedia
{
private $token;
private $url;
private $metodo;
########################################################################
## VARIAVEIS DA CLASSE ##
########################################################################
private $query;
private $requestType;
private $request;
private $params = array();
private $hook;
private $storage = "/var/www/html/aplicativo/audio/";
public $channel = CONF_TELEGRAM_CHANNEL;
public $timeout_client_resposta = CONF_TELEGRAM_TIMEOUT_CLIENT_RESPOSTA;
function __construct()
{
$this->token = CONF_TELEGRAM_AUTH_TOKEN;
$this->url = CONF_TELEGRAM_AUTH_URL;
$this->request = new RequestURL();
}
function convertToWebsocket($msg)
{
}
function enviarMsgIterativaLista($telegram, $mensagem, $nomeButton, $lista, $prex = '')
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"text" => array("body" => utf8_encode("$mensagem")),
"options" => array(
"reply_markup" => array(
"inline_keyboard" => $this->montaOp($lista, $prex)
)
)
);
$this->requestType("POST");
$this->setMetodo('sendMessage');
return $this->exec();
}
return false;
}
function montaOp($lista, $prex = '')
{
$botoes = [];
for ($i = 0; $i < count($lista); $i++) {
array_push(
$botoes,
array(
array(
"text" => utf8_encode("{$lista[$i]['title']}"),
"callback_data" => $prex == "C" ? utf8_encode("{$lista[$i]['title']}") : utf8_encode("{$lista[$i]['sub']}")
),
)
);
}
return $botoes;
}
function enviarMsgIterativaBotao($telegram, $mensagem, $buttons)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"text" => array("body" => utf8_encode("$mensagem")),
"options" => array(
"reply_markup" => array(
"inline_keyboard" => array(
array(
array(
"text" => utf8_encode("/presente"),
"callback_data" => utf8_encode("/presente")
),
)
)
)
)
);
$this->requestType("POST");
$this->setMetodo('sendMessage');
return $this->exec();
}
return false;
}
function enviarMsg($telegram, $mensagem)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"text" => array("body" => "$mensagem")
);
$this->requestType("POST");
$this->setMetodo('sendMessage');
return $this->exec();
}
return false;
}
function enviarContato($telegram, $nome, $contato)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"type" => "contacts",
"contacts" => array(
array(
"name" => array(
"first_name" => "$nome",
"formatted_name" => "$nome"
),
"phones" => array(
array(
"phone" => "$contato",
"type" => "CELL",
"wa_id" => "$contato"
)
)
)
)
);
$this->requestType("POST");
$this->setMetodo('sendContact');
return $this->exec();
}
return false;
}
function enviarLocalizacao($telegram, $longitude, $latitude, $nome = null, $endereco = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"longitude" => "$longitude",
"latitude" => "$latitude",
);
$this->requestType("POST");
$this->setMetodo('sendLocation');
return $this->exec();
}
return false;
}
function enviaDocumento($telegram, $link, $titulo = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"file" => "$link",
"options" => array(
"caption" => "$titulo"
),
"fileOptions" => array(
"filename" => "$titulo"
)
);
$this->requestType("POST");
$this->setMetodo('sendDocument');
return $this->exec();
}
return false;
}
function enviaImagem($telegram, $link, $titulo = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"file" => "$link",
);
$this->requestType("POST");
$this->setMetodo('sendPhoto');
return $this->exec();
}
return false;
}
function enviaSticker($telegram, $link)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"file" => "$link",
);
$this->requestType("POST");
$this->setMetodo('sendSticker');
return $this->exec();
}
return false;
}
function enviaVideo($telegram, $link, $titulo = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"file" => "$link",
"options" => array(
"caption" => "$titulo"
)
);
$this->requestType("POST");
$this->setMetodo('sendVideo');
return $this->exec();
}
return false;
}
function enviaAudio($telegram, $link)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"chatId" => "$telegram",
"file" => "$link",
);
$this->requestType("POST");
$this->setMetodo('sendVoice');
return $this->exec();
}
return false;
}
function baixarMidia($name)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->requestType("GET");
$this->setMetodo('media/' . $name);
$file = $this->storage . $name;
file_put_contents($file, $this->exec());
if (file_exists($file)) {
return $file;
}
}
return false;
}
function setStorage($storage)
{
$this->storage = $storage;
}
/**
* Profile WhatsApp
* @return string
*/
public function getProfile()
{
return $this->hook['from']['first_name'];
}
/**
* Phone WhatsApp
* @return string
*/
public function getPhone()
{
if ($this->hook['chat']['id']) {
return $this->hook['chat']['id'];
} else {
return $this->hook['from']['id'];
}
}
/**
* Returns the type of the message
* @return string|boolean
*/
public function getType()
{
if ($this->hook) {
if (array_key_exists("contact", $this->hook)) {
return 'contacts';
}
if (array_key_exists("location", $this->hook)) {
return 'location';
}
if (array_key_exists("document", $this->hook)) {
return 'document';
}
if (array_key_exists("audio", $this->hook)) {
return 'audio';
}
if (array_key_exists("video", $this->hook)) {
return 'video';
}
if (array_key_exists("sticker", $this->hook)) {
return 'sticker';
}
if (array_key_exists("photo", $this->hook)) {
return 'image';
}
if (array_key_exists("text", $this->hook)) {
return 'text';
}
if (array_key_exists("data", $this->hook)) {
return 'text';
}
return $this->hook['messages'][0]['type'];
}
return false;
}
/**
* Returns the mime of the message
* @return string|boolean
*/
public function getMimetype()
{
if ($this->hook['messages'][0][$this->getType()]['mime_type']) {
return base64_encode($this->hook['messages'][0][$this->getType()]['mime_type']);
}
return false;
}
/**
* Returns the id of the message
* @return string|boolean
*/
public function getId()
{
if ($this->hook && $this->getType()) {
return $this->hook['messages'][0][$this->getType()]['id'];
}
return false;
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getIsValidMessage()
{
return true;
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getMessage()
{
if ($this->hook['data']) {
return $this->hook['data'];
}
if ($this->hook['text']) {
return $this->hook['text'];
}
$message = $this->hook['data'];
return ($message ? $message : false);
}
/**
* Returns the name of the contact
* @return string|boolean
*/
public function getContactFormatted()
{
$formatted = $this->hook['messages'][0]['contacts'][0]['name']['formatted_name'];
if ($formatted) {
return $formatted;
}
return false;
}
/**
* Returns the phone of the contact
* @return string|boolean
*/
public function getContactPhone()
{
$contact = $this->hook['messages'][0]['contacts'][0]['phones'][0]['wa_id'];
if ($contact) {
return $contact;
}
return false;
}
/**
* Returns the latitude|longitude of the location
* @return string|boolean
*/
public function getGeolocation($type)
{
$geolocation = $this->hook['location'][strtolower($type)];
if ($geolocation) {
return $geolocation;
}
return false;
}
function setHook($hook)
{
$this->hook = $hook;
}
########################################################################
## FUNCOES DO SISTEMA ##
########################################################################
function setMetodo($metodo)
{
$this->metodo = $metodo;
}
/**
* Escreve a query para ser passada para o curl
*
* @param string $query
*/
function setQuery($query)
{
return $this->query .= $query;
}
/**
* retorna a string pronta da query do curl e limpa a variavel.
*
* @return string $query
*/
function getQuery()
{
$query = $this->query;
unset($this->query);
return $query;
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
function getArgs($args)
{
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
/**
* Recebe o tipo de Requisi<EFBFBD><EFBFBD>o GET/POST
*
* @return boolean
*/
function requestType($req = null)
{
if (!$req) {
return $this->requestType;
}
if (strtoupper($req) == "GET") {
return $this->requestType = "GET";
} else if (strtoupper($req) == "POST") {
return $this->requestType = "POST";
}
}
function exec()
{
$this->setQuery(json_encode($this->params)); //SET QUERY
$this->request->setUrl($this->url . $this->metodo);
$header = array();
//$header[] = "Authorization: Bearer {$this->token}";
if ($this->requestType == 'POST') {
$header[] = 'Content-Type: application/json';
$this->request->post_field($this->getQuery(), true);
}
$this->request->header($header);
$this->request->method_request($this->requestType);
$response = $this->request->exec_request();
return $this->response($response);
}
function response($result)
{
if ($result) {
if (json_decode($result, true) !== null) {
return json_decode($result, true);
}
return $result;
} else {
return false;
}
}
public function getLinkDownload($host)
{
if ($this->hook['photo']) {
return end($this->hook['photo'])['file_id'];
}
if ($this->hook['sticker']) {
return $this->hook['sticker']['file_id'];
}
if ($this->hook['video']) {
return $this->hook['video']['file_id'];
}
if ($this->hook['audio']) {
return $this->hook['audio']['file_id'];
}
if ($this->hook['document']) {
return $this->hook['document']['file_id'];
}
}
public function retornaTituloDocument($msg)
{
return $this->hook['document']['file_name'];
}
}

231
integracao/media/app/Providers/ApiTwilio.php

@ -0,0 +1,231 @@
<?php
namespace app\Providers;
use app\Interfaces\IApiMedia;
use Twilio\Rest\Client;
class ApiTwilio implements IApiMedia
{
private $sid = 'ACab626d6f133aa20b21879d37cd21b139';
private $token = '131e5ed83468349ff93250ca72417d70';
private $numeroTwilio = '553140428280';
/** @var string $hook resposta do webhook */
private $hook;
function getContentType()
{
return 'text/xml';
}
function getchannel()
{
return CONF_WHATSAPP_CHANNEL;
}
function enviarMedia($whatsapp, $link, $type, $titulo = null)
{
/*
twilio só suporta esses formatos.
Images JPG, JPEG, PNG
Audio MP3, OGG, AMR
Documents PDF
Video MP4 (with H.264 video codec and AAC audio)
Contacts vCard (.vcf)*/
$twilio = new Client($this->sid, $this->token);
$message = $twilio->messages->create(
"whatsapp:+$whatsapp", // to
[
"from" => "whatsapp:+{$this->numeroTwilio}",
"mediaUrl" => [$link]
]
);
logger('twilio')->info(var_export($message->body, true));
return $message->body;
}
function enviarMsg($whatsapp, $mensagem, $encode = true)
{
if ($encode) {
$mensagem = utf8_encode($mensagem);
}
$twilio = new Client($this->sid, $this->token);
$message = $twilio->messages->create(
"whatsapp:+$whatsapp", // to
[
"from" => "whatsapp:+{$this->numeroTwilio}",
"body" => $mensagem,
]
);
logger('twilio')->info(var_export($message->body, true));
return $message->body;
}
function enviarMsgIterativaLista($whatsapp, $mensagem, $nomeButton, $sections)
{
}
function enviarMsgIterativaBotao($whatsapp, $mensagem, $buttons)
{
}
function enviarContato($whatsapp, $nome, $contato)
{
}
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null)
{
}
function baixarMidia()
{
$request = new Requests();
if (in_array($this->getType(), ['location', 'contacts', 'text'])) {
return true;
}
logger('baixarMidia')->info('url: ' . $this->hook['MediaUrl0']);
$request->setToken(base64_encode("ACab626d6f133aa20b21879d37cd21b139:131e5ed83468349ff93250ca72417d70"));
$request->setUrl($this->hook['MediaUrl0']);
$name = $this->getId();
$request->requestType("GET");
$request->setMetodo('');
$pathfile = $request->storage . $name;
$retorno = $request->exec('Basic');
logger('baixarMidia')->info(var_export($retorno, true));
file_put_contents($pathfile, $retorno);
if (file_exists($pathfile)) {
return true;
}
return false;
}
function getProfile()
{
return $this->hook['ProfileName'];
}
function getPhone()
{
return $this->hook['WaId'];
}
function getType()
{
$type = $this->hook['MediaContentType0'];
if ($type) {
$type = explode('/', $type);
if ($type[0] == 'application') {
return 'document';
}
return $type[0];
}
return 'text';
}
function getMimetype()
{
return $this->hook['MediaContentType0'];
}
function getId()
{
return $this->hook['MessageSid'];
}
function getIsValidMessage()
{
return is_array($this->hook);
}
function getMessage()
{
return $this->hook['Body'];
}
function setMessage($msg)
{
$this->hook['Body'] = $msg;
}
function getContactFormatted()
{
return false;
}
function getContactPhone()
{
return false;
}
function getGeolocation($type)
{
return false;
}
function setHook($hook)
{
//$array = "SmsMessageSid=SM3f3e0cac9d0da519ec0ffa7f15eaa15b&NumMedia=0&ProfileName=Lucas&SmsSid=SM3f3e0cac9d0da519ec0ffa7f15eaa15b&WaId=556596107663&SmsStatus=received&Body=sdsdfads&To=whatsapp%3A%2B14155238886&NumSegments=1&MessageSid=SM3f3e0cac9d0da519ec0ffa7f15eaa15b&AccountSid=ACab626d6f133aa20b21879d37cd21b139&From=whatsapp%3A%2B556596107663&ApiVersion=2010-04-01";
$array = explode("&", urldecode($hook));
$map = [];
foreach ($array as $key => $value) {
$auxi = $array = explode("=", $value);
$map[$auxi[0]] = $auxi[1];
}
// mensagem normal
// [SmsMessageSid] => SM3f3e0cac9d0da519ec0ffa7f15eaa15b
// [NumMedia] => 0
// [ProfileName] => Lucas
// [SmsSid] => SM3f3e0cac9d0da519ec0ffa7f15eaa15b
// [WaId] => 556596107663
// [SmsStatus] => received
// [Body] => sdsdfads
// [To] => whatsapp%3A%2B14155238886
// [NumSegments] => 1
// [MessageSid] => SM3f3e0cac9d0da519ec0ffa7f15eaa15b
// [AccountSid] => ACab626d6f133aa20b21879d37cd21b139
// [From] => whatsapp%3A%2B556596107663
// [ApiVersion] => 2010-04-01
// imagem
// [MediaContentType0] => image/jpeg
// [SmsMessageSid] => MM0e531d626f74ec950e637d7491b0080c
// [NumMedia] => 1
// [ProfileName] => Lucas
// [SmsSid] => MM0e531d626f74ec950e637d7491b0080c
// [WaId] => 556596107663
// [SmsStatus] => received
// [Body] =>
// [To] => whatsapp:+14155238886
// [NumSegments] => 1
// [MessageSid] => MM0e531d626f74ec950e637d7491b0080c
// [AccountSid] => ACab626d6f133aa20b21879d37cd21b139
// [From] => whatsapp:+556596107663
// [MediaUrl0] => https://api.twilio.com/2010-04-01/Accounts/ACab626d6f133aa20b21879d37cd21b139/Messages/MM0e531d626f74ec950e637d7491b0080c/Media/ME4ff81dee03f2cd1b7875d87954e8abd7
// [ApiVersion] => 2010-04-01
// documento n�o valido
// [SmsMessageSid] => MM2f04ee178bf6843dd26ac19e6e193c19
// [NumMedia] => 0
// [ProfileName] => Lucas
// [SmsSid] => MM2f04ee178bf6843dd26ac19e6e193c19
// [WaId] => 556596107663
// [SmsStatus] => received
// [Body] => INSTALA��O WHATSAPP.docx
// [To] => whatsapp:+553140428280
// [NumSegments] => 1
// [MessageSid] => MM2f04ee178bf6843dd26ac19e6e193c19
// [AccountSid] => ACab626d6f133aa20b21879d37cd21b139
// [From] => whatsapp:+556596107663
// [ApiVersion] => 2010-04-01
// documento pdf
// [MediaContentType0] => application/pdf
// [SmsMessageSid] => MM1042d93ac503a7468b7d3fb3a0ca77d5
// [NumMedia] => 1
// [ProfileName] => Lucas
// [SmsSid] => MM1042d93ac503a7468b7d3fb3a0ca77d5
// [WaId] => 556596107663
// [SmsStatus] => received
// [Body] => Cap1-_atlas_.pdf
// [To] => whatsapp:+553140428280
// [NumSegments] => 1
// [MessageSid] => MM1042d93ac503a7468b7d3fb3a0ca77d5
// [AccountSid] => ACab626d6f133aa20b21879d37cd21b139
// [From] => whatsapp:+556596107663
// [MediaUrl0] => https://api.twilio.com/2010-04-01/Accounts/ACab626d6f133aa20b21879d37cd21b139/Messages/MM1042d93ac503a7468b7d3fb3a0ca77d5/Media/ME8fead4a393c68d2fcd14bdff03cc8e74
// [ApiVersion] => 2010-04-01
$this->hook = $map;
}
function retornaTituloDocument()
{
if ($this->getType() == 'text') {
return null;
}
return $this->hook['Body'];
}
}

78
integracao/media/app/Providers/Crypt.php

@ -0,0 +1,78 @@
<?php
namespace app\Providers;
/**
* Description of Cripto
*
* @author Lucas Awade
*/
class Crypt {
private $message;
private $key;
private $option;
private $tag;
private $cipher;
private $ivlen;
private $iv;
private $textcrypt;
const CONF_CIPHER_CRYPT = 'aes-256-cbc';
function __construct($cipher = null, $key = null, $option = OPENSSL_RAW_DATA, $tag = null) {
if (!$cipher) {
$this->cipher = self::CONF_CIPHER_CRYPT;
} else {
$this->cipher = $cipher;
}
$this->key = $key;
$this->option = $option;
$this->tag = $tag;
$this->openssl_crypt();
}
public function encrypt($message = null) {
$this->setMessage($message);
$encrypt = openssl_encrypt($this->message, $this->cipher, $this->key, $this->option, $this->iv);
$hashcode = hash_hmac('sha256', $encrypt, $this->key, true);
$this->textcrypt = base64_encode($this->iv . $hashcode . $encrypt);
return $this->textcrypt;
}
public function decrypt($textcrypt = null) {
$c = base64_decode($textcrypt);
$this->iv = substr($c, 0, $this->ivlen);
$hmac = substr($c, $this->ivlen, 32);
$ciphertext_raw = substr($c, $this->ivlen + 32);
$original_plaintext = openssl_decrypt($ciphertext_raw, $this->cipher, $this->key, $options = OPENSSL_RAW_DATA, $this->iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $this->key, true);
if (hash_equals($hmac, $calcmac)) {
return $original_plaintext;
}
}
private function openssl_crypt() {
if (in_array(strtolower($this->cipher), openssl_get_cipher_methods())) {
$this->ivlen = openssl_cipher_iv_length($this->cipher);
$this->iv = openssl_random_pseudo_bytes($this->ivlen);
}
}
public function setKey($key) {
$this->key = $key;
}
public function setOption($option) {
$this->option = $option;
}
public function setTag($tag) {
$this->tag = $tag;
}
public function setMessage($message) {
$this->message = $message;
}
}

177
integracao/media/app/Providers/Logger.php

@ -0,0 +1,177 @@
<?php
namespace app\Providers;
/**
* Classe para utilizar
*
* @documentation:
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.0
*/
class Logger
{
/*
* GENERATE LOG
*/
private $active;
private $log;
private $type;
private $text;
/*
* CONF. FILE LOG
*/
private $file;
private $path;
private $name;
/*
* CONST. MESSAGE TYPE
*/
const LOG_SUCCESS = "SUCCESS";
const LOG_DEBUG = "DEBUG";
const LOG_INFO = "INFO";
const LOG_WARNING = "WARNING";
const LOG_ERROR = "ERROR";
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/")
{
$this->name = $nameLog;
$this->path = $path;
$this->active = $active;
$this->config($nameLog);
}
########################################################################
## TYPES ##
########################################################################
public function success($log, $debug_trace = null)
{
$this->type = self::LOG_SUCCESS;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace());
$this->write();
}
public function debug($log, $debug_trace = null)
{
$this->type = self::LOG_DEBUG;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function info($log, $debug_trace = null)
{
$this->type = self::LOG_INFO;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function error($log, $debug_trace = null)
{
$this->type = self::LOG_ERROR;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function warning($log, $debug_trace = null)
{
$this->type = self::LOG_WARNING;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
########################################################################
## IMPORTANT ##
########################################################################
private function write()
{
if ($this->active) {
file_put_contents($this->file, $this->log, FILE_APPEND);
}
}
private function header($log, $debug_trace)
{
$this->log = "________________________________________________________________________________________\n";
if (is_array($debug_trace)) {
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function'];
$args = null;
$x = 0;
if (count($debug_trace[0]['args']) > 0) {
foreach ($debug_trace[0]['args'] as $key => $arg) {
$x++;
$args .= $arg;
if (count($debug_trace[0]['args']) != $x) {
$args .= ",";
}
}
}
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type);
} else {
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type);
}
$this->log .= "> " . $log;
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n";
}
public function openLog()
{
//$file = fopen($this->file, 'rb');
}
public function locateLog()
{
echo "\n\n {$this->file} \n\n";
}
########################################################################
## CONFIGS ##
########################################################################
public function config($name, $exten = ".log", $prefix = null)
{
if(strpos('.log', $name) !== false){
$exten = '';
}
if (file_exists($this->file)) {
$contents = file_get_contents($this->file);
}
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten);
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND);
}
public function getType()
{
return $this->type;
}
public function getText()
{
return $this->text;
}
public function setLogger($active)
{
if ($this->active === true) {
$this->active = $active;
} else if ($active === false) {
$this->active = $active;
} else {
$this->active = true;
}
}
}

343
integracao/media/app/Providers/Positus.php

@ -0,0 +1,343 @@
<?php
namespace app\Providers;
use app\Interfaces\IApiMedia;
class Positus extends Requests implements IApiMedia
{
/** @var string $hook resposta do webhook */
private $hook;
function getContentType()
{
return "application/json; charset=UTF-8";
}
public function getchannel()
{
return CONF_WHATSAPP_CHANNEL;
}
function setHook($hook)
{
$this->hook = json_decode($hook, true);
}
function enviarMedia($whatsapp, $link, $type, $titulo = null)
{
$tipos = [];
$tipos['link'] = $link;
if (!empty($titulo)) {
$tipos['caption'] = $titulo;
}
$this->debug = debug_backtrace();
$this->params = [
"to" => "+$whatsapp",
"type" => "$type",
"$type" => $tipos
];
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
function enviarMsg($whatsapp, $mensagem, $encode = true)
{
if ($encode) {
$mensagem = utf8_encode($mensagem);
}
$this->debug = debug_backtrace();
$this->params = array(
"to" => "+$whatsapp",
"type" => "text",
"text" => array("body" => "$mensagem")
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
function enviarMsgIterativaLista($whatsapp, $mensagem, $nomeButton, $lista, $prex = '')
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "interactive",
"interactive" => array(
"type" => "list",
"body" => array(
"text" => utf8_encode($mensagem)
),
"action" => array(
"button" => utf8_encode($nomeButton),
"sections" => $this->montaSection($lista, $prex)
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
$ret = $this->exec();
return $ret;
}
return false;
}
function montaSection($lista, $prex = '')
{
$sections = [];
for ($i = 0; $i < count($lista); $i++) {
array_push(
$sections,
array(
"id" => "$prex$i",
"title" => utf8_encode("{$lista[$i]['title']}"),
"description" => utf8_encode("{$lista[$i]['sub']}")
)
);
}
return array(
array(
"title" => utf8_encode("Comandos"),
"rows" => $sections
),
);
}
function enviarMsgIterativaBotao($whatsapp, $mensagem, $buttons)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "interactive",
"recipient_type" => "individual",
"interactive" => array(
"type" => "button",
"body" => array(
"text" => utf8_encode($mensagem)
),
"action" => array(
"buttons" => $buttons
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
$ret = $this->exec();
return $ret;
}
return false;
}
function enviarContato($whatsapp, $nome, $contato)
{
$this->debug = debug_backtrace();
if ($whatsapp) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "contacts",
"contacts" => array(
array(
"name" => array(
"first_name" => "$nome",
"formatted_name" => "$nome"
),
"phones" => array(
array(
"phone" => "+$contato",
"type" => "CELL",
"wa_id" => "$contato"
)
)
)
)
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
return false;
}
function enviarLocalizacao($whatsapp, $longitude, $latitude, $nome = null, $endereco = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"to" => "+$whatsapp",
"type" => "location",
"location" => array(
"longitude" => "$longitude",
"latitude" => "$latitude",
"name" => "$nome",
"address" => utf8_encode("$endereco")
)
);
$this->requestType("POST");
$this->setMetodo('messages');
return $this->exec();
}
return false;
}
function baixarMidia()
{
if (in_array($this->getType(), ['location', 'contacts', 'text'])) {
return true;
}
$name = $this->getId();
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->requestType("GET");
$this->setMetodo('media/' . $name);
$pathfile = $this->storage . $name;
$retorno = $this->exec();
file_put_contents($pathfile, $retorno);
if (file_exists($pathfile)) {
return true;
}
}
return false;
}
/**
* Profile WhatsApp
* @return string
*/
public function getProfile()
{
return $this->hook['contacts'][0]['profile']['name'];
}
/**
* Phone WhatsApp
* @return string
*/
public function getPhone()
{
return $this->hook['contacts'][0]['wa_id'];
}
/**
* Returns the type of the message
* @return string|boolean
*/
public function getType()
{
if ($this->hook) {
return $this->hook['messages'][0]['type'];
}
return false;
}
/**
* Returns the mime of the message
* @return string|boolean
*/
public function getMimetype()
{
if ($this->hook['messages'][0][$this->getType()]['mime_type']) {
return $this->hook['messages'][0][$this->getType()]['mime_type'];
}
return false;
}
/**
* Returns the id of the message
* @return string|boolean
*/
public function getId()
{
if ($this->hook && $this->getType()) {
if ($this->getType() == 'text') {
return $this->hook['messages'][0]['id'];
}
return $this->hook['messages'][0][$this->getType()]['id'];
}
return false;
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getIsValidMessage()
{
return $this->hook['contacts'];
}
/**
* Returns the (text, body) of the message
* @return string|boolean
*/
public function getMessage()
{
if ($this->hook['messages'][0]['interactive']) {
if ($this->hook['messages'][0]['interactive']['list_reply']) {
$id = $this->hook['messages'][0]['interactive']['list_reply']['id'];
if (strpos($id, 'P') === 0) {
return $this->hook['messages'][0]['interactive']['list_reply']['description'];
}
return $this->hook['messages'][0]['interactive']['list_reply']['title'];
} else {
return $this->hook['messages'][0]['interactive']['button_reply']['title'];
}
}
$message = $this->hook['messages'][0]['text']['body'];
return ($message ? $message : false);
}
public function setMessage($msg)
{
$this->hook['messages'][0]['text']['body'] = $msg;
}
/**
* Returns the name of the contact
* @return string|boolean
*/
public function getContactFormatted()
{
$formatted = $this->hook['messages'][0]['contacts'][0]['name']['formatted_name'];
if ($formatted) {
return $formatted;
}
return false;
}
/**
* Returns the phone of the contact
* @return string|boolean
*/
public function getContactPhone()
{
$contact = $this->hook['messages'][0]['contacts'][0]['phones'][0]['wa_id'];
if ($contact) {
return $contact;
}
return false;
}
/**
* Returns the latitude|longitude of the location
* @return string|boolean
*/
public function getGeolocation($type)
{
$geolocation = $this->hook['messages'][0]['location'][strtolower($type)];
if ($geolocation) {
return $geolocation;
}
return false;
}
public function retornaTituloDocument()
{
if ($this->hook['messages'][0]['document']) {
return $this->hook['messages'][0]['document']['filename'];
}
return null;
}
}

103
integracao/media/app/Providers/RequestURL.php

@ -0,0 +1,103 @@
<?php
namespace app\Providers;
class RequestURL
{
private $method;
private $curl;
private $ssl;
private $post_field;
private $header;
const CONF_TIMEOUT = 30;
public function setUrl($url, $ssl = true)
{
$this->debug = debug_backtrace();
$this->curl = curl_init($url);
$this->ssl = is_bool($ssl) ? $ssl : true;
}
public function header($header)
{
$this->debug = debug_backtrace();
if (is_array($header)) {
$this->header = $header;
} else {
$this->header = array($header);
}
}
public function post_field($data, $json = false)
{
$this->debug = debug_backtrace();
if ($json) {
$this->post_field = $data;
} else {
$this->post_field = http_build_query($data);
}
}
public function method_request($method = 'GET')
{
$this->debug = debug_backtrace();
$this->method = strtoupper($method);
}
public function exec_request()
{
$this->debug = debug_backtrace();
$this->conf_request();
if (curl_error($this->curl)) {
return false;
}
$this->response = curl_exec($this->curl);
curl_close($this->curl);
return $this->response($this->response);
}
public function convert_xml_to_object()
{
$this->debug = debug_backtrace();
if (!$this->response) {
return false;
}
return simplexml_load_string($this->response);
}
private function response($result)
{
// logger('deburguer')->info(print_r($result, true));
if ($result) {
if (json_decode($result, true) !== null) {
return json_decode($result, true);
}
return $result;
} else {
return false;
}
}
############################################################################
### CONFIG. CURL ###
############################################################################
private function conf_request()
{
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $this->method);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, $this->ssl);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, $this->ssl);
if ($this->post_field) {
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->post_field);
}
curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, self::CONF_TIMEOUT);
curl_setopt($this->curl, CURLOPT_TIMEOUT, self::CONF_TIMEOUT);
}
}

144
integracao/media/app/Providers/Requests.php

@ -0,0 +1,144 @@
<?php
namespace app\Providers;
class Requests
{
/** @var string $token token de autenticação das requesições */
protected $token;
/** @var string $url url base das requsições */
protected $url;
/** @var string $metodo endpoint da requsição */
protected $metodo;
/** @var string $query query da requsição */
protected $query;
/** @var string $query tipo da requsição */
protected $requestType;
/** @var array $params parametros da request */
protected $params = array();
/** @var RequestURL $request description */
protected $request;
/** @var string $contentType tipo da requsição */
protected $contentType;
/** @var string $storage caminho dos arquivos */
public $storage = CONF_PATH_FILES;
function __construct()
{
$this->request = new RequestURL();
$this->setToken();
$this->setUrl(CONF_WHATSAPP_AUTH_URL);
}
function response($result)
{
if ($result) {
if (json_decode($result, true) !== null) {
return json_decode($result, true);
}
return $result;
} else {
return false;
}
}
function exec($typeAuth = 'Bearer')
{
$this->setQuery(json_encode($this->params)); //SET QUERY
$this->request->setUrl($this->url . $this->metodo, false);
$header = array();
$header[] = "Authorization: $typeAuth {$this->token}";
if ($this->requestType == 'POST') {
$header[] = 'Content-Type: application/json';
$this->request->post_field($this->getQuery(), true);
}
$this->request->header($header);
$this->request->method_request($this->requestType);
logger('request')->info(print_r($header, true));
logger('request')->info($this->requestType);
return $this->request->exec_request();
}
/**
* Recebe o tipo de Requisi��o GET/POST
*
* @return boolean
*/
function requestType($req = null)
{
if (!$req) {
return $this->requestType;
}
if (strtoupper($req) == "GET") {
return $this->requestType = "GET";
} else if (strtoupper($req) == "POST") {
return $this->requestType = "POST";
}
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
function getArgs($args)
{
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
function setMetodo($metodo)
{
$this->metodo = $metodo;
}
/**
* Escreve a query para ser passada para o curl
*
* @param string $query
*/
function setQuery($query)
{
return $this->query .= $query;
}
/**
* retorna a string pronta da query do curl e limpa a variavel.
*
* @return string $query
*/
function getQuery()
{
$query = $this->query;
unset($this->query);
return $query;
}
function setToken($token = CONF_WHATSAPP_AUTH_TOKEN)
{
$this->token = $token;
}
public function setUrl($url)
{
$this->url = $url;
}
}

259
integracao/media/app/Providers/WebHeader.php

@ -0,0 +1,259 @@
<?php
namespace app\Providers;
/**
* Description of WebHeader
*
* @author Lucas Awade
*/
class WebHeader
{
/** @class support headers * */
private $headers = [
"Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Cache-Control",
"Connection",
"Content-Description",
"Content-Disposition",
"Content-Length",
"Access-Control-Max-Age",
"Content-Transfer-Encoding",
"Content-Type",
"Expires",
"Pragma",
"Location"
];
/** @codes https://http.cat/ * */
const HTTP_CODE_RESPONSE = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
204 => 'No Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moves Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Request Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'Im a teapot',
420 => 'Enhance Your Calm',
421 => 'Misdirected Request',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Too Early',
426 => 'Upgrade Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
444 => 'No Response',
450 => 'Blocked by Windows Parental Controls',
451 => 'Unavailable For Legal Reasons',
499 => 'Client Closed Request',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
511 => 'Network Authentication Required',
599 => 'Network Connect Timeout Error'
];
/**
* This variable set methods to use headers
* @var $methods
*/
private $methods = [];
/**
* This variable for logs
* @var $log
*/
private $log;
/**
* This variable for set new configs.
* @var $config
*/
private $config;
########################################################################
##### CLASS METHODS #####
########################################################################
function __construct($config = null)
{
$this->config($config);
$this->blockRequest();
}
public function config($config)
{
if ($config) {
foreach ($config as $key => $val) {
$this->config[strtoupper($key)] = $val;
}
}
return $this->config;
}
public function API($contentType)
{
$this->methods([
"Access-Control-Allow-Origin" => ['*'],
"Content-Type" => $contentType,
"Access-Control-Allow-Methods" => ['GET', 'POST', 'PUT', 'DELETE'],
"Access-Control-Max-Age" => 0,
"Access-Control-Allow-Headers" => ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization']
]);
$this->bootstrap();
}
public function response($code)
{
if (array_key_exists($code, self::HTTP_CODE_RESPONSE)) {
header("HTTP/1.0 {$code} " . self::HTTP_CODE_RESPONSE[$code]);
}
}
public function redirect($url = null)
{
// $redirect = ($url ? $url : $this->config['REDIRECT']);
// if (strpos('http://', $redirect) === false && strpos('https://', $redirect) === false) {
// $redirect = "http://$redirect";
// }
$redirect = $url ? $url : CONF_MIDDLEWARE_REDIRECT;
$this->methods([
"Location" => ($redirect)
]);
$this->bootstrap();
}
public function fileTransfer($name, $file, $mimetype)
{
//logger('logggeeeee')->info(basename($name . "." . explode('/', $mimetype)[1]));
$this->methods([
"Content-Description" => 'File Transfer',
"Content-Transfer-Encoding" => "binary",
"Content-Type" => $mimetype,
"Cache-Control" => "must-revalidate",
"Content-Length" => filesize($file),
"Content-Disposition" => "attachment; filename=" . basename($name . "." . explode('/', $mimetype)[1]),
"Expires" => 0,
"Connection" => 'close',
"Pragma" => 'public'
]);
$this->bootstrap();
ob_end_clean();
ob_start();
readfile($file);
ob_flush();
}
########################################################################
##### PRIVATE METHODS #####
########################################################################
private function bootstrap($header = null)
{
if (!$header && !$this->getMethods()) {
return null;
}
foreach ($header as $key => $val) {
if (!in_array($key, $this->headers)) {
array_push($this->headers, $key);
}
}
$this->methods($header);
$this->headers();
$this->clean();
}
private function blockRequest()
{
if ($this->config['BLOCK_REQUEST']) {
if (is_array($this->config['BLOCK_REQUEST'])) {
if (in_array($_SERVER['REMOTE_ADDR'], $this->config['BLOCK_REQUEST'])) {
$this->log->info("BLOCK REQUEST: " . $_SERVER['REMOTE_ADDR']);
$this->response(301);
$this->redirect(($this->config['REDIRECT'] ? $this->config['REDIRECT'] : 'index.php'));
exit(0);
}
} else if ($_SERVER['REMOTE_ADDR'] == $this->config['BLOCK_REQUEST']) {
$this->log->info("BLOCK REQUEST: " . $_SERVER['REMOTE_ADDR']);
$this->response(301);
$this->redirect($this->config['REDIRECT']);
exit(0);
}
}
}
private function headers()
{
foreach ($this->methods as $key => $header) {
if (in_array($key, $this->headers)) {
header("{$key}: {$header}");
}
}
}
private function methods($header)
{
foreach ($header as $key => $val) {
$method = str_replace(' ', '-', ucwords(str_replace('-', ' ', $key)));
if (is_array($val)) {
$this->methods[$method] = implode(',', $val);
} else {
$this->methods[$method] = $val;
}
}
}
private function clean()
{
unset($this->methods);
}
########################################################################
##### GETS AND SETTERS #####
########################################################################
function getMethods()
{
return $this->methods;
}
}

9
integracao/media/app/Providers/whatsapp.php

@ -0,0 +1,9 @@
<?php
namespace app\Providers;
use app\Providers\Positus;
class Whatsapp extends Positus
{
}

9
integracao/media/bd

@ -0,0 +1,9 @@
HOST_DB="192.168.115.65"
BASE_DB="pbx"
USUARIO="contacte"
SENHA="ctepgSQL"
PORTA_DB="5432"
HOST_SCK="127.0.0.1"
PORTA_SCK="5038"
USUARIO_SCK="manager"
SENHA_SCK="manager007"

146
integracao/media/client.php

@ -0,0 +1,146 @@
<?php
$tpLayout = 1;
$files = "integracao/media/public/";
if($_SESSION['SSToken'] != $_GET['t']){
$jsStartup[] = "window.close()";
} else {
unset($_SESSION['SSToken']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multi Channel | Simples Chat</title>
<link rel="icon" href="<?= $files ?>images/favicon.ico" />
<link rel="stylesheet" href="<?= $files ?>css/styles.css" />
</head>
<body>
<div class="grid">
<div class="top"></div>
<div class="bottom"></div>
<!-- App -->
<div class="app">
<div class="sidebar">
<!-- Sidebar header -->
<div class="sidebar-header">
<div class="sidebar-name">
<span class="sidebar-span"><span id="nameagent" style="text-transform: uppercase"></span> - <span id="myuniqueid"></span></span>
<span class="sidebar-span" id="queueagente"></span>
<span class="sidebar-span">STATUS: <span class="status-connect" id="status_agent"></span></span>
</div>
<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"/>
</div>
</div>
<div class="chats" id="chats"></div>
</div>
<div class="main">
<div class="chat-window-header">
<div class="chat-window-header-left" id="headermediaagent">
<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>
<span class="chat-window-contact-status">WhatsApp</span>
</div>
</div>
<div class="chat-window-header-right" id="headerbuttonsagent">
<div class="chat-window-header-right-commands btn-info" id="tranferagent" title="Transferir atendimento">
<img class="chat-window-menu-icon" src="<?= $files ?>images/redo.svg" />
<span class="chat-window-menu-span"> Transferir</span>
</div>
<div class="chat-window-header-right-commands btn-danger" id="finalizaratendimento" title="Finalizar atendimento">
<img class="chat-window-menu-icon" src="<?= $files ?>images/cross-circle.svg" />
<span class="chat-window-menu-span"> Finalizar</span>
</div>
</div>
</div>
<div class="chat-window" id="chatwindowagent">
<div class="type-window-image" id="welcometomessage">
<h1>Bem-vindo</h1>
<h2>Seu canal de atendimento por mensagens!</h2>
<img src="<?= $files ?>images/community_message.svg" />
</div>
<div class="type-message-bar-icons-upload" id="uploadfiles">
<label for="uploadfile" class="type-message-bar-icons-upload-btn" style="cursor: pointer;" title="Anexar arquivo">
<img src="<?= $files ?>images/file.svg" />
</label>
<input id="uploadfile" accept="*" type="file"
multiple="" style="display: none;">
<label for="uploadimage" class="type-message-bar-icons-upload-btn" style="cursor: pointer;" title="Enviar uma imagem">
<img src="<?= $files ?>images/picture.svg">
</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"/>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="modalselect" class="modal">
<div class="modal-content">
<div class="modal-header">
<div class="modal-header-title"></div>
<span class="close">&times;</span>
</div>
<div class="modal-body">
<div class="modal-content-body"></div>
</div>
<div class="modal-footer">
<div class="modal-footer-content flex-1" id="footer-content-left"></div>
<div class="modal-footer-content flex-right" id="footer-content-right"></div>
</div>
</div>
</div>
<script>
let modal = document.getElementById("modalselect");
let span = document.getElementsByClassName("close")[0];
span.onclick = function () {
modal.style.display = "none";
}
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<script src="<?= $files ?>js/jquery-3.6.0.min.js"></script>
<script src="<?= $files ?>js/config.js"></script>
<script src="<?= $files ?>js/cronometro.js"></script>
<script src="<?= $files ?>js/requests.js"></script>
<script src="<?= $files ?>js/util.js"></script>
<script src="<?= $files ?>js/main.js"></script>
</body>
</html>

22
integracao/media/composer.json

@ -0,0 +1,22 @@
{
"name": "simplesip/whatsapp",
"description": "Projeto WhatsApp",
"authors": [{
"name": "Simples IP Desenvolvimento",
"email": "lucasawade46@gmail.com"
}],
"autoload": {
"psr-4": {
"app\\": "app/",
"scripts\\": "scripts/",
"websocket\\": "websocket/",
"service\\": "service/",
"tests\\": "tests/"
}
},
"require": {
"cboden/ratchet": "^0.4.4",
"textalk/websocket": "^1.3.1",
"twilio/sdk": "^5.42.2"
}
}

BIN
integracao/media/composer.phar

Binary file not shown.

15
integracao/media/config/agent.php

@ -0,0 +1,15 @@
<?php
/*
|--------------------------------------------------------------------------
| Eventos
|--------------------------------------------------------------------------
|
| Eventos utilizados pelo gerenciamento dos atendimentos.
|
*/
define("CONF_AGENT_STATUS_LIVRE", 'LIVRE');
define("CONF_AGENT_STATUS_OCUPADO", 'OCUPADO');
define("CONF_AGENT_STATUS_PAUSA", 'PAUSA');
define("CONF_AGENT_STATUS_INDISPONIVEL", 'INDISPONIVEL');
define("CONF_AGENT_STATUS_CHAMANDO", 'CHAMANDO');

78
integracao/media/config/app.php

@ -0,0 +1,78 @@
<?php
/*
|--------------------------------------------------------------------------
| Nome Agente Resposta
|--------------------------------------------------------------------------
|
| Nome que apresentará as mensages de comando
|
*/
define("CONF_NAME_REPONSE", 'Simples IP');
/*
|--------------------------------------------------------------------------
| Log
|--------------------------------------------------------------------------
|
| Local para armazenar os dados referente a API utilzada.
|
*/
define("CONF_LOG_PATH", '/var/www/html/aplicativo/integracao/media/storage/log/');
/*
|--------------------------------------------------------------------------
| Configuracao de Middleware
|--------------------------------------------------------------------------
|
| Redirecionamento para página inicial do projeto
|
*/
define('CONF_MIDDLEWARE_REDIRECT', $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME']);
define('CONF_MIDDLEWARE_LINKUPLOAD', CONF_MIDDLEWARE_REDIRECT . '/integracao/media/link/');
/*
|--------------------------------------------------------------------------
| Configuracao do Banco de dados
|--------------------------------------------------------------------------
|
| Credencias para a conexão com o banco de dados
|
*/
define('CONF_DB_DRIVER', 'pgsql');
define('CONF_DB_HOST', '192.168.115.65');
define('CONF_DB_PORT', '5432');
define('CONF_DB_BASE', 'pbx');
define('CONF_DB_USER', '');
define('CONF_DB_PASSWD', '');
/*
|--------------------------------------------------------------------------
| Configuracao de MEDIA SIMPLES IP
|--------------------------------------------------------------------------
|
| Configuração para a media do PBX
|
*/
define('CONF_MEDIA_PBX', 99);
/*
|--------------------------------------------------------------------------
| Configuracao de Protocolo
|--------------------------------------------------------------------------
|
| Configuração geral de protocolo
|
*/
define('CONF_PROTOCOL_TENTATIVAS_GERAR', 5);
define('CONF_PATH_FILES', '/var/www/html/aplicativo/integracao/media/storage/files/');
/*
|--------------------------------------------------------------------------
| Informações da aplicação
|--------------------------------------------------------------------------
*/
define('INFO_VERSION_SYSTEM', '1.0.0');

15
integracao/media/config/display_errors.php

@ -0,0 +1,15 @@
<?php
error_reporting(E_ERROR);
ini_set('display_errors', CONF_LOG_DISPLAY_ACTIVE);
ini_set("memory_limit", "512M");
$filename = CONF_LOG_PATH . CONF_LOG_DISPLAY_NAME;
if (!file_exists($filename)) {
file_put_contents($filename, '');
exec(" chown pbx:pbx {$filename}");
}
ini_set('log_errors', CONF_LOG_DISPLAY_ACTIVE);
ini_set('error_log', $filename);
ini_set('log_errors_max_len', 4096);

23
integracao/media/config/event.php

@ -0,0 +1,23 @@
<?php
/*
|--------------------------------------------------------------------------
| Eventos
|--------------------------------------------------------------------------
|
| Eventos utilizados pelo gerenciamento dos atendimentos.
|
*/
// define("CONF_EVENT_WHATSAPP_ATENDIDA", 'MD_ATENDIDA');
define("CONF_EVENT_ESPERA", 'EMESPERA');
// define("CONF_EVENT_WHATSAPP_CANCELADA", 'MD_CANCELADO');
define("CONF_EVENT_TIMEOUT_CLIENTE", 'TIMEOUT_CALLER');
define("CONF_EVENT_TIMEOUT_AGENTE", 'TIMEOUT_AGENT');
define("CONF_EVENT_TIMERMINO_CLIENTE", 'COMPLETE_CALLER');
define("CONF_EVENT_TIMERMINO_AGENTE", 'COMPLETE_AGENT');
define("CONF_EVENT_ABANDONADA", 'ABANDON');
define("CONF_EVENT_TRANSFER", 'TRANSFER');
define("CONF_EVENT_START", 'START');
define("CONF_EVENT_ERRO_ATEND", 'LOST_CONNECTION');
// define("CONF_EVENT_WHATSAPP_OCUPADO", 'MD_OCUPADO');

74
integracao/media/config/helpers.php

@ -0,0 +1,74 @@
<?php
use app\Interfaces\IApiMedia;
use app\Providers\ApiTelegram;
use app\Providers\Logger;
use app\Providers\Positus;
use app\Providers\Whatsapp;
function logger($name = null, $active = true)
{
return new Logger(($name ? $name . "_" . date('Ymd') : 'logger_' . date('Ymd')), $active, CONF_LOG_PATH);
}
function whereIn($array)
{
if (is_array($array)) {
return "'" . implode("','", $array) . "'";
}
return "'$array'";
}
/**
* undocumented function summary
*
* Undocumented function long description
*
* @param Type $var Description
* @return IApiMedia
* @throws conditon
**/
function returnChannel($channel)
{
switch ($channel) {
case CONF_WHATSAPP_CHANNEL:
return new Positus();
case CONF_TELEGRAM_CHANNEL:
return new ApiTelegram();
}
}
function ConvertWavToMp3($fileOrig)
{
try {
// ffmpeg -i 61f1a021ca8908.72216404_1643308267776 61f1a021ca8908.72216404_1643308267776
$cmd = "ffmpeg -y -i $fileOrig $fileOrig.mp3";
exec($cmd);
copy($fileOrig . ".mp3", $fileOrig);
} catch (\Exception $th) {
throw $th;
}
}
//retorna uma string sem acentos
function removeAcentos($str, $upper = False)
{
$text = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý');
$subs = array('A', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'U', 'P', 'B', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y');
for ($i = 0; $i < strlen($str); $i++) {
$j = array_search($str[$i], $text);
if ($j)
$str[$i] = $subs[$j];
}
if ($upper)
$str = strtoupper($str);
return ($str);
}
//retorna uma string sem acentos
function removeAcentosArray(array $str)
{
foreach ($str as $key => $value) {
$str[$key] = removeAcentos($value);
}
return ($str);
}

32
integracao/media/config/log.php

@ -0,0 +1,32 @@
<?php
/*
|--------------------------------------------------------------------------
| Display Error
|--------------------------------------------------------------------------
|
| Configuracao do arquivo log display_error
|
*/
define("CONF_LOG_DISPLAY_ACTIVE", true);
define("CONF_LOG_DISPLAY_NAME",'display_errors.log');
/*
|--------------------------------------------------------------------------
| Log Controllers
|--------------------------------------------------------------------------
|
|
*/
define("CONF_LOG_CONTROLLERS_ACTIVE", true);
define("CONF_LOG_CONTROLLERS_NAME",'controllers.log');
/*
|--------------------------------------------------------------------------
| Log Database
|--------------------------------------------------------------------------
|
|
*/
define("CONF_LOG_DATABASE_ACTIVE", true);
define("CONF_LOG_DATABASE_NAME",'database.log');

25
integracao/media/config/middleware.php

@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| Configuracao do Middleware
|--------------------------------------------------------------------------
|
| Variaveis gerenericas para serem iniciadas no momento que o projeto for
| executado.
|
*/
return $config = [
'REDIRECT' => CONF_MIDDLEWARE_REDIRECT,
/** @BLOCK_REQUEST CONDUZ REDIRECIONAMENTOS DE REQUISICOES INVALIDAS E BLOQUEADAS * */
'BLOCK_REQUEST' => [],
/** @ACCEPT_HEADERS LIBERA HEADERS PARA SEREM UTILIZANDOS * */
'ACCEPT_HEADERS' => ['Location', 'Access-Control-Allow-Origin', 'Access-Control-Max-Age', 'Expires'],
/** @API_HEADER DEFINE OS HEADERS E SEUS VALORES PARA COMPOR A ESTRUTURA DAS API * */
'API_HEADER' => [],
/** @DOWNLOAD_HEADER DEFINE OS HEADERS E SEUS VALORES PARA TRANSFERENCIA DE ARQUIVOS * */
'DOWNLOAD_HEADER' => ["Cache-Control" => 'must-revalidate', 'Connection' => 'close'],
/** @LINK_UPLOAD DEFINE A URL QUE SERA UTILIZADA PARA FAZER O UPLOAD DOS ARQUIVOS DE WHATSAPP * */
'LINK_UPLOAD' => CONF_MIDDLEWARE_LINKUPLOAD
];

18
integracao/media/config/moments.php

@ -0,0 +1,18 @@
<?php
/*
|--------------------------------------------------------------------------
| Momonts
|--------------------------------------------------------------------------
|
| Eventos utilizados pelo gerenciamento dos atendimentos.
|
*/
define("CONF_MOMENT_SAUDACAO", 'SAUDACAO');
define("CONF_MOMENT_INICIAR_ATENDIMENTO", 'INICIAR_ATENDIMENTO');
define("CONF_MOMENT_FINALIZAR_ATENDIMENTO", 'FINALIZAR_ATENDIMENTO');
define("CONF_MOMENT_CANCELAR_FILA", 'CANCELAR_FILA'); //entrou na fila mas n tem agente logado
define("CONF_MOMENT_ENTRAR_FILA_SEM", 'ENTRAR_FILA_SEM'); //entrou na fila mas n tem agente livre
define("CONF_MOMENT_ENTRAR_FILA_COM", 'ENTRAR_FILA_COM');
define("CONF_MOMENT_ERRO_ATEND", 'LOST_CONNECTION');// quando estiver em atendimento e perder a conexão com websocket

60
integracao/media/config/telegram.php

@ -0,0 +1,60 @@
<?php
/*
|--------------------------------------------------------------------------
| Auth
|--------------------------------------------------------------------------
|
| Local para armazenar os dados referente a API utilzada.
|
*/
define("CONF_TELEGRAM_AUTH_TOKEN", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNGViZDYxOTJmMThhNTU2OGVlMDQ5ZDM3NDYzYTZmNDg5YjcxYjQyMGNhYzZmYWM0OWI5MjBkMmIxM2MzMzFmZDExMjAzMzhiZDhiODE5NWUiLCJpYXQiOjE2MjA4MzI1MTYsIm5iZiI6MTYyMDgzMjUxNiwiZXhwIjoxNjUyMzY4NTE2LCJzdWIiOiIyOTQ1Iiwic2NvcGVzIjpbXX0.mPLDDdSZuL6XlZbJ_xRNxebZgKKnYPS7Ecuit_8nPKRwLkY4MCuUA7UVWgt7Z7IG6PfNaxWzZtld7qQ_grV469Va_UbGbD342FJnL6iMVrXRv8_ybArS5J65zRR50zclexaKklplRxfebMIo6eovTJrc9kOeUPbfD-vztVB-MEXdW8sH4BTl23p8XVSxRhAegCcd9eA_IDymUpRJ8XPjJ_ZD2KkOXgucBwotl4srE3CweTdbKtCLqZfQcePE0rxxcDN6d4R0vj5TU2ze0iL-jwNUV1Gk4CF6lHqTr-8xqEzNsPHlJSsLFwmrlAqokgVFLA4ktfywBYZmzI6VJRODyqNuA-sf1KKDcWmVy6y1wdbX0pKiE96yHp86IO0Dqb7nZTH035rC7Ml0UTAo0-AmO-1WRS2BCtirBTpP9EGzWtBElwKLpPzokwbiae-GZgykDO9HUbGSm5GV8zvVGRhRNys_kbXjJaL_0DcHevHlcnEQDHqIX0-3fP5uvC5NhFSXBOtzJ796DLYpUXCunAsh5KzDFGdK_VTP6Xhsf2YGofn1okyHgU0J1B-a9F3AZpMYdnv7_FQC_SuZJ8mXFcoFSGI8F6RfjsO9dVY-N6MHsNQ8vWCkf4c4bv0XhBgPz5Uo3kOETpvzQjgmeptC7Wl4G_jG4RoVSjnH-QnLpdrO9zg');
define("CONF_TELEGRAM_AUTH_URL", 'http://192.168.115.75:3003/message/');
/*
|--------------------------------------------------------------------------
| Channel
|--------------------------------------------------------------------------
|
| Informa o tipo de midia utilizado para gravar no banco de dados.
| -> Facilita da identificacao durante um atendimento.
|
*/
define("CONF_TELEGRAM_CHANNEL", 'TELEGRAM');
/*
|--------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------
|
| Anexa um prefixo nas tabelas do banco de dados.
| -> Em caso de tabelas separadas para o controle de dados.
|
*/
define("CONF_TELEGRAM_DATABASE", '');
/*
|--------------------------------------------------------------------------
| Timeout
|--------------------------------------------------------------------------
|
| Informa o tempo em segundos para os tipos de alertas.
|
*/
define("CONF_TELEGRAM_TIMEOUT_CLIENT_AVISO_RESPOSTA", 120);
define("CONF_TELEGRAM_TIMEOUT_CLIENT_RESPOSTA", 180);
define("CONF_TELEGRAM_TIMEOUT_AGENT_AVISO", 1800);
define("CONF_TELEGRAM_TIMEOUT_AGENT_DESCONEXAO", 1980);
define("CONF_TELEGRAM_TIMEOUT_AGENT_CLASSIFICACAO", 180);
/*
|--------------------------------------------------------------------------
| Log
|--------------------------------------------------------------------------
|
| Informacoes de local e atividade do registro de log e o nome do arquivo.
|
*/
define("CONF_TELEGRAM_LOG_NAME_PATH", 'whatsapp');
define("CONF_TELEGRAM_LOG_ACTIVE", true);

60
integracao/media/config/whatsapp.php

@ -0,0 +1,60 @@
<?php
/*
|--------------------------------------------------------------------------
| Auth
|--------------------------------------------------------------------------
|
| Local para armazenar os dados referente a API utilzada.
|
*/
define("CONF_WHATSAPP_AUTH_TOKEN", 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzNjYWMyMDQ0ZmUwNDRjZmM4ZGM1YmNhMjVjMjNmOWY3ZTM3ZjNlODM4OWFhNmQwYjgxMWQ0M2RlYzM2MGI4NWY3MjZiYzQxZjQxOWZmODgiLCJpYXQiOjE2NTIzODUyODAuNzE5Nzg2LCJuYmYiOjE2NTIzODUyODAuNzE5Nzg5LCJleHAiOjE2ODM5MjEyODAuNzE3NTkxLCJzdWIiOiIyOTQ1Iiwic2NvcGVzIjpbXX0.s1gK_z4-95xHBd4DgMURH4BoZhObWxrEpMbp5h4zVC2qKi8YT88KAxKbFTGoscnaASXc42RLJ19Q0ptM-canWgmJ3jHLYerRLrM7YMowe_FhpQmaso5GuEk64tP27FywMixi3ULI2yf0u9KCbfUVxnVNLfxeaLeI90hxJxuIna72loGFMf-sDRg5UEb4AynosC3aNglslVUUpIvZt4CocpSbFjnO_MpCKCxwEA0E542ps-mkvld1wz5xp6YO9SkJ7XhmKbIm5Axh4bQgSkMfufghr7Xy9eXjS-9lCmC1k8sUoD4wu6W4lkUkzXYtds8AjGpqoOpxHBfiqBiJTO1o8AekkXq1X1VEzAY1GpzEQ64KEzfAk0h4Qjo_jc2FROeMto65AK7PKzOohrUUlXoWGMxZI9TnIRzlZ1G8CBMIomK8z_Ppgw41nd9mGOrd399YLlJa0BJZelLSjnTuFzdXnW90FYpapxoB7TRNdtg-DO3cUKioKwjq2lSkIbZKCvmQ9BPwZiGnm8Ft4YBh9o_AEWR2a1kEUr6xxQL6BFXnNTACYgzOTHt3TY5hMYxh93KM8aKni0oBcPfuIG9FcyabinmdNiyLNPH8NM4rhhnW-4hajvcfouNjkddbwtxK9gAgmp_VkP8ohZtDbgZ7yAHEZdIoyVuGouVhgVlZDEa2h3E');
define("CONF_WHATSAPP_AUTH_URL", 'https://api.positus.global/v2/whatsapp/numbers/ea4c9088-e34e-49ce-ba02-8ea55e6fdaa4/');
/*
|--------------------------------------------------------------------------
| Channel
|--------------------------------------------------------------------------
|
| Informa o tipo de midia utilizado para gravar no banco de dados.
| -> Facilita da identificacao durante um atendimento.
|
*/
define("CONF_WHATSAPP_CHANNEL", 'whatsapp');
/*
|--------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------
|
| Anexa um prefixo nas tabelas do banco de dados.
| -> Em caso de tabelas separadas para o controle de dados.
|
*/
define("CONF_WHATSAPP_DATABASE", '');
/*
|--------------------------------------------------------------------------
| Timeout
|--------------------------------------------------------------------------
|
| Informa o tempo em segundos para os tipos de alertas.
|
*/
define("CONF_WHATSAPP_TIMEOUT_CLIENT_AVISO_RESPOSTA", 120);
define("CONF_WHATSAPP_TIMEOUT_CLIENT_RESPOSTA", 180);
define("CONF_WHATSAPP_TIMEOUT_AGENT_AVISO", 1800);
define("CONF_WHATSAPP_TIMEOUT_AGENT_DESCONEXAO", 1980);
define("CONF_WHATSAPP_TIMEOUT_AGENT_CLASSIFICACAO", 180);
/*
|--------------------------------------------------------------------------
| Log
|--------------------------------------------------------------------------
|
| Informacoes de local e atividade do registro de log e o nome do arquivo.
|
*/
define("CONF_WHATSAPP_LOG_NAME_PATH", 'whatsapp');
define("CONF_WHATSAPP_LOG_ACTIVE", true);

282
integracao/media/database/att-v2.sql

@ -0,0 +1,282 @@
CREATE TABLE pbx_notifica_media (
id SERIAL NOT NULL PRIMARY KEY,
uniqueid character varying NOT NULL,
src character varying NOT NULL,
msg character varying NOT NULL,
notif_date timestamp WITHOUT TIME ZONW DEFAULT(NOW())
);
CREATE TABLE pbx_lista_negra_palavras (
id SERIAL NOT NULL PRIMARY KEY,
palavra character varying NOT NULL,
date_create timestamp WITHOUT TIME ZONW DEFAULT(NOW())
);
INSERT INTO
pbx_lista_negra_palavras (palavra)
VALUES
('Anus'),
('Baba-ovo'),
('Babaovo'),
('Babaca'),
('Bacura'),
('Bagos'),
('Baitola'),
('Bebum'),
('Besta'),
('Bicha'),
('Bisca'),
('Bixa'),
('Boazuda'),
('Boceta'),
('Boco'),
('Boiola'),
('Bolagato'),
('Boquete'),
('Bolcat'),
('Bosseta'),
('Bosta'),
('Bostana'),
('Brecha'),
('Brexa'),
('Brioco'),
('Bronha'),
('Buca'),
('Buceta'),
('Bunda'),
('Bunduda'),
('Burra'),
('Burro'),
('Busseta'),
('Cachorra'),
('Cachorro'),
('Cadela'),
('Caga'),
('Cagado'),
('Cagao'),
('Cagona'),
('Canalha'),
('Caralho'),
('Casseta'),
('Cassete'),
('Checheca'),
('Chereca'),
('Chibumba'),
('Chibumbo'),
('Chifruda'),
('Chifrudo'),
('Chota'),
('Chochota'),
('Chupada'),
('Chupado'),
('Clitoris'),
('Cocaina'),
('Coco'),
('Corna'),
('Corno'),
('Cornuda'),
('Cornudo'),
('Corrupta'),
('Corrupto'),
('Cretina'),
('Cretino'),
('Cruz-credo'),
('Cu'),
('Culhao'),
('Curalho'),
('Cuzao'),
('Cuzuda'),
('Cuzudo'),
('Debil'),
('Debiloide'),
('Defunto'),
('Demonio'),
('Difunto'),
('Doida'),
('Doido'),
('Egua'),
('Escrota'),
('Escroto'),
('Esporrada'),
('Esporrado'),
('Esporro'),
('Estupida'),
('Estupidez'),
('Estupido'),
('Fedida'),
('Fedido'),
('Fedor'),
('Fedorenta'),
('Feia'),
('Feio'),
('Feiosa'),
('Feioso'),
('Feioza'),
('Feiozo'),
('Felacao'),
('Fenda'),
('Foda'),
('Fodao'),
('Fode'),
('FodidaFodido'),
('Fornica'),
('Fudendo'),
('Fudecao'),
('Fudida'),
('Fudido'),
('Furada'),
('Furado'),
('Furão'),
('Furnica'),
('Furnicar'),
('Furo'),
('Furona'),
('Gaiata'),
('Gaiato'),
('Gay'),
('Gonorrea'),
('Gonorreia'),
('Gosma'),
('Gosmenta'),
('Gosmento'),
('Grelinho'),
('Grelo'),
('Homo-sexual'),
('Homossexual'),
('Homossexual'),
('Idiota'),
('Idiotice'),
('Imbecil'),
('Iscrota'),
('Iscroto'),
('Japa'),
('Ladra'),
('Ladrao'),
('Ladroeira'),
('Ladrona'),
('Lalau'),
('Leprosa'),
('Leproso'),
('Lésbica'),
('Macaca'),
('Macaco'),
('Machona'),
('Machorra'),
('Manguaca'),
('Mangua¦a'),
('Masturba'),
('Meleca'),
('Merda'),
('Mija'),
('Mijada'),
('Mijado'),
('Mijo'),
('Mocrea'),
('Mocreia'),
('Moleca'),
('Moleque'),
('Mondronga'),
('Mondrongo'),
('Naba'),
('Nadega'),
('Nojeira'),
('Nojenta'),
('Nojento'),
('Nojo'),
('Olhota'),
('Otaria'),
('Ot-ria'),
('Otario'),
('Ot-rio'),
('Paca'),
('Paspalha'),
('Paspalhao'),
('Paspalho'),
('Pau'),
('Peia'),
('Peido'),
('Pemba'),
('Pênis'),
('Pentelha'),
('Pentelho'),
('Perereca'),
('Peru'),
('Pica'),
('Picao'),
('Pilantra'),
('Piranha'),
('Piroca'),
('Piroco'),
('Piru'),
('Porra'),
('Prega'),
('Prostibulo'),
('Prost-bulo'),
('Prostituta'),
('Prostituto'),
('Punheta'),
('Punhetao'),
('Pus'),
('Pustula'),
('Puta'),
('Puto'),
('Puxa-saco'),
('Puxasaco'),
('Rabao'),
('Rabo'),
('Rabuda'),
('Rabudao'),
('Rabudo'),
('Rabudona'),
('Racha'),
('Rachada'),
('Rachadao'),
('Rachadinha'),
('Rachadinho'),
('Rachado'),
('Ramela'),
('Remela'),
('Retardada'),
('Retardado'),
('Ridícula'),
('Rola'),
('Rolinha'),
('Rosca'),
('Sacana'),
('Safada'),
('Safado'),
('Sapatao'),
('Sifilis'),
('Siririca'),
('Tarada'),
('Tarado'),
('Testuda'),
('Tezao'),
('Tezuda'),
('Tezudo'),
('Trocha'),
('Trolha'),
('Troucha'),
('Trouxa'),
('Troxa'),
('Vaca'),
('Vagabunda'),
('Vagabundo'),
('Vagina'),
('Veada'),
('Veadao'),
('Veado'),
('Viada'),
('Víado'),
('Viado'),
('Viadao'),
('Xavasca'),
('Xerereca'),
('Xexeca'),
('Xibiu'),
('Xibumba'),
('Xota'),
('Xochota'),
('Xoxota'),
('Xana'),
('Xaninha');

515
integracao/media/database/att-v3.sql

@ -0,0 +1,515 @@
ALTER TABLE
pbx_supervisor_agentes
ADD
media int NOT NULL DEFAULT 0;
-- pbx_eventos_agentes
ALTER TABLE
pbx_eventos_agentes
ADD
entrada_indisponivel timestamp(0) NULL;
ALTER TABLE
pbx_eventos_agentes
ADD
saida_indisponivel timestamp(0) NULL;
select
id,
prm_sk_host_chat,
prm_chat_api,
prm_media_simultaneo,
prm_chat_api_supervisor into pbx_parametros_bk
from
pbx_parametros
where
id = 1;
alter table
pbx_parametros drop column prm_chat_api_supervisor;
alter table
pbx_parametros
add
prm_chat_api_supervisor varchar(255);
alter table
pbx_parametros drop column prm_sk_host_chat;
alter table
pbx_parametros
add
prm_sk_host_chat varchar(255);
alter table
pbx_parametros drop column prm_chat_api;
alter table
pbx_parametros
add
prm_chat_api varchar(255);
update
pbx_parametros
set
prm_chat_api_supervisor = (
select
prm_chat_api_supervisor
from
pbx_parametros_bk
where
id = 1
);
update
pbx_parametros
set
prm_chat_api = (
select
prm_chat_api
from
pbx_parametros_bk
where
id = 1
);
update
pbx_parametros
set
prm_sk_host_chat = (
select
prm_sk_host_chat
from
pbx_parametros_bk
where
id = 1
);
drop table pbx_parametros_bk;
select
id,
prm_sk_host_chat,
prm_chat_api,
prm_media_simultaneo,
prm_chat_api_supervisor
from
pbx_parametros
where
id = 1;
ALTER TABLE
pbx_parametros
ADD
prm_media_simultaneo int not NULL DEFAULT 3;
CREATE TABLE md_supervisor (
id SERIAL NOT NULL PRIMARY KEY,
ramal varchar NULL,
matricula varchar NULL,
nome varchar NULL,
tempo_login timestamp NULL,
fila varchar NULL,
status varchar NULL,
duracao timestamp NULL,
uniqueid varchar NULL DEFAULT '',
status_agente int NOT NULL DEFAULT 0,
motivo_pausa varchar NULL,
chamada_classificado int NOT NULL DEFAULT 1,
cliente_id varchar NULL
);
CREATE TABLE md_message (
id SERIAL NOT NULL PRIMARY KEY,
uniqueid varchar NOT NULL,
src varchar NOT NULL,
dst varchar NOT NULL,
type varchar NOT NULL,
content varchar NOT NULL,
profile_name varchar NOT NULL,
msg_date timestamptz NULL DEFAULT now(),
media varchar NULL,
status varchar NULL,
file_name varchar NULL,
id_provedor varchar NULL,
mimetype varchar NULL
);
CREATE TABLE md_evento (
id SERIAL NOT NULL PRIMARY KEY,
uniqueid varchar NOT NULL,
evento varchar NOT NULL,
data_evento timestamp NULL,
data_reg timestamp NULL DEFAULT now(),
fila varchar NOT NULL,
matricula varchar NULL
);
CREATE TABLE md_atendimento (
id SERIAL NOT NULL PRIMARY KEY,
matricula varchar NULL,
cliente_id varchar NOT NULL,
direcao varchar(1) NOT NULL,
uniqueid varchar NULL,
context varchar NULL,
data_reg timestamp NULL DEFAULT now(),
nome varchar NULL
);
CREATE TABLE md_system_message (
id SERIAL NOT NULL PRIMARY KEY,
data_reg timestamp NULL DEFAULT now(),
texto varchar NOT NULL,
ordem int NOT NULL,
fila varchar NULL,
momento varchar NULL
);
INSERT INTO
md_system_message (data_reg, texto, ordem, momento)
VALUES
(
now(),
'Olá @cliente_name tudo certo?',
0,
'SAUDACAO'
),
(
now(),
'@cliente_name escolha uma das opções abaixo para iniciar o atendimento',
0,
'SAUDACAO'
),
(
now(),
'Cancelado o atendimento!',
0,
'CANCELAR_FILA'
),
(
now(),
'Atendimento iniciado com @agente_name!',
0,
'INICIAR_ATENDIMENTO'
),
(
now(),
'Atendimento finalizado!',
0,
'FINALIZAR_ATENDIMENTO'
),
(
now(),
'Não temos nenhum atendente disponível no momento, iremos lhe atender assim que um atendente estiver disponível!',
0,
'ENTRAR_FILA_SEM'
),
(
now(),
'Nossos atendentes estão ocupados, por favor aguarde que iremos lhe atender!',
0,
'ENTRAR_FILA_COM'
),
(
now(),
'Para finalar o atendimento digite \n*"/finalizar"*.',
0,
'INICIAR_ATENDIMENTO'
),
(
now(),
'Para sair da fila digite \n*"/cancelar"*.',
0,
'ENTRAR_FILA_SEM'
),
(
now(),
'Para sair da fila digite \n*"/cancelar"*.',
0,
'ENTRAR_FILA_COM'
);
CREATE TABLE pbx_notifica_media (
id SERIAL NOT NULL PRIMARY KEY,
uniqueid character varying NOT NULL,
src character varying NOT NULL,
msg character varying NOT NULL,
notif_date timestamp NULL DEFAULT now()
);
CREATE TABLE pbx_lista_negra_palavras (
id SERIAL NOT NULL PRIMARY KEY,
palavra character varying NOT NULL,
date_create timestamp NULL DEFAULT now()
);
INSERT INTO
pbx_lista_negra_palavras (palavra)
VALUES
('Anus'),
('Baba-ovo'),
('Babaovo'),
('Babaca'),
('Bacura'),
('Bagos'),
('Baitola'),
('Bebum'),
('Besta'),
('Bicha'),
('Bisca'),
('Bixa'),
('Boazuda'),
('Boceta'),
('Boco'),
('Boiola'),
('Bolagato'),
('Boquete'),
('Bolcat'),
('Bosseta'),
('Bosta'),
('Bostana'),
('Brecha'),
('Brexa'),
('Brioco'),
('Bronha'),
('Buca'),
('Buceta'),
('Bunda'),
('Bunduda'),
('Burra'),
('Burro'),
('Busseta'),
('Cachorra'),
('Cachorro'),
('Cadela'),
('Caga'),
('Cagado'),
('Cagao'),
('Cagona'),
('Canalha'),
('Caralho'),
('Casseta'),
('Cassete'),
('Checheca'),
('Chereca'),
('Chibumba'),
('Chibumbo'),
('Chifruda'),
('Chifrudo'),
('Chota'),
('Chochota'),
('Chupada'),
('Chupado'),
('Clitoris'),
('Cocaina'),
('Coco'),
('Corna'),
('Corno'),
('Cornuda'),
('Cornudo'),
('Corrupta'),
('Corrupto'),
('Cretina'),
('Cretino'),
('Cruz-credo'),
('Cu'),
('Culhao'),
('Curalho'),
('Cuzao'),
('Cuzuda'),
('Cuzudo'),
('Debil'),
('Debiloide'),
('Defunto'),
('Demonio'),
('Difunto'),
('Doida'),
('Doido'),
('Egua'),
('Escrota'),
('Escroto'),
('Esporrada'),
('Esporrado'),
('Esporro'),
('Estupida'),
('Estupidez'),
('Estupido'),
('Fedida'),
('Fedido'),
('Fedor'),
('Fedorenta'),
('Feia'),
('Feio'),
('Feiosa'),
('Feioso'),
('Feioza'),
('Feiozo'),
('Felacao'),
('Fenda'),
('Foda'),
('Fodao'),
('Fode'),
('FodidaFodido'),
('Fornica'),
('Fudendo'),
('Fudecao'),
('Fudida'),
('Fudido'),
('Furada'),
('Furado'),
('Furão'),
('Furnica'),
('Furnicar'),
('Furo'),
('Furona'),
('Gaiata'),
('Gaiato'),
('Gay'),
('Gonorrea'),
('Gonorreia'),
('Gosma'),
('Gosmenta'),
('Gosmento'),
('Grelinho'),
('Grelo'),
('Homo-sexual'),
('Homossexual'),
('Homossexual'),
('Idiota'),
('Idiotice'),
('Imbecil'),
('Iscrota'),
('Iscroto'),
('Japa'),
('Ladra'),
('Ladrao'),
('Ladroeira'),
('Ladrona'),
('Lalau'),
('Leprosa'),
('Leproso'),
('Lésbica'),
('Macaca'),
('Macaco'),
('Machona'),
('Machorra'),
('Manguaca'),
('Mangua¦a'),
('Masturba'),
('Meleca'),
('Merda'),
('Mija'),
('Mijada'),
('Mijado'),
('Mijo'),
('Mocrea'),
('Mocreia'),
('Moleca'),
('Moleque'),
('Mondronga'),
('Mondrongo'),
('Naba'),
('Nadega'),
('Nojeira'),
('Nojenta'),
('Nojento'),
('Nojo'),
('Olhota'),
('Otaria'),
('Ot-ria'),
('Otario'),
('Ot-rio'),
('Paca'),
('Paspalha'),
('Paspalhao'),
('Paspalho'),
('Pau'),
('Peia'),
('Peido'),
('Pemba'),
('Pênis'),
('Pentelha'),
('Pentelho'),
('Perereca'),
('Peru'),
('Pica'),
('Picao'),
('Pilantra'),
('Piranha'),
('Piroca'),
('Piroco'),
('Piru'),
('Porra'),
('Prega'),
('Prostibulo'),
('Prost-bulo'),
('Prostituta'),
('Prostituto'),
('Punheta'),
('Punhetao'),
('Pus'),
('Pustula'),
('Puta'),
('Puto'),
('Puxa-saco'),
('Puxasaco'),
('Rabao'),
('Rabo'),
('Rabuda'),
('Rabudao'),
('Rabudo'),
('Rabudona'),
('Racha'),
('Rachada'),
('Rachadao'),
('Rachadinha'),
('Rachadinho'),
('Rachado'),
('Ramela'),
('Remela'),
('Retardada'),
('Retardado'),
('Ridícula'),
('Rola'),
('Rolinha'),
('Rosca'),
('Sacana'),
('Safada'),
('Safado'),
('Sapatao'),
('Sifilis'),
('Siririca'),
('Tarada'),
('Tarado'),
('Testuda'),
('Tezao'),
('Tezuda'),
('Tezudo'),
('Trocha'),
('Trolha'),
('Troucha'),
('Trouxa'),
('Troxa'),
('Vaca'),
('Vagabunda'),
('Vagabundo'),
('Vagina'),
('Veada'),
('Veadao'),
('Veado'),
('Viada'),
('Víado'),
('Viado'),
('Viadao'),
('Xavasca'),
('Xerereca'),
('Xexeca'),
('Xibiu'),
('Xibumba'),
('Xota'),
('Xochota'),
('Xoxota'),
('Xana'),
('ladrão'),
('viado'),
('Xaninha');

45
integracao/media/database/database.sql

@ -0,0 +1,45 @@
CREATE TABLE pbx_message_wpp (
id SERIAL NOT NULL PRIMARY KEY,
uniqueid character varying NOT NULL,
src character varying NOT NULL,
dst character varying NOT NULL,
type character varying NOT NULL,
content character varying NOT NULL,
profile_name character varying NOT NULL,
msg_date timestamp WITHOUT TIME ZONW DEFAULT(NOW())
);
ALTER TABLE
pbx_queues_grupos
ADD
COLUMN midiafila VARCHAR(1);
ALTER TABLE
pbx_sip_ramais
ADD
COLUMN midiaramal VARCHAR(1);
CREATE TABLE md_supervisor (
id SERIAL NOT NULL PRIMARY KEY,
ramal character varying NOT NULL,
matricula character varying NULL,
nome character varying NULL,
tempo_login timestamp NULL,
cliente_id character varying NULL,
fila character varying NULL,
status character varying NULL,
duracao timestamp NULL,
uniqueid character varying NULL DEFAULT '',
status_agente int NOT NULL DEFAULT 0,
motivo_pausa character varying NULL,
chamada_classificado int NOT NULL DEFAULT 1
);
ALTER TABLE
md_message
add
COLUMN mimetype character varying NOT null,
add
COLUMN id_provedor character varying NOT null,
add
COLUMN file_name character varying NOT NULL;

21
integracao/media/database/modelo_mensagem.json

@ -0,0 +1,21 @@
{
"event": {
"type": "mensagem",
"contact": {
"name": "Lucas",
"number": "556596107663",
"matricula": ""
},
"mensagem": {
"type": "text",
"content": "ola",
"id_provedor": null,
"dst": "1040",
"uniqueid": 1638191429,
"media": "whatsapp",
"datetime": 1638191429,
"status": "sent",
"mimetype": false
}
}
}

17
integracao/media/database/msg-text-positus.json

@ -0,0 +1,17 @@
{
"contacts": [{
"profile": {
"name": "Lucas"
},
"wa_id": "556596107663"
}],
"messages": [{
"from": "556596107663",
"id": "ABEGVWWWEHZjAhBQHfcZqjRX4rWUHoW5CZul",
"text": {
"body": "Test"
},
"timestamp": "1637696166",
"type": "text"
}]
}

10
integracao/media/docker-compose.yml

@ -0,0 +1,10 @@
version: '3'
services:
mid:
container_name: mid
build: .
volumes:
- $PWD/data:/var/www/html/aplicativo/integracao/media/storage/files
ports:
- 8090:8090
- 8081:8081

32
integracao/media/docker/README

@ -0,0 +1,32 @@
# -------------------
# SIMPLESIP
# -------------------
## BUILD IMAGE ##
# docker image build -t simplesip .
#
# -------------------
# APLICAÇÃO
# -------------------
## BUILD IMAGE ##
# docker image build -t aplicativo .
#
# ## RUN CONTAINER ##
# docker run -d --name aplicativo --privileged -p 8080:80 -e DB_PORT=5433 -e DB_HOST=192.168.115.240 -e DB_BASE=pbx -e DB_USER=contacte -e DB_PASSWD=ctepgSQL aplicativo
#
# --------------------
# BANCO DE DADOS
# --------------------
# ## BUILD IMAGE ##
# docker image build -t simplesip-postgres .
#
# ## RUN CONTAINER ##
# docker run --name simplesip-postgres --privileged -e POSTGRES_DB=pbx -e POSTGRES_USER=contacte -e POSTGRES_PASSWORD=ctepgSQL -p 5433:5432 -d simplesip-postgres
#
# --------------------
# PORTAINER
# --------------------
# @doc https://docs.portainer.io/v/ce-2.11/start/install/server/docker/linux
## CREATE VOLUME ##
# docker volume create portainer_data
#
# docker run -d -p 9000:9000 -p 9443:9443 --name portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce:2.11.1

31
integracao/media/docker/aplicativo/Dockerfile

@ -0,0 +1,31 @@
FROM simplesip
### DOWNLOAD PROJECT ###
RUN mkdir -p /var/www/html/
WORKDIR /var/www/html/
RUN git clone http://desenvolvimento:SimpleS_G1t34@192.168.115.83:3000/awade/aplicativo.git
## CONFIGURANDO AMBIENTE WEB ##
WORKDIR /var/www/html/aplicativo/integracao/
RUN /bin/rm -rf media
RUN git clone -b 1.0.0 http://desenvolvimento:SimpleS_G1t34@192.168.115.83:3000/LucasCM/simples-whatsapp
RUN /bin/mv simples-whatsapp media
WORKDIR /var/www/html/aplicativo/integracao/media
RUN php /bin/composer install
WORKDIR /var/www/html/aplicativo
RUN /bin/cp -Rap asterisk/var_lib_asterisk/scripts/supervisor/supervisor.service /etc/systemd/system/
RUN chmod 755 /etc/systemd/system/supervisor.service
RUN chmod 755 /var/www/html/aplicativo/scriptdb/install/docker/simplesip/sip_install.sh
RUN chmod 755 /var/www/html/aplicativo/scriptdb/install/docker/simplesip/init.sh
RUN sh scriptdb/install/docker/simplesip/sip_install.sh
EXPOSE 80
ENTRYPOINT ["scriptdb/install/docker/simplesip/init.sh"]
CMD [ "/usr/sbin/httpd", "-D", "FOREGROUND" ]

16
integracao/media/docker/asterisk/Dockerfile

@ -0,0 +1,16 @@
FROM centos:7
LABEL maintainer="Andrius Kairiukstis <k@andrius.mobi>"
ENV ASTERISK_VERSION 16.26.0
ENV ASTERISK_ADDONS_VERSION 1.6.2.4
COPY build-asterisk.sh /
RUN /build-asterisk.sh
EXPOSE 5060/udp 5060/tcp
VOLUME /var/lib/asterisk/sounds /var/lib/asterisk/keys /var/lib/asterisk/phoneprov /var/spool/asterisk /var/log/asterisk
COPY docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["/usr/sbin/asterisk", "-vvvdddf", "-T", "-W", "-U", "asterisk", "-p"]

96
integracao/media/docker/asterisk/build-asterisk.sh

@ -0,0 +1,96 @@
#!/bin/bash
PROGNAME=$(basename $0)
if test -z ${ASTERISK_VERSION}; then
echo "${PROGNAME}: ASTERISK_VERSION required" >&2
exit 1
fi
set -ex
useradd --system asterisk
yum -y install \
cpp \
gcc \
gcc-c++ \
make \
ncurses \
ncurses-devel \
libxml2 \
libxml2-devel \
openssl-devel \
newt-devel \
libuuid-devel \
net-snmp-devel \
xinetd \
tar \
libffi-devel \
sqlite-devel \
curl \
bison
mkdir -p /usr/src/asterisk \
/usr/src/asterisk/addons
cd /usr/src/asterisk/addons
curl -vsL http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/asterisk-addons-${ASTERISK_ADDONS_VERSION}.tar.gz | tar --strip-components 1 -xz
cd /usr/src/asterisk
curl -vsL http://downloads.asterisk.org/pub/telephony/asterisk/old-releases/asterisk-${ASTERISK_VERSION}.tar.gz | tar --strip-components 1 -xz
# 1.5 jobs per core works out okay
: ${JOBS:=$(( $(nproc) + $(nproc) / 2 ))}
mkdir -p /etc/asterisk/ \
/var/spool/asterisk/fax
./configure --libdir=/usr/lib64
make menuselect/menuselect menuselect-tree menuselect.makeopts
# we don't need any sounds in docker, they will be mounted as volume
menuselect/menuselect --disable-category MENUSELECT_CORE_SOUNDS menuselect.makeopts
menuselect/menuselect --disable-category MENUSELECT_MOH menuselect.makeopts
menuselect/menuselect --disable-category MENUSELECT_EXTRA_SOUNDS menuselect.makeopts
make -j ${JOBS} all
make install
# copy default configs
# cp /usr/src/asterisk/configs/basic-pbx/*.conf /etc/asterisk/
make samples
make dist-clean
# set runuser and rungroup
sed -i -E 's/^;(run)(user|group)/\1\2/' /etc/asterisk/asterisk.conf
sed -i -e 's/# MAXFILES=/MAXFILES=/' /usr/sbin/safe_asterisk
cd /usr/src/asterisk/addons
./configure --libdir=/usr/lib64
make menuselect/menuselect menuselect-tree menuselect.makeopts
# disable saycountpl
menuselect/menuselect --disable app_saycountpl
# enable ooh323
menuselect/menuselect --enable chan_ooh323 menuselect.makeopts
make -j ${JOBS} all
make install
make samples
chown -R asterisk:asterisk /etc/asterisk \
/var/*/asterisk \
/usr/*/asterisk \
/usr/lib64/asterisk
chmod -R 750 /var/spool/asterisk
cd /
rm -rf /usr/src/asterisk \
/usr/src/codecs
yum -y clean all
rm -rf /var/cache/yum/*
exec rm -f /build-asterisk.sh

27
integracao/media/docker/asterisk/docker-entrypoint.sh

@ -0,0 +1,27 @@
#!/bin/sh
# run as user asterisk by default
ASTERISK_USER=${ASTERISK_USER:-asterisk}
if [ "$1" = "" ]; then
COMMAND="/usr/sbin/asterisk -T -W -U ${ASTERISK_USER} -p -vvvdddf"
else
COMMAND="$@"
fi
if [ "${ASTERISK_UID}" != "" ] && [ "${ASTERISK_GID}" != "" ]; then
# recreate user and group for asterisk
# if they've sent as env variables (i.e. to macth with host user to fix permissions for mounted folders
deluser asterisk && \
adduser --gecos "" --no-create-home --uid ${ASTERISK_UID} --disabled-password ${ASTERISK_USER} \
|| exit
fi
mkdir -p /var/run/asterisk
chown -R ${ASTERISK_USER}: /var/log/asterisk \
/var/lib/asterisk \
/var/run/asterisk \
/var/spool/asterisk; \
exec ${COMMAND}

15
integracao/media/docker/asterisk/hooks/post_push

@ -0,0 +1,15 @@
#!/bin/bash
# AUTOMATICALLY GENERATED
# DO NOT EDIT THIS FILE DIRECTLY, USE /post_push.erb
set -e
# Parse image name for repo name
tagStart=$(expr index "$IMAGE_NAME" :)
repoName=${IMAGE_NAME:0:tagStart-1}
# Tag and push image for each additional tag
for tag in {1.6.2.24}; do
docker tag $IMAGE_NAME ${repoName}:${tag}
docker push ${repoName}:${tag}
done

90
integracao/media/docker/asterisk13/Dockerfile

@ -0,0 +1,90 @@
FROM centos:centos7
LABEL maintainer='Doug Smith <info@laboratoryb.org>' contributors='Christophe Langenberg <christophe@langenberg.be>'
ENV build_date 2016-05-15
ENV AUTOBUILD_UNIXTIME 123124
RUN yum update -y \
&& yum install -y \
epel-release \
git \
kernel-headers \
wget \
gcc \
gcc-c++ \
cpp \
ncurses \
ncurses-devel \
libxml2 \
libxml2-devel \
sqlite \
sqlite-devel \
openssl-devel \
newt-devel \
kernel-devel \
libuuid-devel \
net-snmp-devel \
xinetd \
tar \
jansson-devel \
make \
bzip2 \
gettext \
&& yum clean all \
&& cd /tmp \
# Get pj project
&& git clone -b pjproject-2.4.5 --depth 1 https://github.com/asterisk/pjproject.git \
# Build pj project
&& cd pjproject \
&& ./configure \
--prefix=/usr \
--libdir=/usr/lib64 \
--enable-shared \
--disable-sound \
--disable-resample \
--disable-video \
--disable-opencore-amr \
1> /dev/null \
&& make -j$(nproc) dep 1> /dev/null \
&& make -j$(nproc) 1> /dev/null \
&& make -j$(nproc) install \
&& ldconfig \
&& ldconfig -p | grep pj \
&& cd .. \
# Download asterisk.
&& git clone -b certified/13.8 --depth 1 https://gerrit.asterisk.org/asterisk \
&& cd asterisk \
# Configure
&& ./configure \
--libdir=/usr/lib64 \
1> /dev/null \
# Remove the native build option
# from: https://wiki.asterisk.org/wiki/display/AST/Building+and+Installing+Asterisk
&& make -j$(nproc) menuselect.makeopts \
&& menuselect/menuselect \
--disable BUILD_NATIVE \
--enable cdr_csv \
--enable chan_sip \
--enable res_snmp \
--enable res_http_websocket \
--enable res_hep_pjsip \
--enable res_hep_rtcp \
menuselect.makeopts \
# Continue with a standard make.
&& make -j$(nproc) 1> /dev/null \
&& make -j$(nproc) install 1> /dev/null \
&& make -j$(nproc) samples 1> /dev/null \
&& make dist-clean \
# Update max number of open files.
&& sed -i -e 's/# MAXFILES=/MAXFILES=/' /usr/sbin/safe_asterisk \
# Create and configure asterisk for running asterisk user.
&& useradd -m asterisk -s /sbin/nologin \
&& chown -R asterisk:asterisk /var/run/asterisk \
/etc/asterisk/ \
/var/lib/asterisk \
/var/log/asterisk \
/var/spool/asterisk \
/usr/lib64/asterisk/
# And run asterisk in the foreground.
USER asterisk
CMD /usr/sbin/asterisk -f

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save