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.
 
 
 
 
 
 

208 lines
7.5 KiB

#!/usr/bin/php -q
<?php
error_reporting(E_ERROR);
ini_set('display_errors', 0);
include("util/util.php");
include("funcoes/shared.php");
include("util/Pid.php");
/*
* Inicio da busca.
*/
$dataInicio = isset($argv[1]) ? isset($argv[1]) : date("Y-m-d");
/*
* 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_dacs.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 conectar com o banco de dados!");
}
/*
* Importa os registros da tabela ast_eveentos_dacs para a tabela ast_bilhetes.
*/
if (!pg_query($dbcon, ImportaReg($dataInicio))) {
ibRaiseExcept("Nao foi possivel importar os registros para o banco de dados!");
}
$dataLog = date("d-m-Y");
while (true) {
//$query = "select distinct id_bilhetes, calldate, uniqueid, userfield, billsec from pbx_bilhetes a, pbx_eventos_dacs b where b.uid2 = a.uniqueid and trim(coalesce(userfield, '')) = '' and amaflags <> 777999 order by a.calldate limit 100;";
$query = "select distinct id_bilhetes, calldate, uniqueid, userfield, billsec from pbx_bilhetes a where trim(coalesce(userfield, '')) = '' and amaflags <> 777999 and a.calldate::date >= '$dataInicio' order by a.calldate limit 100;";
$result = pg_query($query);
if (!pg_num_rows($result)) {
break;
}
while ($dados = pg_fetch_array($result)) {
$uid = $dados["uniqueid"];
$billsec = $dados["billsec"];
//
// Procura o arquivo.
$infoFile = GetFileAudio($uid);
if (!$infoFile) {
$query = "update pbx_bilhetes set amaflags = 777999 where uniqueid = '{$uid}'";
if (!pg_query($query)) {
WriteLog($log, $query . " $dataLog \n");
}
} else if ($billsec < 3) {
$query = sprintf("update pbx_bilhetes set amaflags = 777999, userfield = '%s', billsec = '%s', duration = '%s' where uniqueid = '%s'", $infoFile[0], $infoFile[1], $infoFile[1], $uid);
if (!pg_query($query)) {
WriteLog($log, $query . " $dataLog \n");
}
} else {
$query = sprintf("update pbx_bilhetes set amaflags = 777999, userfield = '%s' where uniqueid = '%s'", $infoFile[0], $uid);
if (!pg_query($query)) {
WriteLog($log, $query . " $dataLog \n");
}
}
}
}
WriteLog("Registros importados com sucesso.", $pathLog);
} catch (Exception $ex) {
$log = sprintf("Erro: %s Data %s\n", $ex->getMessage(), 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 impGetConnection($connStr = '') {
/*
* Se precisar de uma conex<EFBFBD>o diferente da padr<EFBFBD>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 ? GetDefStrDb() : $connStr;
$conn = pg_connect($connStr);
if (!$conn) {
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel estabelecer uma conex<EFBFBD>o com o banco de dados!");
}
return $conn;
}
function ImportaReg($dataInicio) {
return "
-- Seleciona os registros a serem restaurados.
drop table if exists pbx_eventos_dacs_perdidos;
select * into pbx_eventos_dacs_perdidos from pbx_eventos_dacs a where to_timestamp(uid1::numeric)::date >= '$dataInicio' and not exists(select '' from pbx_bilhetes where uniqueid = a.uid2)
and evento in(
'COMPLETACALLERRAMAL','COMPLETAAGENT','COMPLETACALLER','COMPLETAAGENTRAMAL', 'TRANSFERORIG','COMPLETECALLERRAMAL','COMPLETEAGENT','COMPLETEAGENTRAMAL','COMPLETECALLER', 'TRANSFER', 'ABANDON');
-- select count(*) from pbx_eventos_dacs_perdidos;
-- select * from pbx_eventos_dacs_perdidos;
--Adiciona um campo para indexar os registros.
alter table pbx_eventos_dacs_perdidos add iddpl serial not null;
--Seleciono os registro que irao permanecer para serem restaurados
drop table if exists pbx_eventos_dacs_perdidos_dupl;
select uid2, min(iddpl) as iddpl into pbx_eventos_dacs_perdidos_dupl from pbx_eventos_dacs_perdidos group by uid2 having count(*) > 1;
-- select count(*) from pbx_eventos_dacs_perdidos_dupl;
--Apaga os registros duplicados com base na tabela pbx_eventos_dacs_perdidos_dupl, qualquer registro duplicado que o id nao esteja neta tabela sera apagado.
delete
from pbx_eventos_dacs_perdidos a
using pbx_eventos_dacs_perdidos_dupl b
where a.uid2 = b.uid2
and not exists(select '' from pbx_eventos_dacs_perdidos_dupl where iddpl = a.iddpl);
--select '' from pbx_eventos_dacs_perdidos group by uid2 having count(*) > 1;
--select count(*) from pbx_eventos_dacs_perdidos;
-- IMPORTA CHAMADAS ABANDONADAS -
insert into ast_bilhetes(calldate,clid, src,dst,duration, billsec, disposition, uniqueid, data_bilhete)
select distinct to_timestamp(a.uid2::numeric::bigint), b.param2, b.param2, (select numero from pbx_dacs where nome = a.fila), strtoint(a.param3), strtoint(a.param3),'ANSWERED', a.uid2, to_timestamp(a.uid2::numeric::bigint)::date
from pbx_eventos_dacs_perdidos a, pbx_eventos_dacs b
where b.uid2 = a.uid2
and A.evento = 'ABANDON'
and b.evento = 'ENTERQUEUE'
and coalesce(trim(b.param2), '') <> '';
-- IMPORTA CHAMADAS ATENDIDAS -
insert into ast_bilhetes(calldate,clid, src,dst,duration, billsec, disposition, uniqueid, data_bilhete)
select to_timestamp(a.uid2::numeric::bigint),
b.param2 as clid,
b.param2 as src,
(select numero from pbx_dacs where nome = a.fila) as dst,
strtoint(a.param2) as billsec,
strtoint(a.param2) as duration,
'ANSWERED' as disposition,
a.uid2 as uniqueid,
to_timestamp(a.uid2::numeric::bigint)::date as data_bilhete
from pbx_eventos_dacs_perdidos a, pbx_eventos_dacs b
where b.uid2 = a.uid2
and A.evento in('COMPLETECALLERRAMAL','COMPLETEAGENT','COMPLETEAGENTRAMAL','COMPLETECALLER', 'TRANSFER')
and b.evento = 'ENTERQUEUE'
and coalesce(trim(b.param2), '') <> '';
-- IMPORTA CHAMADAS EFETUADAS NA FILA -
insert into ast_bilhetes(calldate,clid, src,dst,duration, billsec, disposition, uniqueid, data_bilhete)
select to_timestamp(a.uid2::numeric::bigint),
b.agente as clid,
b.agente as src,
b.destino as dst,
strtoint(a.param2) as billsec,
strtoint(a.param2) as duration,
case when(strtoint(a.param2) > 0)then 'ANSWERED' else 'NO ANSWER' end as disposition,
a.uid2 as uniqueid,
to_timestamp(a.uid2::numeric::bigint)::date as data_bilhete
from pbx_eventos_dacs_perdidos a, pbx_bilhetes_complemento b
where b.uniqueid2 = a.uid2
and a.evento in('COMPLETACALLERRAMAL','COMPLETAAGENT','COMPLETACALLER','COMPLETAAGENTRAMAL', 'TRANSFERORIG')
and b.direcao = 'saida-pstn'
and coalesce(trim(b.agente), '') <> '';;
";
}
function GetFileAudio($uid) {
$file = glob("/var/spool/asterisk/monitor/*{$uid}.WAV");
if (!$file) {
return false;
}
$fileName = basename($file[0]);
$size = filesize($fileName) / 1024;
$billsec = $size * 0.6276;
return array($fileName, (int) $billsec);
}