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.
 
 
 
 
 
 

548 lines
19 KiB

<?php
include('FPDF/GerarPDF.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
abstract class Relatorios {
/*
* Valores globais para dados de formul?rio.
*/
private $___data = null; // Dados retornados da consulta.
protected $___dataRel = null; //Dados formatados para impress?o.
protected $___dataCount = null; // Numero de linhas retornado em uma consulta;
private $___msg = null; // Cont?m mensagens para o cliente.
private $___incDac = null; // Atribua valor "1" para incluir filtro de dac;
protected $___dataIni = null; // Data inicial usada no filtro.
protected $___dataFim = null; // Data final usada no filtro.
protected $___dac = null; // Dac retornado do formul?rio.
protected $___dataFile = null; // Arquivo de dados
protected $___pathLog = null; // Arquivo de log.
protected $___media = null; // Tipo de saida para o relat?rio.
protected $___print = null; // Indica que o relat?rio ser? enviado como arquivo.
private $___type; // Indica algum tipo incomum nos relatórios.
private $idProg;
private $dbcon;
public function __construct($idProg, $dbcon, $incDac) {
$this->idProg = $idProg;
$this->dbcon = $dbcon;
$this->___incDac = $incDac;
$this->___InicializaForm();
}
protected function ___GetQuery($query) {
$result = pg_query($query);
if (!$result) {
GeraExcept("Não foi possível executar a consulta no banco de dados!");
}
return $result;
}
public function ___ValidaForm() {
if (!IsPostBack())
return;
if ($this->GetIncDac() && !StrToIntDef($this->___dac)) {
GeraExcept('Informe uma Fila!');
}
if (!is_date($this->___dataIni)) {
GeraExcept('A "Data Inicial" informada é inválida!');
}
if (!is_date($this->___dataFim)) {
GeraExcept('A "Data Final" informada é inválida!');
}
if (strtotime(FormatDateHour($this->___dataIni)) > strtotime(FormatDateHour($this->___dataFim))) {
GeraExcept('A "Data Inicial" não pode ser maior que a "Data Final"!');
}
if (GetMaxDaysRel() != 0) {
if (strtotime(FormatDateHour($this->___dataFim)) > strtotime(FormatDateHour($this->___dataIni) . "+" . GetMaxDaysRel() . "days")) {
GeraExcept('O perído não pode ultrapassar ' . GetMaxDaysRel() . ' dias!');
}
}
}
protected function ___InicializaForm() {
/*
* Dados de formul?rio.
*/
$this->___dac = IsPostBack() ? $_POST['listaDacs'] : '';
$this->___dataIni = IsPostBack() ? $_POST['dataIni'] : date('d/m/Y');
$this->___dataFim = IsPostBack() ? $_POST['dataFim'] : date('d/m/Y');
$this->___media = isset($_GET['media']) ? $_GET['media'] : MEDIA_PRINT_GRID;
$this->___print = isset($_GET['print']) ? $_GET['print'] : 0;
/*
* Dados globais.
*/
/*
* Armazenah dados retornados da consulta.
*/
$this->___data = array();
/*
* Aramazena a quantidade de linhas em $this->___data;
*/
$this->___dataCount = 0;
/*
* Mensagens do usu?rio.
*/
$this->___msg = '';
/*
* Nome do arquivo de dados serializados na consulta. Quando o usu?rio
* faz a consulta a primeira vez os dados s?o serializados para posteriormente
* serem recuperados para outras midias, n?o necessitando fazer novamente a con-
* sulta no banco de dados.
*/
$scrpName = $this->___GetScptName();
$this->___dataFile = sprintf("/tmp/__%s_%s_%s.rel", GetLogin(), session_id(), $scrpName);
/*
* Path do arquivo de log.
*/
$this->___pathLog = sprintf("/var/log/asterisk/relatorio_%s.log", $scrpName);
}
protected function ___FiltrosRelatorio() {
if ($this->___media != MEDIA_PRINT_GRID) {
/*
* Recupera os filtros da sess�o do usu�rio.
*/
list( $this->___dac, $this->___dataIni, $this->___dataFim) = $_SESSION["SSstorageFiltros"];
if ($this->___media == MEDIA_PRINT_HTML) {
$fila = $this->GetIncDac() ? ('Fila:' . GetDacDesc($this->dbcon, $this->idProg) . ' ') : '';
return sprintf("%sData Inicial: %s Data Final: %s ", $fila, $this->___dataIni, $this->___dataFim);
}
$fltCsv = array();
if ($this->GetIncDac())
$fltCsv[] = 'Fila:' . GetDacDesc($this->dbcon, $this->idProg);
$fltCsv[] = "Data Inicial:" . $this->___dataIni;
$fltCsv[] = "Data Final:" . $this->___dataFim;
$fltCsv[] = "Data Emissao:" . Date('Y-m-d H:i:s');
$fltCsv[] = "Emitido Por:" . GetLogin();
return $fltCsv;
}
if ($this->GetIncDac()) {
$dacs = GetDac($this->dbcon, $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->idProg, MEDIA_PRINT_EXCEL, 'prt-xls.png');
$lkPrint .= sprintf($prt, $this->idProg, MEDIA_PRINT_PDF, 'prt-pdf.png');
$lkPrint .= sprintf($prt, $this->idProg, MEDIA_PRINT_CSV, 'prt-csv.png');
}
/*
* Personalise esta fun��o se necessitar de outras op��es de filtro.
*/
$filtro = '<table border="0" cellspacing="1" cellpadding="1">';
/*
* Rotulos.
*/
$filtro .= '<tr>';
if ($this->GetIncDac())
$filtro .= '<td>Fila</td>';
$filtro .= '<td>Data Inicial</td>';
$filtro .= '<td>Data Final </td>';
$filtro .= '<td>&nbsp;</td>';
$filtro .= '</tr>';
/*
* Valores.
*/
$filtro .= '<tr>';
if ($this->GetIncDac())
$filtro .= sprintf('<td>%s</td>', $dacs);
$filtro .= '<td><input name="dataIni" id="dataIni" type="text" size="15" maxlength="10" value="%s" onkeyup="formataData(this)" title="dd/mm/aaaa"></td>';
$filtro .= '<td><input name="dataFim" id="dataFim" type="text" size="15" maxlength="10" value="%s" onkeyup="formataData(this)" title="dd/mm/aaaa"></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 emiss�o dos relat?ios para impress�o.
*/
$_SESSION["SSstorageFiltros"] = array($this->___dac, $this->___dataIni, $this->___dataFim);
return sprintf($filtro, $this->___dataIni, $this->___dataFim, $lkPrint);
}
public function ___ConteudoRelatorio() {
if ($this->___media == MEDIA_PRINT_GRID) {
$this->___GetDadosDb();
SaveVarToFile($this->___data, $this->___dataFile);
$this->___PreparaData();
} else {
$this->___data = ReadVarFile($this->___dataFile);
$this->___PreparaData();
}
$this->___dataCount = count($this->___data[0]?? []);
}
public function ___ImprimeRelatorio() {
switch ($this->___media) {
//case MEDIA_PRINT_HTML: return $this->___ImprimeHtml();
case MEDIA_PRINT_HTML: return $this->___ImprimePdf("I");
case MEDIA_PRINT_PDF: return $this->___ImprimePdf("D");
case MEDIA_PRINT_EXCEL: return $this->___ImprimeExcel();
case MEDIA_PRINT_CSV: return $this->___ImprimeCsv();
default:
return $this->___ImprimeGrid();
}
}
protected function ___GravaLog($erro = true) {
$erroSys = error_get_last();
$erroSys = sprintf("Msg: %s Line: %s", $erroSys['message'], $erroSys['line']);
$erroBd = pg_last_error();
$log = sprintf("Data: %s Login: %s Msg: %s Sys:[ %s ] BD: %s Tipo: %s ", date('Y-m-d H:i:s'), GetLogin(), $this->___msg, $erroSys, $erroBd, $erro ? 'ER' : 'OK');
$arq = fopen($this->___pathLog, 'a');
fwrite($arq, $log);
fclose($arq);
}
private function ___GetScptName() {
$query = sprintf("select arquivo from pbx_funcoes_internas where id_prog = '%s'", $this->idProg);
$result = pg_query($query);
$row = pg_fetch_row($result);
$path = pathinfo($row[0]);
return $path['filename'];
}
private function ___PreparaData() {
switch ($this->___media) {
// case MEDIA_PRINT_HTML: $this->___PreparaHtml();
// break;
case MEDIA_PRINT_HTML: $this->___PreparaPdf();
break;
case MEDIA_PRINT_PDF: $this->___PreparaPdf();
break;
case MEDIA_PRINT_EXCEL: $this->___PreparaExcel();
break;
case MEDIA_PRINT_CSV: $this->___PreparaCsv();
break;
default:
case MEDIA_PRINT_GRID: $this->___PreparaGrid();
break;
}
}
abstract protected function ___PreparaHtml();
abstract protected function ___PreparaPdf();
abstract protected function ___PreparaExcel();
abstract protected function ___PreparaCsv();
abstract protected function ___PreparaGrid();
private function ___ImprimeGrid() {
$fh = fopen('php://memory', 'rw');
$numTable = 0;
foreach ($this->___dataRel as $dadosPrint) {
/*
* Imprime uma linha entre as tabelas.
*/
if ($numTable++) {
fwrite($fh, "<br />");
}
/*
* Imprime as tabelas.
*/
foreach ($dadosPrint as $row) {
fwrite($fh, $row);
}
}
rewind($fh);
return stream_get_contents($fh);
}
private function ___ImprimeHtml() {
$fh = fopen('php://memory', 'rw');
$numTable = 0;
foreach ($this->___dataRel as $dadosPrint) {
/*
* Imprime uma linha entre as tabelas.
*/
if ($numTable++) {
fwrite($fh, "<br />");
}
/*
* Imprime as tabelas.
*/
foreach ($dadosPrint as $row) {
fwrite($fh, $row);
}
}
rewind($fh);
$conteudoRelatorio = stream_get_contents($fh);
fclose($fh);
$filtros = $this->___FiltrosRelatorio();
ob_end_clean();
ob_start();
echo $this->___GetTemplate($filtros, $conteudoRelatorio);
ob_flush();
exit(0);
}
private function ___GetTemplate($filtros, $conteudoRelatorio) {
$pathTpl = $_SESSION[PATH_ABSOLUTO] . 'templates/relbasehtml.tpl';
$vars = array('tituloPage' => GetDispProgSel($this->idProg),
'logoRel' => GetLogoRel(),
'REL_HEAD_NIVEL1' => GetHeadRel(REL_HEAD_NIVEL1),
'tituloRelatorio' => GetDispProgSel($this->idProg),
'filtros' => $filtros,
'conteudoRelatorio' => $conteudoRelatorio,
'dataEmissao' => date('d/m/Y H:i:s'),
'login' => GetLogin()
);
$content = file_get_contents($pathTpl);
foreach ($vars as $key => $value) {
$content = str_replace('{' . $key . '}', $value, $content);
}
return $content;
}
private function ___ImprimePdf($target) {
$pdf = new GerarPDF();
//Informações do Filtro do Relatório
$pdf->setLogoRel(GetLogoRel());
$pdf->setNomeRel(GetDispProgSel($this->GetIdProg()));
$pdf->setDataRel(date('d/m/Y H:i:s'));
$pdf->setUserRel(GetLogin());
$pdf->setFiltroRelIni($this->___dataIni);
$pdf->setFiltroRelFim($this->___dataFim);
$pdf->setFiltroRelDac(GetDacDesc($this->GetDbCon(), $this->___dac));
$pdf->setType($this->___type);
//Formatação do PDF
$pdf->SetFont('Arial', '', 6);
$pdf->AddPage($this->___type == "L" ? $this->___type : "P");
$pdf->Ln(5);
//Tabela Principal
foreach ($this->___dataRel as $dadosRel) {
$pdf->Table($dadosRel[0], $dadosRel[1], $dadosRel[2], $dadosRel[3], $dadosRel[4], $dadosRel[5]);
}
//Gera o download do PDF
$pdf->Output(GetDispProgSel($this->GetIdProg()) . ".pdf", $target);
}
private function ___ImprimeExcel() {
$fileName = sprintf("%s.xls", substr(LimpaString(GetDispProgSel($this->idProg)), 0, 32));
$objPHPExcel = new Spreadsheet();
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
//Nome do Relatório
$sheet->getRowDimension(1)->setRowHeight(20);
$cell = $sheet->setCellValue('A1', RemoveAcentos(GetDispProgSel($this->idProg)));
$sheet->mergeCells('A1:F1');
$cell->getStyle('A1:F1')->getFont()->setSize(13)->setBold(true);
$cell->getStyle('A1:F1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
//Cria Alfabeto de A à Z
$alf = array();
$final = ord('Z');
for ($letra = ord('A'); $letra <= $final; $letra++) {
$current = chr($letra);
if ($current !== 'Y') {
$alf[] = $current;
}
}
$linha = 2;
foreach ($this->___dataRel as $values) {
foreach ($values as $dados) {
$coluna = 0;
$startLabel = 0;
$startValue = 0;
$sheet->getDefaultColumnDimension()->setWidth(17);
foreach ($dados as $value) {
if (($value === 'LABEL') || $startLabel) {
if ($startLabel) {
$sheet->setCellValue($alf[$coluna] . $linha, $value)->getStyle($alf[$coluna] . $linha)->getFont()->setSize(12)->setBold(true);
$coluna++;
}
$startLabel++;
} elseif (($value === 'DADOS') || $startValue) {
if ($startValue) {
$sheet->setCellValue($alf[$coluna] . $linha, $value);
$coluna++;
}
$startValue++;
}
$sheet->getRowDimension($linha)->setRowHeight(17);
}
$linha++;
}
}
$writer = new Xls($objPHPExcel);
$fh = fopen('php://memory', 'rw');
$writer->save($fh);
rewind($fh);
$this->___SendFile($fh, $fileName);
}
private function ___ImprimeExcelOld() {
$fileName = sprintf("%s.xls", substr(LimpaString(GetDispProgSel($this->idProg)), 0, 32));
$fh = fopen('php://memory', 'rw');
$linha = 1;
$coluna = 0;
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
//Nome do Relatório
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(20);
$cell = $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($coluna, $linha, RemoveAcentos(GetDispProgSel($this->idProg)));
$cell->mergeCells('A1:F1');
$cell->getStyle()->getFont()->setSize(13)->setBold(true);
$cell->getStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//Cria Alfabeto de A à Z
$alf = array();
$final = ord('Z');
for ($letra = ord('A'); $letra <= $final; $letra++) {
$current = chr($letra);
if ($current !== 'Y') {
$alf[] = $current;
}
}
foreach ($this->___dataRel as $values) {
foreach ($values as $dados) {
$linha++;
$coluna = 0;
$startLabel = 0;
$startValue = 0;
$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
foreach ($dados as $value) {
if (($value === 'LABEL') || $startLabel) {
if ($startLabel) {
$objPHPExcel->getActiveSheet()->getColumnDimension($alf[$coluna])->setWidth(17);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($coluna, $linha, $value)->getStyleByColumnAndRow($coluna, $linha)->getFont()->setSize(12)->setBold(true);
$coluna++;
}
$startLabel++;
} elseif (($value === 'DADOS') || $startValue) {
if ($startValue) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($coluna++, $linha, $value);
}
$startValue++;
}
$objPHPExcel->getActiveSheet()->getRowDimension($linha)->setRowHeight(17);
}
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save($fh);
rewind($fh);
$this->___SendFile($fh, $fileName);
}
private function ___ImprimeCsv() {
$fileName = sprintf("%s.csv", substr(LimpaString(GetDispProgSel($this->idProg)), 0, 32));
$fh = fopen('php://memory', 'rw');
foreach ($this->___dataRel as $values) {
foreach ($values as $value) {
fwrite($fh, $value);
}
}
rewind($fh);
$this->___SendFile($fh, $fileName);
}
private function ___SendFile($data, $fileName) {
ob_end_clean();
ob_start();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header(sprintf("Content-type: %s", GetMimeContentType($fileName)));
header(sprintf("Content-Disposition: attachment; filename=%s", $fileName));
header("Expires: 0");
header("Pragma: public");
fpassthru($data);
ob_flush();
fclose($data);
exit(0);
}
protected function GetData() {
return $this->___data;
}
protected function SetData($data) {
$this->___data[] = ($data ?? []);
}
protected function GetIdProg() {
return $this->idProg;
}
protected function GetDbCon() {
return $this->dbcon;
}
protected function GetMsg() {
return $this->___msg;
}
protected function GetIncDac() {
return $this->___incDac;
}
protected function SetMsg($msg) {
$this->___msg = $msg;
}
function getType() {
return $this->___type;
}
function setType($___type) {
$this->___type = $___type;
}
abstract protected function ___GetDadosDb();
abstract public function ExecutaRelatorio();
}
?>