diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e33be7f..a48d0704 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [Unreleased] + +### Changed + +- Redesign the mappings, additional information, file preview, injection log and profile rights screens +- Show the mapped and link fields counters, and warn when a field is used both by a mapping and an additional information +- `PluginDatainjectionInjectionType::dropdownLinkedTypes()`, `dropdownFields()` and `showMandatoryCheckbox()` are removed, and `PluginDatainjectionModelcsv::showSample()` returns a response instead of displaying the file + ## [2.15.13] - 2026-11-13 ### Fixed diff --git a/ajax/dropdownChooseField.php b/ajax/dropdownChooseField.php deleted file mode 100644 index 2cd618dd..00000000 --- a/ajax/dropdownChooseField.php +++ /dev/null @@ -1,40 +0,0 @@ -. - * ------------------------------------------------------------------------- - * @copyright Copyright (C) 2007-2023 by DataInjection plugin team. - * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html - * @link https://github.com/pluginsGLPI/datainjection - * ------------------------------------------------------------------------- - */ - -// Direct access to file -if (strpos((string) $_SERVER['PHP_SELF'], "dropdownChooseField.php")) { - header("Content-Type: text/html; charset=UTF-8"); - Html::header_nocache(); -} - -Session::checkCentralAccess(); -// Reads the session only: release it so that the calls of a tab run in parallel -Session::writeClose(); -PluginDatainjectionInjectionType::dropdownFields($_POST); diff --git a/ajax/dropdownMandatory.php b/ajax/dropdownMandatory.php deleted file mode 100644 index f2f575b3..00000000 --- a/ajax/dropdownMandatory.php +++ /dev/null @@ -1,40 +0,0 @@ -. - * ------------------------------------------------------------------------- - * @copyright Copyright (C) 2007-2023 by DataInjection plugin team. - * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html - * @link https://github.com/pluginsGLPI/datainjection - * ------------------------------------------------------------------------- - */ - -// Direct access to file -if (strpos((string) $_SERVER['PHP_SELF'], "dropdownMandatory.php")) { - header("Content-Type: text/html; charset=UTF-8"); - Html::header_nocache(); -} - -Session::checkCentralAccess(); -// Reads the session only: release it so that the calls of a tab run in parallel -Session::writeClose(); -PluginDatainjectionInjectionType::showMandatoryCheckbox($_POST); diff --git a/ajax/fieldsChoices.php b/ajax/fieldsChoices.php new file mode 100644 index 00000000..066af793 --- /dev/null +++ b/ajax/fieldsChoices.php @@ -0,0 +1,78 @@ +. + * ------------------------------------------------------------------------- + * @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + * @link https://github.com/pluginsGLPI/datainjection + * ------------------------------------------------------------------------- + */ +use Glpi\Exception\Http\BadRequestHttpException; +use Symfony\Component\HttpFoundation\JsonResponse; + +use function Safe\json_decode; + +Html::header_nocache(); + +Session::checkRight('plugin_datainjection_model', READ); + +$itemtype = (string) ($_POST['itemtype'] ?? PluginDatainjectionInjectionType::NO_VALUE); +$primary_type = (string) ($_POST['primary_type'] ?? ''); +$called_by = (string) ($_POST['called_by'] ?? ''); + +try { + $mapping_or_info = json_decode((string) ($_POST['mapping_or_info'] ?? ''), true); +} catch (JsonException) { + throw new BadRequestHttpException(); +} + +if ( + !is_a($primary_type, CommonDBTM::class, true) + || ($itemtype !== PluginDatainjectionInjectionType::NO_VALUE && !is_a($itemtype, CommonDBTM::class, true)) + || !in_array($called_by, [PluginDatainjectionMapping::class, PluginDatainjectionInfo::class], true) + || !isset($mapping_or_info['models_id'], $mapping_or_info['value']) +) { + throw new BadRequestHttpException(); +} + +// Reads the session only: release it so that the calls of a tab run in parallel +Session::writeClose(); + +$choices = PluginDatainjectionInjectionType::getFieldsChoices([ + 'itemtype' => $itemtype, + 'primary_type' => $primary_type, + 'called_by' => $called_by, + 'mapping_or_info' => $mapping_or_info, + 'need_decode' => false, +]); + +// Use a list of pairs to keep the options order on client side +$fields = []; +foreach ($choices['fields'] as $key => $label) { + $fields[] = [$key, $label]; +} + +return new JsonResponse([ + 'fields' => $fields, + 'value' => $choices['value'], +]); diff --git a/ajax/inject_batch.php b/ajax/inject_batch.php index d86e647d..6ea0cb5f 100644 --- a/ajax/inject_batch.php +++ b/ajax/inject_batch.php @@ -27,9 +27,8 @@ * @link https://github.com/pluginsGLPI/datainjection * ------------------------------------------------------------------------- */ -use function Safe\json_encode; +use Symfony\Component\HttpFoundation\JsonResponse; -header("Content-Type: application/json; charset=UTF-8"); Html::header_nocache(); Session::checkRight(PluginDatainjectionClientInjection::$rightname, READ); @@ -37,6 +36,6 @@ $offset = (int) ($_POST['offset'] ?? 0); $batch_size = (int) ($_POST['batch_size'] ?? 10); -echo json_encode( +return new JsonResponse( PluginDatainjectionClientInjection::processBatch($offset, $batch_size), ); diff --git a/front/info.form.php b/front/info.form.php index 5f21cb55..2e9dceaa 100644 --- a/front/info.form.php +++ b/front/info.form.php @@ -37,7 +37,7 @@ PluginDatainjectionInfo::manageInfos($_POST['models_id'], $_POST); } elseif (isset($_POST["delete"])) { $info = new PluginDatainjectionInfo(); - foreach ($_POST["item"] as $key => $val) { + foreach ($_POST["item"] ?? [] as $key => $val) { $input = ['id' => $key]; if ($val == 1) { $info->check($key, UPDATE); diff --git a/front/model.form.php b/front/model.form.php index 95f32e3c..848fa4b7 100644 --- a/front/model.form.php +++ b/front/model.form.php @@ -101,8 +101,7 @@ $model->check($_GET['sample'], READ); $modeltype = PluginDatainjectionModel::getInstance($model->getField('filetype')); $modeltype->getFromDBByModelID($model->getField('id')); - $modeltype->showSample($model); - return; + return $modeltype->showSample($model); } Html::header( diff --git a/inc/clientinjection.class.php b/inc/clientinjection.class.php index a8a12128..bff02efd 100644 --- a/inc/clientinjection.class.php +++ b/inc/clientinjection.class.php @@ -118,6 +118,7 @@ public static function showUploadFileForm($options = []) 'url' => $url, 'models_id' => $options['models_id'] ?? null, 'confirm' => $confirm, + 'warn_override' => $options['warn_override'] ?? true, 'submit_label' => $options['submit'] ?? __('Launch the import', 'datainjection'), 'file_encoding_values' => PluginDatainjectionDropdown::getFileEncodingValue(), ]; @@ -177,8 +178,6 @@ public static function showInjectionForm(PluginDatainjectionModel $model, $entit 'result_url' => $result_url, 'plugin_url' => plugin_datainjection_geturl(), ]); - - echo ""; } diff --git a/inc/info.class.php b/inc/info.class.php index ff7bae6a..6bc8c9f1 100644 --- a/inc/info.class.php +++ b/inc/info.class.php @@ -100,43 +100,17 @@ public static function showAddInfo(PluginDatainjectionModel $model, $canedit = f { if ($canedit) { - echo "
"; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - - echo ""; - echo ""; - echo sprintf("", $infos_id); - echo sprintf("", $infos_id); - echo ""; - - echo ""; - echo ""; - - echo "
" . __s('Tables', 'datainjection') . "" . _sn('Field', 'Fields', 2) . "" . __s('Mandatory information', 'datainjection') . "
"; - $infos_id = -1; - $info = new PluginDatainjectionInfo(); + $info = new PluginDatainjectionInfo(); + $info->getEmpty(); $info->fields['id'] = -1; $info->fields['models_id'] = $model->fields['id']; - $info->getEmpty(); - $rand = PluginDatainjectionInjectionType::dropdownLinkedTypes( - $info, - ['primary_type' - => $model->fields['itemtype'], - ], - ); - echo "
"; - echo ""; - echo ""; - echo "
"; - Html::closeForm(); - echo "
"; + TemplateRenderer::getInstance()->display('@datainjection/info_add_form.html.twig', [ + 'form_action' => Toolbox::getItemTypeFormURL(self::class), + 'fields_url' => plugin_datainjection_geturl() . "ajax/fieldsChoices.php", + 'info' => PluginDatainjectionInjectionType::getRow($info, $model->fields['itemtype']), + 'model_id' => $model->fields['id'], + ]); } } @@ -151,81 +125,24 @@ public static function showFormInfos(PluginDatainjectionModel $model) self::showAddInfo($model, $canedit); $model->loadInfos(); - $nb = count($model->getInfos()); - $rand = mt_rand(); - if ($nb > 0) { - echo sprintf(""; - echo ""; - echo ""; - if ($canedit) { - echo ""; - } - - echo ""; - echo ""; - echo ""; - echo ""; - - foreach ($model->getInfos() as $info) { - $infos_id = $info->fields['id']; - echo ""; - if ($canedit) { - echo ""; - } - - echo ""; - $fields_html = PluginDatainjectionInjectionType::getFieldsHtml( - $info, - ['primary_type' => $model->fields['itemtype']], - ); - echo sprintf("", $infos_id, $fields_html['field']); - echo sprintf("", $infos_id, $fields_html['mandatory']); - } - - if ($canedit) { - echo ""; - echo ""; - - $formname = 'info_form' . $rand; - echo "
 " . __s('Tables', 'datainjection') . "" . __s('Fields', 'datainjection') . "" . __s('Mandatory information', 'datainjection') . "
