Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions Model/Report.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use FacturaScripts\Core\Template\ModelTrait;
use FacturaScripts\Core\Tools;
use FacturaScripts\Core\Where;
use FacturaScripts\Dinamic\Model\Report as DinReport;

/**
* Descripcion de un informe o gráfico configurable
Expand Down Expand Up @@ -159,6 +160,20 @@ public function getCustomSql(): string
return $this->customSql;
}

/**
* Indica si tiene sentido mostrar el saldo acumulado de los valores del eje Y:
* solo cuando se suman o cuentan valores agrupados por periodos consecutivos.
*/
public function canShowBalance(): bool
{
$additive = in_array($this->yoperation ?? '', ['', 'SUM', 'COUNT', 'COUNT_DISTINCT'], true);
$sequential = in_array($this->xoperation ?? '', [
'DAY', 'WEEK', 'MONTHS', 'YEAR', 'UNIXTIME_DAY', 'UNIXTIME_WEEK', 'UNIXTIME_MONTH', 'UNIXTIME_YEAR'
], true);

return $additive && $sequential;
}

public function clear(): void
{
parent::clear();
Expand All @@ -176,6 +191,16 @@ public function getChart()
return new $className($this);
}

public function getComparedReport(): ?Report
{
if (empty($this->compared)) {
return null;
}

$report = new DinReport();
return $report->load($this->compared) ? $report : null;
}

public function getFiledXName(): string
{
return $this->fieldXName ?: $this->xcolumn;
Expand Down Expand Up @@ -239,6 +264,41 @@ public function getTable(): string
return $data[0] ?? '';
}

public function getXColumnLabel(): string
{
return empty($this->xcolumn) ? Tools::trans('x-column') : $this->getColumnLabel($this->xcolumn);
}

public function getYColumnLabel(): string
{
if (empty($this->ycolumn)) {
return Tools::trans('count');
}

$operation = match ($this->yoperation ?? '') {
'AVERAGE' => 'average',
'COUNT', 'COUNT_DISTINCT' => 'count',
'MAXIMUM' => 'maximum',
'MINIMUM' => 'minimum',
default => 'sum',
};

return $this->getColumnLabel($this->ycolumn) . ' (' . mb_strtolower(Tools::trans($operation)) . ')';
}

/**
* Devuelve los decimales con los que mostrar los valores del eje Y,
* o null para usar los decimales predeterminados.
*/
public function getYDecimals(): ?int
{
if (empty($this->ycolumn) || in_array($this->yoperation, ['COUNT', 'COUNT_DISTINCT'], true)) {
return 0;
}

return null;
}

public function primaryDescriptionColumn(): string
{
return 'name';
Expand All @@ -261,4 +321,18 @@ public function test(): bool
$this->yoperation = Tools::noHtml($this->yoperation);
return parent::test();
}

/**
* Devuelve el nombre traducido de una columna, sin el prefijo de la tabla.
* Las expresiones SQL se devuelven tal cual.
*/
private function getColumnLabel(string $column): string
{
if (false === (bool)preg_match('/^(?:\w+\.)?(\w+)$/', $column, $matches)) {
return $column;
}

$translation = Tools::trans($matches[1]);
return $translation === $matches[1] ? ucfirst($matches[1]) : $translation;
}
}
143 changes: 143 additions & 0 deletions Test/main/ReportTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

namespace FacturaScripts\Test\Plugins;

use FacturaScripts\Core\Html;
use FacturaScripts\Core\Tools;
use FacturaScripts\Plugins\Informes\Model\Report;
use FacturaScripts\Test\Traits\LogErrorsTrait;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -133,6 +135,147 @@ public function testDeleteReportDeletesFilters(): void
}
}

public function testCanShowBalance(): void
{
$report = new Report();
$report->xcolumn = 'fecha';
$report->ycolumn = 'total';

// con sumas o recuentos agrupados por periodos consecutivos se muestra el saldo
foreach (['', 'SUM', 'COUNT', 'COUNT_DISTINCT'] as $yOperation) {
foreach (['DAY', 'WEEK', 'MONTHS', 'YEAR', 'UNIXTIME_MONTH'] as $xOperation) {
$report->xoperation = $xOperation;
$report->yoperation = $yOperation;
$this->assertTrue($report->canShowBalance(), $xOperation . ' / ' . $yOperation);
}
}

// con medias, máximos o mínimos no se muestra el saldo
$report->xoperation = 'MONTHS';
foreach (['AVERAGE', 'MAXIMUM', 'MINIMUM'] as $yOperation) {
$report->yoperation = $yOperation;
$this->assertFalse($report->canShowBalance(), $yOperation);
}

// con agrupaciones cíclicas, por categorías o sin agrupar no se muestra el saldo
$report->yoperation = 'SUM';
foreach (['', 'HOUR', 'MONTH', 'HAS_A_VALUE', 'DOES_NOT_HAVE_A_VALUE'] as $xOperation) {
$report->xoperation = $xOperation;
$this->assertFalse($report->canShowBalance(), $xOperation);
}
}

