KoolReport's Forum

Official Support Area, Q&As, Discussions, Suggestions and Bug reports.
Forum's Guidelines

Doubt AccumulativeColumn #604

Open Hermílio opened this topic on on Jan 22, 2019 - 6 comments

Hermílio commented on Jan 22, 2019

I want to make the field total "margin" so I used the AccumulativeColumn but my result is coming empty

->pipe(new CalculatedColumn(array(

            "totalMargem"=>function($data){
                if(!empty($data["totalVenda"])){
                    $data["totalMargem"] = (($data["totalVenda"] - $data["totalCusto"])/$data["totalVenda"])*100;

                }
     
                return   $data["totalMargem"];
            }
        )))
        ->pipe(new AccumulativeColumn(array(
            "Total"=>"totalMargem"
        )))

I put an alert to see if the data was passing

Thank you very much in advance

David Winterburn commented on Jan 23, 2019

Hi Hermílio,

Would you please post your full php code including the Pivot process for us to understand your question? Thanks!

Hermílio commented on Jan 23, 2019

vendasAnual.php <?php

require_once BASE_EXTRAS . "/koolreport/autoload.php";

use \koolreport\processes\Filter; use \koolreport\processes\TimeBucket; use \koolreport\processes\ColumnMeta; use \koolreport\processes\CalculatedColumn; use \koolreport\processes\AccumulativeColumn; use \koolreport\processes\AggregatedColumn; use \koolreport\processes\RemoveColumn; use \koolreport\processes\Map; use \koolreport\pivot\processes\Pivot; use \koolreport\processes\Group; use \koolreport\processes\ValueMap; use \koolreport\processes\Sort; use \koolreport\processes\Limit; use \koolreport\inputs\GETBinding;

/* Filtro Data movimentacaodatadata_inicio dataInicial datafinal */ $array = $this->input->get();

$datIni = $array["movimentacao__data__data_inicio"][0]; $datFim = $array["movimentacao__data__data_inicio"][1];

/* Partição dataInicial datafinal */ $util = $this->call("util", "util", "getInstance"); $sqlParticao = $util->getSqlParticao($datIni, $datFim, false); class vendasAnual {

public function __construct($params = array())
{

    parent::__construct();
}

}

set_time_limit(0);

