Esempio n. 1
0
 function EquipmentOperator($sqlserverConnection, $businessPartnerCode, $equipmentCode)
 {
     // Cria os objetos de mapeamento objeto relacional
     $businessPartnerDAO = new BusinessPartnerDAO($sqlserverConnection);
     $businessPartnerDAO->showErrors = 1;
     $equipmentDAO = new EquipmentDAO($sqlserverConnection);
     $equipmentDAO->showErrors = 1;
     $contactPersonDAO = new ContactPersonDAO($sqlserverConnection);
     $contactPersonDAO->showErrors = 1;
     // Recupera os dados do parceiro de negócios
     $businessPartner = $businessPartnerDAO->RetrieveRecord($businessPartnerCode);
     if ($businessPartner != null) {
         $this->businessPartnerCode = $businessPartner->cardCode;
         $this->businessPartnerName = $businessPartner->cardName;
         $this->telephoneNumber = $businessPartner->telephoneNumber;
     }
     // Recupera os dados do equipamento
     $equipment = $equipmentDAO->RetrieveRecord($equipmentCode);
     if ($equipment != null) {
         $contactPerson = null;
         if (!empty($equipment->contactPerson)) {
             $contactPerson = $contactPersonDAO->RetrieveRecord($equipment->contactPerson);
         }
         if ($contactPerson != null) {
             $contactTel = trim($contactPerson->phoneNumber);
             if (!empty($contactTel)) {
                 $this->operatorName = $contactPerson->name;
                 $this->telephoneNumber = $contactPerson->phoneNumber;
             }
         }
         $this->equipmentCode = $equipment->insID;
         $this->serialNumber = $equipment->manufacturerSN;
         $this->equipmentStatus = $equipment->status;
     }
 }
 static function GetTelephoneNumber($sqlserverConnection, $cardCode)
 {
     $telephoneNumber = "";
     $businessPartnerDAO = new BusinessPartnerDAO($sqlserverConnection);
     $businessPartnerDAO->showErrors = 1;
     $businessPartner = $businessPartnerDAO->RetrieveRecord($cardCode);
     if ($businessPartner != null) {
         $telephoneNumber = $businessPartner->telephoneNumber;
     }
     return $telephoneNumber;
 }
Esempio n. 3
0
$nivelAutorizacao = GetAuthorizationLevel($dataConnector->mysqlConnection, $functionalities["gerenciamentoLeituras"]);
if ($nivelAutorizacao <= 1) {
    DisplayNotAuthorizedWarning();
    exit;
}
// Cria os objetos de mapeamento objeto-relacional
$readingDAO = new ReadingDAO($dataConnector->mysqlConnection);
$readingDAO->showErrors = 1;
$counterDAO = new CounterDAO($dataConnector->mysqlConnection);
$counterDAO->showErrors = 1;
$equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
$equipmentDAO->showErrors = 1;
$equipment = $equipmentDAO->RetrieveRecord($equipmentCode);
$capacity = $equipment->capacity;
$serialNumber = $equipment->manufacturerSN . " ( " . $equipment->internalSN . " ) ";
$clientName = new Text(BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $equipment->customer));
$id = 0;
$reading = new ReadingDTO();
if (isset($_REQUEST["id"]) && $_REQUEST["id"] != 0) {
    $id = $_REQUEST["id"];
    $reading = $readingDAO->RetrieveRecord($id);
}
?>

    <h1>Administração - Leitura - <?php 
echo $serialNumber;
?>
</h1><br/>
    <h1><?php 
echo str_pad('_', 52, '_', STR_PAD_LEFT);
?>
    <input type="hidden" name="reportUrl" value="<?php 
echo $reportUrl;
?>
" />
    <input type="hidden" name="parameters" value="<?php 
echo $parameters;
?>
" />

    <label class="left" style="width:99%; text-align: left; <?php 
echo $searchMethod != 1 ? "display:inline;" : "display:none;";
?>
">Cliente<br/>
        <select name="businessPartnerCode" style="width: 98%;" >
            <?php 
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
$clientArray = $businessPartnerDAO->RetrieveRecordArray("CardName IS NOT NULL ORDER BY CardName");
foreach ($clientArray as $client) {
    $informacaoAdicional = "";
    if ($client->cardName != $client->cardFName) {
        $informacaoAdicional = " (" . $client->cardFName . ")";
    }
    $clientInfo = new Text($client->cardName . $informacaoAdicional);
    echo "<option value=" . $client->cardCode . ">" . $clientInfo->Truncate(85) . "</option>";
}
?>
        </select>
    </label>
    <div style="clear:both; <?php 
