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
186 changes: 186 additions & 0 deletions Controller/Informes/ReportTareaProyecto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php
/**
* This file is part of Proyectos plugin for FacturaScripts
* Copyright (C) 2026 Carlos Garcia Gomez <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace FacturaScripts\Plugins\Proyectos\Controller\Informes;

use FacturaScripts\Core\Template\Controller;
use FacturaScripts\Core\Tools;

/**
* Informe de tareas de proyectos. Solo se despliega si el plugin Informes está activado.
*/
class ReportTareaProyecto extends Controller
{
/** Tareas con su fase, para poder filtrar por el tipo de fase. */
const FROM = ' FROM tareas t INNER JOIN tareas_fases f ON f.idfase = t.idfase';

/** Tareas abiertas: su fase no es completada (tipo 0) ni cancelada (tipo 1). */
const OPEN = '(f.tipo IS NULL OR f.tipo NOT IN (0, 1))';

public $overdueTasks = [];
public $projectsWithMostOpenTasks = [];
public $tasksByMonth = [];
public $tasksByPhase = [];
public $tasksByUser = [];
public $tasksByYear = [];
public $totals = [];

public function getPageData(): array
{
$data = parent::getPageData();
$data['menu'] = 'reports';
$data['title'] = 'project-tasks';
$data['icon'] = 'fa-solid fa-list-check';
return $data;
}

public function run(): void
{
parent::run();

$this->loadTotals();
$this->loadTasksByPhase();
$this->loadTasksByUser();
$this->loadProjectsWithMostOpenTasks();
$this->loadOverdueTasks();
$this->loadTasksByPeriod();

$this->view('ReportTareaProyecto.html.twig');
}

protected function loadTotals(): void
{
$lastMonth = $this->db()->var2str(date('Y-m-d', strtotime('-1 month')));
$lastYear = $this->db()->var2str(date('Y-m-d', strtotime('-1 year')));

$this->totals = [
'total' => $this->count(),
'opened' => $this->count(self::OPEN),
'last_month' => $this->count('t.fecha >= ' . $lastMonth),
'last_year' => $this->count('t.fecha >= ' . $lastYear),
];

// tiempo medio de resolución en días (AVG ignora las tareas sin fecha de completado)
$sql = 'SELECT AVG(' . $this->resolutionDays() . ') AS media FROM tareas t';
$this->totals['media'] = $this->db()->select($sql)[0]['media'] ?? null;
}

protected function loadTasksByPhase(): void
{
$sql = 'SELECT f.nombre, f.tipo, COUNT(t.idtarea) AS total'
. ' FROM tareas_fases f'
. ' LEFT JOIN tareas t ON t.idfase = f.idfase'
. ' GROUP BY f.idfase, f.nombre, f.tipo'
. ' ORDER BY total DESC';
$this->tasksByPhase = $this->db()->select($sql);
}

protected function loadTasksByUser(): void
{
$sql = 'SELECT t.nick, COUNT(*) AS total,'
. ' SUM(CASE WHEN ' . self::OPEN . ' THEN 1 ELSE 0 END) AS opened,'
. ' SUM(CASE WHEN f.tipo = 0 THEN 1 ELSE 0 END) AS completed,'
. ' SUM(CASE WHEN f.tipo = 1 THEN 1 ELSE 0 END) AS canceled,'
. ' AVG(' . $this->resolutionDays() . ') AS media'
. self::FROM
. ' GROUP BY t.nick'
. ' ORDER BY total DESC';
$this->tasksByUser = $this->db()->select($sql);
}

protected function loadProjectsWithMostOpenTasks(): void
{
$sql = 'SELECT p.idproyecto, p.nombre, COUNT(*) AS total'
. self::FROM
. ' INNER JOIN proyectos p ON p.idproyecto = t.idproyecto'
. ' WHERE ' . self::OPEN
. ' GROUP BY p.idproyecto, p.nombre'
. ' ORDER BY total DESC';
$this->projectsWithMostOpenTasks = $this->db()->selectLimit($sql, 10);
}

protected function loadOverdueTasks(): void
{
$sql = 'SELECT t.idtarea, t.nombre, t.fechafin, p.nombre AS proyecto'
. self::FROM
. ' INNER JOIN proyectos p ON p.idproyecto = t.idproyecto'
. ' WHERE ' . self::OPEN
. ' AND t.fechafin < ' . $this->db()->var2str(Tools::date())
. ' ORDER BY t.fechafin ASC';
$this->overdueTasks = $this->db()->select($sql);
}

/**
* Tareas creadas (fecha) y completadas (fechacompletado), por mes (últimos 12) y por año.
*/
protected function loadTasksByPeriod(): void
{
// los últimos 12 meses empiezan a cero para que el gráfico muestre también los meses vacíos
for ($i = 11; $i >= 0; $i--) {
$month = date('Y-m', mktime(0, 0, 0, (int)date('n') - $i, 1));
$this->tasksByMonth[$month] = ['created' => 0, 'completed' => 0];
}

foreach (['created' => 'fecha', 'completed' => 'fechacompletado'] as $key => $column) {
$year = 'EXTRACT(YEAR FROM ' . $column . ')';
$month = 'EXTRACT(MONTH FROM ' . $column . ')';
$sql = 'SELECT ' . $year . ' AS anyo, ' . $month . ' AS mes, COUNT(*) AS total'
. ' FROM tareas'
. ' WHERE ' . $column . ' IS NOT NULL'
. ' GROUP BY ' . $year . ', ' . $month;

foreach ($this->db()->select($sql) as $row) {
$y = (int)$row['anyo'];
$ym = sprintf('%04d-%02d', $y, $row['mes']);
$total = (int)$row['total'];

if (isset($this->tasksByMonth[$ym])) {
$this->tasksByMonth[$ym][$key] = $total;
}

if (false === isset($this->tasksByYear[$y])) {
$this->tasksByYear[$y] = ['created' => 0, 'completed' => 0];
}
$this->tasksByYear[$y][$key] += $total;
}
}

ksort($this->tasksByYear);
}

/** Cuenta las tareas que cumplen la condición, o todas si no se indica ninguna. */
private function count(string $where = ''): int
{
$sql = 'SELECT COUNT(*) AS total' . self::FROM;
if ($where !== '') {
$sql .= ' WHERE ' . $where;
}
return (int)($this->db()->select($sql)[0]['total'] ?? 0);
}

/** Expresión SQL con los días entre la creación de la tarea y su fecha de completado. */
private function resolutionDays(): string
{
if (strtolower(Tools::config('db_type')) === 'postgresql') {
return 'EXTRACT(EPOCH FROM (t.fechacompletado - CAST(t.fecha AS TIMESTAMP))) / 86400';
}

return 'TIMESTAMPDIFF(SECOND, t.fecha, t.fechacompletado) / 86400';
}
}
37 changes: 37 additions & 0 deletions Model/TareaProyecto.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ class TareaProyecto extends ModelClass
/** @var string Fecha de creación de la tarea. */
public $fecha;