class vendasCore extends \koolreport\KoolReport {

public function settings()
{

    return array(
        "dataSources" => array(
            "vendasAnual" => array(
                "connectionString" => "mysql:host=localhost;dbname=Stage",
                "username" => "root",
                "password" => "a7v400mx",
                "charset" => "utf8"
            )
        ),
        "assets" => array(
            "path" => BASE_ARQUIVOS,
            "url" => PATH_ARQUIVOS_DIR
        )
    );
}

public function setup()
{
    $this->src('vendasAnual')
        ->query("SELECT 
        p.LevelDescription1, 
        p.LevelDescription2,
        p.LevelDescription3, 
        p.LevelDescription4,
        l.BriefDescription,
        m.LocalCode,
       
        COALESCE(SUM(TotalSaleValue), 0)   as 'totalVenda',
        COALESCE(SUM(ValueCMV), 0)   as 'totalCusto',
        month(m.dateMoviment) as mes, 
        SUM(TotalSaleAmount) as 'qtde',
       -- round(if((((sum(TotalSaleValue) - sum(ValueCMV))/sum(TotalSaleValue))*100) is null, 0, (((sum(TotalSaleValue) - sum(ValueCMV))/sum(TotalSaleValue))*100)),2) AS 'totalMargem',

        m.dateMoviment ,
        m.ProductCode ,
        COALESCE(estoque.totalEstoque, 0) as 'totalEstoque',
        0 as 'totalMargem',
        COALESCE(estoque.totalVendaEstoque, 0) as 'totalVendaEstoque',
        COALESCE(estoque.totalCustoEstoque, 0) as 'totalCustoEstoque'
        FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
        LEFT JOIN Stage.ProductDimension p
            ON p.ProductCode = m.ProductCode 
        LEFT JOIN  Stage.LocalDimension l
            ON l.LocalCode = m.LocalCode
        LEFT JOIN (SELECT      
            AmountStockTotal as 'totalEstoque',
            ValueStockTotal as 'totalVendaEstoque',
            CostStockTotal as 'totalCustoEstoque',
            m.ProductCode as 'ProductCodeEstoque'
            FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
            LEFT JOIN Stage.ProductDimension p
                ON p.ProductCode = m.ProductCode 
            LEFT JOIN  Stage.LocalDimension l
                ON l.LocalCode = m.LocalCode
            LEFT JOIN (
                    SELECT 
                        max(m.dateMoviment) as m,
                        m.ProductCode as id
                    FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
                    LEFT JOIN Stage.ProductDimension p
                        ON p.ProductCode = m.ProductCode 
                    LEFT JOIN  Stage.LocalDimension l
                        ON l.LocalCode = m.LocalCode
                    WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
                    GROUP BY l.BriefDescription
            ) ee ON ee.id = m.ProductCode 
            WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
            GROUP BY l.BriefDescription) estoque ON estoque.ProductCodeEstoque =  m.ProductCode  
     WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
     GROUP BY DATE_FORMAT(m.dateMoviment,'%m'),l.BriefDescription,p.LevelDescription1,p.LevelDescription2,p.LevelDescription3,p.LevelDescription4 ")
        ->params(array(
            ":dataIni" => $this->params["extraParams"]["movimentacao__data__data_inicio"][0],
            ":datafim" => $this->params["extraParams"]["movimentacao__data__data_inicio"][1]
        ))
      
      
        ->pipe(new ColumnMeta(array(
            "totalMargem"=>array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalVenda" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
           
            "totalCusto" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "qtde" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            
            "totalEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalVendaEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalCustoEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            )
        )))
        ->pipe(new TimeBucket(array(
            "dateMoviment" => "month"
        )))
        ->pipe(new Pivot(array(
            "dimensions" => array(
                "column" => "mes",
                // "row" => "BriefDescription,LevelDescription1,LevelDescription2,LevelDescription3,LevelDescription4"
                "row" => "BriefDescription"
            ),
            "aggregates" => array(
                "sum" => "totalVenda,totalCusto,qtde",
                "max" => "totalEstoque,totalVendaEstoque,totalCustoEstoque"
          
              
            )
        )))
     
        ->pipe(new CalculatedColumn(array(
            // "margem_percent"=>"(({totalVenda - sum}-{totalCusto - sum})/{totalVenda - sum})*100"
      "margem_percent"=>function($data){
          alert($data);
                 if(!empty($data["totalVenda - sum"])){
                  $data["totalMargem"] = (($data["totalVenda - sum"] - $data["totalCusto - sum"])/$data["totalVenda - sum"])*100;

                }
     
                 return   $data["totalMargem"];
            }
            
        )))

        
        
        ->pipe($this->dataStore('vendasAnual'));
}

} // renomeando arquivo que o gestor gera para o padrao do kool troca o .html pelo .view

$_POST = $_REQUEST; $retorno = rename($this->_VISUAL, str_replace(".html.php", ".view.php", $this->_VISUAL)); $arquivo_view = str_replace(".html", "", pathinfo($this->_VISUAL, PATHINFO_FILENAME)); $vendasCore = new vendasCore([

"extraParams" => [
    "data64" => base64_encode(json_encode([
        "action" => "relatorios/relatorio_gestor",
        "method" => "generic",

        "params" => [
            "report" => "Venda_anual",
            "movimentacao__data__data_inicio" => [$datIni, $datFim]

        ]
    ])),
    "movimentacao__data__data_inicio" => [$datIni, $datFim]
],
"part" => (string)$sqlParticao

]);

// exibe o relatórios passando qual view ira utlizar $vendasCore->run()->render($arquivo_view);

exit; vendasAnual.view.php <?php use \koolreport\pivot\widgets\PivotMatrix; use \koolreport\core\Utility; use \koolreport\processes\Filter; use \koolreport\processes\ColumnMeta; use \koolreport\pivot\processes\Pivot; use \koolreport\instant\Widget; use \koolreport\datasources\CSVDataSource;

?>

"pivotMatrix1", 'dataSource' => $this->dataStore('vendasAnual'), "measures" => array( // "totalVenda - sum", "margem_percent" ), 'rowSort' => array( // 'totalVenda - sum' => 'desc', 'margem_percent' => 'desc' ), 'columnCollapseLevels' => array(0), 'rowCollapseLevels' => array(0), 'width' => '100%', 'height' => '100%', 'headerMap' => function ($v, $f) { switch ($v) { case 'totalVenda - sum': return 'Total Vendas'; case 'totalCusto - sum': return 'Qtde Custo'; case 'qtde - sum': return 'Qtde'; case 'margem_percent': return 'Margem'; case 'totalEstoque - max': return 'Total Estoque'; case 'totalVendaEstoque - max': return 'Total Venda Estoque'; case 'totalCustoEstoque - max': return 'Total Custo Estoque'; case 'mes': return 'Mês'; case 'LevelDescription1': return 'Descrição 01'; case 'LevelDescription2': return 'Descrição 02'; case 'LevelDescription3': return 'Descrição 03'; case 'LevelDescription4': return 'Descrição 04'; case 'BriefDescription': return 'Lojas'; } $r = $v; $map = array( '1' => 'Jan', '2' => 'Fev', '3' => 'Mar', '4' => 'Abr', '5' => 'Mai', '6' => 'Jun', '7' => 'Jul', '8' => 'Ago', '9' => 'Set', '10' => 'Out', '11' => 'Nov', '12' => 'Dez', ); if ($f === 'mes') $r = $map[$v]; return $r; }, // 'totalName' => 'Total', 'waitingFields' => array( 'totalVenda - sum' => 'data', 'totalCusto - sum' => 'data', 'qtde - sum' => 'data', 'totalEstoque - max' => 'data', 'totalVendaEstoque - max' => 'data', 'totalCustoEstoque - max' => 'data', // 'totalMargem - max' => 'data', 'LevelDescription1' => 'label', 'LevelDescription2' => 'label', 'LevelDescription3' => 'label', 'LevelDescription4' => 'label' ), 'paging' => array(), "scope" => $this->params["extraParams"] )); ?>
David Winterburn commented on Jan 23, 2019

Hi Hermílio,

Please post php in the view file where you render PivotMatrix as well. Thanks!

Hermílio commented on Jan 23, 2019

Ok. vendasAnual.php

<?php

require_once BASE_EXTRAS . "/koolreport/autoload.php";

use \koolreport\processes\Filter; use \koolreport\processes\TimeBucket; use \koolreport\processes\ColumnMeta; use \koolreport\processes\CalculatedColumn; use \koolreport\processes\AccumulativeColumn; use \koolreport\processes\AggregatedColumn; use \koolreport\processes\RemoveColumn; use \koolreport\processes\Map; use \koolreport\pivot\processes\Pivot; use \koolreport\processes\Group; use \koolreport\processes\ValueMap; use \koolreport\processes\Sort; use \koolreport\processes\Limit; use \koolreport\inputs\GETBinding;

/* Filtro Data movimentacaodatadata_inicio dataInicial datafinal */ $array = $this->input->get();

$datIni = $array["movimentacao__data__data_inicio"][0]; $datFim = $array["movimentacao__data__data_inicio"][1];

/* Partição dataInicial datafinal */ $util = $this->call("util", "util", "getInstance"); $sqlParticao = $util->getSqlParticao($datIni, $datFim, false); class vendasAnual {

public function __construct($params = array())
{

    parent::__construct();
}

}

set_time_limit(0);

class vendasCore extends \koolreport\KoolReport {

public function settings()
{

    return array(
        "dataSources" => array(
            "vendasAnual" => array(
                "connectionString" => "mysql:host=localhost;dbname=Stage",
                "username" => "root",
                "password" => "a7v400mx",
                "charset" => "utf8"
            )
        ),
        "assets" => array(
            "path" => BASE_ARQUIVOS,
            "url" => PATH_ARQUIVOS_DIR
        )
    );
}

public function setup()
{
    $this->src('vendasAnual')
        ->query("SELECT 
        p.LevelDescription1, 
        p.LevelDescription2,
        p.LevelDescription3, 
        p.LevelDescription4,
        l.BriefDescription,
        m.LocalCode,
       
        COALESCE(SUM(TotalSaleValue), 0)   as 'totalVenda',
        COALESCE(SUM(ValueCMV), 0)   as 'totalCusto',
        month(m.dateMoviment) as mes, 
        SUM(TotalSaleAmount) as 'qtde',
       -- round(if((((sum(TotalSaleValue) - sum(ValueCMV))/sum(TotalSaleValue))*100) is null, 0, (((sum(TotalSaleValue) - sum(ValueCMV))/sum(TotalSaleValue))*100)),2) AS 'totalMargem',

        m.dateMoviment ,
        m.ProductCode ,
        COALESCE(estoque.totalEstoque, 0) as 'totalEstoque',
        0 as 'totalMargem',
        COALESCE(estoque.totalVendaEstoque, 0) as 'totalVendaEstoque',
        COALESCE(estoque.totalCustoEstoque, 0) as 'totalCustoEstoque'
        FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
        LEFT JOIN Stage.ProductDimension p
            ON p.ProductCode = m.ProductCode 
        LEFT JOIN  Stage.LocalDimension l
            ON l.LocalCode = m.LocalCode
        LEFT JOIN (SELECT      
            AmountStockTotal as 'totalEstoque',
            ValueStockTotal as 'totalVendaEstoque',
            CostStockTotal as 'totalCustoEstoque',
            m.ProductCode as 'ProductCodeEstoque'
            FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
            LEFT JOIN Stage.ProductDimension p
                ON p.ProductCode = m.ProductCode 
            LEFT JOIN  Stage.LocalDimension l
                ON l.LocalCode = m.LocalCode
            LEFT JOIN (
                    SELECT 
                        max(m.dateMoviment) as m,
                        m.ProductCode as id
                    FROM Stage.MetricData partition(" . $this->params["part"] . ")  m
                    LEFT JOIN Stage.ProductDimension p
                        ON p.ProductCode = m.ProductCode 
                    LEFT JOIN  Stage.LocalDimension l
                        ON l.LocalCode = m.LocalCode
                    WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
                    GROUP BY l.BriefDescription
            ) ee ON ee.id = m.ProductCode 
            WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
            GROUP BY l.BriefDescription) estoque ON estoque.ProductCodeEstoque =  m.ProductCode  
     WHERE (DATE(m.dateMoviment) BETWEEN :dataIni AND :datafim)
     GROUP BY DATE_FORMAT(m.dateMoviment,'%m'),l.BriefDescription,p.LevelDescription1,p.LevelDescription2,p.LevelDescription3,p.LevelDescription4 ")
        ->params(array(
            ":dataIni" => $this->params["extraParams"]["movimentacao__data__data_inicio"][0],
            ":datafim" => $this->params["extraParams"]["movimentacao__data__data_inicio"][1]
        ))
      
      
        ->pipe(new ColumnMeta(array(
            "totalMargem"=>array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalVenda" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
           
            "totalCusto" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "qtde" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            
            "totalEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalVendaEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            ),
            "totalCustoEstoque" => array(
                'type' => 'number',
                "prefix" => "",
                "decimals" => 2,
                "dec_point" => ",",
                "thousand_sep" => "."
            )
        )))
        ->pipe(new TimeBucket(array(
            "dateMoviment" => "month"
        )))
        ->pipe(new Pivot(array(
            "dimensions" => array(
                "column" => "mes",
                // "row" => "BriefDescription,LevelDescription1,LevelDescription2,LevelDescription3,LevelDescription4"
                "row" => "BriefDescription"
            ),
            "aggregates" => array(
                "sum" => "totalVenda,totalCusto,qtde",
                "max" => "totalEstoque,totalVendaEstoque,totalCustoEstoque"
          
              
            )
        )))
     
        ->pipe(new CalculatedColumn(array(
            // "margem_percent"=>"(({totalVenda - sum}-{totalCusto - sum})/{totalVenda - sum})*100"
      "margem_percent"=>function($data){
          alert($data);
                 if(!empty($data["totalVenda - sum"])){
                  $data["totalMargem"] = (($data["totalVenda - sum"] - $data["totalCusto - sum"])/$data["totalVenda - sum"])*100;

                }
     
                 return   $data["totalMargem"];
            }
            
        )))

        
        
        ->pipe($this->dataStore('vendasAnual'));
}

} // renomeando arquivo que o gestor gera para o padrao do kool troca o .html pelo .view

$_POST = $_REQUEST; $retorno = rename($this->_VISUAL, str_replace(".html.php", ".view.php", $this->_VISUAL)); $arquivo_view = str_replace(".html", "", pathinfo($this->_VISUAL, PATHINFO_FILENAME)); $vendasCore = new vendasCore([

"extraParams" => [
    "data64" => base64_encode(json_encode([
        "action" => "relatorios/relatorio_gestor",
        "method" => "generic",

        "params" => [
            "report" => "Venda_anual",
            "movimentacao__data__data_inicio" => [$datIni, $datFim]

        ]
    ])),
    "movimentacao__data__data_inicio" => [$datIni, $datFim]
],
"part" => (string)$sqlParticao

]);

// exibe o relatórios passando qual view ira utlizar $vendasCore->run()->render($arquivo_view);

exit;

Hermílio commented on Jan 23, 2019

venda.view.php

<?php use \koolreport\pivot\widgets\PivotMatrix; use \koolreport\core\Utility; use \koolreport\processes\Filter; use \koolreport\processes\ColumnMeta; use \koolreport\pivot\processes\Pivot; use \koolreport\instant\Widget; use \koolreport\datasources\CSVDataSource;

?>

"pivotMatrix1", 'dataSource' => $this->dataStore('vendasAnual'), "measures" => array( // "totalVenda - sum", "margem_percent" ), 'rowSort' => array( // 'totalVenda - sum' => 'desc', 'margem_percent' => 'desc' ), 'columnCollapseLevels' => array(0), 'rowCollapseLevels' => array(0), 'width' => '100%', 'height' => '100%', 'headerMap' => function ($v, $f) { switch ($v) { case 'totalVenda - sum': return 'Total Vendas'; case 'totalCusto - sum': return 'Qtde Custo'; case 'qtde - sum': return 'Qtde'; case 'margem_percent': return 'Margem'; case 'totalEstoque - max': return 'Total Estoque'; case 'totalVendaEstoque - max': return 'Total Venda Estoque'; case 'totalCustoEstoque - max': return 'Total Custo Estoque'; case 'mes': return 'Mês'; case 'LevelDescription1': return 'Descrição 01'; case 'LevelDescription2': return 'Descrição 02'; case 'LevelDescription3': return 'Descrição 03'; case 'LevelDescription4': return 'Descrição 04'; case 'BriefDescription': return 'Lojas'; } $r = $v; $map = array( '1' => 'Jan', '2' => 'Fev', '3' => 'Mar', '4' => 'Abr', '5' => 'Mai', '6' => 'Jun', '7' => 'Jul', '8' => 'Ago', '9' => 'Set', '10' => 'Out', '11' => 'Nov', '12' => 'Dez', ); if ($f === 'mes') $r = $map[$v]; return $r; }, // 'totalName' => 'Total', 'waitingFields' => array( 'totalVenda - sum' => 'data', 'totalCusto - sum' => 'data', 'qtde - sum' => 'data', 'totalEstoque - max' => 'data', 'totalVendaEstoque - max' => 'data', 'totalCustoEstoque - max' => 'data', // 'totalMargem - max' => 'data', 'LevelDescription1' => 'label', 'LevelDescription2' => 'label', 'LevelDescription3' => 'label', 'LevelDescription4' => 'label' ), 'paging' => array(), "scope" => $this->params["extraParams"] )); ?>
Hermílio commented on Jan 23, 2019

Hi David, I have now sent the separate code vendasAnual.php vendasAnual.view.php I found the problem in my report ->pipe(new Pivot(array(

            "dimensions" => array(
                "column" => "mes",
                // "row" => "BriefDescription,LevelDescription1,LevelDescription2,LevelDescription3,LevelDescription4"
                "row" => "BriefDescription"
            ),
            "aggregates" => array(
                "sum" => "totalVenda,totalCusto,qtde",
                "max" => "totalEstoque,totalVendaEstoque,totalCustoEstoque"
          
              
            )
        )))
     
        ->pipe(new CalculatedColumn(array(
            // "margem_percent"=>"(({totalVenda - sum}-{totalCusto - sum})/{totalVenda - sum})*100"
      "margem_percent"=>function($data){
          alert($data);
                 if(!empty($data["totalVenda - sum"])){
                  $data["totalMargem"] = (($data["totalVenda - sum"] - $data["totalCusto - sum"])/$data["totalVenda - sum"])*100;

                }
     
                 return   $data["totalMargem"];
            }
            
        )))

I'll get the data at the beginning as you can see

when I update the data it gets lost

how do i solve this? Thank you very much in advance

Build Your Excellent Data Report

Let KoolReport help you to make great reports. It's free & open-source released under MIT license.

Download KoolReport View demo
help needed

Pivot