public function testColumnLabels(): void
{
$report = new Report();

// sin columnas se usan las etiquetas genéricas
$this->assertEquals(Tools::trans('x-column'), $report->getXColumnLabel());
$this->assertEquals(Tools::trans('count'), $report->getYColumnLabel());

// se traduce el nombre de la columna sin el prefijo de la tabla
$report->xcolumn = 'facturascli.fecha';
$fecha = Tools::trans('fecha') === 'fecha' ? 'Fecha' : Tools::trans('fecha');
$this->assertEquals($fecha, $report->getXColumnLabel());

// la columna Y incluye la operación
$report->ycolumn = 'total';
$total = Tools::trans('total') === 'total' ? 'Total' : Tools::trans('total');
$this->assertEquals($total . ' (' . mb_strtolower(Tools::trans('sum')) . ')', $report->getYColumnLabel());

$report->yoperation = 'AVERAGE';
$this->assertEquals($total . ' (' . mb_strtolower(Tools::trans('average')) . ')', $report->getYColumnLabel());

// las expresiones SQL se muestran tal cual
$report->xcolumn = 'COALESCE(codcliente, codproveedor)';
$this->assertEquals('COALESCE(codcliente, codproveedor)', $report->getXColumnLabel());
}

public function testGetYDecimals(): void
{
$report = new Report();

// los recuentos no tienen decimales
$this->assertSame(0, $report->getYDecimals());

$report->ycolumn = 'total';
$report->yoperation = 'COUNT';
$this->assertSame(0, $report->getYDecimals());

// el resto de operaciones usa los decimales predeterminados
$report->yoperation = 'SUM';
$this->assertNull($report->getYDecimals());
}

public function testGetComparedReport(): void
{
// sin informe comparado devuelve null
$report = new Report();
$report->name = 'Test Report';
$report->table = 'test_table';
$this->assertNull($report->getComparedReport());

// creamos el informe comparado
$compared = new Report();
$compared->name = 'Test Compared Report';
$compared->table = 'test_table';
$this->assertTrue($compared->save());

// comprobamos que se carga el informe comparado
$report->compared = $compared->id;
$comparedReport = $report->getComparedReport();
$this->assertNotNull($comparedReport);
$this->assertEquals($compared->id, $comparedReport->id);

// si no existe el informe comparado devuelve null
$this->assertTrue($compared->delete());
$this->assertNull($report->getComparedReport());
}

public function testRenderChartTables(): void
{
// creamos un informe y otro comparado que cuentan los informes por mes
$compared = new Report();
$compared->name = 'Test Chart Compared';
$compared->table = 'reports';
$compared->type = Report::DEFAULT_TYPE;
$compared->xcolumn = 'creationdate';
$compared->xoperation = 'MONTHS';
$compared->ycolumn = 'id';
$compared->yoperation = 'COUNT';
$this->assertTrue($compared->save());

$report = new Report();
$report->name = 'Test Chart Main';
$report->table = 'reports';
$report->type = Report::DEFAULT_TYPE;
$report->xcolumn = 'creationdate';
$report->xoperation = 'MONTHS';
$report->ycolumn = 'id';
$report->yoperation = 'COUNT';
$report->compared = $compared->id;
$this->assertTrue($report->save());

// las tres tablas (informe, comparado y diferencia) muestran el saldo
$balanceHeader = '<th class="text-end">' . Tools::trans('balance') . '</th>';
$yHeader = '<th class="text-end">' . htmlspecialchars($report->getYColumnLabel()) . '</th>';
$html = Html::render('Master/htmlChart.html.twig', ['fsc' => ['views' => [['model' => $report]]]]);
$this->assertEquals(3, substr_count($html, $balanceHeader));
$this->assertEquals(3, substr_count($html, $yHeader));

// si el comparado usa otra operación, su tabla y la diferencia no muestran el saldo
$compared->yoperation = 'AVERAGE';
$this->assertTrue($compared->save());
$html = Html::render('Master/htmlChart.html.twig', ['fsc' => ['views' => [['model' => $report]]]]);
$this->assertEquals(1, substr_count($html, $balanceHeader));
$this->assertEquals(1, substr_count($html, $yHeader));
$this->assertStringContainsString('<th class="text-end">' . Tools::trans('y-column') . '</th>', $html);

// eliminamos los informes
$this->assertTrue($report->delete());
$this->assertTrue($compared->delete());
}