"; - $sel = ""; - if (isset($_GET["select"]) && ($_GET["select"] == "all")) { - $sel = "checked"; - } - - echo "", $sel); - echo ""; - $rand = PluginDatainjectionInjectionType::dropdownLinkedTypes( - $info, - ['primary_type' - => $model->fields['itemtype'], - ], - false, - ); - echo "%s%s
"; - echo ""; - echo ""; - echo "
"; - $arrow = "fas fa-level-up-alt"; - - echo ""; - echo sprintf("", $arrow); - echo ""; - echo ""; - echo ""; - echo ""; - echo "
"; - echo sprintf("", $formname) . __s('Check all') . "/"; - echo sprintf("", $formname) . __s('Uncheck all') . ""; - - echo " "; - echo "
"; - } + if (count($model->getInfos()) === 0) { + return; + } - echo ""; - Html::closeForm(); + $infos = []; + foreach ($model->getInfos() as $info) { + $infos[] = PluginDatainjectionInjectionType::getRow($info, $model->fields['itemtype']); } + + TemplateRenderer::getInstance()->display('@datainjection/infos_form.html.twig', [ + 'form_action' => Toolbox::getItemTypeFormURL(self::class), + 'fields_url' => plugin_datainjection_geturl() . "ajax/fieldsChoices.php", + 'infos' => $infos, + 'nb_mandatory' => count(array_filter(array_column($infos, 'is_mandatory'))), + 'canedit' => $canedit, + 'select_all' => ($_GET['select'] ?? '') === 'all', + 'model_id' => $model->fields['id'], + ]); } @@ -334,9 +251,16 @@ public static function displayAdditionalInformation(PluginDatainjectionInfo $inf $info->fields['value'], ); if ($option) { - echo "" . htmlescape(sprintf(__('%1$s - %2$s'), $info->fields['itemtype']::getTypeName(1), $option['name'])) . ""; + ob_start(); self::showAdditionalInformation($info, $option, $injectionClass, $values); - echo ""; + $field_html = ob_get_clean(); + + TemplateRenderer::getInstance()->display('@datainjection/info_additional_information.html.twig', [ + 'name' => $info->getInputName(), + 'label' => sprintf(__('%1$s - %2$s'), $info->fields['itemtype']::getTypeName(1), $option['name']), + 'field_html' => $field_html, + 'is_mandatory' => $info->isMandatory(), + ]); } } @@ -365,12 +289,11 @@ public static function showAdditionalInformation( $value = ($option['default'] ?? ''); } - echo sprintf(""; + TemplateRenderer::getInstance()->display('@datainjection/info_additional_input.html.twig', [ + 'type' => 'text', + 'name' => $name, + 'value' => $value, + ]); break; case 'dropdown': @@ -411,7 +334,11 @@ public static function showAdditionalInformation( break; case 'multiline_text': - echo sprintf("", $name, $value); + TemplateRenderer::getInstance()->display('@datainjection/info_additional_input.html.twig', [ + 'type' => 'textarea', + 'name' => $name, + 'value' => $value, + ]); break; case 'dropdown_integer': @@ -436,7 +363,10 @@ public static function showAdditionalInformation( break; case 'password': - echo sprintf("", $name); + TemplateRenderer::getInstance()->display('@datainjection/info_additional_input.html.twig', [ + 'type' => 'password', + 'name' => $name, + ]); break; default: @@ -445,10 +375,6 @@ public static function showAdditionalInformation( $injectionClass->showAdditionalInformation($info, $option); } } - - if ($info->isMandatory()) { - echo " *"; - } } diff --git a/inc/injectiontype.class.php b/inc/injectiontype.class.php index a8f45a56..1096a512 100644 --- a/inc/injectiontype.class.php +++ b/inc/injectiontype.class.php @@ -31,8 +31,6 @@ use function Safe\json_decode; use function Safe\json_encode; -use function Safe\ob_get_clean; -use function Safe\ob_start; use function Safe\preg_replace; class PluginDatainjectionInjectionType @@ -112,139 +110,36 @@ public static function dropdown($value = '', $only_primary = false) /** * Get all types linked with a primary type * - * @param mixed $mapping_or_info - * @param array $options array - * @param bool $load_fields load the fields dropdown through AJAX on page load - **/ - public static function dropdownLinkedTypes($mapping_or_info, $options = [], bool $load_fields = true) - { - [$p, $values] = self::getLinkedTypesParams($mapping_or_info, $options); - - $mappings_id = $mapping_or_info->fields['id']; - - $rand = Dropdown::showFromArray( - "data[" . $mappings_id . "][itemtype]", - $values, - ['value' => $p['itemtype']], - ); - - $p['itemtype'] = '__VALUE__'; - $di_base_url = plugin_datainjection_geturl(); - $url_field = $di_base_url . "ajax/dropdownChooseField.php"; - $toobserve = "dropdown_data[" . $mapping_or_info->getID() . ('][itemtype]' . $rand); - $toupdate = "span_field_" . $mappings_id; - if ($load_fields) { - Ajax::updateItem($toupdate, $url_field, $p, $toobserve); - } - - Ajax::updateItemOnSelectEvent($toobserve, $toupdate, $url_field, $p); - return $rand; - } - - - /** - * Get the HTML of the fields dropdown and of the mandatory checkbox of a mapping or an info, - * as the AJAX calls of dropdownLinkedTypes() and dropdownFields() load them - * - * @param mixed $mapping_or_info - * @param array $options array + * @param string $primary_type * - * @return array{field: string, mandatory: string} + * @return array itemtype => name, with the empty value on top **/ - public static function getFieldsHtml($mapping_or_info, $options = []): array - { - [$p, $values] = self::getLinkedTypesParams($mapping_or_info, $options); - - //Value the browser selects in the itemtype dropdown - $p['itemtype'] = self::getSelectedValue($values, $p['itemtype']); - - ob_start(); - $p['value'] = self::dropdownFields($p, false); - $field_html = ob_get_clean(); - - ob_start(); - self::showMandatoryCheckbox($p + ['need_decode' => true]); - $mandatory_html = ob_get_clean(); - - return [ - 'field' => $field_html, - 'mandatory' => $mandatory_html, - ]; - } - - - /** - * Value selected by the browser in a dropdown: the given value, or the first one if it is not in the list - * - * @param int|string $value - * @return int|string - **/ - private static function getSelectedValue(array $values, $value) - { - return isset($values[$value]) ? $value : array_key_first($values); - } - - - /** - * Get the parameters and the values of the linked types dropdown - * - * @param mixed $mapping_or_info - * @param array $options array - * - * @return array{0: array, 1: array} - **/ - private static function getLinkedTypesParams($mapping_or_info, $options = []): array + public static function getLinkedTypes($primary_type) { /** @var array[mixed] $INJECTABLE_TYPES */ global $INJECTABLE_TYPES; getTypesToInject(); // populate $INJECTABLE_TYPES - $p['primary_type'] = ''; - $p['itemtype'] = self::NO_VALUE; - // Use hex code for all special chars to prevent problems when adding/stripping slashes - $p['mapping_or_info'] = json_encode( - $mapping_or_info->fields, - JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP, - ); - $p['called_by'] = $mapping_or_info::class; - $p['fields_update'] = true; - foreach ($options as $key => $value) { - $p[$key] = $value; - } - - $values = []; - - if ( - ($p['itemtype'] == self::NO_VALUE) - && ($mapping_or_info->fields['itemtype'] != self::NO_VALUE) - ) { - $p['itemtype'] = $mapping_or_info->fields['itemtype']; - } - - //Add null value - $values[self::NO_VALUE] = __('-------Choose a table-------', 'datainjection'); - //Add primary_type to the list of availables types - if (!is_a($p['primary_type'], CommonDBTM::class, true)) { - throw new HttpException(500, 'Class ' . $p['primary_type'] . ' is not a valid class'); + if (!is_a($primary_type, CommonDBTM::class, true)) { + throw new HttpException(500, 'Class ' . $primary_type . ' is not a valid class'); } //The linked types are the same for all the rows of a model: computed once per request static $values_by_primary_type = []; - if (isset($values_by_primary_type[$p['primary_type']])) { - return [$p, $values_by_primary_type[$p['primary_type']]]; + if (isset($values_by_primary_type[$primary_type])) { + return $values_by_primary_type[$primary_type]; } - $type = new $p['primary_type'](); - $values[$p['primary_type']] = $type->getTypeName(); + $values = [$primary_type => $primary_type::getTypeName()]; foreach ($INJECTABLE_TYPES as $type => $plugin) { if (is_a($type, CommonDBTM::class, true)) { $injectionClass = new $type(); if (method_exists($injectionClass, 'connectedTo')) { $connected_to = $injectionClass->connectedTo(); - if (in_array($p['primary_type'], $connected_to)) { + if (in_array($primary_type, $connected_to)) { $typename = getItemTypeForTable($injectionClass->getTable()); $values[$typename] = call_user_func([$type, 'getTypeName']); } @@ -253,30 +148,27 @@ private static function getLinkedTypesParams($mapping_or_info, $options = []): a } asort($values); - $values_by_primary_type[$p['primary_type']] = $values; + //Add null value on top of the list + $values_by_primary_type[$primary_type] = [self::NO_VALUE => Dropdown::EMPTY_VALUE] + $values; - return [$p, $values]; + return $values_by_primary_type[$primary_type]; } /** - * @param array $options array - * @param bool $load_mandatory load the mandatory checkbox through AJAX on page load + * Get the fields that can be mapped for an itemtype, and the value to select * - * @return int|string the value selected in the fields dropdown + * @param array $options itemtype, primary_type, called_by and mapping_or_info (array, or JSON if need_decode) + * + * @return array{fields: array, value: string} **/ - public static function dropdownFields($options = [], bool $load_mandatory = true) + public static function getFieldsChoices($options = []) { - /** @var array $CFG_GLPI */ - global $CFG_GLPI; - - $used = []; $p['itemtype'] = self::NO_VALUE; $p['primary_type'] = ''; $p['mapping_or_info'] = []; $p['called_by'] = ''; $p['need_decode'] = true; - $p['fields_update'] = true; foreach ($options as $key => $value) { $p[$key] = $value; @@ -292,7 +184,7 @@ public static function dropdownFields($options = [], bool $load_mandatory = true } $fields = []; - $fields[self::NO_VALUE] = __('-------Choose a field-------', 'datainjection'); + $used = []; //By default field has no default value $mapping_value = self::NO_VALUE; @@ -335,35 +227,134 @@ public static function dropdownFields($options = [], bool $load_mandatory = true $used = self::getUsedMappingsOrInfos($p, $search_options); } + $fields = array_diff_key($fields, $used); asort($fields); - $rand = Dropdown::showFromArray( - "data[" . $mapping_or_info['id'] . "][value]", - $fields, - ['value' => $mapping_value, - 'used' => $used, - ], + if (!isset($fields[$mapping_value])) { + $mapping_value = self::NO_VALUE; + } + + return [ + //Add null value on top of the list + 'fields' => [self::NO_VALUE => Dropdown::EMPTY_VALUE] + $fields, + 'value' => $mapping_value, + ]; + } + + + /** + * Indicates if the link field / mandatory checkbox is available for a mapping or an info + * + * @param string $called_by class of the mapping or info + * @param string $primary_type primary type of the model + * @param string $itemtype selected table + * @param string $value selected field + **/ + public static function canBeMandatory($called_by, $primary_type, $itemtype, $value) + { + return $called_by == PluginDatainjectionInfo::class || ( + $primary_type == $itemtype + && !in_array($value, self::NON_MANDATORY_FIELDS) ); + } - $p['value'] = '__VALUE__'; - $url = plugin_datainjection_geturl() . "ajax/dropdownMandatory.php"; - if ($load_mandatory) { - Ajax::updateItem( - "span_mandatory_" . $mapping_or_info['id'], - $url, - $p, - "dropdown_data[" . $mapping_or_info['id'] . ('][value]' . $rand), - ); + + /** + * Get the fields targeted by the other kind of rows of a model: the infos ones for a mapping, + * the mappings ones for an info. A field should not be both mapped from the file and asked as info. + * + * @param string $called_by class of the mapping or info + * @param int $models_id + * + * @return string[] "itemtype|field" keys + **/ + public static function getOtherTargetedFields($called_by, $models_id) + { + /** @var array $cache */ + static $cache = []; + + $table = $called_by == PluginDatainjectionInfo::class + ? PluginDatainjectionMapping::getTable() + : PluginDatainjectionInfo::getTable(); + $key = $table . '_' . $models_id; + + if (!isset($cache[$key])) { + $cache[$key] = []; + $rows = getAllDataFromTable($table, [ + 'models_id' => $models_id, + 'NOT' => ['value' => self::NO_VALUE], + ]); + foreach ($rows as $row) { + $cache[$key][] = $row['itemtype'] . '|' . $row['value']; + } } - Ajax::updateItemOnSelectEvent( - "dropdown_data[" . $mapping_or_info['id'] . ('][value]' . $rand), - "span_mandatory_" . $mapping_or_info['id'], - $url, - $p, - ); + return $cache[$key]; + } - return self::getSelectedValue($fields, $mapping_value); + + /** + * Get the data needed to display a mapping or info row: table and field dropdowns, + * mandatory checkbox, and the parameters used to refresh the fields client side + * + * @param PluginDatainjectionMapping|PluginDatainjectionInfo $mapping_or_info + * @param string $primary_type + * + * @return array + **/ + public static function getRow($mapping_or_info, $primary_type) + { + $id = $mapping_or_info->fields['id']; + $itemtype = $mapping_or_info->fields['itemtype']; + // The stored itemtype may no longer be injectable (e.g. a Fields container of a disabled plugin) + if (!isset(self::getLinkedTypes($primary_type)[$itemtype])) { + $itemtype = self::NO_VALUE; + } + + $choices = self::getFieldsChoices([ + 'itemtype' => $itemtype, + 'primary_type' => $primary_type, + 'mapping_or_info' => $mapping_or_info->fields, + 'called_by' => $mapping_or_info::class, + 'need_decode' => false, + ]); + + $other_targets = self::getOtherTargetedFields($mapping_or_info::class, $mapping_or_info->fields['models_id']); + + return [ + 'has_conflict' => in_array($itemtype . '|' . $choices['value'], $other_targets, true), + 'conflict_label' => sprintf( + __('This field is also used in %s', 'datainjection'), + $mapping_or_info::class == PluginDatainjectionInfo::class + ? __('Mappings', 'datainjection') + : __('Additional Information', 'datainjection'), + ), + 'id' => $id, + 'itemtype_html' => Dropdown::showFromArray( + "data[" . $id . "][itemtype]", + self::getLinkedTypes($primary_type), + ['value' => $itemtype, 'width' => '100%', 'display' => false], + ), + 'field_html' => Dropdown::showFromArray( + "data[" . $id . "][value]", + $choices['fields'], + ['value' => $choices['value'], 'width' => '100%', 'display' => false], + ), + 'is_mapped' => $choices['value'] != self::NO_VALUE, + 'is_mandatory' => (bool) $mapping_or_info->fields['is_mandatory'], + 'can_be_mandatory' => self::canBeMandatory($mapping_or_info::class, $primary_type, $itemtype, $choices['value']), + 'params' => [ + 'primary_type' => $primary_type, + 'called_by' => $mapping_or_info::class, + // Use hex code for all special chars to prevent problems when adding/stripping slashes + 'mapping_or_info' => json_encode( + $mapping_or_info->fields, + JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP, + ), + 'non_mandatory' => self::NON_MANDATORY_FIELDS, + 'other_targets' => $other_targets, + ], + ]; } @@ -407,40 +398,6 @@ public static function testBasicEqual($name, $option = []) || (strtolower((string) $option['linkfield']) == $name); } - /** - * @param array $options array - **/ - public static function showMandatoryCheckbox($options = []) - { - - // Received data has been slashed. - - if ($options['need_decode']) { - // JSON data has been slashed twice, stripslashes has to be done a second time. - $mapping_or_info = json_decode( - $options['mapping_or_info'], - true, - ); - } else { - $mapping_or_info = $options['mapping_or_info']; - } - - //TODO : to improve - $checked = ''; - if ($mapping_or_info['is_mandatory']) { - $checked = 'checked'; - } - - if ( - $options['called_by'] == 'PluginDatainjectionInfo' || ( - $options['primary_type'] == $options['itemtype'] - && !in_array($options['value'], self::NON_MANDATORY_FIELDS) - ) - ) { - echo "", $checked); - } - } - /** * @param array $options array diff --git a/inc/mapping.class.php b/inc/mapping.class.php index 002f1394..93f20ff5 100644 --- a/inc/mapping.class.php +++ b/inc/mapping.class.php @@ -30,9 +30,6 @@ use Glpi\Application\View\TemplateRenderer; -use function Safe\ob_get_clean; -use function Safe\ob_start; - class PluginDatainjectionMapping extends CommonDBTM { public static $rightname = "plugin_datainjection_model"; @@ -112,26 +109,18 @@ public static function showFormMappings(PluginDatainjectionModel $model) $mappings = []; foreach ($model->getMappings() as $mapping) { - ob_start(); - $options = ['primary_type' => $model->fields['itemtype']]; - PluginDatainjectionInjectionType::dropdownLinkedTypes($mapping, $options, false); - $dropdown_html = ob_get_clean(); - $fields_html = PluginDatainjectionInjectionType::getFieldsHtml($mapping, $options); - - $mappings[] = [ - 'id' => $mapping->getID(), - 'name' => $mapping->fields['name'], - 'dropdown_html' => $dropdown_html, - 'field_html' => $fields_html['field'], - 'mandatory_html' => $fields_html['mandatory'], - ]; + $mappings[] = PluginDatainjectionInjectionType::getRow($mapping, $model->fields['itemtype']) + + ['name' => $mapping->fields['name']]; } TemplateRenderer::getInstance()->display('@datainjection/mappings_form.html.twig', [ 'form_action' => Toolbox::getItemTypeFormURL(self::class), + 'fields_url' => plugin_datainjection_geturl() . "ajax/fieldsChoices.php", 'show_preview' => $show_preview, 'preview_url' => $preview_url, 'mappings' => $mappings, + 'nb_mapped' => count(array_filter(array_column($mappings, 'is_mapped'))), + 'nb_link' => count(array_filter($mappings, fn($mapping) => $mapping['is_mandatory'] && $mapping['can_be_mandatory'])), 'canedit' => $canedit, 'model_id' => $model->fields['id'], ]); diff --git a/inc/model.class.php b/inc/model.class.php index aa7ca103..77d91d29 100644 --- a/inc/model.class.php +++ b/inc/model.class.php @@ -320,60 +320,38 @@ public function getSpecificModel() /** * @param array $options array * - * @return void + * @return int|string random part of the dropdown id, or HTML code if `display` option is false **/ public static function dropdown($options = []) { - /** @var array $CFG_GLPI */ - global $CFG_GLPI; - $models = self::getModels( Session::getLoginUserID(), 'name', $_SESSION['glpiactive_entity'], false, ); - $p = ['models_id' => '__VALUE__']; - - $value = $_SESSION['datainjection']['models_id'] ?? 0; - - $rand = mt_rand(); - echo "\n"; - - $url = $CFG_GLPI['root_doc'] . "/plugins/datainjection/ajax/dropdownSelectModel.php"; - Ajax::updateItemOnSelectEvent('dropdown_models' . $rand, "span_injection", $url, $p); + // The model change is handled by the client injection form script + return Dropdown::showFromArray('dropdown_models', $elements, [ + 'value' => $_SESSION['datainjection']['models_id'] ?? 0, + 'option_tooltips' => $tooltips, + 'rand' => $options['rand'] ?? mt_rand(), + 'width' => $options['width'] ?? '', + 'display' => $options['display'] ?? true, + ]); } @@ -739,7 +717,6 @@ public function showAdvancedForm($ID, $options = []) } $this->showFormButtons($options); - echo ""; return true; } @@ -813,6 +790,11 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ case 3: $options['confirm'] = 'creation'; $options['models_id'] = $item->fields['id']; + // Only warn when there are existing mappings to override + $options['warn_override'] = countElementsInTable( + PluginDatainjectionMapping::getTable(), + ['models_id' => $item->fields['id']], + ) > 0; $options['add_form'] = true; $options['submit'] = __('Load this file', 'datainjection'); PluginDatainjectionClientInjection::showUploadFileForm($options); @@ -1378,43 +1360,33 @@ public static function cleanSessionVariables() **/ public static function showPreviewMappings($models_id) { + $headers = []; + $rows = []; - echo ""; if (isset($_SESSION['datainjection']['lines'])) { $injectionData = PluginDatainjectionSession::unserialize($_SESSION['datainjection']['lines']); $lines = $injectionData->getData(); - $nblines = $_SESSION['datainjection']['nblines']; $model = self::getInstanceByModelID($models_id); $model->loadMappings(); - $mappings = $model->getMappings(); if ($model->getSpecificModel()->isHeaderPresent()) { - $nbmappings = count($mappings); - echo ""; - - foreach ($mappings as $mapping) { - echo""; + foreach ($model->getMappings() as $mapping) { + $headers[] = $mapping->getMappingName(); } - echo ""; unset($lines[0]); } foreach ($lines as $line) { - echo ""; - foreach ($line[0] as $value) { - echo ""; - } - - echo ""; + $rows[] = $line[0]; } } - Html::closeForm(); - echo "
"; - echo "" . __s('Close') . ""; - echo "
"; + TemplateRenderer::getInstance()->display('@datainjection/preview_mappings.html.twig', [ + 'headers' => $headers, + 'rows' => $rows, + ]); } diff --git a/inc/modelcsv.class.php b/inc/modelcsv.class.php index 8666a76b..91f9ae94 100644 --- a/inc/modelcsv.class.php +++ b/inc/modelcsv.class.php @@ -29,6 +29,7 @@ */ use Glpi\Application\View\TemplateRenderer; +use Symfony\Component\HttpFoundation\Response; /** * ------------------------------------------------------------------------- @@ -115,26 +116,21 @@ public function haveSample() * * @param PluginDatainjectionModel $model PluginDatainjectionModel object **/ - public function showSample(PluginDatainjectionModel $model) + public function showSample(PluginDatainjectionModel $model): Response { $headers = PluginDatainjectionMapping::getMappingsSortedByRank($model->fields['id']); $sample = '"' . implode('"' . $this->getDelimiter() . '"', $headers) . "\"\n"; - header( - 'Content-disposition: attachment; filename="' . str_replace( - ' ', - '_', - $model->getName(), - ) . '.csv"', - ); - header('Content-Type: text/comma-separated-values'); - header('Content-Transfer-Encoding: UTF-8'); - header('Content-Length: ' . strlen($sample)); - header('Pragma: no-cache'); - header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); - header('Expires: 0'); - echo $sample; + return new Response($sample, Response::HTTP_OK, [ + 'Content-Disposition' => 'attachment; filename="' . str_replace(' ', '_', $model->getName()) . '.csv"', + 'Content-Type' => 'text/comma-separated-values', + 'Content-Transfer-Encoding' => 'UTF-8', + 'Content-Length' => strlen($sample), + 'Pragma' => 'no-cache', + 'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', + 'Expires' => '0', + ]); } diff --git a/inc/profile.class.php b/inc/profile.class.php index bd657c27..4287feda 100644 --- a/inc/profile.class.php +++ b/inc/profile.class.php @@ -28,6 +28,8 @@ * ------------------------------------------------------------------------- */ +use Glpi\Application\View\TemplateRenderer; + class PluginDatainjectionProfile extends Profile { public static $rightname = "profile"; @@ -178,34 +180,14 @@ public static function migrateProfiles() public function showForm($ID, $options = []) { - - echo "
"; - if ($canedit = Session::haveRightsOr(self::$rightname, [CREATE, UPDATE, PURGE])) { - $profile = new Profile(); - echo "
"; - } - $profile = new Profile(); $profile->getFromDB($ID); - $rights = self::getAllRights(); - $profile->displayRightsChoiceMatrix( - $rights, - [ - 'canedit' => $canedit, - 'default_class' => 'tab_bg_2', - 'title' => __('General'), - ], - ); - if ($canedit) { - echo "
"; - echo Html::hidden('id', ['value' => $ID]); - echo Html::submit(_sx('button', 'Save'), ['name' => 'update']); - echo "
\n"; - Html::closeForm(); - } - - echo "
"; + TemplateRenderer::getInstance()->display('@datainjection/profile_form.html.twig', [ + 'profile' => $profile, + 'rights' => self::getAllRights(), + 'canedit' => Session::haveRightsOr(self::$rightname, [CREATE, UPDATE, PURGE]), + ]); return true; } diff --git a/public/css/datainjection.css b/public/css/datainjection.css index 8cb598eb..0f30d42c 100644 --- a/public/css/datainjection.css +++ b/public/css/datainjection.css @@ -26,299 +26,34 @@ * ------------------------------------------------------------------------- */ -/************************ General Tag ***************************/ -legend { - font-size: 16px; - font-weight: bold; -} - -/**************** Global container for wizard *******************/ -.global { - margin: 0 auto; - position: relative; - text-align: left; - font-family: "New Roman",serif; -} - -/********************** Onglet table ****************************/ -.step { - margin:0; - text-align: center; - -moz-border-radius-topright: 8px; - -moz-border-radius-topleft: 8px; - border-left: 2px solid #d3d3ce; - border-right: 2px solid #d3d3ce; - border-top: 2px solid #d3d3ce; -} - -.step td { - width: 50px; - height: 50px; - font-size: 20px; - background-color: #d3d3ce; -} - -/********************** Wizard table ****************************/ -.wizard { - height: 450px; - text-align: left; - background-color: #e6e6e6; - border: 2px solid #d3d3ce; - -moz-border-radius-topright: 8px; - -moz-border-radius-bottomright: 8px; - -moz-border-radius-bottomleft: 8px; -} - -.wizard_left_area { - width: 212px; - background-color: white; - border-right: 2px inset black; -} - -.wizard_right_area { - padding: 20px; - font-size: 14px; -} - -.wizard_button { - height: 35px; - border-top: 2px outset black; -} - -.wizard_title { - font-size: 18px; - text-align: center; - margin-top: 20px; - margin-bottom: 50px; -} - -.wizard_explain { - font-size: 14px; - text-align: justify; - margin-left: 10px; - margin-right: 10px; - margin-top: 20px; -} - -/************************** Button ******************************/ -.next { - float: right; - margin-right: 10px; -} - -.preview { - float: left; - margin-left: 10px; -} - -/*********************** Presentation ***************************/ -.presentation_logo { - margin: auto; - width: 180px; - height: 192px; - margin-top: 100px; -} - -.presentation_title { - font-size: 22px; - text-align: left; - margin-top: 30px; -} - -.presentation_text { - font-size: 16px; - line-height: 20px; - margin-top: 80px; - text-align: justify; -} - -/************************ Choice Step ***************************/ -.choiceStep_selection { - font-size: 14px; - width: 350px; - margin-left: auto; - margin-right: auto; - margin-top: 20px; - padding-top: 0; -} - -.choiceStep_table { - margin-bottom: 20px; - border-spacing: 10px; - font-size: 14px; -} - -.choiceStep_dropdown { - margin:auto; - width: 130px; -} - -.choiceStep_comments { - display: none; - font-size: 14px; - margin-left: auto; - margin-right: auto; - margin-top: 20px; - width: 350px; -} - -/************************* Model Step ***************************/ -.modelStep_selection { - width: 400px; - margin-left: auto; - margin-right: auto; - margin-top: 10px; - padding-top: 0; -} - -.modelStep_table { - font-size: 14px; - text-align: left; -} - -.modelStep_table td { - height: 30px; -} - -.delimiter { - text-align: center; - margin-top: 10px; - font-size: 14px; - visibility: hidden; - color: red; -} - -/************************ Delete Step ***************************/ -.deleteStep_table { - font-size: 16px; - margin-top: 100px; - border-spacing: 15px; - text-align: center; -} - -.save_delete { - font-size: 14px; - margin-top: 150px; - margin-left: auto; - margin-right: auto; - width: 180px; - line-height: 20px; - text-align: center; -} - -.suppr { - font-size: 14px; - margin-top: 70px; -} - -.question { - line-height: 20px; -} - -/********************* Mapping & Infos Step *********************/ -.mandatory { - text-align: center; - visibility: hidden; - color: red; -} - -/************************** File Step ***************************/ -.fileStep_table { - text-align:center; - margin-top: 120px; - margin-bottom: 20px; - font-size: 16px; -} +/************************ Card tables ***************************/ -.fileStep_error { - color: red; - font-size: 14px; - margin-left: auto; - margin-right: auto; - width: 250px; - text-align: center; +/* The card already draws the bottom border: avoid a double line under the last row */ +.datainjection-card-table > .table > tbody > tr:last-child > td { + border-bottom-width: 0; } -/************************** Save Step ***************************/ -.saveStep_table { - font-size: 14px; - margin-top: 100px; - border-spacing: 10px; -} - -.saveStep2_table { - font-size: 14px; - margin-top: 70px; - border-spacing: 10px; -} - -/*********************** Fill Info Step *************************/ -.fillInfoStep_fieldset { - margin-top: 30px; - margin-bottom: 10px; -} - -.fillInfoStep_tab td { - font-size: 14px; -} - -.fillInfoStep_mandatory { - color: red; - text-align: center; -} - -.fillInfoStep_red { - color: red; - font-size: 11px; -} - -.fillInfoStep_error { - color: red; - text-align: center; - margin-top: 50px; -} - -/************************* Import Step **************************/ -.importStep_cadre { - margin-top: 150px; - margin-left: auto; - margin-right: auto; - width: 300px; - height: 40px; - text-align: center; -} - -.importStep_end { - text-align: center; - margin-top: 20px; -} - -/**************************** Log Step **************************/ -.logStep_success { - margin-top: 120px; - font-size: 20px; - width: 200px; - margin-left: auto; - margin-right: auto; - text-align: center; -} +/************************ Mappings form *************************/ -.logStep_button { - width: 150px; +/* Field targeted both by a mapping and an additional information */ +.table > tbody > tr.datainjection-row-conflict > td { + --tblr-table-bg-state: var(--tblr-orange-lt); } -.logStep_tab { - text-align: center; - margin-top: 100px; +/* Actions applied to the selected rows, sized like the GLPI massive actions button */ +.btn.datainjection-selection-btn { + --tblr-btn-padding-y: 0.125rem; + --tblr-btn-padding-x: 0.75rem; + --tblr-btn-font-size: 0.75rem; } -.logStep_tab td{ - height: 50px; +/******************** Centered form fields **********************/ +.datainjection-centered-fields { + max-width: 600px; } -.logStep_title { - width: 920px; - text-align: center; - font-size: 14px; - font-weight: bold; +/************************ File preview **************************/ +.datainjection-preview { + max-height: calc(100vh - 10rem); + overflow-y: auto; } diff --git a/public/js/datainjection.js b/public/js/datainjection.js index 15893c8a..8647a65c 100644 --- a/public/js/datainjection.js +++ b/public/js/datainjection.js @@ -27,15 +27,120 @@ */ /** - * @param num + * Update the rows of a mappings / infos form without rebuilding them: + * - on table change, only the options of the field dropdown are replaced, + * - on field change, the link field switch and the conflict warning are shown or hidden in place. + * + * Each row must hold its parameters in a `data-field-params` attribute. + * + * @param {HTMLFormElement} form + * @param {string} url URL of the fields choices endpoint + */ +function initMappingRows(form, url) { + if (!form) { + return; + } + + const updateRow = (row) => { + const params = JSON.parse(row.dataset.fieldParams); + const itemtype = row.querySelector('select[name$="[itemtype]"]').value; + const value = row.querySelector('select[name$="[value]"]').value; + const label = row.querySelector('[data-mandatory-switch]'); + const input = label.querySelector('input'); + + const available = params.called_by === 'PluginDatainjectionInfo' + || (itemtype === params.primary_type && !params.non_mandatory.includes(value)); + + label.classList.toggle('invisible', !available); + input.disabled = !available; + if (!available) { + input.checked = false; + } + + // Field also targeted by the other kind of rows (mapping vs additional information) + const conflict = params.other_targets.includes(`${itemtype}|${value}`); + row.querySelector('[data-field-conflict]').classList.toggle('invisible', !conflict); + row.classList.toggle('datainjection-row-conflict', conflict); + }; + + $(form).on('change', 'select[name$="[itemtype]"]', function () { + const row = this.closest('tr'); + const field = $(row).find('select[name$="[value]"]'); + const params = JSON.parse(row.dataset.fieldParams); + + field.prop('disabled', true); + $.post(url, { + itemtype: this.value, + primary_type: params.primary_type, + called_by: params.called_by, + mapping_or_info: params.mapping_or_info, + }).done((data) => { + field.empty(); + data.fields.forEach(([key, label]) => field.append(new Option(label, key))); + field.val(data.value); + }).always(() => { + field.prop('disabled', false).trigger('change'); + }); + }); + + $(form).on('change', 'select[name$="[value]"]', function () { + updateRow(this.closest('tr')); + }); +} + +/** + * Keep the counters badges (mapped fields, link fields, conflicts) of a mappings / infos form up to date. + * + * @param {HTMLFormElement} form + * @param {Object} labels counter name => [singular, plural] labels, containing "%d" */ -function show_log(num) { - - if (document.getElementById('log'+num+'_table').style.display == 'none') { - document.getElementById('log'+num).src = '../pics/minus.png'; - document.getElementById('log'+num+'_table').style.display = 'block'; - } else { - document.getElementById('log'+num).src = '../pics/plus.png'; - document.getElementById('log'+num+'_table').style.display = 'none'; +function initMappingsCounters(form, labels) { + if (!form) { + return; } + + const counters = { + mapped: () => Array.from(form.querySelectorAll('select[name$="[value]"]')) + .filter((select) => select.value !== '' && select.value !== 'none').length, + link: () => form.querySelectorAll('input[name$="[is_mandatory]"]:checked:not(:disabled)').length, + conflict: () => form.querySelectorAll('[data-field-conflict]:not(.invisible)').length, + }; + + const refresh = () => { + Object.keys(counters).forEach((name) => { + const badge = form.querySelector(`[data-mappings-counter="${name}"]`); + if (badge && labels[name]) { + const count = counters[name](); + badge.querySelector('[data-counter-text]').textContent = labels[name][count === 1 ? 0 : 1].replace('%d', count); + if (badge.hasAttribute('data-hide-empty')) { + badge.classList.toggle('d-none', count === 0); + } + } + }); + }; + + $(form).on('change', refresh); + refresh(); +} + +/** + * Enable the selection actions of a mappings / infos form only when rows are selected. + * + * @param {HTMLFormElement} form + */ +function initSelectionActions(form) { + const container = form ? form.querySelector('[data-selection-actions]') : null; + if (!container) { + return; + } + + const refresh = () => { + const has_selection = form.querySelector('input[name^="item["]:checked') !== null; + container.querySelectorAll('button').forEach((button) => { + button.disabled = !has_selection; + }); + }; + + $(form).on('change', 'input[name^="item["]', refresh); + refresh(); } diff --git a/public/js/injection_progress.js b/public/js/injection_progress.js index 51659c5e..f8c7302d 100644 --- a/public/js/injection_progress.js +++ b/public/js/injection_progress.js @@ -43,20 +43,26 @@ function startBatchInjection(container) { let offset = 0; + // GLPI progress bar (Html::getProgressBar()) + const progressContainer = container.querySelector('.progress'); + const progressBar = container.querySelector('.progress-bar'); + function updateProgressBar(progress) { - const progressBar = container.querySelector('.progress-bar'); - const progressContainer = container.querySelector('.progress'); if (progressBar && progressContainer) { + const label = Math.floor(progress) + ' %'; progressBar.style.width = progress + '%'; - progressBar.textContent = progress + '%'; - progressContainer.setAttribute('aria-valuenow', progress); + progressBar.textContent = label; + progressBar.setAttribute('aria-valuenow', progress); + // Bootstrap reads the tooltip text from this attribute once initialized + progressContainer.setAttribute('title', label); + progressContainer.setAttribute('data-bs-original-title', label); } } function updateStatus(processed, total) { const status = container.querySelector('#injection_status'); if (status) { - status.textContent = statusLabel + ' — ' + processed + ' / ' + total + ' ' + linesLabel; + status.textContent = statusLabel + ' - ' + processed + ' / ' + total + ' ' + linesLabel; } } @@ -75,11 +81,7 @@ function startBatchInjection(container) { offset = response.offset; if (response.done) { - const progressBar = container.querySelector('.progress-bar'); - if (progressBar) { - progressBar.classList.remove('progress-bar-animated'); - } - $('#span_injection').load(resultUrl, { + $(container).find('#span_injection').load(resultUrl, { models_id: modelId, nblines: nblines }); @@ -88,10 +90,10 @@ function startBatchInjection(container) { } }, error: function() { - const progressBar = container.querySelector('.progress-bar'); + // Same failure display as the GLPI ProgressIndicator if (progressBar) { - progressBar.classList.remove('progress-bar-animated'); progressBar.textContent = errorLabel; + progressBar.classList.replace('bg-info', 'bg-danger'); } } }); diff --git a/templates/clientinjection.html.twig b/templates/clientinjection.html.twig index 590b9cae..5af607f3 100644 --- a/templates/clientinjection.html.twig +++ b/templates/clientinjection.html.twig @@ -41,17 +41,19 @@
{% if models|length > 0 %} - {{ fields.dropdownField( - 'PluginDatainjectionModel', - 'dropdown_models', - 0, - __('Model', 'datainjection'), - { - 'add_field_class' : 'col-sm-12', - 'input_class' : 'col-6 col-sm-6', - 'label_class' : 'col-6 col-sm-6', - } - ) }} +
+ {{ fields.dropdownField( + 'PluginDatainjectionModel', + 'dropdown_models', + 0, + __('Model', 'datainjection'), + { + 'field_class': 'col-12', + 'label_class': 'col-sm-4', + 'input_class': 'col-sm-8', + } + ) }} +
{% else %} {% set text = __('No model currently available', 'datainjection') %} {% if can_create_model %} @@ -71,11 +73,11 @@ diff --git a/templates/info_add_form.html.twig b/templates/info_add_form.html.twig new file mode 100644 index 00000000..592c68c2 --- /dev/null +++ b/templates/info_add_form.html.twig @@ -0,0 +1,44 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +{% embed '@datainjection/components/mapping_table.html.twig' with { + form_action: form_action, + fields_url: fields_url, + rows: [info], + title: __('Add an additional information', 'datainjection'), + icon: 'ti ti-row-insert-bottom', + switch_label: __('Mandatory information', 'datainjection'), +} %} + {% block footer %} + + + {% endblock %} +{% endembed %} diff --git a/templates/info_additional_information.html.twig b/templates/info_additional_information.html.twig new file mode 100644 index 00000000..4f795499 --- /dev/null +++ b/templates/info_additional_information.html.twig @@ -0,0 +1,37 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +{% import 'components/form/fields_macros.html.twig' as fields %} + +{{ fields.htmlField(name, field_html, label, { + 'field_class': 'col-12', + 'label_class': 'col-sm-4', + 'input_class': 'col-sm-8', + 'wrapper_class': 'd-block', + 'required': is_mandatory, +}) }} diff --git a/templates/info_additional_input.html.twig b/templates/info_additional_input.html.twig new file mode 100644 index 00000000..ac21dfd8 --- /dev/null +++ b/templates/info_additional_input.html.twig @@ -0,0 +1,37 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +{% import 'components/form/basic_inputs_macros.html.twig' as inputs %} + +{% if type == 'textarea' %} + {{ inputs.textarea(name, value, {'id': '%id%', 'rows': 5}) }} +{% elseif type == 'password' %} + {{ inputs.password(name, '', {'id': '%id%', 'additional_attributes': {'autocomplete': 'off'}}) }} +{% else %} + {{ inputs.text(name, value, {'id': '%id%'}) }} +{% endif %} diff --git a/templates/infoadditionnalinfo.html.twig b/templates/infoadditionnalinfo.html.twig index 50ff3c63..442548cb 100644 --- a/templates/infoadditionnalinfo.html.twig +++ b/templates/infoadditionnalinfo.html.twig @@ -48,16 +48,10 @@ {% endif %} {% if rendered_infos|length > 0 %} -
-
" . htmlescape($mapping->getMappingName()) . "
" . htmlescape($value) . "
- - {% for rendered_info in rendered_infos %} - - {{ rendered_info|raw }} - - {% endfor %} - -
+
+ {% for rendered_info in rendered_infos %} + {{ rendered_info|raw }} + {% endfor %}
{% endif %} {% endif %} \ No newline at end of file diff --git a/templates/infos_form.html.twig b/templates/infos_form.html.twig new file mode 100644 index 00000000..b8f7938e --- /dev/null +++ b/templates/infos_form.html.twig @@ -0,0 +1,69 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +{% embed '@datainjection/components/mapping_table.html.twig' with { + form_action: form_action, + fields_url: fields_url, + rows: infos, + title: __('Additional information', 'datainjection'), + icon: 'ti ti-list-details', + selectable: canedit, + select_all: select_all, + switch_label: __('Mandatory information', 'datainjection'), + badges: [ + { + class: 'bg-secondary-lt', + labels: [_n('%d additional information', '%d additional information', 1, 'datainjection'), _n('%d additional information', '%d additional information', 2, 'datainjection')], + count: infos|length, + }, + { + class: 'bg-blue-lt', + labels: [_n('%d mandatory information', '%d mandatory information', 1, 'datainjection'), _n('%d mandatory information', '%d mandatory information', 2, 'datainjection')], + count: nb_mandatory, + counter: 'link', + }, + ], +} %} + {% block selection_actions %} + {% if canedit %} + + {% endif %} + {% endblock %} + {% block footer %} + {% if canedit %} + + + {% endif %} + {% endblock %} +{% endembed %} diff --git a/templates/log_results.html.twig b/templates/log_results.html.twig index 0a8fd8f2..b5ee7947 100644 --- a/templates/log_results.html.twig +++ b/templates/log_results.html.twig @@ -26,121 +26,153 @@ # ------------------------------------------------------------------------- #} -
+{% set nb_success = (logresults[SUCCESS] ?? [])|length %} +{% set nb_failed = (logresults[FAILED] ?? [])|length %} - {% if logresults[SUCCESS] is defined %} -
-
- - {{ __('Array of successful injections', 'datainjection') }} -
- - - - - - - - - - - - {% for result in logresults[SUCCESS] %} - - - - - - - - {% endfor %} - -
{{ __('Line', 'datainjection') }}{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Object Identifier', 'datainjection') }}
{{ result.line }}{{ result.status_message|nl2br }}{{ result.type }}{{ result.url|raw }}
-
- {% endif %} +{% macro status_icon(is_success) %} + {% if is_success %} + + {% else %} + + {% endif %} +{% endmacro %} + +{% macro section_title(icon, label) %} +
+ + {{ label }} +
+{% endmacro %} - {% if logresults[FAILED] is defined %} -
-
- - {{ __('Array of failed injections', 'datainjection') }} +
+
+ + {{ __('Number of lines processed', 'datainjection') }} : {{ nblines }} + + + + {{ _n('%d line', '%d lines', nb_success, 'datainjection')|format(nb_success) }} + + + + {{ _n('%d line', '%d lines', nb_failed, 'datainjection')|format(nb_failed) }} + + +
+ + {% if nb_success > 0 %} + {{ _self.section_title('ti-progress-check', __('Array of successful injections', 'datainjection')) }} +
+
+ + + + + + + + + + + + + + + + + + + {% for result in logresults[SUCCESS] %} + + + + + + + + {% endfor %} + +
{{ __('Line', 'datainjection') }}{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Object Identifier', 'datainjection') }}
{{ _self.status_icon(true) }}{{ result.line }}{{ result.status_message|nl2br }}{{ result.type }}{{ result.url|raw }}
+
- - - - - - - - - - - - - {% for result in logresults[FAILED] %} - - - - - - - - - {% endfor %} - -
{{ __('Line', 'datainjection') }}{{ __('Data check', 'datainjection') }}{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Object Identifier', 'datainjection') }}
{{ result.line }}{{ result.check_message|nl2br }}{{ result.status_message|nl2br }}{{ result.type }}{{ result.url|raw }}
-
- {% endif %} + {% endif %} - {% if resume is not empty %} -
-
- - {{ __('Global report', 'datainjection') }} + {% if nb_failed > 0 %} + {{ _self.section_title('ti-progress-x', __('Array of failed injections', 'datainjection')) }} +
+
+ + + + + + + + + + + + + + + + + + + + + {% for result in logresults[FAILED] %} + + + + + + + + + {% endfor %} + +
{{ __('Line', 'datainjection') }}{{ __('Data check', 'datainjection') }}{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Object Identifier', 'datainjection') }}
{{ _self.status_icon(false) }}{{ result.line }}{{ result.check_message|nl2br }}{{ result.status_message|nl2br }}{{ result.type }}{{ result.url|raw }}
+
-

{{ __('Number of lines processed', 'datainjection') }} : {{ nblines }}

- - - - - - - - - - - {% for status, types in resume %} - {% set rowspan = types|length %} - - - - {% for type, value in types %} - {% if not loop.first %} - - {% endif %} - - - {% if not loop.last %} - - {% endif %} - {% endfor %} - - {% endfor %} - -
{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Counter', 'datainjection') }}
- {% if status == SUCCESS %} - - {% else %} - - {% endif %} - - {% set label = call('PluginDatainjectionCommonInjectionLib::getLogLabel', [status])|raw %} - {{ label }} -
{{ type }}{{ value }}
-
- {% endif %} + {% endif %} - -
\ No newline at end of file + {% if resume is not empty %} + {{ _self.section_title('ti-report', __('Global report', 'datainjection')) }} +
+
+ + + + + + + + + + + + + + + + + {% for status, types in resume %} + {% for type, value in types %} + + + + + + + {% endfor %} + {% endfor %} + +
{{ __('Data Import', 'datainjection') }}{{ __('Injection type', 'datainjection') }}{{ __('Counter', 'datainjection') }}
{{ _self.status_icon(status == SUCCESS) }}{{ call('PluginDatainjectionCommonInjectionLib::getLogLabel', [status]) }}{{ type }}{{ value }}
+
+
+ {% endif %} +
diff --git a/templates/mappings_form.html.twig b/templates/mappings_form.html.twig index 598065a1..e2e8f638 100644 --- a/templates/mappings_form.html.twig +++ b/templates/mappings_form.html.twig @@ -26,45 +26,51 @@ # ------------------------------------------------------------------------- #} - - - {% if show_preview %} - - - - -
- - {{ __('See the file', 'datainjection') }} - -
- {% endif %} - - - - - - - - - - {% for mapping in mappings %} - - - - - - - {% endfor %} +{% embed '@datainjection/components/mapping_table.html.twig' with { + form_action: form_action, + fields_url: fields_url, + rows: mappings, + title: __('Mappings', 'datainjection'), + icon: 'ti ti-arrows-shuffle', + name_label: __('Header of the file', 'datainjection'), + switch_label: __('Link field', 'datainjection'), + badges: [ + { + class: 'bg-secondary-lt', + labels: [_n('%d column', '%d columns', 1, 'datainjection'), _n('%d column', '%d columns', 2, 'datainjection')], + count: mappings|length, + }, + { + class: 'bg-green-lt', + labels: [_n('%d mapped field', '%d mapped fields', 1, 'datainjection'), _n('%d mapped field', '%d mapped fields', 2, 'datainjection')], + count: nb_mapped, + counter: 'mapped', + }, + { + class: 'bg-blue-lt', + labels: [_n('%d link field', '%d link fields', 1, 'datainjection'), _n('%d link field', '%d link fields', 2, 'datainjection')], + count: nb_link, + counter: 'link', + }, + ], +} %} + {% block toolbar_actions %} + {% if show_preview %} + + {% endif %} + {% endblock %} + {% block footer %} {% if canedit %} - - - + + {% endif %} -
{{ __('Header of the file', 'datainjection') }}{{ __('Tables', 'datainjection') }}{{ _n('Field', 'Fields', 2) }}{{ __('Link field', 'datainjection') }}
{{ mapping.name }}{{ mapping.dropdown_html|raw }}{{ mapping.field_html|raw }}{{ mapping.mandatory_html|raw }}
- - -
- - + {% endblock %} +{% endembed %} diff --git a/templates/preview_mappings.html.twig b/templates/preview_mappings.html.twig new file mode 100644 index 00000000..857572f1 --- /dev/null +++ b/templates/preview_mappings.html.twig @@ -0,0 +1,87 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +{% set nb_columns = headers|length > 0 ? headers|length : (rows|first ?: [])|length %} +{% set nb_rows = rows|length %} + +
+
+ + {{ __('See the file', 'datainjection') }} +
+ +
+ + {{ _n('%d column', '%d columns', nb_columns, 'datainjection')|format(nb_columns) }} + + + {{ _n('%d line', '%d lines', nb_rows, 'datainjection')|format(nb_rows) }} + + +
+ + {% if nb_rows > 0 %} +
+
+ + {% if headers|length > 0 %} + + + + {% for header in headers %} + + {% endfor %} + + + {% endif %} + + {% for row in rows %} + + + {% for value in row %} + + {% endfor %} + + {% endfor %} + +
#{{ header }}
{{ loop.index }} + {% if value is same as('') or value is null %} + - + {% else %} + {{ value }} + {% endif %} +
+
+
+ {% else %} +
{{ __('No data to display', 'datainjection') }}
+ {% endif %} +
diff --git a/templates/profile_form.html.twig b/templates/profile_form.html.twig new file mode 100644 index 00000000..d61f4630 --- /dev/null +++ b/templates/profile_form.html.twig @@ -0,0 +1,51 @@ +{# + # ------------------------------------------------------------------------- + # DataInjection plugin for GLPI + # ------------------------------------------------------------------------- + # + # LICENSE + # + # This file is part of DataInjection. + # + # DataInjection 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 2 of the License, or + # (at your option) any later version. + # + # DataInjection 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 DataInjection. If not, see . + # ------------------------------------------------------------------------- + # @copyright Copyright (C) 2007-2023 by DataInjection plugin team. + # @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + # @link https://github.com/pluginsGLPI/datainjection + # ------------------------------------------------------------------------- + #} + +
+ {% if canedit %} +
+ + + {% endif %} + + {% do profile.displayRightsChoiceMatrix(rights, { + 'canedit': canedit, + 'default_class': 'tab_bg_2', + 'title': __('General'), + }) %} + + {% if canedit %} +
+ +
+
+ {% endif %} +
diff --git a/tests/unit/AdditionalInformationTest.php b/tests/unit/AdditionalInformationTest.php index f366d82f..12f689ce 100644 --- a/tests/unit/AdditionalInformationTest.php +++ b/tests/unit/AdditionalInformationTest.php @@ -42,6 +42,7 @@ use PluginDatainjectionMapping; use PluginDatainjectionModel; use Session; +use Symfony\Component\DomCrawler\Crawler; final class AdditionalInformationTest extends DbTestCase { @@ -128,7 +129,13 @@ public function testFormInputIsNamedAfterItemtypeAndField(): void PluginDatainjectionInfo::displayAdditionalInformation($info); $html = ob_get_clean(); - self::assertStringContainsString("name='info[DeviceProcessor][designation]'", $html); + $crawler = new Crawler($html); + $input = $crawler->filter('input[name="info[DeviceProcessor][designation]"]'); + self::assertCount(1, $input); self::assertStringContainsString(DeviceProcessor::getTypeName(1) . ' - ', $html); + + // The label targets the input + self::assertNotEmpty($input->attr('id')); + self::assertSame($input->attr('id'), $crawler->filter('label')->attr('for')); } } diff --git a/tests/unit/InjectionTypeFieldsHtmlTest.php b/tests/unit/InjectionTypeFieldsHtmlTest.php index 2cb817b7..ed41fb19 100644 --- a/tests/unit/InjectionTypeFieldsHtmlTest.php +++ b/tests/unit/InjectionTypeFieldsHtmlTest.php @@ -36,6 +36,7 @@ use PluginDatainjectionModel; use Session; use Glpi\Tests\DbTestCase; +use Symfony\Component\DomCrawler\Crawler; final class InjectionTypeFieldsHtmlTest extends DbTestCase { @@ -68,15 +69,15 @@ public function testEachRowKeepsItsFieldAndHidesTheOtherRowsOne(): void } //Rendered in the same request, as the Mappings tab does: the static caches are shared by the rows - $options = ['primary_type' => Computer::class]; - $html = []; + $selects = []; foreach ($mappings as $field => $mapping) { - $html[$field] = PluginDatainjectionInjectionType::getFieldsHtml($mapping, $options)['field']; + $row = PluginDatainjectionInjectionType::getRow($mapping, Computer::class); + $selects[$field] = (new Crawler($row['field_html']))->filter('select'); } foreach (['name' => 'serial', 'serial' => 'name'] as $field => $other) { - $this->assertStringContainsString(sprintf("