/** @var string|null Fecha y hora en que la tarea pasó a una fase de tipo completada. */
public $fechacompletado;

/** @var string Fecha de finalización de la tarea. */
public $fechafin;

Expand Down Expand Up @@ -137,6 +140,8 @@ public function primaryDescriptionColumn(): string

public function save(): bool
{
$this->updateCompletionDate();

if (false === parent::save()) {
return false;
}
Expand Down Expand Up @@ -274,6 +279,38 @@ protected function onUpdate(): void
parent::onUpdate();
}

/**
* Rellena la fecha de completado cuando la tarea pasa a una fase de tipo completada
* y la vacía cuando está en una fase que no lo es.
*/
protected function updateCompletionDate(): void
{
$phase = $this->getPhase();
if ($phase->tipo !== self::TYPE_COMPLETED) {
$this->fechacompletado = null;
return;
}

// si ya estaba en una fase completada, conservamos la fecha original
// (puede estar vacía en tareas completadas antes de existir este campo)
if ($this->exists() && $this->isCompletedPhase($this->getOriginal('idfase'))) {
$this->fechacompletado = $this->getOriginal('fechacompletado');
return;
}

$this->fechacompletado = Tools::dateTime();
}

protected function isCompletedPhase($idfase): bool
{
$phase = new FaseTarea();
if (empty($idfase) || false === $phase->load($idfase)) {
return false;
}

return $phase->tipo === self::TYPE_COMPLETED;
}

/**
* If the project is completed or canceled and a new task is added,
* then it sets the default project status.
Expand Down
4 changes: 4 additions & 0 deletions Table/tareas.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
<type>date</type>
<null>NO</null>
</column>
<column>
<name>fechacompletado</name>
<type>timestamp</type>
</column>
<column>
<name>fechafin</name>
<type>date</type>
Expand Down
8 changes: 8 additions & 0 deletions Test/main/ProjectAttachmentManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

use FacturaScripts\Dinamic\Model\AttachedFile;
use FacturaScripts\Dinamic\Model\AttachedFileRelation;
use FacturaScripts\Dinamic\Model\ProductoImagen;
use FacturaScripts\Plugins\Proyectos\Lib\ProjectAttachmentManager;
use FacturaScripts\Plugins\Proyectos\Model\Proyecto;
use FacturaScripts\Test\Traits\LogErrorsTrait;
Expand All @@ -34,6 +35,13 @@ final class ProjectAttachmentManagerTest extends TestCase
{
use LogErrorsTrait;

public static function setUpBeforeClass(): void
{
// la tabla productos_imagenes debe existir antes de borrar archivos:
// AttachedFile la consulta dentro de una transacción y en PostgreSQL no se puede crear ahí
new ProductoImagen();
}

public function testNumDocsFollowsAttachments(): void
{
// creamos un proyecto, que empieza sin adjuntos
Expand Down
7 changes: 7 additions & 0 deletions Test/main/ProjectTotalManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use FacturaScripts\Dinamic\Model\AlbaranProveedor;
use FacturaScripts\Dinamic\Model\Cliente;
use FacturaScripts\Dinamic\Model\FacturaProveedor;
use FacturaScripts\Dinamic\Model\PagoCliente;
use FacturaScripts\Dinamic\Model\PagoProveedor;
use FacturaScripts\Dinamic\Model\PedidoCliente;
use FacturaScripts\Dinamic\Model\PedidoProveedor;
use FacturaScripts\Dinamic\Model\PresupuestoCliente;
Expand All @@ -39,6 +41,11 @@ final class ProjectTotalManagerTest extends TestCase
public static function setUpBeforeClass(): void
{
self::setDefaultSettings();

// las tablas de pagos deben existir antes de borrar facturas: los recibos las consultan
// dentro de una transacción y en PostgreSQL no se pueden crear ahí
new PagoCliente();
new PagoProveedor();
}

public function testTotalCalculate(): void
Expand Down
25 changes: 0 additions & 25 deletions Translation/ca_ES.json

This file was deleted.

25 changes: 0 additions & 25 deletions Translation/cs_CZ.json

This file was deleted.

25 changes: 0 additions & 25 deletions Translation/de_DE.json

This file was deleted.

Loading
Loading