echo $searchMethod != 1 ? "display:inline;" : "display:none;";
include_once "../ClassLibrary/DataConnector.php";
include_once "../DataAccessObjects/ContractDAO.php";
include_once "../DataTransferObjects/ContractDTO.php";
include_once "../DataAccessObjects/BusinessPartnerDAO.php";
include_once "../DataTransferObjects/BusinessPartnerDTO.php";
// Abre a conexao com o banco de dados
$dataConnector = new DataConnector('both');
$dataConnector->OpenConnection();
if ($dataConnector->mysqlConnection == null || $dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
// Cria os objetos de mapeamento objeto-relacional
$contractDAO = new ContractDAO($dataConnector->mysqlConnection);
$contractDAO->showErrors = 1;
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
// Traz os contratos que estão na última parcela
$contractArray = $contractDAO->RetrieveRecordArray("parcelaAtual=quantidadeParcelas AND status <> 3 AND status <> 4  AND categoria < 5");
if (sizeof($contractArray) == 0) {
    echo '<tr><td colspan="2" align="center">Nenhum registro encontrado!</td></tr>';
    exit;
}
foreach ($contractArray as $contract) {
    $businessPartner = $businessPartnerDAO->RetrieveRecord($contract->pn);
    ?>
        <tr>
            <td>
                <a href="Frontend/contrato/editar.php?id=<?php 
    echo $contract->id;
    ?>
Esempio n. 6
0
        <br/>
        <a href="<?php 
echo $root . '/logout.php';
?>
" >
            Sair
        </a>
    </div>

    <!--  MENU LATERAL ALTERNATIVO
    <div style="width:260px; height:800px; float:left;" >
        <hr noshade="noshade" style="width:260px; color:white;" />
        <?php 
foreach ($contractArray as $contract) {
    $contractNum = str_pad($contract->numero, 5, '0', STR_PAD_LEFT);
    $clientName = new Text(BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $contract->pn));
    $contractStatus = ContractDAO::GetStatusAsText($contract->status);
    $subContractArray = $subContractDAO->RetrieveRecordArray("contrato_id=" . $contract->id);
    $typeEnumeration = "";
    foreach ($subContractArray as $subContract) {
        if (!empty($typeEnumeration)) {
            $typeEnumeration .= ', ';
        }
        $typeEnumeration .= $subContract->siglaTipoContrato;
    }
    $contractTypes = new Text($typeEnumeration);
    $tags = $contractNum . ' ' . $clientName->Truncate(50) . ' ' . $contractTypes->Truncate(20) . ' ' . $contractStatus;
    echo '<a style="float:left; text-align:center;" class="contractIcon" rel="' . $contract->id . '" rev="' . $tags . '" >';
    echo '<img src="' . $pathImg . '/document.png" alt="" style="width:50px; height:50px;" /><br/>';
    echo $contractNum;
    echo '</a>';
Esempio n. 7
0
include_once "../ClassLibrary/DataConnector.php";
include_once "../DataAccessObjects/EquipmentDAO.php";
include_once "../DataTransferObjects/EquipmentDTO.php";
include_once "../DataAccessObjects/BusinessPartnerDAO.php";
include_once "../DataTransferObjects/BusinessPartnerDTO.php";
// Abre a conexao com o banco de dados
$dataConnector = new DataConnector('both');
$dataConnector->OpenConnection();
if ($dataConnector->mysqlConnection == null || $dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
// Cria os objetos de mapeamento objeto-relacional
$equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
$equipmentDAO->showErrors = 1;
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
$manufacturerSN = "";
$internalSN = "";
$itemCode = "";
$itemName = "";
$customer = "";
$address = "";
$instLocation = "";
$sla = "";
$equipmentDTO = $equipmentDAO->RetrieveRecord($equipmentCode);
if (!empty($equipmentDTO)) {
    $manufacturerSN = $equipmentDTO->manufacturerSN;
    $internalSN = $equipmentDTO->internalSN;
    $itemCode = $equipmentDTO->itemCode;
    $itemName = $equipmentDTO->itemName;
Esempio n. 8
0
                            <a href="<?php 
    echo 'Frontend/' . $currentDir . '/editar.php?id=' . $billing->id;
    ?>
" >
                                <?php 
    echo str_pad($billing->id, 5, '0', STR_PAD_LEFT);
    ?>
                            </a>
                        </td>
                        <td >
                            <a href="<?php 
    echo 'Frontend/' . $currentDir . '/editar.php?id=' . $billing->id;
    ?>
" >
                                <?php 
    $clientName = new Text(BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $mailing->businessPartnerCode));
    echo $clientName->Truncate(35);
    ?>
                            </a>
                        </td>
                        <td>
                            <?php 
    if ($mailing->contrato_id == 0) {
        echo 'Agrupar equipmts. do cliente';
    } else {
        $contract = $contractDAO->RetrieveRecord($mailing->contrato_id);
        $numero = str_pad($contract->numero, 5, '0', STR_PAD_LEFT);
        $status = ContractDAO::GetStatusAsText($contract->status);
        echo $numero . '(' . $status . ')';
    }
    ?>
$dataConnector->OpenConnection();
if ($dataConnector->mysqlConnection == null || $dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
// Cria os objetos de mapeamento objeto-relacional
$serviceCallDAO = new ServiceCallDAO($dataConnector->mysqlConnection);
$serviceCallDAO->showErrors = 1;
$equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
$equipmentDAO->showErrors = 1;
// Busca os dados do chamado
$serviceCall = $serviceCallDAO->RetrieveRecord($serviceCallId);
// Recupera dados do cartão de equipamento
$equipment = $equipmentDAO->RetrieveRecord($serviceCall->codigoCartaoEquipamento);
// Busca os dados do cliente
$clientName = BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $serviceCall->businessPartnerCode);
?>

    <script type='text/javascript'>
        $(document).ready(function() {
            <?php 
if (isset($sendToPrinter)) {
    echo 'window.print();';
}
?>
        });
    </script>

    <div style="width:99%;height:99%; margin-top:12px; margin-left:auto; margin-right:auto; border:1px solid black;" id="pageBorder" >
        <div style="width:96%; margin-top:12px; margin-left:auto; margin-right:auto; border:1px solid black;" >
            <img src="http://www.datacount.com.br/Datacount/images/logo.png" alt="Datacopy Trade" style="width:150px; height:50px; margin-top:10px; margin-left: 10px; margin-right: 10px; float:left;" />
function BuildReportTable($startColumn, $startRow)
{
    global $root;
    global $dataConnector;
    global $objPhpExcel;
    global $billingItemArray;
    $businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
    $businessPartnerDAO->showErrors = 1;
    $industryDAO = new IndustryDAO($dataConnector->sqlserverConnection);
    $industryDAO->showErrors = 1;
    $equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
    $equipmentDAO->showErrors = 1;
    $equipmentModelDAO = new EquipmentModelDAO($dataConnector->mysqlConnection);
    $equipmentModelDAO->showErrors = 1;
    $manufacturerDAO = new ManufacturerDAO($dataConnector->sqlserverConnection);
    $manufacturerDAO->showErrors = 1;
    $contractDAO = new ContractDAO($dataConnector->mysqlConnection);
    $contractDAO->showErrors = 1;
    $inventoryItemDAO = new InventoryItemDAO($dataConnector->sqlserverConnection);
    $inventoryItemDAO->showErrors = 1;
    $counterDAO = new CounterDAO($dataConnector->mysqlConnection);
    $counterDAO->showErrors = 1;
    $salesPersonDAO = new SalesPersonDAO($dataConnector->sqlserverConnection);
    $salesPersonDAO->showErrors = 1;
    // Busca os segmentos/ramos de atividade cadastrados no sistema
    $industryArray = array(0 => "");
    $tempArray = $industryDAO->RetrieveRecordArray();
    foreach ($tempArray as $industry) {
        $industryArray[$industry->id] = $industry->name;
    }
    // Busca os fabricantes cadastrados no sistema
    $manufacturerArray = array(0 => "");
    $tempArray = $manufacturerDAO->RetrieveRecordArray();
    foreach ($tempArray as $manufacturer) {
        $manufacturerArray[$manufacturer->FirmCode] = $manufacturer->FirmName;
    }
    // Busca os modelos de equipamento cadastrados no sistema
    $modelArray = array(0 => "");
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray();
    foreach ($equipmentModelArray as $modelDTO) {
        $modelArray[$modelDTO->id] = $modelDTO->modelo;
    }
    // Cria um array para as estatísticas dos equipamentos (por modelo)
    $statsArray = array();
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray("id > 0 ORDER BY fabricante, modelo");
    foreach ($equipmentModelArray as $modelDTO) {
        $statsArray[$modelDTO->id] = new EquipmentModelStats($modelDTO->id, $modelDTO->modelo, $modelDTO->fabricante);
    }
    // Cria um array para as receitas de cada equipamento
    $equipRevenueArray = array();
    // Cria um array para as receitas provenientes de cada cliente
    $customerRevenueArray = array();
    $associativeList = array(0 => "");
    foreach ($equipmentModelArray as $model) {
        $associativeList[$model->id] = $manufacturerArray[$model->fabricante];
    }
    // Busca os contadores cadastrados no sistema
    $retrievedArray = $counterDAO->RetrieveRecordArray();
    $counterArray = array();
    foreach ($retrievedArray as $counter) {
        $counterArray[$counter->id] = $counter->nome;
    }
    // Busca os vendedores cadastrados no sistema
    $retrievedArray = $salesPersonDAO->RetrieveRecordArray();
    $salesPersonArray = array();
    foreach ($retrievedArray as $salesPersonDTO) {
        $salesPersonArray[$salesPersonDTO->slpCode] = $salesPersonDTO->slpName;
    }
    // Define o titulo da tabela
    $currentRow = $startRow;
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $startRow, 'SÍNTESE POR EQUIPAMENTO');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $startRow . ':' . $startColumn . $startRow)->applyFromArray($styleArray);
    // Cria o cabeçalho da tabela
    $colNum = ord($startColumn) - 65;
    // startColumn é uma letra no intervalo A-Z
    $headers = array('Cliente', 'Segmento', 'Modelo', 'Fabricante', 'Série Fabricante', 'Nosso Núm. Série', 'Obs. Item', 'Data Instalação', 'Inicio Atendimento', 'Fim Atendimento', 'Parcela Atual', 'Vendedor', 'Medidor', 'Data Leitura', 'Medição Final', 'Medição Inicial', 'Ajuste Medição(Acrésc/Desc)', 'Consumo', 'Franquia', 'Excedente (Págs.)', 'Tarifa sobre exced.', 'Valor Fixo (R$)', 'Valor Variável (R$)', 'Acrésc/Desc (R$)', 'Valor Total (R$)', 'Custo Aquisição', 'Vida Útil', 'Custo Pág. do Equip.', 'Custo Pág. Peças/Mat.', 'Custo Pág. Total', 'Custo/Receita', 'Despesas');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(GetNameFromNumber($colNum + $offset))->setWidth(30);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Gera as linhas da tabela
    $totalFixo = 0;
    $totalVariavel = 0;
    $totalAcrescDesc = 0;
    $grandTotal = 0;
    foreach ($billingItemArray as $billingItem) {
        $equipment = $equipmentDAO->RetrieveRecord($billingItem->codigoCartaoEquipamento);
        $businessPartner = $businessPartnerDAO->RetrieveRecord($equipment->customer);
        $contractCoveragePeriod = ContractDAO::GetContractCoveragePeriod($dataConnector->mysqlConnection, $billingItem->contrato_id);
        $installationDate = empty($equipment->installationDate) ? '' : $equipment->installationDate->format('d/m/Y');
        $inicioAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["inicioAtendimento"] : '';
        $fimAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["fimAtendimento"] : '';
        $parcelaAtual = isset($contractCoveragePeriod) ? $contractCoveragePeriod["parcelaAtual"] : '';
        $receitaTotal = $billingItem->total + $billingItem->acrescimoDesconto;
        $inventoryItem = $inventoryItemDAO->RetrieveRecord($equipment->itemCode);
        $obsItem = $inventoryItem->userText;
        $custoAquisicao = $inventoryItem->avgPrice;
        $custoPagPecas = $inventoryItem->expenses;
        $vidaUtil = $inventoryItem->durability;
        if (empty($vidaUtil)) {
            $custoPagEquip = 0;
            $custoTotal = 0;
            $custoSobreReceita = 0;
        } else {
            $custoPagEquip = $custoAquisicao / $vidaUtil * 1.4;
            $custoTotal = ($custoPagEquip + $custoPagPecas) * $billingItem->consumo;
            $custoSobreReceita = 0;
            if ($receitaTotal != 0) {
                $custoSobreReceita = $custoTotal / $receitaTotal;
            }
        }
        // Busca os dados do vendedor
        $salesPersonCode = $equipment->salesPerson;
        if (empty($salesPersonCode)) {
            $salesPersonCode = -1;
        }
        $salesPersonName = $salesPersonArray[$salesPersonCode];
        // Busca os dados do segmento/ramo de atividade
        $industryCode = $businessPartner->industry;
        if (empty($industryCode)) {
            $industryCode = 0;
        }
        $industryName = $industryArray[$industryCode];
        // Busca o modelo e fabricante do equipamento
        $modelName = "";
        if (array_key_exists($equipment->model, $modelArray)) {
            $modelName = $modelArray[$equipment->model];
        }
        $manufacturerName = "";
        if (array_key_exists($equipment->model, $modelArray)) {
            $manufacturerName = $associativeList[$equipment->model];
        }
        if (!array_key_exists($equipment->manufacturerSN, $equipRevenueArray)) {
            $equipRevenueArray[$equipment->manufacturerSN] = new EquipmentRevenue($equipment->manufacturerSN, $equipment->model, $modelName, $manufacturerName, 0);
        }
        $equipRevenue = $equipRevenueArray[$equipment->manufacturerSN];
        $equipRevenue->revenue += $receitaTotal;
        if (!array_key_exists($equipment->customer, $customerRevenueArray)) {
            $customerRevenueArray[$equipment->customer] = new CustomerRevenue($equipment->customer, 0);
        }
        $customerRevenue = $customerRevenueArray[$equipment->customer];
        $customerRevenue->revenue += $receitaTotal;
        $row = array();
        $row[0] = $businessPartner->cardName . ' (' . $businessPartner->cardCode . ')';
        $row[1] = $industryName;
        $row[2] = $modelName;
        $row[3] = $manufacturerName;
        $row[4] = $equipment->manufacturerSN;
        $row[5] = $equipment->internalSN;
        $row[6] = $obsItem;
        $row[7] = $installationDate;
        $row[8] = $inicioAtendimento;
        $row[9] = $fimAtendimento;
        $row[10] = $parcelaAtual;
        $row[11] = $salesPersonName;
        $row[12] = $counterArray[$billingItem->counterId];
        // Recupera o nome do medidor/contador
        $row[13] = $billingItem->dataLeitura;
        $row[14] = $billingItem->medicaoFinal;
        $row[15] = $billingItem->medicaoInicial;
        $row[16] = $billingItem->ajuste;
        $row[17] = $billingItem->consumo;
        $row[18] = $billingItem->franquia;
        $row[19] = $billingItem->excedente;
        $row[20] = formatDecimal($billingItem->tarifaSobreExcedente, null);
        $row[21] = formatBrCurrency($billingItem->fixo, 2);
        $row[22] = formatBrCurrency($billingItem->variavel, 2);
        $row[23] = formatBrCurrency($billingItem->acrescimoDesconto, 2);
        $row[24] = formatBrCurrency($receitaTotal, 2);
        $row[25] = formatBrCurrency($custoAquisicao, 2);
        $row[26] = $vidaUtil;
        $row[27] = formatDecimal($custoPagEquip, 6);
        $row[28] = formatDecimal($custoPagPecas, 6);
        $row[29] = formatBrCurrency($custoTotal, 2);
        $row[30] = formatDecimal($custoSobreReceita, 6);
        $row[31] = 'http://datadb/contratos/AjaxCalls/GetEquipmentExpenses.php?equipmentCode=' . $equipment->insID . '&billingId=' . $billingItem->codigoFaturamento . '&showDetails=true';
        $currentRow++;
        InsereLinhaPlanilha($currentRow, $startColumn, $row);
        $totalFixo += $billingItem->fixo;
        // Soma os valores fixos dos equipamentos
        $totalVariavel += $billingItem->variavel;
        // Soma os valores variáveis dos equipamentos
        $totalAcrescDesc += $billingItem->acrescimoDesconto;
        // Soma os acrescimos descontos dos equipamentos
        $grandTotal += $receitaTotal;
        // Soma a receita total dos equipamentos ( fixo mais variável )
    }
    $currentRow++;
    $summary = array('Quant. Clientes: ' . sizeof($customerRevenueArray), '', '', '', 'Quant. Equipamentos: ' . sizeof($equipRevenueArray), '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Total Fixo: ' . number_format($totalFixo, 2, ',', '.'), 'Total Variável: ' . number_format($totalVariavel, 2, ',', '.'), 'Total Acrésc/Desc: ' . number_format($totalAcrescDesc, 2, ',', '.'), 'Total Receita: ' . number_format($grandTotal, 2, ',', '.'), '', '', '', '', '', '', '');
    InsereLinhaPlanilha($currentRow, $startColumn, $summary, '80BB80FF', 32, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    foreach ($equipRevenueArray as $equipRevenue) {
        if (array_key_exists($equipRevenue->modelId, $statsArray)) {
            $modelStats = $statsArray[$equipRevenue->modelId];
            $modelStats->revenue += $equipRevenue->revenue;
            $modelStats->equipmentCount += 1;
        }
    }
    $currentRow += 3;
    // pula 3 linhas
    $startColumn = 'G';
    // fixa o quadro resumo na setima coluna da planilha
    // Define o titulo do quadro resumo
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $currentRow, 'QUADRO RESUMO');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $currentRow . ':' . $startColumn . $currentRow)->applyFromArray($styleArray);
    // Cria o cabeçalho do quadro resumo
    $colNum = ord($startColumn);
    $headers = array('Modelo', 'Fabricante', 'Quantidade', 'Receita');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(chr($colNum + $offset))->setWidth(25);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $valorPrevio = "";
    $equipCount = 0;
    $somaReceita = 0;
    foreach ($statsArray as $equipmentModelStats) {
        if ($equipmentModelStats->equipmentCount > 0) {
            $manufacturerName = $manufacturerArray[$equipmentModelStats->fabricante];
            $valorAtual = $manufacturerName;
            if ($valorPrevio != $valorAtual) {
                if (!empty($valorPrevio)) {
                    $subTotal = array('', '', $equipCount, number_format($somaReceita, 2, ',', '.'));
                    $currentRow++;
                    InsereLinhaPlanilha($currentRow, $startColumn, $subTotal, '80AAFFFF', 20, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $equipCount = 0;
                    $somaReceita = 0;
                }
                $valorPrevio = $valorAtual;
            }
            $currentRow++;
            $row = array();
            $row[0] = $equipmentModelStats->model;
            $row[1] = $manufacturerName;
            $row[2] = $equipmentModelStats->equipmentCount;
            $row[3] = number_format($equipmentModelStats->revenue, 2, ',', '.');
            InsereLinhaPlanilha($currentRow, $startColumn, $row);
            $equipCount = $equipCount + $equipmentModelStats->equipmentCount;
            $somaReceita = $somaReceita + $equipmentModelStats->revenue;
        }
    }
    $subTotal = array('', '', $equipCount, number_format($somaReceita, 2, ',', '.'));
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $subTotal, '80AAFFFF', 20, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
}
function BuildReportTable($startColumn, $startRow)
{
    global $dataConnector;
    global $objPhpExcel;
    global $contractArray;
    global $model;
    global $searchMethod;
    $contractDAO = new ContractDAO($dataConnector->mysqlConnection);
    $contractDAO->showErrors = 1;
    $subContractDAO = new SubContractDAO($dataConnector->mysqlConnection);
    $subContractDAO->showErrors = 1;
    $contractItemDAO = new ContractItemDAO($dataConnector->mysqlConnection);
    $contractItemDAO->showErrors = 1;
    $equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
    $equipmentDAO->showErrors = 1;
    $equipmentModelDAO = new EquipmentModelDAO($dataConnector->mysqlConnection);
    $equipmentModelDAO->showErrors = 1;
    $salesPersonDAO = new SalesPersonDAO($dataConnector->sqlserverConnection);
    $salesPersonDAO->showErrors = 1;
    // Define o titulo da tabela
    $currentRow = $startRow;
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $startRow, 'CONTRATOS');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $startRow . ':' . $startColumn . $startRow)->applyFromArray($styleArray);
    // Cria o cabeçalho da tabela
    $colNum = ord($startColumn);
    $headers = array('Número', 'Cliente', 'Detalhes', 'Assinatura', 'Encerramento', 'Inicio do Atendimento', 'Fim do Atendimento', 'Parcela', 'Vendedor', 'Status', 'Global(S OU N)');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(chr($colNum + $offset))->setWidth(25);
        $offset++;
    }
    $activeSheet->getColumnDimension(chr($colNum + 1))->setWidth(50);
    $activeSheet->getColumnDimension(chr($colNum + 2))->setWidth(50);
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Busca os modelos de equipamento cadastrados no sistema
    $modelArray = array(0 => "");
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray();
    foreach ($equipmentModelArray as $modelDTO) {
        $modelArray[$modelDTO->id] = $modelDTO->modelo;
    }
    // Busca os vendedores cadastrados no sistema
    $retrievedArray = $salesPersonDAO->RetrieveRecordArray();
    $salesPersonArray = array();
    foreach ($retrievedArray as $salesPersonDTO) {
        $salesPersonArray[$salesPersonDTO->slpCode] = $salesPersonDTO->slpName;
    }
    // Gera as linhas da tabela
    $identifierArray = array();
    $LFCR = chr(10) . chr(13);
    foreach ($contractArray as $contract) {
        if (array_key_exists($contract->id, $identifierArray)) {
            continue;
        }
        // contrato repetido, pula para o próximo registro
        $clientName = BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $contract->pn);
        $salesPersonName = $salesPersonArray[$contract->vendedor];
        $details = "";
        $subContractArray = $subContractDAO->RetrieveRecordArray("contrato_id=" . $contract->id);
        foreach ($subContractArray as $subContract) {
            if (!empty($details)) {
                $details = $details . $LFCR;
            }
            $details = $details . $subContract->siglaTipoContrato;
            $itemArray = $contractItemDAO->RetrieveRecordArray("subContrato_id=" . $subContract->id);
            foreach ($itemArray as $contractItem) {
                $equipment = $equipmentDAO->RetrieveRecord($contractItem->codigoCartaoEquipamento);
                $installationDate = empty($equipment->installationDate) ? '' : $equipment->installationDate->format('d/m/Y');
                // filtra apenas os items ativos e emprestados
                if ($equipment->status == 'A' || $equipment->status == 'L') {
                    if (!empty($details)) {
                        $details = $details . $LFCR;
                    }
                    $equipmentModel = "";
                    if (array_key_exists($equipment->model, $modelArray)) {
                        $equipmentModel = $modelArray[$equipment->model];
                    }
                    $details = $details . $equipmentModel . ' Série ' . $equipment->manufacturerSN . ' Data Instalação ' . $installationDate;
                }
            }
        }
        if ($searchMethod == 1 || $searchMethod == 2) {
            if (!empty($model)) {
                $modelMatched = false;
                if (strpos($details, $model)) {
                    $modelMatched = true;
                }
                if (!$modelMatched) {
                    continue;
                }
            }
        }
        $currentRow++;
        $row = array();
        $row[0] = str_pad($contract->numero, 5, '0', STR_PAD_LEFT);
        $row[1] = $clientName;
        $row[2] = $details;
        $row[3] = $contract->dataAssinatura;
        $row[4] = $contract->dataEncerramento;
        $row[5] = $contract->inicioAtendimento;
        $row[6] = $contract->fimAtendimento;
        $row[7] = $contract->parcelaAtual . '/' . $contract->quantidadeParcelas;
        $row[8] = $salesPersonName;
        $row[9] = $contractDAO->GetStatusAsText($contract->status);
        $row[10] = $contract->global == 0 ? 'N' : 'S';
        InsereLinhaPlanilha($currentRow, $startColumn, $row);
        $identifierArray[$contract->id] = $contract->numero;
    }
}
include_once "../ClassLibrary/DataConnector.php";
include_once "../DataAccessObjects/BusinessPartnerDAO.php";
include_once "../DataTransferObjects/BusinessPartnerDTO.php";
include_once "../DataAccessObjects/IndustryDAO.php";
include_once "../DataTransferObjects/IndustryDTO.php";
include_once "../DataAccessObjects/ContactPersonDAO.php";
include_once "../DataTransferObjects/ContactPersonDTO.php";
// Abre a conexao com o banco de dados
$dataConnector = new DataConnector('sqlServer');
$dataConnector->OpenConnection();
if ($dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
// Cria o objeto de mapeamento objeto-relacional
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
$industryDAO = new IndustryDAO($dataConnector->sqlserverConnection);
$industryDAO->showErrors = 1;
$contactPersonDAO = new ContactPersonDAO($dataConnector->sqlserverConnection);
$contactPersonDAO->showErrors = 1;
// Busca os dados do parceiro de negócios
$businessPartner = $businessPartnerDAO->RetrieveRecord($businessPartnerCode);
if ($businessPartner == null) {
    echo '<h3>Erro ao localizar parceiro de negócios.</h3>';
    exit;
}
$industryCode = $businessPartner->industry;
if (empty($industryCode)) {
    $industryCode = 0;
}
    echo 'Falha no envio. A extensão Open SSL não está habilitada no PHP.';
    exit;
}
error_reporting(E_ALL);
// manage php errors
$from = trim($user);
$to = trim($recipients);
$toArray = explode(",", $recipients);
$subj = 'Solicitação de peças para equipamento';
$content = '<br/><h1>SOLICITAÇÃO DE PEÇAS</h1>';
$content = $content . '<div style="clear:both;"><br/><br/></div>';
$content = $content . 'Número da solicitação: ' . str_pad($partRequestId, 5, '0', STR_PAD_LEFT) . '<br/>';
$content = $content . 'Chamado de Serviço: ' . str_pad($serviceCall->id, 5, '0', STR_PAD_LEFT) . '<br/>';
$content = $content . 'Data do Chamado: ' . $serviceCall->dataAbertura . '<br/>';
$content = $content . 'Técnico: ' . $technicianName . '<br/>';
$content = $content . 'Cliente: ' . BusinessPartnerDAO::GetClientName($dataConnector->sqlserverConnection, $serviceCall->businessPartnerCode) . '<br/>';
$content = $content . 'Equipamento: ' . $shortDescription . '<br/>';
$content = $content . 'Modelo: ' . $model . '<br/><br/>';
$content = $content . '<h3>Itens</h3> <div style="border:1px solid black; min-height:100px;" >' . $pecas . '</div><br/><br/>';
$content = $content . '<h3>Revisões</h3><br/>' . $revisions;
$message = MIME::message($content, 'text/html', null, 'UTF-8');
// compose message in MIME format
$mess = MIME::compose(null, $message);
// standard mail message RFC2822
$body = 'From: ' . $from . "\r\n" . 'To: ' . $to . "\r\n" . 'Subject: ' . $subj . "\r\n" . $mess['header'] . "\r\n\r\n" . $mess['content'];
$conn = SMTP::connect($host, $port, $user, $pass, $vssl) or die('Falha na conexão - ' . print_r($_RESULT));
$sent = SMTP::send($conn, array($toArray[0]), $body, $from);
if ($sent) {
    echo 'Email enviado com sucesso!';
} else {
    echo 'Falha no envio - ' . print_r($_RESULT);
Esempio n. 14
0
if (isset($_REQUEST["mailingId"]) && $_REQUEST["mailingId"] != 0) {
    $mailingId = $_REQUEST["mailingId"];
}
// Abre a conexao com o banco de dados
$dataConnector = new DataConnector('both');
$dataConnector->OpenConnection();
if ($dataConnector->mysqlConnection == null || $dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
// Cria o objeto de mapeamento objeto-relacional
$billingDAO = new BillingDAO($dataConnector->mysqlConnection);
$billingDAO->showErrors = 1;
$mailingDAO = new MailingDAO($dataConnector->mysqlConnection);
$mailingDAO->showErrors = 1;
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
$contractDAO = new ContractDAO($dataConnector->mysqlConnection);
$contractDAO->showErrors = 1;
// Recupera o mailing correspondente ao faturamento
$mailing = $mailingDAO->RetrieveRecord($mailingId);
// Recupera o cliente
$businessPartner = $businessPartnerDAO->RetrieveRecord($mailing->businessPartnerCode);
// Recupera o contrato caso o mailing faça referencia a um
if ($mailing->contrato_id != 0) {
    $contract = $contractDAO->RetrieveRecord($mailing->contrato_id);
}
// Calcula o valor de implantação a ser cobrado/parcelado
$acrescimoDesconto = "";
$observacoes = "";
if (isset($contract)) {
Esempio n. 15
0
// Abre a conexao com o banco de dados
$dataConnector = new DataConnector('both');
$dataConnector->OpenConnection();
if ($dataConnector->mysqlConnection == null || $dataConnector->sqlserverConnection == null) {
    echo 'Não foi possível se connectar ao bando de dados!';
    exit;
}
$nivelAutorizacao = GetAuthorizationLevel($dataConnector->mysqlConnection, $functionalities["gerenciamentoChamados"]);
if ($nivelAutorizacao <= 1) {
    DisplayNotAuthorizedWarning();
    exit;
}
// Cria os objetos de mapeamento objeto-relacional
$serviceCallDAO = new ServiceCallDAO($dataConnector->mysqlConnection);
$serviceCallDAO->showErrors = 1;
$businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
$businessPartnerDAO->showErrors = 1;
// Traz a lista de chamados cadastrados
$maxRecordCount = ConfigDAO::GetConfigurationParam($dataConnector->mysqlConnection, "limiteListaChamados");
$recCount = $serviceCallDAO->GetRecordCount(null);
$boundary = "";
if ($recCount > $maxRecordCount && empty($equipmentCode)) {
    $boundary = "LIMIT " . ($recCount - $maxRecordCount) . ", " . $recCount;
}
$filter = "id > 0 ORDER BY id";
if ($equipmentCode != 0) {
    $filter = "cartaoEquipamento = " . $equipmentCode;
}
$serviceCallArray = $serviceCallDAO->RetrieveRecordArray($filter . ' ' . $boundary);
$extraInfo = "( últimos " . $maxRecordCount . " )";
if (!empty($equipmentCode)) {
function BuildReportTable($startColumn, $startRow)
{
    global $dataConnector;
    global $objPhpExcel;
    global $invoicePaymentArray;
    $salesPersonDAO = new SalesPersonDAO($dataConnector->sqlserverConnection);
    $salesPersonDAO->showErrors = 1;
    $equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
    $equipmentDAO->showErrors = 1;
    $businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
    $businessPartnerDAO->showErrors = 1;
    $industryDAO = new IndustryDAO($dataConnector->sqlserverConnection);
    $industryDAO->showErrors = 1;
    $contractDAO = new ContractDAO($dataConnector->mysqlConnection);
    $contractDAO->showErrors = 1;
    $billingDAO = new BillingDAO($dataConnector->mysqlConnection);
    $billingDAO->showErrors = 1;
    $billingItemDAO = new BillingItemDAO($dataConnector->mysqlConnection);
    $billingItemDAO->showErrors = 1;
    $commissionPerSignatureDAO = new CommissionPerSignatureDAO($dataConnector->mysqlConnection);
    $commissionPerSignatureDAO->showErrors = 1;
    // Define o titulo da tabela
    $currentRow = $startRow;
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $startRow, 'PAGAMENTOS');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $startRow . ':' . $startColumn . $startRow)->applyFromArray($styleArray);
    // Cria o cabeçalho da tabela
    $colNum = ord($startColumn);
    $headers = array('Nº NF', 'Tipo', 'Cliente', 'Segmento', 'Nº Boleto', 'Valor Cobrado', 'Valor Recebido', 'Data Pagamento', 'Demonstrativo Fat.', 'Descritivo Faturamento');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(chr($colNum + $offset))->setWidth(25);
        $offset++;
    }
    $activeSheet->getColumnDimension(chr($colNum + $offset - 1))->setWidth(50);
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Cria um array para as estatísticas dos vendedores
    $statsArray = array();
    $salesPersonArray = $salesPersonDAO->RetrieveRecordArray();
    foreach ($salesPersonArray as $salesPerson) {
        $statsArray[$salesPerson->slpCode] = new SalesPerson($salesPerson->slpCode, $salesPerson->slpName);
    }
    // Cria um array para as regras de comissão
    $rulesArray = array(0 => new CommissionRule(0, "", "", 0));
    $commissionRuleArray = $commissionPerSignatureDAO->RetrieveRecordArray();
    foreach ($commissionRuleArray as $commissionRuleDTO) {
        $rulesArray[$commissionRuleDTO->id] = new CommissionRule($commissionRuleDTO->segmento, $commissionRuleDTO->dataAssinaturaDe, $commissionRuleDTO->dataAssinaturaAte, $commissionRuleDTO->comissao);
    }
    // Busca os segmentos/ramos de atividade cadastrados no sistema
    $industryArray = array(-1 => "- Nenhum Segmento -");
    $tempArray = $industryDAO->RetrieveRecordArray();
    foreach ($tempArray as $industry) {
        $industryArray[$industry->id] = $industry->name;
    }
    foreach ($invoicePaymentArray as $payment) {
        $billingDescription = "";
        $billing = new BillingDTO();
        if ($payment->demFaturamento >= 1) {
            $billing = $billingDAO->RetrieveRecord($payment->demFaturamento);
            if (!isset($billing)) {
                $billing = new BillingDTO();
            }
        }
        $industry = -1;
        // Busca os itens de faturamento
        $billingItemArray = $billingItemDAO->RetrieveRecordArray("codigoFaturamento = '" . $billing->id . "'");
        $quantidadeItens = sizeof($billingItemArray);
        if ($quantidadeItens < 1) {
            $quantidadeItens = 1;
        }
        $multaRecisoria = $billing->multaRecisoria / $quantidadeItens;
        foreach ($billingItemArray as $billingItem) {
            $equipment = $equipmentDAO->RetrieveRecord($billingItem->codigoCartaoEquipamento);
            $businessPartner = $businessPartnerDAO->RetrieveRecord($payment->cardCode);
            if (isset($businessPartner->industry)) {
                $industry = $businessPartner->industry;
            }
            if ($equipment->salesPerson > 0) {
                $contract = $contractDAO->RetrieveRecord($billingItem->contrato_id);
                $salesPersonStats = $statsArray[$equipment->salesPerson];
                if (!isset($salesPersonStats->statistics)) {
                    $salesPersonStats->statistics = array();
                }
                $ruleKey = 0;
                $comissao = 0;
                $commissionRuleArray = $commissionPerSignatureDAO->RetrieveRecordArray("(segmento = 0 OR segmento = " . $industry . ") AND dataAssinaturaDe <= '" . $contract->dataAssinatura . "' AND dataAssinaturaAte >= '" . $contract->dataAssinatura . "' ORDER BY segmento DESC, comissao DESC");
                if (sizeof($commissionRuleArray) > 0) {
                    $rule = $commissionRuleArray[0];
                    $ruleKey = $rule->id;
                    $comissao = $rule->comissao;
                }
                if (!array_key_exists($ruleKey, $salesPersonStats->statistics)) {
                    $salesPersonStats->statistics[$ruleKey] = new SalesPersonStats($ruleKey);
                }
                $ruleStats = $salesPersonStats->statistics[$ruleKey];
                $ruleStats->comissionRate = $comissao;
                $ruleStats->revenue += $billingItem->total + $billingItem->acrescimoDesconto - $multaRecisoria;
                if (!IsContractAdded($contract, $ruleStats)) {
                    $ruleStats->contractCount++;
                    if (!isset($ruleStats->contractArray)) {
                        $ruleStats->contractArray = array();
                    }
                    $ruleStats->contractArray[$contract->id] = $contract->id;
                }
            }
            $LFCR = chr(10) . chr(13);
            $salesPersonName = SalesPersonDAO::GetSalesPersonName($dataConnector->sqlserverConnection, $equipment->salesPerson);
            $billingDescription .= $salesPersonName . ' Serial ' . $equipment->manufacturerSN . ' R$ ' . $billingItem->total . $LFCR;
        }
        $currentRow++;
        $row = array();
        $row[0] = $payment->serial;
        $row[1] = GetInvoiceTypeAsText($payment->tipo);
        $row[2] = $payment->cardName;
        $row[3] = $industryArray[$industry];
        $row[4] = GetBOENumber($payment);
        $row[5] = GetDocTotal($payment);
        $row[6] = GetReceivedAmount($payment);
        $row[7] = empty($payment->date) ? '' : $payment->date->format('d/m/Y');
        $row[8] = empty($billing->id) ? ' - ' : str_pad($billing->id, 5, '0', STR_PAD_LEFT);
        $row[9] = $billingDescription;
        InsereLinhaPlanilha($currentRow, $startColumn, $row);
    }
    $currentRow += 3;
    // pula 3 linhas
    // Define o titulo do quadro resumo
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $currentRow, 'COMISSÕES');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $currentRow . ':' . $startColumn . $currentRow)->applyFromArray($styleArray);
    // Cria o cabeçalho do quadro resumo
    $colNum = ord($startColumn);
    $headers = array('Vendedor', 'Segmento', 'Data de Assinatura', 'Quantidade de Contratos', 'Faturamento (R$)', 'Comissão (%)', 'Comissão (R$)');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(chr($colNum + $offset))->setWidth(25);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    foreach ($statsArray as $salesPersonStats) {
        if (isset($salesPersonStats->statistics)) {
            $statistics = $salesPersonStats->statistics;
            foreach ($statistics as $stat) {
                $commissionRule = $rulesArray[$stat->index];
                $industryName = "Todos";
                if ($commissionRule->segmento > 0) {
                    $industryName = $industryArray[$commissionRule->segmento];
                }
                $period = "";
                if ($commissionRule->comissao > 0) {
                    $period = $commissionRule->dataAssinaturaDe . ' até ' . $commissionRule->dataAssinaturaAte;
                }
                $comissionPercentage = $stat->comissionRate;
                $comissionValue = $stat->comissionRate / 100 * $stat->revenue;
                $currentRow++;
                $row = array();
                $row[0] = $salesPersonStats->name;
                $row[1] = $industryName;
                $row[2] = $period;
                $row[3] = $stat->contractCount;
                $row[4] = number_format($stat->revenue, 2, ',', '.');
                $row[5] = $comissionPercentage;
                $row[6] = number_format($comissionValue, 2, ',', '.');
                InsereLinhaPlanilha($currentRow, $startColumn, $row);
            }
        }
    }
}