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çao de clientes qdo verdadeiro classifica -> Lista com classificacoes cadastradas para o dac clasItem -> Listas com itens relacioanados a classificaçao 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"); include("util/funcoesMesa.php"); /* * Define mensagens para o usuário. */ $vl_msgAgente = ''; $wAlineMaster = "center"; $tpLayout = 0; //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", '80%', $sZh, $styleAdd); $sZbtRegStatus = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '16%', $sZh, $styleAdd); $sZbtEncerraLibera = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '30%', $sZh, $styleAdd); $sZbtEncerra = sprintf("width: %s;height: %s;padding:0;margin:0;%s", '30%', $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 = ''; //$dac = IsPostBack() ? (AgenteON() ? $_SESSION[SS_DAC_CODIGO] : $_POST["listaDacs"] ) : ( AgenteON() ? $_SESSION[SS_DAC_CODIGO] : (isset($_GET["dac"]) ? $_GET["dac"] : GetIdDacPadrao($dbcon, $_SESSION["SSidUser"])) ); if (AgenteON()) { $dac = $_SESSION[SS_DAC_CODIGO]; } else if (IsPostBack()) { $dac = $_POST["listaDacs"]; } else if (isset($_GET["dac"])) { $dac = $_GET["dac"]; } else { $dac = GetIdDacPadrao($dbcon, GetIdUser()); $_SESSION[SS_DAC_PADRAO_ID] = $dac; } $ufForm = ""; //IsPostBack() ? $_POST["listaUfs"] : ""; /* * Mostra erros na aplicação */ $displayError = 0; //$heightMasterContent = 265; if (!IsAjax()) { $footerDisplay = 0; $useAguarde = 0; $tplAgente = 'callcenter/agente/agenteMesa.tpl'; $cssBlock = ""; if (IsPostBack()) { $tpAtende = isset($_POST["modoAtendimento"]) ? $_POST["modoAtendimento"] : $_SESSION[SS_MODO_ATENDIMENTO_COD]; if (ConectarDac() && !AgenteON()) { if (!$dac) { SetMsgAgente("Selecione um DAC!"); $jsStartup[] = "alert('Selecione um DAC!')"; } else { ConnectaAgenteRt($dbcon, $dac, $tpAtende); } } else if (DesconectarDac()) { $jaConnectado = strtoupper($_POST["btConDac"]) == 'CONECTAR'; if ($jaConnectado) { $msg = "Este usuário já esta conectado!"; $jsStartup[] = sprintf("alert('%s');", $msg); SetMsgAgente($msg); } else { 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); } } $jsStartup[] = "window.setInterval(\"GetAgenteRt()\", " . GetTempoAgente() . ");"; $jsStartup[] = "window.setInterval(\"SetDataAtual()\", 1000);"; // $jsJQuery[] = "\$(document).bind(\"keydown keypress\", function (event) { if (event.which == 116 || event.which == 8) { return false; }});"; $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());"; $jsJQuery[] = "\$(window).resize( function(){ ResizeAgente(); } ); "; } //$jsJQuery[] = "\$(document).ajaxStart(function(){\$('#loading').show();}).ajaxStop(function(){\$('#loading').hide();});"; if ($clasAtende) { $GLOBALS["jsStartup"][] = $clasAtende; } //$GLOBALS["jsStartup"][] = "\$(window).bind('beforeunload', function() { return SaidaPausaLogoffRt();});"; $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"] = $_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 = 'Pausas'; $dadosMonitorCompl["pausa_detalhes"] = sprintf("%s", 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('sZbtDiscador',$sZbtDiscador); $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('linhasMesa', GetLinhasMesa()); /* $dados = RetornaAbandon($dbcon); $linkAbandonadas = !$dados ? $dados : sprintf("abandonadasRet%s", $dados); $smarty->assign('abandonadasRet',$linkAbandonadas); * */ GetTemplate($smarty, $tplAgente); } else { /* * Chamadas em Ajax para atualizar Interface. */ $acao = $_GET["acao"]; 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 (!GetStatusAgente()) { $dadosMonitor["ramal_monitor"] = GetRamalMonitorar(RAMAL_MONITOR_AGENTE); $dadosMonitor["tempo_logado"] = '00:00:00'; $dadosMonitor["matricula"] = GetMatricula(); $dadosMonitor["abandonadasRet"] = '0'; $dadosMonitor["status_agente"] = "OFF"; $dadosMonitor = array_merge($dadosMonitor, $dadosDiscador); echo FormataDadosRt($dadosMonitor); } else { $oldStatus = $_SESSION[SS_STATUS_AGENTE]; DadosAtualiza($dbcon); $chamadaValida = trim($dadosMonitor["uniqueid2"]); if ($statusServer) $dadosMonitor["tempo_logado"] = sprintf('%s', $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); } $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"]; /* * Controla alerta sonoro para agente quando o chamado não é classificado. */ $exigeClass = $dadosMonitor["chamada_classificado_exige"]; $statusLivre = ($statusAtual == 'LIVRE'); if ($chamadaValida && (GetAlertOcupado() === false) && ($statusAtual == 'OCUPADO')) { SetAlertOcupado(true); SetAlertAgente(false); SetAlertTempo(false); } $naoClass = $dadosMonitor["chamada_classificado"]; if ($chamadaValida && $exigeClass && $statusLivre && !$naoClass && !GetAlertAgente() && GetAlertOcupado()) { SetAlertAgente(true); SetAlertTempo(time()); } $alerta = (GetAlertTempo() !== false) && ((time() - GetAlertTempo())) > GetTempoAlertClas(); if ($chamadaValida && $statusLivre && GetAlertAgente() && !$naoClass && $alerta && GetAlertOcupado()) { 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; } } /* * Ajusta o status dispnivel_atendimento com base na variavel de sessao SS_CK_DISPO, que tem seu valor modificado * na funçao DisponivelAtendimento(). */ if ($_SESSION["SS_CK_DISPO"] && !$dadosMonitor["disponivel_atendimento"]) { $dadosMonitor["disponivel_atendimento"] = 1; } $pref = ''; //GetMunOrigem($dadosMonitor); $statusAgente = trim($_SESSION[SS_STATUS_AGENTE]); $dadosFone = trim($dadosMonitor["fone"]); $txtCliente = trim($_SESSION["txt_cliente"]); $dadosIntegracao = trim($dadosMonitor["cont_identificador"]); //dado alimento pelo agente_fila com orgem na tabela pbx_integracao_reg $param = explode("|", $dadosIntegracao); $dadosCliente = sprintf("%s - %s", $param[3], $param[4]); if (($dadosFone != "") && (($statusAgente === 'OCUPADO') || ($statusAgente === 'CHAMANDO') ) && ($txtCliente == "")) { $cliente = GetClienteClassifica($dbcon, $dadosFone); if (!$cliente) { $cliente = trim($dadosCliente) === '-' ? "" : $dadosCliente; } $dadosMonitor["txt_cliente"] = $cliente; $_SESSION["txt_cliente"] = trim($dadosMonitor["txt_cliente"]); } $dadosMonitor["abandonadasRet"] = RetornaAbandon($dbcon, $dadosMonitor["dac_logado"], GetRamalMonitorar(RAMAL_MONITOR_AGENTE), "", "", $dadosMonitor["abandonadasRet"]); $statusDiscador = $dadosMonitor["status_discador"]; /* * Verifica se existe uma campanha ativa para o dac/agente. */ $dadosDiscador__ = GetDadosDiscador($dac, 0); 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); $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); } } } else { /* * Tratamento de ações invocadas pelo agente. */ ob_clean(); if ($acao == 'classifica') { SetAlertOcupado(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(); } } /* * 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; /* * Pega o canal do agente */ $query = "select canal from pbx_supervisor_agentes where matricula = '$matricula'"; $result = @pg_query($db, $query); if ($result) { $row = @pg_fetch_row($result); } if ($row[0]) { $_SESSION[AGT_CHANNEL_TRANSF] = $row[0]; } if ($result) { $result = GetUrl(AST_TRANSF_PESQUISA); } $query = "update pbx_supervisor_agentes set status = 'LIVRE', protocolo = '', origem_destino = '', duracao = now(), canal = '' where matricula = '$matricula'"; if ($result) { @pg_query($db, $query); } echo $result ? "OK;Transferência realizada com sucesso!" : "ERRO;Não foi possível transferir para pesquisa!"; } 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 = '$liberar' where matricula = '$matricula'"; $result = pg_query($db, $query); if (!$result) { GeraExcept("ERRO;Erro ao liberar o agente!"); }; /* * Marca o telefone com o ultimo staus */ $query = "update pbx_campanha_contato_fone set conf_discado = 1, conf_status = %s, conf_agente_matricula = %s, conf_uid = %s where conf_id = %s"; $query = sprintf($query, 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. */ $query = sprintf("update pbx_campanha_operacao set cmpo_status = 1, cmpo_fim = now() where cont_id = %s and cmpo_status = 0 and matricula = %s", QuotedStr($contId), QuotedStr($matricula)); $result = pg_query($db, $query); if (!$result) { GeraExcept("ERRO;Erro ao alterar o status da operação!"); }; if (!$liberar) { if (GetDispoDiscador()) { DisponivelAtendimento(); SetDispoDiscador(false); } } $result = pg_query($db, 'commit'); if (!$result) { GeraExcept("ERRO;Não foi finalizar a transação!"); } echo "OK;Liberação executada com sucesso!"; } 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!"); } 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' 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("Para o protocolo informe somente números com 12 dígitos!"); } $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 atuzlizaçã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() - $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)) { $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); foreach ($dados as $key => $value) { if (!is_numeric($key)) { $GLOBALS['dadosMonitor'][$key] = $value; } } } } else { SetStatusAgente(); } } function DisablePausa() { return AgenteON() && !AgentePausa() ? "" : 'disabled="disabled"'; } function EntraPausa($db, $codMotivo) { $matricula = GetMatricula(); $dac = $_SESSION[SS_DAC_CODIGO]; $ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE); $motivoPausa = @GetPausaDescricao($db, $codMotivo); $pausa_produtiva_obs = NullDb($_POST['pausa_produtiva_obs']); if (strlen($pausa_produtiva_obs) > 255) { $pausa_produtiva_obs = substr($pausa_produtiva_obs, 0, 255); } $emPausa = GetPausa($db, $matricula, true); $inTran = 0; try { if ($emPausa) { GetExcept("O agente já esta em pausa!"); } /* * Coloca o agente em pausa no asterisk. */ if (!GetUrl(AST_ADD_PAUSA)) { GetExcept("Falha ao colocar o agente em pausa na central!"); } @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) values('$matricula', '$ramal', $dac, $codMotivo, now(), 0, $relEvt, now(), (select produtiva from pbx_motivos_pausas where id = '$codMotivo'), $pausa_produtiva_obs)"; $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çao 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) { $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!"); } /* * Remove da pausa do asterisk somente se a opçao 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', protocolo = '', 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çoes de pausa na supervisao!"); } /* * Registra a pausa no sistema. */ $query = "update pbx_eventos_agentes set saida_pausa = now(), flag = 2 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çoes de pausa no sistema!"); } $result = pg_query($db, "commit"); if (!$result) { GeraExcept("Nao foi concluir a remoçao 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; /* * Se o agente já estiver logado aborta a operação de login */ $ramal = GetRamalMonitorar(RAMAL_MONITOR_AGENTE); $ramalEst = VerificaRamalEstatico($db, $ramal); $dacCheck = ''; $agtCheck = ''; SetStatusAgente(); try { if (!$ramal) { $msg = "Não há ramal configurado!"; GeraExcept($msg); } else if (VerficaAgenteLogado($db)) { $ramalCon = GetRamalAgenteLogado($db); $msg = "Não é possível conectar ao servidor, o Agente já está Conectado no Ramal: $ramalCon!"; GeraExcept($msg); } if (VerificaRamalLogado($db, $dacCheck, $agtCheck)) { $msg = "Não é possível conectar ao servidor, Ramal: \"$ramal\" já 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 = "Esta 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]; $_SESSION[SS_MODO_ATENDIMENTO] = $tpAtend == ATENDIMENTO_MANUAL ? "Manual" : "Automático"; $_SESSION[SS_MODO_ATENDIMENTO_COD] = $tpAtend; $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. */ $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; } 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) values('$matricula', '$ramal',$dac,$idMotivoPausa,now(),0,$relEvt)"; $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($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; 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) { $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!"); } /* * 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 */ @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!"); } 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 = $_SESSION[SS_DAC_CODIGO]; $fila = $_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 ,ORIGINADAS_PA ,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 + TEMPO_ORIGINDADA) / (ATENDIDAS_PA + ORIGINADAS_PA))END) * INTERVAL '1 SECOND' AS TMA FROM ( SELECT fila ,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER', 'TRANSFER') THEN 1 ELSE 0 END) AS ATENDIDAS_PA ,SUM (CASE WHEN EVENTO IN ('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG') 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 WHERE b.evento in ('CONNECT','ABANDON','COMPLETEAGENT','COMPLETECALLER','TRANSFER', 'COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG','ENTERQUEUE') AND a.lastapp <> 'Transferred Call' AND a.data_bilhete = now()::date AND substring(b.agente, 7,4) = '$matricula' AND c.id = $dac ) 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); } 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 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 = split("-", $_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 { /* * O protocolo externo pode passar junto com a classificação. */ if ($proto) { if (!ValidaProtoParceiro($proto)) { GeraExcept("ERRO; Para o protocolo informe somente números com 12 dígitos!"); } 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, contrib_id, id_dac, mun_id) values(%s, %s, %s, %s, %s, %s, %s)"; $query = sprintf($query, QuotedStr($matricula), $clas, $clasItem, QuotedStr($uniqueid), $idContrib, $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 (isset($_GET["numeroDiscar"]) && $acaoDiscar) { if ($discador) { $statusDiscado = GetNumDiscadoStatus($confId); if ($statusDiscado !== false) { GeraExcept(sprintf("9;ERRO;%s;%s!", $statusDiscado['conf_id'], $statusDiscado['conf_fone'])); } } /* * 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); $_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 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); /* * Seta o canal para discagem */ if ($row[0]) { $_SESSION[AGT_CHANNEL_TRANSF] = $row[0]; } /* * 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!"); } $query = "update pbx_supervisor_agentes set status = 'LIVRE', protocolo = '', origem_destino = '', duracao = now(), canal = '' 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"]) $_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"); $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"); $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 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) { $cmd = array(); $cmd[] = Sprintf("%s: %s", "Action", "Setvar"); $cmd[] = Sprintf("%s: %s", "channel", GetChannelAgente()); $cmd[] = Sprintf("%s: %s", "variable", "SAIR"); $cmd[] = Sprintf("%s: %s", "value", "OK"); SetCmdAmi($cmd); @GetUrl(AST_EXEC_AMI); $result = GetUrl(AST_TRCONSULTA_TRANSFERE); 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 canal_transfer = '' 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çoes!"); } 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 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çoes!"); } $inTran = 1; } $result = @pg_query($query); if (!$result) { GeraExcept("ERRO;Não foi possível registrar informaçoes 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 inforaçoes para supervisao!"); } if ($useTran) { $result = @pg_query('commit'); if (!$result) { GeraExcept("ERRO;Não foi possível finalizar o registro de informaçoes!"); } } 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) { $matricula = GetMatricula(); $query = "update pbx_supervisor_agentes set chamada_classificado = '$st' where matricula = '$matricula'"; $result = @pg_query($db, $query); if ($result && $setPausa) { if ($_SESSION["SS_CK_DISPO"] && LiberaPausa($db, $matricula)) { @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, '') = '')"; $result = @pg_query($query); if (!$result || !pg_num_rows($result)) { return false; } return true; } 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) { $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'"; /* * 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) { return strlen(soNumero($proto)) == 12; } ?>