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.

636 lines
26 KiB

<?php
include_once 'util/relatoriosBase.php';
class RelComissao extends Relatorios {
/**
* CONF_ATIVO_CLIENTE
* CONF_ATIVO_PROSPECT
*
* Para realizar a consulta conforme o status aceita "vazio, 0 e 1"
*/
const CONF_ATIVO_CLIENTE = '';
const CONF_ATIVO_PROSPECT = '';
const CONF_STATUS_CLIENTE = array(30);
private $___agente;
private $___client_id;
private $___ajax;
private $___status;
private $___dataLead;
public function __construct($idProg, $dbcon, $incDac) {
parent::__construct($idProg, $dbcon, $incDac);
$this->___ajax = isset($_GET["ajax"]) ? $_GET["ajax"] : 0;
$this->___client_id = isset($_POST["client_id"]) ? $_POST["client_id"] : 0;
$this->___agente = isset($_POST["agente"]) ? $_POST["agente"] : 0;
$this->___status = isset($_REQUEST["status"]) ? $_REQUEST["status"] : 'Todos';
$this->___dataLead = isset($_REQUEST["dataLead"]) ? $_REQUEST["dataLead"] : '';
$oldMouth = date("m", strtotime("first day of previous month"));
$this->___dataIni = IsPostBack() ? $_POST['dataIni'] : date("21/{$oldMouth}/Y");
$this->___dataFim = IsPostBack() ? $_POST['dataFim'] : date('20/m/Y');
}
function ___FiltrosRelatorio() {
$agente = $this->getAgente($this->___agente);
$status = $this->getStatus($this->___status);
if ($this->___media != MEDIA_PRINT_GRID) {
/*
* Recupera os filtros da sess<EFBFBD>o do usu<EFBFBD>rio.
*/
list($this->___dataIni, $this->___dataFim, $this->___tipoRelatorio) = $_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<EFBFBD>tico' : 'Sint<EFBFBD>tico'));
}
$fltCsv = array();
if ($this->GetIncDac()) {
$fltCsv[] = 'Fila:' . GetDacDesc($this->GetDbCon(), $this->___dac);
}
$fltCsv[] = "Data Inicial:" . $this->___dataIni;
$fltCsv[] = "Data Final:" . $this->___dataFim;
$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&status=%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&status=%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, $this->___status, substr(LimpaString(GetDispProgSel($this->GetIdProg())), 0, 20), 'print.gif');
$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_EXCEL, $this->___tipoRelatorio, $this->___status, 'prt-xls.png');
$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_PDF, $this->___tipoRelatorio, $this->___status, 'prt-pdf.png');
//$lkPrint .= sprintf($prt, $this->GetidProg(), MEDIA_PRINT_CSV, $this->___tipoRelatorio, 'prt-csv.png');
}
// $tipoRel = !$this->___tipoRelatorio ? '' : 'checked="checked"';
/*
* Personalise esta fun<EFBFBD><EFBFBD>o se necessitar de outras op<EFBFBD><EFBFBD>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>Agente</td>';
$filtro .= '<td>Status</td>';
$filtro .= '<td align="center" valign="middle">&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 .= sprintf('<td>%s</td>', $agente);
$filtro .= sprintf('<td>%s</td>', $status);
$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<EFBFBD>o dos relat<EFBFBD>ios para impress<EFBFBD>o.
*/
$_SESSION["SSstorageFiltros"] = array($this->___dataIni, $this->___dataFim, $this->___tipoRelatorio);
return sprintf($filtro, $this->___dataIni, $this->___dataFim, $lkPrint);
}
protected function ___GetDadosDb($add = null, $dataLead = null) {
if ($dataLead && $add) {
$query = sprintf("UPDATE pbx_cliente SET data_lead = '%s' WHERE client_id = '%s';", $dataLead . " " . date('H:i:s'), $add);
$result = $this->___GetQuery($query);
return true;
}
if ($add) {
$query = "UPDATE pbx_cliente SET data_lead = 'now' WHERE client_out_id = $add AND client_status = '21';";
$result = $this->___GetQuery($query);
return true;
}
$dataIni = FormatDtMssql($this->___dataIni);
$dataFim = FormatDtMssql($this->___dataFim);
$agente = $this->___agente;
$query = "SELECT client_id, client_out_id, matricula, client_documento, client_razao_social, apelido, data_lead, client_update::date
FROM pbx_cliente a
INNER JOIN pbx_usuarios b ON client_user_contato = matricula
WHERE client_status = '21'
AND client_update >= '$dataIni'
AND client_update <= '$dataFim' ";
if ($agente) {
$query .= " AND matricula = '$agente' ";
}
$query .= " ORDER BY apelido, client_update";
$result = $this->___GetQuery($query);
$row = pg_fetch_all($result);
if (!$agente) {
$_SESSION['SSDadosAgents'] = $row;
}
$this->SetData($row ? $row : array());
}
protected function ___PreparaCsv() {
}
protected function ___PreparaExcel() {
$dataRel = array();
$filtro = $this->___FiltrosRelatorio();
/*
* Inicia o relat<EFBFBD>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;
}
$dataRel[] = $linha;
$dadosCabecalio = array(
'Documento',
'Empresa',
'Apelido',
'Atualizado',
'Proposta'
);
$dadosField = array(
'client_documento',
'client_razao_social',
'apelido',
'client_update',
'proposta'
);
$linha = array('LABEL');
foreach ($dadosCabecalio as $value) {
$linha[] = $value;
}
$dataRel[] = $linha;
$count = 0;
$countVendas = 0;
$lastAgent = null;
$proposta = $this->ConsultaProposta();
foreach ($this->GetData()[0] as $row) {
if($this->___status == "LEAD" && !$proposta[$row["client_out_id"]] && !$row["data_lead"]){
continue;
} else if($this->___status == "EXPORTADOS" && ($proposta[$row["client_out_id"]] || $row["data_lead"])){
continue;
}
$count++;
$row['client_razao_social'] = RemoveAcentos($row['client_razao_social']);
$row['proposta'] = ($proposta[$row["client_out_id"]] || $row["data_lead"]) ? 'SIM' : 'NAO';
if ($lastAgent == null) {
$lastAgent = $row['apelido'];
}
if ($row['apelido'] != $lastAgent) {
$dataRel[] = array('LABEL', "[$lastAgent]", 'Total Exportados: ' . $countVendas, '', '');
$countVendas = 0;
$lastAgent = $row['apelido'];
}
$linha = array('DADOS');
foreach ($dadosField as $key) {
if ($key == 'client_update') {
$linha[] .= date('d/m/Y', strtotime($row["$key"]));
} else {
$linha[] .= $row["$key"];
}
}
$dataRel[] = $linha;
$countVendas++;
}
$dataRel[] = array('LABEL', "[$lastAgent]", 'Total Exportados: ' . $countVendas);
$this->___dataRel[] = $dataRel;
}
protected function ___PreparaGrid() {
$dataRel = array();
$dadosCabecalio = array(
'Documento' => 'align="center"',
'Empresa' => 'align="center"',
'Apelido' => 'align="center"',
'Atualizado' => 'align="center"',
'Proposta' => 'align=center'
);
$dadosField = array(
'client_documento' => 'align="center"',
'client_razao_social' => 'align="center"',
'apelido' => 'align="center"',
'client_update' => 'align="center"',
'proposta' => 'align="center"'
);
/*
* Inicia o relat<EFBFBD>rio.
*/
$dataRel[] = '<table width="80%" cellpadding="2" class="grid">';
/*
* Monta a linha de cabecalio.
*/
$linha = '<tr>';
$linha .= "<th align=\"center\" colspan=\"7\">Relat<EFBFBD>rio de Comiss<EFBFBD>o por Agente</th>";
$linha .= "</tr>";
$dataRel[] = $linha;
/*
* Verifica se retornou dados
*/
if (!IsPostBack() || !count($this->GetData()[0])) {
$dataRel[] = sprintf("<tr><td align=\"center\" colspan=\"%s\">%s</td></tr></table>", count(1), (!IsPostBack() ? 'Informe os parametros e clique em consultar!' : 'Nenhum registro encontado!'));
$this->___dataRel[] = $dataRel;
return;
}
$linhaC = "<tr>";
foreach ($dadosCabecalio as $key => $value) {
$linhaC .= sprintf("<th %s>%s</th>", $value, $key);
}
$linhaC .= "</tr>";
$dataRel[] = $linhaC;
/*
* Linhas de dados.
*/
$count = 0;
$countVendas = 0;
$lastAgent = null;
$proposta = $this->ConsultaProposta();
foreach ($this->GetData()[0] as $row) {
if($this->___status == "LEAD" && !$proposta[$row["client_out_id"]] && !$row["data_lead"]){
continue;
} else if($this->___status == "EXPORTADOS" && ($proposta[$row["client_out_id"]] || $row["data_lead"])){
continue;
}
$count++;
if ($lastAgent == null) {
$lastAgent = $row['apelido'];
}
if ($row['apelido'] != $lastAgent) {
$dataRel[] = sprintf('<tr><th align="center" colspan="7" >[%s] Total %s: %s</th></tr> <tr><td colspan="7" >&nbsp</td></tr>', ($this->___status == "Todos" ? "GERAL" : $this->___status), $lastAgent, $countVendas);
$countVendas = 0;
$lastAgent = $row['apelido'];
}
$edit = function ($tipo, $row) {
return sprintf("<img src='imgSite/%s.png' id='%s' class='%s'> &nbsp "
. "<input type='date' class='date_{$row['client_id']}' name='dateDataLead' style='display: none'/> "
. "<a href='#' class='date_{$row['client_id']}' id='save' style='display: none'><img align='absmiddle' style='vertical-align: middle' src='imgSite/Save.png'></a>"
. " &nbsp <a href='#' class='date_{$row['client_id']}' id='close' style='display: none'><img src='imgSite/Cancel.png' align='absmiddle' style='vertical-align: middle'></a>", $tipo, $row['client_id'], $tipo);
};
$checkbox = '<input type="checkbox" name="%s" id="%s" class="clickedProposta" title="Selecione para habilitar a proposta tempor<EFBFBD>ria" %s> &nbsp %s';
$row['proposta'] = ($proposta[$row["client_out_id"]] || $row["data_lead"]) ? sprintf($checkbox, $row["client_out_id"], $row["client_out_id"], 'checked', $edit('editaUser', $row)) : sprintf($checkbox, $row["client_out_id"], $row["client_out_id"], '', $edit('editaUserOff', $row));
$linha = "<tr>";
foreach ($dadosField as $key => $value) {
if ($key == 'client_update') {
$linha .= sprintf("<td %s>%s</td>", $value, date('d/m/Y', strtotime($row["$key"])));
} else {
$linha .= sprintf("<td %s>%s</td>", $value, $row["$key"]);
}
}
$linha .= "</tr>";
$dataRel[] = $linha;
$countVendas++;
}
// echo implode(',',$datas);
$dataRel[] = sprintf('<tr><th align="center" colspan="7" >[%s] Total %s: %s</th></tr> <tr><td colspan="7" >&nbsp</td></tr>', ($this->___status == "Todos" ? "GERAL" : $this->___status), $lastAgent, $countVendas);
$dataRel[] = sprintf('<tr><th align="left" colspan="7" >Total: %s</th></tr>', $count);
$this->___dataRel[] = $dataRel;
}
protected function ___PreparaHtml() {
}
protected function ___PreparaPdf() {
list($this->___dataIni, $this->___dataFim, $this->___tipoRelatorio) = $_SESSION["SSstorageFiltros"];
$dadosCabecalio = array(
'Documento' => 'C',
'Empresa' => 'C',
'Apelido' => 'C',
'Atualizado' => 'C',
'Proposta' => 'C'
);
$dadosField = array(
'client_documento' => 'C',
'client_razao_social' => 'C',
'apelido' => 'C',
'client_update' => 'C',
'proposta' => 'C'
);
$count = 0;
$countVendas = 0;
$lastAgent = null;
$tables = array();
$widthHeader = array(35, 73, 32, 25, 25);
$dadosTable = array();
$proposta = $this->ConsultaProposta();
/*
* Linhas de dados.
*/
foreach ($this->GetData()[0] as $key => $row) {
if($this->___status == "LEAD" && !$proposta[$row["client_out_id"]] && !$row["data_lead"]){
continue;
} else if($this->___status == "EXPORTADOS" && ($proposta[$row["client_out_id"]] || $row["data_lead"])){
continue;
}
$count++;
if ($lastAgent == null) {
$lastAgent = $row['apelido'];
}
if ($row['apelido'] != $lastAgent) {
$totalizador = array('', '', "[$lastAgent]", 'Total Exportados: ' . $countVendas, '');
${"table" . $count} = array($dadosCabecalio, $dadosField, $dadosTable, $widthHeader, $totalizador, 0);
array_push($tables, ${"table" . $count});
$countVendas = 0;
$dadosTable = array();
$lastAgent = $row['apelido'];
}
$row['proposta'] = ($proposta[$row["client_out_id"]] || $row["data_lead"]) ? 'SIM' : 'N<EFBFBD>O';
$row['client_update'] = date('d/m/Y', strtotime($row['client_update']));
$countVendas++;
$dadosTable[] = $row;
}
$totalizador = array('', '', "[$lastAgent]", 'Total Exportados: ' . $countVendas, '');
${"table" . $count} = array($dadosCabecalio, $dadosField, $dadosTable, $widthHeader, $totalizador, 0);
array_push($tables, ${"table" . $count});
$totalizador = array('Total:' . $count, '' , '', '');
$total = array('', '', '', '', $totalizador, 0);
array_push($tables, $total);
$this->___dataRel = $tables;
}
function ConsultaVendaMais() {
$query = "exec sip_cliente_prevenda 0";
$data = $this->getConnection($query);
$clientId = array();
$cpf = array();
foreach ($data as $cli) {
if ((strtotime($cli['data_cadastro']) >= strtotime(FormatDtMssql($this->___dataIni))) && (strtotime($cli['data_cadastro']) <= strtotime(FormatDtMssql($this->___dataFim)))) {
$clientId[] = $cli['cliente_id'];
$cpf[] = QuotedStr($cli['cgc_cpf']);
}
}
return array($clientId, $cpf);
}
function ConsultaProposta() {
$dados = array();
foreach ($this->GetData()[0] as $row) {
$dados[] = $row['client_out_id'];
}
$imp = implode(',', $dados);
if (!$imp) {
return $imp;
}
$query = "SELECT a.ClienteId, RazaoSocial, VendedorId, CGC_CPF, PropostaId, Descricao, StatusId, b.AddedDate
FROM Clientes a
INNER JOIN Propostas b ON b.ClienteId = a.ClienteId
INNER JOIN PropostasStatus c ON c.PropostaStatusId = b.StatusId
WHERE a.ClienteId IN ($imp)
AND b.PropostaId = (SELECT MAX(PropostaId) FROM Propostas WHERE ClienteId = a.ClienteId)
GROUP BY a.ClienteId, RazaoSocial, VendedorId, CGC_CPF, PropostaId, Descricao, StatusId, b.AddedDate
ORDER BY a.ClienteId, b.AddedDate";
$data = $this->getConnection($query);
$clientes = array();
foreach ($data as $cli) {
$clientes[$cli['ClienteId']] = $cli['CGC_CPF'];
}
return $clientes;
}
private function getConnection($query) {
$connection = mssql_connect('192.168.115.28', 'integracao', 'SimpleS_root');
mssql_select_db('VendaMaisDB_simplesip');
$result = mssql_query($query, $connection);
$return = array();
while ($data = mssql_fetch_array($result)) {
$return[] = $data;
}
return $return;
}
private function getAgente($select = null) {
$opt = "<select name=\"agente\" id=\"agente\" size=\"1\">";
$opt .= "<option value='0'>Todos</option>";
$agentes = array();
$lastMatricula = 0;
foreach ($_SESSION['SSDadosAgents'] as $agente) {
if ($lastMatricula != $agente['matricula']) {
array_push($agentes, array('matricula' => $agente['matricula'], 'apelido' => $agente['apelido']));
$lastMatricula = $agente['matricula'];
}
}
if ($agentes) {
foreach ($agentes as $val) {
$selected = $select == $val['matricula'] ? 'selected' : '';
$opt .= "<option value='{$val['matricula']}' $selected>{$val['apelido']}</option>";
}
}
$opt .= "</select>";
return $opt;
}
private function getStatus($select = null) {
$opt = "<select name=\"status\" id=\"status\" size=\"1\">";
$opt .= "<option value='0'>Todos</option>";
$status = ['LEAD','EXPORTADOS'];
foreach ($status as $val) {
$selected = $select == strtoupper($val) ? 'selected' : '';
$opt .= "<option value='{$val}' $selected>{$val}</option>";
}
$opt .= "</select>";
return $opt;
}
private function vendasValores($vendas) {
if (!$vendas) {
return 0;
}
if ($vendas >= 1 && $vendas <= 10) {
$meta = 10;
return array('meta' => $meta, 'recebiveis' => $vendas * $meta);
}
if ($vendas >= 11 && $vendas <= 15) {
$meta = 15;
return array('meta' => $meta, 'recebiveis' => $vendas * $meta);
}
if ($vendas >= 16 && $vendas <= 20) {
$meta = 17;
return array('meta' => $meta, 'recebiveis' => $vendas * $meta);
}
if ($vendas >= 21) {
$meta = 23;
return array('meta' => $meta, 'recebiveis' => $vendas * $meta);
}
}
public function ExecutaRelatorio() {
global $jsStartup, $jsJQuery, $smarty;
try {
if ($this->___ajax && $this->___client_id) {
$this->___GetDadosDb($this->___client_id, $this->___dataLead);
echo "OK";
exit();
}
/*
* Use esta fun<EFBFBD><EFBFBD>o para validar dados do formul<EFBFBD>rio.
*/
$this->___ValidaForm();
/*
* Recupera os dados do banco.
*/
$this->___ConteudoRelatorio();
/*
* Imprime relat<EFBFBD>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<EFBFBD>rios aqui.
*/
$jsJQuery[] = "$('.clickedProposta').on('click', function(){
if(confirm('Deseja adicionar esse cliente como Lead?')){
$.ajax({
url: 'index.php?idProg=352&ajax=1',
type: 'post',
data: {
'client_id': this.id
},
success: function (resp) {
if(resp.trim() == 'OK'){
alert('Cliente adicionado com sucesso!')
}
}
})
} else {
$(this).prop('checked', false)
}
})";
$jsJQuery[] = "$('.editaUser').on('click', function(){
$('.date_' + this.id).on('click', function(){
if(this.id == 'close'){
$('.' + this.className).hide();
}
if(this.id == 'save'){
let dataLead = $('.' + this.className).val()
if(dataLead){
$.ajax({
url: 'index.php?idProg=352&ajax=1&dataLead=' + dataLead,
type: 'post',
data: {
'client_id': this.className.replace('date_', '')
},
success: function (resp) {
console.log(resp)
if(resp.trim() == 'OK'){
alert('Lead alterado com sucesso!')
}
}
})
} else {
alert('Informe uma data valida para o Lead!')
}
}
})
$('.date_' + this.id).show();
})";
$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');
}
}
$relRelContribuinte = new RelComissao($idProg, $dbcon, 0);
$relRelContribuinte->ExecutaRelatorio();
?>