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.
 
 
 
 
 
 

206 lines
8.3 KiB

#!/usr/bin/php -q
<?php
//error_reporting(E_ERROR);
//ini_set('display_errors', 'Off');
/*
* Descomente a linha abaixo para ativar o log de eventos do php,
* o mesmo sera gravado no arquivo /var/log/asterisk/display_erros.log.
*/
include("util/display_errors.php");
include("util/util.php");
include("funcoes/shared.php");
$pathFile = IBGetPathFile('BILHE2L.TXT');
$pathLog = '/var/log/asterisk/tarifacao.log';
$imp = 0;
$inTran = false;
$linhasDwnld = '';
$linhaUpd = array();
//$connStr = sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s'", '192.168.115.2', '5432', 'pbx', 'contacte', 'ctepgSQL');
$connStr = sprintf("host='%s' port='%s' dbname='%s' user='%s' password='%s'", '127.0.0.1', '5432', 'pbx', 'contacte', 'ctepgSQL');
try {
if (file_exists($pathFile)) {
exit();
}
$dbcon = IBConnect($connStr);
if (!$dbcon) {
GeraExcept('Nao foi posssivel conectar ao banco de dados!');
}
$dddPadrao = GetDddPadrao();
if (!$dddPadrao) {
GeraExcept('Nao foi posssivel recuperar o ddd padrao!');
}
$result = pg_query($dbcon, GetQuery());
if (!$result) {
GeraExcept('Nao foi posssivel consultar a tarifacao!');
}
if (!pg_num_rows($result)) {
GeraExcept('Nao foi foi encontrado registros para exportacao!');
}
/*
* Separa chamadas realizadas das transferencias
*/
while ($row = @pg_fetch_array($result)) {
$linhaUpd[] = sprintf("update pbx_tarif_registra set trr_exporta = 'S' where trr_id = '%s'", $row['trr_id']);
$linhasDwnld .= GetLinhaRelTarifa($row, $transf, 0);
$imp++;
}
$result = pg_query($dbcon, 'begin');
if (!$result) {
GeraExcept('Nao foi posssivel iniciar uma transacao com o banco de dados!');
}
$inTran = true;
foreach ($linhaUpd as $upd) {
$result = pg_query($dbcon, $upd);
if (!$result) {
GeraExcept('Nao foi posssivel atualizar a tarifacao!');
}
}
$result = file_put_contents($pathFile, $linhasDwnld);
if (!$result) {
GeraExcept('Nao foi posssivel gravar o arquivo de tarifacao!');
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
GeraExcept('Nao foi posssivel finalizar uma transacao com o banco de dados!');
}
} catch (Exception $exc) {
if ($inTran) {
@pg_query($dbcon, 'rollback');
}
WriteLog($exc->getMessage(), $pathLog);
unlink($pathFile);
}
function GetQuery($empresa, $depto) {
$sql = " select a.trr_id, a.oper_id_dest, a.oper_numero_dest, a.uniqueid, a.trr_link, a.trr_data, a.trr_origem, a.trr_destino, a.trr_inicio, a.trr_fim, a.trr_duracao, a.trr_preco,
a.trr_vc, a.trr_preco_tipo, a.trr_tipo_opera, a.trr_sentido_chamada, a.trr_tarifa_zero, a.trr_conta_senha, a.trr_conta, a.trr_vc_cad, a.trr_vc_ext,
a.trr_preco_total, substring(b.oper_nome, 1, 30) as oper_nome, substring(d.cc_descricao, 1,30) as cc_descricao, coalesce(e.id, 0) as id_empresa, substring(coalesce(e.nome, 'NI'),1,30) as nome_empresa, coalesce(f.id,0) as id_depto, substring(coalesce(f.nome_depto, 'NI'), 1,30) as nome_depto,
case when(substring(a.trr_destino,1,4) = '0800')then 'Gratuito' else g.ttp_descricao end as ttp_descricao,
(a.trr_duracao / 60)::int as duracao_mininuto, (a.trr_duracao % 60) as duracao_segundo, a.trr_franquia, h.contr_tipo_franquia, a.trr_duracao as duracao,
a.trr_tipo_chamada, a.trr_duracao_transf
from pbx_tarif_registra a
inner join pbx_operadoras b on b.oper_id = a.oper_id_dest
inner join pbx_tarif_contrato h on h.contr_id = a.contr_id
left join pbx_pbx_centro_custo_ramais c on c.ramal = a.trr_origem
left join pbx_centro_custo d on d.cc_id = c.cc_id
left join pbx_empresa e on e.id = d.empresa
left join pbx_departamentos f on f.id = d.departamento
left join pbx_tarifa_tipo_preco g on g.ttp_id = a.trr_vc
where length(trr_destino) >= 8
and a.trr_exporta is null order by a.trr_data, a.trr_inicio";
//if(IsAdmin ())echo $sql;
return $sql;
}
function GetLinhaRelTarifa($row) {
global $dddPadrao;
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$uid = $row["uniqueid"];
$empresa = $row["nome_empresa"]; // $row["id_empresa"] . '-' . $row["nome_empresa"];
$depto = $row["nome_depto"]; //$row["id_depto"] . '-' . $row["nome_depto"];
$oper = $row["oper_nome"]; //$row["oper_id_dest"] . '-' . $row["oper_nome"];
$tipo = $row["ttp_descricao"];
$origem = $row["trr_origem"];
$conta = $row["trr_conta_senha"] ? $row["trr_conta"] : "-";
$dest = $row["trr_destino"];
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$data = IBFmtDataHora($row["trr_inicio"]);
$dataFormatada = ParseDbTimestamp($row["trr_inicio"]);
$duration = (int) $row["trr_duracao"];
$dura = (int) $row["trr_duracao"];
if ($tarifaZero) {
$valor = (0);
} else {
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
}
/* Empresa,Depto,Operadora,Ramal ,Destino,Data,Dura<EFBFBD><EFBFBD>o,Valor
a.trr_id, a.oper_id_dest, a.oper_numero_dest, a.uniqueid, a.trr_link, a.trr_data, a.trr_origem, a.trr_destino, a.trr_inicio, a.trr_fim, a.trr_duracao, a.trr_preco,
a.trr_vc, a.trr_preco_tipo, a.trr_tipo_opera, a.trr_sentido_chamada, a.trr_tarifa_zero, a.trr_conta_senha, a.trr_conta, a.trr_vc_cad, a.trr_vc_ext,
a.trr_preco_total, b.oper_nome, d.cc_descricao, e.id as id_empresa, e.nome as nome_empresa, f.id as id_depto, f.nome_depto
*/
/*
* Formata<EFBFBD><EFBFBD>o do arquivo
- Data/Hora da chamada -> 'dd/mm/aaaa hh:mm:ss' -> '14/11/2017 15:39:05' -> 19;
- Ramal -> '0000000000' -> ' 8823' -> 10;
- Destino da liga<EFBFBD><EFBFBD>o -> '0000000000' -> 'DDPPPPPNNNN' -> 13
- Dura<EFBFBD><EFBFBD>o da chamada -> '0000000000' -> '0000000300' -> 10
- Valor da tarifa<EFBFBD><EFBFBD>o; -> '000000000000' -> '000000003432' -> 12 R$ 34,32
*
*/
$isCelular = array_search(GetTipoChamadaCod($dest, $dddPadrao, 'S'), array(23, 24, 33, 34)) !== false;
$origem = substr(soNumero($origem), 0, 5);
$origem = str_pad($origem, 5, ' ');
$duration = SecondToStrTime($duration);
$dest = ((strlen($dest) == 8) || (strlen($dest) == 9)) ? ($dddPadrao . $dest) : substr(trim($dest), -13);
$localDest = str_pad(($isCelular ? 'Chamada Movel' : IBGetMunicipio(substr($dest, -10))), 32, ' ');
$dest = str_pad($dest, 16, ' ');
$valor = $valor ? FormataValor($valor) : '0';
$valor = str_pad($valor, 12, ' ');
$ni = '0 ';
return sprintf("%s%s%s%s%s%s%s\n", $origem, $data, $duration, $dest, $valor, $ni, $localDest);
}
function IBConnect($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 IBGetPathFile($fileName = 'registro_tarifacao.txt') {
$path = '/hdaux/bilhetagem/';
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
return $path . str_replace('/', '', $fileName);
}
function IBFmtDataHora($dt) {
$dt = trim(substr($dt, 0, 19));
$data = preg_split('/[-" ":\/]/', $dt);
return sprintf("%s/%s/%s%s:%s", $data[2], $data[1], substr($data[0], -2), $data[3], $data[4]);
}
function IBGetMunicipio($numero) {
$prefixo = substr($numero, 0, 6);
$sufixo = substr($numero, 7, 4);
$query = sprintf("select nome_municipio, uf from pbx_municipios where prefixo = '%s' and faixa_inicial <= '%s' and faixa_final >= '%s'", $prefixo, $sufixo, $sufixo);
$result = pg_query($query);
if (!$result || !pg_num_rows($result)) {
return '';
}
$row = pg_fetch_array($result);
return sprintf("%s - %s", RemoveAcentos($row['nome_municipio']), $row['uf']);
}
?>