protected function tearDown(): void
{
$this->logErrors();
Expand Down
52 changes: 35 additions & 17 deletions View/Master/htmlChart.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,31 @@
{% set firstView = fsc.views | first %}
{% set model = firstView.model %}
{% set chart = model.getChart() %}
{% set compared = model.getComparedReport() %}

<div class="card shadow mb-4">
{{ chart.render() | raw }}
</div>

<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
{% for s_name, source in chart.getDataSources() %}
{% if s_name == 'difference' %}
{% set sameColumns = compared is not null
and compared.getXColumnLabel() == model.getXColumnLabel()
and compared.getYColumnLabel() == model.getYColumnLabel() %}
{% set xLabel = sameColumns ? model.getXColumnLabel() : trans('x-column') %}
{% set yLabel = sameColumns ? model.getYColumnLabel() : trans('y-column') %}
{% set decimals = sameColumns ? model.getYDecimals() : null %}
{% set showBalance = sameColumns and model.canShowBalance() %}
{% else %}
{% set report = compared is not null and s_name == compared.name and s_name != model.name ? compared : model %}
{% set xLabel = report.getXColumnLabel() %}
{% set yLabel = report.getYColumnLabel() %}
{% set decimals = report.getYDecimals() %}
{% set showBalance = report.canShowBalance() %}
{% endif %}
{% set total = 0 %}
{% set totalClass = '' %}
<div class="col">
<div class="card shadow mb-4">
<div class="card-body">
Expand All @@ -20,43 +37,44 @@
<table class="table table-striped table-hover mb-0">
<thead>
<tr>
<th>{{ trans('x-column') }}</th>
<th>{{ trans('y-column') }}</th>
<th>{{ xLabel }}</th>
<th class="text-end">{{ yLabel }}</th>
{% if showBalance %}
<th class="text-end">{{ trans('balance') }}</th>
{% endif %}
</tr>
</thead>
<tbody>
{% for item in source %}
{% set total = total + item.ycol %}
{% set totalClass = s_name != 'difference' ? '' : (total > 0 ? 'text-success' : (total < 0 ? 'text-danger' : '')) %}
{% set itemClass = s_name != 'difference' ? '' : (item.ycol > 0 ? 'text-success' : (item.ycol < 0 ? 'text-danger' : '')) %}
<tr>
<td>{{ item.xcol }}</td>
<td>
{% if s_name != 'difference' %}
{{ item.ycol }}
{% elseif item.ycol > 0 %}
<span class="text-success">{{ item.ycol }}</span>
{% elseif item.ycol < 0 %}
<span class="text-danger">{{ item.ycol }}</span>
{% else %}
{{ item.ycol }}
{% endif %}
</td>
<td class="text-end {{ itemClass }}">{{ number(item.ycol, decimals) }}</td>
{% if showBalance %}
<td class="text-end {{ totalClass }}">{{ number(total, decimals) }}</td>
{% endif %}
</tr>
{% else %}
<tr>
<td colspan="2" class="table-warning">{{ trans('no-data') }}</td>
<td colspan="{{ showBalance ? 3 : 2 }}" class="table-warning">{{ trans('no-data') }}</td>
</tr>
{% endfor %}
</tbody>
{% if total > 0 %}
{% if source is not empty %}
<tfoot class="sticky-bottom bg-light fw-bold">
<tr>
<td>{{ trans('total') }}</td>
<td>{{ number(total) }}</td>
<td class="text-end {{ totalClass }}">{{ number(total, decimals) }}</td>
{% if showBalance %}
<td></td>
{% endif %}
</tr>
</tfoot>
{% endif %}
</table>
</div>
</div>
{% endfor %}
</div>
</div>
Loading