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.
 
 
 
 
 
 

1033 lines
40 KiB

<?php
include_once 'util/relatoriosBase.php';
class RelTarifaFatura extends Relatorios
{
private $___contrato;
private $___empresa = 0;
private $___departamento;
private $___ramal;
private $___ano;
private $___mes;
private $___tipoRelatorio;
public function __construct($idProg, $dbcon, $incDac)
{
parent::__construct($idProg, $dbcon, $incDac);
$this->___contrato = isset($_POST["contr_id"]) ? $_POST["contr_id"] : 0;
$this->___empresa = isset($_POST["listaEmpresas"]) ? $_POST["listaEmpresas"] : 0;
$this->___departamento = isset($_POST["listaDeptos"]) ? $_POST["listaDeptos"] : 0;
$this->___ramal = isset($_POST['ramal']) ? $_POST['ramal'] : '';
$this->___mes = isset($_POST['mes']) ? $_POST['mes'] : date('m');
$this->___ano = isset($_POST['ano']) ? $_POST['ano'] : date('Y');
}
function ___ValidaForm()
{
if (!IsPostBack()) {
return;
}
if (!$this->___contrato) {
GeraExcept('Informe o contrato!');
}
if (!$this->___ano) {
GeraExcept('Informe o ano!');
}
if (!$this->___mes) {
GeraExcept('Informe o mês!');
}
}
function ___FiltrosRelatorio()
{
global $dbcon;
$anos = $this->___GetAnosFatura($dbcon, $this->___ano, $this->___contrato);
$meses = $this->___GetMesesFatura($this->___mes);
$contratos = PbxContratos($this->___contrato);
$empresas = GetEmpresas($dbcon, $this->___empresa, '', 1, 0, 'Todos');
$departamentos = GetDeptos($dbcon, $this->___empresa, $this->___departamento, "", 1, 1, 'Todos');
if ($this->___media != MEDIA_PRINT_GRID) {
/*
* Recupera os filtros da sessao do usuario.
*/
list($this->___ano, $this->___mes) = $_SESSION["SSstorageFiltros"];
if ($this->___media == MEDIA_PRINT_HTML) {
$fila = $this->GetIncDac() ? 'Fila: ' . GetDacDesc($this->GetDbCon(), $this->GetIdProg() . ' ') : '';
return sprintf("%sData Inicial: %s Data Final: %s Tipo: %s", $fila, $this->___dataIni, $this->___dataFim, ($this->___tipoRelatorio ? 'Analítico' : 'Sintético'));
}
$fltCsv = array();
if ($this->GetIncDac()) {
$fltCsv[] = 'Fila:' . GetDacDesc($this->GetDbCon(), $this->___dac);
}
$fltCsv[] = "Ano:" . $this->___ano;
$fltCsv[] = "Mes:" . $this->___mes;
$fltCsv[] = "Data Emissao:" . date('d/m/Y H:i:s');
$fltCsv[] = "Emitido Por:" . GetLogin();
return $fltCsv;
}
if ($this->GetIncDac()) {
$dacs = GetDac($this->GetDbCon(), $this->___dac, "", 0, 1, 0, 0, 1);
}
$lkPrint = "";
if ($this->___dataCount) {
$prt = '<a href="index.php?idProg=%s&media=%s&tipoRelatorio=%s"><img src="imgSite/%s" alt="Clique aqui para imprimir!" width="24" height="24" border="0"></a>';
$prtHtml = "<a href=\"javaScript:NovaJanela('index.php?idProg=%s&media=%s&tipoRelatorio=%s', '%s', '720', '700', 'scrollbars=YES');\"><img src=\"imgSite/%s\" alt=\"Clique aqui para imprimir!\" width=\"24\" height=\"24\" border=\"0\"></a>";
$lkPrint .= sprintf($prtHtml, $this->GetidProg(), MEDIA_PRINT_HTML, $this->___tipoRelatorio, substr(LimpaString(GetDispProgSel($this->GetIdProg())), 0, 20), 'print.gif');
$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_EXCEL, $this->___tipoRelatorio, 'prt-xls.png');
$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_PDF, $this->___tipoRelatorio, 'prt-pdf.png');
$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_CSV, $this->___tipoRelatorio, 'prt-csv.png');
}
//$tipoRel = !$this->___tipoRelatorio ? '' : 'checked="checked"';
/*
* Personalise esta funcao se necessitar de outras opnioes de filtro.
*/
$filtro = '<table border="0" cellspacing="1" cellpadding="1">';
/*
* Rotulos.
*/
$filtro .= '<tr>';
$filtro .= '<td>Contrato </td>';
$filtro .= '<td>Empresa </td>';
$filtro .= '<td>Departamento </td>';
$filtro .= '<td>Ano </td>';
$filtro .= '<td>Mês </td>';
$filtro .= '<td align="center" valign="middle">&nbsp;</td>';
$filtro .= '</tr>';
/*
* Valores.
*/
$filtro .= '<tr>';
$filtro .= "<td><select name=\"contr_id\">$contratos</select></td>";
$filtro .= "<td><select name='listaEmpresas'>$empresas</select></td>";
$filtro .= "<td>$departamentos</td>";
$filtro .= "<td><select name='ano'>$anos</select></td>";
$filtro .= "<td><select name='mes'>$meses</select></td>";
$filtro .= '<td><input type="submit" name="btConsulta" id="btConsulta" value="Consultar"></td>';
$filtro .= '<td>%s</td>';
$filtro .= '</tr>';
$filtro .= '</table>';
/*
* Guarda os filtros passados para recuperar na emissao dos relatoios para impressao.
*/
$_SESSION["SSstorageFiltros"] = array($this->___ano, $this->___mes);
return sprintf($filtro, $lkPrint, $this->___ano, $this->___mes);
}
protected function ___GetDadosDb()
{
global $dbcon;
$infoFatura = $this->___GetInfoFatura($dbcon, $this->___contrato, $this->___ano, $this->___mes);
$diaFecha = $infoFatura["contr_dia_fechamento"];
$dataIni = GetDataIniFatura($this->___ano, $this->___mes, $diaFecha); // $ano . "-" . ($mes - 1) . "-" . ($diaFecha + 1);
$dataFim = GetDataFimFatura($this->___ano, $this->___mes, $diaFecha); //$ano . "-" . ($mes) . "-" . ($diaFecha);
$ramal = $this->___ramal;
$empresa = $this->___empresa;
$depto = $this->___departamento;
$contr_id = $this->___contrato;
$query = "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, b.oper_nome, d.cc_descricao, coalesce(e.id, 0) as id_empresa,
coalesce(e.nome, 'NI') as nome_empresa, coalesce(f.id,0) as id_depto, coalesce(f.nome_depto, 'NI') 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, pcu.apelido, pm.nome_municipio, pm.uf
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
LEFT JOIN pbx_cs_usuarios pcu on pcu.matricula::text = a.trr_conta
LEFT JOIN pbx_bilhetes pb on a.uniqueid = pb.uniqueid
LEFT JOIN pbx_municipios pm on pb.id_municipio = pm.id
WHERE a.contr_id = '$contr_id'
AND a.trr_data >= '$dataIni'
AND a.trr_data <= '$dataFim' ";
if ($ramal) {
$query .= " AND a.trr_origem = '$ramal' ";
}
if ($empresa) {
$query .= " AND d.empresa = '$empresa' ";
}
if ($depto) {
$query .= " AND d.departamento = '$depto' ";
}
$query .= " ORDER BY a.trr_data, a.trr_inicio ";
$result = $this->___GetQuery($query);
$row = pg_fetch_all($result);
$this->SetData($row ? $row : array());
$queryFranq = "SELECT DISTINCT a.contr_dia_fechamento, b.prc_tipo, b.prc_franquia,
b.prc_franquia_movel, a.contr_tipo_franquia,
c.tfq_descricao, CASE WHEN(b.prc_tipo::INT = 1)THEN 'Minuto' ELSE 'Chamada' END AS prc_tipo_descricao
FROM pbx_tarif_contrato a, pbx_tarif_contrato_preco b, pbx_tarif_tipo_franquia c
WHERE b.contr_id = a.contr_id
AND c.tfq_id = a.contr_tipo_franquia
AND a.contr_id = '$contr_id' ";
$result1 = $this->___GetQuery($queryFranq);
$dados = pg_fetch_array($result1);
$fecha = GetFechamentoContrato($this->___ano, $this->___mes, $dados['contr_dia_fechamento']);
$dados['contr_dia_fechamento'] = $fecha ? $fecha : date('d');
$this->SetData($dados ? $dados : array());
$subQuery = sprintf("SELECT tff_saldo, tff_saldo_movel FROM pbx_tarif_franquia WHERE tff_mes = %s AND contr_id = %s", $this->___mes, $this->___contrato);
$result2 = $this->___GetQuery($subQuery);
$row2 = pg_fetch_array($result2);
$this->SetData($row2 ? $row2 : array());
}
protected function ___PreparaCsv()
{
$dataRel = array();
$filtro = $this->___FiltrosRelatorio();
$dataRel[] = GenerateCsvFromArray($filtro);
/*
* Inicia o relatório.
*/
/**
* TABELA DE FRANQUIA
*/
$franqCabecalio = array(
'Tipo', 'Fixo', 'Saldo', 'Movel', 'Saldo Movel'
);
$dataRel[] = GenerateCsvFromArray($franqCabecalio);
/**
* DADOS RETORNADOS DA FRANQUIA MENSAL
*/
$saldo = $this->GetData()[2];
/**
* SALDO DA FRANQUIA DE ACORDO COM O CONTRATO
*/
$franquia = $this->GetData()[1];
$franquiaSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo'] / 60 : $saldo['tff_saldo'];
$franquiaMovelSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo_movel'] / 60 : $saldo['tff_saldo_movel'];
$descricao = RemoveAcentos($franquia['tfq_descricao']);
$descricaoTipo = RemoveAcentos($franquia['prc_tipo_descricao']);
$dataRel[] = GenerateCsvFromArray(array("[ {$descricao} ]" . " [{$descricaoTipo} ]", $franquia['prc_franquia'], $franquiaSaldo, $franquia['prc_franquia_movel'], $franquiaMovelSaldo));
/**
* TABELA PRINCIPAL
*/
$dadosCabecalio = array(
'Data',
'Empresa',
'Departamento',
'Operadora',
'Tipo',
'Localidade',
'UF',
'Ramal',
'Conta',
'Usuario',
'Destino',
'Duracao',
'Valor'
);
$dadosField = array(
'trr_inicio',
'nome_empresa',
'cc_descricao',
'oper_nome',
'ttp_descricao',
'nome_municipio',
'uf',
'trr_origem',
'trr_conta',
'apelido',
'trr_destino',
'trr_duracao',
'trr_preco_total'
);
/*
* Monta a linha de cabecalio.
*/
$dataRel[] = GenerateCsvFromArray($dadosCabecalio);
$somaDuracao = 0;
$somaReg = 0;
$somaValor = 0;
$agrupado = array();
/*
* Linhas de dados.
*/
foreach ($this->GetData()[0] as $row) {
/**
* ARMAZENA OS VALORES PARA APRESENTAR NO AGRUPADO
*/
$somaReg++;
$somaDuracao += $row['trr_duracao'];
$somaValor += $row['trr_preco_total'];
/**
* ARMAZENA DADOS DO BANCO NAS VARIAVEIS
*/
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['duracao'] += (int) $row["trr_duracao"];
/**
* VERIFICA O TIPO DE TARIFA
*/
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = 0;
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor(0);
} else {
/*
* [ TARIFA CHAMADA ] FUNÇÃO PARA CALCULAR O VALOR DA TARIFAÇÃO
*/
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor($valor);
}
/*
* FORMATA OS DADOS PARA SER APRESENTADOS
*/
$row['trr_inicio'] = date('d/m/Y H:i:s', strtotime($row['trr_inicio']));
$row['trr_destino'] = ocultarTelefone($row['trr_destino']);
$row['apelido'] = $row['apelido'] ? $row['apelido'] : ' - ';
$row['trr_conta'] = $row['trr_conta'] ? $row['trr_conta'] : ' - ';
$row['nome_municipio'] = $row['nome_municipio'] ? $row['nome_municipio'] : ' - ';
$row['uf'] = $row['uf'] ? $row['uf'] : ' - ';
$row['trr_duracao'] = $row['trr_duracao'] ? SecondToStrTime($row['trr_duracao']) : '00:00:00';
$row['ttp_descricao'] = RemoveAcentos($row['ttp_descricao']);
// Formata linha de dados.
$linha = array();
foreach ($dadosField as $key) {
$linha[] = $row["$key"];
}
$dataRel[] = GenerateCsvFromArray($linha);
}
$dataRel[] = GenerateCsvFromArray(array('Chamadas ', $somaReg, '', '', 'Totalizador', '', '', '', SecondToStrTime($somaDuracao), FormataValor($somaValor)));
$dataRel[] = GenerateCsvFromArray(array());
/**
* TABELA DE FRANQUIA
*/
$dataRel[] = GenerateCsvFromArray(array('Empresa', 'Departamento', 'Duracao', 'Valor'));
foreach ($agrupado as $key => $valor) {
foreach ($valor as $k => $chave) {
$dataRel[] = GenerateCsvFromArray(array($key, $k ? $k : ' --- ', SecondToStrTime($chave['duracao']), FormataValor($chave['valor'])));
}
}
$this->___dataRel[] = $dataRel;
}
protected function ___PreparaExcel()
{
$dataRel = array();
$filtro = $this->___FiltrosRelatorio();
/*
* Inicia o relatório.
*/
/*
* Cria os filtros
*/
$linha = array('LABEL');
foreach ($filtro as $values) {
list($label, $value) = explode(":", $values);
$linha[] = $label;
}
$dataRel[] = $linha;
$linha = array('DADOS');
foreach ($filtro as $values) {
list($label, $value) = explode(":", $values);
$linha[] = $value;
}
$linha[] = array('DADOS', '');
$dataRel[] = $linha;
/**
* TABELA DE FRANQUIA
*/
$franqCabecalio = array(
'Tipo', 'Fixo', 'Saldo', 'Movel', 'Saldo Movel'
);
/**
* DADOS RETORNADOS DA FRANQUIA MENSAL
*/
$saldo = $this->GetData()[2];
/**
* SALDO DA FRANQUIA DE ACORDO COM O CONTRATO
*/
$franquia = $this->GetData()[1];
$franquiaSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo'] / 60 : $saldo['tff_saldo'];
$franquiaMovelSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo_movel'] / 60 : $saldo['tff_saldo_movel'];
$linha = array('LABEL');
foreach ($franqCabecalio as $values) {
list($label, $value) = explode(":", $values);
$linha[] = $label;
}
$dataRel[] = $linha;
$descricao = RemoveAcentos($franquia['tfq_descricao']);
$descricaoTipo = RemoveAcentos($franquia['prc_tipo_descricao']);
$dataRel[] = array('DADOS', "[ {$descricao} ]" . " [{$descricaoTipo} ]", $franquia['prc_franquia'], $franquiaSaldo, $franquia['prc_franquia_movel'], $franquiaMovelSaldo);
/**
* TABELA PRINCIPAL
*/
$dadosCabecalio = array(
'Data',
'Empresa',
'Departamento',
'Operadora',
'Tipo',
'Localidade',
'UF',
'Ramal',
'Conta',
'Usuario',
'Destino',
'Duracao',
'Valor'
);
$dadosField = array(
'trr_inicio',
'nome_empresa',
'cc_descricao',
'oper_nome',
'ttp_descricao',
'nome_municipio',
'uf',
'trr_origem',
'trr_conta',
'apelido',
'trr_destino',
'trr_duracao',
'trr_preco_total'
);
/*
* Monta a linha de cabecalio.
*/
$linha = array('LABEL');
foreach ($dadosCabecalio as $values) {
list($label, $value) = explode(":", $values);
$linha[] = $label;
}
$dataRel[] = $linha;
$somaDuracao = 0;
$somaReg = 0;
$somaValor = 0;
$agrupado = array();
/*
* Linhas de dados.
*/
foreach ($this->GetData()[0] as $row) {
/**
* ARMAZENA OS VALORES PARA APRESENTAR NO AGRUPADO
*/
$somaReg++;
$somaDuracao += $row['trr_duracao'];
$somaValor += $row['trr_preco_total'];
/**
* ARMAZENA DADOS DO BANCO NAS VARIAVEIS
*/
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['duracao'] += (int) $row["trr_duracao"];
/**
* VERIFICA O TIPO DE TARIFA
*/
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = 0;
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor(0);
} else {
/*
* [ TARIFA CHAMADA ] FUNÇÃO PARA CALCULAR O VALOR DA TARIFAÇÃO
*/
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor($valor);
}
/*
* FORMATA OS DADOS PARA SER APRESENTADOS
*/
$row['trr_destino'] = ocultarTelefone($row['trr_destino']);
$row['trr_inicio'] = date('d/m/Y H:i:s', strtotime($row['trr_inicio']));
$row['apelido'] = $row['apelido'] ? $row['apelido'] : ' - ';
$row['trr_conta'] = $row['trr_conta'] ? $row['trr_conta'] : ' - ';
$row['nome_municipio'] = $row['nome_municipio'] ? $row['nome_municipio'] : ' - ';
$row['uf'] = $row['uf'] ? $row['uf'] : ' - ';
$row['trr_duracao'] = $row['trr_duracao'] ? SecondToStrTime($row['trr_duracao']) : '00:00:00';
$row['nome_municipio'] = RemoveAcentos($row['nome_municipio']);
$row['ttp_descricao'] = RemoveAcentos($row['ttp_descricao']);
// Formata linha de dados.
$linha = array('DADOS');
foreach ($dadosField as $key) {
$linha[] = $row["$key"];
}
$dataRel[] = $linha;
}
$dataRel[] = array('LABEL', 'Chamadas ', $somaReg, '', '', 'Totalizador', '', '', '', SecondToStrTime($somaDuracao), FormataValor($somaValor));
$dataRel[] = array('DADOS', '');
/**
* TABELA DE FRANQUIA
*/
$dataRel[] = array('LABEL', 'Empresa', 'Departamento', 'Duracao', 'Valor');
foreach ($agrupado as $key => $valor) {
foreach ($valor as $k => $chave) {
$dataRel[] = array('DADOS', $key, $k ? $k : ' --- ', SecondToStrTime($chave['duracao']), FormataValor($chave['valor']));
}
}
$this->___dataRel[] = $dataRel;
}
protected function ___PreparaGrid()
{
$dataRel = array();
$dadosCabecalio = array(
'Data' => 'align="center"',
'Empresa' => 'align="left"',
'Departamento' => 'align="left"',
'Operadora' => 'align="left"',
'Tipo' => 'align="left"',
'Localidade' => 'align="left"',
'UF' => 'align="left"',
'Ramal' => 'align="left"',
'Conta' => 'align="left"',
'Usuário' => 'align="left"',
'Destino' => 'align="left"',
'Duração' => 'align="right"',
'Valor' => 'align="right"'
);
$dadosField = array(
'trr_inicio' => 'align="center"',
'nome_empresa' => 'align="left"',
'cc_descricao' => 'align="left"',
'oper_nome' => 'align="left"',
'ttp_descricao' => 'align="left"',
'nome_municipio' => 'align="left"',
'uf' => 'align="left"',
'trr_origem' => 'align="left"',
'trr_conta' => 'align="left"',
'apelido' => 'align="left"',
'trr_destino' => 'align="left"',
'trr_duracao' => 'align="right"',
'trr_preco_total' => 'align="right"'
);
/**
* DADOS RETORNADOS DA FRANQUIA MENSAL
*/
$saldo = $this->GetData()[2];
/**
* SALDO DA FRANQUIA DE ACORDO COM O CONTRATO
*/
$franquia = $this->GetData()[1];
$franquiaSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo'] / 60 : $saldo['tff_saldo'];
$franquiaMovelSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo_movel'] / 60 : $saldo['tff_saldo_movel'];
/**
* TABELA DE FRANQUIA
*/
$dataRel[] = '<table width="55%" cellpadding="2" class="grid">';
$dataRel[] = '<tr><th colspan="4">Franquia</th></tr>';
$dataRel[] = sprintf('<tr><th>Tipo</th><td colspan="3">[ %s ] [ %s ]</td></tr>', $franquia['tfq_descricao'], $franquia['prc_tipo_descricao']);
$dataRel[] = sprintf('<tr><th>Fixo</th><td>%s</td><th>Saldo</th><td>%s</td></tr>', $franquia['prc_franquia'], $franquiaSaldo);
$dataRel[] = sprintf('<tr><th>Móvel</th><td>%s</td><th>Saldo Móvel</th><td>%s</td></tr>', $franquia['prc_franquia_movel'], $franquiaMovelSaldo);
$dataRel[] = '</table><br>';
/*
* Inicia o relatório.
*/
$dataRel[] = '<table width="70%" cellpadding="2" class="grid">';
/*
* Monta a linha de cabecalio.
*/
$dataRel[] = "<tr><th colspan='13'>Relatório Tarifação por Fatura</th></tr>";
$linhas = "<tr>";
foreach ($dadosCabecalio as $key => $value) {
$linhas .= sprintf("<th %s>%s</th>", $value, $key);
}
$linhas .= "</tr>";
$dataRel[] = $linhas;
/*
* Verifica se retornou dados
*/
if (!IsPostBack() || !count($this->GetData()[0])) {
$dataRel[] = sprintf("<tr><td align=\"center\" colspan=\"%s\">%s</td></tr></table>", count($dadosCabecalio), (!IsPostBack() ? 'Informe os parametros e clique em consultar!' : 'Nenhum registro encontado!'));
$this->___dataRel[] = $dataRel;
return;
}
$somaReg = 0;
$somaValor = 0;
$somaDuracao = 0;
$agrupado = array();
/*
* Linhas de dados.
*/
foreach ($this->GetData()[0] as $row) {
/**
* ARMAZENA OS VALORES PARA APRESENTAR NO AGRUPADO
*/
$somaReg++;
$somaDuracao += $row['trr_duracao'];
$somaValor += $row['trr_preco_total'];
/**
* ARMAZENA DADOS DO BANCO NAS VARIAVEIS
*/
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['duracao'] += (int) $row["trr_duracao"];
/**
* VERIFICA O TIPO DE TARIFA
*/
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = 0;
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor(0);
} else {
/*
* [ TARIFA CHAMADA ] FUNÇÃO PARA CALCULAR O VALOR DA TARIFAÇÃO
*/
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$row['trr_preco_total'] = FormataValor($valor);
}
/*
* FORMATA OS DADOS PARA SER APRESENTADOS
*/
$row['trr_inicio'] = date('d/m/Y H:i:s', strtotime($row['trr_inicio']));
$row['apelido'] = $row['apelido'] ? $row['apelido'] : ' - ';
$row['trr_conta'] = $row['trr_conta'] ? $row['trr_conta'] : ' - ';
$row['nome_municipio'] = $row['nome_municipio'] ? $row['nome_municipio'] : ' - ';
$row['uf'] = $row['uf'] ? $row['uf'] : ' - ';
$row['trr_duracao'] = $row['trr_duracao'] ? SecondToStrTime($row['trr_duracao']) : '00:00:00';
$row['trr_destino'] = ocultarTelefone($row['trr_destino']);
/**
* MONTA A TABELA DO RELATORIO
*/
$linha = "<tr>";
foreach ($dadosField as $key => $value) {
$linha .= sprintf("<td %s>%s</td>", $value, $row["$key"]);
}
$linha .= "</tr>";
$dataRel[] = $linha;
}
/*
* MONTA A TABELA DE AGRUPAMENTO DE ACORDO COM OS DADOS GUARDADOS
*/
$dataRel[] = sprintf("<tr><th align='left' colspan='2'>Chamadas: $somaReg</th><th colspan='9'>Totalizador</th><th align='right'>%s</th><th align='right'>%s</th></tr>", SecondToStrTime($somaDuracao), FormataValor($somaValor));
$dataRel[] = '</table>';
$dataRel[] = '<br>';
$dataRel[] = '<table width="70%" cellpadding="2" class="grid">';
$dataRel[] = '<tr><th colspan=\'4\'>Agrupado Departamento</th></tr>';
$dataRel[] = '<tr><th align=\'left\'>Empresa</th><th align=\'left\'>Departamento</th><th>Duração</th><th align=\'right\'>Valor</th></tr>';
foreach ($agrupado as $key => $valor) {
foreach ($valor as $k => $chave) {
$dataRel[] = sprintf('<tr><td align=\'left\'>%s</td><td align=\'left\'>%s</td><td align=\'center\'>%s</td><td align=\'right\'>%s</td></tr>', $key, $k ? $k : ' --- ', SecondToStrTime($chave['duracao']), FormataValor($chave['valor']));
}
}
$dataRel[] = '</table>';
/*
* FECHA O RELATORIO
*/
$this->___dataRel[] = $dataRel;
}
protected function ___PreparaHtml()
{
}
protected function ___PreparaPdf()
{
list($this->___ano, $this->___mes) = $_SESSION["SSstorageFiltros"];
$this->___dataIni = $this->___mes;
$this->___dataFim = $this->___ano;
$this->settype("L");
/**
* TABELA DADOS PRINCIPAIS
*/
$dadosCabecalio = array(
'Data' => 'C',
'Empresa' => 'C',
'Departamento' => 'C',
'Operadora' => 'C',
'Tipo' => 'C',
'Localidade' => 'C',
'UF' => 'C',
'Ramal' => 'C',
'Conta' => 'C',
'Usuário' => 'C',
'Destino' => 'C',
'Duração' => 'C',
'Valor' => 'C'
);
$dadosField = array(
'trr_inicio' => 'C',
'nome_empresa' => 'C',
'cc_descricao' => 'C',
'oper_nome' => 'C',
'ttp_descricao' => 'C',
'nome_municipio' => 'C',
'uf' => 'C',
'trr_origem' => 'C',
'trr_conta' => 'C',
'apelido' => 'C',
'trr_destino' => 'C',
'trr_duracao' => 'C',
'trr_preco_total' => 'C'
);
/**
* TABELA DE FRANQUIA
*/
$franqCabecalio = array(
'Tipo' => 'C',
'Fixo' => 'C',
'Saldo' => 'C',
'Móvel' => 'C',
'Saldo Móvel' => 'C'
);
$franqField = array(
'tipo' => 'C',
'fixo' => 'C',
'saldo' => 'C',
'movel' => 'C',
'saldo_movel' => 'C'
);
$franqHeader = array(40, 40, 40, 40, 35);
/**
* DADOS RETORNADOS DA FRANQUIA MENSAL
*/
$saldo = $this->GetData()[2];
/**
* SALDO DA FRANQUIA DE ACORDO COM O CONTRATO
*/
$franquia = $this->GetData()[1];
$franquiaSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo'] / 60 : $saldo['tff_saldo'];
$franquiaMovelSaldo = $franquia['prc_tipo'] == 1 ? $saldo['tff_saldo_movel'] / 60 : $saldo['tff_saldo_movel'];
/**
* MONTA ARRAY PARA O RELATORIO
*/
$dataFranq = array(array(
'tipo' => "[ {$franquia['tfq_descricao']} ]" . "[ {$franquia['prc_tipo_descricao']} ]",
'fixo' => $franquia['prc_franquia'],
'saldo' => $franquiaSaldo,
'movel' => $franquia['prc_franquia_movel'],
'saldo_movel' => $franquiaMovelSaldo
));
$tables[] = array($franqCabecalio, $franqField, $dataFranq, $franqHeader, 0, 0);
$somaReg = 0;
$somaValor = 0;
$somaDuracao = 0;
$agrupado = array();
$widthHeader = array(20, 25, 25, 20, 20, 60, 10, 10, 10, 20, 25, 25);
$dados = $this->GetData()[0];
foreach ($dados as $row) {
/**
* ARMAZENA OS VALORES PARA APRESENTAR NO AGRUPADO
*/
$somaDuracao += $row['trr_duracao'];
$somaValor += $row['trr_preco_total'];
/**
* ARMAZENA DADOS DO BANCO NAS VARIAVEIS
*/
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['duracao'] += (int) $row["trr_duracao"];
/**
* VERIFICA O TIPO DE TARIFA
*/
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = 0;
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$dados[$somaReg]['trr_preco_total'] = FormataValor(0);
} else {
/*
* [ TARIFA CHAMADA ] FUNÇÃO PARA CALCULAR O VALOR DA TARIFAÇÃO
*/
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
$agrupado[$row['nome_empresa']][$row['cc_descricao']]['valor'] += $valor;
$somaValor += $valor;
$dados[$somaReg]['trr_preco_total'] = FormataValor($valor);
}
/*
* FORMATA OS DADOS PARA SER APRESENTADOS
*/
$dados[$somaReg]['trr_destino'] = ocultarTelefone($row['trr_destino']);
$dados[$somaReg]['trr_inicio'] = date('d/m/Y H:i:s', strtotime($row['trr_inicio']));
$dados[$somaReg]['apelido'] = $row['apelido'] ? $row['apelido'] : ' - ';
$dados[$somaReg]['trr_conta'] = $row['trr_conta'] ? $row['trr_conta'] : ' - ';
$dados[$somaReg]['nome_municipio'] = $row['nome_municipio'] ? $row['nome_municipio'] : ' - ';
$dados[$somaReg]['uf'] = $row['uf'] ? $row['uf'] : ' - ';
$dados[$somaReg]['trr_duracao'] = $row['trr_duracao'] ? SecondToStrTime($row['trr_duracao']) : '00:00:00';
$somaReg++;
}
$totalizador = array('Chamadas: ', $somaReg, '', '', 'Totalizador', '', '', '', SecondToStrTime($somaDuracao), FormataValor($somaValor));
$tables[] = array($dadosCabecalio, $dadosField, $dados, $widthHeader, $totalizador, 0);
/**
* TABELA DE AGRUPADOS
*/
$agrpCabecalio = array(
'Empresa' => 'C',
'Departamento' => 'C',
'Duração' => 'C',
'Valor' => 'C'
);
$agrpField = array(
'empresa' => 'C',
'departamento' => 'C',
'duracao' => 'C',
'valor' => 'C'
);
$agrpHeader = array(50, 50, 50, 45);
$dataAgp = array();
$z = 0;
foreach ($agrupado as $key => $valor) {
foreach ($valor as $k => $chave) {
$dataAgp[$z]['empresa'] = $key;
$dataAgp[$z]['departamento'] = $k ? $k : ' --- ';
$dataAgp[$z]['duracao'] = SecondToStrTime($chave['duracao']);
$dataAgp[$z]['valor'] = FormataValor($chave['valor']);
$z++;
}
}
$tables[] = array($agrpCabecalio, $agrpField, $dataAgp, $agrpHeader, 0, 0);
$this->___dataRel = $tables;
}
private function ___GetInfoFatura($dbcon, $contr_id, $ano, $mes)
{
$query = "SELECT DISTINCT a.contr_dia_fechamento, b.prc_tipo, b.prc_franquia, b.prc_franquia_movel, a.contr_tipo_franquia,
c.tfq_descricao, CASE WHEN(b.prc_tipo::INT = 1)THEN 'Minuto' ELSE 'Chamada' END AS prc_tipo_descricao
FROM pbx_tarif_contrato a, pbx_tarif_contrato_preco b, pbx_tarif_tipo_franquia c
WHERE b.contr_id = a.contr_id
AND c.tfq_id = a.contr_tipo_franquia
AND a.contr_id = '$contr_id' ";
$result = pg_query($dbcon, $query);
$dados = @pg_fetch_array($result);
$fecha = GetFechamentoContrato($ano, $mes, $dados['contr_dia_fechamento']);
$dados['contr_dia_fechamento'] = $fecha ? $fecha : date('d');
return $dados;
}
private function ___GetAnosFatura($dbcon, $ano, $contrato)
{
$query = "SELECT COALESCE(date_part('year', MIN(trr_data)), date_part('year', NOW())),
COALESCE(date_part('year', NOW()),date_part('year', MAX(trr_data)))
FROM pbx_tarif_registra WHERE 1=1 ";
$query .= $contrato > 0 ? " AND contr_id = $contrato" : '';
$query .= " AND org_id = {$this->GetOrgId()}";
$result = pg_query($dbcon, $query);
if (!pg_num_rows($result)) {
return "<option value=\"0\" selected>----------</option>";
}
$dados = @pg_fetch_row($result);
$min = $dados[0];
$max = $dados[1];
while ($max >= $min) {
$sel = ($dados[0] == $ano) ? "selected" : "";
$ano .= "<option value=\"$max\" $sel>$max</option>";
$max--;
}
return $ano;
}
private function ___GetMesesFatura($mes)
{
$meses = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
$mes = $mes ? $mes : date('m');
$ret = '';
foreach ($meses as $mesA) {
$sel = $mes == $mesA ? 'selected="selected"' : '';
$ret .= "<option value=\"$mesA\" $sel>$mesA</option>\n";
}
return $ret;
}
public function ExecutaRelatorio()
{
global $jsStartup, $jsJQuery, $smarty;
try {
/*
* Use esta função para validar dados do formulário.
*/
$this->___ValidaForm();
/*
* Recupera os dados do banco.
*/
$this->___ConteudoRelatorio();
/*
* Imprime relatório de acordo com a media passada.
*/
$conteudoRelatorio = $this->___ImprimeRelatorio();
} catch (Exception $exc) {
$this->SetMsg($exc->getMessage());
$jsStartup[] = sprintf("alert('%s');", $this->GetMsg());
$this->___GravaLog();
}
/*
* Inclua os scripts necessários aqui.
*/
$jsJQuery[] = "\$('#dataIni').keypress(function(){formataDataHora(this);}) ";
$jsJQuery[] = "\$('#dataFim').keypress(function(){formataDataHora(this);}) ";
$smarty->assign('filtros', $this->___FiltrosRelatorio());
$smarty->assign('conteudo', $conteudoRelatorio);
$smarty->assign('msg', $this->GetMsg());
GetTemplate($smarty, 'relatoriosGrid.tpl');
}
}
$relTarifaFatura = new RelTarifaFatura($idProg, $dbcon, 0);
$relTarifaFatura->ExecutaRelatorio();