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

2706 lines
105 KiB

<?php
/*
* Agente
* Status:
* $_SESSION[AGT_EM_PAUSA] Agente em Pausa = 1 e 0 fora de pausa;
* $_SESSION[AGT_PAUSA_MOTIVO] Motivo da pausa setado pelo agente;
* $_SESSION[AGT_DAC_CONECT_DESC] Nome do dac
* $_SESSION[AGT_TP_ATEND_COD] = Automático = "**60" Manual = "**50"
* $_SESSION[AGT_TP_ATEND] 1 Manual 0 automático
* $_SESSION[AGT_TP_ATEND_COD]
* $_SESSION[AGT_CONECT] O Agente esta conectado = 1 desconectado = 0;
*/
/*
* Variaveis de interface agente no template
Informacoes da Fila
qtdeFila -> Quantidade de chamadas em fila
duracao -> Duração da chamada corrente
fone -> Numere de origem ou destino
Informacoes de chamadas do agente
abandonadas -> Chamadads Abandonadas na fila
tme -> Tempo médio de espera na fila
tma -> tempo médio de atendimento
atendidasPa -> número de chamadas atendidas pelo agente
Infoemacoes gerais
motivoPausa -> Combo com os motivos de pausa disponiveis
numProtocolo -> número do protocolo de atendimento
dacs -> Lista com os dacs Disponiveis
valueBtConectar -> Label refletindo o status do agente no botao conecar ao dac
msg_sis -> Mensagens para o usuarios
ramalAgente -> Ramal do Agente
dacLogado -> Dispositivo ou Dac que o agente se logou
statusAgente -> Status atual do agente
horaAtu -> Hora Atual
tempoLogado -> Tempo que o agente esta conectado ao dac
Classificação
useClassifica -> Mostra controles para classificação de chamadas qdo verdadeiro
useContrib -> Mostra controles para identificação de clientes qdo verdadeiro
classifica -> Lista com classificacoes cadastradas para o dac
clasItem -> Listas com itens relacioanados a classificação da chamada
*/
/*
* Constantes para sesssao do agente,
* definidas em constantes.php sessao AgenteRT
*/
$dadosMonitor = array("qtde_fila" => 0, "duracao" => '00:00:00', "fone" => '-', "abandonadas" => '0', "tme" => '0', "tma" => '0',
"atendidas_pa" => '0', "num_protocolo" => '-', "ramal_monitor" => '', "dac_logado" => '-',
"status_agente" => 'OFF', "tempo_logado" => '-', "uniqueid2" => 0, "tempo_atualiza" => 0, "pausa_motivo_rt" => '-', "pausa_motivo_ausente" => 0,
"uniqueid" => 0, 'matricula' => '-', "disponivel_atendimento" => 1, "disponivelFila" => '1', "originadas_pa" => '0', "agente_anota_key" => "",
"txt_cliente" => "", "chamada_classificado" => '2', "chamada_classificado_txt" => '...', "chamada_classificado_exige" => '0', "prm_obs_pausaprod" => '0',
"exibePesquisa" => '0', 'canal_transfer' => '', "abandonadasRet" => '0', "tipo_ligacao" => '', "cont_identificador" => '', "status_discador" => 0, "vendido" => 0);
$dadosMonitorCompl = array("use_contrib" => '0', "classifica" => '', "dacs" => '-', "clas_item" => '', "value_bt_conectar" => 'Conectar',
"msg_sis" => 'Sistema de Atendimento', "motivo_pausa" => '', "use_lassifica" => '0', "value_bt_pausa" => "Entrar",
"use_proto" => "1", "habilitaConectar" => 0, "habilita_pausa" => 0, "disab_modo_atend" => "", "modu_auto" => '',
"modu_manual" => 'checked="checked"', "hora_atu" => '-', "apelido" => "", "ufs" => '',
"modo_auto_permite" => '0', "modo_manu_permite" => '1', "pausa_detalhes" => "", "lst_pesquisa" => "", "exige_clas", 'prm_cadastro_atendidos' => 'Clientes',
"habilitaDiscador" => '0');
$dadosDiscador = array('cmpo_id' => '0', 'cmp_id' => '0', 'list_id' => '0', 'cont_id' => '', 'conf_id' => '', 'cmp_descricao' => '', 'list_nome' => '-', 'cont_identificador' => '-',
'cont_param1' => '-', 'cont_param2' => '-', 'cont_param3' => '-', 'cont_param4' => '-', 'cont_param5' => '-',
'disp_param1' => '-', 'disp_param2' => '-', 'disp_param3' => '-', 'disp_param4' => '-', 'disp_param5' => '-',
'conf_fone' => '', 'lista_fones_discador' => '', 'matricula' => '', 'cmpo_status' => '-1', 'carrega_fone' => '1', 'discagem_inicial' => '1');
/*
* Funcoes especificas do agente
*/
require("agente/funcoesAgente.php");
include("util/funcoesSsupervisor.php");
include("util/sharedMem.php");
/*
* Define mensagens para o usuário.
*/
$vl_msgAgente = '';
$wAlineMaster = "center";
$tpLayout = AgenteNovaJanela(); //Indica o template para esata pagina
$styleAdd = '';
$sZw = '170px';
$sZh = '26px';
$sZHeadTh = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '75px', $sZh, $styleAdd);
//Dac Pausa
$styleAdd = "border:1px solid #bbb;background-color: #eee;";
$sZlistaDacs = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '60%', $sZh, $styleAdd);
$sZbtConDac = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '35%', $sZh, $styleAdd);
$sZlistaMotivo = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '72%', $sZh, $styleAdd);
$sZbtPausa = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '23%', $sZh, $styleAdd);
$sZw = '100%';
// Classificacao.
$styleAdd = "border:1px solid #bbb;background-color: #eee;";
$sZtxtCliente = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '80%', $sZh, $styleAdd);
$sZbtCliente = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '16%', $sZh, $styleAdd);
$sZlistaClas = sprintf("width: %s;height: %s;padding:0;margin:0;%s", $sZw, $sZh, $styleAdd);
$sZlistaClasItem = sprintf("width: %s;height: %s;padding:0;margin:0;%s", $sZw, $sZh, $styleAdd);
$sZbt_classifica = sprintf("width: %s;height: %s;padding:0;margin:0;%s", UseModVendas() ? '80%' : '100%', $sZh, $styleAdd);
// Pesquisa
$sZw = '170px';
$sZlst_pesquisa = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '80%', $sZh, $styleAdd);
$sZbtPesquisa = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '16%', $sZh, $styleAdd);
// Discagem
$sZtxtDiscar = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '47%', $sZh, $styleAdd);
$sZbtLigar = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '20%', $sZh, $styleAdd);
$sZbtDesligar = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '20%', $sZh, $styleAdd);
$sZListaFones = sprintf("width: %s;height: %s;padding:0;margin:0;%sdisplay: none", '47%', $sZh, $styleAdd);
$sZbtIncluiFoneDiscador = sprintf("width: %s;height: %s;padding:0;margin:0;%sdisplay: none", '10%', $sZh, $styleAdd);
// Discador
$sZListaStatus = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '90%', $sZh, $styleAdd);
$sZbtRegStatus = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '42%', $sZh, $styleAdd);
$sZbtEncerraLibera = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '43%', $sZh, $styleAdd);
$sZbtEncerra = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '43%', $sZh, $styleAdd);
$sZinfContatosRestantes = sprintf("width: %s;height: %s;padding:0;margin:0;%stext-align:center;font-weight: bold", '30%', $sZh, $styleAdd);
$styleAdd = "border:0";
$sZcmp_descricao = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '99%', $sZh, $styleAdd);
$sZcont_identificador = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '99%', $sZh, $styleAdd);
$sZw = '100%';
$sZh = '50px';
$styleAdd = '';
$sZmsg_discador = sprintf("width: %s;height: %s;padding:0;margin:0;%s", $sZw, $sZh, $styleAdd);
/*
* Ativa log ami.
*/
$debugAmi = true; // true para ativar.
/*
* Informações sobre alerta para agente que ainda não classificou o chamado.
*/
$alertaAgente = array();
$matricula = GetMatricula();
$clasAtende = '';
if (AgenteON()) {
$dac = $_SESSION[SS_DAC_CODIGO];
} else if (IsPostBack()) {
$dac = isset($_POST["listaDacs"]) ? $_POST["listaDacs"] : '';
$_SESSION[SS_DAC_CODIGO] = $dac;
} else if (isset($_GET["dac"])) {
$dac = $_GET["dac"];
} else {
$dac = GetIdDacPadrao($dbcon, GetIdUser());
$_SESSION[SS_DAC_PADRAO_ID] = $dac;
}
if (!$dac) {
$dac = SetIdDacPadrao($dbcon, GetIdUser());
$_SESSION[SS_DAC_CODIGO] = $dac;
}
$ufForm = "";
/*
* Mostra erros na aplicação
*/
$displayError = 0;
if (!IsAjax()) {
$footerDisplay = 0;
$useAguarde = 0;
$tplAgente = 'callcenter/agente/agentert.tpl';
$cssBlock = "<style type=\"text/css\">
html, body, form { height:100%; min-height:100%;}
#content {
margin:0;
padding:0;
top:0;
left:0;
border: 0;
}
#conteudoSite {
margin: 0;
padding: 0;
top: 0;
left: 0;
border: 0;
}
</style>";
if (IsPostBack()) {
$tpAtende = isset($_POST["modoAtendimento"]) ? $_POST["modoAtendimento"] : $_SESSION[SS_MODO_ATENDIMENTO_COD];
if (ConectarDac()) {
if (!$dac) {
SetMsgAgente("Selecione um DAC!");
$jsStartup[] = "alert('Selecione um DAC!')";
} else {
if (AgenteON())
DesConectaAgenteRt($dbcon);
ConnectaAgenteRt($dbcon, $dac, $tpAtende);
}
}
else if (DesconectarDac()) {
DesConectaAgenteRt($dbcon);
} else if (SairDePausa()) {
SairPausa($dbcon);
} else if (EntrarPausa()) {
if (!isset($_POST["listaMotivo"]) || !$_POST["listaMotivo"]) {
$dadosMonitorCompl["msg_sis"] = "Selecione uma Pausa!";
$jsStartup[] = "alert('Selecione uma Pausa!')";
} else if (VerificaMaxAgentePausa($dac)) {
$dadosMonitorCompl["msg_sis"] = "número Máximo de Agente/Pausa Excedido, Aguarde!";
$jsStartup[] = "alert('número Máximo de Agente/Pausa Excedido, Aguarde!')";
} else {
$codMotivo = explode('|', $_POST["listaMotivo"]);
EntraPausa($dbcon, $codMotivo[0]);
}
}
DadosAtualiza($dbcon);
$_SESSION[RAMAL_DESTINO] = GetAnotacoesKey() ? $dadosMonitor["fone"] : $dadosMonitor["num_protocolo"];
} else {
/*
* Chamada get na inicializacao
*/
$_SESSION[SS_STATUS_AGENTE] = "OFF";
$ramalTmp = trim(GetRamalMonitorar(RAMAL_MONITOR_AGENTE));
if (!$ramalTmp) {
$_SESSION['SSconfRamal'] = 1;
$jsStartup[] = sprintf("RegistraRamalMonitorApl('99','%s','%s');", RAMAL_MONITOR_AGENTE, CANAL_MONITOR_AGENTE);
}
}
/*
* Inicializacao do sistema
*/
if (AgenteON()) {
DadosAtualiza($dbcon);
if ($_SESSION[SS_PRM_AGENTE_CLASSIFICA]) {
$clasAtende = CarregaClassificacao($dbcon, $dac);
}
}else{
$_SESSION[SS_MODO_ATENDIMENTO_COD] = $_SESSION['prm_atende_preferencial'] === "0" ? ATENDIMENTO_AUTOMATICO : ATENDIMENTO_MANUAL;
$_SESSION[SS_MODO_ATENDIMENTO] = $_SESSION[SS_MODO_ATENDIMENTO_COD] === ATENDIMENTO_MANUAL ? "Manual" : "Automático";
}
$jsStartup[] = "window.setInterval(\"GetAgenteRt()\", " . GetTempoAgente() . ");";
$jsStartup[] = "window.setInterval(\"SetDataAtual()\", 1000);";
$jsJQuery[] = "\$(document).bind(\"keydown keypress\", function (event) { if (!ativaBackspace && (event.which == 8)) { return false; }});";
$jsJQuery[] = "\$('#txtDiscar').focus(function(){ ativaBackspace = true; }) ";
$jsJQuery[] = "\$('#txtDiscar').blur(function(){ ativaBackspace = false; }) ";
$jsJQuery[] = "\$('#msg_discador').focus(function(){ ativaBackspace = true; }) ";
$jsJQuery[] = "\$('#msg_discador').blur(function(){ ativaBackspace = false; }) ";
if ($tpLayout) {
$jsJQuery[] = " \$('#contentAgente').height($(document).height() - 4);";
$jsJQuery[] = "\$(window).resize( function(){ ResizeAgente(); } ); ";
}
if ($clasAtende) {
$GLOBALS["jsStartup"][] = $clasAtende;
}
$useContribuinte = $_SESSION[SS_PRM_AGENTE_CONTRIBUINTE];
$useClassificacao = $_SESSION[SS_PRM_AGENTE_CLASSIFICA];
$dadosMonitorCompl["habilitaConectar"] = true;
$dadosMonitorCompl["dacs"] = GetDac($dbcon, $dac, AgenteON() ? "disabled=\"disabled\"" : "", 0, 1, 0, 0, 1);
$dadosMonitorCompl["motivo_pausa"] = GetMotivo($dbcon, AgenteON() ? $_SESSION[SS_PAUSA_AGENTE_MOTIVO] : 0, DisablePausa(), true, 1);
$dadosMonitorCompl["value_bt_pausa"] = AgentePausa() ? "Sair" : "Entrar";
$dadosMonitorCompl["habilita_pausa"] = AgenteON();
$dadosMonitorCompl["use_proto"] = $_SESSION[SS_PRM_AGENTE_PROTO];
$dadosMonitorCompl["use_contrib"] = $useContribuinte;
$dadosMonitorCompl["use_classifica"] = $useClassificacao;
$dadosMonitorCompl["classifica"] = GetHtmlSelect("listaClas", $useClassificacao ? '' : 'Desabilitado', "style=\"$sZlistaClas\" onchange=\"GetAgtClasItem(this.value);\"", $useClassificacao ? 0 : 1);
$dadosMonitorCompl["clas_item"] = GetHtmlSelect("listaClasItem", '', "style=\"$sZlistaClasItem\"");
$dadosMonitorCompl["value_bt_conectar"] = AgenteON() ? "Desconectar" : "Conectar";
$dadosMonitor["status_agente"] = AgenteON() ? $_SESSION[SS_STATUS_AGENTE] : 'OFF';
$dadosMonitor["ramal_monitor"] = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$dadosMonitorCompl["modu_auto"] = (($_SESSION[SS_MODO_ATENDIMENTO_COD] == '**60') ) ? 'checked="checked"' : "";
$dadosMonitorCompl["modu_manual"] = (($_SESSION[SS_MODO_ATENDIMENTO_COD] == '**50')) ? 'checked="checked"' : "";
$dadosMonitorCompl["disab_modo_atend"] = AgenteON() ? "disabled=\"disabled\"" : "";
$dadosMonitorCompl["hora_atu"] = date("H:i:s");
$dadosMonitor["matricula"] = GetMatricula();
$dadosMonitorCompl["apelido"] = GetLogin();
$dadosMonitorCompl["ufs"] = AgenteON() ? GetUfs($dbcon, $ufForm) : GetHtmlSelect("", "---------------", "", 1);
$dadosMonitorCompl["modo_auto_permite"] = GetPermitAtendAuto();
$dadosMonitorCompl["modo_manu_permite"] = GetPermitAtendManual();
$dadosMonitor["disponivelFila"] = GetDisponivelFila();
$dadosMonitorCompl["lst_pesquisa"] = AgenteON() ? GetPesquisaDisponivel($dbcon, $dac) : GetHtmlSelect("", "---------------", "", 1);
$dadosMonitorCompl["exige_clas"] = GetExigeClas();
$dadosMonitor["chamada_classificado_txt"] = GetExigeClassStatusTxt($dadosMonitor["chamada_classificado"]);
$dadosMonitor["chamada_classificado_exige"] = GetExigeClas() ? 1 : 0;
$dadosMonitor["prm_obs_pausaprod"] = GetObsProdAgente();
$dadosMonitorCompl["exibePesquisa"] = ExibePesquisa();
$dadosMonitorCompl["prm_cadastro_atendidos"] = GetNomeCadCli();
$dadosMonitor["dac_logado"] = isset($_SESSION[SS_DAC_DESCRICAO]) ? $_SESSION[SS_DAC_DESCRICAO] : '';
$dadosMonitor["abandonadasRet"] = !AgenteON() ? '0' : RetornaAbandon($dbcon, $dadosMonitor["dac_logado"], GetRamalMonitorar(RAMAL_MONITOR_AGENTE), '', '', $dadosMonitor["abandonadasRet"]);
$var = $dadosMonitor["abandonadasRet"];
$dadosMonitorCompl["msg_sis"] = GetMsgAgente();
$dadosMonitorCompl["habilitaDiscador"] = HabilitaDiscador();
$imgPausa = '<img src="imgSite/pausa32.png" alt="Pausas" width="25" height="25" border="0" title="Pausas" />';
$dadosMonitorCompl["pausa_detalhes"] = sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=203&matricula=%s', 'agtRelMotPausa', '600', '500', 'scrollbars=YES');\" style=\"color:black;\">%s</a>", GetMatricula(), $imgPausa);
GetMunOrigem($dadosMonitor);
$arTemp = array_merge($dadosMonitor, $dadosMonitorCompl);
foreach ($arTemp as $key => $value) {
$smarty->assign($key, $value);
}
$ListaStatus = isset($_REQUEST['ListaStatus']) ? $_REQUEST['ListaStatus'] : '0';
$smarty->assign('nomeRamalMonitor', RAMAL_MONITOR_AGENTE);
$smarty->assign('canalRamallMonitor', CANAL_MONITOR_AGENTE);
$smarty->assign('ListaStatus', AgenteON() ? GetStatusDiscador($ListaStatus) : '');
$smarty->assign('sZtxtCliente', $sZtxtCliente);
$smarty->assign('sZbtCliente', $sZbtCliente);
$smarty->assign('sZlst_pesquisa', $sZlst_pesquisa);
$smarty->assign('sZbtPesquisa', $sZbtPesquisa);
$smarty->assign('sZbtConDac', $sZbtConDac);
$smarty->assign('sZListaFones', $sZListaFones);
$smarty->assign('sZListaStatus', $sZListaStatus);
$smarty->assign('sZbtRegStatus', $sZbtRegStatus);
$smarty->assign('sZbtPausa', $sZbtPausa);
$smarty->assign('sZtxtDiscar', $sZtxtDiscar);
$smarty->assign('sZtxtDiscar', $sZtxtDiscar);
$smarty->assign('sZbtLigar', $sZbtLigar);
$smarty->assign('sZbtDesligar', $sZbtDesligar);
$smarty->assign('sZbt_classifica', $sZbt_classifica);
$smarty->assign('sZbtIncluiFoneDiscador', $sZbtIncluiFoneDiscador);
$smarty->assign('sZHeadTh', $sZHeadTh);
$smarty->assign('sZmsg_discador', $sZmsg_discador);
$smarty->assign('sZbtEncerraLibera', $sZbtEncerraLibera);
$smarty->assign('sZbtEncerra', $sZbtEncerra);
$smarty->assign('sZcont_identificador', $sZcont_identificador);
$smarty->assign('sZcmp_descricao', $sZcmp_descricao);
$smarty->assign('sZinfContatosRestantes', $sZinfContatosRestantes);
$smarty->assign('janH', $_REQUEST['janH']);
$smarty->assign('tpLayout', $tpLayout);
$smarty->assign('versao', GetVersao());
$smarty->assign('labelProtocolo', $_SESSION['prm_label_protoco_pesquisa']);
$smarty->assign("prm_label_protoco_texto", $_SESSION['prm_label_protoco_texto']);
$smarty->assign('useModVendas', UseModVendas());
$smarty->assign('exigeProtoExt', (ExigeProtoVendas() ? '1' : '0'));
$smarty->assign('vendido', GetVendasAgente($dac, $matricula));
$smarty->assign('ativa_integracao', GetAtivaIntegracao());
$smarty->assign('linkaudio', '...');
$smarty->assign('ativaComplementoCampanha', ComplementoCampanhaAtivo());
$clienteOperacao = GetClientOperacao($matricula)['cont_identificador'] ?? "";
if ($clienteOperacao) {
$smarty->assign('clienteoperacao', sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=45&formAction=4&id=%s&refresh=1', 'clienteOperacao', '760', '600', 'resizable=NO,scrollbars=NO');\"><img src=\"imgSite/usuarios.gif\" alt=\"Ir para a Tela do Cliente\" width=\"25\" border=\"0\" title=\"Visualiza as Informações do cliente!\" /></a>", $clienteOperacao));
}
GetTemplate($smarty, $tplAgente);
} else {
/*
* Chamadas em Ajax para atualizar Interface.
*/
$acao = $_GET["acao"];
$audioFone = isset($_GET['audioFone']) ? $_GET['audioFone'] : '';
if ($audioFone) {
echo ClassificacaoAudioEscuta($audioFone);
exit();
}
if ($acao == 'avisodesconnect') {
DesConectaAgenteRt($dbcon, 'DESCONNECT');
exit;
}
if ($acao == 'atualiza') {
$dadosMonitor["pausa_motivo_ausente"] = 0;
$dadosMonitor["dac_padrao"] = $_SESSION["SS_ultimo_dac_agente"] ? $_SESSION["SS_ultimo_dac_agente"] : $_SESSION[SS_DAC_PADRAO_ID];
if($_SESSION['SS_IS_LOGGED'] == true && $_SESSION[SS_STATUS_AGENTE] == "OFF"){
unset($_SESSION['SS_IS_LOGGED']);
echo 'ERROR@@Você foi desconectado do sistema, verifique sua internet ou navegador! Entre em contato com seu supervisor.';
RegistraLogAgente("LogoffError", "Usuário foi desconectado inesperadamente, por queda da internet ou problema do navegador. [ Matricula : ". GetMatricula() . " ]" , 'ErrorLogoff');
exit;
}
/*
* O agente deslogou ou foi desconectado.
*/
if (!GetStatusAgente()) {
$dadosMonitor["ramal_monitor"] = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$dadosMonitor["tempo_logado"] = '00:00:00';
$dadosMonitor["matricula"] = GetMatricula();
$dadosMonitor["abandonadasRet"] = '0';
$dadosMonitor["status_agente"] = "OFF";
$_SESSION['SS_IS_LOGGED'] == false;
$dadosMonitor = array_merge($dadosMonitor, $dadosDiscador);
echo FormataDadosRt($dadosMonitor);
} else {
$_SESSION['SS_IS_LOGGED'] = true;
$oldStatus = $_SESSION[SS_STATUS_AGENTE];
DadosAtualiza($dbcon);
$chamadaValida = trim($dadosMonitor["uniqueid2"]);
$statusAtual = $dadosMonitor["status_agente"];
//
// Limpa link de audio.
//
if (($oldStatus != $statusAtual) && ($statusAtual == 'CHAMANDO')) {
$dadosMonitor["linkaudio"] = "...";
}
if ($statusServer){
$dadosMonitor["tempo_logado"] = sprintf('<span style="color: #00FF00">%s</span>', $dadosMonitor["tempo_logado"]);
}
$dadosMonitor["dac_logado"] = $_SESSION[SS_DAC_DESCRICAO];
$_SESSION[SS_STATUS_AGENTE] = $dadosMonitor["status_agente"] ? $dadosMonitor["status_agente"] : "OFF";
$statusAtual = $dadosMonitor["status_agente"];
if (($oldStatus != $statusAtual) && ($statusAtual == 'OCUPADO')) {
SetaClassificaChamado($dbcon, 0, 0);
//
// Cria um link para audio.
//
$dadosMonitor["linkaudio"] = sprintf("http://%s/ad/?%s", GetLinkAudio(), base64_encode($dadosMonitor["uniqueid2"]));
}
$dadosMonitor["chamada_classificado_txt"] = GetExigeClassStatusTxt($dadosMonitor["chamada_classificado"]);
$dadosMonitor["chamada_classificado_exige"] = GetExigeClas() ? 1 : 0;
$dadosMonitor["prm_obs_pausaprod"] = GetObsProdAgente();
$_SESSION[RAMAL_DESTINO] = GetAnotacoesKey() ? $dadosMonitor["fone"] : $dadosMonitor["num_protocolo"];
$clienteOperacao = GetClientOperacao($matricula)['cont_identificador'];
if ($clienteOperacao) {
$dadosMonitor['clienteoperacao'] = sprintf("<a href=\"javaScript:NovaJanela('index.php?idProg=45&formAction=4&id=%s&refresh=1', 'clienteOperacao', '760', '600', 'resizable=NO,scrollbars=NO');\"><img src=\"imgSite/usuarios.gif\" alt=\"Ir para a Tela do Cliente\" width=\"25\" border=\"0\" title=\"Visualiza as Informações do cliente!\" /></a>", $clienteOperacao);
}
/*
* Controla alerta sonoro para agente quando o chamado não é classificado.
*/
$exigeClass = $dadosMonitor["chamada_classificado_exige"];
$naoClass = $dadosMonitor["chamada_classificado"];
$startAlert = ($statusAtual == 'LIVRE');
if (($oldStatus != $statusAtual) && ($statusAtual == 'LIVRE')) {
SetAlertTempo(false);
SetAlertAgente(false);
}
if ($chamadaValida && $exigeClass && !$naoClass && $startAlert && !GetAlertAgente()) {
SetAlertAgente(true);
SetAlertTempo(time());
}
$alertTEmpo = GetAlertTempo();
$alerta = (GetAlertTempo() !== false) && ((time() - GetAlertTempo())) > GetTempoAlertClas();
if (!$naoClass && GetAlertAgente() && $alerta && $startAlert) {
GetUrl(AST_ALERTA_AGENTE);
SetAlertAgente(false);
SetAlertTempo(false);
}
if (($_SESSION[SS_STATUS_AGENTE] != 'OCUPADO') && ($_SESSION[SS_STATUS_AGENTE] != 'ORIGINANDO')) {
$dadosMonitor["duracao"] = '00:00:00';
}
if (($_SESSION[SS_STATUS_AGENTE] != 'OCUPADO') || ($_SESSION[SS_STATUS_AGENTE] != 'CHAMANDO')) {
$_SESSION["txt_cliente"] = "";
}
if (($_SESSION[SS_STATUS_AGENTE] != 'PAUSA')) {
$_SESSION[SS_PAUSA_AGENTE] = 0;
} else {
$nomePausa = $dadosMonitor["pausa_motivo_rt"];
if (strtoupper($nomePausa) == 'AUSENTE') {
/*
* Pausa ausente é setada pela central toda vez que o agente não atende a uma chamada.
*/
$dadosMonitor["pausa_motivo_ausente"] = 1;
} else if (strtoupper($nomePausa) == 'RECUSADA') {
$dadosMonitor["pausa_motivo_ausente"] = 2;
}
}
/*
* Ajusta o status dispnivel_atendimento com base na variavel de sessao SS_CK_DISPO, que tem seu valor modificado
* na função DisponivelAtendimento().
*/
if ($_SESSION["SS_CK_DISPO"] && !$dadosMonitor["disponivel_atendimento"]) {
$dadosMonitor["disponivel_atendimento"] = 1;
}
$dadosMonitor["fone"] = ocultarTelefone($dadosMonitor["fone"]);
$pref = '';
//GetMunOrigem($dadosMonitor);
$statusAgente = trim($_SESSION[SS_STATUS_AGENTE]);
$dadosFone = trim($dadosMonitor["fone"]);
$txtCliente = trim($_SESSION["txt_cliente"]);
$statusDiscador = $dadosMonitor["status_discador"];
$dispIntegracao = false;
if (!$statusDiscador) {
$dadosIntegracao = GetDadosIntegracao($dadosMonitor["cont_identificador"]); //dado alimento pelo agente_fila com orgem na tabela pbx_integracao_reg
$dispIntegracao = $dadosIntegracao !== false;
if ($dispIntegracao) {
$dadosMonitor = array_merge($dadosMonitor, $dadosIntegracao);
}
if (($dadosFone != "") && (($statusAgente === 'OCUPADO') || ($statusAgente === 'CHAMANDO') ) && (!$dispIntegracao)) {
$cliente = GetClienteClassifica($dbcon, $dadosFone);
$dadosMonitor["txt_cliente"] = $cliente;
$_SESSION["txt_cliente"] = trim($dadosMonitor["txt_cliente"]);
}
}
$dadosMonitor["abandonadasRet"] = RetornaAbandon($dbcon, $dadosMonitor["dac_logado"], GetRamalMonitorar(RAMAL_MONITOR_AGENTE), "", "", $dadosMonitor["abandonadasRet"]);
/*
* $dispIntegracao -> Indica que dados obtidos de uma integração seriam mostrados no campo do discador.
*/
if (!$dispIntegracao) {
$dadosMonitor['disp_param0'] = 'Identificador';
/*
* Verifica se existe uma campanha ativa para o dac/agente.
*/
$dadosDiscador__ = GetDadosDiscador($dac, 0);
$idCampanha = GetCampanhaDiscador($dac);
if ($statusDiscador) {
$idCampanha = GetCampanhaDiscador($dac);
if ($idCampanha !== false) {
$dadosDiscador__ = GetDadosDiscador($dac, $idCampanha);
}
}
$ContatosRestantes = 0;
if ($dadosDiscador__ !== false) {
$dadosDiscador = $dadosDiscador__;
}
if (HabilitaDiscador()) {
$infoContatos = GetDiscadorRestantes($dac, $matricula, $idCampanha);
$dadosMonitor['quantidade_contatos'] = $infoContatos['quantidade_contatos'];
$dadosMonitor['quantidade_discados'] = $infoContatos['quantidade_discados'];
$dadosMonitor['contatos_restantes'] = $infoContatos['contatos_restantes'];
$dadosMonitor = array_merge($dadosMonitor, $dadosDiscador);
}
}
if (!$dadosMonitor['tma'])
$dadosMonitor['tma'] = '0';
if (!$dadosMonitor['tme'])
$dadosMonitor['tme'] = '0';
$dadosMonitor['vendido'] = !UseModVendas() ? '0' : GetVendasAgente($dac, $matricula);
echo FormataDadosRt($dadosMonitor);
//if($dadosMonitor["tempo_atualiza"] >= 30){ UpdateLogoffRt($dbcon); }
UpdateLogoffRt($dbcon);
}
} else {
/*
* Tratamento de ações invocadas pelo agente.
*/
$obStart = ob_start();
$obClean = ob_clean();
if ($acao == 'classifica') {
SetAlertOcupado(false);
SetAlertAgente(false);
SetAlertTempo(false);
ClassificaChamada($dbcon);
} else if ($acao == 'discar') {
$acaoDiscar = $_GET["acaoDiscar"];
if ($acaoDiscar == 2) {
IniciaTransferenciaConsultaRt();
} else {
AgtCallRt($dbcon);
}
} else if ($acao == 'pesquisa') {
TransfPesquisa($dbcon);
} else if ($acao == 'finalizar') {
FinalizaTransferenciaConsultaRt();
} else if ($acao == 'dispAtendimento') {
DisponivelAtendimento();
} else if ($acao == 'liberaDiscador') {
LiberaDiscador($dbcon);
} else if ($acao == 'dispDiscador') {
AtivaDiscador($dbcon);
} else if ($acao == 'incluiDiscador') {
IncluiDiscador($dbcon);
} else if ($acao == 'statusFoneDiscador') {
StatusFoneDiscador($dbcon);
} else if ($acao == 'operaDiscador') {
FuncoesOperacao();
} else if ($acao == 'protoExterno') {
GravaProtocoloExterno();
} else if ($acao == 'integracao' && GetStatusAgente() && GetAtivaIntegracao()) {
RealizaConsultaIntegracao();
}
}
/*
* Fim área comum das ações.
*/
ob_flush();
exit;
}
function TransfPesquisa($db) {
$plId = $_GET["plId"];
$numeroTransf = "psq-" . $plId . "-ini";
$matricula = GetMatricula();
$_SESSION[AGT_NUM_DISC] = $numeroTransf;
$idProgPesquisa = __GetIdProgPesquisa();
$GLOBALS["PESQUISA_MATRICULA"] = $matricula;
try {
/*
* Pega o canal do agente
*/
$query = "select canal, uniqueid, dac from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result || !pg_num_rows($result)) {
GeraExcept("não foi possível obter Informações da chamada!");
}
$row = @pg_fetch_row($result);
$canal = $row[0];
$uid = $row[1];
$dac = $row[2];
/*
* Registra que o agente clicou em transferir a pesquisa
*/
GravaFull($idProgPesquisa, $uid, 'O agente clicou em transferir pesquisa!');
if (!$canal) {
GeraExcept("não foi possível recuperar o canal para realizar a transferencia!");
}
$_SESSION[AGT_CHANNEL_TRANSF] = $canal;
if (!GetUrl(AST_TRANSF_PESQUISA)) {
GeraExcept("não foi possível realizar a transferencia!");
}
$sql = sprintf("INSERT INTO pbx_pesquisa_log (uniqueid, id_dac, fila, matricula, pl_id, plog_log) VALUES (%s, %s, %s, %s, %s, %s);", QuotedStr($uid), QuotedStr(GetDacCod($db, $dac)), QuotedStr($dac), QuotedStr($matricula), QuotedStr($plId), QuotedStr('MANUAL'));
$rst = pg_query($db, $sql);
if (!$rst) {
GeraExcept("não foi possível registrar o envio para a pesquisa!");
}
/*
* Transferencia realizada com sucesso limpa o status do agente.
*/
$query = "update pbx_supervisor_agentes
set status = 'LIVRE',
protocolo = '',
origem_destino = '',
duracao = now(),
canal = '',
canal_agente = '',
canal_transfer = '',
uniqueid = ''
where matricula = '$matricula'";
pg_query($db, $query);
/*
* Notifica o agente que a chamada foi encaminhada para a pesquisa com sucesso.
*/
echo "OK;Transferência realizada com sucesso!";
} catch (Exception $exc) {
echo "ERRO;" . $exc->getMessage();
/*
* Registra erro ao tentar tranferir a pesquisa.
*/
if (!$uid) {
RegistroInc(false, "select uniqueid from pbx_supervisor_agentes where matricula = '$matricula'");
}
GravaFull($idProgPesquisa, $uid, $exc->getMessage());
}
}
function __GetIdProgPesquisa() {
return RegistroInc(false, "select id_prog from pbx_funcoes_internas where arquivo like '%pesquisa.php'");
}
function FechaRegistroDiscaor($db) {
try {
$matricula = GetMatricula();
/*
* Libera o registro para nova discagem.
*/
$query = sprintf("update pbx_campanha_operacao set cmpo_status = 1 where cmpo_status = 2 and matricula = %s", QuotedStr($matricula));
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;Erro ao alterar o status da operação!");
};
return true;
} catch (Exception $ex) {
RegistraLogAgente("FechaRegistroDiscaor", $ex->getMessage(), $ex);
return false;
}
}
function GetPendenciaDiscador($db, $silent = false) {
$matricula = GetMatricula();
$query = "select count(*) as num_reg
from pbx_campanha_contato_fone a, pbx_campanha_operacao b
where b.cont_id = a.cont_id
and b.matricula = '$matricula'
and b.cmpo_status in(0, 2)
and a.conf_discado = 1
and a.conf_status = '0'";
if (RegistroInc($db, $query)) {
if ($silent) {
return true;
}
GeraExcept("Para realizar esta operação é necessário informar um status para o contato discado!");
}
return false;
}
function AtivoDiscador($db) {
$matricula = GetMatricula();
$query = "select status_discador from pbx_supervisor_agentes where matricula = '$matricula'";
return RegistroInc($db, $query);
}
function LiberaDiscador($db) {
global $dac;
$liberar = $_REQUEST['liberar'];
$msg = $_REQUEST['msg'];
$status = $_REQUEST['status'];
$confId = $_REQUEST['conf_id'];
$contId = $_REQUEST['cont_id'];
$inTran = 0;
$matricula = GetMatricula();
$uid = trim($_REQUEST['uniqueid']);
$uid = $uid ? QuotedStr($uid) : 'null';
try {
if ((GetDadosDiscador($dac, 0) === false)) {
GeraExcept("ERRO;não há atendimento pendente!");
}
/*
* se a classificação ogrigatória estiver configurada,
* garante que o discador não será liberado até que a
* chamada seja classificada.
if(GetExigeClas())
{
$liberar = 0;
}
*/
if ($_SESSION[SS_STATUS_AGENTE] == 'OCUPADO') {
GeraExcept("ERRO; não é possível encerrar o atendimento quando \"Ocupado\"!");
};
if (GetExigeClas() && !ChamdaClassificadaAgente($db, $matricula)) {
GeraExcept("ERRO;Para gravar o atendimento a chamda deve estar classificada!");
}
$result = pg_query($db, 'begin');
if (!$result) {
GeraExcept("ERRO;não foi iniciar uma transação!");
}
$inTran = 1;
$query = "update pbx_supervisor_agentes set status_discador = '1' where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;Erro ao liberar o agente!");
};
/*
* Marca o telefone com o ultimo staus
*/
// "update pbx_campanha_contato_fone set conf_status = %s, conf_agente_matricula = %s, conf_uid = %s where conf_id = %s";
$query = "update pbx_campanha_contato_fone set conf_discado = %s, conf_status = %s, conf_agente_matricula = %s, conf_uid = %s where conf_id = %s";
$query = sprintf($query, QuotedStr($liberar), QuotedStr($status), QuotedStr($matricula), $uid, QuotedStr($confId));
$result = pg_query($db, $query);
if (!$result || !pg_affected_rows($result)) {
GeraExcept("ERRO;não foi possível atualizar o número informado!");
}
/*
* Marca o contato da lista com discado.
*/
$query = sprintf("update pbx_campanha_contato set cont_discado = 1, cont_status = %s, cont_fechamento = now(), cont_msg = %s where cont_id = %s", QuotedStr($status), QuotedStr($msg), QuotedStr($contId));
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;Erro ao alterar o contato do número discado!");
};
/*
* Libera o registro para nova discagem.
*/
GetContidClient($contId, $uid);
$query = sprintf("update pbx_campanha_operacao set cmpo_status = %s, cmpo_fim = now() where cont_id = %s and cmpo_status in(0,2) and matricula = %s", QuotedStr($liberar ? '1' : '2'), QuotedStr($contId), QuotedStr($matricula));
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;Erro ao alterar o status da operação! Query: " . $query);
};
$result = pg_query($db, 'commit');
if (!$result) {
GeraExcept("ERRO;não foi finalizar a transação!");
}
echo sprintf("OK;Liberação executada com sucesso!;%s", ($liberar ? 'S' : 'N'));
} catch (Exception $ex) {
RegistraLogAgente("LiberaDiscador", $ex->getMessage(), $ex);
if ($inTran) {
pg_query($db, 'rollback');
}
echo $ex->getMessage();
}
}
function AtivaDiscador($db) {
global $dac;
try {
$dispo = $_REQUEST['dispo'];
$matricula = GetMatricula();
if (!AgenteON()) {
GeraExcept("ERRO;Para ativar o discador o agente deve estar conectado!");
}
FechaRegistroDiscaor($db);
if ((GetDadosDiscador($dac, 0) !== false)) {
GeraExcept("ERRO;Para desativar o discador é necessario encerrar o atendimento!");
}
if ($dispo && !AgenteLivre()) {
GeraExcept("ERRO;Para ativar o discador o agente deve estar com status \"LIVRE\"!");
}
if ($dispo && GetExigeClas() && !ChamdaClassificadaAgente($db, $matricula)) {
GeraExcept("ERRO;Para ativar o discador a chamada deve ser classificada!");
}
$inTran = 0;
$result = pg_query($db, 'begin');
if (!$result) {
GeraExcept("ERRO;não foi possível iniciar a transação!");
}
$inTran = 1;
$query = "update pbx_supervisor_agentes set status_discador = '$dispo', cont_identificador = '' where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;não foi possível realizar a operação!");
}
if ($dispo && GetAgenteDisponivelFila()) {
DisponivelAtendimento(0);
SetDispoDiscador(true);
} else if (GetDispoDiscador()) {
DisponivelAtendimento(0);
SetDispoDiscador(false);
}
$result = pg_query($db, 'commit');
if (!$result) {
GeraExcept("ERRO;não foi possível finalizar a transação!");
}
echo "OK;operação realizada com sucesso!";
} catch (Exception $ex) {
RegistraLogAgente("AtivaDiscador", $ex->getMessage(), $ex);
echo $ex->getMessage();
}
}
function IncluiDiscador($db) {
try {
global $dadosMonitor, $dac;
$inTran = 0;
$numero = soNumero($_REQUEST['numero']);
$matricula = GetMatricula();
$dadosDiscador = GetDadosDiscador($dac, 0);
if ($dadosDiscador === false) {
GeraExcept('ERRO@não foi possível acessar os dados da campanha');
}
$result = pg_query($db, 'begin');
if (!$result) {
GeraExcept('ERRO@não foi possível iniciar uma transação!');
}
$inTran = 1;
/*
* Verifica se o telefone já existe na base.
*/
$query = sprintf("select '' from pbx_campanha_contato_fone where cont_id = '%s' and conf_fone = '%s'", $dadosDiscador['cont_id'], $numero);
$result = pg_query($db, $query);
if (!$result) {
GeraExcept('ERRO@não foi possível verificar a lista do contato!');
}
if (pg_num_rows($result)) {
GeraExcept('ERRO@número já cadastrado para este contato!');
}
/*
* insere o telefone para o contato.
*/
$query = "insert into pbx_campanha_contato_fone(cmp_id, list_id, cont_id, conf_fone)values(%s, %s, %s, %s)";
$query = sprintf($query, QuotedStr($dadosDiscador['cmp_id']), QuotedStr($dadosDiscador['list_id']), QuotedStr($dadosDiscador['cont_id']), QuotedStr($numero));
$result = pg_query($db, $query);
if (!$result) {
GeraExcept('ERRO@não foi possível gravar o número informado!');
}
/*
* Recupera o id do telefone;
*/
$confId = GetCurrVal('pbx_campanha_contato_fone');
/*
* Exige que telefones já discados estejam com o status atualizado.
*/
$statusDiscado = GetNumDiscadoStatus($confId);
if ($statusDiscado !== false) {
GeraExcept(sprintf("ERRO@Antes de incluir um novo número(%s), você de gravar o status do número já discado%s!", $numero, $statusDiscado['conf_fone']));
}
/*
* Carrega a lista de telefones para ataulizar a operacao com o fone origianal selecionado.
*/
$listaFones = GetFonesContato($dadosDiscador['cont_id'], $dadosDiscador['conf_fone']);
$query = "update pbx_campanha_operacao set lista_fones_discador = %s where cmpo_id = %s";
$query = sprintf($query, QuotedStr($listaFones), QuotedStr($dadosDiscador['cmpo_id']));
$result = pg_query($db, $query);
if (!$result) {
GeraExcept('ERRO@não foi possível atualizar a lista do contato!');
}
/*
* Selediona o numero recem informado;
*/
$listaFones = GetFonesContato($dadosDiscador['cont_id'], $numero);
$result = pg_query($db, 'commit');
if (!$result) {
GeraExcept('ERRO@não foi possível finalizar a transação!');
}
/*
* sucesso retorna a lista de telefones.
*/
echo "OK@operação realizada com sucesso!@$listaFones";
} catch (Exception $ex) {
if ($inTran)
pg_query($db, 'rollback');
RegistraLogAgente("IncluiDiscador", $ex->getMessage(), $ex);
echo sprintf("%s", $ex->getMessage());
}
}
function StatusFoneDiscador($db, $silent = 0) {
try {
$status = soNumero($_REQUEST['status']);
$confId = soNumero($_REQUEST['conf_id']);
$uid = trim($_REQUEST['uniqueid']);
$uid = $uid ? QuotedStr($uid) : 'null';
$query = "update pbx_campanha_contato_fone set conf_status = %s, conf_agente_matricula = %s, conf_uid = %s where conf_id = %s";
$query = sprintf($query, QuotedStr($status), QuotedStr(GetMatricula()), $uid, QuotedStr($confId));
$result = pg_query($db, $query);
if (!$result || !pg_affected_rows($result)) {
GeraExcept("ERRO;não foi possível atualizar o número informado!;$confId;0");
}
if ($silent) {
return true;
}
echo "OK;operação realizada com sucesso!;$confId;$status";
} catch (Exception $ex) {
RegistraLogAgente("StatusFoneDiscador", $ex->getMessage(), $ex);
if ($silent) {
return false;
}
echo $ex->getMessage();
}
}
function FuncoesOperacao() {
try {
if (isset($_REQUEST['carregaFones'])) {
$query = "update pbx_campanha_operacao set carrega_fone = 1 where cmpo_id = %s";
$query = sprintf($query, QuotedStr($_REQUEST['carregaFones']));
$result = pg_query($query);
if (!$result) {
GeraExcept("ERRO;não foi possível carregar a lista de telefones!");
}
echo "OK;operação realizada com sucesso!";
}
if (isset($_REQUEST['discagemInicial'])) {
$query = "update pbx_campanha_operacao set discagem_inicial = 1 where cmpo_id = %s";
$query = sprintf($query, QuotedStr($_REQUEST['discagemInicial']));
$result = pg_query($query);
if (!$result) {
GeraExcept("ERRO;não foi possível realizar a discagem!");
}
echo "OK;operação realizada com sucesso!";
}
} catch (Exception $ex) {
RegistraLogAgente("FuncoesOperacao", $ex->getMessage(), $ex);
echo $ex->getMessage();
}
}
function GravaProtocoloExterno($dispMsg = true) {
try {
/*
* O protocolo do paraceiro deve ser informado com 12 numeros.
*/
$protoExterno = soNumero($_REQUEST['proto']);
if (!ValidaProtoParceiro($protoExterno)) {
GeraExcept("Protocolo Inválido!");
}
$matricula = GetMatricula();
$query = sprintf("select uniqueid2, protocolo from pbx_supervisor_agentes where matricula = '%s'", $matricula);
$result = pg_query($query);
if (!$result) {
GeraExcept("Erro consultar banco de dados!");
}
if (!pg_num_rows($result)) {
GeraExcept("não foi possível concluir a operação, \"Agente não Conectado\" registro não localizado!!");
}
$dados = pg_fetch_array($result);
$uid2 = trim($dados['uniqueid2']);
if (!$uid2) {
GeraExcept("não foi possível concluir a operação, \"Registro não Localizado\"!");
}
$query = sprintf("update pbx_protocolo_reg set protoparceiro = %s where uniqueid = %s", QuotedStr($protoExterno), QuotedStr($uid2));
$result = pg_query($query);
if (!$result || !pg_affected_rows($result)) {
GeraExcept("não foi possível registrar a informação!");
}
if ($dispMsg) {
echo "operação concluida com sucesso!";
}
return true;
} catch (Exception $ex) {
RegistraLogAgente("GravaProtocoloExterno", $ex->getMessage(), $ex);
if ($dispMsg) {
echo $ex->getMessage();
}
return false;
}
}
function DadosAtualiza($dbcon) {
global $statusServer;
$statusServer = false;
$arControle = GetInfoControle();
// print_r($arControle); exit;
/*
* Verifica o tempo de atuzlizção do servidor,
* se for inferior a 10s usa o servidor do su-
* pervisor para obter os dados, do contrário
* utiliza o acesso direto ao banco de dados.
*/
$ultAtu = time();
if($arControle){
$ultAtu = $ultAtu - $arControle['ultAtulizacao'];
}
if ($ultAtu < 10) {
$statusServer = true;
$matricula = GetMatricula();
/*
* Tenta obter os dados do supervisor atraves do acesso ao servico
* do supervisor
*/
$dados = RetornaDadosAgt($arControle);
//if(!IsAjax()) print_r($dados);
/*
* Se a função retornar dados retorna para aplicação, caso
* contrario continua com o banco de dados;
*/
if (count($dados) && isset($dados[$matricula])) {
$dadoAgt = $dados[$matricula];
foreach ($dadoAgt as $key => $value) {
$GLOBALS['dadosMonitor'][$key] = $value;
if (($key == 'status_agente') && ($value == 'PAUSA')) {
$_SESSION[SS_PAUSA_AGENTE] = 1;
} else if ($key == 'chamadas_atendidas') {
$GLOBALS['dadosMonitor']['atendidas_pa'] = $value;
} else if ($key == 'chamadas_originadas') {
$GLOBALS['dadosMonitor']['originadas_pa'] = $value;
}
}
return;
}
}
/*
* Recupera chamadas abandonadas sem retorno.
*/
SetAbandonasFila();
$query = GetQueryAgenteRt(1);
$result = pg_query($dbcon, $query);
$agenteLogado = $result && (pg_num_rows($result) > 0);
if ($agenteLogado) {
/*
* Dados da tablea pbx_supervisor_agentes
*/
$dados = pg_fetch_array($result);
foreach ($dados as $key => $value) {
if (!is_numeric($key)) {
$GLOBALS['dadosMonitor'][$key] = $value;
if (($key == 'status_agente') && ($value == 'PAUSA')) {
$_SESSION[SS_PAUSA_AGENTE] = 1;
}
}
}
/*
* Informacoes sobre o atendimento do agente
*/
$query = GetQueryAgenteRt(2);
$result = pg_query($dbcon, $query);
if ($result && (pg_num_rows($result) > 0)) {
$dados = pg_fetch_array($result, null, PGSQL_ASSOC);
foreach ($dados as $key => $value) {
$GLOBALS['dadosMonitor'][$key] = $value;
}
}
} else {
SetStatusAgente();
}
}
function DisablePausa() {
return AgenteON() && !AgentePausa() ? "" : 'disabled="disabled"';
}
function EntraPausa($db, $codMotivo) {
$regProc = QuotedStr(sprintf("AddPausa: Login: %s Scrp: %s Func: %s ", GetLogin(), 'agentert.php', 'EntradaPausa'));
$matricula = GetMatricula();
$dac = $_SESSION[SS_DAC_CODIGO];
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$motivoPausa = @GetPausaDescricao($db, $codMotivo);
$pausa_produtiva_obs = NullDb(trim($_POST['pausa_produtiva_obs']));
$emPausa = GetPausa($db, $matricula, true);
$inTran = 0;
try {
if ($emPausa) {
GetExcept("O agente já esta em pausa!");
}
GetPendenciaDiscador($db);
/*
* Coloca o agente em pausa no asterisk.
*/
if (!GetUrl(AST_ADD_PAUSA)) {
GetExcept("Falha ao colocar o agente em pausa na central!");
}
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid, status from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if ($result) {
$row = @pg_fetch_array($result);
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
@GetUrl(AST_DESLIGAR_LIGACAO);
}
/*
* Inicia a transação.
*/
$result = pg_query($db, "begin");
if (!$result) {
GetExcept("Erro ao iniciar o procedimento de pausa!");
}
/*
* Atualiza dados no superviosr.
*/
$query = "update pbx_supervisor_agentes
set status = 'PAUSA', motivo_pausa = '$motivoPausa', duracao = now(), origem_destino = ''
where matricula = '$matricula' and status <> 'PAUSA' ";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
GetExcept("Falha ao atualizar registro de pausa na supervisão!");
}
$relEvt = '0';
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, id_motivo_pausa, entrada_pausa, flag, relaciona_eventos, saida_pausa, pausa_produtiva, pausa_produtiva_obs, reg_proc)
values('$matricula', '$ramal', $dac, $codMotivo, now(), 0, $relEvt, now(), (select produtiva from pbx_motivos_pausas where id = '$codMotivo'), $pausa_produtiva_obs, $regProc)";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
GetExcept("Falha ao inserir registro de pausa no sistema!");
}
$result = pg_query($db, "commit");
if (!$result) {
GeraExcept("Nao foi concluir a remoção da pausa!");
}
$_SESSION[SS_PAUSA_AGENTE] = 1;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO] = $codMotivo;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO_DESCRICAO] = $motivoPausa;
$_SESSION[SS_STATUS_AGENTE] = 'PAUSA';
SetMsgAgente("O agente foi colocado em pausa!");
return true;
} catch (Exception $ex) {
pg_query($db, "rollback");
SetMsgAgente($ex->getMessage());
RegistraLogAgente("EntraPausa", $ex->getMessage(), $ex);
return false;
}
}
function SairPausa($db) {
global $jsStartup;
$regProc = QuotedStr(sprintf("|RemPausa: Login: %s Scrp: %s Func: %s ", GetLogin(), 'agentert.php', 'SairPausa'));
$matricula = GetMatricula();
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$login = GetLogin();
$dac = $_SESSION[SS_DAC_CODIGO];
$inTran = 0;
$emPausa = GetPausa($db, $matricula, true);
try {
if (!$emPausa) {
GeraExcept("O agente não esta em pausa!");
}
if (GetExigeClas() && !GetChamadaClassificada()) {
GeraExcept("Para sair de pausa é necessário Classificar a chamada!");
}
$audio = GetStatusChamadaClassificada($dac);
if ($audio) {
$audio = substr($audio, 0, -4);
GetAudioClassificacaoRamal($audio);
$modo = GetModoAtende() == ATENDIMENTO_AUTOMATICO ? ',1' : '';
$jsStartup[] = sprintf("GetAlertConfirmAudio('$audio'%s)", $modo);
$_SESSION['SSClassificaPendente'] = 1;
if ($modo) {
GeraExcept('Para escutar a chamada clique no botão ao lado.' . " <a href=\"javaScript:GetAlertConfirmAudio('$audio',1);\" style=\"color: #000;\">" . "<img src=\"imgSite/audio-escuta-apl.png\" align='absmiddle' border=\"0\">" . "</a>");
} else {
GeraExcept('Para escutar a chamada clique no botão ao lado.' . " <a href=\"javaScript:AudioEscutaApl('$audio');\" style=\"color: #000;\">" . "<img src=\"imgSite/audio-escuta-apl.png\" align='absmiddle' border=\"0\">" . "</a>");
}
}
/*
* Remove da pausa do asterisk somente se a opção disponivel atendimento nao
* estiver marcada,
*/
if (IsAgenteDisponivel($db, $matricula)) {
@GetUrl(AST_REM_PAUSA);
}
$result = pg_query($db, "begin");
if (!$result) {
GeraExcept("Nao foi possivel iniciar o procedimento de retirada da pausa!");
}
/*
* atualiza dados do supervisor
*/
$query = "update pbx_supervisor_agentes
set status = 'LIVRE',
motivo_pausa = '',
protocolo = '',
origem_destino = '',
duracao = now()
where matricula = '$matricula'
and status = 'PAUSA'";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
GeraExcept("Nao foi possivel atualizar as informações de pausa na supervisao!");
}
/*
* Registra a pausa no sistema.
*/
$query = "update pbx_eventos_agentes
set saida_pausa = now(),
flag = 2,
reg_proc = coalesce(reg_proc, '') || $regProc
where matricula = '$matricula'
and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
GeraExcept("Nao foi possivel atualizar as informações de pausa no sistema!");
}
$result = pg_query($db, "commit");
if (!$result) {
GeraExcept("Nao foi concluir a remoção da pausa!");
}
SetMsgAgente("O agente foi retirado da pausa!");
$_SESSION[SS_PAUSA_AGENTE] = 0;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO] = 0;
$_SESSION[SS_STATUS_AGENTE] = 'LIVRE';
return true;
} catch (Exception $ex) {
pg_query($db, "rollback");
SetMsgAgente($ex->getMessage());
RegistraLogAgente("SairPausa", $ex->getMessage(), $ex);
return false;
}
}
function ConnectaAgenteRt($db, $dac, $tpAtend) {
global $jsStartup, $argv;
$regProc = QuotedStr(sprintf("AddPausa: Login: %s Scrp: %s Func: %s ", GetLogin(), 'agentert.php', 'ConnectaAgenteRt'));
/*
* Se o agente já estiver logado aborta a operação de login
*/
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$ramalEst = VerificaRamalEstatico($db, $ramal, $dac);
$dacCheck = '';
$agtCheck = '';
SetStatusAgente();
try {
if (!$ramal) {
$msg = "não há ramal configurado!";
GeraExcept($msg);
}
if (VerficaAgenteLogado($db)) {
$ramalCon = GetRamalAgenteLogado($db);
$msg = "não é possível conectar ao servidor, o Agente já está Conectado no Ramal: $ramalCon!";
GeraExcept($msg);
}
/*
* Remove conexoes do usuario corrente.
*/
LimpaConexao($db);
if (VerificaRamalLogado($db, $dacCheck, $agtCheck)) {
$msg = "não é possível conectar ao servidor, Ramal: \"$ramal\" conectado! Dac: \"$dacCheck\" Agente: \"$agtCheck\"";
GeraExcept($msg);
}
if ($ramalEst) {
$msg = "não é possível conectar ao servidor, Ramal: \"$ramal\" estático na(s) fila(s): \"[$ramalEst]\"!";
GeraExcept($msg);
}
if (VerificaMaxAgenteLogado($db) ) {
$msg = "não é possível conectar o Agente! O número Máximo de \"PAs\" simultaneos já foi atingido!";
GeraExcept($msg);
}
if (VerificaRamalSigame($db, $ramal)) {
$msg = "não é possível conectar ao servidor, Ramal: \"$ramal\" possui siga-me ativado";
GeraExcept($msg);
}
if (VerificaClassObrigatoria($db, $dac)) {
$msg = "Está configurado \"classificação Obrigatória\", mas não há clssificações disponiveis para este Dac!";
GeraExcept($msg);
}
/*
* Seleciona a descricao do dac escolhido;
*/
$query = "select nome from pbx_dacs where id = '$dac'";
$result = pg_query($db, $query);
if (!$result) {
$msg = "não foi possível consultar o DAC!";
GeraExcept($msg);
}
$row = pg_fetch_row($result);
$_SESSION[SS_DAC_DESCRICAO] = $row[0];
$modoAtendimento = VerificaModoAtendimento($db, $dac);
if ($modoAtendimento != "default") {
$_SESSION[SS_MODO_ATENDIMENTO] = $modoAtendimento == 'manual' ? "Manual" : "Automático";
$_SESSION[SS_MODO_ATENDIMENTO_COD] = $modoAtendimento == 'manual' ? ATENDIMENTO_MANUAL : ATENDIMENTO_AUTOMATICO;
$tpAtend != $_SESSION[SS_MODO_ATENDIMENTO_COD] ? $jsStartup[] = "alert('você foi conectado no modo atendimento {$_SESSION[SS_MODO_ATENDIMENTO]}');" : '';
} else {
$_SESSION[SS_MODO_ATENDIMENTO] = $tpAtend == ATENDIMENTO_MANUAL ? "Manual" : "Automático";
$_SESSION[SS_MODO_ATENDIMENTO_COD] = $tpAtend;
}
/**
* Verifica a disponibilidade da fila
*/
$q = "SELECT disponivelfila FROM pbx_queues_grupos WHERE id = '$dac'";
$res = pg_query($db, $q);
$ret = pg_fetch_assoc($res);
$_SESSION["prm_disponivel_fila"] = $ret['disponivelfila'];
$moduAtendDesc = $_SESSION[SS_MODO_ATENDIMENTO];
$_SESSION[SS_DAC_CODIGO] = $dac;
$matricula = GetMatricula();
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$login = GetLogin();
$conAst = false;
$_SESSION[SS_AGT_CONTEXTO_RAMAL] = GetContextoRamal($db, $ramal);
/*
* loga o agente no asterisk
*/
if (!GetUrl(AST_LOGIN_AGENTE)) {
$msg = "não foi possível logar o agente!";
GeraExcept($msg);
}
/*
* Verifica se o login foi executado com sucesso.
*/
sleep(1);
$verConexao = 0;
$i = 0;
while ($i++ < 10) {
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' and upper(status) = 'PAUSA' ";
$result = pg_query($db, $query);
if (!$result) {
$msg = "não foi possível verificar a conexão do agente!";
GeraExcept($msg);
}
$row = pg_fetch_row($result);
/*
* Se a verificação foi efetuada com sucesso, retorna para a função.
*/
if ($row[0]) {
$verConexao = true;
break;
}
$NumArgv = $argv[0] ?? "";
WriteLog(sprintf("Script: %s Data: %s Cmd: %s\n", $NumArgv, (date("Y-m-d H:m:i") . '.' . microtime(true)), $query), "/var/log/asterisk/log_erro_pabx.log");
usleep(500000);
}
if (!$verConexao) {
$msg = "O registro do agente não está disponível!";
GeraExcept($msg);
}
/*
* Registra login no banco de dados.
*/
$dacDesc = $_SESSION[SS_DAC_DESCRICAO];
$result = pg_query($db, "begin");
if (!$result) {
$msg = "Não foi possível iniciar uma transação para registrar o login do agente!";
GeraExcept($msg);
}
/*
* Registra o agente na supervisão.
*/
$query = "update pbx_supervisor_agentes
set ramal = '$ramal', nome = '$login', dac = '$dacDesc', modo_atendimento = '$moduAtendDesc', duracao = now(), chamada_classificado = '2'
where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
$msg = "Não foi possível registrar o login do agente na supervisão!";
GeraExcept($msg);
}
/*
* Registra o login do agente no sistema.
*
*/
$query = "insert into pbx_eventos_agentes(matricula,ramal,id_dac,\"login\", logoff, flag) values('$matricula', '$ramal',$dac, now(),now(),0)";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
$msg = "não foi possível registrar o login do agente no sistema!";
GeraExcept($msg);
}
/*
* Registra pausa de Login.
*/
$idMotivoPausa = GetMotivoLogin($db);
$relEvt = '0';
$query = "insert into pbx_eventos_agentes(matricula,ramal,id_dac,id_motivo_pausa,entrada_pausa,flag,relaciona_eventos, reg_proc) values('$matricula', '$ramal',$dac,$idMotivoPausa,now(),0,$relEvt, $regProc)";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
$msg = "não foi possível registrar a pausa do login!";
GeraExcept($msg);
}
$result = pg_query($db, "commit");
if (!$result) {
$msg = "não foi possível finalizar o registro de login do agente!";
GeraExcept($msg);
}
/*
* Tem a simples função de ativar os numeros de discagem,
* qdo o agente desloga sem encerrar uma operação de dis-
* gem;
*/
@AtivaNumeroDiscagem($db, $matricula);
SetMsgAgente("operação realizada com sucesso!");
SetStatusAgente(1);
$_SESSION[SS_PAUSA_AGENTE] = 1;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO] = $idMotivoPausa;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO_DESCRICAO] = 'login';
$_SESSION[SS_STATUS_AGENTE] = 'PAUSA';
$_SESSION[SS_EXIGE_CLASSIFICACAO] = GetExigeClas($db, $dac);
$_SESSION[SS_JUSTIFICATIVA_PAUSA] = GetObsProdAgente($db, $dac);
$_SESSION["SSPausaAtomatica"] = GetPausaAutomatica($db, $dac);
$_SESSION["SS_CK_DISPO"] = 1;
$_SESSION["SS_ultimo_dac_agente"] = $dac;
$_SESSION['SSClassificaPendente'] = 0;
$_SESSION['SS_IS_LOGGED'] = true;
return true;
} catch (Exception $ex) {
//APRESENTA POPUP COM A MENSAGEM DE ERRO
$jsStartup[] = sprintf("alert('%s');", $ex->getMessage());
SetMsgAgente($ex->getMessage());
SetStatusAgente();
$_SESSION[SS_PAUSA_AGENTE] = 0;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO] = '';
$_SESSION[SS_PAUSA_AGENTE_MOTIVO_DESCRICAO] = '';
$_SESSION[SS_STATUS_AGENTE] = 'OFF';
$_SESSION[SS_EXIGE_CLASSIFICACAO] = NULL;
$_SESSION[SS_JUSTIFICATIVA_PAUSA] = NULL;
pg_query($db, "rollback");
RegistraLogAgente("ConnectaAgenteRt", $ex->getMessage(), $ex);
return false;
}
}
function DesConectaAgenteRt($db, $type = '') {
global $jsStartup;
$matricula = GetMatricula();
$ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE);
$login = GetLogin();
$dac = $_SESSION[SS_DAC_CODIGO];
try {
if (GetExigeClas() && !GetChamadaClassificada()) {
GeraExcept("Para efetuar o logoff é necessário Classificar a chamada!");
}
GetPendenciaDiscador($db);
if ($_SESSION['prm_aviso_desconnect'] == 'yes' && empty($type)) {
$jsStartup[] = "GetAvisoDesconnect()";
return false;
}
/*
* Se o agente estiver em pausa é removido antes de deslogar.
*/
if ($_SESSION[SS_PAUSA_AGENTE]) {
@SairPausa($db);
}
/*
* Se o tipo de atendimento for manual remove agente da fila.
*/
if ($_SESSION[SS_MODO_ATENDIMENTO_COD] == ATENDIMENTO_MANUAL) {
@GetUrl(AST_REM_FILA);
}
/*
* Desliga a chamada corrente
* e desconecta o usuario do asterisk
*/
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid, status from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if ($result) {
$row = @pg_fetch_array($result);
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
@GetUrl(AST_DESLIGAR_LIGACAO);
}
@GetUrl(AST_LOGOFF_AGENTE);
$result = pg_query($db, "begin");
if (!$result) {
GeraExcept("não foi possível iniciar a desconexão do agente!");
}
//atualiza dados do supervisor
/*
* Quando este parametro for 0 nao mais ha dados do agennte nesta tabela
*/
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("não foi possível remover o agente da supervisão!");
}
$query = "update pbx_eventos_agentes
set logoff = now(), flag = 2
where matricula = '$matricula'
and id_dac = '$dac'
and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = '$dac') ";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
GeraExcept("Falha ao registrar o logoff do agente no sistema!");
}
$result = pg_query($db, "commit");
if (!$result) {
GeraExcept("não foi possível finalizar o registro de logoff do agente!");
}
$_SESSION['SS_IS_LOGGED'] = false;
SetMsgAgente("Agente desconectado com sucesso!");
AgenteDesconectRt();
return true;
} catch (Exception $ex) {
pg_query($db, "rollback");
SetMsgAgente($ex->getMessage());
RegistraLogAgente("DesConectaAgenteRt", $ex->getMessage(), $ex);
return false;
}
}
function GetQueryAgenteRt($qr) {
$matricula = GetMatricula();
$dac = isset($_SESSION[SS_DAC_CODIGO]) ? $_SESSION[SS_DAC_CODIGO] : 0;
$fila = isset($_SESSION[SS_DAC_DESCRICAO]) ? $_SESSION[SS_DAC_DESCRICAO] : '';
if ($qr == 1) { //substring(now()::time, 1, 8) as hora_atu, ( (EXTRACT(EPOCH FROM (now() - a.duracao)) / 60)) as status_time,
return "select (LOCALTIMESTAMP(0) - tempo_login) as tempo_logado, origem_destino as fone,
trim(status) as status_agente, (LOCALTIMESTAMP(0) - duracao) as duracao,
protocolo as num_protocolo, ramal as ramal_monitor,
uniqueid2, extract(epoch from (now() - logado))::int as tempo_atualiza,
trim(motivo_pausa) as pausa_motivo_rt,
trim(uniqueid) as uniqueid, disponivel_atendimento, chamada_classificado, coalesce(canal_transfer, '') as canal_transfer,
tipo_ligacao, cont_identificador, status_discador
from pbx_supervisor_agentes
where matricula = '$matricula' ";
}
if ($qr == 2) {
/*
* Informações sobre a fila de atendimento
*/
return "SELECT
ATENDIDAS_PA, ABANDONADAS, (select espera from pbx_supervisor_dacs where dac = dados.FILA) as qtde_fila
,(select tempo_espera * INTERVAL '1 SECOND' from pbx_supervisor_dacs where dac = dados.FILA) as TME
,ORIGINADAS_PA
,round( CASE WHEN(ATENDIDAS_PA = 0)THEN 0 ELSE ((TEMPO_ATENDIMENTO + TEMPO_ORIGINDADA) / (ATENDIDAS_PA + ORIGINADAS_PA))END) * INTERVAL '1 SECOND' AS TMA
FROM (
SELECT fila
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER', 'TRANSFER','COMPLETEAGENTRAMAL','COMPLETECALLERRAMAL') THEN 1 ELSE 0 END) AS ATENDIDAS_PA
,SUM (CASE WHEN EVENTO = 'ABANDON' THEN 1 ELSE 0 END) AS ABANDONADAS
,SUM (CASE WHEN EVENTO IN ('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG','BUSYS','NOANSWERS') THEN 1 ELSE 0 END) AS ORIGINADAS_PA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND strtoint(param1) > '3' THEN 1 ELSE 0 END) AS ESPERA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND strtoint(param1) > '1' THEN strtoint(param1) ELSE 0 END) AS TEMPO_ESPERA
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER') AND strtoint(param2) > '1' THEN strtoint(param2) ELSE 0 END) AS TEMPO_ATENDIMENTO
,SUM (CASE WHEN EVENTO IN ('COMPLETAAGENT','COMPLETACALLER') AND strtoint(param2) > '1' THEN strtoint(param2) ELSE 0 END) AS TEMPO_ORIGINDADA
,SUM (CASE WHEN( (EVENTO = 'ABANDON') AND (strtoint(param2) > '1') ) THEN strtoint(param3) ELSE 0 END) AS TEMPO_ABANDONO
FROM (
SELECT
a.calldate,b.fila,b.evento,b.param1,b.param2,b.param3,b.param4
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b on b.uid2 = a.uniqueid
INNER JOIN pbx_dacs c on c.nome = b.fila
LEFT JOIN pbx_usuarios d on d.matricula = SUBSTRING(b.agente,7 ,4)
WHERE b.evento in ('CONNECT','ABANDON','COMPLETEAGENT','COMPLETECALLER','TRANSFER', 'COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG','ENTERQUEUE','BUSYS','NOANSWERS','COMPLETEAGENTRAMAL','COMPLETECALLERRAMAL')
AND a.lastapp <> 'Transferred Call'
AND a.data_bilhete = now()::date
AND c.id = $dac
AND d.matricula = '$matricula'
) AS DADOS
GROUP BY FILA
) AS DADOS";
}
}
function FormataDadosRt($dados) {
$ret = '';
foreach ($dados as $key => $value) {
$key = trim($key);
$value = str_replace('@', '##', $value);
$ret .= !$ret ? "$key|$value" : "@$key|$value";
}
return $ret;
}
function UpdateLogoffRt($db) {
if ($_SESSION[SS_PAUSA_AGENTE]) {
@UpdatePausaRt($db);
}
$matricula = GetMatricula();
$dac = $_SESSION[SS_DAC_CODIGO];
$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 matricula = '$matricula'
and id_dac = $dac
and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
/** ERRO AO ATUALIZAR AGENTE **/
}
function UpdatePausaRt($db) {
$matricula = GetMatricula();
$dac = $_SESSION[SS_DAC_CODIGO];
$query = "update pbx_eventos_agentes
set saida_pausa = now(),
flag = 1
where matricula = '$matricula'
and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
}
function AgenteDesconectRt() {
$_SESSION[SS_STATUS_AGENTE] = 'OFF';
SetStatusAgente();
$_SESSION[SS_PAUSA_AGENTE] = 0;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO] = 0;
$_SESSION[SS_PAUSA_AGENTE_MOTIVO_DESCRICAO] = "";
$_SESSION[SS_EXIGE_CLASSIFICACAO] = NULL;
$_SESSION[SS_JUSTIFICATIVA_PAUSA] = NULL;
$_SESSION[SS_DAC_DESCRICAO] = "";
}
function LimpaConexao($db) {
/*
* Matricula do usuário logado
*/
$matricula = GetMatricula();
@LogAgente("LimpaConexao", "Inicio", true);
/*
* Desliga a chamada corrente
* e desconecta o usuário do asterisk
*/
$query = "select canal, canal_transfer, canal_agente, ramal, upper(modo_atendimento) as modo_atendimento, dac, uniqueid, status from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result || !pg_num_rows($result)) {
@LogAgente("LimpaConexao", "Nao logado: {$matricula}", false);
return;
}
$dadosConexao = @pg_fetch_array($result);
$canal = $dadosConexao['canal'];
$canalAgente = $dadosConexao['canal_agente'];
$ramal = $dadosConexao['ramal'];
$dac = $dadosConexao['dac'];
$status = $dadosConexao['status'];
$modoAtendimento = $dadosConexao['modo_atendimento'];
/*
* Derruba chamada caso esteja em curso.
*/
if ($canalAgente) {
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $canalAgente;
@GetUrl(AST_DESLIGAR_LIGACAO);
}
/*
* Retira o agente de pausa na central.
*/
if ($status == 'PAUSA') {
@SairPausa($db);
}
/*
* Se o tipo de atendimento for manual remove agente da fila.
*/
if ($modoAtendimento == 'MANUAL') {
@GetUrl(AST_REM_FILA);
}
/*
* Desloga o agente na central.
*/
@GetUrl(AST_LOGOFF_AGENTE, $dac, $matricula);
/*
* Quando este parametro for 0 nao mais ha dados do agennte nesta tabela
*/
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
pg_query($db, $query);
$query = "update pbx_eventos_agentes
set logoff = now(), flag = 2
where matricula = '$matricula'
and id_dac = '$dac'
and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = '$dac') ";
pg_query($db, $query);
@LogAgente("LimpaConexao", "Logado: {$matricula}", false);
AgenteDesconectRt();
}
function SetStatusAgente($status = 0) {
$_SESSION[SS_AGENTE_CONECTADO] = $status;
}
function GetStatusAgente() {
return isset($_SESSION[SS_AGENTE_CONECTADO]) ? $_SESSION[SS_AGENTE_CONECTADO] : 0;
}
function ClassificaChamada($db) {
$dac = $_SESSION[SS_DAC_CODIGO];
$matricula = GetMatricula();
$result = true;
$msg = '';
if (!isset($_GET["contrib_id"]) || !$_GET["contrib_id"]) {
$idContrib = 'null';
} else {
$contr = explode("-", $_GET["contrib_id"]);
$idContrib = soNumero($contr[0]) ? soNumero($contr[0]) : null;
/*
* Verifica se o cliente existe na base.
*/
$query = "select count(*) from pbx_contribuinte where contrib_id = '$idContrib'";
if (!($idContrib && RegistroInc($db, $query))) {
$idContrib = 'null';
}
}
$clas = $_GET["idClas"];
$clasItem = $_GET["idClasItem"];
$uniqueid = $_GET["uniqueid"];
$proto = isset($_GET["proto"]) ? $_GET["proto"] : '';
$munId = 0;
$inTran = 0;
try {
if (GetPausaAusente($db, $matricula)) {
SetaClassificaChamado($db, 1, 0);
echo "OK;Pausa ausente não pode ser classificada, chamada liberada!";
return;
}
/*
* O protocolo externo pode passar junto com a classificação.
*/
if ($proto) {
if (!ValidaProtoParceiro($proto)) {
GeraExcept("ERRO; Protocolo Inválido!");
}
if (!GravaProtocoloExterno(false)) {
GeraExcept("ERRO; não foi possível gravar o protocolo!");
}
}
if (UseModVendas() && ExigeProtoVendas()) {
if (!GetProtoExternoReg($uniqueid, $clas)) {
GeraExcept('ERRO; Antes de classificar como "Venda" informe o "Protocolo"!');
}
}
$result = pg_query($db, 'begin');
if (!$result) {
GeraExcept("ERRO;não foi possível iniciar o registro da classificação no sistema!");
}
$inTran = 1;
/*
* Esta Informações são utilizadas no relatorio de abandonadas na fila para identificar
* qdo o agente não esta recdebendo uma chamada por não ter classificado a mesma estando
* portanto desabilitado de receber chamadas o que pode causar abandono.
*/
$query = "update pbx_registra_classificacao set rgc_saida = now(), matricula_reg = '$matricula' where uid = '$uniqueid' and rgc_saida is null";
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("ERRO;não foi possível registrar a classificação no sistema!");
}
/*
* Registra a classificação.
*/
$query = "insert
into pbx_classifica_reg(matricula, clas_id, clit_id, id_bilhetes, id_dac, mun_id";
if($idContrib != 'null'){
$query .= ", idcontrib) values(%s,%s,%s,%s,%s,%s,%s)";
$query = sprintf($query, QuotedStr($matricula), $clas, $clasItem, QuotedStr($uniqueid), $idContrib,$dac, $munId);
}else{
$query .= ") values(%s,%s,%s,%s,%s,%s)";
$query = sprintf($query, QuotedStr($matricula), $clas, $clasItem, QuotedStr($uniqueid),$dac, $munId);
}
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
$erro = @pg_last_error();
if (stripos($erro, "duplicate key ") !== false) {
GeraExcept("ERRO;Esta classificação já foi registrada!");
}
GeraExcept("ERRO;não foi possível registrar a classificação!");
}
/*
* Atualizar o supervisor.
*/
if (!SetaClassificaChamado($db, 1, 1)) {
GeraExcept("ERRO;não foi possível atualizar a supervisão!");
}
$result = pg_query($db, 'commit');
if (!$result) {
GeraExcept("ERRO;não foi possível concluir o registro da classificação no sistema!");
}
echo "OK;classificação registrada com sucesso!";
} catch (Exception $ex) {
RegistraLogAgente("ClassificaChamada", $ex->getMessage(), $ex);
if ($inTran) {
pg_query($db, 'rollback');
}
$msg = $ex->getMessage();
echo $msg;
}
}
function ExistePrefixo($db, $prefixo) {
$query = "select count(*) from pbx_municipio_prefixo where prx_prefixo = '$prefixo'";
$result = pg_query($db, $query);
if ($result) {
$row = @pg_fetch_row($result);
return $row[0];
}
return false;
}
function GravaPrefixo($db, $munId, $prefixo, $upd = 0) {
if ($upd) {
$query = "update pbx_municipio_prefixo set mun_id = '$munId' where prx_prefixo = '$prefixo'";
} else {
$query = "insert into pbx_municipio_prefixo(mun_id, prx_prefixo)values('$munId', '$prefixo')";
}
$result = pg_query($db, $query);
return $result && @pg_affected_rows($result);
}
function AgtCallRt($db) {
$msgSis = GetSlogan();
$matricula = GetMatricula();
$acaoDiscar = isset($_GET["acaoDiscar"]) && (!$_GET["acaoDiscar"]);
$numeroDiscar = soNumero($_GET["numeroDiscar"]);
$confId = isset($_GET['conf_id']) ? $_GET['conf_id'] : 0;
$discador = $confId > 0;
$inTran = 0;
try {
if (!AgenteON()) {
GeraExcept("0;ERRO;Por favor para realizar a operação é necessário estar com agente conectado!");
}
if (isset($_GET["numeroDiscar"]) && $acaoDiscar) {
if ($discador) {
$statusDiscado = GetNumDiscadoStatus($confId);
if ($statusDiscado !== false) {
GeraExcept(sprintf("9;ERRO;%s;%s!", $statusDiscado['conf_id'], $statusDiscado['conf_fone']));
}
if ($statusDiscado) {
$_SESSION['SSCodigoParam'] = $statusDiscado['cont_id'];
}
}
/*
* Altera o status do numero na lista.
*/
$result = pg_query($db, "begin");
if (!$result) {
GeraExcept("1;ERRO;não foi possível iniciar a operação!");
}
$inTran = 1;
AtualizaNumDiscador($db, $confId, $numeroDiscar);
//LimpaUidAgente($db, $matricula);
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
if (!GetUrl(AST_DISCAR)) {
GeraExcept("0;ERRO;não foi possível discar para o número informado!");
}
/*
* A ligação já foi efetuada pela central.
*/
pg_query($db, "commit");
echo "0;OK;Discagem realizada com sucesso!";
} else if (isset($_GET["numeroDiscar"])) {
$matricula = GetMatricula();
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
$result = pg_query($db, "begin");
if (!$result) {
GeraExcept("1;ERRO;não foi possível iniciar a Transferência!");
}
$inTran = 1;
/*
* obtem Informações do canal.
*/
$query = "select canal, canal_agente from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result) {
GeraExcept("1;ERRO;não foi possível obter Informações sobre o canal para Transferência!");
}
$row = @pg_fetch_row($result);
if (!$row[0]) {
GeraExcept("1;ERRO;não existe canal disponível para realizar a Transferência!");
}
/*
* Seta o canal para discagem
*/
if ($row[0]) {
$_SESSION[AGT_CHANNEL_TRANSF] = $row[0];
}
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row[1];
/*
* Incia a trasnferencia na central.
*/
GetUrl(AST_SET_VAR);
if (!GetUrl(AST_TRANSFERIR)) {
GeraExcept("1;ERRO;não foi possível transferir para o número informado!");
}
// if (!GetExigeClas() || !GetDisponivelAtendimetno()) {
// @GetUrl(AST_REM_PAUSA);
// }
$query = "update pbx_supervisor_agentes
set status = 'LIVRE', protocolo = '', origem_destino = '', duracao = now(), canal = '', canal_agente = '', uniqueid = ''
where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = $result && pg_affected_rows($result);
if (!$result) {
GeraExcept("1;ERRO;não foi possível registrar a Transferência para o número informado!");
}
$result = pg_query($db, "commit");
if (!$result) {
GeraExcept("1;ERRO;não foi possível finalizar a Transferência!");
}
echo "1;OK;Transferência realizada com sucesso!";
} else if (isset($_GET["numeroDiscar"]) && empty($_GET["numeroDiscar"])) {
echo "0;WNG;Informe um número!";
} else {
echo "0;WNG;Ação não identificada!";
}
} catch (Exception $ex) {
if ($inTran) {
pg_query($db, "rollback");
}
RegistraLogAgente("AgtCallRt", $ex->getMessage(), $ex);
echo $ex->getMessage();
}
}
function IniciaTransferenciaConsultaRt() {
try {
$numeroTransferencia = $_GET["numeroDiscar"];
$matricula = trim(GetMatricula());
$dbcon = $GLOBALS['dbcon'];
$moduAuto = (GetModoAtende() != ATENDIMENTO_MANUAL);
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("2;ERRO;não foi possivel obter Informações sobre a chamada!");
}
if (!pg_num_rows($result)) {
GeraExcept("2;WNG;não há nenhuma ligação em curso!");
}
/*
* Coleta Informações sobre a chamada.
*/
$row = @pg_fetch_array($result);
if (!$row["canal"]) {
GeraExcept("8;ERRO;não há canal disponível para realizar a Transferência!");
}
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$emtransf = !empty($row["canal_transfer"]);
/*
* Ainda não iniciou a transferencia
* Se canal_transfer estiver vazio
*/
if (!$emtransf) {
$_SESSION[AGT_NUM_DISC] = $numeroTransferencia;
//GetUrl(AST_ADD_PAUSA);
$cmd = array();
$cmd[] = Sprintf("%s: %s", "Action", "Setvar");
$cmd[] = Sprintf("%s: %s", "channel", GetChannelAgente());
$cmd[] = Sprintf("%s: %s", "variable", "ESPERA_AGENTE_DESATIVADO");
$cmd[] = Sprintf("%s: %s", "value", "OK");
SetCmdAmi($cmd);
GetUrl(AST_EXEC_AMI);
GetUrl(AST_SET_VAR);
$retPendulo = IniciaPenduloRt();
$retA = explode(";", $retPendulo);
$result = $retA[1] == "OK";
if (!$result) {
GeraExcept($retPendulo);
}
sleep(1);
/*
* Agente em atendimento automatico.
*/
// if ($moduAuto) {
// $result = GetUrl(AST_TRCONSULTA_ESPERA);
// }
if ($moduAuto && !$result) {
GeraExcept("2;ERRO;não foi possível discar para o agente!");
}
/*
* Tenta alterar as Informações no agente.
*/
$query = "update pbx_supervisor_agentes set canal_transfer = 'Agent/$matricula' where matricula = '$matricula'";
pg_query($dbcon, $query);
echo "2;OK;Transferencia Iniciada";
} else {
$cmd = array();
$cmd[] = Sprintf("%s: %s", "Action", "Setvar");
$cmd[] = Sprintf("%s: %s", "channel", GetChannelAgente());
$cmd[] = Sprintf("%s: %s", "variable", "ESPERA_AGENTE_DESATIVADO");
$cmd[] = Sprintf("%s: %s", "value", "");
SetCmdAmi($cmd);
GetUrl(AST_EXEC_AMI);
$result = GetUrl(AST_TRCONSULTA_TRANSFERE_ABORTA);
if (!$result) {
GeraExcept("2;ERRO;não foi possível abortar Transferência!");
}
echo "2;OK;Transferência interropida";
/*
* Tenta alterar as Informações no agente.
*/
$query = "update pbx_supervisor_agentes set canal_transfer = '' where matricula = '$matricula'";
pg_query($dbcon, $query);
}
} catch (Exception $ex) {
RegistraLogAgente("IniciaTransferenciaConsultaRt", $ex->getMessage(), $ex);
echo $ex->getMessage();
}
}
function FinalizaTransferenciaConsultaRt() {
echo DesligarChamadaRt();
}
function DesligarChamadaRt() {
$dbcon = $GLOBALS['dbcon'];
$msgErro = "";
$result = true;
$inTran = 0;
try {
if (!AgenteON()) {
GeraExcept("ERRO;Agente Desconectado!");
}
$matricula = GetMatricula();
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid, status, tipo_ligacao from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("ERRO;não foi possível consultar Informações da chamada!");
}
$row = @pg_fetch_array($result);
/*
* Obtem informacoes sobre a chamada.
*/
if ($row["canal"]) {
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
}
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
/*
* Verifica se a uma transferencia em curso, para tormar a ação de desligar a chamada
* ou concluir a transferenica.
*/
$emTransf = !empty($row["canal_transfer"]);
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$status = $row["status"];
if ($emTransf) {
if ($row["tipo_ligacao"] == 'E') {
$cmd = array();
$cmd[] = Sprintf("%s: %s", "Action", "Setvar");
$cmd[] = Sprintf("%s: %s", "channel", $row["canal"]);
$cmd[] = Sprintf("%s: %s", "variable", "MATRICULA");
$cmd[] = Sprintf("%s: %s", "value", "");
SetCmdAmi($cmd);
@GetUrl(AST_EXEC_AMI);
unset($cmd);
// EXECUTA LIMPA MATRICULA
$cmd[] = Sprintf("%s: %s", "Action", "Setvar");
$cmd[] = Sprintf("%s: %s", "channel", $row["canal"]);
$cmd[] = Sprintf("%s: %s", "variable", "MATRICULA-DESTINO");
$cmd[] = Sprintf("%s: %s", "value", "");
SetCmdAmi($cmd);
@GetUrl(AST_EXEC_AMI);
}
$result = GetUrl(AST_DESLIGAR_LIGACAO);
if (!$result) {
GeraExcept("ERRO;não foi possível transferir a chamada! TRANSFERE");
}
/*
* Tenta limpar o canal de transferencia.
*/
$query = "update pbx_supervisor_agentes
set status = 'LIVRE',
protocolo = '',
origem_destino = '',
duracao = now(),
canal = '',
canal_agente = '',
canal_transfer = '',
uniqueid = ''
where matricula = '$matricula'";
pg_query($dbcon, $query);
return "OK;Chamada transferida com sucesso!";
} else {
//if(!isset($_SESSION[AGT_MATRICULA])){ GeraExcept("2;ERRO;Agente Desconectado!"); }
/*
* Atualiza o agente de acordo com o status.
*/
$result = pg_query($dbcon, 'begin');
if (!$result) {
GeraExcept("ERRO;não foi possível iniciar o procedimento para desligar a chamada!");
}
$inTran = 1;
if ($status == 'PAUSA') {
$query = "update pbx_supervisor_agentes
set canal_transfer = '',
origem_destino = '',
uniqueid = '',
tipo_ligacao = '',
status_gravacao = 'F'
where matricula = '$matricula'";
} else {
$query = "update pbx_supervisor_agentes
set canal_transfer = '',
origem_destino = '',
status = 'LIVRE',
protocolo = '',
duracao = now(),
uniqueid = '',
tipo_ligacao = '',
status_gravacao = 'F'
where matricula = '$matricula'";
}
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("ERRO;não foi possível atualizar a supervisão!");
}
/*
* Executa comando no asterisk.
*/
GetUrl(AST_DESLIGAR_LIGACAO);
//$result = GetUrl(AST_DESLIGAR_LIGACAO);
//if(!$result){ GeraExcept("ERRO;não foi possível desligar a chamada na central!"); }
$result = pg_query($dbcon, 'commit');
if (!$result) {
GeraExcept("ERRO;não foi possível finalizar o registro de informações!");
}
return "OK;Chamada encerrada";
}
} catch (Exception $ex) {
RegistraLogAgente("DesligarChamadaRt", $ex->getMessage(), $ex);
if ($inTran) {
pg_query($db, 'rollback');
}
return $ex->getMessage();
}
}
function IniciaPenduloRt() {
$matricula = GetMatricula();
$dbcon = $GLOBALS['dbcon'];
try {
$query = "select canal, ramal, nome, dac, canal_agente, uniqueid, sala_2 from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("2;WNG;não foi possível acessar Informações sobre a chamada!");
}
if (!pg_num_rows($result)) {
GeraExcept("2;WNG;não há nenhuma ligação em curso!");
}
/*
* obtem Informações sobre a chamada.
*/
$row = pg_fetch_array($result);
if ($row["canal"])
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$_SESSION["salaMute"] = $row["sala_2"];
$result = GetUrl(AST_PENDULO_ADD_CANAIS);
if (!$result) {
$GeraExcept("2;ERRO;não foi possível iniciar a consulta!");
}
return "2;OK;Pêndulo iniciado!";
} catch (Exception $ex) {
RegistraLogAgente("IniciaPenduloRt", $ex->getMessage(), $ex);
return $ex->getMessage();
}
}
function GetDisponivelAtendimetno() {
$query = "select disponivel_atendimento from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return -1;
}
$row = pg_fetch_array($result, null, PGSQL_ASSOC);
return StrToIntDef($row["disponivel_atendimento"], 1);
}
function DisponivelAtendimento($useTran = 1) {
$dbcon = $GLOBALS['dbcon'];
$matricula = GetMatricula();
$dac = $_SESSION[SS_DAC_CODIGO];
$inTran = 0;
try {
$query = "select status, disponivel_atendimento from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("ERRO;Erro consultar Informações sobre o agente!");
}
if (!pg_num_rows($result)) {
GeraExcept("ERRO;Informações sobre o agente não estão disponíveis!");
}
/*
* Indica que a opção indisponivel fila não esta marcada.
*/
$row = pg_fetch_array($result, null, PGSQL_ASSOC);
$dispoAtendimento = $row["disponivel_atendimento"];
$status = trim($row["status"]);
/*
* Indica que o agente esta em pausa.
*/
$status = ($status == 'PAUSA');
$msgAgt = '';
if ($dispoAtendimento) {
@GetUrl(AST_ADD_PAUSA);
$newDispo = 0;
} else if (!$dispoAtendimento && !$status) {
@GetUrl(AST_REM_PAUSA);
$newDispo = 1;
} else {
$newDispo = $dispoAtendimento ? 0 : 1;
}
/*
* Variavel de sessao indica o status atual do agente quando a opcao indisponivel fila.
*/
$_SESSION["SS_CK_DISPO"] = $newDispo;
/*
* Registra a entrada e saida da indisponibilidade da fila.
*/
if ($newDispo) {
$query = "update pbx_indisponivel_fila set idf_saida = now() where id_dac = '$dac' and matricula = '$matricula' and idf_saida is null and id_login = (select max(id) from pbx_eventos_agentes where matricula = '$matricula' and login is not null )";
} else {
$query = "insert into pbx_indisponivel_fila(id_dac, matricula, idf_entrada, id_login)values('$dac','$matricula',now(), (select max(id) from pbx_eventos_agentes where matricula = '$matricula' and login is not null ))";
}
/*
* $dspSet true indica que uma transação já foi aberta.
*/
if ($useTran) {
$result = pg_query('begin');
if (!$result) {
GeraExcept("ERRO;não foi possível iniciar o registro de informações!");
}
$inTran = 1;
}
$result = pg_query($query);
if (!$result) {
GeraExcept("ERRO;não foi possível registrar informações sobre a indisponibilidade!");
}
$query = "update pbx_supervisor_agentes set disponivel_atendimento = '$newDispo' where matricula = '$matricula' ";
$result = pg_query($query);
if (!$result) {
GeraExcept("ERRO;não foi possível alterar informações para supervisao!");
}
if ($useTran) {
$result = pg_query('commit');
if (!$result) {
GeraExcept("ERRO;não foi possível finalizar o registro de informações!");
}
}
echo "OK;operação realizada com sucesso!";
} catch (Exception $ex) {
RegistraLogAgente("DisponivelAtendimento", $ex->getMessage(), $ex);
if ($inTran) {
pg_query($db, 'rollback');
}
echo $ex->getMessage();
}
}
function GetMunOrigem(&$dadosMonitor) {
$fone = trim($dadosMonitor["fone"]);
$getUf = $fone && ($fone != '-') && (strlen($fone) >= 10);
if ($getUf) {
$dbcon = $GLOBALS['dbcon'];
$prefixo = substr(substr($fone, -10), 0, 6);
$query = "select a.mun_id, a.uf, a.mun_nome from pbx_municipio_classifica a, pbx_municipio_prefixo b where b.mun_id = a.mun_id and prx_prefixo = '$prefixo'";
$result = pg_query($dbcon, $query);
if ($result && pg_num_rows($result)) {
$dados = pg_fetch_array($result);
$dadosMonitor["uf_origem"] = $dados["uf"];
$dadosMonitor["mun_origem"] = $dados["mun_nome"];
$dadosMonitor["mun_id"] = $dados["mun_id"];
$dadosMonitor["prefixo_fone"] = $prefixo;
} else {
$dadosMonitor["uf_origem"] = '';
$dadosMonitor["mun_origem"] = '';
$dadosMonitor["mun_id"] = '0';
$dadosMonitor["prefixo_fone"] = $prefixo;
}
}
}
function SetaClassificaChamado($db, $st, $setPausa = 0) {
$subQuery = "";
$matricula = GetMatricula();
/*
* Se houver classificacao e for em modo automatico desliga a chamada do audio na classficacao;
*/
$channel = GetCanalAudioClassificacao();
if ($channel && $_SESSION['SSClassificaPendente']) {
list($sckHost, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$socket = ConectaAmi($sckHost, $sckPort, $sckUser, $sckPass);
DesligarAmi($socket, $channel);
$subQuery = ", canal_agente = ''";
$_SESSION['SSClassificaPendente'] = 0;
}
$query = "update pbx_supervisor_agentes
set chamada_classificado = '$st' $subQuery
where matricula = '$matricula'";
$result = pg_query($db, $query);
if ($result && $setPausa) {
if ($_SESSION["SS_CK_DISPO"] && LiberaPausa($db, $matricula)) {
if (GetMotivoPausa() != 'LOGIN') {
@GetUrl(AST_REM_PAUSA);
}
}
return true;
}
return false;
}
function GetChamadaClassificada() {
/*
*
*/
$matricula = GetMatricula();
$query = "select '' from pbx_supervisor_agentes where matricula = '$matricula' and ( (chamada_classificado <> 0) or (coalesce(uniqueid2, '') = '') or (upper(motivo_pausa) in('AUSENTE', 'RECUSADA')))";
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return false;
}
return true;
}
function GetCanalAudioClassificacao() {
$query = sprintf("SELECT canal_agente FROM pbx_supervisor_agentes WHERE matricula = '%s'", GetMatricula());
$result = pg_query($query);
$channel = pg_fetch_assoc($result);
return $channel['canal_agente'];
}
function LiberaPausa($db, $matricula) {
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' and upper(motivo_pausa) = 'ACW'";
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
return !($_SESSION["SSPausaAtomatica"] && $dados[0]);
}
function GetPausaAutomatica($db, $idDac) {
$query = "select count(*) from pbx_pausa_automatica where iddac = '$idDac'";
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
return $dados[0];
}
function VerificaRamalEstatico($db, $num, $dac) {
//$query = "select b.nome from pbx_queues_membros a, pbx_dacs b where a.id_fila = b.id and b.status = 'A' and a.dispositivo like '%$num'";
$query = "select b.nome from pbx_queues_membros a, pbx_dacs b where a.id_fila = b.id and a.id_fila = '{$dac}' and b.status = 'A' and substring(a.dispositivo,position('/' in a.dispositivo)+1) = '{$num}'";
/*
* Retorna falso se não existirem ramais como membro estatico de nenhuma fila.
*/
$result = pg_query($db, $query);
if (!pg_num_rows($result)) {
return false;
}
while ($dados = pg_fetch_array($result)) {
$param .= $param ? ", $dados[0]" : $dados[0];
}
return $param;
}
function SetMsgAgente($msg) {
global $vl_msgAgente;
$vl_msgAgente = $msg;
}
function GetMsgAgente() {
global $vl_msgAgente;
return $vl_msgAgente;
}
function GetTempoAlertClas() {
return (isset($_SESSION['prm_alerta_classificacao']) && $_SESSION['prm_alerta_classificacao']) ? $_SESSION['prm_alerta_classificacao'] : 30;
}
function ValidaProtoParceiro($proto) {
if (!$_SESSION['prm_validacao_protocolo']) {
$_SESSION['prm_validacao_protocolo'] = GetSelectValProto('result');
}
$ret = ___GetValidacaoProtocolo($proto, $_SESSION['prm_validacao_protocolo']);
if ($ret) {
return $ret;
} else {
GeraExcept("ERRO;não foi possível validar o protocolo, verifique o protocolo digitado!");
}
}
function GetStatusChamadaClassificada($dac) {
if (!GetExigeClas()) {
return false;
}
$matricula = GetMatricula();
$query = "SELECT DISTINCT a.uniqueid,a.calldate,a.src,
(CASE WHEN (direcao = 'E')THEN (src)
WHEN (direcao = 'S') THEN (dst) END) as dst,c.matricula,f.data_reg,a.userfield,g.protocolo
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b ON a.uniqueid = b.uid2
INNER JOIN pbx_usuarios c ON c.matricula = SUBSTRING(b.agente,7,4)
INNER JOIN pbx_dacs d ON d.nome = b.fila
INNER JOIN pbx_queues_grupos h ON h.nome = d.nome
LEFT JOIN pbx_classifica_reg f ON f.id_bilhetes = a.uniqueid
LEFT JOIN pbx_protocolo_reg g ON g.uniqueid = a.uniqueid
WHERE c.matricula = '$matricula'
AND d.id = $dac
AND b.evento in('COMPLETAAGENT', 'COMPLETACALLER', 'COMPLETEAGENT', 'COMPLETEAGENTRAMAL', 'COMPLETECALLER','COMPLETECALLERRAMAL')
AND a.lastapp <> 'Transferred Call'
AND calldate = (select max(calldate) from pbx_bilhetes, pbx_eventos_dacs where pbx_eventos_dacs.uid2 = pbx_bilhetes.uniqueid and substring(agente,7,4) = '$matricula')
ORDER BY calldate";
$result = pg_query($query);
if (!pg_num_rows($result)) {
$query = "SELECT DISTINCT a.uniqueid,a.calldate,a.src,
(CASE WHEN (a.tipo_chamada in(21,22,23,24,25))THEN (src) else (dst) END) as dst,c.matricula,f.data_reg,a.userfield,g.protocolo
FROM pbx_bilhetes a
INNER JOIN pbx_eventos_dacs b ON a.uniqueid = b.uid2
INNER JOIN pbx_usuarios c ON c.matricula = SUBSTRING(b.agente,7,4)
INNER JOIN pbx_dacs d ON d.nome = b.fila
INNER JOIN pbx_queues_grupos h ON h.nome = d.nome
LEFT JOIN pbx_classifica_reg f ON f.id_bilhetes = a.uniqueid
LEFT JOIN pbx_protocolo_reg g ON g.uniqueid = a.uniqueid
WHERE c.matricula = '$matricula'
AND d.id = $dac
AND b.evento in('COMPLETAAGENT', 'COMPLETACALLER', 'COMPLETEAGENT', 'COMPLETEAGENTRAMAL', 'COMPLETECALLER','COMPLETECALLERRAMAL')
AND a.lastapp <> 'Transferred Call'
AND calldate = (select max(calldate) from pbx_bilhetes, pbx_eventos_dacs where pbx_eventos_dacs.uid2 = pbx_bilhetes.uniqueid and substring(agente,7,4) = '$matricula')
ORDER BY calldate";
$result = pg_query($query);
if (!pg_num_rows($result)) {
return false;
}
}
$resp = pg_fetch_assoc($result);
if (!$resp['data_reg']) {
$sql = "UPDATE pbx_supervisor_agentes SET origem_destino = '{$resp['dst']}', uniqueid2 = '{$resp['uniqueid']}', protocolo = '{$resp['protocolo']}' ,chamada_classificado = 0 WHERE matricula = '$matricula'";
pg_query($sql);
return $resp['userfield'];
}
return false;
}
function GetAudioClassificacaoRamal($audio) {
global $debugAmi, $dbcon;
$ramal = GetRamalAgenteLogado($dbcon);
$canalMonitorar = ValidaRamalApl($ramal);
$_SESSION['ramalMonitorAudio'] = $ramal;
$_SESSION['canalMonitorAudio'] = $canalMonitorar;
$uid_registro = $audio;
$cmd = array();
$cmd["Action"] = "Originate";
$cmd["Channel"] = GetRamalMonitorar($canalMonitorar);
$cmd["Context"] = 'audio-escuta-apl';
$cmd["Exten"] = 's';
$cmd["Priority"] = '1';
$cmd["CallerID"] = GetRamalMonitorar($ramal);
$cmd["Variable"] = sprintf("AUDIO=%s,AVISO=OK", $uid_registro);
CommandoAmi($cmd);
}
?>