From e4040bb1f012bcfa3f64ebf48853e93591e3aae9 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 19 Sep 2025 10:47:27 +0200 Subject: [PATCH 01/27] bump(1.2.0-dev): 1.2.0-dev --- install/migration/update_1.1.0_to_1.2.0.php | 69 +++++++ .../01_rename_carbonintensitysource.php | 65 ++++++ install/mysql/plugin_carbon_1.1.0_empty.sql | 191 ++++++++++++++++++ install/mysql/plugin_carbon_empty.sql | 32 +-- setup.php | 2 +- src/{CarbonIntensitySource.php => Source.php} | 0 ...tensitySource_Zone.php => Source_Zone.php} | 0 ...IntensitySourceTest.php => SourceTest.php} | 0 ...ource_ZoneTest.php => Source_ZoneTest.php} | 0 9 files changed, 342 insertions(+), 17 deletions(-) create mode 100644 install/migration/update_1.1.0_to_1.2.0.php create mode 100644 install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php create mode 100644 install/mysql/plugin_carbon_1.1.0_empty.sql rename src/{CarbonIntensitySource.php => Source.php} (100%) rename src/{CarbonIntensitySource_Zone.php => Source_Zone.php} (100%) rename tests/units/{CarbonIntensitySourceTest.php => SourceTest.php} (100%) rename tests/units/{CarbonIntensitySource_ZoneTest.php => Source_ZoneTest.php} (100%) diff --git a/install/migration/update_1.1.0_to_1.2.0.php b/install/migration/update_1.1.0_to_1.2.0.php new file mode 100644 index 00000000..cb9599dc --- /dev/null +++ b/install/migration/update_1.1.0_to_1.2.0.php @@ -0,0 +1,69 @@ +. + * + * ------------------------------------------------------------------------- + */ + +function update001to100(Migration $migration) +{ + /** @var DBmysql $DB */ + global $DB; + + $updateresult = true; + $from_version = '0.0.1'; + $to_version = '1.0.0'; + $update_dir = __DIR__ . "/update_{$from_version}_to_{$to_version}/"; + + //TRANS: %s is the number of new version + $migration->addInfoMessage(sprintf(__('Update to %s'), $to_version)); + $migration->setVersion($to_version); + + // New tables from enpty.sql file after the migration + // If a script requires a new table, it may create it by itself + + $update_scripts = scandir($update_dir); + natcasesort($update_scripts); + foreach ($update_scripts as $update_script) { + if (preg_match('/\.php$/', $update_script) !== 1) { + continue; + } + require $update_dir . $update_script; + } + + $dbFile = plugin_carbon_getSchemaPath($to_version); + if ($dbFile === null || !$DB->runFile($dbFile)) { + $migration->addWarningMessage("Error creating tables : " . $DB->error()); + $updateresult = false; + } + + // ************ Keep it at the end ************** + $migration->executeMigration(); + + return $updateresult; +} diff --git a/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php b/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php new file mode 100644 index 00000000..237dbc1f --- /dev/null +++ b/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php @@ -0,0 +1,65 @@ +. + * + * ------------------------------------------------------------------------- + */ + +/** @var DBmysql $DB */ +/** @var Migration $migration */ + +// Rename CarbonIntensitySource +// Move data to new table +$old_table = 'glpi_plugin_carbon_carbonintensitysources'; +$new_table = 'glpi_plugin_carbon_sources'; +$migration->renameTable($old_table, $new_table); + +$old_itemtype = '\\GlpiPlugin\\Carbon\\CarbonIntensitySource'; +$new_itemtype = '\\GlpiPlugin\\Carbon\\Source'; + +// Update display preferences +$DB->update(DisplayPreference::getTable(), [ + 'itemtype' => $new_itemtype +], [ + 'itemtype' => $old_itemtype +]); + +// Rename CarbonIntensitySource_Zone +$old_table = 'glpi_plugin_carbon_carbonintensitysources_zones'; +$new_table = 'glpi_plugin_carbon_sources_zones'; +$migration->renameTable($old_table, $new_table); + +$old_itemtype = '\\GlpiPlugin\\Carbon\\CarbonIntensitySource_Zone'; +$new_itemtype = '\\GlpiPlugin\\Carbon\\Source_Zone'; + +// Update display preferences +$DB->update(DisplayPreference::getTable(), [ + 'itemtype' => $new_itemtype +], [ + 'itemtype' => $old_itemtype +]); \ No newline at end of file diff --git a/install/mysql/plugin_carbon_1.1.0_empty.sql b/install/mysql/plugin_carbon_1.1.0_empty.sql new file mode 100644 index 00000000..2758eee4 --- /dev/null +++ b/install/mysql/plugin_carbon_1.1.0_empty.sql @@ -0,0 +1,191 @@ +-- +-- ------------------------------------------------------------------------- +-- Carbon plugin for GLPI +-- +-- @copyright Copyright (C) 2024-2025 Teclib' and contributors. +-- @license https://www.gnu.org/licenses/gpl-3.0.txt GPLv3+ +-- @license MIT https://opensource.org/licenses/mit-license.php +-- @link https://github.com/pluginsGLPI/carbon +-- +-- ------------------------------------------------------------------------- +-- +-- LICENSE +-- +-- This file is part of Carbon plugin for GLPI. +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU 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 General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see . +-- +-- ------------------------------------------------------------------------- +-- + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonemissions` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `itemtype` varchar(255) DEFAULT NULL, + `items_id` int unsigned NOT NULL DEFAULT '0', + `engine` varchar(255) DEFAULT NULL, + `engine_version` varchar(255) DEFAULT NULL, + `date_mod` timestamp NULL DEFAULT NULL, + `entities_id` int unsigned NOT NULL DEFAULT '0', + `types_id` int unsigned NOT NULL DEFAULT '0', + `models_id` int unsigned NOT NULL DEFAULT '0', + `locations_id` int unsigned NOT NULL DEFAULT '0', + `energy_per_day` float DEFAULT '0' COMMENT 'KWh', + `emission_per_day` float DEFAULT '0' COMMENT 'gCO2eq', + `date` timestamp NULL DEFAULT NULL, + `energy_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `emission_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`itemtype`, `items_id`, `date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensities` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `date` timestamp NULL DEFAULT NULL, + `plugin_carbon_carbonintensitysources_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_zones_id` int unsigned NOT NULL DEFAULT '0', + `intensity` float DEFAULT '0' COMMENT 'gCO2eq/KWh', + `data_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`date`, `plugin_carbon_carbonintensitysources_id`, `plugin_carbon_zones_id`), + INDEX `date` (`date`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_zones` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `entities_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_carbonintensitysources_id_historical` int unsigned NOT NULL DEFAULT '0' COMMENT 'Source to be used for historical calculation', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`name`), + INDEX `entities_id` (`entities_id`), + INDEX `plugin_carbon_carbonintensitysources_id_historical` (`plugin_carbon_carbonintensitysources_id_historical`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensitysources` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `is_fallback` tinyint NOT NULL DEFAULT '0' COMMENT 'Fallback source for carbon intensity', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensitysources_zones` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `plugin_carbon_carbonintensitysources_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_zones_id` int unsigned NOT NULL DEFAULT '0', + `code` varchar(255) DEFAULT NULL COMMENT 'Zone identifier in the API of the source', + `is_download_enabled` tinyint NOT NULL DEFAULT '0' COMMENT 'Download enabled from the source for this zone', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`plugin_carbon_carbonintensitysources_id`, `plugin_carbon_zones_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_computertypes` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `computertypes_id` int unsigned NOT NULL DEFAULT '0', + `power_consumption` int DEFAULT '0', + `category` int NOT NULL DEFAULT '0' COMMENT 'ComputerType::CATEGORY_* constants', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`computertypes_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_computerusageprofiles` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `time_start` varchar(255) DEFAULT NULL, + `time_stop` varchar(255) DEFAULT NULL, + `day_1` tinyint NOT NULL DEFAULT '0', + `day_2` tinyint NOT NULL DEFAULT '0', + `day_3` tinyint NOT NULL DEFAULT '0', + `day_4` tinyint NOT NULL DEFAULT '0', + `day_5` tinyint NOT NULL DEFAULT '0', + `day_6` tinyint NOT NULL DEFAULT '0', + `day_7` tinyint NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_embodiedimpacts` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `itemtype` varchar(255) DEFAULT NULL, + `items_id` int unsigned NOT NULL DEFAULT '0', + `engine` varchar(255) DEFAULT NULL, + `engine_version` varchar(255) DEFAULT NULL, + `date_mod` timestamp NULL DEFAULT NULL, + `gwp` float unsigned DEFAULT '0' COMMENT '(unit gCO2eq) Global warming potential', + `gwp_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `adp` float unsigned DEFAULT '0' COMMENT '(unit gSbeq) Abiotic depletion potential', + `adp_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `pe` float unsigned DEFAULT '0' COMMENT '(unit J) Primary energy', + `pe_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`itemtype`, `items_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_environmentalimpacts` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `computers_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_computerusageprofiles_id` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`computers_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_monitortypes` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `monitortypes_id` int unsigned NOT NULL DEFAULT '0', + `power_consumption` int DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`monitortypes_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_networkequipmenttypes` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `networkequipmenttypes_id` int unsigned NOT NULL DEFAULT '0', + `power_consumption` int DEFAULT '0', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`networkequipmenttypes_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_locations` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `locations_id` int unsigned NOT NULL DEFAULT '0', + `boavizta_zone` varchar(255) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`locations_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_usageinfos` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `itemtype` varchar(255) DEFAULT NULL, + `items_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_computerusageprofiles_id` int unsigned NOT NULL DEFAULT '0', + `planned_lifespan` int unsigned NOT NULL DEFAULT '0' COMMENT '(unit months)', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`itemtype`, `items_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_usageimpacts` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `itemtype` varchar(255) DEFAULT NULL, + `items_id` int unsigned NOT NULL DEFAULT '0', + `engine` varchar(255) DEFAULT NULL, + `engine_version` varchar(255) DEFAULT NULL, + `date_mod` timestamp NULL DEFAULT NULL, + `gwp` float unsigned DEFAULT '0' COMMENT '(unit gCO2eq) Global warming potential', + `gwp_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `adp` float unsigned DEFAULT '0' COMMENT '(unit gSbeq) Abiotic depletion potential', + `adp_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `pe` float unsigned DEFAULT '0' COMMENT '(unit J) Primary energy', + `pe_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + PRIMARY KEY (`id`), + UNIQUE KEY `unicity` (`itemtype`, `items_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/install/mysql/plugin_carbon_empty.sql b/install/mysql/plugin_carbon_empty.sql index 2758eee4..84e4436a 100644 --- a/install/mysql/plugin_carbon_empty.sql +++ b/install/mysql/plugin_carbon_empty.sql @@ -50,29 +50,29 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonemissions` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensities` ( - `id` int unsigned NOT NULL AUTO_INCREMENT, - `date` timestamp NULL DEFAULT NULL, - `plugin_carbon_carbonintensitysources_id` int unsigned NOT NULL DEFAULT '0', - `plugin_carbon_zones_id` int unsigned NOT NULL DEFAULT '0', - `intensity` float DEFAULT '0' COMMENT 'gCO2eq/KWh', - `data_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', + `id` int unsigned NOT NULL AUTO_INCREMENT, + `date` timestamp NULL DEFAULT NULL, + `plugin_carbon_sources_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_zones_id` int unsigned NOT NULL DEFAULT '0', + `intensity` float DEFAULT '0' COMMENT 'gCO2eq/KWh', + `data_quality` int unsigned NOT NULL DEFAULT '0' COMMENT 'DataTtacking\\AbstractTracked::DATA_QUALITY_* constants', PRIMARY KEY (`id`), - UNIQUE KEY `unicity` (`date`, `plugin_carbon_carbonintensitysources_id`, `plugin_carbon_zones_id`), + UNIQUE KEY `unicity` (`date`, `plugin_carbon_sources_id`, `plugin_carbon_zones_id`), INDEX `date` (`date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_zones` ( - `id` int unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(255) DEFAULT NULL, - `entities_id` int unsigned NOT NULL DEFAULT '0', - `plugin_carbon_carbonintensitysources_id_historical` int unsigned NOT NULL DEFAULT '0' COMMENT 'Source to be used for historical calculation', + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `entities_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_sources_id_historical` int unsigned NOT NULL DEFAULT '0' COMMENT 'Source to be used for historical calculation', PRIMARY KEY (`id`), UNIQUE KEY `unicity` (`name`), INDEX `entities_id` (`entities_id`), - INDEX `plugin_carbon_carbonintensitysources_id_historical` (`plugin_carbon_carbonintensitysources_id_historical`) + INDEX `plugin_carbon_sources_id_historical` (`plugin_carbon_sources_id_historical`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensitysources` ( +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_sources` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `is_fallback` tinyint NOT NULL DEFAULT '0' COMMENT 'Fallback source for carbon intensity', @@ -80,14 +80,14 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensitysources` ( UNIQUE KEY `unicity` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_carbonintensitysources_zones` ( +CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_sources_zones` ( `id` int unsigned NOT NULL AUTO_INCREMENT, - `plugin_carbon_carbonintensitysources_id` int unsigned NOT NULL DEFAULT '0', + `plugin_carbon_sources_id` int unsigned NOT NULL DEFAULT '0', `plugin_carbon_zones_id` int unsigned NOT NULL DEFAULT '0', `code` varchar(255) DEFAULT NULL COMMENT 'Zone identifier in the API of the source', `is_download_enabled` tinyint NOT NULL DEFAULT '0' COMMENT 'Download enabled from the source for this zone', PRIMARY KEY (`id`), - UNIQUE KEY `unicity` (`plugin_carbon_carbonintensitysources_id`, `plugin_carbon_zones_id`) + UNIQUE KEY `unicity` (`plugin_carbon_sources_id`, `plugin_carbon_zones_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_computertypes` ( diff --git a/setup.php b/setup.php index e9cfdd45..8e8f7300 100644 --- a/setup.php +++ b/setup.php @@ -41,7 +41,7 @@ use Profile as GlpiProfile; use GlpiPlugin\Carbon\Dashboard\Grid; -define('PLUGIN_CARBON_VERSION', '1.1.0-dev'); +define('PLUGIN_CARBON_VERSION', '1.2.0-dev'); define('PLUGIN_CARBON_SCHEMA_VERSION', '1.1.0'); // Minimal GLPI version, inclusive diff --git a/src/CarbonIntensitySource.php b/src/Source.php similarity index 100% rename from src/CarbonIntensitySource.php rename to src/Source.php diff --git a/src/CarbonIntensitySource_Zone.php b/src/Source_Zone.php similarity index 100% rename from src/CarbonIntensitySource_Zone.php rename to src/Source_Zone.php diff --git a/tests/units/CarbonIntensitySourceTest.php b/tests/units/SourceTest.php similarity index 100% rename from tests/units/CarbonIntensitySourceTest.php rename to tests/units/SourceTest.php diff --git a/tests/units/CarbonIntensitySource_ZoneTest.php b/tests/units/Source_ZoneTest.php similarity index 100% rename from tests/units/CarbonIntensitySource_ZoneTest.php rename to tests/units/Source_ZoneTest.php From 5c3f7b9c33400f72468527363ef81294171fb8bf Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 19 Sep 2025 11:19:14 +0200 Subject: [PATCH 02/27] refactor(CarbonIntensitySource): rename object to Source Impacts CarbonIntensityZource_Zone, which has been renamed Semantically unlocks the abolity to use Source object to store data for data sources other than carbon intensity --- ajax/toggleZoneDownload.php | 8 ++-- hook.php | 14 +++--- install/Install.php | 16 +++---- install/install/init_datasources.php | 14 +++++- install/migration/update_1.1.0_to_1.2.0.php | 6 +-- .../01_rename_carbonintensitysource.php | 35 +++++++------- src/CarbonIntensity.php | 20 ++++---- src/Command/CollectCarbonIntensityCommand.php | 12 ++--- .../CreateFakeCarbonIntensityCommand.php | 6 +-- src/Dashboard/Provider.php | 6 +-- src/DataSource/Boaviztapi.php | 28 +++++------ .../CarbonIntensity/AbstractClient.php | 22 ++++----- .../CarbonIntensity/ElectricityMapClient.php | 12 ++--- src/DataSource/CarbonIntensity/RteClient.php | 14 +++--- src/Engine/V1/AbstractAsset.php | 42 ++++++++--------- src/Location.php | 16 +++---- src/Source.php | 6 +-- src/Source_Zone.php | 46 ++++++++++--------- src/Zone.php | 26 +++++------ tests/install/PluginInstallTest.php | 21 ++++----- tests/integration/SearchOptionTest.php | 8 ++-- tests/src/CommonTestCase.php | 10 ++-- tests/src/GlobalFixture.php | 14 +++--- tests/units/CarbonIntensityTest.php | 40 ++++++++-------- .../ElectricityMapClientTest.php | 10 ++-- tests/units/LocationTest.php | 22 ++++----- tests/units/SourceTest.php | 46 +++++++++---------- tests/units/Source_ZoneTest.php | 18 ++++---- tests/units/ZoneTest.php | 8 ++-- 29 files changed, 277 insertions(+), 269 deletions(-) diff --git a/ajax/toggleZoneDownload.php b/ajax/toggleZoneDownload.php index 581a2a8c..feba5601 100644 --- a/ajax/toggleZoneDownload.php +++ b/ajax/toggleZoneDownload.php @@ -30,8 +30,8 @@ * ------------------------------------------------------------------------- */ -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; include(__DIR__ . '/../../../inc/includes.php'); @@ -41,7 +41,7 @@ die(); } -if (!CarbonIntensitySource::canView()) { +if (!Source::canView()) { // Will die http_response_code(403); die(); @@ -52,7 +52,7 @@ die(); } -$source_zone = new CarbonIntensitySource_Zone(); +$source_zone = new Source_Zone(); if (!$source_zone->getFromDB($_GET['id'])) { http_response_code(403); die(); diff --git a/hook.php b/hook.php index 7f91f6ef..6e6c574f 100644 --- a/hook.php +++ b/hook.php @@ -36,14 +36,14 @@ use GlpiPlugin\Carbon\Install; use GlpiPlugin\Carbon\Uninstall; use GlpiPlugin\Carbon\UsageInfo; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use ComputerType as GlpiComputerType; use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\CarbonIntensity; use MonitorType as GlpiMonitorType; use NetworkEquipmentType as GlpiNetworkEquipmentType; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Config; use GlpiPlugin\Carbon\EmbodiedImpact; use GlpiPlugin\Carbon\Location; @@ -120,7 +120,7 @@ function plugin_carbon_getDropdown() { return [ ComputerUsageProfile::class => ComputerUsageProfile::getTypeName(), - CarbonIntensitySource::class => CarbonIntensitySource::getTypeName(), + Source::class => Source::getTypeName(), Zone::class => Zone::getTypeName(), CarbonIntensity::class => CarbonIntensity::getTypeName(), ]; @@ -188,10 +188,10 @@ function plugin_carbon_hook_add_asset(CommonDBTM $item) if ($zone === null) { return; } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ $zone->getForeignKeyField() => $zone->fields['id'], - CarbonIntensitySource::getForeignKeyField() => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], + Source::getForeignKeyField() => $zone->fields['plugin_carbon_sources_id_historical'], ]); if ($source_zone->isNewItem()) { return; @@ -215,10 +215,10 @@ function plugin_carbon_hook_update_asset(CommonDBTM $item) if ($zone === null) { return; } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ $zone->getForeignKeyField() => $zone->fields['id'], - CarbonIntensitySource::getForeignKeyField() => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], + Source::getForeignKeyField() => $zone->fields['plugin_carbon_sources_id_historical'], ]); if ($source_zone->isNewItem()) { return; diff --git a/install/Install.php b/install/Install.php index 10b885f3..995e6f5f 100644 --- a/install/Install.php +++ b/install/Install.php @@ -35,8 +35,6 @@ use Config; use DBmysql; use DirectoryIterator; -use Glpi\Message\MessageType; -use Glpi\Toolbox\Sanitizer; use Migration; use Plugin; @@ -251,7 +249,7 @@ private function getMigrationsToDo(string $current_version): array */ public static function getOrCreateSource(string $name, int $is_fallback = 1): int { - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit(['name' => $name]); if ($source->isNewItem()) { $source->add([ @@ -280,7 +278,7 @@ public static function getOrCreateZone(string $name, int $source_id): int if ($zone->isNewItem()) { $zone->add([ 'name' => $name, - 'plugin_carbon_carbonintensitysources_id_historical' => $source_id, + 'plugin_carbon_sources_id_historical' => $source_id, ]); /** @phpstan-ignore if.alwaysTrue */ if ($zone->isNewItem()) { @@ -300,15 +298,15 @@ public static function getOrCreateZone(string $name, int $source_id): int */ public static function linkSourceZone(int $source_id, int $zone_id): int { - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ - 'plugin_carbon_carbonintensitysources_id' => $source_id, - 'plugin_carbon_zones_id' => $zone_id, + 'plugin_carbon_sources_id' => $source_id, + 'plugin_carbon_zones_id' => $zone_id, ]); if ($source_zone->isNewItem()) { $source_zone->add([ - 'plugin_carbon_carbonintensitysources_id' => $source_id, - 'plugin_carbon_zones_id' => $zone_id, + 'plugin_carbon_sources_id' => $source_id, + 'plugin_carbon_zones_id' => $zone_id, ]); } diff --git a/install/install/init_datasources.php b/install/install/init_datasources.php index 2614450b..b12e4e48 100644 --- a/install/install/init_datasources.php +++ b/install/install/init_datasources.php @@ -33,10 +33,20 @@ use GlpiPlugin\Carbon\Install; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Output\ConsoleOutput; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; +use GlpiPlugin\Carbon\Zone; /** @var DBmysql $DB */ global $DB; +// This file ys executed at the end of an upgrade. +// Upgrade to 1.2.0 changed the tables modified by this code +// then we need to reset DB columns cache +$DB->listFields(getTableForItemType(Source::class), false); +$DB->listFields(getTableForItemType(Source_Zone::class), false); +$DB->listFields(getTableForItemType(Zone::class), false); + $source_id = Install::getOrCreateSource('RTE', 0); $zone_id = Install::getOrCreateZone('France', $source_id); @@ -97,7 +107,7 @@ 'data_quality' => 2 // constant GlpiPlugin\Carbon\DataTracking::DATA_QUALITY_ESTIMATED ], [ 'date' => "$year-01-01 00:00:00", - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id ]); @@ -122,7 +132,7 @@ 'data_quality' => 2 // constant GlpiPlugin\Carbon\DataTracking::DATA_QUALITY_ESTIMATED ], [ 'date' => "$year-01-01 00:00:00", - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id_quebec, ]); diff --git a/install/migration/update_1.1.0_to_1.2.0.php b/install/migration/update_1.1.0_to_1.2.0.php index cb9599dc..e92d090e 100644 --- a/install/migration/update_1.1.0_to_1.2.0.php +++ b/install/migration/update_1.1.0_to_1.2.0.php @@ -30,14 +30,14 @@ * ------------------------------------------------------------------------- */ -function update001to100(Migration $migration) +function update110to120(Migration $migration) { /** @var DBmysql $DB */ global $DB; $updateresult = true; - $from_version = '0.0.1'; - $to_version = '1.0.0'; + $from_version = '1.1.0'; + $to_version = '1.2.0'; $update_dir = __DIR__ . "/update_{$from_version}_to_{$to_version}/"; //TRANS: %s is the number of new version diff --git a/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php b/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php index 237dbc1f..795e235b 100644 --- a/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php +++ b/install/migration/update_1.1.0_to_1.2.0/01_rename_carbonintensitysource.php @@ -39,27 +39,26 @@ $new_table = 'glpi_plugin_carbon_sources'; $migration->renameTable($old_table, $new_table); -$old_itemtype = '\\GlpiPlugin\\Carbon\\CarbonIntensitySource'; -$new_itemtype = '\\GlpiPlugin\\Carbon\\Source'; - -// Update display preferences -$DB->update(DisplayPreference::getTable(), [ - 'itemtype' => $new_itemtype -], [ - 'itemtype' => $old_itemtype -]); - // Rename CarbonIntensitySource_Zone $old_table = 'glpi_plugin_carbon_carbonintensitysources_zones'; $new_table = 'glpi_plugin_carbon_sources_zones'; $migration->renameTable($old_table, $new_table); -$old_itemtype = '\\GlpiPlugin\\Carbon\\CarbonIntensitySource_Zone'; -$new_itemtype = '\\GlpiPlugin\\Carbon\\Source_Zone'; +$table = 'glpi_plugin_carbon_carbonintensities'; +$migration->changeField($table, 'plugin_carbon_carbonintensitysources_id', 'plugin_carbon_sources_id', 'fkey'); + +$table = 'glpi_plugin_carbon_zones'; +$migration->changeField($table, 'plugin_carbon_carbonintensitysources_id_historical', 'plugin_carbon_sources_id_historical', 'fkey'); +$migration->dropKey($table, 'plugin_carbon_carbonintensitysources_id_historical'); +$migration->addKey($table, 'plugin_carbon_sources_id_historical', 'plugin_carbon_sources_id_historical'); + +$table = 'glpi_plugin_carbon_sources_zones'; +$migration->changeField($table, 'plugin_carbon_carbonintensitysources_id', 'plugin_carbon_sources_id', 'fkey'); -// Update display preferences -$DB->update(DisplayPreference::getTable(), [ - 'itemtype' => $new_itemtype -], [ - 'itemtype' => $old_itemtype -]); \ No newline at end of file +// Migrate tables now and clear cache to avoid issues in subsequent upgrade tasks +$migration->migrationOneTable('glpi_plugin_carbon_carbonintensities'); +$DB->listFields('glpi_plugin_carbon_carbonintensities', false); +$migration->migrationOneTable('glpi_plugin_carbon_sources_zones'); +$DB->listFields('glpi_plugin_carbon_sources_zones', false); +$migration->migrationOneTable('glpi_plugin_carbon_zones'); +$DB->listFields('glpi_plugin_carbon_zones', false); diff --git a/src/CarbonIntensity.php b/src/CarbonIntensity.php index e6b067a6..a319562e 100644 --- a/src/CarbonIntensity.php +++ b/src/CarbonIntensity.php @@ -38,7 +38,7 @@ use DateTimeImmutable; use DateTimeInterface; use DBmysql; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use Glpi\DBAL\QueryParam; use GlpiPlugin\Carbon\DataSource\CarbonIntensity\ClientInterface; @@ -92,9 +92,9 @@ public function rawSearchOptions() $tab[] = [ 'id' => SearchOptions::CARBON_INTENSITY_SOURCE, - 'table' => CarbonIntensitySource::getTable(), + 'table' => Source::getTable(), 'field' => 'name', - 'name' => CarbonIntensitySource::getTypeName(1), + 'name' => Source::getTypeName(1), 'massiveaction' => false, // implicit field is id 'datatype' => 'dropdown', ]; @@ -131,7 +131,7 @@ public function rawSearchOptions() private function getKnownDatesQuery(string $zone_name, string $source_name) { $intensity_table = CarbonIntensity::getTable(); - $source_table = CarbonIntensitySource::getTable(); + $source_table = Source::getTable(); $zone_table = Zone::getTable(); return [ 'SELECT' => [$intensity_table => ['id', 'date']], @@ -139,7 +139,7 @@ private function getKnownDatesQuery(string $zone_name, string $source_name) 'INNER JOIN' => [ $source_table => [ 'FKEY' => [ - $intensity_table => CarbonIntensitySource::getForeignKeyField(), + $intensity_table => Source::getForeignKeyField(), $source_table => 'id', ] ], @@ -151,7 +151,7 @@ private function getKnownDatesQuery(string $zone_name, string $source_name) ] ], 'WHERE' => [ - CarbonIntensitySource::getTableField('name') => $source_name, + Source::getTableField('name') => $source_name, Zone::getTableField('name') => $zone_name ], ]; @@ -218,7 +218,7 @@ public function downloadOneZone(ClientInterface $data_source, string $zone_name, $total_count = 0; // Check if there are gaps to fill - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit(['name' => $data_source->getSourceName()]); $zone = new Zone(); $zone->getFromDBByCrit(['name' => $zone_name]); @@ -334,7 +334,7 @@ public function save(string $zone_name, string $source_name, array $data): int global $DB; $count = 0; - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name, ]); @@ -357,7 +357,7 @@ public function save(string $zone_name, string $source_name, array $data): int CarbonIntensity::getTable(), [ 'date' => new QueryParam(), - CarbonIntensitySource::getForeignKeyField() => new QueryParam(), + Source::getForeignKeyField() => new QueryParam(), Zone::getForeignKeyField() => new QueryParam(), 'intensity' => new QueryParam(), 'data_quality' => new QueryParam(), @@ -399,7 +399,7 @@ public function save(string $zone_name, string $source_name, array $data): int public function findGaps(int $source_id, int $zone_id, DateTimeInterface $start, ?DateTimeInterface $stop = null): array { $criteria = [ - CarbonIntensitySource::getForeignKeyField() => $source_id, + Source::getForeignKeyField() => $source_id, Zone::getForeignKeyField() => $zone_id, ]; $interval = new DateInterval('PT1H'); diff --git a/src/Command/CollectCarbonIntensityCommand.php b/src/Command/CollectCarbonIntensityCommand.php index 370f160f..9f26b90b 100644 --- a/src/Command/CollectCarbonIntensityCommand.php +++ b/src/Command/CollectCarbonIntensityCommand.php @@ -36,10 +36,10 @@ use DateTimeImmutable; use Glpi\Console\AbstractCommand; use GlpiPlugin\Carbon\CarbonIntensity; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\DataSource\CarbonIntensity\ClientFactory; use GlpiPlugin\Carbon\DataSource\CarbonIntensity\ClientInterface; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; @@ -76,7 +76,7 @@ protected function interact(InputInterface $input, OutputInterface $output) // Set data source argument if not provided if (is_null($input->getArgument('source'))) { $question_helper = new QuestionHelper(); - $choices = (new CarbonIntensitySource())->getDownloadableSources(); + $choices = (new Source())->getDownloadableSources(); $choices = ClientFactory::getClientNames(); $question = new ChoiceQuestion(__('Source:', 'carbon'), array_values($choices)); $value = $question_helper->ask($input, $output, $question); @@ -118,7 +118,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln("$message"); // Create the source if it does not exist - $data_source = new CarbonIntensitySource(); + $data_source = new Source(); $source_name = $input->getArgument('source'); if (!$data_source->getFromDBByCrit(['name' => $source_name])) { $data_source->add([ @@ -139,7 +139,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (!$zone->getID()) { $zone->add([ 'name' => $this->zones[$zone_code], - 'plugin_carbon_carbonintensitysources_id_historical' => $data_source->getID(), + 'plugin_carbon_sources_id_historical' => $data_source->getID(), ]); if ($zone->isNewItem()) { $message = __("Zone not found", 'carbon'); @@ -150,7 +150,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $carbon_intensity = new CarbonIntensity(); // Create relation between source and zone if t does not exist - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $input = [ 'code' => $zone_code, $data_source::getForeignKeyField() => $data_source->getID(), diff --git a/src/Command/CreateFakeCarbonIntensityCommand.php b/src/Command/CreateFakeCarbonIntensityCommand.php index 8090b8f9..b65ef0b3 100644 --- a/src/Command/CreateFakeCarbonIntensityCommand.php +++ b/src/Command/CreateFakeCarbonIntensityCommand.php @@ -37,7 +37,7 @@ use DateTimeZone; use GlpiPlugin\Carbon\CarbonIntensity; use GlpiPlugin\Carbon\Zone; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputInterface; @@ -66,7 +66,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $message = __("Creating data source name", 'carbon'); $output->writeln("$message"); - $dataSource = new CarbonIntensitySource(); + $dataSource = new Source(); $source_name = 'Fake data'; if (!$dataSource->getFromDBByCrit(['name' => $source_name])) { $dataSource->add([ @@ -117,7 +117,7 @@ protected function generateFakeData(DateTime $start_date, DateTime $end_date) $carbon_intensity = new CarbonIntensity(); foreach ($intensities as $date => $intensity) { $carbon_intensity->add([ - 'plugin_carbon_carbonintensitysources_id' => $this->source_id, + 'plugin_carbon_sources_id' => $this->source_id, 'plugin_carbon_zones_id' => $this->zone_id, 'date' => $date, // Eco2mix seems to provide datetime in 'intensity' => $intensity, diff --git a/src/Dashboard/Provider.php b/src/Dashboard/Provider.php index b30c10d0..dbb15e5f 100644 --- a/src/Dashboard/Provider.php +++ b/src/Dashboard/Provider.php @@ -46,7 +46,7 @@ use GlpiPlugin\Carbon\Toolbox; use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\CarbonIntensity; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use GlpiPlugin\Carbon\SearchOptions; use GlpiPlugin\Carbon\UsageImpact; @@ -590,7 +590,7 @@ public static function getCarbonIntensity(array $params): array /** @var DBmysql $DB */ global $DB; - $source = new CarbonIntensitySource(); + $source = new Source(); $zone = new Zone(); $source->getFromDBByCrit([ 'name' => 'RTE' @@ -606,7 +606,7 @@ public static function getCarbonIntensity(array $params): array // ], 'FROM' => CarbonIntensity::getTable(), 'WHERE' => [ - CarbonIntensitySource::getForeignKeyField() => $source->getID(), + Source::getForeignKeyField() => $source->getID(), Zone::getForeignKeyField() => $zone->getID(), ], ]; diff --git a/src/DataSource/Boaviztapi.php b/src/DataSource/Boaviztapi.php index 4db15b7d..15b7cf03 100644 --- a/src/DataSource/Boaviztapi.php +++ b/src/DataSource/Boaviztapi.php @@ -35,8 +35,8 @@ use Config; use DBmysql; use Dropdown; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; class Boaviztapi @@ -99,8 +99,8 @@ public function get(string $endpoint, array $options = []): array public function createSource(): bool { $source_name = $this->getSourceName(); - // create a source in CarbonIntensitySource - $source = new CarbonIntensitySource(); + // create a source in Source + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name, ]); @@ -136,7 +136,7 @@ public function queryZones(): array */ public function saveZones(array $zones): void { - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $this->getSourceName(), ]); @@ -161,14 +161,14 @@ public function saveZones(array $zones): void } else { $zone_id = $zone->getID(); } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone_id = $source_zone->getFromDBByCrit([ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, ]); if ($source_zone_id === false) { $source_zone_id = $source_zone->add([ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, ]); if ($source_zone_id === false) { @@ -190,12 +190,12 @@ public static function getZones() global $DB; $zone_table = Zone::getTable(); - $source_table = CarbonIntensitySource::getTable(); - $source_zone_table = CarbonIntensitySource_Zone::getTable(); + $source_table = Source::getTable(); + $source_zone_table = Source_Zone::getTable(); $result = $DB->request([ 'SELECT' => [ Zone::getTableField('name'), - CarbonIntensitySource_Zone::getTableField('code'), + Source_Zone::getTableField('code'), ], 'FROM' => Zone::getTable(), 'INNER JOIN' => [ @@ -207,13 +207,13 @@ public static function getZones() ], $source_table => [ 'FKEY' => [ - $source_zone_table => 'plugin_carbon_carbonintensitysources_id', - CarbonIntensitySource::getTable() => 'id', + $source_zone_table => 'plugin_carbon_sources_id', + Source::getTable() => 'id', ], ], ], 'WHERE' => [ - CarbonIntensitySource::getTableField('name') => self::$source_name, + Source::getTableField('name') => self::$source_name, ], 'ORDER' => Zone::getTableField('name'), ]); diff --git a/src/DataSource/CarbonIntensity/AbstractClient.php b/src/DataSource/CarbonIntensity/AbstractClient.php index 415a460b..619f862f 100644 --- a/src/DataSource/CarbonIntensity/AbstractClient.php +++ b/src/DataSource/CarbonIntensity/AbstractClient.php @@ -39,8 +39,8 @@ use DateTimeImmutable; use Toolbox as GlpiToolbox; use GlpiPlugin\Carbon\CarbonIntensity; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; use Symfony\Component\Console\Helper\ProgressBar; @@ -58,11 +58,11 @@ abstract protected function formatOutput(array $response, int $step): array; * Create the source in the database * Should not be called as it shall be created at plugin installation * - * @return CarbonIntensitySource + * @return Source */ - protected function getOrCreateSource(): ?CarbonIntensitySource + protected function getOrCreateSource(): ?Source { - $source = new CarbonIntensitySource(); + $source = new Source(); if (!$source->getFromDBByCrit(['name' => $this->getSourceName()])) { $source->add([ 'name' => $this->getSourceName(), @@ -146,11 +146,11 @@ public function getZones(array $crit = []): array /** @var DBmysql $DB */ global $DB; - $source_table = CarbonIntensitySource::getTable(); - $source_fk = CarbonIntensitySource::getForeignKeyField(); + $source_table = Source::getTable(); + $source_fk = Source::getForeignKeyField(); $zone_table = Zone::getTable(); $zone_fk = Zone::getForeignKeyField(); - $source_zone_table = CarbonIntensitySource_Zone::getTable(); + $source_zone_table = Source_Zone::getTable(); $iterator = $DB->request([ 'SELECT' => Zone::getTableField('name'), 'FROM' => $zone_table, @@ -169,7 +169,7 @@ public function getZones(array $crit = []): array ], ], 'WHERE' => [ - CarbonIntensitySource::getTableField('name') => $this->getSourceName(), + Source::getTableField('name') => $this->getSourceName(), ] + $crit, ]); @@ -310,9 +310,9 @@ protected function sliceDateRangeByDay(DateTimeImmutable $start, DateTimeImmutab } } - protected function toggleZoneDownload(Zone $zone, CarbonIntensitySource $source, ?bool $state): bool + protected function toggleZoneDownload(Zone $zone, Source $source, ?bool $state): bool { - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ $zone->getForeignKeyField() => $zone->getID(), $source->getForeignKeyField() => $source->getID(), diff --git a/src/DataSource/CarbonIntensity/ElectricityMapClient.php b/src/DataSource/CarbonIntensity/ElectricityMapClient.php index b9c05570..becb6ee9 100644 --- a/src/DataSource/CarbonIntensity/ElectricityMapClient.php +++ b/src/DataSource/CarbonIntensity/ElectricityMapClient.php @@ -38,9 +38,9 @@ use DateTimeZone; use DateTimeImmutable; use GlpiPlugin\Carbon\CarbonIntensity; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source_Zone; use Config as GlpiConfig; use GLPIKey; use GlpiPlugin\Carbon\DataSource\RestApiClientInterface; @@ -120,16 +120,16 @@ public function createZones(): int $zone = new Zone(); if ($zone->getFromDbByCrit($zone_input) === false) { if ($this->enableHistorical($zone_spec['zoneName'])) { - $zone_input['plugin_carbon_carbonintensitysources_id_historical'] = $source_id; + $zone_input['plugin_carbon_sources_id_historical'] = $source_id; } if ($zone->add($zone_input) === false) { $failed = true; continue; } } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->add([ - CarbonIntensitySource::getForeignKeyField() => $source_id, + Source::getForeignKeyField() => $source_id, Zone::getForeignKeyField() => $zone->getID(), 'code' => $zone_key, 'is_download_enabled' => Toolbox::isLocationExistForZone($zone->fields['name']), @@ -212,7 +212,7 @@ public function getSupportedZones(): array */ public function fetchDay(DateTimeImmutable $day, string $zone): array { - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $zone_code = $source_zone->getFromDbBySourceAndZone($this->getSourceName(), $zone); if ($zone_code === null) { diff --git a/src/DataSource/CarbonIntensity/RteClient.php b/src/DataSource/CarbonIntensity/RteClient.php index 773a9137..72d65edc 100644 --- a/src/DataSource/CarbonIntensity/RteClient.php +++ b/src/DataSource/CarbonIntensity/RteClient.php @@ -38,9 +38,9 @@ use DateTimeInterface; use DateTimeZone; use DBmysql; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; use GlpiPlugin\Carbon\DataSource\RestApiClientInterface; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; use GlpiPlugin\Carbon\DataTracking\AbstractTracked; use GlpiPlugin\Carbon\Toolbox; @@ -118,21 +118,21 @@ public function createZones(): int 'name' => 'France', ]; if ($zone->getFromDBByCrit($input) === false) { - $input['plugin_carbon_carbonintensitysources_id_historical'] = $source_id; + $input['plugin_carbon_sources_id_historical'] = $source_id; if (!$zone->add($input)) { return -1; } } else { - if ($zone->fields['plugin_carbon_carbonintensitysources_id_historical'] == 0) { - $input['plugin_carbon_carbonintensitysources_id_historical'] = $source_id; + if ($zone->fields['plugin_carbon_sources_id_historical'] == 0) { + $input['plugin_carbon_sources_id_historical'] = $source_id; $input['id'] = $zone->getID(); } $zone->update($input); } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->add([ - CarbonIntensitySource::getForeignKeyField() => $source_id, + Source::getForeignKeyField() => $source_id, Zone::getForeignKeyField() => $zone->getID(), 'is_download_enabled' => Toolbox::isLocationExistForZone($zone->fields['name']), ]); diff --git a/src/Engine/V1/AbstractAsset.php b/src/Engine/V1/AbstractAsset.php index 1c13efa9..ef6434dc 100644 --- a/src/Engine/V1/AbstractAsset.php +++ b/src/Engine/V1/AbstractAsset.php @@ -41,8 +41,8 @@ use DbUtils; use DBmysql; use GlpiPlugin\Carbon\CarbonIntensity; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\DataTracking\TrackedInt; use GlpiPlugin\Carbon\Zone; use Glpi\DBAL\QueryExpression; @@ -112,7 +112,7 @@ protected function requestCarbonIntensitiesPerDay(DateTimeImmutable $start_time, 'WHERE' => [ 'AND' => [ CarbonIntensity::getTableField('plugin_carbon_zones_id') => $zone->getID(), - CarbonIntensity::getTableField('plugin_carbon_carbonintensitysources_id') => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], + CarbonIntensity::getTableField('plugin_carbon_sources_id') => $zone->fields['plugin_carbon_sources_id_historical'], [CarbonIntensity::getTableField('date') => ['>=', $start_date_s]], [CarbonIntensity::getTableField('date') => ['<', $stop_date_s]], ], @@ -192,8 +192,8 @@ protected function getFallbackCarbonIntensity(DateTimeInterface $day, Zone $zone global $DB; $carbon_intensity_table = CarbonIntensity::getTable(); - $carbon_intensity_source_zone_table = CarbonIntensitySource_Zone::getTable(); - $carbon_intensity_source_table = CarbonIntensitySource::getTable(); + $carbon_intensity_source_zone_table = Source_Zone::getTable(); + $carbon_intensity_source_table = Source::getTable(); $request = [ 'SELECT' => "$carbon_intensity_table.*", 'FROM' => $carbon_intensity_table, @@ -206,15 +206,15 @@ protected function getFallbackCarbonIntensity(DateTimeInterface $day, Zone $zone ], $carbon_intensity_source_table => [ 'FKEY' => [ - $carbon_intensity_source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $carbon_intensity_source_zone_table => 'plugin_carbon_sources_id', $carbon_intensity_source_table => 'id', ] ] ], 'WHERE' => [ - CarbonIntensitySource::getTableField('is_fallback') => 1, - 'NOT' => [CarbonIntensitySource::getTableField('name') => 'Ember - Energy Institute'], - CarbonIntensitySource_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), + Source::getTableField('is_fallback') => 1, + 'NOT' => [Source::getTableField('name') => 'Ember - Energy Institute'], + Source_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), CarbonIntensity::getTableField('date') => ['<=', $day->format('Y-m-d H:i:s')], ], 'ORDER' => CarbonIntensity::getTableField('date') . ' DESC', @@ -237,8 +237,8 @@ protected function getFallbackCarbonIntensityFromEmber(DateTimeInterface $day, Z global $DB; $carbon_intensity_table = CarbonIntensity::getTable(); - $carbon_intensity_source_zone_table = CarbonIntensitySource_Zone::getTable(); - $carbon_intensity_source_table = CarbonIntensitySource::getTable(); + $carbon_intensity_source_zone_table = Source_Zone::getTable(); + $carbon_intensity_source_table = Source::getTable(); $request = [ 'SELECT' => "$carbon_intensity_table.*", 'FROM' => $carbon_intensity_table, @@ -251,15 +251,15 @@ protected function getFallbackCarbonIntensityFromEmber(DateTimeInterface $day, Z ], $carbon_intensity_source_table => [ 'FKEY' => [ - $carbon_intensity_source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $carbon_intensity_source_zone_table => 'plugin_carbon_sources_id', $carbon_intensity_source_table => 'id', ] ] ], 'WHERE' => [ - CarbonIntensitySource::getTableField('is_fallback') => 1, - CarbonIntensitySource::getTableField('name') => 'Ember - Energy Institute', - CarbonIntensitySource_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), + Source::getTableField('is_fallback') => 1, + Source::getTableField('name') => 'Ember - Energy Institute', + Source_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), CarbonIntensity::getTableField('date') => ['<=', $day->format('Y-m-d H:i:s')], ], 'ORDER' => CarbonIntensity::getTableField('date') . ' DESC', @@ -288,8 +288,8 @@ public function getFallbackCarbonIntensityForEmberWorldwide(DateTimeInterface $d global $DB; $carbon_intensity_table = CarbonIntensity::getTable(); - $carbon_intensity_source_zone_table = CarbonIntensitySource_Zone::getTable(); - $carbon_intensity_source_table = CarbonIntensitySource::getTable(); + $carbon_intensity_source_zone_table = Source_Zone::getTable(); + $carbon_intensity_source_table = Source::getTable(); $carbon_intensity_zone_table = Zone::getTable(); $request = [ 'SELECT' => "$carbon_intensity_table.*", @@ -303,7 +303,7 @@ public function getFallbackCarbonIntensityForEmberWorldwide(DateTimeInterface $d ], $carbon_intensity_source_table => [ 'FKEY' => [ - $carbon_intensity_source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $carbon_intensity_source_zone_table => 'plugin_carbon_sources_id', $carbon_intensity_source_table => 'id', ] ], @@ -315,14 +315,14 @@ public function getFallbackCarbonIntensityForEmberWorldwide(DateTimeInterface $d ], $carbon_intensity_source_table => [ 'FKEY' => [ - $carbon_intensity_table => 'plugin_carbon_carbonintensitysources_id', + $carbon_intensity_table => 'plugin_carbon_sources_id', $carbon_intensity_source_table => 'id', ] ], ], 'WHERE' => [ - CarbonIntensitySource::getTableField('is_fallback') => 1, - CarbonIntensitySource::getTableField('name') => 'Ember - Energy Institute', + Source::getTableField('is_fallback') => 1, + Source::getTableField('name') => 'Ember - Energy Institute', Zone::getTableField('name') => 'World', CarbonIntensity::getTableField('date') => ['<=', $day->format('Y-m-d H:i:s')], ], diff --git a/src/Location.php b/src/Location.php index c8e039d1..f4bc4317 100644 --- a/src/Location.php +++ b/src/Location.php @@ -216,10 +216,10 @@ protected function enableCarbonIntensityDownload(CommonDBTM $item): bool if ($zone === null) { return false; } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ Zone::getForeignKeyField() => $zone->fields['id'], - CarbonIntensitySource::getForeignKeyField() => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], + Source::getForeignKeyField() => $zone->fields['plugin_carbon_sources_id_historical'], ]); if ($source_zone->isNewItem()) { return false; @@ -239,10 +239,10 @@ public function isCarbonIntensityDownloadEnabled(CommonDBTM $item): bool if ($zone === null) { return false; } - $source_zone = new CarbonIntensitySource_Zone(); + $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ Zone::getForeignKeyField() => $zone->fields['id'], - CarbonIntensitySource::getForeignKeyField() => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], + Source::getForeignKeyField() => $zone->fields['plugin_carbon_carbonintensitysources_id_historical'], ]); if ($source_zone->isNewItem()) { return false; @@ -266,8 +266,8 @@ public function hasFallbackCarbonIntensityData(CommonDBTM $item): bool return false; } $carbon_intensity_table = CarbonIntensity::getTable(); - $carbon_intensity_source_zone_table = CarbonIntensitySource_Zone::getTable(); - $carbon_intensity_source_table = CarbonIntensitySource::getTable(); + $carbon_intensity_source_zone_table = Source_Zone::getTable(); + $carbon_intensity_source_table = Source::getTable(); $request = [ 'COUNT' => 'count', 'FROM' => $carbon_intensity_table, @@ -286,8 +286,8 @@ public function hasFallbackCarbonIntensityData(CommonDBTM $item): bool ] ], 'WHERE' => [ - CarbonIntensitySource::getTableField('is_fallback') => 1, - CarbonIntensitySource_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), + Source::getTableField('is_fallback') => 1, + Source_Zone::getTableField('plugin_carbon_zones_id') => $zone->getID(), ], 'ORDER' => CarbonIntensity::getTableField('date') . ' DESC', 'LIMIT' => 1, diff --git a/src/Source.php b/src/Source.php index e4d319d0..8af03bf6 100644 --- a/src/Source.php +++ b/src/Source.php @@ -39,7 +39,7 @@ use DBmysql; use Session; -class CarbonIntensitySource extends CommonDropdown +class Source extends CommonDropdown { public static function getTypeName($nb = 0) { @@ -82,7 +82,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) case Zone::class: if ($_SESSION['glpishow_count_on_tabs']) { $nb = (new DbUtils())->countElementsInTable( - CarbonIntensitySource_Zone::getTable(), + Source_Zone::getTable(), [self::getForeignKeyField() => $item->getID()] ); } @@ -98,7 +98,7 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ /** @var CommonDBTM $item */ switch ($item->getType()) { case Zone::class: - CarbonIntensitySource_Zone::showForZone($item); + Source_Zone::showForZone($item); } return true; diff --git a/src/Source_Zone.php b/src/Source_Zone.php index 10081e5f..cf1a6e7b 100644 --- a/src/Source_Zone.php +++ b/src/Source_Zone.php @@ -41,10 +41,10 @@ use Glpi\Application\View\TemplateRenderer; use Html; -class CarbonIntensitySource_Zone extends CommonDBRelation +class Source_Zone extends CommonDBRelation { - public static $itemtype_1 = CarbonIntensitySource::class; // Type ref or field name (must start with itemtype) - public static $items_id_1 = 'plugin_carbon_carbonintensitysources_id'; // Field name + public static $itemtype_1 = Source::class; // Type ref or field name (must start with itemtype) + public static $items_id_1 = 'plugin_carbon_sources_id'; // Field name public static $checkItem_1_Rights = self::HAVE_SAME_RIGHT_ON_ITEM; public static $itemtype_2 = Zone::class; // Type ref or field name (must start with itemtype) @@ -53,10 +53,10 @@ class CarbonIntensitySource_Zone extends CommonDBRelation public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { - if ($item->getType() === CarbonIntensitySource::class) { + if ($item->getType() === Source::class) { return self::createTabEntry(Zone::getTypeName(), 0); } - return self::createTabEntry(CarbonIntensitySource::getTypeName(), 0); + return self::createTabEntry(Source::getTypeName(), 0); } public function rawSearchOptions() @@ -65,7 +65,7 @@ public function rawSearchOptions() $tab[] = [ 'id' => '5', - 'table' => CarbonIntensitySource::getTable(), + 'table' => Source::getTable(), 'field' => 'name', 'name' => __('Source name', 'carbon'), 'datatype' => 'dropdown', @@ -81,7 +81,7 @@ public function rawSearchOptions() $tab[] = [ 'id' => '7', - 'table' => CarbonIntensitySource::getTable(), + 'table' => Source::getTable(), 'field' => 'is_download_enabled', 'name' => __('Download enabled', 'carbon'), 'datatype' => 'bool', @@ -110,21 +110,21 @@ public static function showForSource(CommonDBTM $item) } $canedit = $item->canEdit($item_id); - $source_table = CarbonIntensitySource::getTable(); + $source_table = Source::getTable(); $zone_table = Zone::getTable(); $source_zone_table = self::getTable(); $iterator = $DB->request([ 'SELECT' => [ $zone_table => 'name', $source_zone_table => ['id', 'is_download_enabled'], - CarbonIntensitySource::getTableField('name') . ' AS historical_source_name', + Source::getTableField('name') . ' AS historical_source_name', $source_table => 'is_fallback' ], 'FROM' => $source_zone_table, 'INNER JOIN' => [ $source_table => [ 'FKEY' => [ - $source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $source_zone_table => 'plugin_carbon_sources_id', $source_table => 'id', ], ], @@ -136,7 +136,7 @@ public static function showForSource(CommonDBTM $item) ], ], 'WHERE' => [ - CarbonIntensitySource::getTableField('id') => $item_id, + Source::getTableField('id') => $item_id, ], 'ORDER' => ['name ASC'], ]); @@ -150,7 +150,7 @@ public static function showForSource(CommonDBTM $item) $is_download_enabled = self::getToggleLink($data['id'], $data['is_download_enabled']); } $entries[] = [ - 'itemtype' => CarbonIntensitySource::class, + 'itemtype' => Source::class, 'id' => $item->getID(), 'name' => $data['name'], 'historical_source_name' => $data['historical_source_name'], @@ -213,8 +213,10 @@ public static function showForZone(CommonDBTM $item) } $canedit = $item->canEdit($item_id); - $source_table = CarbonIntensitySource::getTable(); + $source_table = Source::getTable(); + $source_fk = Source::getForeignKeyField(); $zone_table = Zone::getTable(); + $zone_fk = Zone::getForeignKeyField(); $source_zone_table = self::getTable(); $iterator = $DB->request([ 'SELECT' => [ @@ -225,13 +227,13 @@ public static function showForZone(CommonDBTM $item) 'INNER JOIN' => [ $source_table => [ 'FKEY' => [ - $source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $source_zone_table => $source_fk, $source_table => 'id', ], ], $zone_table => [ 'FKEY' => [ - $source_zone_table => 'plugin_carbon_zones_id', + $source_zone_table => $zone_fk, $zone_table => 'id', ], ], @@ -246,7 +248,7 @@ public static function showForZone(CommonDBTM $item) $entries = []; foreach ($iterator as $data) { $entries[] = [ - 'itemtype' => CarbonIntensitySource::class, + 'itemtype' => Source::class, 'id' => $item->getID(), 'name' => $data['name'], 'is_download_enabled' => self::getToggleLink($data['id'], $data['is_download_enabled']), @@ -307,16 +309,16 @@ public function getFromDbBySourceAndZone(string $source_name, string $zone_name) global $DB; $zone_table = Zone::getTable(); - $source_table = CarbonIntensitySource::getTable(); + $source_table = Source::getTable(); $source_zone_table = self::getTable(); $request = [ - 'SELECT' => CarbonIntensitySource_Zone::getTableField('code'), + 'SELECT' => Source_Zone::getTableField('code'), 'FROM' => $source_zone_table, 'INNER JOIN' => [ $source_table => [ 'ON' => [ $source_table => 'id', - $source_zone_table => CarbonIntensitySource::getForeignKeyField(), + $source_zone_table => Source::getForeignKeyField(), ] ], $zone_table => [ @@ -327,7 +329,7 @@ public function getFromDbBySourceAndZone(string $source_name, string $zone_name) ] ], 'WHERE' => [ - CarbonIntensitySource::getTableField('name') => $source_name, + Source::getTableField('name') => $source_name, Zone::getTableField('name') => $zone_name, ], 'LIMIT' => '1' @@ -361,8 +363,8 @@ protected static function getToggleLink(int $zone_id, ?string $state): string public function toggleZone(?bool $state = null): bool { // Check if the source is a fallback source - $source = new CarbonIntensitySource(); - $source->getFromDB($this->fields['plugin_carbon_carbonintensitysources_id']); + $source = new Source(); + $source->getFromDB($this->fields['plugin_carbon_sources_id']); if ($source->fields['is_fallback'] === 1) { // Fallback sources cannot be toggled return false; diff --git a/src/Zone.php b/src/Zone.php index 542fa47d..b14325a6 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -76,7 +76,7 @@ public static function canPurge(): bool public function defineTabs($options = []) { $tabs = parent::defineTabs($options); - $this->addStandardTab(CarbonIntensitySource::class, $tabs, $options); + $this->addStandardTab(Source::class, $tabs, $options); return $tabs; } @@ -86,11 +86,11 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) $nb = 0; /** @var CommonDBTM $item */ switch ($item->getType()) { - case CarbonIntensitySource::class: + case Source::class: if ($_SESSION['glpishow_count_on_tabs']) { $nb = (new DbUtils())->countElementsInTable( - CarbonIntensitySource_Zone::getTable(), - [CarbonIntensitySource::getForeignKeyField() => $item->getID()] + Source_Zone::getTable(), + [Source::getForeignKeyField() => $item->getID()] ); } return self::createTabEntry(self::getTypeName(Session::getPluralNumber()), $nb); @@ -111,8 +111,8 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ { /** @var CommonDBTM $item */ switch ($item->getType()) { - case CarbonIntensitySource::class: - CarbonIntensitySource_Zone::showForSource($item); + case Source::class: + Source_Zone::showForSource($item); } return true; @@ -122,7 +122,7 @@ public function getAdditionalFields() { return [ [ - 'name' => 'plugin_carbon_carbonintensitysources_id_historical', + 'name' => 'plugin_carbon_sources_id_historical', 'label' => __('Data source for historical calculation', 'carbon'), 'type' => 'dropdownValue', 'list' => true @@ -136,13 +136,13 @@ public function rawSearchOptions() $tab[] = [ 'id' => SearchOptions::HISTORICAL_DATA_SOURCE, - 'table' => CarbonIntensitySource::getTable(), + 'table' => Source::getTable(), 'field' => 'name', 'name' => __('Data source for historical calculation', 'carbon'), 'datatype' => 'dropdown', 'joinparams' => [ 'beforejoin' => [ - 'table' => CarbonIntensitySource_Zone::getTable(), + 'table' => Source_Zone::getTable(), 'joinparams' => [ 'jointype' => 'child', ], @@ -152,7 +152,7 @@ public function rawSearchOptions() $tab[] = [ 'id' => SearchOptions::HISTORICAL_DATA_DL_ENABLED, - 'table' => CarbonIntensitySource_Zone::getTable(), + 'table' => Source_Zone::getTable(), 'field' => 'is_download_enabled', 'name' => __('Download enabled', 'carbon'), 'datatype' => 'bool', @@ -298,11 +298,11 @@ public function hasHistoricalData(): bool if ($this->isNewItem()) { return false; } - if (!isset($this->fields['plugin_carbon_carbonintensitysources_id_historical'])) { + if (!isset($this->fields['plugin_carbon_sources_id_historical'])) { return false; } - $source = new CarbonIntensitySource(); - if (!$source->getFromDB($this->fields['plugin_carbon_carbonintensitysources_id_historical'])) { + $source = new Source(); + if (!$source->getFromDB($this->fields['plugin_carbon_sources_id_historical'])) { // source does not exists return false; } diff --git a/tests/install/PluginInstallTest.php b/tests/install/PluginInstallTest.php index 5720f222..b523582d 100644 --- a/tests/install/PluginInstallTest.php +++ b/tests/install/PluginInstallTest.php @@ -48,7 +48,6 @@ use Glpi\DBAL\QueryExpression as QueryExpression; use Glpi\Plugin\Hooks; use Glpi\System\Diagnostic\DatabaseSchemaIntegrityChecker; -use Glpi\Toolbox\Sanitizer; use GlpiPlugin\Carbon\CarbonIntensity; use GlpiPlugin\Carbon\CarbonIntensitySource; use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; @@ -347,7 +346,7 @@ private function checkInitialDataSources() { $sources = ['RTE', 'ElectricityMap']; foreach ($sources as $source_name) { - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name, 'is_fallback' => 0 @@ -357,7 +356,7 @@ private function checkInitialDataSources() $sources = ['Ember - Energy Institute', 'Hydro Quebec']; foreach ($sources as $source_name) { - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name, 'is_fallback' => 1 @@ -399,7 +398,7 @@ private function checkInitialCarbonIntensities() // Find the source for Ember - Energy Institute $source_name = 'Ember - Energy Institute'; - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name, ]); @@ -426,7 +425,7 @@ private function checkInitialCarbonIntensities() // Find the source for Hydro Quebec $source_name = 'Hydro Quebec'; - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit([ 'name' => $source_name ]); @@ -443,10 +442,10 @@ private function checkInitialCarbonIntensities() $this->assertEquals(1, $count); // Check all sources and zones are linked together via source_zone table - $source_zone_table = getTableForItemType(CarbonIntensitySource_Zone::class); + $source_zone_table = getTableForItemType(Source_Zone::class); $zone_table = $dbUtils->getTableForItemType(Zone::class); - $source_table = $dbUtils->getTableForItemType(CarbonIntensitySource::class); - $source_fk = getForeignKeyFieldForItemType(CarbonIntensitySource::class); + $source_table = $dbUtils->getTableForItemType(Source::class); + $source_fk = getForeignKeyFieldForItemType(Source::class); $zone_fk = getForeignKeyFieldForItemType(Zone::class); $iterator = $DB->request([ 'SELECT' => '*', @@ -779,9 +778,9 @@ public function checkSourceZoneRelation() /** @var DBmysql */ global $DB; - $source_table = CarbonIntensitySource::getTable(); + $source_table = Source::getTable(); $zone_table = Zone::getTable(); - $source_zone_table = CarbonIntensitySource_Zone::getTable(); + $source_zone_table = Source_Zone::getTable(); $iterator = $DB->request([ 'SELECT' => $source_zone_table . '.id', @@ -789,7 +788,7 @@ public function checkSourceZoneRelation() 'INNER JOIN' => [ $source_table => [ 'FKEY' => [ - $source_zone_table => 'plugin_carbon_carbonintensitysources_id', + $source_zone_table => 'plugin_carbon_sources_id', $source_table => 'id' ] ], diff --git a/tests/integration/SearchOptionTest.php b/tests/integration/SearchOptionTest.php index d00f0ef7..d95d8fb5 100644 --- a/tests/integration/SearchOptionTest.php +++ b/tests/integration/SearchOptionTest.php @@ -51,8 +51,8 @@ #[CoversMethod('GlpiPlugin\Carbon\CarbonEmission', 'rawSearchOptions')] #[CoversMethod('GlpiPlugin\Carbon\CarbonIntensity', 'rawSearchOptions')] -#[CoversMethod('GlpiPlugin\Carbon\CarbonIntensitySource', 'rawSearchOptions')] -#[CoversMethod('GlpiPlugin\Carbon\CarbonIntensitySource_Zone', 'rawSearchOptions')] +#[CoversMethod('GlpiPlugin\Carbon\Source', 'rawSearchOptions')] +#[CoversMethod('GlpiPlugin\Carbon\Source_Zone', 'rawSearchOptions')] #[CoversMethod('GlpiPlugin\Carbon\ComputerUsageProfile', 'rawSearchOptions')] #[CoversMethod('GlpiPlugin\Carbon\EmbodiedImpact', 'rawSearchOptions')] #[CoversMethod('GlpiPlugin\Carbon\UsageImpact', 'rawSearchOptions')] @@ -85,11 +85,11 @@ class SearchOptionTest extends CommonTestCase private array $mapping = [ CarbonIntensity::class => [ - 'plugin_carbon_carbonintensitysources_id' => 'name', + 'plugin_carbon_sources_id' => 'name', 'plugin_carbon_zones_id' => 'name', ], Zone::class => [ - 'plugin_carbon_carbonintensitysources_id_historical' => 'name', + 'plugin_carbon_sources_id_historical' => 'name', ] ]; diff --git a/tests/src/CommonTestCase.php b/tests/src/CommonTestCase.php index bc9c5666..cae37c43 100644 --- a/tests/src/CommonTestCase.php +++ b/tests/src/CommonTestCase.php @@ -46,7 +46,7 @@ use GlpiPlugin\Carbon\UsageInfo; use GlpiPlugin\Carbon\ComputerUsageProfile; use GlpiPlugin\Carbon\ComputerType; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use GlpiPlugin\Carbon\CarbonIntensity; use Entity; @@ -286,10 +286,10 @@ protected function createComputerUsageProfilePowerLocation(array $usage_profile_ protected function createCarbonIntensityData(string $country, string $source_name, DateTimeInterface $begin_date, float $intensity, string $length = 'P2D') { - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit(['name' => $source_name]); if ($source->isNewItem()) { - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => $source_name ]); } @@ -299,7 +299,7 @@ protected function createCarbonIntensityData(string $country, string $source_nam if ($zone->isNewItem()) { $zone = $this->createItem(Zone::class, [ 'name' => $country, - 'plugin_carbon_carbonintensitysources_id_historical' => $source->getID() + 'plugin_carbon_sources_id_historical' => $source->getID() ]); } @@ -310,7 +310,7 @@ protected function createCarbonIntensityData(string $country, string $source_nam $one_hour = new DateInterval('PT1H'); while ($current_date < $end_date) { $crit = [ - CarbonIntensitySource::getForeignKeyField() => $source->getID(), + Source::getForeignKeyField() => $source->getID(), Zone::getForeignKeyField() => $zone->getID(), 'date' => $current_date->format('Y-m-d H:00:00'), 'intensity' => $intensity, diff --git a/tests/src/GlobalFixture.php b/tests/src/GlobalFixture.php index cd6abbe1..531fa4c8 100644 --- a/tests/src/GlobalFixture.php +++ b/tests/src/GlobalFixture.php @@ -71,7 +71,7 @@ public static function loadDataset() Config::setConfigurationValues('core', ['timezone' => 'Europe/Paris']); $DB->beginTransaction(); - $source_table = 'glpi_plugin_carbon_carbonintensitysources'; + $source_table = 'glpi_plugin_carbon_sources'; $fake_source_name = 'Fake source'; $iterator = $DB->request([ 'SELECT' => ['id'], @@ -101,24 +101,24 @@ public static function loadDataset() if ($iterator->count() === 0) { $result = $DB->insert($zone_table, [ 'name' => $fake_zone_name, - 'plugin_carbon_carbonintensitysources_id_historical' => $source_id, + 'plugin_carbon_sources_id_historical' => $source_id, ]); $zone_id = $DB->insertId(); } else { $zone_id = $iterator->current()['id']; } - $source_zone_table = 'glpi_plugin_carbon_carbonintensitysources_zones'; + $source_zone_table = 'glpi_plugin_carbon_sources_zones'; $iterator = $DB->request([ 'SELECT' => ['id'], 'FROM' => $source_zone_table, 'WHERE' => [ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, ], ]); if ($iterator->count() === 0) { $result = $DB->insert($source_zone_table, [ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, 'code' => 'FZ', ]); @@ -135,7 +135,7 @@ public static function loadDataset() } while (($row = fgetcsv($handle, 256, ',', '"', '\\')) !== false) { $DB->insert($intensity_table, [ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, 'date' => $row[0], 'intensity' => $row[1], @@ -143,7 +143,7 @@ public static function loadDataset() } // ini_set('auto_detect_line_endings', $line_ending_mode); $condition = [ - 'plugin_carbon_carbonintensitysources_id' => $source_id, + 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, ]; $count = (new DbUtils())->countElementsInTable($intensity_table, $condition); diff --git a/tests/units/CarbonIntensityTest.php b/tests/units/CarbonIntensityTest.php index 2c6a3793..23ff95f2 100644 --- a/tests/units/CarbonIntensityTest.php +++ b/tests/units/CarbonIntensityTest.php @@ -39,8 +39,8 @@ use GlpiPlugin\Carbon\CarbonIntensity; use GlpiPlugin\Carbon\Tests\DbTestCase; use GlpiPlugin\Carbon\Zone; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\DataSource\AbstractCarbonIntensity; use GlpiPlugin\Carbon\DataSource\CarbonIntensity\AbstractClient; use Infocom; @@ -60,10 +60,10 @@ public function testGetLastKnownDate() $zone = $this->createItem(Zone::class, [ 'name' => 'foo', ]); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'bar' ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID() ]); @@ -98,10 +98,10 @@ public function testGetFirstKnownDate() $zone = $this->createItem(Zone::class, [ 'name' => 'foo', ]); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'bar' ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID() ]); @@ -147,15 +147,15 @@ public function testFindGaps() $this->login('glpi', 'glpi'); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'test_source', ]); $zone = $this->createItem(Zone::class, [ 'name' => 'test_zone', - 'plugin_carbon_carbonintensitysources_id_historical' => $source->getID(), + 'plugin_carbon_sources_id_historical' => $source->getID(), ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + $source_zone = $this->createItem(Source_Zone::class, [ + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), ]); @@ -167,7 +167,7 @@ public function testFindGaps() while ($cursor_date < $end_date) { $DB->insert($table, [ 'date' => $cursor_date->format('Y-m-d H:i:s'), - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'intensity' => 1, ]); @@ -181,7 +181,7 @@ public function testFindGaps() // delete some samples at the beginning $delete_before_date = new DateTime('2024-01-03 12:00:00'); $DB->delete($table, [ - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'date' => ['<', $delete_before_date->format('Y-m-d H:i:s')], ]); @@ -197,7 +197,7 @@ public function testFindGaps() // delete some samples at the end $delete_after_date = new DateTime('2024-02-17 09:00:00'); $DB->delete($table, [ - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'date' => ['>=', $delete_after_date->format('Y-m-d H:i:s')], ]); @@ -217,7 +217,7 @@ public function testFindGaps() $delete_middle_start_date = new DateTime('2024-01-29 06:00:00'); $delete_middle_end_date = new DateTime('2024-02-05 18:00:00'); $DB->delete($table, [ - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'AND' => [ ['date' => ['>=', $delete_middle_start_date->format('Y-m-d H:i:s')]], @@ -245,7 +245,7 @@ public function testFindGaps() while ($cursor_date < $delete_before_date) { $DB->insert($table, [ 'date' => $cursor_date->format('Y-m-d H:i:s'), - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'intensity' => 1, ]); @@ -269,7 +269,7 @@ public function testFindGaps() while ($cursor_date < $delete_middle_end_date) { $DB->insert($table, [ 'date' => $cursor_date->format('Y-m-d H:i:s'), - 'plugin_carbon_carbonintensitysources_id' => $source->getID(), + 'plugin_carbon_sources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'intensity' => 1, ]); @@ -324,11 +324,11 @@ public function testGetDownloadStopDate() $zone = $this->createItem(Zone::class, [ 'name' => 'foo', ]); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'bar' ]); $expected = new DateTimeImmutable('2019-01-31 23:00:00'); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID(), ]); @@ -352,10 +352,10 @@ public function testDownloadOneZone() $zone = $this->createItem(Zone::class, [ 'name' => 'foo', ]); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'bar' ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID() ]); diff --git a/tests/units/DataSource/CarbonIntensity/ElectricityMapClientTest.php b/tests/units/DataSource/CarbonIntensity/ElectricityMapClientTest.php index 358c0c40..7be47381 100644 --- a/tests/units/DataSource/CarbonIntensity/ElectricityMapClientTest.php +++ b/tests/units/DataSource/CarbonIntensity/ElectricityMapClientTest.php @@ -34,11 +34,11 @@ use GlpiPlugin\Carbon\DataSource\CarbonIntensity\ElectricityMapClient; use GlpiPlugin\Carbon\DataSource\RestApiClientInterface; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use GlpiPlugin\Carbon\Tests\DbTestCase; use DateTimeImmutable; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source_Zone; class ElectricityMapClientTest extends DbTestCase { @@ -75,14 +75,14 @@ public function testFetchDay() /** @var RestApiClientInterface $client */ $data_source = new ElectricityMapClient($client); - $source = new CarbonIntensitySource(); + $source = new Source(); $source->getFromDBByCrit(['name' => $data_source->getSourceName()]); $this->assertFalse($source->isNewItem()); $zone = new Zone(); $zone->getFromDbByCrit(['name' => 'France']); $this->assertFalse($zone->isNewItem()); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ - CarbonIntensitySource::getForeignKeyField() => $source->getID(), + $source_zone = $this->createItem(Source_Zone::class, [ + Source::getForeignKeyField() => $source->getID(), Zone::getForeignKeyField() => $zone->getID(), 'code' => 'FR' ]); diff --git a/tests/units/LocationTest.php b/tests/units/LocationTest.php index fcd283ba..18684555 100644 --- a/tests/units/LocationTest.php +++ b/tests/units/LocationTest.php @@ -40,8 +40,8 @@ use Geocoder\Model\AdminLevelCollection; use Geocoder\Model\Country; use Geocoder\Provider\Nominatim\Model\NominatimAddress; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; use Location as GlpiLocation; use GlpiPlugin\Carbon\Location; @@ -277,14 +277,14 @@ public function testEnableCarbonIntensityDownload() $this->assertFalse($result); // Test when the zone does not matchs a source - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'bar', ]); $zone = $this->createItem(Zone::class, [ 'name' => 'foo', - 'plugin_carbon_carbonintensitysources_id_historical' => 0, + 'plugin_carbon_sources_id_historical' => 0, ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $zone::getForeignKeyField() => $zone->getID(), $source::getForeignKeyField() => $source->getID(), 'is_download_enabled' => 0, @@ -296,14 +296,14 @@ public function testEnableCarbonIntensityDownload() $this->assertFalse($result); // Test when the zone matches a source and download switches to enabled - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'baz', ]); $zone = $this->createItem(Zone::class, [ 'name' => 'baz', - 'plugin_carbon_carbonintensitysources_id_historical' => $source->getID(), + 'plugin_carbon_sources_id_historical' => $source->getID(), ]); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ $zone::getForeignKeyField() => $zone->getID(), $source::getForeignKeyField() => $source->getID(), 'is_download_enabled' => 0, @@ -338,12 +338,12 @@ public function testIsCarbonIntensityDownloadEnabled() $this->assertFalse($result); // Test with a core location with a country and the relation zource / zone exists, download disabled - $source_zone = new CarbonIntensitySource_Zone(); - $source = new CarbonIntensitySource(); + $source_zone = new Source_Zone(); + $source = new Source(); $source->getFromDBByCrit(['name' => 'RTE']); $zone = new Zone(); $zone->getFromDBByCrit(['name' => 'France']); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source_zone = $this->createItem(Source_Zone::class, [ 'plugin_carbon_carbonintensitysources_id' => $source->getID(), 'plugin_carbon_zones_id' => $zone->getID(), 'is_download_enabled' => 0, diff --git a/tests/units/SourceTest.php b/tests/units/SourceTest.php index f7589969..75826323 100644 --- a/tests/units/SourceTest.php +++ b/tests/units/SourceTest.php @@ -33,75 +33,75 @@ namespace GlpiPlugin\Carbon\Tests; use Computer; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; use Log; use Session; -class CarbonIntensitySourceTest extends DbTestCase +class SourceTest extends DbTestCase { /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::getTypeName + * #CoversMethod \GlpiPlugin\Carbon\Source::getTypeName */ public function testGetTypeName() { - $result = CarbonIntensitySource::getTypeName(1); + $result = Source::getTypeName(1); $this->assertEquals('Carbon intensity source', $result); - $result = CarbonIntensitySource::getTypeName(Session::getPluralNumber()); + $result = Source::getTypeName(Session::getPluralNumber()); $this->assertEquals('Carbon intensity sources', $result); } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::canCreate + * #CoversMethod \GlpiPlugin\Carbon\Source::canCreate */ public function testCanCreate() { $this->login('glpi', 'glpi'); - $result = CarbonIntensitySource::canCreate(); + $result = Source::canCreate(); $this->assertFalse($result); } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::canUpdate + * #CoversMethod \GlpiPlugin\Carbon\Source::canUpdate */ public function testCanUpdate() { $this->login('glpi', 'glpi'); - $result = CarbonIntensitySource::canUpdate(); + $result = Source::canUpdate(); $this->assertFalse($result); } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::canDelete + * #CoversMethod \GlpiPlugin\Carbon\Source::canDelete */ public function testCanDelete() { $this->login('glpi', 'glpi'); - $result = CarbonIntensitySource::canDelete(); + $result = Source::canDelete(); $this->assertFalse($result); } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::canPurge + * #CoversMethod \GlpiPlugin\Carbon\Source::canPurge */ public function testCanPurge() { $this->login('glpi', 'glpi'); - $result = CarbonIntensitySource::canPurge(); + $result = Source::canPurge(); $this->assertFalse($result); } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::defineTabs + * #CoversMethod \GlpiPlugin\Carbon\Source::defineTabs */ public function testDefineTabs() { $this->login('glpi', 'glpi'); - $instance = new CarbonIntensitySource(); + $instance = new Source(); $result = $instance->defineTabs(); - $this->assertStringContainsString('Carbon intensity source', $result[CarbonIntensitySource::class . '$main']); + $this->assertStringContainsString('Carbon intensity source', $result[Source::class . '$main']); $this->assertStringContainsString('Carbon intensity zones', $result[Zone::class . '$1']); $this->assertStringContainsString('Historical', $result[Log::class . '$1']); } @@ -110,7 +110,7 @@ public function testGetTabNameForItem() { $this->login('glpi', 'glpi'); $item = $this->createItem(Zone::class); - $instance = new CarbonIntensitySource(); + $instance = new Source(); $result = $instance->getTabNameForItem($item); $expected = 'Carbon intensity sources'; $this->assertStringContainsString($expected, $result); @@ -126,7 +126,7 @@ public function testGetTabNameForItem() } /** - * #CoversMethod \GlpiPlugin\Carbon\CarbonIntensitySource::displayTabContentForItem + * #CoversMethod \GlpiPlugin\Carbon\Source::displayTabContentForItem */ public function testDisplayTabContentForItem() { @@ -135,21 +135,21 @@ public function testDisplayTabContentForItem() ob_start(function ($buffer) { return $buffer; }); - $result = CarbonIntensitySource::displayTabContentForItem($item); + $result = Source::displayTabContentForItem($item); $output = ob_get_clean(); $this->assertEquals('', $output); $this->assertTrue($result); $item = $this->createItem(Zone::class); - $source = $this->createItem(CarbonIntensitySource::class); - $source_zone = $this->createItem(CarbonIntensitySource_Zone::class, [ + $source = $this->createItem(Source::class); + $source_zone = $this->createItem(Source_Zone::class, [ $item::getForeignKeyField() => $item->getID(), $source::getForeignKeyField() => $source->getID() ]); ob_start(function ($buffer) { return $buffer; }); - $result = CarbonIntensitySource::displayTabContentForItem($item); + $result = Source::displayTabContentForItem($item); $output = ob_get_clean(); $this->assertNotEquals('', $output); $this->assertTrue($result); diff --git a/tests/units/Source_ZoneTest.php b/tests/units/Source_ZoneTest.php index 3e4749be..ca3e4c70 100644 --- a/tests/units/Source_ZoneTest.php +++ b/tests/units/Source_ZoneTest.php @@ -32,20 +32,20 @@ namespace GlpiPlugin\Carbon\Tests; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Tests\DbTestCase; use GlpiPlugin\Carbon\Zone; use PHPUnit\Framework\Attributes\CoversMethod; -class CarbonIntensitySource_ZoneTest extends DbTestCase +class Source_ZoneTest extends DbTestCase { /** - * #CoversMethod GlpiPlugin\Carbon\CarbonIntensitySource_Zone::showForSource + * #CoversMethod GlpiPlugin\Carbon\Source_Zone::showForSource */ public function testShowForSource() { - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'foo' ]); @@ -53,7 +53,7 @@ public function testShowForSource() 'name' => 'bar' ]); - $instance = $this->createItem(CarbonIntensitySource_Zone::class, [ + $instance = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID(), ]); @@ -72,11 +72,11 @@ public function testShowForSource() } /** - * #CoversMethod GlpiPlugin\Carbon\CarbonIntensitySource_Zone::showForZone + * #CoversMethod GlpiPlugin\Carbon\Source_Zone::showForZone */ public function testShowForZone() { - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'foo' ]); @@ -84,7 +84,7 @@ public function testShowForZone() 'name' => 'bar' ]); - $instance = $this->createItem(CarbonIntensitySource_Zone::class, [ + $instance = $this->createItem(Source_Zone::class, [ $source::getForeignKeyField() => $source->getID(), $zone::getForeignKeyField() => $zone->getID(), ]); diff --git a/tests/units/ZoneTest.php b/tests/units/ZoneTest.php index 6b1e19a5..20c694ad 100644 --- a/tests/units/ZoneTest.php +++ b/tests/units/ZoneTest.php @@ -33,7 +33,7 @@ namespace GlpiPlugin\Carbon\Tests; use Computer; -use GlpiPlugin\Carbon\CarbonIntensitySource; +use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use Location; @@ -160,7 +160,7 @@ public function testHasHistoricalData() // Test with a Zone object without the field $zone = $this->createItem(Zone::class); - unset($zone->fields['plugin_carbon_carbonintensitysources_id_historical']); + unset($zone->fields['plugin_carbon_sources_id_historical']); $this->assertFalse($zone->hasHistoricalData()); // Test with a Zone object that has no historical data @@ -168,11 +168,11 @@ public function testHasHistoricalData() $zone = $this->createItem(Zone::class); $this->assertFalse($zone->hasHistoricalData()); - $source = $this->createItem(CarbonIntensitySource::class, [ + $source = $this->createItem(Source::class, [ 'name' => 'foo' ]); $zone->update(array_merge($zone->fields, [ - 'plugin_carbon_carbonintensitysources_id_historical' => $source->getID(), + 'plugin_carbon_sources_id_historical' => $source->getID(), ])); $this->assertTrue($zone->hasHistoricalData()); } From 514beca60ff496692e5c5cfc023ef6148551311e Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 19 Sep 2025 09:43:34 +0200 Subject: [PATCH 03/27] feat(Location): move plugin specific field for location to a tab --- setup.php | 2 ++ src/DataSource/Boaviztapi.php | 1 - src/Location.php | 24 +++++++++++++++++++++++- src/Zone.php | 1 - templates/location.html.twig | 33 ++++++++++++++++++++++++++++++++- 5 files changed, 57 insertions(+), 4 deletions(-) diff --git a/setup.php b/setup.php index 8e8f7300..2bfdcbc5 100644 --- a/setup.php +++ b/setup.php @@ -40,6 +40,7 @@ use Location as GlpiLocation; use Profile as GlpiProfile; use GlpiPlugin\Carbon\Dashboard\Grid; +use GlpiPlugin\Carbon\Location; define('PLUGIN_CARBON_VERSION', '1.2.0-dev'); define('PLUGIN_CARBON_SCHEMA_VERSION', '1.1.0'); @@ -138,6 +139,7 @@ function plugin_carbon_registerClasses() { Plugin::registerClass(Config::class, ['addtabon' => GlpiConfig::class]); Plugin::registerClass(Profile::class, ['addtabon' => GlpiProfile::class]); + Plugin::registerClass(Location::class, ['addtabon' => GlpiLocation::class]); foreach (PLUGIN_CARBON_TYPES as $itemtype) { $item_type_class = 'GlpiPlugin\\Carbon\\' . $itemtype . 'Type'; diff --git a/src/DataSource/Boaviztapi.php b/src/DataSource/Boaviztapi.php index 15b7cf03..8fe9f351 100644 --- a/src/DataSource/Boaviztapi.php +++ b/src/DataSource/Boaviztapi.php @@ -234,7 +234,6 @@ public static function getZones() */ public static function dropdownBoaviztaZone(string $name, array $options = []) { - return Dropdown::showFromArray($name, self::getZones(), $options); } } diff --git a/src/Location.php b/src/Location.php index f4bc4317..c0e71ae1 100644 --- a/src/Location.php +++ b/src/Location.php @@ -34,6 +34,7 @@ use CommonDBChild; use CommonDBTM; +use CommonGLPI; use Config as GlpiConfig; use DBmysql; use DBmysqlIterator; @@ -52,7 +53,7 @@ use Session; /** - * Additional data for a location + * Additional data for a location. Extends the Location object from GLPI with aditional fields */ class Location extends CommonDBChild { @@ -60,6 +61,27 @@ class Location extends CommonDBChild public static $itemtype = GlpiLocation::class; public static $items_id = 'locations_id'; + public static function getIcon() + { + return 'ti ti-map-2'; + } + + public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) + { + if (!is_a($item, GlpiLocation::class)) { + return ''; + } + return self::createTabEntry(__('Environmental impact', 'carbon'), 0); + } + + public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) + { + /** @var CommonDBTM $item */ + $location = new self(); + $location->showForm($item->getID()); + return true; + } + public function showForm($ID, array $options = []) { $this->getFromDB($ID); diff --git a/src/Zone.php b/src/Zone.php index b14325a6..2568b381 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -38,7 +38,6 @@ use DateTime; use DBmysql; use DbUtils; -use Glpi\Toolbox\Sanitizer; use Location; use LogicException; use Session; diff --git a/templates/location.html.twig b/templates/location.html.twig index 101d8a64..9e97b901 100644 --- a/templates/location.html.twig +++ b/templates/location.html.twig @@ -32,7 +32,11 @@ {% import 'components/form/fields_macros.html.twig' as fields %} {% import '@carbon/components/form/fields_macros.html.twig' as carbonFields %} -{{ fields.smallTitle(__('Environmental impact', 'carbon')) }} +
+ + {{ __('Boavizta', 'carbon') }} +
+ {{ carbonFields.dropdownBoaviztaZone('_boavizta_zone', item.fields['boavizta_zone'] ?? '', __('Boavizta zone', 'carbon'), @@ -40,3 +44,30 @@ 'display_emptychoice': true, }) }} + +
+ + {{ __('Carbon intensity', 'carbon') }} +
+ +{{ fields.dropdownField('GlpiPlugin\\Carbon\\Source', + 'plugin_carbon_sources_id', + item.fields['plugin_carbon_sources_id'] ?? '', + __('Source', 'carbon'), + { + display_emptychoice: true, + multiple: false, + disabled: false, + condition: { + is_fallback: 0 + } + }) +}} + +{# {{ fields.dropdownField('plugin_carbon_zones_id', + item.fields['boavizta_zone'] ?? '', + __('Carbon intensity source', 'carbon'), + { + 'display_emptychoice': true, + }) +}} #} From 6d7f480551a40b12088f17ed889f605f59502b9a Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Tue, 23 Sep 2025 16:39:11 +0200 Subject: [PATCH 04/27] fix(ComputerType,MonitorType): more conststent right checks --- front/computertype.form.php | 6 +++--- front/monitortype.form.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/front/computertype.form.php b/front/computertype.form.php index b7b90a71..d2503e62 100644 --- a/front/computertype.form.php +++ b/front/computertype.form.php @@ -32,6 +32,7 @@ use Glpi\Exception\Http\NotFoundHttpException; use GlpiPlugin\Carbon\ComputerType; +use ComputerType as GlpiComputerType; include(__DIR__ . '/../../../inc/includes.php'); @@ -39,13 +40,12 @@ throw new NotFoundHttpException(); } -Session::checkRight('config', UPDATE); +Session::checkRight(GlpiComputerType::$rightname, UPDATE); $item = new ComputerType(); if (isset($_POST['update'])) { - // Add a new Form - Session::checkRight('entity', UPDATE); + Session::checkRight(GlpiComputerType::$rightname, UPDATE); $item->update($_POST); Html::back(); } diff --git a/front/monitortype.form.php b/front/monitortype.form.php index 585a3dd6..02dc412a 100644 --- a/front/monitortype.form.php +++ b/front/monitortype.form.php @@ -34,18 +34,18 @@ use GlpiPlugin\Carbon\MonitorType; use Glpi\Exception\Http\NotFoundHttpException; +use MonitorType as GlpiMonitorType; if (!Plugin::isPluginActive('carbon')) { throw new NotFoundHttpException(); } -Session::checkRight('config', UPDATE); +Session::checkRight(GlpiMonitorType::$rightname, UPDATE); $item = new MonitorType(); if (isset($_POST['update'])) { - // Add a new Form - Session::checkRight('entity', UPDATE); + Session::checkRight(GlpiMonitorType::$rightname, UPDATE); $item->update($_POST); Html::back(); } From 59e85da29c0e02a0811b8d8ee0018996713bae53 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 29 Sep 2025 15:02:53 +0200 Subject: [PATCH 05/27] feat(Location): associate location to a carbon intensity zone --- ajax/dropdownZone.php | 54 +++++++ front/location.form.php | 53 +++++++ front/networkequipmenttype.form.php | 6 +- hook.php | 24 +-- install/Install.php | 4 +- install/install/init_datasources.php | 2 +- .../02_update_tables_schema.php | 59 +++++++ install/mysql/plugin_carbon_empty.sql | 14 +- js/carbon.js | 14 ++ setup.php | 3 +- src/CronTask.php | 6 +- src/Location.php | 146 ++++++++++++++++-- src/Source.php | 13 +- src/Zone.php | 19 +++ templates/location.html.twig | 94 ++++++----- tests/integration/SearchOptionTest.php | 2 + tests/src/CommonTestCase.php | 9 +- tests/units/LocationTest.php | 60 +++++++ tests/units/ZoneTest.php | 1 + 19 files changed, 505 insertions(+), 78 deletions(-) create mode 100644 ajax/dropdownZone.php create mode 100644 front/location.form.php create mode 100644 install/migration/update_1.1.0_to_1.2.0/02_update_tables_schema.php diff --git a/ajax/dropdownZone.php b/ajax/dropdownZone.php new file mode 100644 index 00000000..f801150b --- /dev/null +++ b/ajax/dropdownZone.php @@ -0,0 +1,54 @@ +. + * + * ------------------------------------------------------------------------- + */ + +use GlpiPlugin\Carbon\Source_Zone; +use GlpiPlugin\Carbon\Zone; + +include(__DIR__ . '/../../../inc/includes.php'); + +// Check if plugin is activated... +if (!Plugin::isPluginActive('carbon')) { + http_response_code(404); + die(); +} + +// throw new RuntimeException('Required argument missing or incorrect!'); + +$source_zone_table = Source_Zone::getTable(); +$zone_table = Zone::getTable(); +$source_id = (int) $_POST['plugin_carbon_sources_id']; +Zone::dropdown([ + 'rand' => (int) $_POST['dom_id'], + 'condition' => Zone::getRestrictBySourceCondition($source_id), + // 'disabled' => ($source_id === 0), + 'specific_tags' => ($source_id === 0 ? ['disabled' => 'disabled'] : []), +]); diff --git a/front/location.form.php b/front/location.form.php new file mode 100644 index 00000000..2ebed113 --- /dev/null +++ b/front/location.form.php @@ -0,0 +1,53 @@ +. + * + * ------------------------------------------------------------------------- + */ + +use Glpi\Exception\Http\NotFoundHttpException; +use GlpiPlugin\Carbon\Location; +use Location as GlpiLocation; + +include(__DIR__ . "/../../../inc/includes.php"); + +if (!Plugin::isPluginActive('carbon')) { + throw new NotFoundHttpException(); +} + +Session::checkRight(GlpiLocation::$rightname, UPDATE); + +$item = new Location(); + +if (isset($_POST['update'])) { + Session::checkRight(GlpiLocation::$rightname, UPDATE); + $item->update($_POST); + Html::back(); +} + +Html::back(); diff --git a/front/networkequipmenttype.form.php b/front/networkequipmenttype.form.php index 093c1f8e..397f092e 100644 --- a/front/networkequipmenttype.form.php +++ b/front/networkequipmenttype.form.php @@ -32,6 +32,7 @@ use Glpi\Exception\Http\NotFoundHttpException; use GlpiPlugin\Carbon\NetworkEquipmentType; +use NetworkEquipmentType as GlpiNetworkEquipmentType; include(__DIR__ . '/../../../inc/includes.php'); @@ -39,13 +40,12 @@ throw new NotFoundHttpException(); } -Session::checkRight('config', UPDATE); +Session::checkRight(GlpiNetworkEquipmentType::$rightname, UPDATE); $item = new NetworkEquipmentType(); if (isset($_POST['update'])) { - // Add a new Form - Session::checkRight('entity', UPDATE); + Session::checkRight(GlpiNetworkEquipmentType::$rightname, UPDATE); $item->update($_POST); Html::back(); } diff --git a/hook.php b/hook.php index 6e6c574f..c78e9556 100644 --- a/hook.php +++ b/hook.php @@ -159,18 +159,18 @@ function plugin_carbon_getAddSearchOptionsNew($itemtype): array * 'options => array * @return void */ -function plugin_carbon_postItemForm(array $params) -{ - switch ($params['item']->getType()) { - case GlpiLocation::class: - $location = new Location(); - $location->getFromDBByCrit([ - GlpiLocation::getForeignKeyField() => $params['item']->getID(), - ]); - $location->showForm($location->getID()); - break; - } -} +// function plugin_carbon_postItemForm(array $params) +// { +// switch ($params['item']->getType()) { +// case GlpiLocation::class: +// $location = new Location(); +// $location->getFromDBByCrit([ +// GlpiLocation::getForeignKeyField() => $params['item']->getID(), +// ]); +// $location->showForm($location->getID()); +// break; +// } +// } function plugin_carbon_hook_add_asset(CommonDBTM $item) { diff --git a/install/Install.php b/install/Install.php index 995e6f5f..7949eb3b 100644 --- a/install/Install.php +++ b/install/Install.php @@ -245,9 +245,10 @@ private function getMigrationsToDo(string $current_version): array * * @param string $name Name of the zone * @param int $is_fallback Is the zone a fallback zone (1) or not (0) + * @param int $is_carbon_intensity_source Does the source provide carbon intensity (1) or not (0) * @return int ID of the zone */ - public static function getOrCreateSource(string $name, int $is_fallback = 1): int + public static function getOrCreateSource(string $name, int $is_fallback = 1, int $is_carbon_intensity_source = 1): int { $source = new Source(); $source->getFromDBByCrit(['name' => $name]); @@ -255,6 +256,7 @@ public static function getOrCreateSource(string $name, int $is_fallback = 1): in $source->add([ 'name' => $name, 'is_fallback' => $is_fallback, + 'is_carbon_intensity_source' => $is_carbon_intensity_source, ]); /** @phpstan-ignore if.alwaysTrue */ if ($source->isNewItem()) { diff --git a/install/install/init_datasources.php b/install/install/init_datasources.php index b12e4e48..e0461c97 100644 --- a/install/install/init_datasources.php +++ b/install/install/init_datasources.php @@ -121,7 +121,7 @@ } $file = null; // close the file -$source_id = Install::getOrCreateSource('Hydro Quebec'); +$source_id = Install::getOrCreateSource('Hydro Quebec', 1, 0); $zone_id_quebec = Install::getOrCreateZone('Quebec', $source_id); Install::linkSourceZone($source_id, $zone_id_quebec); diff --git a/install/migration/update_1.1.0_to_1.2.0/02_update_tables_schema.php b/install/migration/update_1.1.0_to_1.2.0/02_update_tables_schema.php new file mode 100644 index 00000000..90fe1f45 --- /dev/null +++ b/install/migration/update_1.1.0_to_1.2.0/02_update_tables_schema.php @@ -0,0 +1,59 @@ +. + * + * ------------------------------------------------------------------------- + */ + +use GlpiPlugin\Carbon\Location; +use GlpiPlugin\Carbon\Source; + +/** @var DBmysql $DB */ +/** @var Migration $migration */ + +$table = (new DbUtils())->getTableForItemType(Source::class); +$migration->addField( + $table, + 'is_carbon_intensity_source', + 'bool', + [ + 'after' => 'is_fallback', + 'update' => 1, + 'condition' => "WHERE `name` IN ('RTE', 'ElectricityMap', 'Ember - Energy Institute', 'Hydro Quebec')" + ] +); + +$table = (new DbUtils())->getTableForItemType(Location::class); +$migration->addField( + $table, + 'plugin_carbon_sources_zones_id', + 'fkey', + [ + 'after' => 'boavizta_zone' + ] +); diff --git a/install/mysql/plugin_carbon_empty.sql b/install/mysql/plugin_carbon_empty.sql index 84e4436a..a7fcc0fa 100644 --- a/install/mysql/plugin_carbon_empty.sql +++ b/install/mysql/plugin_carbon_empty.sql @@ -73,9 +73,10 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_zones` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_sources` ( - `id` int unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(255) DEFAULT NULL, - `is_fallback` tinyint NOT NULL DEFAULT '0' COMMENT 'Fallback source for carbon intensity', + `id` int unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `is_fallback` tinyint NOT NULL DEFAULT '0' COMMENT 'Fallback source for carbon intensity', + `is_carbon_intensity_source` tinyint NOT NULL DEFAULT '0' COMMENT 'provides carbon intensity', PRIMARY KEY (`id`), UNIQUE KEY `unicity` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; @@ -156,9 +157,10 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_networkequipmenttypes` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; CREATE TABLE IF NOT EXISTS `glpi_plugin_carbon_locations` ( - `id` int unsigned NOT NULL AUTO_INCREMENT, - `locations_id` int unsigned NOT NULL DEFAULT '0', - `boavizta_zone` varchar(255) DEFAULT NULL, + `id` int unsigned NOT NULL AUTO_INCREMENT, + `locations_id` int unsigned NOT NULL DEFAULT '0', + `boavizta_zone` varchar(255) DEFAULT NULL, + `plugin_carbon_sources_zones_id` int unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `unicity` (`locations_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/js/carbon.js b/js/carbon.js index 530bea44..ea8ad782 100644 --- a/js/carbon.js +++ b/js/carbon.js @@ -27,3 +27,17 @@ * * ------------------------------------------------------------------------- */ + +window.GLPIPlugin = window.GLPIPlugin || {}; + +window.GLPIPlugin.Carbon = { + onSourceChange: function() { + var value = document.querySelector("select[name='plugin_carbon_sources_id']").value; + var zoneDropdown = document.querySelector("select[name='plugin_carbon_zones_id']").closest('div.form-field'); + if (value == 0 && !zoneDropdown.classList.contains('d-none')) { + zoneDropdown.classList.add('d-none'); + } else if (value != 0 && zoneDropdown.classList.contains('d-none')) { + zoneDropdown.classList.remove('d-none'); + } + } +}; diff --git a/setup.php b/setup.php index 2bfdcbc5..8bc52c66 100644 --- a/setup.php +++ b/setup.php @@ -114,7 +114,7 @@ function plugin_carbon_setupHooks() // asset's type $PLUGIN_HOOKS[Hooks::PRE_ITEM_PURGE]['carbon'][$itemtype . 'Type'] = 'plugin_carbon_hook_pre_purge_assettype'; } - $PLUGIN_HOOKS[Hooks::POST_ITEM_FORM]['carbon'] = 'plugin_carbon_postItemForm'; + // $PLUGIN_HOOKS[Hooks::POST_ITEM_FORM]['carbon'] = 'plugin_carbon_postItemForm'; // Actions taken on locations events $PLUGIN_HOOKS[Hooks::ITEM_ADD]['carbon'][GlpiLocation::class] = 'plugin_carbon_locationAdd'; @@ -126,6 +126,7 @@ function plugin_carbon_setupHooks() $PLUGIN_HOOKS[Hooks::PRE_ITEM_ADD]['carbon'][GlpiProfile::class] = 'plugin_carbon_profileAdd'; $PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT]['carbon'][] = 'lib/apexcharts.js'; + $PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT]['carbon'][] = 'lib/carbon.js'; // Import CSS $PLUGIN_HOOKS[Hooks::ADD_CSS]['carbon'][] = 'lib/carbon.css'; diff --git a/src/CronTask.php b/src/CronTask.php index 9038dbc8..1ec0cfb3 100644 --- a/src/CronTask.php +++ b/src/CronTask.php @@ -171,7 +171,7 @@ public static function cronEmbodiedImpact(GlpiCronTask $task): int */ public static function cronDownloadRte(GlpiCronTask $task): int { - $client = ClientFactory::create('rte'); + $client = ClientFactory::create('Rte'); return self::downloadCarbonIntensityFromSource($task, $client, new CarbonIntensity()); } @@ -182,7 +182,7 @@ public static function cronDownloadRte(GlpiCronTask $task): int */ public static function cronDownloadElectricityMap(GlpiCronTask $task): int { - $client = ClientFactory::create('electricitymap'); + $client = ClientFactory::create('ElectricityMap'); return self::downloadCarbonIntensityFromSource($task, $client, new CarbonIntensity()); } @@ -193,7 +193,7 @@ public static function cronDownloadElectricityMap(GlpiCronTask $task): int */ public static function cronDownloadWatttime(GlpiCronTask $task): int { - $client = ClientFactory::create('watttime'); + $client = ClientFactory::create('Watttime'); return self::downloadCarbonIntensityFromSource($task, $client, new CarbonIntensity()); } diff --git a/src/Location.php b/src/Location.php index c0e71ae1..acfa62f7 100644 --- a/src/Location.php +++ b/src/Location.php @@ -38,19 +38,15 @@ use Config as GlpiConfig; use DBmysql; use DBmysqlIterator; +use DbUtils; use Geocoder\Geocoder; -use Geocoder\Provider\Nominatim\Nominatim; use Geocoder\Query\GeocodeQuery; -use Geocoder\StatefulGeocoder; -use GuzzleHttp\Client; use Html; use Location as GlpiLocation; use MassiveAction; use Glpi\Application\View\TemplateRenderer; -use GLPINetwork; use GlpiPlugin\Carbon\DataSource\Boaviztapi; use League\ISO3166\ISO3166; -use Session; /** * Additional data for a location. Extends the Location object from GLPI with aditional fields @@ -68,25 +64,102 @@ public static function getIcon() public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { - if (!is_a($item, GlpiLocation::class)) { - return ''; + if (is_a($item, GlpiLocation::class)) { + return self::createTabEntry(__('Environmental impact', 'carbon'), 0); } - return self::createTabEntry(__('Environmental impact', 'carbon'), 0); + return ''; } public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { - /** @var CommonDBTM $item */ - $location = new self(); - $location->showForm($item->getID()); + if (is_a($item, GlpiLocation::class)) { + /** @var GlpiLocation $item */ + $location = new self(); + $location->showForLocation($item); + } return true; } - public function showForm($ID, array $options = []) + public function prepareInputForAdd($input) + { + if (isset($input['plugin_carbon_sources_id']) && isset($input['plugin_carbon_zones_id'])) { + $source_zone = new Source_Zone(); + $source_zone->getFromDBByCrit([ + 'plugin_carbon_sources_id' => $input['plugin_carbon_sources_id'], + 'plugin_carbon_zones_id' => $input['plugin_carbon_zones_id'], + ]); + if (!$source_zone->isNewItem()) { + $input['plugin_carbon_sources_zones_id'] = $source_zone->getID(); + } + } + + return $input; + } + + public function prepareInputForUpdate($input) + { + if (isset($input['plugin_carbon_sources_id']) && isset($input['plugin_carbon_zones_id'])) { + $source_zone = new Source_Zone(); + $source_zone->getFromDBByCrit([ + 'plugin_carbon_sources_id' => $input['plugin_carbon_sources_id'], + 'plugin_carbon_zones_id' => $input['plugin_carbon_zones_id'], + ]); + if (!$source_zone->isNewItem()) { + $input['plugin_carbon_sources_zones_id'] = $source_zone->getID(); + } else { + $input['plugin_carbon_sources_zones_id'] = 0; + } + } + + return $input; + } + + public function showForLocation(GlpiLocation $item, array $options = []) { - $this->getFromDB($ID); + global $DB; + + $this->getFromDBByCrit(['locations_id' => $item->getID()]); + if ($this->isNewItem()) { + $this->add(['locations_id' => $item->getID()]); + } + + $source_zone_table = Source_Zone::getTable(); + $source_table = Source::getTable(); + $iterator = $DB->request([ + 'SELECT' => [ + Source_Zone::getTableField('plugin_carbon_sources_id') . ' AS sources_id', + Source_Zone::getTableField('plugin_carbon_zones_id') . ' AS zones_id', + ], + 'FROM' => $source_table, + 'LEFT JOIN' => [ + $source_zone_table => [ + 'FKEY' => [ + $source_zone_table => 'plugin_carbon_sources_id', + $source_table => 'id', + ] + ] + ], + 'WHERE' => [ + 'is_fallback' => 0, + 'is_carbon_intensity_source' => 1, + Source_Zone::getTableField('id') => $this->fields['plugin_carbon_sources_zones_id'], + ] + ]); + $row = $iterator->current(); + $source_id = $row['sources_id'] ?? 0; + $zone_id = $row['zones_id'] ?? 0; + if ($source_id === 0) { + $zone_id = 0; + } + TemplateRenderer::getInstance()->display('@carbon/location.html.twig', [ 'item' => $this, + 'params' => [ + 'candel' => false, + ], + 'source_id' => $source_id, + 'zone_id' => $zone_id, + 'zone_condition' => Zone::getRestrictBySourceCondition($source_id), ]); return true; @@ -450,4 +523,51 @@ public static function getIncompleteLocations(array $where = []): DBmysqlIterato return $result; } + + public function getSourceZoneId(): int + { + /** @var DBmysql */ + global $DB; + + if ($this->isNewItem()) { + return 0; + } + + if (!Source_Zone::isNewID($this->fields['plugin_carbon_sources_zones_id'])) { + return $this->fields['plugin_carbon_sources_zones_id']; + } + + $location_table = self::getTable(); + $glpi_location_table = GlpiLocation::getTable(); + $ancestors = (new DbUtils())->getAncestorsOf($glpi_location_table, $this->fields['locations_id']); + if (count($ancestors) === 0) { + return 0; + } + + $ancestors = array_values($ancestors); // Drop keys + $request = [ + 'SELECT' => self::getTableField('plugin_carbon_sources_zones_id'), + 'FROM' => $glpi_location_table, + 'INNER JOIN' => [ + $location_table => [ + 'FKEY' => [ + $glpi_location_table => 'id', + $location_table => 'locations_id', + ] + ] + ], + 'WHERE' => [ + GlpiLocation::getTableField('id') => $ancestors, + self::getTableField('plugin_carbon_sources_zones_id') => ['>', 0] + ], + 'ORDER' => 'level DESC', + 'LIMIT' => '1' + ]; + $iterator = $DB->request($request); + if ($iterator->count() === 0) { + return 0; + } + + return $iterator->current()['plugin_carbon_sources_zones_id']; + } } diff --git a/src/Source.php b/src/Source.php index 8af03bf6..6ba1c7e3 100644 --- a/src/Source.php +++ b/src/Source.php @@ -108,15 +108,26 @@ public function rawSearchOptions() { $tab = parent::rawSearchOptions(); + $table = self::getTable(); + $tab[] = [ 'id' => '3', - 'table' => $this->getTable(), + 'table' => $table, 'field' => 'is_fallback', 'name' => __('Is a fallback source'), 'massiveaction' => false, 'datatype' => 'boolean', ]; + $tab[] = [ + 'id' => '4', + 'table' => $table, + 'field' => 'is_carbon_intensity_source', + 'name' => __('Is a carbon intensity source'), + 'massiveaction' => false, + 'datatype' => 'boolean', + ]; + return $tab; } diff --git a/src/Zone.php b/src/Zone.php index 2568b381..abada810 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -365,4 +365,23 @@ public function getByItem(CommonDBTM $item, ?DateTime $date = null, bool $use_co throw new LogicException('Not implemented yet'); } + + public static function getRestrictBySourceCondition(int $source_id) + { + $source_zone_table = Source_Zone::getTable(); + $zone_table = Zone::getTable(); + return [ + 'LEFT JOIN' => [ + $source_zone_table => [ + 'FKEY' => [ + $source_zone_table => 'plugin_carbon_zones_id', + $zone_table => 'id', + ] + ] + ], + 'WHERE' => [ + Source_Zone::getTableField('plugin_carbon_sources_id') => $source_id, + ] + ]; + } } diff --git a/templates/location.html.twig b/templates/location.html.twig index 9e97b901..501909cc 100644 --- a/templates/location.html.twig +++ b/templates/location.html.twig @@ -29,45 +29,69 @@ # ------------------------------------------------------------------------- #} +{% extends "generic_show_form.html.twig" %} + {% import 'components/form/fields_macros.html.twig' as fields %} {% import '@carbon/components/form/fields_macros.html.twig' as carbonFields %} -
- - {{ __('Boavizta', 'carbon') }} -
+{% block form_fields %} +
+ + {{ __('Boavizta', 'carbon') }} +
+ + {{ carbonFields.dropdownBoaviztaZone('boavizta_zone', + item.fields['boavizta_zone'] ?? '', + __('Boavizta zone', 'carbon'), + { + 'display_emptychoice': true, + }) + }} -{{ carbonFields.dropdownBoaviztaZone('_boavizta_zone', - item.fields['boavizta_zone'] ?? '', - __('Boavizta zone', 'carbon'), - { - 'display_emptychoice': true, - }) -}} +
+ + {{ __('Carbon intensity', 'carbon') }} +
-
- - {{ __('Carbon intensity', 'carbon') }} -
+ {% set plugin_carbon_zones_rand = random() %} + {{ fields.dropdownField('GlpiPlugin\\Carbon\\Source', + 'plugin_carbon_sources_id', + source_id, + __('Source', 'carbon'), + { + display_emptychoice: true, + multiple: false, + disabled: false, + condition: { + is_fallback: 0, + is_carbon_intensity_source: 1 + }, + }) + }} -{{ fields.dropdownField('GlpiPlugin\\Carbon\\Source', - 'plugin_carbon_sources_id', - item.fields['plugin_carbon_sources_id'] ?? '', - __('Source', 'carbon'), - { - display_emptychoice: true, - multiple: false, - disabled: false, - condition: { - is_fallback: 0 - } - }) -}} + -{# {{ fields.dropdownField('plugin_carbon_zones_id', - item.fields['boavizta_zone'] ?? '', - __('Carbon intensity source', 'carbon'), - { - 'display_emptychoice': true, - }) -}} #} + {{ fields.dropdownField('GlpiPlugin\\Carbon\\Zone', + 'plugin_carbon_zones_id', + zone_id, + __('Carbon intensity zone', 'carbon'), + { + rand: plugin_carbon_zones_rand, + display_emptychoice: true, + condition: zone_condition, + disabled: (source_id == 0) + }) + }} +{% endblock %} diff --git a/tests/integration/SearchOptionTest.php b/tests/integration/SearchOptionTest.php index d95d8fb5..d8bca027 100644 --- a/tests/integration/SearchOptionTest.php +++ b/tests/integration/SearchOptionTest.php @@ -45,6 +45,7 @@ use RecursiveDirectoryIterator; use CommonDBTM; use CommonGLPI; +use DBmysql; use DbUtils; use Plugin; use PHPUnit\Framework\Attributes\CoversMethod; @@ -95,6 +96,7 @@ class SearchOptionTest extends CommonTestCase public function testSearchOption() { + /** @var DBmysql $DB */ global $DB; // Find each .php file in /src directory and subdirectories diff --git a/tests/src/CommonTestCase.php b/tests/src/CommonTestCase.php index cae37c43..32a16eea 100644 --- a/tests/src/CommonTestCase.php +++ b/tests/src/CommonTestCase.php @@ -146,6 +146,10 @@ protected function getUniqueString() /** * @deprecated use createItem instead + * + * @param class-string $itemtype itemtype to create + * @param array $input + * @return T */ protected function getItem(string $itemtype, array $input = []): CommonDBTM { @@ -155,9 +159,10 @@ protected function getItem(string $itemtype, array $input = []): CommonDBTM /** * Create an item of the given itemtype * - * @param string $itemtype itemtype to create + * @template T of CommonDBTM + * @param class-string $itemtype itemtype to create * @param array $input - * @return CommonDBTM + * @return T */ protected function createItem(string $itemtype, array $input = []): CommonDBTM { diff --git a/tests/units/LocationTest.php b/tests/units/LocationTest.php index 18684555..a20260cb 100644 --- a/tests/units/LocationTest.php +++ b/tests/units/LocationTest.php @@ -45,6 +45,7 @@ use GlpiPlugin\Carbon\Zone; use Location as GlpiLocation; use GlpiPlugin\Carbon\Location; +use Locale; class LocationTest extends DbTestCase { @@ -412,4 +413,63 @@ public function testHasFallbackCarbonIntensityData() $result = $location->hasFallbackCarbonIntensityData($glpi_location); $this->assertTrue($result); } + + public function testGetSourceZoneId() + { + // Test an unitialized location + $location = new Location(); + $result = $location->getSourceZoneId(); + $this->assertEquals(0, $result); + + // Test a location without a relation to a source and a zone + $glpi_location = $this->createItem(GlpiLocation::class); + $location = $this->createItem(Location::class, ['locations_id' => $glpi_location->getID()]); + $result = $location->getSourceZoneId(); + $this->assertEquals(0, $result); + + // Test a location associated to a source_zone + $source = $this->createItem(Source::class); + $zone = $this->createItem(Zone::class); + $source_zone = $this->createItem(Source_Zone::class, [ + Source::getForeignKeyField() => $source->getID(), + Zone::getForeignKeyField() => $zone->getID(), + ]); + $glpi_location = $this->createItem(GlpiLocation::class); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID(), + ]); + $result = $location->getSourceZoneId(); + $this->assertEquals($source_zone->getID(), $result); + + // Test a source_zone associated to the parent of the location + $glpi_location_ancestor = $this->createItem(GlpiLocation::class); + $glpi_location = $this->createItem(GlpiLocation::class, [ + 'locations_id' => $glpi_location_ancestor->getID(), + ]); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location_ancestor->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID(), + ]); + $result = $location->getSourceZoneId(); + $this->assertEquals($source_zone->getID(), $result); + + // Test a source_zone associated to the gand-parent of the location + $glpi_location_grand_ancestor = $this->createItem(GlpiLocation::class); + $glpi_location_ancestor = $this->createItem(GlpiLocation::class, [ + 'locations_id' => $glpi_location_grand_ancestor->getID() + ]); + $glpi_location = $this->createItem(GlpiLocation::class, [ + 'locations_id' => $glpi_location_ancestor->getID(), + ]); + $location_grand_ancestor = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location_grand_ancestor->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID(), + ]); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location->getID(), + ]); + $result = $location->getSourceZoneId(); + $this->assertEquals($source_zone->getID(), $result); + } } diff --git a/tests/units/ZoneTest.php b/tests/units/ZoneTest.php index 20c694ad..6c61bfea 100644 --- a/tests/units/ZoneTest.php +++ b/tests/units/ZoneTest.php @@ -33,6 +33,7 @@ namespace GlpiPlugin\Carbon\Tests; use Computer; +use DBmysql; use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Zone; use Location; From 12432f2740ccee4ba77e415bc58c49d61fc4ae85 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 1 Oct 2025 13:54:53 +0200 Subject: [PATCH 06/27] style(Impact\History\AbstractAsset): code cleanup --- src/Impact/History/AbstractAsset.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Impact/History/AbstractAsset.php b/src/Impact/History/AbstractAsset.php index 5ecc706e..78c92f14 100644 --- a/src/Impact/History/AbstractAsset.php +++ b/src/Impact/History/AbstractAsset.php @@ -38,15 +38,12 @@ use DateTime; use DateTimeImmutable; use DateTimeInterface; -use DateTimeZone; use DBmysql; -use DbUtils; use GlpiPlugin\Carbon\Zone; use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\DataTracking\TrackedFloat; use GlpiPlugin\Carbon\Engine\V1\EngineInterface; use GlpiPlugin\Carbon\Toolbox; -use Location as GlpiLocation; use LogicException; use Session; use Toolbox as GlpiToolbox; @@ -190,7 +187,7 @@ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $e */ $memory_limit = GlpiToolbox::getMemoryLimit() - 8 * 1024 * 1024; if ($memory_limit < 0) { - // May happen in test seems that ini_get("memory_limits") returns + // May happen in test; seems that ini_get("memory_limits") returns // enpty string in PHPUnit environment $memory_limit = null; } From 0c475088417a4e2e0cff5440fec7f640465b5000 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 1 Oct 2025 13:56:14 +0200 Subject: [PATCH 07/27] fix(Impact\History\AbstractAsset): test memory before calculating a carbon emission A result was calculated but not saved, wasting computational resources --- src/Impact/History/AbstractAsset.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Impact/History/AbstractAsset.php b/src/Impact/History/AbstractAsset.php index 78c92f14..7f7d5eed 100644 --- a/src/Impact/History/AbstractAsset.php +++ b/src/Impact/History/AbstractAsset.php @@ -200,6 +200,11 @@ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $e $date_cursor = DateTime::createFromFormat('Y-m-d H:i:s', $gap['start'])->setTime(0, 0, 0, 0); $end_date = DateTime::createFromFormat('Y-m-d H:i:s', $gap['end'])->setTime(0, 0, 0, 0); while ($date_cursor < $end_date) { + if ($memory_limit && $memory_limit < memory_get_usage()) { + // 8 MB memory left, emergency exit + $this->limit_reached = true; + break 2; + } $success = $this->evaluateItemPerDay($item, $engine, $date_cursor); if ($success) { $count++; @@ -208,11 +213,6 @@ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $e break 2; } } - if ($memory_limit && $memory_limit < memory_get_usage()) { - // 8 MB memory left, emergency exit - $this->limit_reached = true; - break 2; - } $date_cursor = $date_cursor->add(new DateInterval(static::$date_increment)); } } From 61cf89ff5b52c8c24616156eed985eebe23c0b09 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 1 Oct 2025 14:14:01 +0200 Subject: [PATCH 08/27] test: replace deprecated methods --- tests/units/CronTaskTest.php | 2 +- tests/units/Dashboard/ProviderTest.php | 6 +++--- tests/units/Engine/V1/InventoryTest.php | 2 +- tests/units/Impact/History/MonitorTest.php | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/units/CronTaskTest.php b/tests/units/CronTaskTest.php index 417e04e7..f0371078 100644 --- a/tests/units/CronTaskTest.php +++ b/tests/units/CronTaskTest.php @@ -137,7 +137,7 @@ public function testFillIncompleteLocations() ]); // Test a single - $glpi_locations = $this->getItems([ + $glpi_locations = $this->createItems([ GlpiLocation::class => [ [ 'name' => 'Valid Location', diff --git a/tests/units/Dashboard/ProviderTest.php b/tests/units/Dashboard/ProviderTest.php index fda3baa6..74ba97eb 100644 --- a/tests/units/Dashboard/ProviderTest.php +++ b/tests/units/Dashboard/ProviderTest.php @@ -147,11 +147,11 @@ protected function handledComputersCountFixture(): int ], ] ]; - $computers = $this->getItems($computers_definition); + $computers = $this->createItems($computers_definition); $total_count += count($computers[Computer::class]); // computers with a usage profile; 3 of them are complete - $computers = $this->getItems($computers_definition); + $computers = $this->createItems($computers_definition); $total_count += count($computers[Computer::class]); foreach ($computers[Computer::class] as $computers_id => $computer) { $impact = $this->createItem(UsageInfo::class, [ @@ -239,7 +239,7 @@ public function testGetSumUsageEmissionsPerModel() ] ]; - $items = $this->getItems($rows); + $items = $this->createItems($rows); } $output = Provider::getSumUsageEmissionsPerModel(); diff --git a/tests/units/Engine/V1/InventoryTest.php b/tests/units/Engine/V1/InventoryTest.php index 665ac340..66c9f4b3 100644 --- a/tests/units/Engine/V1/InventoryTest.php +++ b/tests/units/Engine/V1/InventoryTest.php @@ -57,7 +57,7 @@ public function testAddItemByCrit() $this->login('glpi', 'glpi'); $entities_id = $this->isolateInEntity('glpi', 'glpi'); - $computers = $this->getItems([ + $computers = $this->createItems([ Computer::class => [ [], [], diff --git a/tests/units/Impact/History/MonitorTest.php b/tests/units/Impact/History/MonitorTest.php index 4d931898..2e679ffa 100644 --- a/tests/units/Impact/History/MonitorTest.php +++ b/tests/units/Impact/History/MonitorTest.php @@ -206,12 +206,12 @@ private static function getMonitorLinkedToComputer(?GlpiComputer $computer = nul { $self = new self(); if ($computer === null) { - $computer = $self->getItem(GlpiComputer::class); + $computer = $self->createItem(GlpiComputer::class); } - $item = $self->getItem(GlpiMonitor::class); + $item = $self->createItem(GlpiMonitor::class); - $computer_item = $self->getItem(Computer_Item::class, [ + $computer_item = $self->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), 'itemtype' => $item->getType(), 'items_id' => $item->getID(), @@ -223,7 +223,7 @@ private static function getMonitorLinkedToComputer(?GlpiComputer $computer = nul private static function addManagementToMonitor(CommonDBTM $item) { $self = new self(); - $management = $self->getItem(Infocom::class, [ + $management = $self->createItem(Infocom::class, [ 'itemtype' => $item->getType(), 'items_id' => $item->getID(), ]); From 519bb7e34b49834575113484c480141eef33e34f Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Wed, 1 Oct 2025 14:24:29 +0200 Subject: [PATCH 09/27] refactor(Zone): set alias to location class --- src/Zone.php | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/Zone.php b/src/Zone.php index abada810..b0fd84df 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -38,7 +38,7 @@ use DateTime; use DBmysql; use DbUtils; -use Location; +use Location as GlpiLocation; use LogicException; use Session; @@ -180,28 +180,28 @@ public static function getByLocation(CommonDBTM $item): ?Zone } // TODO: support translations - $location_table = Location::getTable(); + $glpi_location_table = GlpiLocation::getTable(); $zone_table = Zone::getTable(); $request = [ 'SELECT' => Zone::getTableField('id'), 'FROM' => $zone_table, 'INNER JOIN' => [ - $location_table => [ + $glpi_location_table => [ 'FKEY' => [ - $location_table => 'state', + $glpi_location_table => 'state', $zone_table => 'name', ], ], ], 'WHERE' => [ - Location::getTableField('id') => $item->getID(), + GlpiLocation::getTableField('id') => $item->getID(), ] ]; $iterator = $DB->request($request); if ($iterator->count() !== 1) { // no state found, fallback to country - $request['INNER JOIN'][$location_table]['FKEY'][$location_table] = 'country'; + $request['INNER JOIN'][$glpi_location_table]['FKEY'][$glpi_location_table] = 'country'; $iterator = $DB->request($request); if ($iterator->count() !== 1) { // Give up @@ -229,7 +229,7 @@ public static function getByAsset(CommonDBTM $item): ?Zone /** @var DBmysql $DB */ global $DB; - if (!isset($item->fields[Location::getForeignKeyField()])) { + if (!isset($item->fields[GlpiLocation::getForeignKeyField()])) { return null; } @@ -238,24 +238,24 @@ public static function getByAsset(CommonDBTM $item): ?Zone } // TODO: support translations - $location_table = Location::getTable(); + $glpi_location_table = GlpiLocation::getTable(); $zone_table = Zone::getTable(); $item_table = $item::getTable(); - $state_field = Location::getTableField('state'); + $state_field = GlpiLocation::getTableField('state'); $request = [ 'SELECT' => Zone::getTableField('id'), 'FROM' => $zone_table, 'INNER JOIN' => [ - $location_table => [ + $glpi_location_table => [ 'FKEY' => [ - $location_table => 'state', + $glpi_location_table => 'state', $zone_table => 'name', ], ], $item_table => [ 'FKEY' => [ $item_table => 'locations_id', - $location_table => 'id', + $glpi_location_table => 'id', ], ], ], @@ -268,9 +268,9 @@ public static function getByAsset(CommonDBTM $item): ?Zone if ($iterator->count() !== 1) { // no state found, fallback to country - $request['INNER JOIN'][$location_table]['FKEY'][$location_table] = 'country'; + $request['INNER JOIN'][$glpi_location_table]['FKEY'][$glpi_location_table] = 'country'; unset($request['WHERE'][$state_field]); - $request['WHERE'][Location::getTableField('country')] = ['<>', '']; + $request['WHERE'][GlpiLocation::getTableField('country')] = ['<>', '']; $iterator = $DB->request($request); if ($iterator->count() !== 1) { // Give up @@ -327,21 +327,21 @@ public function getByItem(CommonDBTM $item, ?DateTime $date = null, bool $use_co // TODO: use date to find where was the asset at the given date if ($date === null) { $item_table = $item->getTable(); - $location_table = Location::getTable(); + $glpi_location_table = GlpiLocation::getTable(); $zone_table = Zone::getTable(); $request = [ 'INNER JOIN' => [ - $location_table => [ + $glpi_location_table => [ 'FKEY' => [ $zone_table => 'name', - $location_table => 'state', + $glpi_location_table => 'state', ], ], $item_table => [ 'FKEY' => [ - $item_table => Location::getForeignKeyField(), - $location_table => 'id', + $item_table => GlpiLocation::getForeignKeyField(), + $glpi_location_table => 'id', ], ] ], @@ -359,7 +359,7 @@ public function getByItem(CommonDBTM $item, ?DateTime $date = null, bool $use_co } // no state found, fallback to country - $request['INNER JOIN'][$location_table]['FKEY'][$location_table] = 'country'; + $request['INNER JOIN'][$glpi_location_table]['FKEY'][$glpi_location_table] = 'country'; return $this->getFromDBByRequest($request); } From a753af506452d0a3bae5101aecf99d476981e3dc Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Thu, 2 Oct 2025 16:00:59 +0200 Subject: [PATCH 10/27] feat(Zone): update algorithms to find zone from location or asset --- install/Install.php | 17 ++- install/install/init_datasources.php | 8 +- src/Engine/V1/AbstractAsset.php | 2 +- src/Impact/History/AbstractAsset.php | 16 +-- src/Zone.php | 144 +++++++++----------- tests/units/Impact/History/ComputerTest.php | 52 ++++--- tests/units/LocationTest.php | 11 +- tests/units/ZoneTest.php | 130 +++++++----------- 8 files changed, 178 insertions(+), 202 deletions(-) diff --git a/install/Install.php b/install/Install.php index 7949eb3b..832882bf 100644 --- a/install/Install.php +++ b/install/Install.php @@ -294,11 +294,12 @@ public static function getOrCreateZone(string $name, int $source_id): int /** * Link a carbon intensity source to a zone * - * @param int $source_id ID of the carbon intensity source - * @param int $zone_id ID of the zone - * @return int ID of the link + * @param int $source_id ID of the carbon intensity source + * @param int $zone_id ID of the zone + * @param string $code Identifier of the zone used by the source + * @return int ID of the link */ - public static function linkSourceZone(int $source_id, int $zone_id): int + public static function linkSourceZone(int $source_id, int $zone_id, string $code = ''): int { $source_zone = new Source_Zone(); $source_zone->getFromDBByCrit([ @@ -309,7 +310,15 @@ public static function linkSourceZone(int $source_id, int $zone_id): int $source_zone->add([ 'plugin_carbon_sources_id' => $source_id, 'plugin_carbon_zones_id' => $zone_id, + 'code' => $code ]); + } else { + if ($source_zone->fields['code'] !== $code) { + $source_zone->update([ + 'id' => $source_zone->getID(), + 'code' => $code, + ]); + } } return $source_zone->getID(); diff --git a/install/install/init_datasources.php b/install/install/init_datasources.php index e0461c97..bc7a520d 100644 --- a/install/install/init_datasources.php +++ b/install/install/init_datasources.php @@ -40,7 +40,7 @@ /** @var DBmysql $DB */ global $DB; -// This file ys executed at the end of an upgrade. +// This file is executed at the end of an upgrade. // Upgrade to 1.2.0 changed the tables modified by this code // then we need to reset DB columns cache $DB->listFields(getTableForItemType(Source::class), false); @@ -55,7 +55,7 @@ $dbUtil = new DbUtils(); $table = $dbUtil->getTableForItemType(GlpiPlugin\Carbon\CarbonIntensity::class); -// Expected columns are Entity;Code; Year; Carbon intensity of electricity - gCO2/kWh +// Expected columns are Entity; Code; Year; Carbon intensity of electricity - gCO2/kWh $data_source = dirname(__DIR__) . '/data/carbon_intensity/carbon-intensity-electricity.csv'; // Create data source in DB @@ -99,7 +99,7 @@ } $zone_id = Install::getOrCreateZone($entity, $source_id); - Install::linkSourceZone($source_id, $zone_id); + Install::linkSourceZone($source_id, $zone_id, $code); // Insert into the database $success = $DB->updateOrInsert($table, [ @@ -108,7 +108,7 @@ ], [ 'date' => "$year-01-01 00:00:00", 'plugin_carbon_sources_id' => $source_id, - 'plugin_carbon_zones_id' => $zone_id + 'plugin_carbon_zones_id' => $zone_id, ]); if ($success === false) { diff --git a/src/Engine/V1/AbstractAsset.php b/src/Engine/V1/AbstractAsset.php index ef6434dc..e81e089f 100644 --- a/src/Engine/V1/AbstractAsset.php +++ b/src/Engine/V1/AbstractAsset.php @@ -272,7 +272,7 @@ protected function getFallbackCarbonIntensityFromEmber(DateTimeInterface $day, Z // No result, try to find a zone by country $zone = new Zone(); - $zone->getByItem($this->item, null, true); + $zone->getByAsset($this->item); $result = $DB->request($request); if ($result->count() === 1) { return $result->current(); diff --git a/src/Impact/History/AbstractAsset.php b/src/Impact/History/AbstractAsset.php index 7f7d5eed..c2522538 100644 --- a/src/Impact/History/AbstractAsset.php +++ b/src/Impact/History/AbstractAsset.php @@ -154,9 +154,6 @@ public function evaluateItems(): int */ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $end_date = null): int { - /** @var DBmysql $DB */ - global $DB; - $itemtype = static::$itemtype; $item = $itemtype::getById($id); if ($item === false) { @@ -185,11 +182,9 @@ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $e * We NEED to check memory usage to avoid running out of memory * @see DbMysql::doQuery() */ - $memory_limit = GlpiToolbox::getMemoryLimit() - 8 * 1024 * 1024; - if ($memory_limit < 0) { - // May happen in test; seems that ini_get("memory_limits") returns - // enpty string in PHPUnit environment - $memory_limit = null; + $memory_limit = GlpiToolbox::getMemoryLimit(); + if ($memory_limit) { + $memory_limit -= 8 * 1024 * 1024; } foreach ($gaps as $gap) { // $date_cursor = DateTime::createFromFormat('U', $gap['start']); @@ -231,9 +226,8 @@ public function evaluateItem(int $id, ?DateTime $start_date = null, ?DateTime $e protected function evaluateItemPerDay(CommonDBTM $item, EngineInterface $engine, DateTimeInterface $day): bool { $energy = $engine->getEnergyPerDay($day); - $zone = new Zone(); - $zone->getByItem($item /* ,$date_cursor */); - if ($zone->isNewItem()) { + $zone = Zone::getByAsset($item); + if ($zone === null) { return false; } diff --git a/src/Zone.php b/src/Zone.php index b0fd84df..0b2d58c4 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -165,57 +165,74 @@ public function rawSearchOptions() * * @param CommonDBTM $item * @return Zone|null + * @todo : de-staticify the method */ public static function getByLocation(CommonDBTM $item): ?Zone { - /** @var DBmysql $DB */ - global $DB; - if ($item->isNewItem()) { return null; } - if (($item->fields['country'] ?? '') == '' && ($item->fields['state'] ?? '') == '') { + $request = self::getByLocationRequest(); + $request['WHERE'] = [ + Location::getTableField('locations_id') => $item->getID(), + ]; + $zone = new self(); + if (!$zone->getFromDBByRequest($request)) { return null; } - // TODO: support translations - $glpi_location_table = GlpiLocation::getTable(); + return $zone; + } + + /** + * Get the request fragment to find a zone by location + * + * @return array Request fragment + */ + private static function getByLocationRequest(): array + { + $location_table = Location::getTable(); + $source_zone_table = Source_Zone::getTable(); $zone_table = Zone::getTable(); - $request = [ - 'SELECT' => Zone::getTableField('id'), - 'FROM' => $zone_table, + return [ 'INNER JOIN' => [ - $glpi_location_table => [ + $source_zone_table => [ 'FKEY' => [ - $glpi_location_table => 'state', - $zone_table => 'name', - ], + $zone_table => 'id', + $source_zone_table => 'plugin_carbon_zones_id', + ] + ], + $location_table => [ + 'FKEY' => [ + $location_table => 'plugin_carbon_sources_zones_id', + $source_zone_table => 'id' + ] ], ], - 'WHERE' => [ - GlpiLocation::getTableField('id') => $item->getID(), - ] ]; - $iterator = $DB->request($request); - - if ($iterator->count() !== 1) { - // no state found, fallback to country - $request['INNER JOIN'][$glpi_location_table]['FKEY'][$glpi_location_table] = 'country'; - $iterator = $DB->request($request); - if ($iterator->count() !== 1) { - // Give up - return null; - } - } + } - $zone_id = $iterator->current()['id']; - $zone = Zone::getById($zone_id); - if ($zone === false) { - return null; - } + /** + * Get the request fragment to find a zone by asset + * + * @param class-string $itemtype asset type + * @return array Request fragment + */ + private static function getByAssetRequest(string $itemtype): array + { + $glpi_location_table = GlpiLocation::getTable(); + $location_table = Location::getTable(); + $itemtype_table = (new DbUtils())->getTableForItemType($itemtype); + $request = self::getByLocationRequest(); + $request['INNER JOIN'][$itemtype_table] = [ + 'FKEY' => [ + $itemtype_table => 'locations_id', + $location_table => 'locations_id', + ] + ]; - return $zone; + return $request; } /** @@ -223,12 +240,10 @@ public static function getByLocation(CommonDBTM $item): ?Zone * * @param CommonDBTM $item * @return Zone|null + * @todo : de-staticify the method */ public static function getByAsset(CommonDBTM $item): ?Zone { - /** @var DBmysql $DB */ - global $DB; - if (!isset($item->fields[GlpiLocation::getForeignKeyField()])) { return null; } @@ -237,50 +252,13 @@ public static function getByAsset(CommonDBTM $item): ?Zone return null; } - // TODO: support translations - $glpi_location_table = GlpiLocation::getTable(); - $zone_table = Zone::getTable(); - $item_table = $item::getTable(); - $state_field = GlpiLocation::getTableField('state'); - $request = [ - 'SELECT' => Zone::getTableField('id'), - 'FROM' => $zone_table, - 'INNER JOIN' => [ - $glpi_location_table => [ - 'FKEY' => [ - $glpi_location_table => 'state', - $zone_table => 'name', - ], - ], - $item_table => [ - 'FKEY' => [ - $item_table => 'locations_id', - $glpi_location_table => 'id', - ], - ], - ], - 'WHERE' => [ - $state_field => ['<>', ''], - $item::getTableField('id') => $item->getID(), - ] + $request = self::getByAssetRequest($item->getType()); + $request['WHERE'] = [ + $item::getTableField('id') => $item->getID(), ]; - $iterator = $DB->request($request); - - if ($iterator->count() !== 1) { - // no state found, fallback to country - $request['INNER JOIN'][$glpi_location_table]['FKEY'][$glpi_location_table] = 'country'; - unset($request['WHERE'][$state_field]); - $request['WHERE'][GlpiLocation::getTableField('country')] = ['<>', '']; - $iterator = $DB->request($request); - if ($iterator->count() !== 1) { - // Give up - return null; - } - } - $zone_id = $iterator->current()['id']; - $zone = Zone::getById($zone_id); - if ($zone === false) { + $zone = new self(); + if (!$zone->getFromDBByRequest($request)) { return null; } @@ -316,7 +294,7 @@ public function hasHistoricalData(): bool * @param CommonDBTM $item * @param null|DateTime $date Date for which the zone must be found * @param bool $use_country Do not search by state first - * @return bool + * @return bool true if found in DB, false otherwise */ public function getByItem(CommonDBTM $item, ?DateTime $date = null, bool $use_country = false): bool { @@ -366,7 +344,13 @@ public function getByItem(CommonDBTM $item, ?DateTime $date = null, bool $use_co throw new LogicException('Not implemented yet'); } - public static function getRestrictBySourceCondition(int $source_id) + /** + * Undocumented function + * + * @param integer $source_id + * @return array a request fragment + */ + public static function getRestrictBySourceCondition(int $source_id): array { $source_zone_table = Source_Zone::getTable(); $zone_table = Zone::getTable(); diff --git a/tests/units/Impact/History/ComputerTest.php b/tests/units/Impact/History/ComputerTest.php index b1050bf4..b327c057 100644 --- a/tests/units/Impact/History/ComputerTest.php +++ b/tests/units/Impact/History/ComputerTest.php @@ -32,12 +32,10 @@ namespace GlpiPlugin\Carbon\Impact\History\Tests; -use CommonDBTM; use Computer as GlpiComputer; -use DateInterval; use GlpiPlugin\Carbon\Impact\History\Computer; use GlpiPlugin\Carbon\Tests\Impact\History\CommonAsset; -use Location; +use Location as GlpiLocation; use ComputerModel as GlpiComputerModel; use ComputerType as GlpiComputerType; use DateTime; @@ -45,6 +43,9 @@ use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\ComputerType; use GlpiPlugin\Carbon\ComputerUsageProfile; +use GlpiPlugin\Carbon\Location; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\UsageInfo; use GlpiPlugin\Carbon\Zone; @@ -85,9 +86,26 @@ public function testEvaluateItem() $entities_id = $this->isolateInEntity('glpi', 'glpi'); $model_power = 55; - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec', ]); + $source = new Source(); // This source exists after a fresh install + $source->getFromDBByCrit([ + 'name' => 'Hydro Quebec' + ]); + $zone = new Zone(); // This zone exists after a fresh install + $zone->getFromDBByCrit([ + 'name' => 'Quebec' + ]); + $source_zone = new Source_Zone(); // the relation source / zone also exists after a fresh install + $source_zone->getFromDBByCrit([ + $source::getForeignKeyField() => $source->getID(), + $zone::getForeignKeyField() => $zone->getID() + ]); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID() + ]); $model = $this->createItem(GlpiComputerModel::class, ['power_consumption' => $model_power]); $glpi_type = $this->createItem(GlpiComputerType::class); $type = $this->createItem(ComputerType::class, [ @@ -96,7 +114,7 @@ public function testEvaluateItem() $asset = $this->createItem(GlpiComputer::class, [ 'computertypes_id' => $glpi_type->getID(), 'computermodels_id' => $model->getID(), - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), 'date_creation' => '2024-01-01', 'date_mod' => null, ]); @@ -203,16 +221,16 @@ public function testCanHistorize() $this->assertFalse($history->canHistorize($id)); // Add an empty location - $location = $this->createItem(Location::class); + $glpi_location = $this->createItem(GlpiLocation::class); $computer->update([ 'id' => $id, - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $this->assertFalse($history->canHistorize($id)); // Add a country to the location - $location->update([ - 'id' => $location->getID(), + $glpi_location->update([ + 'id' => $glpi_location->getID(), 'country' => 'France', ]); $this->assertFalse($history->canHistorize($id)); @@ -400,9 +418,9 @@ public function testComputerWithEmptyLocationIsNotHistorizable() { $history = new Computer(); - $location = $this->createItem(Location::class); + $glpi_location = $this->createItem(GlpiLocation::class); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $expected = [ 'is_deleted' => true, @@ -429,11 +447,11 @@ public function testComputerWithLocationAndCountryIsNotHistorizable() { $history = new Computer(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'France' ]); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $expected = [ 'is_deleted' => true, @@ -460,11 +478,11 @@ public function testComputerWithLocationAndStateIsNotHistorizable() { $history = new Computer(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec' ]); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $expected = [ 'is_deleted' => true, @@ -678,7 +696,7 @@ public function testComputerWithEverythingIsHistorizable() { $history = new Computer(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'France' ]); $glpi_computer_type = $this->createItem(GlpiComputerType::class); @@ -687,7 +705,7 @@ public function testComputerWithEverythingIsHistorizable() 'computertypes_id' => $glpi_computer_type->getID(), ]); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), 'computertypes_id' => $glpi_computer_type->getID(), ]); $management = $this->createItem(Infocom::class, [ diff --git a/tests/units/LocationTest.php b/tests/units/LocationTest.php index a20260cb..5f425777 100644 --- a/tests/units/LocationTest.php +++ b/tests/units/LocationTest.php @@ -297,11 +297,8 @@ public function testEnableCarbonIntensityDownload() $this->assertFalse($result); // Test when the zone matches a source and download switches to enabled - $source = $this->createItem(Source::class, [ - 'name' => 'baz', - ]); + $source = $this->createItem(Source::class); $zone = $this->createItem(Zone::class, [ - 'name' => 'baz', 'plugin_carbon_sources_id_historical' => $source->getID(), ]); $source_zone = $this->createItem(Source_Zone::class, [ @@ -309,8 +306,10 @@ public function testEnableCarbonIntensityDownload() $source::getForeignKeyField() => $source->getID(), 'is_download_enabled' => 0, ]); - $glpi_location = $this->createItem(GlpiLocation::class, [ - 'country' => 'baz' + $glpi_location = $this->createItem(GlpiLocation::class); + $location = $this->createItem(Location::class, [ + $glpi_location::getForeignKeyField() => $glpi_location->getID(), + $source_zone::getForeignKeyField() => $source_zone->getID(), ]); $result = $this->callPrivateMethod($instance, 'enableCarbonIntensityDownload', $glpi_location); $this->assertTrue($result); diff --git a/tests/units/ZoneTest.php b/tests/units/ZoneTest.php index 6c61bfea..05b5a836 100644 --- a/tests/units/ZoneTest.php +++ b/tests/units/ZoneTest.php @@ -34,64 +34,45 @@ use Computer; use DBmysql; +use GlpiPlugin\Carbon\Location; use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\Zone; -use Location; +use Location as GlpiLocation; class ZoneTest extends DbTestCase { public function testGetByLocation() { // Test with a new Location object - $output = Zone::getByLocation(new Location()); + $output = Zone::getByLocation(new GlpiLocation()); $this->assertNull($output); - // Test with a Location object that has no country or state - $location = $this->createItem(Location::class); + // Test with a core location without plugin location child item + $location = $this->createItem(GlpiLocation::class); $output = Zone::getByLocation($location); $this->assertNull($output); - // Test with a Location object that has a country + // Test with a core location which has a location child without source_zone + $glpi_location = $this->createItem(GlpiLocation::class); $location = $this->createItem(Location::class, [ - 'country' => 'foo' - ]); - $output = Zone::getByLocation($location); - $this->assertNull($output); - - // Test with a Location object that has a country and a zoone exists for this location - $zone = $this->createItem(Zone::class, [ - 'name' => 'foo' - ]); - $output = Zone::getByLocation($location); - $this->assertEquals($output->getID(), $zone->getID()); - - // Test with a Location object that has a state - $location = $this->createItem(Location::class, [ - 'state' => 'bar' + 'locations_id' => $location->getID() ]); - $output = Zone::getByLocation($location); + $output = Zone::getByLocation($glpi_location); $this->assertNull($output); - // Test with a Location object that has a state and a zone exists for this location - $zone = $this->createItem(Zone::class, [ - 'name' => 'bar' + // Test with a location which is associated to a source_zone + $zone = $this->createItem(Zone::class); + $source = $this->createItem(Source::class); + $source_zone = $this->createItem(Source_Zone::class, [ + $zone::getForeignKeyField() => $zone->getID(), + $source::getForeignKeyField() => $source->getID(), ]); - $output = Zone::getByLocation($location); - $this->assertEquals($output->getID(), $zone->getID()); - - // Test with a Location object that has both country and state + $glpi_location = $this->createItem(GlpiLocation::class); $location = $this->createItem(Location::class, [ - 'country' => 'fooo', - 'state' => 'baz' - ]); - $output = Zone::getByLocation($location); - $this->assertNull($output); - // Test with a Location object that has both country and state and a zone exists for this location - $zone = $this->createItem(Zone::class, [ - 'name' => 'baz' + 'locations_id' => $location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID(), ]); - $output = Zone::getByLocation($location); - $this->assertEquals($output->getID(), $zone->getID()); } public function testGetByAsset() @@ -100,57 +81,48 @@ public function testGetByAsset() $output = Zone::getByAsset(new Computer()); $this->assertNull($output); - // Test with a Computer object that has a location with country and no matching zone - $location = $this->createItem(Location::class, [ - 'country' => 'foo' - ]); + // Test with a Computer object that has a location without child location data + $glpi_location = $this->createItem(GlpiLocation::class); $computer = $this->createItem(Computer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $output = Zone::getByAsset($computer); $this->assertNull($output); - // Test with a Computer object that has a location with country and a matching zone - $zone = $this->createItem(Zone::class, [ - 'name' => 'foo' + // Test with a Computer object that has a location with child location data + $zone = $this->createItem(Zone::class); + $source = $this->createItem(Source::class); + $source_zone = $this->createItem(Source_Zone::class, [ + $zone::getForeignKeyField() => $zone->getID(), + $source::getForeignKeyField() => $source->getID(), ]); - $output = Zone::getByAsset($computer); - $this->assertEquals($output->getID(), $zone->getID()); - - // Test with a Computer object that has a location with state and no matching zone + $glpi_location = $this->createItem(GlpiLocation::class); $location = $this->createItem(Location::class, [ - 'state' => 'bar' + 'locations_id' => $glpi_location->getID(), ]); $computer = $this->createItem(Computer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $output = Zone::getByAsset($computer); - $this->assertNull($output); + $this->assertEquals(null, $output); - // Test with a Computer object that has a location with state and a matching zone - $zone = $this->createItem(Zone::class, [ - 'name' => 'bar' + // Test with a Computer object that has a location matching a source_zone + $zone = $this->createItem(Zone::class); + $source = $this->createItem(Source::class); + $source_zone = $this->createItem(Source_Zone::class, [ + $zone::getForeignKeyField() => $zone->getID(), + $source::getForeignKeyField() => $source->getID(), ]); - $output = Zone::getByAsset($computer); - $this->assertEquals($output->getID(), $zone->getID()); - - // Test with a Computer object that has a location with both country and state and no matching zone + $glpi_location = $this->createItem(GlpiLocation::class); $location = $this->createItem(Location::class, [ - 'country' => 'fooo', - 'state' => 'baz' + 'locations_id' => $glpi_location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID(), ]); $computer = $this->createItem(Computer::class, [ - 'locations_id' => $location->getID(), - ]); - $output = Zone::getByAsset($computer); - $this->assertNull($output); - - // Test with a Computer object that has a location with both country and state and a matching zone - $zone = $this->createItem(Zone::class, [ - 'name' => 'baz' + 'locations_id' => $glpi_location->getID(), ]); $output = Zone::getByAsset($computer); - $this->assertEquals($output->getID(), $zone->getID()); + $this->assertEquals($zone->getID(), $output->getID()); } public function testHasHistoricalData() @@ -191,10 +163,10 @@ public function testGetByItem() $this->assertFalse($zone->getByItem($item)); // Test with a Computer object that has a location with country and no matching zone - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'foo' ]); - $item->update(['id' => $item->getID(), 'locations_id' => $location->getID()]); + $item->update(['id' => $item->getID(), 'locations_id' => $glpi_location->getID()]); $zone = new Zone(); $this->assertFalse($zone->getByItem($item)); @@ -207,10 +179,10 @@ public function testGetByItem() $this->assertEquals($zone->getID(), $expected_zone->getID()); // Test with a Computer object that has a location with state and no matching zone - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'bar' ]); - $item->update(['id' => $item->getID(), 'locations_id' => $location->getID()]); + $item->update(['id' => $item->getID(), 'locations_id' => $glpi_location->getID()]); $zone = new Zone(); $this->assertFalse($zone->getByItem($item)); @@ -223,11 +195,11 @@ public function testGetByItem() $this->assertEquals($zone->getID(), $expected_zone->getID()); // Test with a Computer object that has a location with both country and state and no matching zone - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'fooo', 'state' => 'baz' ]); - $item->update(['id' => $item->getID(), 'locations_id' => $location->getID()]); + $item->update(['id' => $item->getID(), 'locations_id' => $glpi_location->getID()]); $zone = new Zone(); $this->assertFalse($zone->getByItem($item)); @@ -240,11 +212,11 @@ public function testGetByItem() $this->assertEquals($zone->getID(), $expected_zone->getID()); // Test with a Computer object that has a location with both country and state and a matching zone for state and country - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'foo', 'state' => 'baz' ]); - $item->update(['id' => $item->getID(), 'locations_id' => $location->getID()]); + $item->update(['id' => $item->getID(), 'locations_id' => $glpi_location->getID()]); $zone = new Zone(); $this->assertTrue($zone->getByItem($item)); $this->assertEquals($zone->getID(), $expected_zone->getID()); From 59e8f2cefb32ca818184e704df46132437089cdd Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 3 Oct 2025 10:31:09 +0200 Subject: [PATCH 11/27] test(Install): add message on failure --- tests/install/PluginInstallTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/install/PluginInstallTest.php b/tests/install/PluginInstallTest.php index b523582d..aba90215 100644 --- a/tests/install/PluginInstallTest.php +++ b/tests/install/PluginInstallTest.php @@ -387,7 +387,7 @@ private function checkInitialZones() $zone->getFromDBByCrit([ 'name' => $zone_name, ]); - $this->assertFalse($zone->isNewItem()); + $this->assertFalse($zone->isNewItem(), "Zone '$zone_name' not found"); } } From 7802940067b5da188f519e8b4f7cdaba7f199651 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 3 Oct 2025 10:32:51 +0200 Subject: [PATCH 12/27] tst(Location): fix test method name --- tests/units/LocationTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/units/LocationTest.php b/tests/units/LocationTest.php index 5f425777..e9ae70c2 100644 --- a/tests/units/LocationTest.php +++ b/tests/units/LocationTest.php @@ -195,7 +195,7 @@ public function testOnGlpiLocationPrePurge() * * @return void */ - public function testgetIncompleteLocations() + public function testGetIncompleteLocations() { $iterator = Location::getIncompleteLocations(); $output = $iterator->count(); From bb444d788049c937254f4ec16bb711b972c02a62 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 3 Oct 2025 18:13:23 +0200 Subject: [PATCH 13/27] test(Impact\History\Monitor): update out of date itemtype --- tests/units/Impact/History/MonitorTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/units/Impact/History/MonitorTest.php b/tests/units/Impact/History/MonitorTest.php index 2e679ffa..98fe2149 100644 --- a/tests/units/Impact/History/MonitorTest.php +++ b/tests/units/Impact/History/MonitorTest.php @@ -46,6 +46,7 @@ use MonitorType as GlpiMonitorType; use ComputerType as GlpiComputerType; use DBmysql; +use Glpi\Asset\Asset_PeripheralAsset; use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\ComputerType; use GlpiPlugin\Carbon\ComputerUsageProfile; @@ -134,7 +135,7 @@ public function testEvaluateItem() 'date_creation' => '2024-01-01', 'date_mod' => null, ]); - $computer_asset = $this->createItem(Computer_Item::class, [ + $computer_asset = $this->createItem(Asset_PeripheralAsset::class, [ 'computers_id' => $computer->getID(), 'itemtype' => $asset->getType(), 'items_id' => $asset->getID(), From 1efb06278c8b879cf3e3ca6bb02b3848f5889f36 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Fri, 3 Oct 2025 18:39:04 +0200 Subject: [PATCH 14/27] test: update tests with location /zone relation --- tests/units/Impact/History/MonitorTest.php | 49 +++++++++++++------ .../Impact/History/NetworkEquipmentTest.php | 39 +++++++++++---- 2 files changed, 65 insertions(+), 23 deletions(-) diff --git a/tests/units/Impact/History/MonitorTest.php b/tests/units/Impact/History/MonitorTest.php index 98fe2149..6bca562c 100644 --- a/tests/units/Impact/History/MonitorTest.php +++ b/tests/units/Impact/History/MonitorTest.php @@ -35,23 +35,27 @@ use CommonDBTM; use Computer as GlpiComputer; use ComputerModel; -use Computer_Item; use Monitor as GlpiMonitor; use GlpiPlugin\Carbon\Impact\History\Monitor; use GlpiPlugin\Carbon\Tests\Impact\History\CommonAsset; use Infocom; -use Location; +use Location as GlpiLocation; use DateTime; use MonitorModel as GlpiMonitorModel; use MonitorType as GlpiMonitorType; use ComputerType as GlpiComputerType; use DBmysql; use Glpi\Asset\Asset_PeripheralAsset; +use Computer_Item; use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\ComputerType; use GlpiPlugin\Carbon\ComputerUsageProfile; +use GlpiPlugin\Carbon\Location; use GlpiPlugin\Carbon\MonitorType; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; use GlpiPlugin\Carbon\UsageInfo; +use GlpiPlugin\Carbon\Zone; /** * #CoversMethod \GlpiPlugin\Carbon\Impact\History\Monitor @@ -91,9 +95,26 @@ public function testEvaluateItem() $entities_id = $this->isolateInEntity('glpi', 'glpi'); $model_power = 55; - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec', ]); + $source = new Source(); // This source exists after a fresh install + $source->getFromDBByCrit([ + 'name' => 'Hydro Quebec' + ]); + $zone = new Zone(); // This zone exists after a fresh install + $zone->getFromDBByCrit([ + 'name' => 'Quebec' + ]); + $source_zone = new Source_Zone(); // the relation source / zone also exists after a fresh install + $source_zone->getFromDBByCrit([ + $source::getForeignKeyField() => $source->getID(), + $zone::getForeignKeyField() => $zone->getID() + ]); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID() + ]); $computer_model_power = 80; $computer_model = $this->createItem(ComputerModel::class, ['power_consumption' => $computer_model_power]); @@ -104,7 +125,7 @@ public function testEvaluateItem() $computer = $this->createItem(GlpiComputer::class, [ 'computertypes_id' => $glpi_computer_type->getID(), 'computermodels_id' => $computer_model->getID(), - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $usage_profile = $this->createItem(ComputerUsageProfile::class, [ 'time_start' => '09:00:00', @@ -131,11 +152,11 @@ public function testEvaluateItem() $asset = $this->createItem(GlpiMonitor::class, [ 'monitortypes_id' => $glpi_type->getID(), 'monitormodels_id' => $model->getID(), - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), 'date_creation' => '2024-01-01', 'date_mod' => null, ]); - $computer_asset = $this->createItem(Asset_PeripheralAsset::class, [ + $computer_asset = $this->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), 'itemtype' => $asset->getType(), 'items_id' => $asset->getID(), @@ -376,9 +397,9 @@ public function testMonitorWithEmptyLocationIsNotHistorizable() $history = new Monitor(); $monitor = $this->createItem(GlpiMonitor::class); - $location = $this->createItem(Location::class); + $glpi_location = $this->createItem(GlpiLocation::class); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $computer_item = $this->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), @@ -412,11 +433,11 @@ public function testMonitorWithLocationWithCountryIsNotHistorizable() $history = new Monitor(); $monitor = $this->createItem(GlpiMonitor::class); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'France', ]); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $computer_item = $this->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), @@ -450,12 +471,12 @@ public function testMonitorWithLocationWithStateIsNotHistorizable() { $history = new Monitor(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec', ]); $monitor = $this->createItem(GlpiMonitor::class); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $computer_item = $this->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), @@ -658,7 +679,7 @@ public function testMonitorIsHistorizable() { $history = new Monitor(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'France', ]); $glpi_monitor_model = $this->createItem(GlpiMonitorModel::class, [ @@ -668,7 +689,7 @@ public function testMonitorIsHistorizable() 'monitormodels_id' => $glpi_monitor_model->getID(), ]); $computer = $this->createItem(GlpiComputer::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $computer_item = $this->createItem(Computer_Item::class, [ 'computers_id' => $computer->getID(), diff --git a/tests/units/Impact/History/NetworkEquipmentTest.php b/tests/units/Impact/History/NetworkEquipmentTest.php index 1f50dcb8..565a0f4f 100644 --- a/tests/units/Impact/History/NetworkEquipmentTest.php +++ b/tests/units/Impact/History/NetworkEquipmentTest.php @@ -36,11 +36,15 @@ use GlpiPlugin\Carbon\CarbonEmission; use GlpiPlugin\Carbon\Tests\Impact\History\CommonAsset; use GlpiPlugin\Carbon\Impact\History\NetworkEquipment; +use GlpiPlugin\Carbon\Location; use GlpiPlugin\Carbon\NetworkEquipmentType; +use GlpiPlugin\Carbon\Source; +use GlpiPlugin\Carbon\Source_Zone; +use GlpiPlugin\Carbon\Zone; use Infocom; use NetworkEquipmentType as GlpiNetworkEquipmentType; use NetworkEquipment as GlpiNetworkEquipment; -use Location; +use Location as GlpiLocation; use NetworkEquipmentModel as GlpiNetworkEquipmentModel; /** @@ -80,9 +84,26 @@ public function testEvaluateItem() $entities_id = $this->isolateInEntity('glpi', 'glpi'); $model_power = 100; - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec', ]); + $source = new Source(); // This source exists after a fresh install + $source->getFromDBByCrit([ + 'name' => 'Hydro Quebec' + ]); + $zone = new Zone(); // This zone exists after a fresh install + $zone->getFromDBByCrit([ + 'name' => 'Quebec' + ]); + $source_zone = new Source_Zone(); // the relation source / zone also exists after a fresh install + $source_zone->getFromDBByCrit([ + $source::getForeignKeyField() => $source->getID(), + $zone::getForeignKeyField() => $zone->getID() + ]); + $location = $this->createItem(Location::class, [ + 'locations_id' => $glpi_location->getID(), + 'plugin_carbon_sources_zones_id' => $source_zone->getID() + ]); $model = $this->createItem(GlpiNetworkEquipmentModel::class, ['power_consumption' => $model_power]); $glpi_type = $this->createItem(GlpiNetworkEquipmentType::class); $type = $this->createItem(NetworkEquipmentType::class, [ @@ -91,7 +112,7 @@ public function testEvaluateItem() $asset = $this->createItem(GlpiNetworkEquipment::class, [ 'networkequipmenttypes_id' => $glpi_type->getID(), 'networkequipmentmodels_id' => $model->getID(), - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), 'date_creation' => '2024-01-01', 'date_mod' => null, ]); @@ -258,9 +279,9 @@ public function testNetDeviceWithEmptyLocationIsNotHistorizable() { $history = new NetworkEquipment(); - $location = $this->createItem(Location::class); + $glpi_location = $this->createItem(GlpiLocation::class); $network_equipment = $this->createItem(GlpiNetworkEquipment::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $result = $history->getHistorizableDiagnosis($network_equipment); $expected = [ @@ -286,11 +307,11 @@ public function testNetDeviceWithLocationWithCountryIsNotHistorizable() { $history = new NetworkEquipment(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'country' => 'France', ]); $network_equipment = $this->createItem(GlpiNetworkEquipment::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $result = $history->getHistorizableDiagnosis($network_equipment); $expected = [ @@ -316,11 +337,11 @@ public function testNetDeviceWithLocationWithStateIsNotHistorizable() { $history = new NetworkEquipment(); - $location = $this->createItem(Location::class, [ + $glpi_location = $this->createItem(GlpiLocation::class, [ 'state' => 'Quebec', ]); $network_equipment = $this->createItem(GlpiNetworkEquipment::class, [ - 'locations_id' => $location->getID(), + 'locations_id' => $glpi_location->getID(), ]); $result = $history->getHistorizableDiagnosis($network_equipment); $expected = [ From 1981acf1b2d4fc251877a4fbddf2c837deeab9e5 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 29 Sep 2025 15:02:53 +0200 Subject: [PATCH 15/27] feat(Location): associate location to a carbon intensity zone --- hook.php | 14 +++++++------- tests/units/ZoneTest.php | 1 - 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/hook.php b/hook.php index c78e9556..e8f9de89 100644 --- a/hook.php +++ b/hook.php @@ -152,13 +152,13 @@ function plugin_carbon_getAddSearchOptionsNew($itemtype): array return SearchOptions::getCoreSearchOptions($itemtype); } -/** - * Callback before showing save / update button on an item form - * - * @param array $params 'item' => CommonDBTM - * 'options => array - * @return void - */ +// /** +// * Callback before showing save / update button on an item form +// * +// * @param array $params 'item' => CommonDBTM +// * 'options => array +// * @return void +// */ // function plugin_carbon_postItemForm(array $params) // { // switch ($params['item']->getType()) { diff --git a/tests/units/ZoneTest.php b/tests/units/ZoneTest.php index 05b5a836..224094ef 100644 --- a/tests/units/ZoneTest.php +++ b/tests/units/ZoneTest.php @@ -33,7 +33,6 @@ namespace GlpiPlugin\Carbon\Tests; use Computer; -use DBmysql; use GlpiPlugin\Carbon\Location; use GlpiPlugin\Carbon\Source; use GlpiPlugin\Carbon\Source_Zone; From bd8132fecbe1450ed83168ac29ec5d46354f98d3 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 6 Oct 2025 08:31:01 +0200 Subject: [PATCH 16/27] fix(Install): avoid use of non-existing classes in migration code --- .../01_fix_source_zone_quebec.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/install/migration/update_1.0.0_to_1.0.1/01_fix_source_zone_quebec.php b/install/migration/update_1.0.0_to_1.0.1/01_fix_source_zone_quebec.php index b07b8b0f..12b617b7 100644 --- a/install/migration/update_1.0.0_to_1.0.1/01_fix_source_zone_quebec.php +++ b/install/migration/update_1.0.0_to_1.0.1/01_fix_source_zone_quebec.php @@ -32,9 +32,6 @@ use Glpi\DBAL\QuerySubQuery; use GlpiPlugin\Carbon\CarbonEmission; -use GlpiPlugin\Carbon\CarbonIntensitySource; -use GlpiPlugin\Carbon\CarbonIntensitySource_Zone; -use GlpiPlugin\Carbon\Zone; /** @var DBmysql $DB */ global $DB; @@ -42,9 +39,9 @@ $db_utils = new DbUtils(); // Update and fix the bad relation -$source_table = $db_utils->getTableForItemType(CarbonIntensitySource::class); -$zone_table = $db_utils->getTableForItemType(Zone::class); -$source_zone_table = $db_utils->getTableForItemType(CarbonIntensitySource_Zone::class); +$source_table = 'glpi_plugin_carbon_carbonintensitysources'; +$zone_table = 'glpi_plugin_carbon_zones'; +$source_zone_table = 'glpi_plugin_carbon_carbonintensitysources_zones'; $source_iterator = $DB->request([ 'SELECT' => 'id', 'FROM' => $source_table, @@ -70,7 +67,7 @@ NetworkEquipment::class ]; -$carbon_emission_table = $db_utils->getTableForItemType(CarbonEmission::class); +$carbon_emission_table = 'glpi_plugin_carbon_carbonemissions'; $location_table = $db_utils->getTableForItemType(Location::class); foreach ($itemtypes as $itemtype) { $item_table = $db_utils->getTableForItemType($itemtype); From 7ed0dcedbcda086bfb99defacacd49241e3f8d3e Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 6 Oct 2025 08:33:41 +0200 Subject: [PATCH 17/27] style: php lint --- src/Location.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Location.php b/src/Location.php index acfa62f7..b51fe486 100644 --- a/src/Location.php +++ b/src/Location.php @@ -116,6 +116,7 @@ public function prepareInputForUpdate($input) public function showForLocation(GlpiLocation $item, array $options = []) { + /** @var DBmysql $DB */ global $DB; $this->getFromDBByCrit(['locations_id' => $item->getID()]); @@ -482,7 +483,7 @@ public function getCountryCode(CommonDBTM $item, Geocoder $geocoder): string */ public static function getIncompleteLocations(array $where = []): DBmysqlIterator { - /** @var DBmysql $DB */ + /** @var DBmysql $DB */ global $DB; $where = array_diff_key($where, [ @@ -526,7 +527,7 @@ public static function getIncompleteLocations(array $where = []): DBmysqlIterato public function getSourceZoneId(): int { - /** @var DBmysql */ + /** @var DBmysql $DB */ global $DB; if ($this->isNewItem()) { From 36249c6e780039564fb63520becb65c92d2a4195 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 6 Oct 2025 08:35:12 +0200 Subject: [PATCH 18/27] style(Zone): remove unused var --- src/Zone.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Zone.php b/src/Zone.php index 0b2d58c4..5e493a01 100644 --- a/src/Zone.php +++ b/src/Zone.php @@ -221,7 +221,6 @@ private static function getByLocationRequest(): array */ private static function getByAssetRequest(string $itemtype): array { - $glpi_location_table = GlpiLocation::getTable(); $location_table = Location::getTable(); $itemtype_table = (new DbUtils())->getTableForItemType($itemtype); $request = self::getByLocationRequest(); From cffab41fa6382dfc31a68e8e72b9acc59f722848 Mon Sep 17 00:00:00 2001 From: Thierry Bugier Date: Mon, 6 Oct 2025 08:36:55 +0200 Subject: [PATCH 19/27] style(Location): twig code style --- templates/location.html.twig | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/templates/location.html.twig b/templates/location.html.twig index 501909cc..4db4480f 100644 --- a/templates/location.html.twig +++ b/templates/location.html.twig @@ -45,8 +45,7 @@ __('Boavizta zone', 'carbon'), { 'display_emptychoice': true, - }) - }} + }) }}
@@ -66,8 +65,7 @@ is_fallback: 0, is_carbon_intensity_source: 1 }, - }) - }} + }) }}