#!/usr/bin/php -q getMessage(), $ex->getFile(), $ex->getLine(), (isset($log) ? $log : ''), date('Y-m-d H:i:s')); WriteLog($log, $pathLog); } $pid->PidRemove(); function ibRaiseExcept($msg, $dbError = true) { if ($dbError) { $msg .= " DB: " . pg_last_error(); } GeraExcept($msg); } function AtualizaFlagFila($minutes, $status = 'I') { /* * Atualiza flag_fila pendente.Observe que o "status = 'I'" indica * que o registro esta pendende de verificação, a consulta é feita * com base na hora atual menos o tempo em minutos indicado na variavel * $minutes, podemos chamar a funcao mantendo o status 'I' pois a * sincronizacao das tabelas envolvidas é assincrona e pode estar presente * na pbx_bilhetes algum tempo antes de ser inserido na pbx_eventos_dacs * devido que a primeira é gravado pela central enquanto a outra é levantada * do log por um script que roda de 1 em 1 minuto. * */ $sql = sprintf("select id_bilhetes, uniqueid from pbx_bilhetes where calldate < (now() - (interval '%s minutes')) and flag_fila = 'I'", StrToIntDef($minutes)); $result = pg_query($sql); if (!$result) { ibRaiseExcept("Nao possivel selecionar registros com flag_fila pendente!"); } while ($row = pg_fetch_array($result)) { $id = $row['id_bilhetes']; /* * Marca a chamda com entrante na fila, para facilitar a emissao de relatorios e * atualiza o biillsec caso verdadeiro. O campo flag_fila contera 'S' quando identificado * na importa bilhetes ou 'I' caso nao identificado, devido a informacoes entre a dacs e * a bilhetes serem tratadas de forma assincrona outro procedimento fara novamente a * checagem pars os registros onde flag_fila = 'I' atulizando para 'S' se a chamada * pertencer a uma fila ou 'N' caso contrario. */ $conFlag = ChamadaFila($row['uniqueid'], 0); $flagFila = !$conFlag ? "flag_fila = '$status'" : sprintf("flag_fila = 'S', billsec = '%s'", $conFlag); $sql = sprintf("update pbx_bilhetes set %s where id_bilhetes = '%s' ", $flagFila, $id); $resultUpd = pg_query($sql); if (!$resultUpd) { ibRaiseExcept("Nao possivel alterar a identificacao do registro!"); } } } function impGetConnection() { /* * Se precisar de uma conexão diferente da padrão, espcifique sua propria connection string. * $connStr = sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s'", '127.0.0.1', '5432', 'pbx', 'contacte', 'ctepgSQL'); */ $connStr = ''; $connStr = !$connStr ? GetDefStrDb() : $connStr; $conn = pg_connect($connStr); if (!$conn) { GeraExcept("Não foi possível estabelecer uma conexão com o banco de dados!"); } return $conn; } function ImportaAstEventosDacs($dbcon) { global $numDacs; /* * Importa a tabela ast_eventos_dacs. */ $sql = "insert into pbx_eventos_dacs (id,uid1, uid2, fila, agente, evento, param1, param2, param3, param4) select id, uid1, uid2, fila, agente, evento, param1, param2, param3, param4 from ast_eventos_dacs a where not exists(select '' from pbx_eventos_dacs where id = a.id)"; if (!$result = pg_query($dbcon, $sql)) { ibRaiseExcept("Nao possivel importar a tabela ast_eventos_dacs!"); } $numDacs = pg_affected_rows($result); } function ImportaAstBilhetes($dbcon) { global $numBilhetes; $query = "drop table if exists tb_parametros; create temporary table tb_parametros as select (select min(id) mun_padrao from pbx_municipios where to_ascii(nome_localidade) = (select to_ascii(prm_mun_padrao) from pbx_parametros) and uf = (select prm_uf_padrao from pbx_parametros)) as mun_padrao, (select prm_ddd_padrao from pbx_parametros) as prm_ddd_padrao; -- MELHOR DESEMPENHO EM PESQUISA DE MUNICIPIO PARA CELULAR drop table if exists tb_municipios; create temporary table tb_municipios as select min(id) as id, codigo_ddd from pbx_municipios group by codigo_ddd; drop table if exists tb_tipo_ligacao; create temporary table tb_tipo_ligacao as select id_bilhetes, uniqueid, dst, tipo_chamada, flag_fila, case when(ast.prefixo = 0)then 0 else case ast.tipo_chamada when(21)then (select mun_padrao from tb_parametros) when(22)then (select min(id) from pbx_municipios where prefixo = ast.prefixo and ast.sufixo >= faixa_inicial and ast.sufixo <= faixa_final) when(23)then (select mun_padrao from tb_parametros) when(24)then (select min(id) from tb_municipios where codigo_ddd = ast.prefixo) when(31)then (select mun_padrao from tb_parametros) when(32)then (select min(id) from pbx_municipios where prefixo = ast.prefixo and ast.sufixo >= faixa_inicial and ast.sufixo <= faixa_final) when(33)then (select mun_padrao from tb_parametros) when(34)then (select min(id) from tb_municipios where codigo_ddd = ast.prefixo) else 0 end end as id_municipio from ( select *, case prf.tipo_chamada when(21)then strtoint(((select prm_ddd_padrao::text from tb_parametros) || substring(prf.dst,1,4))) when(22)then strtoint(substring(substring(prf.dst,'..........$'), 1,6)) when(23)then (select prm_ddd_padrao from tb_parametros) when(24)then strtoint(substring(substring(prf.dst,'...........$'), 1,2)) when(31)then strtoint(((select prm_ddd_padrao::text from tb_parametros) || substring(prf.dst,1,4))) when(32)then strtoint(substring(substring(prf.dst,'..........$'), 1,6)) when(33)then (select prm_ddd_padrao from tb_parametros) when(34)then strtoint(substring(substring(prf.dst,'...........$'), 1,2)) else 0 end as prefixo, strtoint(substring(prf.dst,'....$')) as sufixo, case when(exists(select '' from ast_eventos_dacs where uid2 = prf.uniqueid))then 'S' else 'N' end as flag_fila from ( select id_bilhetes, direcao, case direcao when('E')then sonumero(src) when('S')then sonumero(dst) else '-' end as dst, uniqueid, case when(direcao = 'I')then 1 else tipoligacao(trim(case when(direcao = 'E')then sonumero(src) else sonumero(dst) end), case when(direcao = 'E')then true else false end) end as tipo_chamada from ast_bilhetes a where not exists(select '' from pbx_bilhetes where id_bilhetes = a.id_bilhetes) ) as prf ) as ast; create index \"tb_tipo_ligacaoIdBilhetes\" on tb_tipo_ligacao(id_bilhetes); insert into pbx_bilhetes( id_bilhetes, calldate, clid, dst, dcontext, channel, dstchannel, lastapp, lastdata, duration, billsec, disposition, tipo_chamada, accountcode, uniqueid, userfield, data_bilhete, id_municipio, ramal_origem, fora_horario, flag_fila, src) select a.id_bilhetes, calldate, clid, a.dst, dcontext, channel, dstchannel, lastapp, lastdata, duration, billsec, disposition, b.tipo_chamada, accountcode, a.uniqueid, userfield, calldate::date, b.id_municipio, ramal_origem, fora_horario, b.flag_fila, CASE WHEN(direcao = 'S')THEN coalesce(ramal_origem, src) ELSE src END AS src from ast_bilhetes a, tb_tipo_ligacao b where b.id_bilhetes = a.id_bilhetes; update ast_bilhetes a set tipo_chamada = b.tipo_chamada, flag_fila = b.flag_fila, id_municipio = b.id_municipio from tb_tipo_ligacao b where b.id_bilhetes = a.id_bilhetes;"; if (!$result = pg_query($dbcon, $query)) { ibRaiseExcept("Nao possivel importar a tabela ast_bilhetes!"); } $numBilhetes = pg_affected_rows($result); } function ImportaAstBilhetesComplemento($dbcon) { /* * INICIO DA IM?ORTACAO DA TABELA "ast_bilhetes_complemento". */ $sql = "select coalesce(max(id),0) from pbx_bilhetes_complemento"; $result = pg_query($dbcon, $sql); if (!$result) { ibRaiseExcept("Nao possivel consultar o id na tabela pbx_eventos_dacs!"); } $row = pg_fetch_row($result); $maxIdComplemento = $row[0]; /* * Importa a tabela ast_bilhetes_complemento. */ $sql = "insert into pbx_bilhetes_complemento (uniqueid2,direcao,id,conta,fone,destino,data_registro,id_usuario,agente,dac) select uniqueid2,direcao,id,conta,fone,destino,data_registro,id_usuario,agente,dac from ast_bilhetes_complemento where id > $maxIdComplemento"; if (!$result = pg_query($dbcon, $sql)) { ibRaiseExcept("Nao possivel importar a tabela ast_bilhetes_complemento!"); } } function CorrigeNumeroDestino($dbcon) { $query = "DROP TABLE IF EXISTS ast_corrige_destino; CREATE TEMPORARY TABLE ast_corrige_destino(uid VARCHAR(32) NOT NULL PRIMARY KEY, dst VARCHAR(80)); INSERT INTO ast_corrige_destino SELECT DISTINCT uniqueid, MIN(destino) FROM ( select a.uniqueid, case when(POSITION('/' IN b.agente) > 0)then SUBSTRING(b.agente, POSITION('/' IN b.agente) + 1) else sonumero(b.agente) end AS destino from ast_bilhetes a, ast_eventos_dacs b where b.uid2 = a.uniqueid AND a.amaflags <> 99 and b.evento in('COMPLETEAGENT','COMPLETECALLER','TRANSFER') AND POSITION('Agent/' IN b.agente) = 0 UNION select a.uniqueid, case when(position( 'Local' in a.dstchannel) > 0)then substring(a.dstchannel,7, position( '@' in a.dstchannel) -7 ) when(position( 'SIP' in a.dstchannel) > 0)then substring(a.dstchannel,5, position( '-' in a.dstchannel) -5 ) else soNumero(a.dstchannel) end as destino from ast_bilhetes a, ast_eventos_dacs b where b.uid2 = a.uniqueid AND a.amaflags <> 99 and b.evento in('COMPLETEAGENT','COMPLETECALLER','TRANSFER') AND POSITION('Agent/' IN b.agente) > 0 ) AS bilhetes_bilhetes GROUP BY uniqueid; UPDATE ast_bilhetes SET dst = ast_corrige_destino.dst, amaflags = 99 FROM ast_corrige_destino WHERE ast_bilhetes.uniqueid = ast_corrige_destino.uid AND coalesce(ast_corrige_destino.dst, '') <> '';"; if (!$result = pg_query($dbcon, $query)) { ibRaiseExcept("Nao possivel importar a tabela ast_bilhetes_complemento!"); } } function AtualizaPreVenda($dbcon) { $pathLog = '/var/log/asterisk/atrualiza_prevenda.log'; /* * Lista os contatos que estao sendo discados na campanha de pre-venda e sincroniza com a * base de clientes */ $sql = "select d.cmp_id, d.list_id, d.cont_id, d.conf_id, a.client_id as cont_identificador,d.conf_id, d.conf_uid, d.conf_status from pbx_cliente a, pbx_campanha_contato_fone d where d.cmp_id = a.cmp_id and d.list_id = a.list_id and d.cont_id = a.cont_id and d.conf_discado = 1 and strtoint(d.conf_status) > 0 and d.conf_protocolo is null"; $result = pg_query($dbcon, $sql); if (!$result) { ibRaiseExcept("Nao possivel consultar contatos discados no pre-venda!"); } WriteLog($sql, $pathLog); while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) { $clientId = $row["cont_identificador"]; $clientStatus = $row["conf_status"]; $clientStatus = $row["conf_status"]; $confId = $row["conf_id"]; $inTran = 0; try { if (!pg_query($dbcon, 'begin')) { ibRaiseExcept("Nao possíveliniciar a transacao para atualizar o registro do contato."); } $inTran++; /* * Atualiza o status dos contatos na tabela pbx_cliente */ $sql = "update pbx_cliente set client_status = '{$clientStatus}' where client_id = '{$clientId}'\n"; if (!pg_query($dbcon, $sql)) { ibRaiseExcept("Nao possível atualizar o registro do contato."); } WriteLog($sql, $pathLog); $sql = "update pbx_campanha_contato_fone set conf_protocolo = '1' where conf_id = '{$confId}'\n"; if (!pg_query($dbcon, $sql)) { ibRaiseExcept("Nao possível atualizar o registro do contato."); } WriteLog($sql, $pathLog); if (!pg_query($dbcon, 'commit')) { ibRaiseExcept("Nao possível finalizar a transacao para atualizar o registro do contato."); } } catch (Exception $ex) { if ($inTran) { @pg_query($dbcon, 'rollback'); } $log = sprintf("Erro:%s File: %s Line: %s \ncmd: %s\n %s\n", $ex->getMessage(), $ex->getFile(), $ex->getLine(), $sql, date('Y-m-d H:i:s')); WriteLog($log, $pathLog); } } } ?>