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.
 
 
 
 
 
 

430 lines
19 KiB

#!/usr/bin/php -q
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("util/util.php");
include("funcoes/shared.php");
include("util/Pid.php");
/*
* Realiza a conexao com o banco de dados.
*/
$dbcon = impGetConnection();
/*
* Variavel indica uma transacao em curso.
*/
$inTran = 0;
$numDacs = 0;
$numBilhetes = 0;
$numDuplic = 0;
/*
* Log do sistema
*/
$pathLog = "/var/log/asterisk/importa_bilhetes.log";
/*
* Garante apenas uma instancia do script.
*/
$pid = new Pid();
try {
/*
* verifica se a conexao foi criada com sucesso.
*/
if (pg_connection_status($dbcon) === PGSQL_CONNECTION_BAD) {
ibRaiseExcept("Nao foi possivel conecta com o banco de dados!");
}
//@AtualizaPreVenda($dbcon); //desativado, não estamos usando o sistema.
@ApagaBilheteDuplTransfer($dbcon);
@CorrigeAbandonTransbordo($dbcon);
@CorrigeNumeroDestino($dbcon);
@CorrigeNumeroDestinoImportados($dbcon);
/*
* Inicia uma transacao com o banco de dados
*/
if (!pg_query($dbcon, 'begin')) {
ibRaiseExcept("Nao foi possivel iniciar uma transacao com o banco de dados!");
}
$inTran++;
ImportaAstEventosDacs($dbcon);
ImportaAstBilhetes($dbcon);
ImportaAstBilhetesComplemento($dbcon);
if (!pg_query($dbcon, 'commit')) {
ibRaiseExcept("Nao foi possivel finalizar a transacao com o banco de dados!");
}
$log = sprintf("\nImportados Dacs: %s Bilhetes: %s Excluidos: %s Registros Duplicados %s OK\n", $numDacs, $numBilhetes, $numDuplic, date('Y-m-d H:i:s'));
WriteLog($log, $pathLog);
} 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(), (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')
{
global $dbcon;
/*
* 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($dbcon, $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($dbcon, $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;
$sql = "SELECT org_id FROM pbx_parametros;";
$res = pg_query($dbcon, $sql);
$data = pg_fetch_all($res);
$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 where org_id = %s)
and uf = (select prm_uf_padrao from pbx_parametros where org_id = %s)) as mun_padrao, (select prm_ddd_padrao from pbx_parametros where org_id = %s) 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, %s)
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, org_id)
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, org_id
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;";
foreach ($data as $v) {
$query = sprintf($query, $v['org_id'], $v['org_id'], $v['org_id'], $v['org_id']);
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, corrige_num_destino = 1
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 CorrigeNumeroDestinoImportados($dbcon)
{
// Apagar a tabela temporária
$dropTempTable = "DROP TABLE IF EXISTS temp_table_precisa_corrigir;";
if (!$result = pg_query($dbcon, $dropTempTable)) {
ibRaiseExcept("Não foi possível apagar a tabela temporária precisa_corrigir!");
}
// Criar a tabela temporária precisa_corrigir
$createTempTable = "CREATE TEMP TABLE temp_table_precisa_corrigir AS
WITH importado_sem_corrigir AS (
SELECT uniqueid FROM ast_bilhetes ab
WHERE corrige_num_destino = 0
AND EXISTS (SELECT '' FROM pbx_bilhetes WHERE id_bilhetes = ab.id_bilhetes)
),
precisa_corrigir AS (
SELECT DISTINCT a.uniqueid, a.id_bilhetes, MIN(
CASE
WHEN POSITION('/' IN b.agente) > 0 THEN SUBSTRING(b.agente, POSITION('/' IN b.agente) + 1)
ELSE soNumero(b.agente)
END
) AS dst
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b ON b.uid2 = a.uniqueid
INNER JOIN importado_sem_corrigir c ON c.uniqueid = a.uniqueid
WHERE b.evento IN ('COMPLETEAGENT', 'COMPLETECALLER', 'TRANSFER')
AND POSITION('Agent/' IN b.agente) = 0
AND a.corrige_num_destino = 0
GROUP BY a.id_bilhetes, a.uniqueid
UNION
SELECT DISTINCT a.uniqueid, a.id_bilhetes, MIN(
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 dst
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b ON b.uid2 = a.uniqueid
INNER JOIN importado_sem_corrigir c ON c.uniqueid = a.uniqueid
WHERE b.evento IN ('COMPLETEAGENT', 'COMPLETECALLER', 'TRANSFER')
AND POSITION('Agent/' IN b.agente) > 0
AND a.corrige_num_destino = 0
GROUP BY a.id_bilhetes, a.uniqueid
)SELECT * FROM precisa_corrigir;";
if (!$result = pg_query($dbcon, $createTempTable)) {
ibRaiseExcept("Não foi possível criar a tabela temporária precisa_corrigir!");
}
// Atualizar a tabela pbx_bilhetes usando a tabela temporária
$updatePbxBilhete = "UPDATE pbx_bilhetes
SET dst = pc.dst
FROM temp_table_precisa_corrigir pc
WHERE pbx_bilhetes.uniqueid = pc.uniqueid";
if (!$result = pg_query($dbcon, $updatePbxBilhete)) {
ibRaiseExcept("Não foi possível corrigir os bilhetes na tabela pbx_bilhetes!");
}
// Atualizar a tabela ast_bilhetes usando a tabela temporária
$updateAstBilhete = "UPDATE ast_bilhetes
SET dst = pc.dst, amaflags = 99, corrige_num_destino = 1
FROM temp_table_precisa_corrigir pc
WHERE ast_bilhetes.uniqueid = pc.uniqueid";
if (!$result = pg_query($dbcon, $updateAstBilhete)) {
ibRaiseExcept("Não foi possível corrigir os bilhetes na tabela ast_bilhetes!");
}
}
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);
}
}
}
?>